code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
# frozen_string_literal: true require 'csv' class CourseStudentsCsvBuilder def initialize(course) @course = course end def generate_csv csv_data = [CSV_HEADERS] courses_users.each do |courses_user| csv_data << row(courses_user) end CSV.generate { |csv| csv_data.each { |line| csv << line } } end private def courses_users @course.courses_users.where(role: CoursesUsers::Roles::STUDENT_ROLE).includes(:user) end CSV_HEADERS = %w[ username enrollment_timestamp registered_at revisions_during_project mainspace_bytes_added userpace_bytes_added draft_space_bytes_added registered_during_project ].freeze def row(courses_user) row = [courses_user.user.username] row << courses_user.created_at row << courses_user.user.registered_at row << courses_user.revision_count row << courses_user.character_sum_ms row << courses_user.character_sum_us row << courses_user.character_sum_draft row << newbie?(courses_user.user) end def newbie?(user) (@course.start..@course.end).cover? user.registered_at end end
alpha721/WikiEduDashboard
lib/analytics/course_students_csv_builder.rb
Ruby
mit
1,126
<?php class Typography_test extends CI_TestCase { public function set_up() { $this->type = new Mock_Libraries_Typography(); $this->ci_instance('type', $this->type); } // -------------------------------------------------------------------- /** * Tests the format_characters() function. * * this can and should grow. */ public function test_format_characters() { $strs = array( '"double quotes"' => '&#8220;double quotes&#8221;', '"testing" in "theory" that is' => '&#8220;testing&#8221; in &#8220;theory&#8221; that is', "Here's what I'm" => 'Here&#8217;s what I&#8217;m', '&' => '&amp;', '&amp;' => '&amp;', '&nbsp;' => '&nbsp;', '--' => '&#8212;', 'foo...' => 'foo&#8230;', 'foo..' => 'foo..', 'foo...bar.' => 'foo&#8230;bar.', 'test. new' => 'test.&nbsp; new', ); foreach ($strs as $str => $expected) { $this->assertEquals($expected, $this->type->format_characters($str)); } } // -------------------------------------------------------------------- public function test_nl2br_except_pre() { $str = <<<EOH Hello, I'm a happy string with some new lines. I like to skip. Jump and sing. <pre> I am inside a pre tag. Please don't mess with me. k? </pre> That's my story and I'm sticking to it. The End. EOH; $expected = <<<EOH Hello, I'm a happy string with some new lines. <br /> <br /> I like to skip.<br /> <br /> Jump<br /> <br /> and sing.<br /> <br /> <pre> I am inside a pre tag. Please don't mess with me. k? </pre><br /> <br /> That's my story and I'm sticking to it.<br /> <br /> The End. EOH; $this->assertEquals($expected, $this->type->nl2br_except_pre($str)); } // -------------------------------------------------------------------- public function test_auto_typography() { $this->_blank_string(); $this->_standardize_new_lines(); $this->_reduce_linebreaks(); $this->_remove_comments(); $this->_protect_pre(); $this->_no_opening_block(); $this->_protect_braced_quotes(); } // -------------------------------------------------------------------- private function _blank_string() { // Test blank string $this->assertEquals('', $this->type->auto_typography('')); } // -------------------------------------------------------------------- private function _standardize_new_lines() { $strs = array( "My string\rhas return characters" => "<p>My string<br />\nhas return characters</p>", 'This one does not!' => '<p>This one does not!</p>' ); foreach ($strs as $str => $expect) { $this->assertEquals($expect, $this->type->auto_typography($str)); } } // -------------------------------------------------------------------- private function _reduce_linebreaks() { $str = "This has way too many linebreaks.\n\n\n\nSee?"; $expect = "<p>This has way too many linebreaks.</p>\n\n<p>See?</p>"; $this->assertEquals($expect, $this->type->auto_typography($str, TRUE)); } // -------------------------------------------------------------------- private function _remove_comments() { $str = '<!-- I can haz comments? --> But no!'; $expect = '<p><!-- I can haz comments? -->&nbsp; But no!</p>'; $this->assertEquals($expect, $this->type->auto_typography($str)); } // -------------------------------------------------------------------- private function _protect_pre() { $str = '<p>My Sentence</p><pre>var_dump($this);</pre>'; $expect = '<p>My Sentence</p><pre>var_dump($this);</pre>'; $this->assertEquals($expect, $this->type->auto_typography($str)); } // -------------------------------------------------------------------- private function _no_opening_block() { $str = 'My Sentence<pre>var_dump($this);</pre>'; $expect = '<p>My Sentence</p><pre>var_dump($this);</pre>'; $this->assertEquals($expect, $this->type->auto_typography($str)); } // -------------------------------------------------------------------- public function _protect_braced_quotes() { $this->type->protect_braced_quotes = TRUE; $str = 'Test {parse="foobar"}'; $expect = '<p>Test {parse="foobar"}</p>'; $this->assertEquals($expect, $this->type->auto_typography($str)); $this->type->protect_braced_quotes = FALSE; $str = 'Test {parse="foobar"}'; $expect = '<p>Test {parse=&#8220;foobar&#8221;}</p>'; $this->assertEquals($expect, $this->type->auto_typography($str)); } }
mattgerstman/TweetTwoScreens
tests/codeigniter/libraries/Typography_test.php
PHP
mit
4,416
/* Copyright (c) 2009-2013 Dovecot authors, see the included COPYING file */ #include "lib.h" #include "net.h" #include "ioloop.h" #include "hash.h" #include "strescape.h" #include "fd-set-nonblock.h" #include "login-proxy-state.h" #include <unistd.h> #include <fcntl.h> #define NOTIFY_RETRY_REOPEN_MSECS (60*1000) struct login_proxy_state { HASH_TABLE(struct login_proxy_record *, struct login_proxy_record *) hash; pool_t pool; const char *notify_path; int notify_fd; struct timeout *to_reopen; }; static int login_proxy_state_notify_open(struct login_proxy_state *state); static unsigned int login_proxy_record_hash(const struct login_proxy_record *rec) { return net_ip_hash(&rec->ip) ^ rec->port; } static int login_proxy_record_cmp(struct login_proxy_record *rec1, struct login_proxy_record *rec2) { if (!net_ip_compare(&rec1->ip, &rec2->ip)) return 1; return (int)rec1->port - (int)rec2->port; } struct login_proxy_state *login_proxy_state_init(const char *notify_path) { struct login_proxy_state *state; state = i_new(struct login_proxy_state, 1); state->pool = pool_alloconly_create("login proxy state", 1024); hash_table_create(&state->hash, state->pool, 0, login_proxy_record_hash, login_proxy_record_cmp); state->notify_path = p_strdup(state->pool, notify_path); state->notify_fd = -1; return state; } static void login_proxy_state_close(struct login_proxy_state *state) { if (state->notify_fd != -1) { if (close(state->notify_fd) < 0) i_error("close(%s) failed: %m", state->notify_path); state->notify_fd = -1; } } void login_proxy_state_deinit(struct login_proxy_state **_state) { struct login_proxy_state *state = *_state; *_state = NULL; if (state->to_reopen != NULL) timeout_remove(&state->to_reopen); login_proxy_state_close(state); hash_table_destroy(&state->hash); pool_unref(&state->pool); i_free(state); } struct login_proxy_record * login_proxy_state_get(struct login_proxy_state *state, const struct ip_addr *ip, unsigned int port) { struct login_proxy_record *rec, key; memset(&key, 0, sizeof(key)); key.ip = *ip; key.port = port; rec = hash_table_lookup(state->hash, &key); if (rec == NULL) { rec = p_new(state->pool, struct login_proxy_record, 1); rec->ip = *ip; rec->port = port; hash_table_insert(state->hash, rec, rec); } return rec; } static void login_proxy_state_reopen(struct login_proxy_state *state) { timeout_remove(&state->to_reopen); (void)login_proxy_state_notify_open(state); } static int login_proxy_state_notify_open(struct login_proxy_state *state) { if (state->to_reopen != NULL) { /* reopen later */ return -1; } state->notify_fd = open(state->notify_path, O_WRONLY); if (state->notify_fd == -1) { i_error("open(%s) failed: %m", state->notify_path); state->to_reopen = timeout_add(NOTIFY_RETRY_REOPEN_MSECS, login_proxy_state_reopen, state); return -1; } fd_set_nonblock(state->notify_fd, TRUE); return 0; } static bool login_proxy_state_try_notify(struct login_proxy_state *state, const char *user) { unsigned int len; ssize_t ret; if (state->notify_fd == -1) { if (login_proxy_state_notify_open(state) < 0) return TRUE; } T_BEGIN { const char *cmd; cmd = t_strconcat(str_tabescape(user), "\n", NULL); len = strlen(cmd); ret = write(state->notify_fd, cmd, len); } T_END; if (ret != (ssize_t)len) { if (ret < 0) i_error("write(%s) failed: %m", state->notify_path); else { i_error("write(%s) wrote partial update", state->notify_path); } login_proxy_state_close(state); /* retry sending */ return FALSE; } return TRUE; } void login_proxy_state_notify(struct login_proxy_state *state, const char *user) { if (!login_proxy_state_try_notify(state, user)) (void)login_proxy_state_try_notify(state, user); }
Distrotech/dovecot
src/login-common/login-proxy-state.c
C
mit
3,843
/** * window.c.ProjectSuggestedContributions component * A Project-show page helper to show suggested amounts of contributions * * Example of use: * view: () => { * ... * m.component(c.ProjectSuggestedContributions, {project: project}) * ... * } */ import m from 'mithril'; import _ from 'underscore'; const projectSuggestedContributions = { view(ctrl, args) { const project = args.project(); const suggestionUrl = amount => `/projects/${project.project_id}/contributions/new?amount=${amount}`, suggestedValues = [10, 25, 50, 100]; return m('#suggestions', _.map(suggestedValues, amount => project ? m(`a[href="${suggestionUrl(amount)}"].card-reward.card-big.card-secondary.u-marginbottom-20`, [ m('.fontsize-larger', `R$ ${amount}`) ]) : '')); } }; export default projectSuggestedContributions;
vicnicius/catarse_admin
src/c/project-suggested-contributions.js
JavaScript
mit
881
""" Copyright (c) 2012-2016 Ben Croston Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from RPi._GPIO import * VERSION = '0.6.3'
anatolieGhebea/contatore
python/RPi.GPIO-0.6.3/RPi/GPIO/__init__.py
Python
mit
1,112
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html" charset="iso-8859-1"> <title>org.apache.commons.net.pop3 (Commons Net 3.3 API)</title> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="org.apache.commons.net.pop3 (Commons Net 3.3 API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/commons/net/ntp/package-summary.html">Prev Package</a></li> <li><a href="../../../../../org/apache/commons/net/smtp/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/commons/net/pop3/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Package" class="title">Package&nbsp;org.apache.commons.net.pop3</h1> <div class="docSummary"> <div class="block">POP3 and POP3S mail</div> </div> <p>See:&nbsp;<a href="#package_description">Description</a></p> </div> <div class="contentContainer"> <ul class="blockList"> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation"> <caption><span>Class Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Class</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/commons/net/pop3/ExtendedPOP3Client.html" title="class in org.apache.commons.net.pop3">ExtendedPOP3Client</a></td> <td class="colLast"> <div class="block">A POP3 Cilent class with protocol and authentication extensions support (RFC2449 and RFC2195).</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/commons/net/pop3/POP3.html" title="class in org.apache.commons.net.pop3">POP3</a></td> <td class="colLast"> <div class="block">The POP3 class is not meant to be used by itself and is provided only so that you may easily implement your own POP3 client if you so desire.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/commons/net/pop3/POP3Client.html" title="class in org.apache.commons.net.pop3">POP3Client</a></td> <td class="colLast"> <div class="block">The POP3Client class implements the client side of the Internet POP3 Protocol defined in RFC 1939.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/commons/net/pop3/POP3Command.html" title="class in org.apache.commons.net.pop3">POP3Command</a></td> <td class="colLast"> <div class="block">POP3Command stores POP3 command code constants.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/commons/net/pop3/POP3MessageInfo.html" title="class in org.apache.commons.net.pop3">POP3MessageInfo</a></td> <td class="colLast"> <div class="block">POP3MessageInfo is used to return information about messages stored on a POP3 server.</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><a href="../../../../../org/apache/commons/net/pop3/POP3Reply.html" title="class in org.apache.commons.net.pop3">POP3Reply</a></td> <td class="colLast"> <div class="block">POP3Reply stores POP3 reply code constants.</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/commons/net/pop3/POP3SClient.html" title="class in org.apache.commons.net.pop3">POP3SClient</a></td> <td class="colLast"> <div class="block">POP3 over SSL processing.</div> </td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Summary table, listing enums, and an explanation"> <caption><span>Enum Summary</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Enum</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="../../../../../org/apache/commons/net/pop3/ExtendedPOP3Client.AUTH_METHOD.html" title="enum in org.apache.commons.net.pop3">ExtendedPOP3Client.AUTH_METHOD</a></td> <td class="colLast"> <div class="block">The enumeration of currently-supported authentication methods.</div> </td> </tr> </tbody> </table> </li> </ul> <a name="package_description"> <!-- --> </a> <h2 title="Package org.apache.commons.net.pop3 Description">Package org.apache.commons.net.pop3 Description</h2> <div class="block">POP3 and POP3S mail</div> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li class="navBarCell1Rev">Package</li> <li>Class</li> <li><a href="package-use.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../org/apache/commons/net/ntp/package-summary.html">Prev Package</a></li> <li><a href="../../../../../org/apache/commons/net/smtp/package-summary.html">Next Package</a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?org/apache/commons/net/pop3/package-summary.html" target="_top">Frames</a></li> <li><a href="package-summary.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2001-2013 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved.</small></p> </body> </html>
asad/MCEDS
lib/commons-net-3.3/apidocs/org/apache/commons/net/pop3/package-summary.html
HTML
mit
8,093
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading; namespace GSoft.Dynamite.Collections { /// <summary> /// A list that supports synchronized reading and writing. /// </summary> /// <typeparam name="T">The type of object contained in the list.</typeparam> [Serializable] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This is actually a list.")] public class ConcurrentList<T> : IList<T>, IList { #region Fields private readonly List<T> _underlyingList = new List<T>(); [NonSerialized] private volatile ReaderWriterLockSlim _lock; #endregion #region Properties /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> public int Count { get { this.Lock.EnterReadLock(); try { return this._underlyingList.Count; } finally { this.Lock.ExitReadLock(); } } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get { this.Lock.EnterReadLock(); try { return ((IList)this._underlyingList).IsReadOnly; } finally { this.Lock.ExitReadLock(); } } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> has a fixed size. /// </summary> /// <returns>true if the <see cref="T:System.Collections.IList"/> has a fixed size; otherwise, false.</returns> [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Not part of IList of T.")] bool IList.IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe). /// </summary> /// <returns>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); otherwise, false.</returns> [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Not part of IList of T.")] bool ICollection.IsSynchronized { get { return true; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>. /// </summary> /// <returns>An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.</returns> [SuppressMessage("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes", Justification = "Not part of IList of T.")] object ICollection.SyncRoot { get { return this; } } /// <summary> /// Gets the lock used for synchronization. /// </summary> private ReaderWriterLockSlim Lock { get { if (this._lock == null) { lock (this) { if (this._lock == null) { this._lock = new ReaderWriterLockSlim(); } } } return this._lock; } } /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <param name="index">The index to add the item at.</param> /// <returns> /// The element at the specified index. /// </returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception> /// <exception cref="T:System.NotSupportedException"> /// The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only. /// </exception> object IList.this[int index] { get { return this[index]; } set { this[index] = (T)value; } } /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <param name="index">The index to add the item at.</param> /// <returns> /// The element at the specified index. /// </returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception> /// <exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception> public T this[int index] { get { this.Lock.EnterReadLock(); try { return this._underlyingList[index]; } finally { this.Lock.ExitReadLock(); } } set { this.Lock.EnterWriteLock(); try { this._underlyingList[index] = value; } finally { this.Lock.ExitWriteLock(); } } } #endregion #region Methods /// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> public int IndexOf(T item) { this.Lock.EnterReadLock(); try { return this._underlyingList.IndexOf(item); } finally { this.Lock.ExitReadLock(); } } /// <summary> /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only. /// </exception> public void Insert(int index, T item) { this.Lock.EnterWriteLock(); try { this._underlyingList.Insert(index, item); } finally { this.Lock.ExitWriteLock(); } } /// <summary> /// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </exception> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only. /// </exception> public void RemoveAt(int index) { this.Lock.EnterWriteLock(); try { this._underlyingList.RemoveAt(index); } finally { this.Lock.ExitWriteLock(); } } /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public void Add(T item) { this.Lock.EnterWriteLock(); try { this._underlyingList.Add(item); } finally { this.Lock.ExitWriteLock(); } } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public void Clear() { this.Lock.EnterWriteLock(); try { this._underlyingList.Clear(); } finally { this.Lock.ExitWriteLock(); } } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> public bool Contains(T item) { this.Lock.EnterReadLock(); try { return this._underlyingList.Contains(item); } finally { this.Lock.ExitReadLock(); } } /// <summary> /// Copies to. /// </summary> /// <param name="array">The array.</param> /// <param name="arrayIndex">Index of the array.</param> public void CopyTo(T[] array, int arrayIndex) { ((IList)this).CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </exception> public bool Remove(T item) { this.Lock.EnterWriteLock(); try { return this._underlyingList.Remove(item); } finally { this.Lock.ExitWriteLock(); } } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public virtual IEnumerator<T> GetEnumerator() { this.Lock.EnterReadLock(); return new ReadLockedEnumerator<T>(this.Lock, this._underlyingList.GetEnumerator()); } /// <summary> /// Adds an item to the <see cref="T:System.Collections.IList"/>. /// </summary> /// <param name="value">The object to add to the <see cref="T:System.Collections.IList"/>.</param> /// <returns> /// The position into which the new element was inserted, or -1 to indicate that the item was not inserted into the collection, /// </returns> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IList"/> is read-only.-or- The <see cref="T:System.Collections.IList"/> has a fixed size. </exception> int IList.Add(object value) { this.Lock.EnterWriteLock(); try { return ((IList)this._underlyingList).Add(value); } finally { this.Lock.ExitWriteLock(); } } /// <summary> /// Determines whether the <see cref="T:System.Collections.IList"/> contains a specific value. /// </summary> /// <param name="value">The object to locate in the <see cref="T:System.Collections.IList"/>.</param> /// <returns> /// true if the <see cref="T:System.Object"/> is found in the <see cref="T:System.Collections.IList"/>; otherwise, false. /// </returns> bool IList.Contains(object value) { return this.Contains((T)value); } /// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.IList"/>. /// </summary> /// <param name="value">The object to locate in the <see cref="T:System.Collections.IList"/>.</param> /// <returns> /// The index of <paramref name="value"/> if found in the list; otherwise, -1. /// </returns> int IList.IndexOf(object value) { return this.IndexOf((T)value); } /// <summary> /// Inserts an item to the <see cref="T:System.Collections.IList"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param> /// <param name="value">The object to insert into the <see cref="T:System.Collections.IList"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.IList"/>. </exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IList"/> is read-only.-or- The <see cref="T:System.Collections.IList"/> has a fixed size. </exception> /// <exception cref="T:System.NullReferenceException"> /// <paramref name="value"/> is null reference in the <see cref="T:System.Collections.IList"/>.</exception> void IList.Insert(int index, object value) { this.Insert(index, (T)value); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.IList"/>. /// </summary> /// <param name="value">The object to remove from the <see cref="T:System.Collections.IList"/>.</param> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IList"/> is read-only.-or- The <see cref="T:System.Collections.IList"/> has a fixed size. </exception> void IList.Remove(object value) { this.Remove((T)value); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"> /// <paramref name="array"/> is null. </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"> /// <paramref name="index"/> is less than zero. </exception> /// <exception cref="T:System.ArgumentException"> /// <paramref name="array"/> is multidimensional.-or- The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>. </exception> /// <exception cref="T:System.ArgumentException">The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>. </exception> void ICollection.CopyTo(Array array, int index) { this.Lock.EnterReadLock(); try { ((IList)this._underlyingList).CopyTo(array, index); } finally { this.Lock.ExitReadLock(); } } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region Nested classes /// <summary> /// An enumerator that releases a read lock when Disposing. /// </summary> /// <typeparam name="TItem">The type of the item.</typeparam> private class ReadLockedEnumerator<TItem> : IEnumerator<TItem> { private readonly ReaderWriterLockSlim _syncRoot; private readonly IEnumerator<TItem> _underlyingEnumerator; /// <summary> /// Initializes a new instance of the <see cref="ConcurrentList&lt;T&gt;.ReadLockedEnumerator&lt;TItem&gt;"/> class. /// </summary> /// <param name="syncRoot">The sync root.</param> /// <param name="underlyingEnumerator">The underlying enumerator.</param> public ReadLockedEnumerator(ReaderWriterLockSlim syncRoot, IEnumerator<TItem> underlyingEnumerator) { this._syncRoot = syncRoot; this._underlyingEnumerator = underlyingEnumerator; } /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> /// <returns> /// The element in the collection at the current position of the enumerator. /// </returns> public TItem Current { get { return this._underlyingEnumerator.Current; } } /// <summary> /// Gets the element in the collection at the current position of the enumerator. /// </summary> /// <returns> /// The element in the collection at the current position of the enumerator. /// </returns> object IEnumerator.Current { get { return this.Current; } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { this._syncRoot.ExitReadLock(); } /// <summary> /// Advances the enumerator to the next element of the collection. /// </summary> /// <returns> /// true if the enumerator was successfully advanced to the next element; false if the enumerator has passed the end of the collection. /// </returns> /// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception> public bool MoveNext() { return this._underlyingEnumerator.MoveNext(); } /// <summary> /// Sets the enumerator to its initial position, which is before the first element in the collection. /// </summary> /// <exception cref="T:System.InvalidOperationException">The collection was modified after the enumerator was created. </exception> public void Reset() { this._underlyingEnumerator.Reset(); } } #endregion } }
GSoft-SharePoint/Dynamite
Source/GSoft.Dynamite/Collections/ConcurrentList.cs
C#
mit
22,033
<?php namespace Oro\Bundle\IntegrationBundle\Provider; use Oro\Bundle\IntegrationBundle\Entity\Channel as Integration; interface SyncProcessorInterface { /** * @param Integration $integration * @param $connector * @param array $connectorParameters * * @return bool */ public function process(Integration $integration, $connector, array $connectorParameters = []); }
Djamy/platform
src/Oro/Bundle/IntegrationBundle/Provider/SyncProcessorInterface.php
PHP
mit
407
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_17) on Sun Nov 03 15:35:48 CET 2013 --> <title>Uses of Class com.badlogic.gdx.utils.ObjectFloatMap.Values (libgdx API)</title> <meta name="date" content="2013-11-03"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class com.badlogic.gdx.utils.ObjectFloatMap.Values (libgdx API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/badlogic/gdx/utils/ObjectFloatMap.Values.html" title="class in com.badlogic.gdx.utils">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em> libgdx API <style> body, td, th { font-family:Helvetica, Tahoma, Arial, sans-serif; font-size:10pt } pre, code, tt { font-size:9pt; font-family:Lucida Console, Courier New, sans-serif } h1, h2, h3, .FrameTitleFont, .FrameHeadingFont, .TableHeadingColor font { font-size:105%; font-weight:bold } .TableHeadingColor { background:#EEEEFF; } a { text-decoration:none } a:hover { text-decoration:underline } a:link, a:visited { color:blue } table { border:0px } .TableRowColor td:first-child { border-left:1px solid black } .TableRowColor td { border:0px; border-bottom:1px solid black; border-right:1px solid black } hr { border:0px; border-bottom:1px solid #333366; } </style> </em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/badlogic/gdx/utils/class-use/ObjectFloatMap.Values.html" target="_top">Frames</a></li> <li><a href="ObjectFloatMap.Values.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class com.badlogic.gdx.utils.ObjectFloatMap.Values" class="title">Uses of Class<br>com.badlogic.gdx.utils.ObjectFloatMap.Values</h2> </div> <div class="classUseContainer"> <ul class="blockList"> <li class="blockList"> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation"> <caption><span>Packages that use <a href="../../../../../com/badlogic/gdx/utils/ObjectFloatMap.Values.html" title="class in com.badlogic.gdx.utils">ObjectFloatMap.Values</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Package</th> <th class="colLast" scope="col">Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a href="#com.badlogic.gdx.utils">com.badlogic.gdx.utils</a></td> <td class="colLast">&nbsp;</td> </tr> </tbody> </table> </li> <li class="blockList"> <ul class="blockList"> <li class="blockList"><a name="com.badlogic.gdx.utils"> <!-- --> </a> <h3>Uses of <a href="../../../../../com/badlogic/gdx/utils/ObjectFloatMap.Values.html" title="class in com.badlogic.gdx.utils">ObjectFloatMap.Values</a> in <a href="../../../../../com/badlogic/gdx/utils/package-summary.html">com.badlogic.gdx.utils</a></h3> <table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation"> <caption><span>Methods in <a href="../../../../../com/badlogic/gdx/utils/package-summary.html">com.badlogic.gdx.utils</a> that return <a href="../../../../../com/badlogic/gdx/utils/ObjectFloatMap.Values.html" title="class in com.badlogic.gdx.utils">ObjectFloatMap.Values</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><code><a href="../../../../../com/badlogic/gdx/utils/ObjectFloatMap.Values.html" title="class in com.badlogic.gdx.utils">ObjectFloatMap.Values</a></code></td> <td class="colLast"><span class="strong">ObjectFloatMap.</span><code><strong><a href="../../../../../com/badlogic/gdx/utils/ObjectFloatMap.html#values()">values</a></strong>()</code> <div class="block">Returns an iterator for the values in the map.</div> </td> </tr> </tbody> </table> </li> </ul> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../com/badlogic/gdx/utils/ObjectFloatMap.Values.html" title="class in com.badlogic.gdx.utils">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../../../../../overview-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> <div class="aboutLanguage"><em>libgdx API</em></div> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/badlogic/gdx/utils/class-use/ObjectFloatMap.Values.html" target="_top">Frames</a></li> <li><a href="ObjectFloatMap.Values.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small> <div style="font-size:9pt"><i> Copyright &copy; 2010-2013 Mario Zechner (contact@badlogicgames.com), Nathan Sweet (admin@esotericsoftware.com) </i></div> </small></p> </body> </html>
emeryduh/TeamJones_Project
libgdx/docs/api/com/badlogic/gdx/utils/class-use/ObjectFloatMap.Values.html
HTML
mit
7,368
import { get } from '../get' export function getSearchData(page, cityName, category, keyword) { const keywordStr = keyword ? '/' + keyword : '' const result = get('/api/search/' + page + '/' + cityName + '/' + category + keywordStr) return result }
su-chang/react-web-app
app/fetch/search/search.js
JavaScript
mit
261
/*global define*/ /*jslint white:true,browser:true*/ define([ 'bluebird', // CDN 'kb_common/html', // LOCAL 'common/ui', 'common/runtime', 'common/events', 'common/props', // Wrapper for inputs './inputWrapperWidget', 'widgets/appWidgets/fieldWidget', // Display widgets 'widgets/appWidgets/paramDisplayResolver' ], function ( Promise, html, UI, Runtime, Events, Props, //Wrappers RowWidget, FieldWidget, ParamResolver ) { 'use strict'; var t = html.tag, form = t('form'), span = t('span'), div = t('div'); function factory(config) { var runtime = Runtime.make(), parentBus = config.bus, cellId = config.cellId, workspaceInfo = config.workspaceInfo, container, ui, bus, places, model = Props.make(), inputBusses = [], settings = { showAdvanced: null }, paramResolver = ParamResolver.make(); // DATA /* * The input control widget is selected based on these parameters: * - data type - (text, int, float, workspaceObject (ref, name) * - input app - input, select */ // RENDERING function makeFieldWidget(parameterSpec, value) { var bus = runtime.bus().makeChannelBus(null, 'Params view input bus comm widget'), inputWidget = paramResolver.getWidgetFactory(parameterSpec); inputBusses.push(bus); // An input widget may ask for the current model value at any time. bus.on('sync', function () { parentBus.emit('parameter-sync', { parameter: parameterSpec.id() }); }); parentBus.listen({ key: { type: 'update', parameter: parameterSpec.id() }, handle: function (message) { bus.emit('update', { value: message.value }); } }); // Just pass the update along to the input widget. // TODO: commented out, is it even used? // parentBus.listen({ // test: function (message) { // var pass = (message.type === 'update' && message.parameter === parameterSpec.id()); // return pass; // }, // handle: function (message) { // bus.send(message); // } // }); return FieldWidget.make({ inputControlFactory: inputWidget, showHint: true, useRowHighight: true, initialValue: value, parameterSpec: parameterSpec, bus: bus, workspaceId: workspaceInfo.id }); } function renderAdvanced() { var advancedInputs = container.querySelectorAll('[data-advanced-parameter]'); if (advancedInputs.length === 0) { return; } var removeClass = (settings.showAdvanced ? 'advanced-parameter-hidden' : 'advanced-parameter-showing'), addClass = (settings.showAdvanced ? 'advanced-parameter-showing' : 'advanced-parameter-hidden'); for (var i = 0; i < advancedInputs.length; i += 1) { var input = advancedInputs[i]; input.classList.remove(removeClass); input.classList.add(addClass); } // How many advanaced? // Also update the button var button = container.querySelector('[data-button="toggle-advanced"]'); button.innerHTML = (settings.showAdvanced ? 'Hide Advanced' : 'Show Advanced (' + advancedInputs.length + ' hidden)'); // Also update the } function renderLayout() { var events = Events.make(), content = form({dataElement: 'input-widget-form'}, [ ui.buildPanel({ type: 'default', classes: 'kb-panel-light', body: [ ui.makeButton('Show Advanced', 'toggle-advanced', {events: events}) ] }), ui.buildPanel({ title: 'Inputs', body: div({dataElement: 'input-fields'}), classes: ['kb-panel-container'] }), ui.buildPanel({ title: span(['Parameters', span({dataElement: 'advanced-hidden'})]), body: div({dataElement: 'parameter-fields'}), classes: ['kb-panel-container'] }), ui.buildPanel({ title: 'Outputs', body: div({dataElement: 'output-fields'}), classes: ['kb-panel-container'] }) ]); return { content: content, events: events }; } // MESSAGE HANDLERS function doAttach(node) { container = node; ui = UI.make({ node: container, bus: bus }); var layout = renderLayout(); container.innerHTML = layout.content; layout.events.attachEvents(container); places = { inputFields: ui.getElement('input-fields'), outputFields: ui.getElement('output-fields'), parameterFields: ui.getElement('parameter-fields'), advancedParameterFields: ui.getElement('advanced-parameter-fields') }; } // EVENTS function attachEvents() { bus.on('reset-to-defaults', function () { inputBusses.forEach(function (inputBus) { inputBus.send({ type: 'reset-to-defaults' }); }); }); bus.on('toggle-advanced', function () { settings.showAdvanced = !settings.showAdvanced; renderAdvanced(); }); } // LIFECYCLE API function renderParameters(params) { var widgets = []; // First get the app specs, which is stashed in the model, // with the parameters returned. // Separate out the params into the primary groups. var params = model.getItem('parameters'), inputParams = params.filter(function (spec) { return (spec.spec.ui_class === 'input'); }), outputParams = params.filter(function (spec) { return (spec.spec.ui_class === 'output'); }), parameterParams = params.filter(function (spec) { return (spec.spec.ui_class === 'parameter'); }); return Promise.resolve() .then(function () { if (inputParams.length === 0) { places.inputFields.innerHTML = span({style: {fontStyle: 'italic'}}, 'No input objects for this app'); } else { return Promise.all(inputParams.map(function (spec) { var fieldWidget = makeFieldWidget(spec, model.getItem(['params', spec.name()])), rowWidget = RowWidget.make({widget: fieldWidget, spec: spec}), rowNode = document.createElement('div'); places.inputFields.appendChild(rowNode); widgets.push(rowWidget); rowWidget.attach(rowNode); })); } }) .then(function () { if (outputParams.length === 0) { places.outputFields.innerHTML = span({style: {fontStyle: 'italic'}}, 'No output objects for this app'); } else { return Promise.all(outputParams.map(function (spec) { var fieldWidget = makeFieldWidget(spec, model.getItem(['params', spec.name()])), rowWidget = RowWidget.make({widget: fieldWidget, spec: spec}), rowNode = document.createElement('div'); places.outputFields.appendChild(rowNode); widgets.push(rowWidget); rowWidget.attach(rowNode); })); } }) .then(function () { if (parameterParams.length === 0) { ui.setContent('parameter-fields', span({style: {fontStyle: 'italic'}}, 'No parameters for this app')); } else { return Promise.all(parameterParams.map(function (spec) { var fieldWidget = makeFieldWidget(spec, model.getItem(['params', spec.name()])), rowWidget = RowWidget.make({widget: fieldWidget, spec: spec}), rowNode = document.createElement('div'); places.parameterFields.appendChild(rowNode); widgets.push(rowWidget); rowWidget.attach(rowNode); })); } }) .then(function () { return Promise.all(widgets.map(function (widget) { return widget.start(); })); }) .then(function () { return Promise.all(widgets.map(function (widget) { return widget.run(params); })); }) .then(function () { renderAdvanced(); }); } function start() { // send parent the ready message return Promise.try(function () { parentBus.emit('ready'); // parent will send us our initial parameters parentBus.on('run', function (message) { doAttach(message.node); model.setItem('parameters', message.parameters); // we then create our widgets renderParameters() .then(function () { // do something after success attachEvents(); }) .catch(function (err) { // do somethig with the error. console.error('ERROR in start', err); }); }); }); } function stop() { return Promise.try(function () { // unregister listerrs... }); } // CONSTRUCTION bus = runtime.bus().makeChannelBus(null, 'params view own bus'); return { start: start, stop: stop, bus: function () { return bus; } }; } return { make: function (config) { return factory(config); } }; });
msneddon/narrative
nbextensions/editorCell_bill/widgets/editorParamsViewWidget.js
JavaScript
mit
11,747
#!/bin/bash FN="ALL_1.32.0.tar.gz" URLS=( "https://bioconductor.org/packages/3.12/data/experiment/src/contrib/ALL_1.32.0.tar.gz" "https://bioarchive.galaxyproject.org/ALL_1.32.0.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-all/bioconductor-all_1.32.0_src_all.tar.gz" ) MD5="a7181423086d1ea752a3e417ff1063c0" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
bebatut/bioconda-recipes
recipes/bioconductor-all/post-link.sh
Shell
mit
1,267
/* css Zen Garden submission 145 - 'Paravion', by Emiliano Pennisi, http://www.peamarte.it/01/metro.html */ /* css released under Creative Commons License - http://creativecommons.org/licenses/by-nc-sa/1.0/ */ /* All associated graphics copyright 2004, Emiliano Pennisi */ /* Added: Dec. 16th, 2004 */ /* IMPORTANT */ /* This design is not a template. You may not reproduce it elsewhere without the designer's written permission. However, feel free to study the CSS and use techniques you learn from it elsewhere. */ body{ font-family: "Book Antiqua",Georgia,"MS Sans Serif", Geneva, sans-serif; background: #A3181E url(bg_body.gif) fixed repeat-x; margin: 0; text-align: center; margin: 0; padding: 0; height: 100%; } acronym { color: #A3181E; font-weight: bold; } /*h3 rules*/ div#linkList h3 span{ font-size: 16px; background: #A3181E; border-bottom: 2px solid white; color: White; margin-left: 5px; margin-bottom: 0; padding: 3px; width: 185px; display: block; } #preamble h3 span,#supportingText h3 span{ font-family: "Courier New", Courier, monospace; background: url(h3bg.gif) no-repeat 6px 0; color: #A3181E; font-size: 20px; letter-spacing: -1px; padding-left: 35px; } div#linkList h3{ font-family: "Book Antiqua",Times, Helvetica, sans-serif; font-weight: bold; } /*link*/ #preamble a, #supportingText a,#linkList a{ color: #2B497B; font-weight: bold; } #preamble a:hover,#supportingText a:hover{ background: #2B497B; color: White; text-decoration: none; } /*Style for linkList acronym*/ div#linkList acronym { background: #A3181E; color: White; } /*child selector only for compliant mode*/ body>div#container{ height: auto; min-height: 100%; } /*container*/ div#container{ position: relative; height: 100%; background: url(bg_container.gif); margin-left: auto; margin-right: auto; border-right: 3px solid white; border-left: 3px solid white; border-bottom: 20px solid white; width: 650px; text-align: left; font-size: 0.8em; } #pageHeader { background: url(head.gif) no-repeat; height: 452px; margin: 0 0 30px 0; } #pageHeader h1,#pageHeader h2{ display: none; } /*Hide quicksummary*/ #quickSummary .p2 a{ color: #A3181E; } #quickSummary p.p1 span{ display: none; } #quickSummary p.p2 { font-size: 0.9em; line-height: 12px; position: absolute; top: 275px; left: 235px; padding: 0 0 8px 0; width: 200px; text-transform: uppercase; font-weight: bold; border-top: 1px dashed #000; padding-top: 2px; } #preamble,#supportingText{ position: relative; margin-left: 250px; margin-top: -30px; width: 400px; } /*child selector only for compliant mode*/ div#preamble,div#supportingText{ background: url(st_bg.gif); } div#preamble,#supportingText{ padding: 10px; margin-bottom: 10px; width: 370px; /*Start Tantek Box Model Hack*/ voice-family: "\"}\""; voice-family: inherit; width: 350px; } /*child selector only for compliant mode*/ body > div#preamble,#supportingText{ width: 350px; } /**************************Navigation**********************************/ #linkList{ font-family: Georgia,"MS Sans Serif", Geneva, sans-serif; background: url(linklist_bg.jpg); padding: 10px; width: 220px; position: absolute; top: 450px; margin-left: 15px; /*Start Tantek Box Model Hack*/ voice-family: "\"}\""; voice-family: inherit; width: 200px; } #linkList li { color: #fff; } #linkList ul { list-style: none; margin: 5px; margin-top: -20px; padding: 0px; border-top: 10px solid #CAD2DE; background: #2B497B; } #linkList li { color: #000; border-bottom: 1px dotted #fff; padding: 0.2em 10px; line-height: 15px; } #linkList li:hover { background: #A3181E; } #container > #linkList ul li a:hover{ color: White; } #linkList ul li a:hover{ color: #A3181E; } #linkList li a { font-size: 10px; display: block; color: #fff; font-weight: bold; text-decoration: none; text-transform: uppercase; } #linkList li a:hover { color: #fff; } #linkList li a.c:hover { color: #fff; } #lselect ul li{ color: White; } #lselect ul li a.c{ font-weight: bold; display: inline; color: White; text-transform: none; } /*Start Footer rules*/ #footer { font-family: Georgia,"MS Sans Serif", Geneva, sans-serif; margin: 0 -5px -5px; border-top: 5px solid #FFF; background-color: #A3181E; padding: 10px; text-transform: uppercase; text-align: right; } #footer a{ font-size: 9px; color: #fff; font-weight: bold; padding: 3px; text-decoration: none; border-right: 1px solid white; padding: 0 5px 0 0; } /*End of code*/
codenothing/css-compressor
unit/benchmark/src/csszengarden.com.145.css
CSS
mit
4,813
package com.hearthsim.card.basic.spell; import com.hearthsim.card.spellcard.SpellTargetableCard; import com.hearthsim.event.effect.EffectCharacter; import com.hearthsim.event.effect.EffectCharacterBuffTemp; import com.hearthsim.event.filter.FilterCharacter; import com.hearthsim.event.filter.FilterCharacterTargetedSpell; public class HeroicStrike extends SpellTargetableCard { private final static EffectCharacter effect = new EffectCharacterBuffTemp(4); /** * Constructor * * Defaults to hasBeenUsed = false */ public HeroicStrike() { super(); } @Override public FilterCharacter getTargetableFilter() { return FilterCharacterTargetedSpell.SELF; } /** * Heroic Strike * * Gives the hero +4 attack this turn * * * * @param side * @param boardState The BoardState before this card has performed its action. It will be manipulated and returned. * * @return The boardState is manipulated and returned */ @Override public EffectCharacter getTargetableEffect() { return HeroicStrike.effect; } }
oyachai/HearthSim
src/main/java/com/hearthsim/card/basic/spell/HeroicStrike.java
Java
mit
1,140
module SS::Reference::Site extend ActiveSupport::Concern extend SS::Translation included do cattr_accessor :site_required, instance_accessor: false self.site_required = true attr_accessor :cur_site belongs_to :site, class_name: "SS::Site" validates :site_id, presence: true, if: ->{ self.class.site_required } before_validation :set_site_id, if: ->{ @cur_site } end module ClassMethods # define scope by class method instead of scope to be able to override by subclass def site(site) where(site_id: site.id) end end private def set_site_id self.site_id ||= @cur_site.id end end
ShinjiTanimoto/shirasagi
app/models/concerns/ss/reference/site.rb
Ruby
mit
649
#! /bin/sh # SPDX-License-Identifier: BSD-3-Clause # Copyright 2015 6WIND S.A. # Do some basic checks in MAINTAINERS file cd $(dirname $0)/.. # speed up by ignoring Unicode details export LC_ALL=C # Get files matching paths with wildcards and / meaning recursing files () # <path> [<path> ...] { if [ -z "$1" ] ; then return fi if [ -r .git ] ; then git ls-files "$1" else find $1 -type f | sed 's,^\./,,' fi | # if not ended by / if ! echo "$1" | grep -q '/[[:space:]]*$' ; then # filter out deeper directories sed "/\(\/[^/]*\)\{$(($(echo "$1" | grep -o / | wc -l) + 1))\}/d" else cat fi # next path shift files "$@" } # Get all files matching F: and X: fields parse_fx () # <index file> { IFS=' ' # parse each line excepted underlining for line in $( (sed '/^-\+$/d' $1 ; echo) | sed 's,^$,§,') ; do if echo "$line" | grep -q '^§$' ; then # empty line delimit end of section include_files=$(files $flines) exclude_files=$(files $xlines) match=$(aminusb "$include_files" "$exclude_files") if [ -n "$include_files" ] ; then printf "# $title " maintainers=$(echo "$maintainers" | sed -r 's,.*<(.*)>.*,\1,') maintainers=$(printf "$maintainers" | sed -e 's,^,<,' -e 's,$,>,') echo $maintainers fi if [ -n "$match" ] ; then echo "$match" fi # flush section unset maintainers unset flines unset xlines elif echo "$line" | grep -q '^[A-Z]: ' ; then # maintainer maintainers=$(add_line_to_if "$line" "$maintainers" 'M: ') # file matching pattern flines=$(add_line_to_if "$line" "$flines" 'F: ') # file exclusion pattern xlines=$(add_line_to_if "$line" "$xlines" 'X: ') else # assume it is a title title="$line" fi done } # Check patterns in F: and X: check_fx () # <index file> { IFS=' ' for line in $(sed -n 's,^[FX]: ,,p' $1 | tr '*' '#') ; do line=$(printf "$line" | tr '#' '*') match=$(files "$line") if [ -z "$match" ] ; then echo "$line" fi done } # Add a line to a set of lines if it begins with right pattern add_line_to_if () # <new line> <lines> <head pattern> { ( echo "$2" echo "$1" | sed -rn "s,^$3(.*),\1,p" ) | sed '/^$/d' } # Subtract two sets of lines aminusb () # <lines a> <lines b> { printf "$1\n$2\n$2" | sort | uniq -u | sed '/^$/d' } printf 'sections: ' parsed=$(parse_fx MAINTAINERS) echo "$parsed" | grep -c '^#' printf 'with maintainer: ' echo "$parsed" | grep -c '^#.*@' printf 'maintainers: ' grep '^M:.*<' MAINTAINERS | sort -u | wc -l echo echo '##########' echo '# orphan areas' echo '##########' echo "$parsed" | sed -rn 's,^#([^@]*)$,\1,p' | uniq echo echo '##########' echo '# files not listed' echo '##########' all=$(files ./) listed=$(echo "$parsed" | sed '/^#/d' | sort -u) aminusb "$all" "$listed" echo echo '##########' echo '# wrong patterns' echo '##########' check_fx MAINTAINERS # TODO: check overlaps
john-mcnamara-intel/dpdk
devtools/check-maintainers.sh
Shell
mit
2,892
<!DOCTYPE html> <html> <head> <title>NEJ实例 - 计数器</title> <meta charset="utf-8" /> <script> function log(msg){ var div = document.createElement('div'); div.innerHTML = msg; document.body.appendChild(div); } </script> </head> <body> <textarea id="abc" style="width:300px;height:200px" onclick="b();"></textarea> <input type="button" value="show" onclick="a();"/> <script src="../../../define.js"></script> <script> NEJ.define([ '../cursor.js' ],function(_e){ var xx; var tx = document.getElementById('abc'); tx.onbeforedeactivate = function(){ xx = _e._$cursor(tx); }; window.a = function(){ var p = xx||_e._$cursor(tx), v = tx.value, t = '[表情]'; tx.value = v.substr(0, p.start)+t+ v.substring(p.end); _e._$cursor(tx,p.start+ t.length); xx = null; }; window.b = function(){ log(_e._$lineno(tx)); }; }); </script> </body> </html>
NEYouFan/nej-toolkit
test/cases/nej_0.1.0/webapp/src/javascript/lib/nej/util/cursor/demo/cursor.html
HTML
mit
1,199
TARGET?=tests .PHONY: docs flake8 example test coverage docs: cd docs; make html open docs/_build/html/index.html flake8: flake8 --ignore=W999 two_factor example tests example: DJANGO_SETTINGS_MODULE=example.settings PYTHONPATH=. \ django-admin.py runserver test: DJANGO_SETTINGS_MODULE=tests.settings PYTHONPATH=. \ django-admin.py test ${TARGET} coverage: coverage erase DJANGO_SETTINGS_MODULE=tests.settings PYTHONPATH=. \ coverage run --branch --source=two_factor \ `which django-admin.py` test ${TARGET} coverage combine coverage html coverage report tx-pull: tx pull -a cd two_factor; django-admin.py compilemessages cd example; django-admin.py compilemessages tx-push: cd two_factor; django-admin.py makemessages -l en cd example; django-admin.py makemessages -l en tx push -s
mathspace/django-two-factor-auth
Makefile
Makefile
mit
816
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using Mindscape.Raygun4Net.Messages; using System.Threading; using System.Reflection; using Mindscape.Raygun4Net.Builders; namespace Mindscape.Raygun4Net { public class RaygunClient : RaygunClientBase { private readonly string _apiKey; private readonly List<Type> _wrapperExceptions = new List<Type>(); /// <summary> /// Initializes a new instance of the <see cref="RaygunClient" /> class. /// </summary> /// <param name="apiKey">The API key.</param> public RaygunClient(string apiKey) { _apiKey = apiKey; _wrapperExceptions.Add(typeof(TargetInvocationException)); } /// <summary> /// Initializes a new instance of the <see cref="RaygunClient" /> class. /// Uses the ApiKey specified in the config file. /// </summary> public RaygunClient() : this(RaygunSettings.Settings.ApiKey) { } protected bool ValidateApiKey() { if (string.IsNullOrEmpty(_apiKey)) { System.Diagnostics.Debug.WriteLine("ApiKey has not been provided, exception will not be logged"); return false; } return true; } /// <summary> /// Gets or sets the username/password credentials which are used to authenticate with the system default Proxy server, if one is set /// and requires credentials. /// </summary> public ICredentials ProxyCredentials { get; set; } /// <summary> /// Gets or sets an IWebProxy instance which can be used to override the default system proxy server settings /// </summary> public IWebProxy WebProxy { get; set; } /// <summary> /// Adds a list of outer exceptions that will be stripped, leaving only the valuable inner exception. /// This can be used when a wrapper exception, e.g. TargetInvocationException or HttpUnhandledException, /// contains the actual exception as the InnerException. The message and stack trace of the inner exception will then /// be used by Raygun for grouping and display. The above two do not need to be added manually, /// but if you have other wrapper exceptions that you want stripped you can pass them in here. /// </summary> /// <param name="wrapperExceptions">Exception types that you want removed and replaced with their inner exception.</param> public void AddWrapperExceptions(params Type[] wrapperExceptions) { foreach (Type wrapper in wrapperExceptions) { if (!_wrapperExceptions.Contains(wrapper)) { _wrapperExceptions.Add(wrapper); } } } /// <summary> /// Specifies types of wrapper exceptions that Raygun should send rather than stripping out and sending the inner exception. /// This can be used to remove the default wrapper exceptions (TargetInvocationException and HttpUnhandledException). /// </summary> /// <param name="wrapperExceptions">Exception types that should no longer be stripped away.</param> public void RemoveWrapperExceptions(params Type[] wrapperExceptions) { foreach (Type wrapper in wrapperExceptions) { _wrapperExceptions.Remove(wrapper); } } /// <summary> /// Transmits an exception to Raygun.io synchronously, using the version number of the originating assembly. /// </summary> /// <param name="exception">The exception to deliver.</param> public override void Send(Exception exception) { Send(exception, null, (IDictionary)null, null); } /// <summary> /// Transmits an exception to Raygun.io synchronously specifying a list of string tags associated /// with the message for identification. This uses the version number of the originating assembly. /// </summary> /// <param name="exception">The exception to deliver.</param> /// <param name="tags">A list of strings associated with the message.</param> public void Send(Exception exception, IList<string> tags) { Send(exception, tags, (IDictionary)null, null); } /// <summary> /// Transmits an exception to Raygun.io synchronously specifying a list of string tags associated /// with the message for identification, as well as sending a key-value collection of custom data. /// This uses the version number of the originating assembly. /// </summary> /// <param name="exception">The exception to deliver.</param> /// <param name="tags">A list of strings associated with the message.</param> /// <param name="userCustomData">A key-value collection of custom data that will be added to the payload.</param> public void Send(Exception exception, IList<string> tags, IDictionary userCustomData) { Send(exception, tags, userCustomData, null); } /// <summary> /// Transmits an exception to Raygun.io synchronously specifying a list of string tags associated /// with the message for identification, as well as sending a key-value collection of custom data. /// This uses the version number of the originating assembly. /// </summary> /// <param name="exception">The exception to deliver.</param> /// <param name="tags">A list of strings associated with the message.</param> /// <param name="userCustomData">A key-value collection of custom data that will be added to the payload.</param> /// <param name="userInfo">Information about the user including the identity string.</param> public void Send(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfo) { if (CanSend(exception)) { StripAndSend(exception, tags, userCustomData, userInfo, null); FlagAsSent(exception); } } /// <summary> /// Asynchronously transmits a message to Raygun.io. /// </summary> /// <param name="exception">The exception to deliver.</param> public void SendInBackground(Exception exception) { SendInBackground(exception, null, (IDictionary)null, null); } /// <summary> /// Asynchronously transmits an exception to Raygun.io. /// </summary> /// <param name="exception">The exception to deliver.</param> /// <param name="tags">A list of strings associated with the message.</param> public void SendInBackground(Exception exception, IList<string> tags) { SendInBackground(exception, tags, (IDictionary)null, null); } /// <summary> /// Asynchronously transmits an exception to Raygun.io. /// </summary> /// <param name="exception">The exception to deliver.</param> /// <param name="tags">A list of strings associated with the message.</param> /// <param name="userCustomData">A key-value collection of custom data that will be added to the payload.</param> public void SendInBackground(Exception exception, IList<string> tags, IDictionary userCustomData) { SendInBackground(exception, tags, userCustomData, null); } /// <summary> /// Asynchronously transmits an exception to Raygun.io. /// </summary> /// <param name="exception">The exception to deliver.</param> /// <param name="tags">A list of strings associated with the message.</param> /// <param name="userCustomData">A key-value collection of custom data that will be added to the payload.</param> /// <param name="userInfo">Information about the user including the identity string.</param> public void SendInBackground(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfo) { DateTime? currentTime = DateTime.UtcNow; if (CanSend(exception)) { ThreadPool.QueueUserWorkItem(c => { try { StripAndSend(exception, tags, userCustomData, userInfo, currentTime); } catch (Exception) { // This will swallow any unhandled exceptions unless we explicitly want to throw on error. // Otherwise this can bring the whole process down. if (RaygunSettings.Settings.ThrowOnError) { throw; } } }); FlagAsSent(exception); } } /// <summary> /// Asynchronously transmits a message to Raygun.io. /// </summary> /// <param name="raygunMessage">The RaygunMessage to send. This needs its OccurredOn property /// set to a valid DateTime and as much of the Details property as is available.</param> public void SendInBackground(RaygunMessage raygunMessage) { ThreadPool.QueueUserWorkItem(c => Send(raygunMessage)); } protected RaygunMessage BuildMessage(Exception exception, IList<string> tags, IDictionary userCustomData) { return BuildMessage(exception, tags, userCustomData, null, null); } protected RaygunMessage BuildMessage(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfoMessage) { return BuildMessage(exception, tags, userCustomData, userInfoMessage, null); } protected RaygunMessage BuildMessage(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfoMessage, DateTime? currentTime) { var message = RaygunMessageBuilder.New .SetEnvironmentDetails() .SetTimeStamp(currentTime) .SetMachineName(Environment.MachineName) .SetExceptionDetails(exception) .SetClientDetails() .SetVersion(ApplicationVersion) .SetTags(tags) .SetUserCustomData(userCustomData) .SetUser(userInfoMessage ?? UserInfo ?? (!String.IsNullOrEmpty(User) ? new RaygunIdentifierMessage(User) : null)) .Build(); return message; } private void StripAndSend(Exception exception, IList<string> tags, IDictionary userCustomData, RaygunIdentifierMessage userInfo, DateTime? currentTime) { foreach (Exception e in StripWrapperExceptions(exception)) { Send(BuildMessage(e, tags, userCustomData, userInfo, currentTime)); } } protected IEnumerable<Exception> StripWrapperExceptions(Exception exception) { if (exception != null && _wrapperExceptions.Any(wrapperException => exception.GetType() == wrapperException && exception.InnerException != null)) { AggregateException aggregate = exception as AggregateException; if (aggregate != null) { foreach (Exception e in aggregate.InnerExceptions) { foreach (Exception ex in StripWrapperExceptions(e)) { yield return ex; } } } else { foreach (Exception e in StripWrapperExceptions(exception.InnerException)) { yield return e; } } } else { yield return exception; } } /// <summary> /// Posts a RaygunMessage to the Raygun.io api endpoint. /// </summary> /// <param name="raygunMessage">The RaygunMessage to send. This needs its OccurredOn property /// set to a valid DateTime and as much of the Details property as is available.</param> public override void Send(RaygunMessage raygunMessage) { if (ValidateApiKey()) { bool canSend = OnSendingMessage(raygunMessage); if (canSend) { using (var client = CreateWebClient()) { try { var message = SimpleJson.SerializeObject(raygunMessage); client.UploadString(RaygunSettings.Settings.ApiEndpoint, message); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(string.Format("Error Logging Exception to Raygun.io {0}", ex.Message)); if (RaygunSettings.Settings.ThrowOnError) { throw; } } } } } } protected WebClient CreateWebClient() { var client = new WebClient(); client.Headers.Add("X-ApiKey", _apiKey); client.Headers.Add("content-type", "application/json; charset=utf-8"); client.Encoding = System.Text.Encoding.UTF8; if (WebProxy != null) { client.Proxy = WebProxy; } else if (WebRequest.DefaultWebProxy != null) { Uri proxyUri = WebRequest.DefaultWebProxy.GetProxy(new Uri(RaygunSettings.Settings.ApiEndpoint.ToString())); if (proxyUri != null && proxyUri.AbsoluteUri != RaygunSettings.Settings.ApiEndpoint.ToString()) { client.Proxy = new WebProxy(proxyUri, false); if (ProxyCredentials == null) { client.UseDefaultCredentials = true; client.Proxy.Credentials = CredentialCache.DefaultCredentials; } else { client.UseDefaultCredentials = false; client.Proxy.Credentials = ProxyCredentials; } } } return client; } } }
nelsonsar/raygun4net
Mindscape.Raygun4Net4.ClientProfile/RaygunClient.cs
C#
mit
13,094
// Copyright (c) Microsoft Corporation // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "pch.h" #include "ProfileService_winrt.h" #include "Utils_WinRT.h" using namespace pplx; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Platform; using namespace Platform::Collections; using namespace Microsoft::Xbox::Services::System; using namespace xbox::services::social; using namespace xbox::services; NAMESPACE_MICROSOFT_XBOX_SERVICES_SOCIAL_BEGIN ProfileService::ProfileService( _In_ profile_service cppObj ): m_cppObj(std::move(cppObj)) { } IAsyncOperation<XboxUserProfile^>^ ProfileService::GetUserProfileAsync( _In_ String^ xboxUserId ) { auto task = m_cppObj.get_user_profile( STRING_T_FROM_PLATFORM_STRING(xboxUserId) ) .then([](xbox::services::xbox_live_result<xbox_user_profile> cppUserProfile) { THROW_HR_IF_ERR(cppUserProfile.err()); return ref new XboxUserProfile(cppUserProfile.payload()); }); return ASYNC_FROM_TASK(task); } IAsyncOperation<IVectorView<XboxUserProfile^>^>^ ProfileService::GetUserProfilesAsync( _In_ IVectorView<String^>^ xboxUserIds ) { std::vector<string_t> vecXboxUserIds = UtilsWinRT::CovertVectorViewToStdVectorString(xboxUserIds); auto task = m_cppObj.get_user_profiles(vecXboxUserIds) .then([](xbox::services::xbox_live_result<std::vector<xbox_user_profile>> cppUserProfiles) { THROW_HR_IF_ERR(cppUserProfiles.err()); Vector<XboxUserProfile^>^ responseVector = ref new Vector<XboxUserProfile^>(); const auto& result = cppUserProfiles.payload(); for (auto& cppUserProfile : result) { auto userProfile = ref new XboxUserProfile(cppUserProfile); responseVector->Append(userProfile); } return responseVector->GetView(); }); return ASYNC_FROM_TASK(task); } IAsyncOperation<IVectorView<XboxUserProfile^>^>^ ProfileService::GetUserProfilesForSocialGroupAsync( _In_ Platform::String^ socialGroup ) { auto task = m_cppObj.get_user_profiles_for_social_group(STRING_T_FROM_PLATFORM_STRING(socialGroup)) .then([](xbox_live_result<std::vector<xbox_user_profile>> cppUserProfileList) { THROW_IF_ERR(cppUserProfileList); Vector<XboxUserProfile^>^ responseVector = ref new Vector<XboxUserProfile^>(); for (auto& cppUserProfile : cppUserProfileList.payload()) { XboxUserProfile^ userProfile = ref new XboxUserProfile(cppUserProfile); responseVector->Append(userProfile); } return responseVector->GetView(); }); return ASYNC_FROM_TASK(task); } NAMESPACE_MICROSOFT_XBOX_SERVICES_SOCIAL_END
jicailiu/xbox-live-api
Source/Services/Social/WinRT/ProfileService_WinRT.cpp
C++
mit
2,818
// Copyright 2011 Splunk, Inc. // // 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. (function() { var Http = require('../../http'); var utils = require('../../utils'); var root = exports || this; var getHeaders = function(headersString) { var headers = {}; var headerLines = headersString.split("\n"); for(var i = 0; i < headerLines.length; i++) { if (utils.trim(headerLines[i]) !== "") { var headerParts = headerLines[i].split(": "); headers[headerParts[0]] = headerParts[1]; } } return headers; }; root.JQueryHttp = Http.extend({ init: function(isSplunk) { this._super(isSplunk); }, makeRequest: function(url, message, callback) { var that = this; var params = { url: url, type: message.method, headers: message.headers, data: message.body || "", timeout: message.timeout || 0, dataType: "json", success: utils.bind(this, function(data, error, res) { var response = { statusCode: res.status, headers: getHeaders(res.getAllResponseHeaders()) }; var complete_response = this._buildResponse(error, response, data); callback(complete_response); }), error: function(res, data, error) { var response = { statusCode: res.status, headers: getHeaders(res.getAllResponseHeaders()) }; if (data === "abort") { response.statusCode = "abort"; res.responseText = "{}"; } var json = JSON.parse(res.responseText); var complete_response = that._buildResponse(error, response, json); callback(complete_response); } }; return $.ajax(params); }, parseJson: function(json) { // JQuery does this for us return json; } }); })();
Christopheraburns/projecttelemetry
node_modules/splunk-sdk/lib/platform/client/jquery_http.js
JavaScript
mit
2,820
/* * MP3 muxer * Copyright (c) 2003 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "avformat.h" #include "avio_internal.h" #include "id3v1.h" #include "id3v2.h" #include "rawenc.h" #include "libavutil/avstring.h" #include "libavcodec/mpegaudio.h" #include "libavcodec/mpegaudiodata.h" #include "libavcodec/mpegaudiodecheader.h" #include "libavutil/intreadwrite.h" #include "libavutil/opt.h" #include "libavutil/dict.h" #include "libavutil/avassert.h" static int id3v1_set_string(AVFormatContext *s, const char *key, uint8_t *buf, int buf_size) { AVDictionaryEntry *tag; if ((tag = av_dict_get(s->metadata, key, NULL, 0))) av_strlcpy(buf, tag->value, buf_size); return !!tag; } static int id3v1_create_tag(AVFormatContext *s, uint8_t *buf) { AVDictionaryEntry *tag; int i, count = 0; memset(buf, 0, ID3v1_TAG_SIZE); /* fail safe */ buf[0] = 'T'; buf[1] = 'A'; buf[2] = 'G'; /* we knowingly overspecify each tag length by one byte to compensate for the mandatory null byte added by av_strlcpy */ count += id3v1_set_string(s, "TIT2", buf + 3, 30 + 1); //title count += id3v1_set_string(s, "TPE1", buf + 33, 30 + 1); //author|artist count += id3v1_set_string(s, "TALB", buf + 63, 30 + 1); //album count += id3v1_set_string(s, "TDRL", buf + 93, 4 + 1); //date count += id3v1_set_string(s, "comment", buf + 97, 30 + 1); if ((tag = av_dict_get(s->metadata, "TRCK", NULL, 0))) { //track buf[125] = 0; buf[126] = atoi(tag->value); count++; } buf[127] = 0xFF; /* default to unknown genre */ if ((tag = av_dict_get(s->metadata, "TCON", NULL, 0))) { //genre for(i = 0; i <= ID3v1_GENRE_MAX; i++) { if (!av_strcasecmp(tag->value, ff_id3v1_genre_str[i])) { buf[127] = i; count++; break; } } } return count; } #define XING_NUM_BAGS 400 #define XING_TOC_SIZE 100 // maximum size of the xing frame: offset/Xing/flags/frames/size/TOC #define XING_MAX_SIZE (32 + 4 + 4 + 4 + 4 + XING_TOC_SIZE) typedef struct MP3Context { const AVClass *class; ID3v2EncContext id3; int id3v2_version; int write_id3v1; int write_xing; /* xing header */ int64_t xing_offset; int32_t frames; int32_t size; uint32_t want; uint32_t seen; uint32_t pos; uint64_t bag[XING_NUM_BAGS]; int initial_bitrate; int has_variable_bitrate; /* index of the audio stream */ int audio_stream_idx; /* number of attached pictures we still need to write */ int pics_to_write; /* audio packets are queued here until we get all the attached pictures */ AVPacketList *queue, *queue_end; } MP3Context; static const uint8_t xing_offtbl[2][2] = {{32, 17}, {17, 9}}; /* * Write an empty XING header and initialize respective data. */ static int mp3_write_xing(AVFormatContext *s) { MP3Context *mp3 = s->priv_data; AVCodecContext *codec = s->streams[mp3->audio_stream_idx]->codec; int bitrate_idx; int best_bitrate_idx = -1; int best_bitrate_error= INT_MAX; int xing_offset; int32_t header, mask; MPADecodeHeader c; int srate_idx, ver = 0, i, channels; int needed; const char *vendor = (codec->flags & CODEC_FLAG_BITEXACT) ? "Lavf" : LIBAVFORMAT_IDENT; if (!s->pb->seekable || !mp3->write_xing) return 0; for (i = 0; i < FF_ARRAY_ELEMS(avpriv_mpa_freq_tab); i++) { const uint16_t base_freq = avpriv_mpa_freq_tab[i]; if (codec->sample_rate == base_freq) ver = 0x3; // MPEG 1 else if (codec->sample_rate == base_freq / 2) ver = 0x2; // MPEG 2 else if (codec->sample_rate == base_freq / 4) ver = 0x0; // MPEG 2.5 else continue; srate_idx = i; break; } if (i == FF_ARRAY_ELEMS(avpriv_mpa_freq_tab)) { av_log(s, AV_LOG_WARNING, "Unsupported sample rate, not writing Xing header.\n"); return -1; } switch (codec->channels) { case 1: channels = MPA_MONO; break; case 2: channels = MPA_STEREO; break; default: av_log(s, AV_LOG_WARNING, "Unsupported number of channels, " "not writing Xing header.\n"); return -1; } /* dummy MPEG audio header */ header = 0xffU << 24; // sync header |= (0x7 << 5 | ver << 3 | 0x1 << 1 | 0x1) << 16; // sync/audio-version/layer 3/no crc*/ header |= (srate_idx << 2) << 8; header |= channels << 6; for (bitrate_idx=1; bitrate_idx<15; bitrate_idx++) { int error; avpriv_mpegaudio_decode_header(&c, header | (bitrate_idx << (4+8))); error= FFABS(c.bit_rate - codec->bit_rate); if(error < best_bitrate_error){ best_bitrate_error= error; best_bitrate_idx = bitrate_idx; } } av_assert0(best_bitrate_idx >= 0); for (bitrate_idx= best_bitrate_idx;; bitrate_idx++) { if (15 == bitrate_idx) return -1; mask = bitrate_idx << (4+8); header |= mask; avpriv_mpegaudio_decode_header(&c, header); xing_offset=xing_offtbl[c.lsf == 1][c.nb_channels == 1]; needed = 4 // header + xing_offset + 4 // xing tag + 4 // frames/size/toc flags + 4 // frames + 4 // size + XING_TOC_SIZE // toc + 24 ; if (needed <= c.frame_size) break; header &= ~mask; } avio_wb32(s->pb, header); ffio_fill(s->pb, 0, xing_offset); mp3->xing_offset = avio_tell(s->pb); ffio_wfourcc(s->pb, "Xing"); avio_wb32(s->pb, 0x01 | 0x02 | 0x04); // frames / size / TOC mp3->size = c.frame_size; mp3->want=1; mp3->seen=0; mp3->pos=0; avio_wb32(s->pb, 0); // frames avio_wb32(s->pb, 0); // size // toc for (i = 0; i < XING_TOC_SIZE; ++i) avio_w8(s->pb, (uint8_t)(255 * i / XING_TOC_SIZE)); for (i = 0; i < strlen(vendor); ++i) avio_w8(s->pb, vendor[i]); for (; i < 21; ++i) avio_w8(s->pb, 0); avio_wb24(s->pb, FFMAX(codec->delay - 528 - 1, 0)<<12); ffio_fill(s->pb, 0, c.frame_size - needed); return 0; } /* * Add a frame to XING data. * Following lame's "VbrTag.c". */ static void mp3_xing_add_frame(MP3Context *mp3, AVPacket *pkt) { int i; mp3->frames++; mp3->seen++; mp3->size += pkt->size; if (mp3->want == mp3->seen) { mp3->bag[mp3->pos] = mp3->size; if (XING_NUM_BAGS == ++mp3->pos) { /* shrink table to half size by throwing away each second bag. */ for (i = 1; i < XING_NUM_BAGS; i += 2) mp3->bag[i >> 1] = mp3->bag[i]; /* double wanted amount per bag. */ mp3->want *= 2; /* adjust current position to half of table size. */ mp3->pos = XING_NUM_BAGS / 2; } mp3->seen = 0; } } static int mp3_write_audio_packet(AVFormatContext *s, AVPacket *pkt) { MP3Context *mp3 = s->priv_data; if (pkt->data && pkt->size >= 4) { MPADecodeHeader c; int av_unused base; uint32_t head = AV_RB32(pkt->data); if (ff_mpa_check_header(head) < 0) { av_log(s, AV_LOG_WARNING, "Audio packet of size %d (starting with %08X...) " "is invalid, writing it anyway.\n", pkt->size, head); return ff_raw_write_packet(s, pkt); } avpriv_mpegaudio_decode_header(&c, head); if (!mp3->initial_bitrate) mp3->initial_bitrate = c.bit_rate; if ((c.bit_rate == 0) || (mp3->initial_bitrate != c.bit_rate)) mp3->has_variable_bitrate = 1; #ifdef FILTER_VBR_HEADERS /* filter out XING and INFO headers. */ base = 4 + xing_offtbl[c.lsf == 1][c.nb_channels == 1]; if (base + 4 <= pkt->size) { uint32_t v = AV_RB32(pkt->data + base); if (MKBETAG('X','i','n','g') == v || MKBETAG('I','n','f','o') == v) return 0; } /* filter out VBRI headers. */ base = 4 + 32; if (base + 4 <= pkt->size && MKBETAG('V','B','R','I') == AV_RB32(pkt->data + base)) return 0; #endif if (mp3->xing_offset) mp3_xing_add_frame(mp3, pkt); } return ff_raw_write_packet(s, pkt); } static int mp3_queue_flush(AVFormatContext *s) { MP3Context *mp3 = s->priv_data; AVPacketList *pktl; int ret = 0, write = 1; ff_id3v2_finish(&mp3->id3, s->pb, s->metadata_header_padding); mp3_write_xing(s); while ((pktl = mp3->queue)) { if (write && (ret = mp3_write_audio_packet(s, &pktl->pkt)) < 0) write = 0; av_free_packet(&pktl->pkt); mp3->queue = pktl->next; av_freep(&pktl); } mp3->queue_end = NULL; return ret; } static void mp3_update_xing(AVFormatContext *s) { MP3Context *mp3 = s->priv_data; int i; /* replace "Xing" identification string with "Info" for CBR files. */ if (!mp3->has_variable_bitrate) { avio_seek(s->pb, mp3->xing_offset, SEEK_SET); ffio_wfourcc(s->pb, "Info"); } avio_seek(s->pb, mp3->xing_offset + 8, SEEK_SET); avio_wb32(s->pb, mp3->frames); avio_wb32(s->pb, mp3->size); avio_w8(s->pb, 0); // first toc entry has to be zero. for (i = 1; i < XING_TOC_SIZE; ++i) { int j = i * mp3->pos / XING_TOC_SIZE; int seek_point = 256LL * mp3->bag[j] / mp3->size; avio_w8(s->pb, FFMIN(seek_point, 255)); } avio_seek(s->pb, 0, SEEK_END); } static int mp3_write_trailer(struct AVFormatContext *s) { uint8_t buf[ID3v1_TAG_SIZE]; MP3Context *mp3 = s->priv_data; if (mp3->pics_to_write) { av_log(s, AV_LOG_WARNING, "No packets were sent for some of the " "attached pictures.\n"); mp3_queue_flush(s); } /* write the id3v1 tag */ if (mp3->write_id3v1 && id3v1_create_tag(s, buf) > 0) { avio_write(s->pb, buf, ID3v1_TAG_SIZE); } if (mp3->xing_offset) mp3_update_xing(s); return 0; } static int query_codec(enum AVCodecID id, int std_compliance) { const CodecMime *cm= ff_id3v2_mime_tags; while(cm->id != AV_CODEC_ID_NONE) { if(id == cm->id) return MKTAG('A', 'P', 'I', 'C'); cm++; } return -1; } #if CONFIG_MP2_MUXER AVOutputFormat ff_mp2_muxer = { .name = "mp2", .long_name = NULL_IF_CONFIG_SMALL("MP2 (MPEG audio layer 2)"), .mime_type = "audio/x-mpeg", .extensions = "mp2,m2a,mpa", .audio_codec = AV_CODEC_ID_MP2, .video_codec = AV_CODEC_ID_NONE, .write_packet = ff_raw_write_packet, .flags = AVFMT_NOTIMESTAMPS, }; #endif #if CONFIG_MP3_MUXER static const AVOption options[] = { { "id3v2_version", "Select ID3v2 version to write. Currently 3 and 4 are supported.", offsetof(MP3Context, id3v2_version), AV_OPT_TYPE_INT, {.i64 = 4}, 0, 4, AV_OPT_FLAG_ENCODING_PARAM}, { "write_id3v1", "Enable ID3v1 writing. ID3v1 tags are written in UTF-8 which may not be supported by most software.", offsetof(MP3Context, write_id3v1), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { "write_xing", "Write the Xing header containing file duration.", offsetof(MP3Context, write_xing), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_ENCODING_PARAM}, { NULL }, }; static const AVClass mp3_muxer_class = { .class_name = "MP3 muxer", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; static int mp3_write_packet(AVFormatContext *s, AVPacket *pkt) { MP3Context *mp3 = s->priv_data; if (pkt->stream_index == mp3->audio_stream_idx) { if (mp3->pics_to_write) { /* buffer audio packets until we get all the pictures */ AVPacketList *pktl = av_mallocz(sizeof(*pktl)); if (!pktl) return AVERROR(ENOMEM); pktl->pkt = *pkt; pktl->pkt.buf = av_buffer_ref(pkt->buf); if (!pktl->pkt.buf) { av_freep(&pktl); return AVERROR(ENOMEM); } if (mp3->queue_end) mp3->queue_end->next = pktl; else mp3->queue = pktl; mp3->queue_end = pktl; } else return mp3_write_audio_packet(s, pkt); } else { int ret; /* warn only once for each stream */ if (s->streams[pkt->stream_index]->nb_frames == 1) { av_log(s, AV_LOG_WARNING, "Got more than one picture in stream %d," " ignoring.\n", pkt->stream_index); } if (!mp3->pics_to_write || s->streams[pkt->stream_index]->nb_frames >= 1) return 0; if ((ret = ff_id3v2_write_apic(s, &mp3->id3, pkt)) < 0) return ret; mp3->pics_to_write--; /* flush the buffered audio packets */ if (!mp3->pics_to_write && (ret = mp3_queue_flush(s)) < 0) return ret; } return 0; } /** * Write an ID3v2 header at beginning of stream */ static int mp3_write_header(struct AVFormatContext *s) { MP3Context *mp3 = s->priv_data; int ret, i; if (mp3->id3v2_version && mp3->id3v2_version != 3 && mp3->id3v2_version != 4) { av_log(s, AV_LOG_ERROR, "Invalid ID3v2 version requested: %d. Only " "3, 4 or 0 (disabled) are allowed.\n", mp3->id3v2_version); return AVERROR(EINVAL); } /* check the streams -- we want exactly one audio and arbitrary number of * video (attached pictures) */ mp3->audio_stream_idx = -1; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO) { if (mp3->audio_stream_idx >= 0 || st->codec->codec_id != AV_CODEC_ID_MP3) { av_log(s, AV_LOG_ERROR, "Invalid audio stream. Exactly one MP3 " "audio stream is required.\n"); return AVERROR(EINVAL); } mp3->audio_stream_idx = i; } else if (st->codec->codec_type != AVMEDIA_TYPE_VIDEO) { av_log(s, AV_LOG_ERROR, "Only audio streams and pictures are allowed in MP3.\n"); return AVERROR(EINVAL); } } if (mp3->audio_stream_idx < 0) { av_log(s, AV_LOG_ERROR, "No audio stream present.\n"); return AVERROR(EINVAL); } mp3->pics_to_write = s->nb_streams - 1; if (mp3->pics_to_write && !mp3->id3v2_version) { av_log(s, AV_LOG_ERROR, "Attached pictures were requested, but the " "ID3v2 header is disabled.\n"); return AVERROR(EINVAL); } if (mp3->id3v2_version) { ff_id3v2_start(&mp3->id3, s->pb, mp3->id3v2_version, ID3v2_DEFAULT_MAGIC); ret = ff_id3v2_write_metadata(s, &mp3->id3); if (ret < 0) return ret; } if (!mp3->pics_to_write) { if (mp3->id3v2_version) ff_id3v2_finish(&mp3->id3, s->pb, s->metadata_header_padding); mp3_write_xing(s); } return 0; } AVOutputFormat ff_mp3_muxer = { .name = "mp3", .long_name = NULL_IF_CONFIG_SMALL("MP3 (MPEG audio layer 3)"), .mime_type = "audio/x-mpeg", .extensions = "mp3", .priv_data_size = sizeof(MP3Context), .audio_codec = AV_CODEC_ID_MP3, .video_codec = AV_CODEC_ID_PNG, .write_header = mp3_write_header, .write_packet = mp3_write_packet, .write_trailer = mp3_write_trailer, .query_codec = query_codec, .flags = AVFMT_NOTIMESTAMPS, .priv_class = &mp3_muxer_class, }; #endif
retsu0/FFmepg-Android
jni/ffmpeg/libavformat/mp3enc.c
C
mit
16,996
// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include <QDir> #include <QIntValidator> #include <QLocale> #include <QMessageBox> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(1, 65535, this)); ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_OS_MAC /* remove Window tab on Mac */ ui->tabWidget->removeTab(ui->tabWidget->indexOf(ui->tabWindow)); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable apply button when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApplyButton())); /* disable apply button when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApplyButton())); /* setup/change UI elements when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(QValidatedLineEdit *, bool)), this, SLOT(handleProxyIpValid(QValidatedLineEdit *, bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } /* update the display unit, to not use the default ("BTC") */ updateDisplayUnit(); /* warn only when language selection changes by user action (placed here so init via mapper doesn't trigger this) */ connect(ui->lang, SIGNAL(valueChanged()), this, SLOT(showRestartWarning_Lang())); /* disable apply button after settings are loaded as there is nothing to save */ disableApplyButton(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); /* Wallet */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->spendZeroConfChange, OptionsModel::SpendZeroConfChange); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); /* Window */ #ifndef Q_OS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); mapper->addMapping(ui->coinControlFeatures, OptionsModel::CoinControlFeatures); } void OptionsDialog::enableApplyButton() { ui->applyButton->setEnabled(true); } void OptionsDialog::disableApplyButton() { ui->applyButton->setEnabled(false); } void OptionsDialog::enableSaveButtons() { /* prevent enabling of the save buttons when data modified, if there is an invalid proxy address present */ if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_resetButton_clicked() { if(model) { // confirmation dialog QMessageBox::StandardButton btnRetVal = QMessageBox::question(this, tr("Confirm options reset"), tr("Some settings may require a client restart to take effect.") + "<br><br>" + tr("Do you want to proceed?"), QMessageBox::Yes | QMessageBox::Cancel, QMessageBox::Cancel); if(btnRetVal == QMessageBox::Cancel) return; disableApplyButton(); /* disable restart warning messages display */ fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = true; /* reset all options and save the default values (QSettings) */ model->Reset(); mapper->toFirst(); mapper->submit(); /* re-enable restart warning messages display */ fRestartWarningDisplayed_Lang = fRestartWarningDisplayed_Proxy = false; } } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); disableApplyButton(); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Potcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Potcoin."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { /* Update transactionFee with the current unit */ ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } void OptionsDialog::handleProxyIpValid(QValidatedLineEdit *object, bool fState) { // this is used in a check before re-enabling the save buttons fProxyIpValid = fState; if(fProxyIpValid) { enableSaveButtons(); ui->statusLabel->clear(); } else { disableSaveButtons(); object->setValid(fProxyIpValid); ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(event->type() == QEvent::FocusOut) { if(object == ui->proxyIp) { CService addr; /* Check proxyIp for a valid IPv4/IPv6 address and emit the proxyIpValid signal */ emit proxyIpValid(ui->proxyIp, LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)); } } return QDialog::eventFilter(object, event); }
bankonme/Potcoin-1
src/qt/optionsdialog.cpp
C++
mit
9,332
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "init.h" #include "addrman.h" #include "amount.h" #include "chain.h" #include "chainparams.h" #include "checkpoints.h" #include "compat/sanity.h" #include "consensus/validation.h" #include "httpserver.h" #include "httprpc.h" #include "key.h" #include "validation.h" #include "miner.h" #include "netbase.h" #include "net.h" #include "net_processing.h" #include "policy/policy.h" #include "rpc/server.h" #include "rpc/register.h" #include "script/standard.h" #include "script/sigcache.h" #include "scheduler.h" #include "timedata.h" #include "txdb.h" #include "txmempool.h" #include "torcontrol.h" #include "ui_interface.h" #include "util.h" #include "utilmoneystr.h" #include "validationinterface.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include "warnings.h" #include <stdint.h> #include <stdio.h> #include <memory> #ifndef WIN32 #include <signal.h> #endif #include <boost/algorithm/string/classification.hpp> #include <boost/algorithm/string/predicate.hpp> #include <boost/algorithm/string/replace.hpp> #include <boost/algorithm/string/split.hpp> #include <boost/bind.hpp> #include <boost/filesystem.hpp> #include <boost/function.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/thread.hpp> #include <openssl/crypto.h> #if ENABLE_ZMQ #include "zmq/zmqnotificationinterface.h" #endif bool fFeeEstimatesInitialized = false; static const bool DEFAULT_PROXYRANDOMIZE = true; static const bool DEFAULT_REST_ENABLE = false; static const bool DEFAULT_DISABLE_SAFEMODE = false; static const bool DEFAULT_STOPAFTERBLOCKIMPORT = false; std::unique_ptr<CConnman> g_connman; std::unique_ptr<PeerLogicValidation> peerLogic; #if ENABLE_ZMQ static CZMQNotificationInterface* pzmqNotificationInterface = NULL; #endif #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files don't count towards the fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif /** Used to pass flags to the Bind() function */ enum BindFlags { BF_NONE = 0, BF_EXPLICIT = (1U << 0), BF_REPORT_ERROR = (1U << 1), BF_WHITELIST = (1U << 2), }; static const char* FEE_ESTIMATES_FILENAME="fee_estimates.dat"; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets fRequestShutdown, which triggers // the DetectShutdownThread(), which interrupts the main thread group. // DetectShutdownThread() then exits, which causes AppInit() to // continue (it .joins the shutdown thread). // Shutdown() is then // called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Shutdown for Qt is very similar, only it uses a QTimer to detect // fRequestShutdown getting set, and then does the normal Qt // shutdown thing. // std::atomic<bool> fRequestShutdown(false); std::atomic<bool> fDumpMempoolLater(false); void StartShutdown() { fRequestShutdown = true; } bool ShutdownRequested() { return fRequestShutdown; } /** * This is a minimally invasive approach to shutdown on LevelDB read errors from the * chainstate, while keeping user interface out of the common library, which is shared * between bitcoind, and bitcoin-qt and non-server tools. */ class CCoinsViewErrorCatcher : public CCoinsViewBacked { public: CCoinsViewErrorCatcher(CCoinsView* view) : CCoinsViewBacked(view) {} bool GetCoins(const uint256 &txid, CCoins &coins) const { try { return CCoinsViewBacked::GetCoins(txid, coins); } catch(const std::runtime_error& e) { uiInterface.ThreadSafeMessageBox(_("Error reading from database, shutting down."), "", CClientUIInterface::MSG_ERROR); LogPrintf("Error reading from database: %s\n", e.what()); // Starting the shutdown sequence and returning false to the caller would be // interpreted as 'entry not found' (as opposed to unable to read data), and // could lead to invalid interpretation. Just exit immediately, as we can't // continue anyway, and all writes should be atomic. abort(); } } // Writes do not need similar protection, as failure to write is handled by the caller. }; static CCoinsViewDB *pcoinsdbview = NULL; static CCoinsViewErrorCatcher *pcoinscatcher = NULL; static std::unique_ptr<ECCVerifyHandle> globalVerifyHandle; void Interrupt(boost::thread_group& threadGroup) { InterruptHTTPServer(); InterruptHTTPRPC(); InterruptRPC(); InterruptREST(); InterruptTorControl(); if (g_connman) g_connman->Interrupt(); threadGroup.interrupt_all(); } void Shutdown() { LogPrintf("%s: In progress...\n", __func__); static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; /// Note: Shutdown() must be able to handle cases in which initialization failed part of the way, /// for example if the data directory was found to be locked. /// Be sure that anything that writes files or flushes caches only does this if the respective /// module was initialized. RenameThread("bitcoin-shutoff"); mempool.AddTransactionsUpdated(1); StopHTTPRPC(); StopREST(); StopRPC(); StopHTTPServer(); #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->Flush(false); #endif MapPort(false); UnregisterValidationInterface(peerLogic.get()); peerLogic.reset(); g_connman.reset(); StopTorControl(); UnregisterNodeSignals(GetNodeSignals()); if (fDumpMempoolLater) DumpMempool(); if (fFeeEstimatesInitialized) { boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_fileout(fopen(est_path.string().c_str(), "wb"), SER_DISK, CLIENT_VERSION); if (!est_fileout.IsNull()) mempool.WriteFeeEstimates(est_fileout); else LogPrintf("%s: Failed to write fee estimates to %s\n", __func__, est_path.string()); fFeeEstimatesInitialized = false; } { LOCK(cs_main); if (pcoinsTip != NULL) { FlushStateToDisk(); } delete pcoinsTip; pcoinsTip = NULL; delete pcoinscatcher; pcoinscatcher = NULL; delete pcoinsdbview; pcoinsdbview = NULL; delete pblocktree; pblocktree = NULL; } #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->Flush(true); #endif #if ENABLE_ZMQ if (pzmqNotificationInterface) { UnregisterValidationInterface(pzmqNotificationInterface); delete pzmqNotificationInterface; pzmqNotificationInterface = NULL; } #endif #ifndef WIN32 try { boost::filesystem::remove(GetPidFile()); } catch (const boost::filesystem::filesystem_error& e) { LogPrintf("%s: Unable to remove pidfile: %s\n", __func__, e.what()); } #endif UnregisterAllValidationInterfaces(); #ifdef ENABLE_WALLET delete pwalletMain; pwalletMain = NULL; #endif globalVerifyHandle.reset(); ECC_Stop(); LogPrintf("%s: done\n", __func__); } /** * Signal handlers are very limited in what they are allowed to do, so: */ void HandleSIGTERM(int) { fRequestShutdown = true; } void HandleSIGHUP(int) { fReopenDebugLog = true; } bool static Bind(CConnman& connman, const CService &addr, unsigned int flags) { if (!(flags & BF_EXPLICIT) && IsLimited(addr)) return false; std::string strError; if (!connman.BindListenPort(addr, strError, (flags & BF_WHITELIST) != 0)) { if (flags & BF_REPORT_ERROR) return InitError(strError); return false; } return true; } void OnRPCStarted() { uiInterface.NotifyBlockTip.connect(&RPCNotifyBlockChange); } void OnRPCStopped() { uiInterface.NotifyBlockTip.disconnect(&RPCNotifyBlockChange); RPCNotifyBlockChange(false, nullptr); cvBlockChange.notify_all(); LogPrint("rpc", "RPC stopped.\n"); } void OnRPCPreCommand(const CRPCCommand& cmd) { // Observe safe mode std::string strWarning = GetWarnings("rpc"); if (strWarning != "" && !GetBoolArg("-disablesafemode", DEFAULT_DISABLE_SAFEMODE) && !cmd.okSafeMode) throw JSONRPCError(RPC_FORBIDDEN_BY_SAFE_MODE, std::string("Safe mode: ") + strWarning); } std::string HelpMessage(HelpMessageMode mode) { const bool showDebug = GetBoolArg("-help-debug", false); // When adding new options to the categories, please keep and ensure alphabetical ordering. // Do not translate _(...) -help-debug options, Many technical terms, and only a very small audience, so is unnecessary stress to translators. std::string strUsage = HelpMessageGroup(_("Options:")); strUsage += HelpMessageOpt("-?", _("Print this help message and exit")); strUsage += HelpMessageOpt("-version", _("Print version and exit")); strUsage += HelpMessageOpt("-alertnotify=<cmd>", _("Execute command when a relevant alert is received or we see a really long fork (%s in cmd is replaced by message)")); strUsage += HelpMessageOpt("-blocknotify=<cmd>", _("Execute command when the best block changes (%s in cmd is replaced by block hash)")); if (showDebug) strUsage += HelpMessageOpt("-blocksonly", strprintf(_("Whether to operate in a blocks only mode (default: %u)"), DEFAULT_BLOCKSONLY)); strUsage +=HelpMessageOpt("-assumevalid=<hex>", strprintf(_("If this block is in the chain assume that it and its ancestors are valid and potentially skip their script verification (0 to verify all, default: %s, testnet: %s)"), Params(CBaseChainParams::MAIN).GetConsensus().defaultAssumeValid.GetHex(), Params(CBaseChainParams::TESTNET).GetConsensus().defaultAssumeValid.GetHex())); strUsage += HelpMessageOpt("-conf=<file>", strprintf(_("Specify configuration file (default: %s)"), BITCOIN_CONF_FILENAME)); if (mode == HMM_BITCOIND) { #if HAVE_DECL_DAEMON strUsage += HelpMessageOpt("-daemon", _("Run in the background as a daemon and accept commands")); #endif } strUsage += HelpMessageOpt("-datadir=<dir>", _("Specify data directory")); strUsage += HelpMessageOpt("-dbcache=<n>", strprintf(_("Set database cache size in megabytes (%d to %d, default: %d)"), nMinDbCache, nMaxDbCache, nDefaultDbCache)); if (showDebug) strUsage += HelpMessageOpt("-feefilter", strprintf("Tell other nodes to filter invs to us by our mempool min fee (default: %u)", DEFAULT_FEEFILTER)); strUsage += HelpMessageOpt("-loadblock=<file>", _("Imports blocks from external blk000??.dat file on startup")); strUsage += HelpMessageOpt("-maxorphantx=<n>", strprintf(_("Keep at most <n> unconnectable transactions in memory (default: %u)"), DEFAULT_MAX_ORPHAN_TRANSACTIONS)); strUsage += HelpMessageOpt("-maxmempool=<n>", strprintf(_("Keep the transaction memory pool below <n> megabytes (default: %u)"), DEFAULT_MAX_MEMPOOL_SIZE)); strUsage += HelpMessageOpt("-mempoolexpiry=<n>", strprintf(_("Do not keep transactions in the mempool longer than <n> hours (default: %u)"), DEFAULT_MEMPOOL_EXPIRY)); strUsage += HelpMessageOpt("-blockreconstructionextratxn=<n>", strprintf(_("Extra transactions to keep in memory for compact block reconstructions (default: %u)"), DEFAULT_BLOCK_RECONSTRUCTION_EXTRA_TXN)); strUsage += HelpMessageOpt("-par=<n>", strprintf(_("Set the number of script verification threads (%u to %d, 0 = auto, <0 = leave that many cores free, default: %d)"), -GetNumCores(), MAX_SCRIPTCHECK_THREADS, DEFAULT_SCRIPTCHECK_THREADS)); #ifndef WIN32 strUsage += HelpMessageOpt("-pid=<file>", strprintf(_("Specify pid file (default: %s)"), BITCOIN_PID_FILENAME)); #endif strUsage += HelpMessageOpt("-prune=<n>", strprintf(_("Reduce storage requirements by enabling pruning (deleting) of old blocks. This allows the pruneblockchain RPC to be called to delete specific blocks, and enables automatic pruning of old blocks if a target size in MiB is provided. This mode is incompatible with -txindex and -rescan. " "Warning: Reverting this setting requires re-downloading the entire blockchain. " "(default: 0 = disable pruning blocks, 1 = allow manual pruning via RPC, >%u = automatically prune block files to stay under the specified target size in MiB)"), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024)); strUsage += HelpMessageOpt("-reindex-chainstate", _("Rebuild chain state from the currently indexed blocks")); strUsage += HelpMessageOpt("-reindex", _("Rebuild chain state and block index from the blk*.dat files on disk")); #ifndef WIN32 strUsage += HelpMessageOpt("-sysperms", _("Create new files with system default permissions, instead of umask 077 (only effective with disabled wallet functionality)")); #endif strUsage += HelpMessageOpt("-txindex", strprintf(_("Maintain a full transaction index, used by the getrawtransaction rpc call (default: %u)"), DEFAULT_TXINDEX)); strUsage += HelpMessageGroup(_("Connection options:")); strUsage += HelpMessageOpt("-addnode=<ip>", _("Add a node to connect to and attempt to keep the connection open")); strUsage += HelpMessageOpt("-banscore=<n>", strprintf(_("Threshold for disconnecting misbehaving peers (default: %u)"), DEFAULT_BANSCORE_THRESHOLD)); strUsage += HelpMessageOpt("-bantime=<n>", strprintf(_("Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), DEFAULT_MISBEHAVING_BANTIME)); strUsage += HelpMessageOpt("-bind=<addr>", _("Bind to given address and always listen on it. Use [host]:port notation for IPv6")); strUsage += HelpMessageOpt("-connect=<ip>", _("Connect only to the specified node(s); -noconnect or -connect=0 alone to disable automatic connections")); strUsage += HelpMessageOpt("-discover", _("Discover own IP addresses (default: 1 when listening and no -externalip or -proxy)")); strUsage += HelpMessageOpt("-dns", _("Allow DNS lookups for -addnode, -seednode and -connect") + " " + strprintf(_("(default: %u)"), DEFAULT_NAME_LOOKUP)); strUsage += HelpMessageOpt("-dnsseed", _("Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect/-noconnect)")); strUsage += HelpMessageOpt("-externalip=<ip>", _("Specify your own public address")); strUsage += HelpMessageOpt("-forcednsseed", strprintf(_("Always query for peer addresses via DNS lookup (default: %u)"), DEFAULT_FORCEDNSSEED)); strUsage += HelpMessageOpt("-listen", _("Accept connections from outside (default: 1 if no -proxy or -connect/-noconnect)")); strUsage += HelpMessageOpt("-listenonion", strprintf(_("Automatically create Tor hidden service (default: %d)"), DEFAULT_LISTEN_ONION)); strUsage += HelpMessageOpt("-maxconnections=<n>", strprintf(_("Maintain at most <n> connections to peers (default: %u)"), DEFAULT_MAX_PEER_CONNECTIONS)); strUsage += HelpMessageOpt("-maxreceivebuffer=<n>", strprintf(_("Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXRECEIVEBUFFER)); strUsage += HelpMessageOpt("-maxsendbuffer=<n>", strprintf(_("Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), DEFAULT_MAXSENDBUFFER)); strUsage += HelpMessageOpt("-maxtimeadjustment", strprintf(_("Maximum allowed median peer time offset adjustment. Local perspective of time may be influenced by peers forward or backward by this amount. (default: %u seconds)"), DEFAULT_MAX_TIME_ADJUSTMENT)); strUsage += HelpMessageOpt("-onion=<ip:port>", strprintf(_("Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: %s)"), "-proxy")); strUsage += HelpMessageOpt("-onlynet=<net>", _("Only connect to nodes in network <net> (ipv4, ipv6 or onion)")); strUsage += HelpMessageOpt("-permitbaremultisig", strprintf(_("Relay non-P2SH multisig (default: %u)"), DEFAULT_PERMIT_BAREMULTISIG)); strUsage += HelpMessageOpt("-peerbloomfilters", strprintf(_("Support filtering of blocks and transaction with bloom filters (default: %u)"), DEFAULT_PEERBLOOMFILTERS)); strUsage += HelpMessageOpt("-port=<port>", strprintf(_("Listen for connections on <port> (default: %u or testnet: %u)"), Params(CBaseChainParams::MAIN).GetDefaultPort(), Params(CBaseChainParams::TESTNET).GetDefaultPort())); strUsage += HelpMessageOpt("-proxy=<ip:port>", _("Connect through SOCKS5 proxy")); strUsage += HelpMessageOpt("-proxyrandomize", strprintf(_("Randomize credentials for every proxy connection. This enables Tor stream isolation (default: %u)"), DEFAULT_PROXYRANDOMIZE)); strUsage += HelpMessageOpt("-rpcserialversion", strprintf(_("Sets the serialization of raw transaction or block hex returned in non-verbose mode, non-segwit(0) or segwit(1) (default: %d)"), DEFAULT_RPC_SERIALIZE_VERSION)); strUsage += HelpMessageOpt("-seednode=<ip>", _("Connect to a node to retrieve peer addresses, and disconnect")); strUsage += HelpMessageOpt("-timeout=<n>", strprintf(_("Specify connection timeout in milliseconds (minimum: 1, default: %d)"), DEFAULT_CONNECT_TIMEOUT)); strUsage += HelpMessageOpt("-torcontrol=<ip>:<port>", strprintf(_("Tor control port to use if onion listening enabled (default: %s)"), DEFAULT_TOR_CONTROL)); strUsage += HelpMessageOpt("-torpassword=<pass>", _("Tor control port password (default: empty)")); #ifdef USE_UPNP #if USE_UPNP strUsage += HelpMessageOpt("-upnp", _("Use UPnP to map the listening port (default: 1 when listening and no -proxy)")); #else strUsage += HelpMessageOpt("-upnp", strprintf(_("Use UPnP to map the listening port (default: %u)"), 0)); #endif #endif strUsage += HelpMessageOpt("-whitebind=<addr>", _("Bind to given address and whitelist peers connecting to it. Use [host]:port notation for IPv6")); strUsage += HelpMessageOpt("-whitelist=<IP address or network>", _("Whitelist peers connecting from the given IP address (e.g. 1.2.3.4) or CIDR notated network (e.g. 1.2.3.0/24). Can be specified multiple times.") + " " + _("Whitelisted peers cannot be DoS banned and their transactions are always relayed, even if they are already in the mempool, useful e.g. for a gateway")); strUsage += HelpMessageOpt("-whitelistrelay", strprintf(_("Accept relayed transactions received from whitelisted peers even when not relaying transactions (default: %d)"), DEFAULT_WHITELISTRELAY)); strUsage += HelpMessageOpt("-whitelistforcerelay", strprintf(_("Force relay of transactions from whitelisted peers even if they violate local relay policy (default: %d)"), DEFAULT_WHITELISTFORCERELAY)); strUsage += HelpMessageOpt("-maxuploadtarget=<n>", strprintf(_("Tries to keep outbound traffic under the given target (in MiB per 24h), 0 = no limit (default: %d)"), DEFAULT_MAX_UPLOAD_TARGET)); #ifdef ENABLE_WALLET strUsage += CWallet::GetWalletHelpString(showDebug); #endif #if ENABLE_ZMQ strUsage += HelpMessageGroup(_("ZeroMQ notification options:")); strUsage += HelpMessageOpt("-zmqpubhashblock=<address>", _("Enable publish hash block in <address>")); strUsage += HelpMessageOpt("-zmqpubhashtx=<address>", _("Enable publish hash transaction in <address>")); strUsage += HelpMessageOpt("-zmqpubrawblock=<address>", _("Enable publish raw block in <address>")); strUsage += HelpMessageOpt("-zmqpubrawtx=<address>", _("Enable publish raw transaction in <address>")); #endif strUsage += HelpMessageGroup(_("Debugging/Testing options:")); strUsage += HelpMessageOpt("-uacomment=<cmt>", _("Append comment to the user agent string")); if (showDebug) { strUsage += HelpMessageOpt("-checkblocks=<n>", strprintf(_("How many blocks to check at startup (default: %u, 0 = all)"), DEFAULT_CHECKBLOCKS)); strUsage += HelpMessageOpt("-checklevel=<n>", strprintf(_("How thorough the block verification of -checkblocks is (0-4, default: %u)"), DEFAULT_CHECKLEVEL)); strUsage += HelpMessageOpt("-checkblockindex", strprintf("Do a full consistency check for mapBlockIndex, setBlockIndexCandidates, chainActive and mapBlocksUnlinked occasionally. Also sets -checkmempool (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks())); strUsage += HelpMessageOpt("-checkmempool=<n>", strprintf("Run checks every <n> transactions (default: %u)", Params(CBaseChainParams::MAIN).DefaultConsistencyChecks())); strUsage += HelpMessageOpt("-checkpoints", strprintf("Disable expensive verification for known chain history (default: %u)", DEFAULT_CHECKPOINTS_ENABLED)); strUsage += HelpMessageOpt("-disablesafemode", strprintf("Disable safemode, override a real safe mode event (default: %u)", DEFAULT_DISABLE_SAFEMODE)); strUsage += HelpMessageOpt("-testsafemode", strprintf("Force safe mode (default: %u)", DEFAULT_TESTSAFEMODE)); strUsage += HelpMessageOpt("-dropmessagestest=<n>", "Randomly drop 1 of every <n> network messages"); strUsage += HelpMessageOpt("-fuzzmessagestest=<n>", "Randomly fuzz 1 of every <n> network messages"); strUsage += HelpMessageOpt("-stopafterblockimport", strprintf("Stop running after importing blocks from disk (default: %u)", DEFAULT_STOPAFTERBLOCKIMPORT)); strUsage += HelpMessageOpt("-limitancestorcount=<n>", strprintf("Do not accept transactions if number of in-mempool ancestors is <n> or more (default: %u)", DEFAULT_ANCESTOR_LIMIT)); strUsage += HelpMessageOpt("-limitancestorsize=<n>", strprintf("Do not accept transactions whose size with all in-mempool ancestors exceeds <n> kilobytes (default: %u)", DEFAULT_ANCESTOR_SIZE_LIMIT)); strUsage += HelpMessageOpt("-limitdescendantcount=<n>", strprintf("Do not accept transactions if any ancestor would have <n> or more in-mempool descendants (default: %u)", DEFAULT_DESCENDANT_LIMIT)); strUsage += HelpMessageOpt("-limitdescendantsize=<n>", strprintf("Do not accept transactions if any ancestor would have more than <n> kilobytes of in-mempool descendants (default: %u).", DEFAULT_DESCENDANT_SIZE_LIMIT)); strUsage += HelpMessageOpt("-bip9params=deployment:start:end", "Use given start/end times for specified BIP9 deployment (regtest-only)"); } std::string debugCategories = "addrman, alert, bench, cmpctblock, coindb, db, http, leveldb, libevent, lock, mempool, mempoolrej, net, proxy, prune, rand, reindex, rpc, selectcoins, tor, zmq"; // Don't translate these and qt below if (mode == HMM_BITCOIN_QT) debugCategories += ", qt"; strUsage += HelpMessageOpt("-debug=<category>", strprintf(_("Output debugging information (default: %u, supplying <category> is optional)"), 0) + ". " + _("If <category> is not supplied or if <category> = 1, output all debugging information.") + _("<category> can be:") + " " + debugCategories + "."); if (showDebug) strUsage += HelpMessageOpt("-nodebug", "Turn off debugging messages, same as -debug=0"); strUsage += HelpMessageOpt("-help-debug", _("Show all debugging options (usage: --help -help-debug)")); strUsage += HelpMessageOpt("-logips", strprintf(_("Include IP addresses in debug output (default: %u)"), DEFAULT_LOGIPS)); strUsage += HelpMessageOpt("-logtimestamps", strprintf(_("Prepend debug output with timestamp (default: %u)"), DEFAULT_LOGTIMESTAMPS)); if (showDebug) { strUsage += HelpMessageOpt("-logtimemicros", strprintf("Add microsecond precision to debug timestamps (default: %u)", DEFAULT_LOGTIMEMICROS)); strUsage += HelpMessageOpt("-mocktime=<n>", "Replace actual time with <n> seconds since epoch (default: 0)"); strUsage += HelpMessageOpt("-maxsigcachesize=<n>", strprintf("Limit size of signature cache to <n> MiB (default: %u)", DEFAULT_MAX_SIG_CACHE_SIZE)); strUsage += HelpMessageOpt("-maxtipage=<n>", strprintf("Maximum tip age in seconds to consider node in initial block download (default: %u)", DEFAULT_MAX_TIP_AGE)); } strUsage += HelpMessageOpt("-minrelaytxfee=<amt>", strprintf(_("Fees (in %s/kB) smaller than this are considered zero fee for relaying, mining and transaction creation (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_MIN_RELAY_TX_FEE))); strUsage += HelpMessageOpt("-maxtxfee=<amt>", strprintf(_("Maximum total fees (in %s) to use in a single wallet transaction or raw transaction; setting this too low may abort large transactions (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_TRANSACTION_MAXFEE))); strUsage += HelpMessageOpt("-printtoconsole", _("Send trace/debug info to console instead of debug.log file")); if (showDebug) { strUsage += HelpMessageOpt("-printpriority", strprintf("Log transaction fee per kB when mining blocks (default: %u)", DEFAULT_PRINTPRIORITY)); } strUsage += HelpMessageOpt("-shrinkdebugfile", _("Shrink debug.log file on client startup (default: 1 when no -debug)")); AppendParamsHelpMessages(strUsage, showDebug); strUsage += HelpMessageGroup(_("Node relay options:")); if (showDebug) { strUsage += HelpMessageOpt("-acceptnonstdtxn", strprintf("Relay and mine \"non-standard\" transactions (%sdefault: %u)", "testnet/regtest only; ", !Params(CBaseChainParams::TESTNET).RequireStandard())); strUsage += HelpMessageOpt("-incrementalrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to define cost of relay, used for mempool limiting and BIP 125 replacement. (default: %s)", CURRENCY_UNIT, FormatMoney(DEFAULT_INCREMENTAL_RELAY_FEE))); strUsage += HelpMessageOpt("-dustrelayfee=<amt>", strprintf("Fee rate (in %s/kB) used to defined dust, the value of an output such that it will cost about 1/3 of its value in fees at this fee rate to spend it. (default: %s)", CURRENCY_UNIT, FormatMoney(DUST_RELAY_TX_FEE))); } strUsage += HelpMessageOpt("-bytespersigop", strprintf(_("Equivalent bytes per sigop in transactions for relay and mining (default: %u)"), DEFAULT_BYTES_PER_SIGOP)); strUsage += HelpMessageOpt("-datacarrier", strprintf(_("Relay and mine data carrier transactions (default: %u)"), DEFAULT_ACCEPT_DATACARRIER)); strUsage += HelpMessageOpt("-datacarriersize", strprintf(_("Maximum size of data in data carrier transactions we relay and mine (default: %u)"), MAX_OP_RETURN_RELAY)); strUsage += HelpMessageOpt("-mempoolreplacement", strprintf(_("Enable transaction replacement in the memory pool (default: %u)"), DEFAULT_ENABLE_REPLACEMENT)); strUsage += HelpMessageGroup(_("Block creation options:")); strUsage += HelpMessageOpt("-blockmaxweight=<n>", strprintf(_("Set maximum BIP141 block weight (default: %d)"), DEFAULT_BLOCK_MAX_WEIGHT)); strUsage += HelpMessageOpt("-blockmaxsize=<n>", strprintf(_("Set maximum block size in bytes (default: %d)"), DEFAULT_BLOCK_MAX_SIZE)); strUsage += HelpMessageOpt("-blockmintxfee=<amt>", strprintf(_("Set lowest fee rate (in %s/kB) for transactions to be included in block creation. (default: %s)"), CURRENCY_UNIT, FormatMoney(DEFAULT_BLOCK_MIN_TX_FEE))); if (showDebug) strUsage += HelpMessageOpt("-blockversion=<n>", "Override block version to test forking scenarios"); strUsage += HelpMessageGroup(_("RPC server options:")); strUsage += HelpMessageOpt("-server", _("Accept command line and JSON-RPC commands")); strUsage += HelpMessageOpt("-rest", strprintf(_("Accept public REST requests (default: %u)"), DEFAULT_REST_ENABLE)); strUsage += HelpMessageOpt("-rpcbind=<addr>[:port]", _("Bind to given address to listen for JSON-RPC connections. This option is ignored unless -rpcallowip is also passed. Port is optional and overrides -rpcport. Use [host]:port notation for IPv6. This option can be specified multiple times (default: 127.0.0.1 and ::1 i.e., localhost, or if -rpcallowip has been specified, 0.0.0.0 and :: i.e., all addresses)")); strUsage += HelpMessageOpt("-rpccookiefile=<loc>", _("Location of the auth cookie (default: data dir)")); strUsage += HelpMessageOpt("-rpcuser=<user>", _("Username for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcpassword=<pw>", _("Password for JSON-RPC connections")); strUsage += HelpMessageOpt("-rpcauth=<userpw>", _("Username and hashed password for JSON-RPC connections. The field <userpw> comes in the format: <USERNAME>:<SALT>$<HASH>. A canonical python script is included in share/rpcuser. The client then connects normally using the rpcuser=<USERNAME>/rpcpassword=<PASSWORD> pair of arguments. This option can be specified multiple times")); strUsage += HelpMessageOpt("-rpcport=<port>", strprintf(_("Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), BaseParams(CBaseChainParams::MAIN).RPCPort(), BaseParams(CBaseChainParams::TESTNET).RPCPort())); strUsage += HelpMessageOpt("-rpcallowip=<ip>", _("Allow JSON-RPC connections from specified source. Valid for <ip> are a single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times")); strUsage += HelpMessageOpt("-rpcthreads=<n>", strprintf(_("Set the number of threads to service RPC calls (default: %d)"), DEFAULT_HTTP_THREADS)); if (showDebug) { strUsage += HelpMessageOpt("-rpcworkqueue=<n>", strprintf("Set the depth of the work queue to service RPC calls (default: %d)", DEFAULT_HTTP_WORKQUEUE)); strUsage += HelpMessageOpt("-rpcservertimeout=<n>", strprintf("Timeout during HTTP requests (default: %d)", DEFAULT_HTTP_SERVER_TIMEOUT)); } return strUsage; } std::string LicenseInfo() { const std::string URL_SOURCE_CODE = "<https://github.com/bitcoin/bitcoin>"; const std::string URL_WEBSITE = "<https://bitcoincore.org>"; return CopyrightHolders(strprintf(_("Copyright (C) %i-%i"), 2009, COPYRIGHT_YEAR) + " ") + "\n" + "\n" + strprintf(_("Please contribute if you find %s useful. " "Visit %s for further information about the software."), PACKAGE_NAME, URL_WEBSITE) + "\n" + strprintf(_("The source code is available from %s."), URL_SOURCE_CODE) + "\n" + "\n" + _("This is experimental software.") + "\n" + strprintf(_("Distributed under the MIT software license, see the accompanying file %s or %s"), "COPYING", "<https://opensource.org/licenses/MIT>") + "\n" + "\n" + strprintf(_("This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit %s and cryptographic software written by Eric Young and UPnP software written by Thomas Bernard."), "<https://www.openssl.org>") + "\n"; } static void BlockNotifyCallback(bool initialSync, const CBlockIndex *pBlockIndex) { if (initialSync || !pBlockIndex) return; std::string strCmd = GetArg("-blocknotify", ""); boost::replace_all(strCmd, "%s", pBlockIndex->GetBlockHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } static bool fHaveGenesis = false; static boost::mutex cs_GenesisWait; static CConditionVariable condvar_GenesisWait; static void BlockNotifyGenesisWait(bool, const CBlockIndex *pBlockIndex) { if (pBlockIndex != NULL) { { boost::unique_lock<boost::mutex> lock_GenesisWait(cs_GenesisWait); fHaveGenesis = true; } condvar_GenesisWait.notify_all(); } } struct CImportingNow { CImportingNow() { assert(fImporting == false); fImporting = true; } ~CImportingNow() { assert(fImporting == true); fImporting = false; } }; // If we're using -prune with -reindex, then delete block files that will be ignored by the // reindex. Since reindexing works by starting at block file 0 and looping until a blockfile // is missing, do the same here to delete any later block files after a gap. Also delete all // rev files since they'll be rewritten by the reindex anyway. This ensures that vinfoBlockFile // is in sync with what's actually on disk by the time we start downloading, so that pruning // works correctly. void CleanupBlockRevFiles() { std::map<std::string, boost::filesystem::path> mapBlockFiles; // Glob all blk?????.dat and rev?????.dat files from the blocks directory. // Remove the rev files immediately and insert the blk file paths into an // ordered map keyed by block file index. LogPrintf("Removing unusable blk?????.dat and rev?????.dat files for -reindex with -prune\n"); boost::filesystem::path blocksdir = GetDataDir() / "blocks"; for (boost::filesystem::directory_iterator it(blocksdir); it != boost::filesystem::directory_iterator(); it++) { if (is_regular_file(*it) && it->path().filename().string().length() == 12 && it->path().filename().string().substr(8,4) == ".dat") { if (it->path().filename().string().substr(0,3) == "blk") mapBlockFiles[it->path().filename().string().substr(3,5)] = it->path(); else if (it->path().filename().string().substr(0,3) == "rev") remove(it->path()); } } // Remove all block files that aren't part of a contiguous set starting at // zero by walking the ordered map (keys are block file indices) by // keeping a separate counter. Once we hit a gap (or if 0 doesn't exist) // start removing block files. int nContigCounter = 0; BOOST_FOREACH(const PAIRTYPE(std::string, boost::filesystem::path)& item, mapBlockFiles) { if (atoi(item.first) == nContigCounter) { nContigCounter++; continue; } remove(item.second); } } void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) { const CChainParams& chainparams = Params(); RenameThread("bitcoin-loadblk"); { CImportingNow imp; // -reindex if (fReindex) { int nFile = 0; while (true) { CDiskBlockPos pos(nFile, 0); if (!boost::filesystem::exists(GetBlockPosFilename(pos, "blk"))) break; // No block files left to reindex FILE *file = OpenBlockFile(pos, true); if (!file) break; // This error is logged in OpenBlockFile LogPrintf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); LoadExternalBlockFile(chainparams, file, &pos); nFile++; } pblocktree->WriteReindexing(false); fReindex = false; LogPrintf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): InitBlockIndex(chainparams); } // hardcoded $DATADIR/bootstrap.dat boost::filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; if (boost::filesystem::exists(pathBootstrap)) { FILE *file = fopen(pathBootstrap.string().c_str(), "rb"); if (file) { boost::filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; LogPrintf("Importing bootstrap.dat...\n"); LoadExternalBlockFile(chainparams, file); RenameOver(pathBootstrap, pathBootstrapOld); } else { LogPrintf("Warning: Could not open bootstrap file %s\n", pathBootstrap.string()); } } // -loadblock= BOOST_FOREACH(const boost::filesystem::path& path, vImportFiles) { FILE *file = fopen(path.string().c_str(), "rb"); if (file) { LogPrintf("Importing blocks file %s...\n", path.string()); LoadExternalBlockFile(chainparams, file); } else { LogPrintf("Warning: Could not open blocks file %s\n", path.string()); } } // scan for better chains in the block chain database, that are not yet connected in the active best chain CValidationState state; if (!ActivateBestChain(state, chainparams)) { LogPrintf("Failed to connect best block"); StartShutdown(); } if (GetBoolArg("-stopafterblockimport", DEFAULT_STOPAFTERBLOCKIMPORT)) { LogPrintf("Stopping after block import\n"); StartShutdown(); } } // End scope of CImportingNow LoadMempool(); fDumpMempoolLater = !fRequestShutdown; } /** Sanity checks * Ensure that Bitcoin is running in a usable environment with all * necessary library support. */ bool InitSanityCheck(void) { if(!ECC_InitSanityCheck()) { InitError("Elliptic curve cryptography sanity check failure. Aborting."); return false; } if (!glibc_sanity_test() || !glibcxx_sanity_test()) return false; if (!Random_SanityCheck()) { InitError("OS cryptographic RNG sanity check failure. Aborting."); return false; } return true; } bool AppInitServers(boost::thread_group& threadGroup) { RPCServer::OnStarted(&OnRPCStarted); RPCServer::OnStopped(&OnRPCStopped); RPCServer::OnPreCommand(&OnRPCPreCommand); if (!InitHTTPServer()) return false; if (!StartRPC()) return false; if (!StartHTTPRPC()) return false; if (GetBoolArg("-rest", DEFAULT_REST_ENABLE) && !StartREST()) return false; if (!StartHTTPServer()) return false; return true; } // Parameter interaction based on rules void InitParameterInteraction() { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified if (IsArgSet("-bind")) { if (SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -bind set -> setting -listen=1\n", __func__); } if (IsArgSet("-whitebind")) { if (SoftSetBoolArg("-listen", true)) LogPrintf("%s: parameter interaction: -whitebind set -> setting -listen=1\n", __func__); } if (mapMultiArgs.count("-connect") && mapMultiArgs.at("-connect").size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default if (SoftSetBoolArg("-dnsseed", false)) LogPrintf("%s: parameter interaction: -connect set -> setting -dnsseed=0\n", __func__); if (SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -connect set -> setting -listen=0\n", __func__); } if (IsArgSet("-proxy")) { // to protect privacy, do not listen by default if a default proxy server is specified if (SoftSetBoolArg("-listen", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -listen=0\n", __func__); // to protect privacy, do not use UPNP when a proxy is set. The user may still specify -listen=1 // to listen locally, so don't rely on this happening through -listen below. if (SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -upnp=0\n", __func__); // to protect privacy, do not discover addresses by default if (SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -proxy set -> setting -discover=0\n", __func__); } if (!GetBoolArg("-listen", DEFAULT_LISTEN)) { // do not map ports or try to retrieve public IP when not listening (pointless) if (SoftSetBoolArg("-upnp", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -upnp=0\n", __func__); if (SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -discover=0\n", __func__); if (SoftSetBoolArg("-listenonion", false)) LogPrintf("%s: parameter interaction: -listen=0 -> setting -listenonion=0\n", __func__); } if (IsArgSet("-externalip")) { // if an explicit public IP is specified, do not try to find others if (SoftSetBoolArg("-discover", false)) LogPrintf("%s: parameter interaction: -externalip set -> setting -discover=0\n", __func__); } // disable whitelistrelay in blocksonly mode if (GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY)) { if (SoftSetBoolArg("-whitelistrelay", false)) LogPrintf("%s: parameter interaction: -blocksonly=1 -> setting -whitelistrelay=0\n", __func__); } // Forcing relay from whitelisted hosts implies we will accept relays from them in the first place. if (GetBoolArg("-whitelistforcerelay", DEFAULT_WHITELISTFORCERELAY)) { if (SoftSetBoolArg("-whitelistrelay", true)) LogPrintf("%s: parameter interaction: -whitelistforcerelay=1 -> setting -whitelistrelay=1\n", __func__); } } static std::string ResolveErrMsg(const char * const optname, const std::string& strBind) { return strprintf(_("Cannot resolve -%s address: '%s'"), optname, strBind); } void InitLogging() { fPrintToConsole = GetBoolArg("-printtoconsole", false); fLogTimestamps = GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS); fLogTimeMicros = GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS); fLogIPs = GetBoolArg("-logips", DEFAULT_LOGIPS); LogPrintf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); LogPrintf("Bitcoin version %s\n", FormatFullVersion()); } namespace { // Variables internal to initialization process only ServiceFlags nRelevantServices = NODE_NETWORK; int nMaxConnections; int nUserMaxConnections; int nFD; ServiceFlags nLocalServices = NODE_NETWORK; } [[noreturn]] static void new_handler_terminate() { // Rather than throwing std::bad-alloc if allocation fails, terminate // immediately to (try to) avoid chain corruption. // Since LogPrintf may itself allocate memory, set the handler directly // to terminate first. std::set_new_handler(std::terminate); LogPrintf("Error: Out of memory. Terminating.\n"); // The log was successful, terminate now. std::terminate(); }; bool AppInitBasicSetup() { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); #endif if (!SetupNetworking()) return InitError("Initializing networking failed"); #ifndef WIN32 if (!GetBoolArg("-sysperms", false)) { umask(077); } // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); // Ignore SIGPIPE, otherwise it will bring the daemon down if the client closes unexpectedly signal(SIGPIPE, SIG_IGN); #endif std::set_new_handler(new_handler_terminate); return true; } bool AppInitParameterInteraction() { const CChainParams& chainparams = Params(); // ********************************************************* Step 2: parameter interactions // also see: InitParameterInteraction() // if using block pruning, then disallow txindex if (GetArg("-prune", 0)) { if (GetBoolArg("-txindex", DEFAULT_TXINDEX)) return InitError(_("Prune mode is incompatible with -txindex.")); } // Make sure enough file descriptors are available int nBind = std::max( (mapMultiArgs.count("-bind") ? mapMultiArgs.at("-bind").size() : 0) + (mapMultiArgs.count("-whitebind") ? mapMultiArgs.at("-whitebind").size() : 0), size_t(1)); nUserMaxConnections = GetArg("-maxconnections", DEFAULT_MAX_PEER_CONNECTIONS); nMaxConnections = std::max(nUserMaxConnections, 0); // Trim requested connection counts, to fit into system limitations nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS)), 0); nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS + MAX_ADDNODE_CONNECTIONS); if (nFD < MIN_CORE_FILEDESCRIPTORS) return InitError(_("Not enough file descriptors available.")); nMaxConnections = std::min(nFD - MIN_CORE_FILEDESCRIPTORS - MAX_ADDNODE_CONNECTIONS, nMaxConnections); if (nMaxConnections < nUserMaxConnections) InitWarning(strprintf(_("Reducing -maxconnections from %d to %d, because of system limitations."), nUserMaxConnections, nMaxConnections)); // ********************************************************* Step 3: parameter-to-internal-flags fDebug = mapMultiArgs.count("-debug"); // Special-case: if -debug=0/-nodebug is set, turn off debugging messages if (fDebug) { const std::vector<std::string>& categories = mapMultiArgs.at("-debug"); if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), std::string("0")) != categories.end()) fDebug = false; } // Check for -debugnet if (GetBoolArg("-debugnet", false)) InitWarning(_("Unsupported argument -debugnet ignored, use -debug=net.")); // Check for -socks - as this is a privacy risk to continue, exit here if (IsArgSet("-socks")) return InitError(_("Unsupported argument -socks found. Setting SOCKS version isn't possible anymore, only SOCKS5 proxies are supported.")); // Check for -tor - as this is a privacy risk to continue, exit here if (GetBoolArg("-tor", false)) return InitError(_("Unsupported argument -tor found, use -onion.")); if (GetBoolArg("-benchmark", false)) InitWarning(_("Unsupported argument -benchmark ignored, use -debug=bench.")); if (GetBoolArg("-whitelistalwaysrelay", false)) InitWarning(_("Unsupported argument -whitelistalwaysrelay ignored, use -whitelistrelay and/or -whitelistforcerelay.")); if (IsArgSet("-blockminsize")) InitWarning("Unsupported argument -blockminsize ignored."); // Checkmempool and checkblockindex default to true in regtest mode int ratio = std::min<int>(std::max<int>(GetArg("-checkmempool", chainparams.DefaultConsistencyChecks() ? 1 : 0), 0), 1000000); if (ratio != 0) { mempool.setSanityCheck(1.0 / ratio); } fCheckBlockIndex = GetBoolArg("-checkblockindex", chainparams.DefaultConsistencyChecks()); fCheckpointsEnabled = GetBoolArg("-checkpoints", DEFAULT_CHECKPOINTS_ENABLED); hashAssumeValid = uint256S(GetArg("-assumevalid", chainparams.GetConsensus().defaultAssumeValid.GetHex())); if (!hashAssumeValid.IsNull()) LogPrintf("Assuming ancestors of block %s have valid signatures.\n", hashAssumeValid.GetHex()); else LogPrintf("Validating signatures for all blocks.\n"); // mempool limits int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; int64_t nMempoolSizeMin = GetArg("-limitdescendantsize", DEFAULT_DESCENDANT_SIZE_LIMIT) * 1000 * 40; if (nMempoolSizeMax < 0 || nMempoolSizeMax < nMempoolSizeMin) return InitError(strprintf(_("-maxmempool must be at least %d MB"), std::ceil(nMempoolSizeMin / 1000000.0))); // incremental relay fee sets the minimum feerate increase necessary for BIP 125 replacement in the mempool // and the amount the mempool min fee increases above the feerate of txs evicted due to mempool limiting. if (IsArgSet("-incrementalrelayfee")) { CAmount n = 0; if (!ParseMoney(GetArg("-incrementalrelayfee", ""), n)) return InitError(AmountErrMsg("incrementalrelayfee", GetArg("-incrementalrelayfee", ""))); incrementalRelayFee = CFeeRate(n); } // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency nScriptCheckThreads = GetArg("-par", DEFAULT_SCRIPTCHECK_THREADS); if (nScriptCheckThreads <= 0) nScriptCheckThreads += GetNumCores(); if (nScriptCheckThreads <= 1) nScriptCheckThreads = 0; else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; // block pruning; get the amount of disk space (in MiB) to allot for block & undo files int64_t nPruneArg = GetArg("-prune", 0); if (nPruneArg < 0) { return InitError(_("Prune cannot be configured with a negative value.")); } nPruneTarget = (uint64_t) nPruneArg * 1024 * 1024; if (nPruneArg == 1) { // manual pruning: -prune=1 LogPrintf("Block pruning enabled. Use RPC call pruneblockchain(height) to manually prune block and undo files.\n"); nPruneTarget = std::numeric_limits<uint64_t>::max(); fPruneMode = true; } else if (nPruneTarget) { if (nPruneTarget < MIN_DISK_SPACE_FOR_BLOCK_FILES) { return InitError(strprintf(_("Prune configured below the minimum of %d MiB. Please use a higher number."), MIN_DISK_SPACE_FOR_BLOCK_FILES / 1024 / 1024)); } LogPrintf("Prune configured to target %uMiB on disk for block and undo files.\n", nPruneTarget / 1024 / 1024); fPruneMode = true; } RegisterAllCoreRPCCommands(tableRPC); #ifdef ENABLE_WALLET RegisterWalletRPCCommands(tableRPC); #endif nConnectTimeout = GetArg("-timeout", DEFAULT_CONNECT_TIMEOUT); if (nConnectTimeout <= 0) nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; // Fee-per-kilobyte amount required for mempool acceptance and relay // If you are mining, be careful setting this: // if you set it to zero then // a transaction spammer can cheaply fill blocks using // 0-fee transactions. It should be set above the real // cost to you of processing a transaction. if (IsArgSet("-minrelaytxfee")) { CAmount n = 0; if (!ParseMoney(GetArg("-minrelaytxfee", ""), n)) { return InitError(AmountErrMsg("minrelaytxfee", GetArg("-minrelaytxfee", ""))); } // High fee check is done afterward in CWallet::ParameterInteraction() ::minRelayTxFee = CFeeRate(n); } else if (incrementalRelayFee > ::minRelayTxFee) { // Allow only setting incrementalRelayFee to control both ::minRelayTxFee = incrementalRelayFee; LogPrintf("Increasing minrelaytxfee to %s to match incrementalrelayfee\n",::minRelayTxFee.ToString()); } // Sanity check argument for min fee for including tx in block // TODO: Harmonize which arguments need sanity checking and where that happens if (IsArgSet("-blockmintxfee")) { CAmount n = 0; if (!ParseMoney(GetArg("-blockmintxfee", ""), n)) return InitError(AmountErrMsg("blockmintxfee", GetArg("-blockmintxfee", ""))); } // Feerate used to define dust. Shouldn't be changed lightly as old // implementations may inadvertently create non-standard transactions if (IsArgSet("-dustrelayfee")) { CAmount n = 0; if (!ParseMoney(GetArg("-dustrelayfee", ""), n) || 0 == n) return InitError(AmountErrMsg("dustrelayfee", GetArg("-dustrelayfee", ""))); dustRelayFee = CFeeRate(n); } fRequireStandard = !GetBoolArg("-acceptnonstdtxn", !chainparams.RequireStandard()); if (chainparams.RequireStandard() && !fRequireStandard) return InitError(strprintf("acceptnonstdtxn is not currently supported for %s chain", chainparams.NetworkIDString())); nBytesPerSigOp = GetArg("-bytespersigop", nBytesPerSigOp); #ifdef ENABLE_WALLET if (!CWallet::ParameterInteraction()) return false; #endif fIsBareMultisigStd = GetBoolArg("-permitbaremultisig", DEFAULT_PERMIT_BAREMULTISIG); fAcceptDatacarrier = GetBoolArg("-datacarrier", DEFAULT_ACCEPT_DATACARRIER); nMaxDatacarrierBytes = GetArg("-datacarriersize", nMaxDatacarrierBytes); // Option to startup with mocktime set (used for regression testing): SetMockTime(GetArg("-mocktime", 0)); // SetMockTime(0) is a no-op if (GetBoolArg("-peerbloomfilters", DEFAULT_PEERBLOOMFILTERS)) nLocalServices = ServiceFlags(nLocalServices | NODE_BLOOM); if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) < 0) return InitError("rpcserialversion must be non-negative."); if (GetArg("-rpcserialversion", DEFAULT_RPC_SERIALIZE_VERSION) > 1) return InitError("unknown rpcserialversion requested."); nMaxTipAge = GetArg("-maxtipage", DEFAULT_MAX_TIP_AGE); fEnableReplacement = GetBoolArg("-mempoolreplacement", DEFAULT_ENABLE_REPLACEMENT); if ((!fEnableReplacement) && IsArgSet("-mempoolreplacement")) { // Minimal effort at forwards compatibility std::string strReplacementModeList = GetArg("-mempoolreplacement", ""); // default is impossible std::vector<std::string> vstrReplacementModes; boost::split(vstrReplacementModes, strReplacementModeList, boost::is_any_of(",")); fEnableReplacement = (std::find(vstrReplacementModes.begin(), vstrReplacementModes.end(), "fee") != vstrReplacementModes.end()); } if (mapMultiArgs.count("-bip9params")) { // Allow overriding BIP9 parameters for testing if (!chainparams.MineBlocksOnDemand()) { return InitError("BIP9 parameters may only be overridden on regtest."); } const std::vector<std::string>& deployments = mapMultiArgs.at("-bip9params"); for (auto i : deployments) { std::vector<std::string> vDeploymentParams; boost::split(vDeploymentParams, i, boost::is_any_of(":")); if (vDeploymentParams.size() != 3) { return InitError("BIP9 parameters malformed, expecting deployment:start:end"); } int64_t nStartTime, nTimeout; if (!ParseInt64(vDeploymentParams[1], &nStartTime)) { return InitError(strprintf("Invalid nStartTime (%s)", vDeploymentParams[1])); } if (!ParseInt64(vDeploymentParams[2], &nTimeout)) { return InitError(strprintf("Invalid nTimeout (%s)", vDeploymentParams[2])); } bool found = false; for (int j=0; j<(int)Consensus::MAX_VERSION_BITS_DEPLOYMENTS; ++j) { if (vDeploymentParams[0].compare(VersionBitsDeploymentInfo[j].name) == 0) { UpdateRegtestBIP9Parameters(Consensus::DeploymentPos(j), nStartTime, nTimeout); found = true; LogPrintf("Setting BIP9 activation parameters for %s to start=%ld, timeout=%ld\n", vDeploymentParams[0], nStartTime, nTimeout); break; } } if (!found) { return InitError(strprintf("Invalid deployment (%s)", vDeploymentParams[0])); } } } return true; } static bool LockDataDirectory(bool probeOnly) { std::string strDataDir = GetDataDir().string(); // Make sure only a single Bitcoin process is using the data directory. boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); try { static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) { return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running."), strDataDir, _(PACKAGE_NAME))); } if (probeOnly) { lock.unlock(); } } catch(const boost::interprocess::interprocess_exception& e) { return InitError(strprintf(_("Cannot obtain a lock on data directory %s. %s is probably already running.") + " %s.", strDataDir, _(PACKAGE_NAME), e.what())); } return true; } bool AppInitSanityChecks() { // ********************************************************* Step 4: sanity checks // Initialize elliptic curve code ECC_Start(); globalVerifyHandle.reset(new ECCVerifyHandle()); // Sanity check if (!InitSanityCheck()) return InitError(strprintf(_("Initialization sanity check failed. %s is shutting down."), _(PACKAGE_NAME))); // Probe the data directory lock to give an early error message, if possible return LockDataDirectory(true); } bool AppInitMain(boost::thread_group& threadGroup, CScheduler& scheduler) { const CChainParams& chainparams = Params(); // ********************************************************* Step 4a: application initialization // After daemonization get the data directory lock again and hold on to it until exit // This creates a slight window for a race condition to happen, however this condition is harmless: it // will at most make us exit without printing a message to console. if (!LockDataDirectory(false)) { // Detailed error printed inside LockDataDirectory return false; } #ifndef WIN32 CreatePidFile(GetPidFile(), getpid()); #endif if (GetBoolArg("-shrinkdebugfile", !fDebug)) { // Do this first since it both loads a bunch of debug.log into memory, // and because this needs to happen before any other debug.log printing ShrinkDebugFile(); } if (fPrintToDebugLog) OpenDebugLog(); if (!fLogTimestamps) LogPrintf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime())); LogPrintf("Default data directory %s\n", GetDefaultDataDir().string()); LogPrintf("Using data directory %s\n", GetDataDir().string()); LogPrintf("Using config file %s\n", GetConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)).string()); LogPrintf("Using at most %i automatic connections (%i file descriptors available)\n", nMaxConnections, nFD); InitSignatureCache(); LogPrintf("Using %u threads for script verification\n", nScriptCheckThreads); if (nScriptCheckThreads) { for (int i=0; i<nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); } // Start the lightweight task scheduler thread CScheduler::Function serviceLoop = boost::bind(&CScheduler::serviceQueue, &scheduler); threadGroup.create_thread(boost::bind(&TraceThread<CScheduler::Function>, "scheduler", serviceLoop)); /* Start the RPC server already. It will be started in "warmup" mode * and not really process calls already (but it will signify connections * that the server is there and will be ready later). Warmup mode will * be disabled when initialisation is finished. */ if (GetBoolArg("-server", false)) { uiInterface.InitMessage.connect(SetRPCWarmupStatus); if (!AppInitServers(threadGroup)) return InitError(_("Unable to start HTTP server. See debug log for details.")); } int64_t nStart; // ********************************************************* Step 5: verify wallet database integrity #ifdef ENABLE_WALLET if (!CWallet::Verify()) return false; #endif // ********************************************************* Step 6: network initialization // Note that we absolutely cannot open any actual connections // until the very end ("start node") as the UTXO/block state // is not yet setup and may end up being set up twice if we // need to reindex later. assert(!g_connman); g_connman = std::unique_ptr<CConnman>(new CConnman(GetRand(std::numeric_limits<uint64_t>::max()), GetRand(std::numeric_limits<uint64_t>::max()))); CConnman& connman = *g_connman; peerLogic.reset(new PeerLogicValidation(&connman)); RegisterValidationInterface(peerLogic.get()); RegisterNodeSignals(GetNodeSignals()); // sanitize comments per BIP-0014, format user agent and check total size std::vector<std::string> uacomments; if (mapMultiArgs.count("-uacomment")) { BOOST_FOREACH(std::string cmt, mapMultiArgs.at("-uacomment")) { if (cmt != SanitizeString(cmt, SAFE_CHARS_UA_COMMENT)) return InitError(strprintf(_("User Agent comment (%s) contains unsafe characters."), cmt)); uacomments.push_back(cmt); } } strSubVersion = FormatSubVersion(CLIENT_NAME, CLIENT_VERSION, uacomments); if (strSubVersion.size() > MAX_SUBVERSION_LENGTH) { return InitError(strprintf(_("Total length of network version string (%i) exceeds maximum length (%i). Reduce the number or size of uacomments."), strSubVersion.size(), MAX_SUBVERSION_LENGTH)); } if (mapMultiArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(const std::string& snet, mapMultiArgs.at("-onlynet")) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); } } if (mapMultiArgs.count("-whitelist")) { BOOST_FOREACH(const std::string& net, mapMultiArgs.at("-whitelist")) { CSubNet subnet; LookupSubNet(net.c_str(), subnet); if (!subnet.IsValid()) return InitError(strprintf(_("Invalid netmask specified in -whitelist: '%s'"), net)); connman.AddWhitelistedRange(subnet); } } // Check for host lookup allowed before parsing any network related parameters fNameLookup = GetBoolArg("-dns", DEFAULT_NAME_LOOKUP); bool proxyRandomize = GetBoolArg("-proxyrandomize", DEFAULT_PROXYRANDOMIZE); // -proxy sets a proxy for all outgoing network traffic // -noproxy (or -proxy=0) as well as the empty string can be used to not set a proxy, this is the default std::string proxyArg = GetArg("-proxy", ""); SetLimited(NET_TOR); if (proxyArg != "" && proxyArg != "0") { CService proxyAddr; if (!Lookup(proxyArg.c_str(), proxyAddr, 9050, fNameLookup)) { return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg)); } proxyType addrProxy = proxyType(proxyAddr, proxyRandomize); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address or hostname: '%s'"), proxyArg)); SetProxy(NET_IPV4, addrProxy); SetProxy(NET_IPV6, addrProxy); SetProxy(NET_TOR, addrProxy); SetNameProxy(addrProxy); SetLimited(NET_TOR, false); // by default, -proxy sets onion as reachable, unless -noonion later } // -onion can be used to set only a proxy for .onion, or override normal proxy for .onion addresses // -noonion (or -onion=0) disables connecting to .onion entirely // An empty string is used to not override the onion proxy (in which case it defaults to -proxy set above, or none) std::string onionArg = GetArg("-onion", ""); if (onionArg != "") { if (onionArg == "0") { // Handle -noonion/-onion=0 SetLimited(NET_TOR); // set onions as unreachable } else { CService onionProxy; if (!Lookup(onionArg.c_str(), onionProxy, 9050, fNameLookup)) { return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg)); } proxyType addrOnion = proxyType(onionProxy, proxyRandomize); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -onion address or hostname: '%s'"), onionArg)); SetProxy(NET_TOR, addrOnion); SetLimited(NET_TOR, false); } } // see Step 2: parameter interactions for more information about these fListen = GetBoolArg("-listen", DEFAULT_LISTEN); fDiscover = GetBoolArg("-discover", true); fRelayTxes = !GetBoolArg("-blocksonly", DEFAULT_BLOCKSONLY); if (fListen) { bool fBound = false; if (mapMultiArgs.count("-bind")) { BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-bind")) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) return InitError(ResolveErrMsg("bind", strBind)); fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); } } if (mapMultiArgs.count("-whitebind")) { BOOST_FOREACH(const std::string& strBind, mapMultiArgs.at("-whitebind")) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, 0, false)) return InitError(ResolveErrMsg("whitebind", strBind)); if (addrBind.GetPort() == 0) return InitError(strprintf(_("Need to specify a port with -whitebind: '%s'"), strBind)); fBound |= Bind(connman, addrBind, (BF_EXPLICIT | BF_REPORT_ERROR | BF_WHITELIST)); } } if (!mapMultiArgs.count("-bind") && !mapMultiArgs.count("-whitebind")) { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; fBound |= Bind(connman, CService(in6addr_any, GetListenPort()), BF_NONE); fBound |= Bind(connman, CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); } if (!fBound) return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); } if (mapMultiArgs.count("-externalip")) { BOOST_FOREACH(const std::string& strAddr, mapMultiArgs.at("-externalip")) { CService addrLocal; if (Lookup(strAddr.c_str(), addrLocal, GetListenPort(), fNameLookup) && addrLocal.IsValid()) AddLocal(addrLocal, LOCAL_MANUAL); else return InitError(ResolveErrMsg("externalip", strAddr)); } } if (mapMultiArgs.count("-seednode")) { BOOST_FOREACH(const std::string& strDest, mapMultiArgs.at("-seednode")) connman.AddOneShot(strDest); } #if ENABLE_ZMQ pzmqNotificationInterface = CZMQNotificationInterface::Create(); if (pzmqNotificationInterface) { RegisterValidationInterface(pzmqNotificationInterface); } #endif uint64_t nMaxOutboundLimit = 0; //unlimited unless -maxuploadtarget is set uint64_t nMaxOutboundTimeframe = MAX_UPLOAD_TIMEFRAME; if (IsArgSet("-maxuploadtarget")) { nMaxOutboundLimit = GetArg("-maxuploadtarget", DEFAULT_MAX_UPLOAD_TARGET)*1024*1024; } // ********************************************************* Step 7: load block chain fReindex = GetBoolArg("-reindex", false); bool fReindexChainState = GetBoolArg("-reindex-chainstate", false); boost::filesystem::create_directories(GetDataDir() / "blocks"); // cache size calculations int64_t nTotalCache = (GetArg("-dbcache", nDefaultDbCache) << 20); nTotalCache = std::max(nTotalCache, nMinDbCache << 20); // total cache cannot be less than nMinDbCache nTotalCache = std::min(nTotalCache, nMaxDbCache << 20); // total cache cannot be greater than nMaxDbcache int64_t nBlockTreeDBCache = nTotalCache / 8; nBlockTreeDBCache = std::min(nBlockTreeDBCache, (GetBoolArg("-txindex", DEFAULT_TXINDEX) ? nMaxBlockDBAndTxIndexCache : nMaxBlockDBCache) << 20); nTotalCache -= nBlockTreeDBCache; int64_t nCoinDBCache = std::min(nTotalCache / 2, (nTotalCache / 4) + (1 << 23)); // use 25%-50% of the remainder for disk cache nCoinDBCache = std::min(nCoinDBCache, nMaxCoinsDBCache << 20); // cap total coins db cache nTotalCache -= nCoinDBCache; nCoinCacheUsage = nTotalCache; // the rest goes to in-memory cache int64_t nMempoolSizeMax = GetArg("-maxmempool", DEFAULT_MAX_MEMPOOL_SIZE) * 1000000; LogPrintf("Cache configuration:\n"); LogPrintf("* Using %.1fMiB for block index database\n", nBlockTreeDBCache * (1.0 / 1024 / 1024)); LogPrintf("* Using %.1fMiB for chain state database\n", nCoinDBCache * (1.0 / 1024 / 1024)); LogPrintf("* Using %.1fMiB for in-memory UTXO set (plus up to %.1fMiB of unused mempool space)\n", nCoinCacheUsage * (1.0 / 1024 / 1024), nMempoolSizeMax * (1.0 / 1024 / 1024)); bool fLoaded = false; while (!fLoaded) { bool fReset = fReindex; std::string strLoadError; uiInterface.InitMessage(_("Loading block index...")); nStart = GetTimeMillis(); do { try { UnloadBlockIndex(); delete pcoinsTip; delete pcoinsdbview; delete pcoinscatcher; delete pblocktree; pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex || fReindexChainState); pcoinscatcher = new CCoinsViewErrorCatcher(pcoinsdbview); pcoinsTip = new CCoinsViewCache(pcoinscatcher); if (fReindex) { pblocktree->WriteReindexing(true); //If we're reindexing in prune mode, wipe away unusable block files and all undo data files if (fPruneMode) CleanupBlockRevFiles(); } if (!LoadBlockIndex(chainparams)) { strLoadError = _("Error loading block database"); break; } // If the loaded chain has a wrong genesis, bail out immediately // (we're likely using a testnet datadir, or the other way around). if (!mapBlockIndex.empty() && mapBlockIndex.count(chainparams.GetConsensus().hashGenesisBlock) == 0) return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); // Initialize the block index (no-op if non-empty database was already loaded) if (!InitBlockIndex(chainparams)) { strLoadError = _("Error initializing block database"); break; } // Check for changed -txindex state if (fTxIndex != GetBoolArg("-txindex", DEFAULT_TXINDEX)) { strLoadError = _("You need to rebuild the database using -reindex-chainstate to change -txindex"); break; } // Check for changed -prune state. What we are concerned about is a user who has pruned blocks // in the past, but is now trying to run unpruned. if (fHavePruned && !fPruneMode) { strLoadError = _("You need to rebuild the database using -reindex to go back to unpruned mode. This will redownload the entire blockchain"); break; } if (!fReindex && chainActive.Tip() != NULL) { uiInterface.InitMessage(_("Rewinding blocks...")); if (!RewindBlockIndex(chainparams)) { strLoadError = _("Unable to rewind the database to a pre-fork state. You will need to redownload the blockchain"); break; } } uiInterface.InitMessage(_("Verifying blocks...")); if (fHavePruned && GetArg("-checkblocks", DEFAULT_CHECKBLOCKS) > MIN_BLOCKS_TO_KEEP) { LogPrintf("Prune: pruned datadir may not have more than %d blocks; only checking available blocks", MIN_BLOCKS_TO_KEEP); } { LOCK(cs_main); CBlockIndex* tip = chainActive.Tip(); RPCNotifyBlockChange(true, tip); if (tip && tip->nTime > GetAdjustedTime() + 2 * 60 * 60) { strLoadError = _("The block database contains a block which appears to be from the future. " "This may be due to your computer's date and time being set incorrectly. " "Only rebuild the block database if you are sure that your computer's date and time are correct"); break; } } if (!CVerifyDB().VerifyDB(chainparams, pcoinsdbview, GetArg("-checklevel", DEFAULT_CHECKLEVEL), GetArg("-checkblocks", DEFAULT_CHECKBLOCKS))) { strLoadError = _("Corrupted block database detected"); break; } } catch (const std::exception& e) { if (fDebug) LogPrintf("%s\n", e.what()); strLoadError = _("Error opening block database"); break; } fLoaded = true; } while(false); if (!fLoaded) { // first suggest a reindex if (!fReset) { bool fRet = uiInterface.ThreadSafeQuestion( strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"), strLoadError + ".\nPlease restart with -reindex or -reindex-chainstate to recover.", "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); if (fRet) { fReindex = true; fRequestShutdown = false; } else { LogPrintf("Aborted block database rebuild. Exiting.\n"); return false; } } else { return InitError(strLoadError); } } } // As LoadBlockIndex can take several minutes, it's possible the user // requested to kill the GUI during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (fRequestShutdown) { LogPrintf("Shutdown requested. Exiting.\n"); return false; } LogPrintf(" block index %15dms\n", GetTimeMillis() - nStart); boost::filesystem::path est_path = GetDataDir() / FEE_ESTIMATES_FILENAME; CAutoFile est_filein(fopen(est_path.string().c_str(), "rb"), SER_DISK, CLIENT_VERSION); // Allowed to fail as this file IS missing on first startup. if (!est_filein.IsNull()) mempool.ReadFeeEstimates(est_filein); fFeeEstimatesInitialized = true; // ********************************************************* Step 8: load wallet #ifdef ENABLE_WALLET if (!CWallet::InitLoadWallet()) return false; #else LogPrintf("No wallet support compiled in!\n"); #endif // ********************************************************* Step 9: data directory maintenance // if pruning, unset the service bit and perform the initial blockstore prune // after any wallet rescanning has taken place. if (fPruneMode) { LogPrintf("Unsetting NODE_NETWORK on prune mode\n"); nLocalServices = ServiceFlags(nLocalServices & ~NODE_NETWORK); if (!fReindex) { uiInterface.InitMessage(_("Pruning blockstore...")); PruneAndFlush(); } } if (chainparams.GetConsensus().vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout != 0) { // Only advertise witness capabilities if they have a reasonable start time. // This allows us to have the code merged without a defined softfork, by setting its // end time to 0. // Note that setting NODE_WITNESS is never required: the only downside from not // doing so is that after activation, no upgraded nodes will fetch from you. nLocalServices = ServiceFlags(nLocalServices | NODE_WITNESS); // Only care about others providing witness capabilities if there is a softfork // defined. nRelevantServices = ServiceFlags(nRelevantServices | NODE_WITNESS); } // ********************************************************* Step 10: import blocks if (!CheckDiskSpace()) return false; // Either install a handler to notify us when genesis activates, or set fHaveGenesis directly. // No locking, as this happens before any background thread is started. if (chainActive.Tip() == NULL) { uiInterface.NotifyBlockTip.connect(BlockNotifyGenesisWait); } else { fHaveGenesis = true; } if (IsArgSet("-blocknotify")) uiInterface.NotifyBlockTip.connect(BlockNotifyCallback); std::vector<boost::filesystem::path> vImportFiles; if (mapMultiArgs.count("-loadblock")) { BOOST_FOREACH(const std::string& strFile, mapMultiArgs.at("-loadblock")) vImportFiles.push_back(strFile); } threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); // Wait for genesis block to be processed { boost::unique_lock<boost::mutex> lock(cs_GenesisWait); while (!fHaveGenesis) { condvar_GenesisWait.wait(lock); } uiInterface.NotifyBlockTip.disconnect(BlockNotifyGenesisWait); } // ********************************************************* Step 11: start node //// debug print LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); LogPrintf("nBestHeight = %d\n", chainActive.Height()); if (GetBoolArg("-listenonion", DEFAULT_LISTEN_ONION)) StartTorControl(threadGroup, scheduler); Discover(threadGroup); // Map ports with UPnP MapPort(GetBoolArg("-upnp", DEFAULT_UPNP)); std::string strNodeError; CConnman::Options connOptions; connOptions.nLocalServices = nLocalServices; connOptions.nRelevantServices = nRelevantServices; connOptions.nMaxConnections = nMaxConnections; connOptions.nMaxOutbound = std::min(MAX_OUTBOUND_CONNECTIONS, connOptions.nMaxConnections); connOptions.nMaxAddnode = MAX_ADDNODE_CONNECTIONS; connOptions.nMaxFeeler = 1; connOptions.nBestHeight = chainActive.Height(); connOptions.uiInterface = &uiInterface; connOptions.nSendBufferMaxSize = 1000*GetArg("-maxsendbuffer", DEFAULT_MAXSENDBUFFER); connOptions.nReceiveFloodSize = 1000*GetArg("-maxreceivebuffer", DEFAULT_MAXRECEIVEBUFFER); connOptions.nMaxOutboundTimeframe = nMaxOutboundTimeframe; connOptions.nMaxOutboundLimit = nMaxOutboundLimit; if (!connman.Start(scheduler, strNodeError, connOptions)) return InitError(strNodeError); // ********************************************************* Step 12: finished SetRPCWarmupFinished(); uiInterface.InitMessage(_("Done loading")); #ifdef ENABLE_WALLET if (pwalletMain) pwalletMain->postInitProcess(scheduler); #endif return !fRequestShutdown; }
s-matthew-english/bitcoin
src/init.cpp
C++
mit
80,293
<?php namespace esperanto\UserBundle\Entity; use Doctrine\ORM\Mapping as ORM; use FOS\UserBundle\Model\Group as BaseGroup; /** * Group */ class Group extends BaseGroup { /** * @var integer */ protected $id; /** * @var \Doctrine\Common\Collections\Collection */ private $users; /** * Constructor */ public function __construct() { parent::__construct('', array()); $this->users = new \Doctrine\Common\Collections\ArrayCollection(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Add users * * @param \esperanto\UserBundle\Entity\User $users * @return Group */ public function addUser(\esperanto\UserBundle\Entity\User $users) { $this->users[] = $users; return $this; } /** * Remove users * * @param \esperanto\UserBundle\Entity\User $users */ public function removeUser(\esperanto\UserBundle\Entity\User $users) { $this->users->removeElement($users); } /** * Get users * * @return \Doctrine\Common\Collections\Collection */ public function getUsers() { return $this->users; } }
gseidel/esperanto-cms
src/esperanto/UserBundle/Entity/Group.php
PHP
mit
1,301
@extends('admin.layouts.modal') {{-- Content --}} @section('content') <!-- Tabs --> <ul class="nav nav-tabs"> <li class="active"><a href="#tab-general" data-toggle="tab">General</a></li> </ul> <!-- ./ tabs --> {{-- Delete User Form --}} <form class="form-horizontal" method="post" action="" autocomplete="off"> <!-- CSRF Token --> <input type="hidden" name="_token" value="{{{ csrf_token() }}}" /> <input type="hidden" name="id" value="{{ $user->id }}" /> <!-- ./ csrf token --> <!-- Form Actions --> <div class="control-group"> <div class="controls"> <element class="btn-cancel close_popup">Cancel</element> <button type="submit" class="btn btn-danger close_popup">Delete</button> </div> </div> <!-- ./ form actions --> </form> @stop
mgathu1/groceryshopper
laravel/app/views/admin/users/delete.blade.php
PHP
mit
905
package org.multibit.hd.core.events; /** * <p>Signature interface to provide the following to Core Event API:</p> * <ul> * <li>Identification of core events</li> * </ul> * <p>A core event should be named using a noun as the first part of the name (e.g. ExchangeRateChangedEvent)</p> * <p>A core event can occur at any time and will not be synchronized with other events.</p> * * @since 0.0.1 *   */ public interface CoreEvent { }
oscarguindzberg/multibit-hd
mbhd-core/src/main/java/org/multibit/hd/core/events/CoreEvent.java
Java
mit
449
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; namespace Azure.Media.Analytics.Edge.Models { /// <summary> Http header service credentials. </summary> public partial class MediaGraphHttpHeaderCredentials : MediaGraphCredentials { /// <summary> Initializes a new instance of MediaGraphHttpHeaderCredentials. </summary> /// <param name="headerName"> HTTP header name. </param> /// <param name="headerValue"> HTTP header value. Please use a parameter so that the actual value is not returned on PUT or GET requests. </param> /// <exception cref="ArgumentNullException"> <paramref name="headerName"/> or <paramref name="headerValue"/> is null. </exception> public MediaGraphHttpHeaderCredentials(string headerName, string headerValue) { if (headerName == null) { throw new ArgumentNullException(nameof(headerName)); } if (headerValue == null) { throw new ArgumentNullException(nameof(headerValue)); } HeaderName = headerName; HeaderValue = headerValue; Type = "#Microsoft.Media.MediaGraphHttpHeaderCredentials"; } /// <summary> Initializes a new instance of MediaGraphHttpHeaderCredentials. </summary> /// <param name="type"> The discriminator for derived types. </param> /// <param name="headerName"> HTTP header name. </param> /// <param name="headerValue"> HTTP header value. Please use a parameter so that the actual value is not returned on PUT or GET requests. </param> internal MediaGraphHttpHeaderCredentials(string type, string headerName, string headerValue) : base(type) { HeaderName = headerName; HeaderValue = headerValue; Type = type ?? "#Microsoft.Media.MediaGraphHttpHeaderCredentials"; } /// <summary> HTTP header name. </summary> public string HeaderName { get; set; } /// <summary> HTTP header value. Please use a parameter so that the actual value is not returned on PUT or GET requests. </summary> public string HeaderValue { get; set; } } }
brjohnstmsft/azure-sdk-for-net
sdk/mediaservices/Azure.Media.Analytics.Edge/src/Generated/Models/MediaGraphHttpHeaderCredentials.cs
C#
mit
2,304
var fs = require('fs'); var PNG = require('../lib/png').PNG; var test = require('tape'); var noLargeOption = process.argv.indexOf("nolarge") >= 0; fs.readdir(__dirname + '/in/', function (err, files) { if (err) throw err; files = files.filter(function (file) { return (!noLargeOption || !file.match(/large/i)) && Boolean(file.match(/\.png$/i)); }); console.log("Converting images"); files.forEach(function (file) { var expectedError = false; if (file.match(/^x/)) { expectedError = true; } test('convert sync - ' + file, function (t) { t.timeoutAfter(1000 * 60 * 5); var data = fs.readFileSync(__dirname + '/in/' + file); try { var png = PNG.sync.read(data); } catch (e) { if (!expectedError) { t.fail('Unexpected error parsing..' + file + '\n' + e.message + "\n" + e.stack); } else { t.pass("completed"); } return t.end(); } if (expectedError) { t.fail("Sync: Error expected, parsed fine .. - " + file); return t.end(); } var outpng = new PNG(); outpng.gamma = png.gamma; outpng.data = png.data; outpng.width = png.width; outpng.height = png.height; outpng.pack() .pipe(fs.createWriteStream(__dirname + '/outsync/' + file) .on("finish", function () { t.pass("completed"); t.end(); })); }); test('convert async - ' + file, function (t) { t.timeoutAfter(1000 * 60 * 5); fs.createReadStream(__dirname + '/in/' + file) .pipe(new PNG()) .on('error', function (err) { if (!expectedError) { t.fail("Async: Unexpected error parsing.." + file + '\n' + err.message + '\n' + err.stack); } else { t.pass("completed"); } t.end(); }) .on('parsed', function () { if (expectedError) { t.fail("Async: Error expected, parsed fine .." + file); return t.end(); } this.pack() .pipe( fs.createWriteStream(__dirname + '/out/' + file) .on("finish", function () { t.pass("completed"); t.end(); })); }); }); }); });
lukeapage/pngjs2
test/convert-images-spec.js
JavaScript
mit
2,317
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>make_vector</title> <link rel="stylesheet" href="../../../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.79.1"> <link rel="home" href="../../../../index.html" title="Chapter 1. Fusion 2.2"> <link rel="up" href="../functions.html" title="Functions"> <link rel="prev" href="make_cons.html" title="make_cons"> <link rel="next" href="make_deque.html" title="make_deque"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="make_cons.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../functions.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="make_deque.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="fusion.container.generation.functions.make_vector"></a><a class="link" href="make_vector.html" title="make_vector">make_vector</a> </h5></div></div></div> <h6> <a name="fusion.container.generation.functions.make_vector.h0"></a> <span class="phrase"><a name="fusion.container.generation.functions.make_vector.description"></a></span><a class="link" href="make_vector.html#fusion.container.generation.functions.make_vector.description">Description</a> </h6> <p> Create a <a class="link" href="../../vector.html" title="vector"><code class="computeroutput"><span class="identifier">vector</span></code></a> from one or more values. </p> <h6> <a name="fusion.container.generation.functions.make_vector.h1"></a> <span class="phrase"><a name="fusion.container.generation.functions.make_vector.synopsis"></a></span><a class="link" href="make_vector.html#fusion.container.generation.functions.make_vector.synopsis">Synopsis</a> </h6> <pre class="programlisting"><span class="keyword">template</span> <span class="special">&lt;</span><span class="keyword">typename</span> <span class="identifier">T0</span><span class="special">,</span> <span class="keyword">typename</span> <span class="identifier">T1</span><span class="special">,...</span> <span class="keyword">typename</span> <span class="identifier">TN</span><span class="special">&gt;</span> <span class="keyword">typename</span> <a class="link" href="../metafunctions/make_vector.html" title="make_vector"><code class="computeroutput"><span class="identifier">result_of</span><span class="special">::</span><span class="identifier">make_vector</span></code></a><span class="special">&lt;</span><span class="identifier">T0</span><span class="special">,</span> <span class="identifier">T1</span><span class="special">,...</span> <span class="identifier">TN</span><span class="special">&gt;::</span><span class="identifier">type</span> <span class="identifier">make_vector</span><span class="special">(</span><span class="identifier">T0</span> <span class="keyword">const</span><span class="special">&amp;</span> <span class="identifier">x0</span><span class="special">,</span> <span class="identifier">T1</span> <span class="keyword">const</span><span class="special">&amp;</span> <span class="identifier">x1</span><span class="special">...</span> <span class="identifier">TN</span> <span class="keyword">const</span><span class="special">&amp;</span> <span class="identifier">xN</span><span class="special">);</span> </pre> <p> For C++11 compilers, the variadic function interface has no upper bound. </p> <p> For C++03 compilers, the variadic function accepts <code class="computeroutput"><span class="number">0</span></code> to <code class="computeroutput"><span class="identifier">FUSION_MAX_VECTOR_SIZE</span></code> elements, where <code class="computeroutput"><span class="identifier">FUSION_MAX_VECTOR_SIZE</span></code> is a user definable predefined maximum that defaults to <code class="computeroutput"><span class="number">10</span></code>. You may define the preprocessor constant <code class="computeroutput"><span class="identifier">FUSION_MAX_VECTOR_SIZE</span></code> before including any Fusion header to change the default. Example: </p> <pre class="programlisting"><span class="preprocessor">#define</span> <span class="identifier">FUSION_MAX_VECTOR_SIZE</span> <span class="number">20</span> </pre> <h6> <a name="fusion.container.generation.functions.make_vector.h2"></a> <span class="phrase"><a name="fusion.container.generation.functions.make_vector.parameters"></a></span><a class="link" href="make_vector.html#fusion.container.generation.functions.make_vector.parameters">Parameters</a> </h6> <div class="informaltable"><table class="table"> <colgroup> <col> <col> <col> </colgroup> <thead><tr> <th> <p> Parameter </p> </th> <th> <p> Requirement </p> </th> <th> <p> Description </p> </th> </tr></thead> <tbody><tr> <td> <p> <code class="computeroutput"><span class="identifier">x0</span><span class="special">,</span> <span class="identifier">x1</span><span class="special">,...</span> <span class="identifier">xN</span></code> </p> </td> <td> <p> Instances of <code class="computeroutput"><span class="identifier">T0</span><span class="special">,</span> <span class="identifier">T1</span><span class="special">,...</span> <span class="identifier">TN</span></code> </p> </td> <td> <p> The arguments to <code class="computeroutput"><span class="identifier">make_vector</span></code> </p> </td> </tr></tbody> </table></div> <h6> <a name="fusion.container.generation.functions.make_vector.h3"></a> <span class="phrase"><a name="fusion.container.generation.functions.make_vector.expression_semantics"></a></span><a class="link" href="make_vector.html#fusion.container.generation.functions.make_vector.expression_semantics">Expression Semantics</a> </h6> <pre class="programlisting"><span class="identifier">make_vector</span><span class="special">(</span><span class="identifier">x0</span><span class="special">,</span> <span class="identifier">x1</span><span class="special">,...</span> <span class="identifier">xN</span><span class="special">);</span> </pre> <p> <span class="bold"><strong>Return type</strong></span>: <a class="link" href="../metafunctions/make_vector.html" title="make_vector"><code class="computeroutput"><span class="identifier">result_of</span><span class="special">::</span><span class="identifier">make_vector</span></code></a><code class="computeroutput"><span class="special">&lt;</span><span class="identifier">T0</span><span class="special">,</span> <span class="identifier">T1</span><span class="special">,...</span> <span class="identifier">TN</span><span class="special">&gt;::</span><span class="identifier">type</span></code> </p> <p> <span class="bold"><strong>Semantics</strong></span>: Create a <a class="link" href="../../vector.html" title="vector"><code class="computeroutput"><span class="identifier">vector</span></code></a> from <code class="computeroutput"><span class="identifier">x0</span><span class="special">,</span> <span class="identifier">x1</span><span class="special">,...</span> <span class="identifier">xN</span></code>. </p> <h6> <a name="fusion.container.generation.functions.make_vector.h4"></a> <span class="phrase"><a name="fusion.container.generation.functions.make_vector.header"></a></span><a class="link" href="make_vector.html#fusion.container.generation.functions.make_vector.header">Header</a> </h6> <pre class="programlisting"><span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">fusion</span><span class="special">/</span><span class="identifier">container</span><span class="special">/</span><span class="identifier">generation</span><span class="special">/</span><span class="identifier">make_vector</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> <span class="preprocessor">#include</span> <span class="special">&lt;</span><span class="identifier">boost</span><span class="special">/</span><span class="identifier">fusion</span><span class="special">/</span><span class="identifier">include</span><span class="special">/</span><span class="identifier">make_vector</span><span class="special">.</span><span class="identifier">hpp</span><span class="special">&gt;</span> </pre> <h6> <a name="fusion.container.generation.functions.make_vector.h5"></a> <span class="phrase"><a name="fusion.container.generation.functions.make_vector.example"></a></span><a class="link" href="make_vector.html#fusion.container.generation.functions.make_vector.example">Example</a> </h6> <pre class="programlisting"><span class="identifier">make_vector</span><span class="special">(</span><span class="number">123</span><span class="special">,</span> <span class="string">"hello"</span><span class="special">,</span> <span class="number">12.5</span><span class="special">)</span> </pre> <h6> <a name="fusion.container.generation.functions.make_vector.h6"></a> <span class="phrase"><a name="fusion.container.generation.functions.make_vector.see_also"></a></span><a class="link" href="make_vector.html#fusion.container.generation.functions.make_vector.see_also">See also</a> </h6> <p> <a class="link" href="../../../notes.html#fusion.notes.reference_wrappers"><code class="computeroutput"><span class="identifier">Reference</span> <span class="identifier">Wrappers</span></code></a> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright © 2001-2006, 2011, 2012 Joel de Guzman, Dan Marsden, Tobias Schwinger<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="make_cons.html"><img src="../../../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../functions.html"><img src="../../../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../index.html"><img src="../../../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="make_deque.html"><img src="../../../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
davehorton/drachtio-server
deps/boost_1_77_0/libs/fusion/doc/html/fusion/container/generation/functions/make_vector.html
HTML
mit
12,217
/*************************************************************************************** Extended WPF Toolkit Copyright (C) 2007-2014 Xceed Software Inc. This program is provided to you under the terms of the Microsoft Public License (Ms-PL) as published at http://wpftoolkit.codeplex.com/license For more features, controls, and fast professional support, pick up the Plus Edition at http://xceed.com/wpf_toolkit Stay informed: follow @datagrid on Twitter or Like http://facebook.com/datagrids ************************************************************************************/ using System; using System.IO; using System.Windows; using System.Windows.Resources; namespace Xceed.Wpf.Toolkit.LiveExplorer.Samples.Magnifier.Views { /// <summary> /// Interaction logic for MagnifierView.xaml /// </summary> public partial class MagnifierView : DemoView { public MagnifierView() { InitializeComponent(); // Load and display the RTF file. Uri uri = new Uri( "pack://application:,,,/Xceed.Wpf.Toolkit.LiveExplorer;component/Samples/Magnifier/Resources/SampleText.rtf" ); StreamResourceInfo info = Application.GetResourceStream( uri ); using( StreamReader txtReader = new StreamReader( info.Stream ) ) { _txtContent.Text = txtReader.ReadToEnd(); } } } }
BenInCOSprings/WpfDockingWindowsApplicationTemplate
wpftoolkit-110921/Main/Source/ExtendedWPFToolkitSolution/Src/Xceed.Wpf.Toolkit.LiveExplorer/Samples/Magnifier/Views/MagnifierView.xaml.cs
C#
mit
1,404
var assert = require('assert'); var Q = require('q'); var R = require('..'); describe('pipeP', function() { function a(x) {return x + 'A';} function b(x) {return x + 'B';} it('handles promises', function() { var plusOne = function(a) {return a + 1;}; var multAsync = function(a, b) {return Q.when(a * b);}; return R.pipeP(multAsync, plusOne)(2, 3) .then(function(result) { assert.strictEqual(result, 7); }); }); it('returns a function with arity == leftmost argument', function() { function a2(x, y) { void y; return 'A2'; } function a3(x, y) { void y; return Q.when('A2'); } function a4(x, y) { void y; return 'A2'; } var f1 = R.pipeP(a, b); assert.strictEqual(f1.length, a.length); var f2 = R.pipeP(a2, b); assert.strictEqual(f2.length, a2.length); var f3 = R.pipeP(a3, b); assert.strictEqual(f3.length, a3.length); var f4 = R.pipeP(a4, b); assert.strictEqual(f4.length, a4.length); }); });
donnut/ramda
test/pipeP.js
JavaScript
mit
988
<?php namespace Illuminate\Tests\Support; use DateTime; use DateTimeInterface; use BadMethodCallException; use Carbon\CarbonImmutable; use Illuminate\Support\Carbon; use PHPUnit\Framework\TestCase; use Carbon\Carbon as BaseCarbon; class SupportCarbonTest extends TestCase { /** * @var \Illuminate\Support\Carbon */ protected $now; protected function setUp(): void { parent::setUp(); Carbon::setTestNow($this->now = Carbon::create(2017, 6, 27, 13, 14, 15, 'UTC')); } protected function tearDown(): void { Carbon::setTestNow(); Carbon::serializeUsing(null); parent::tearDown(); } public function testInstance() { $this->assertInstanceOf(DateTime::class, $this->now); $this->assertInstanceOf(DateTimeInterface::class, $this->now); $this->assertInstanceOf(BaseCarbon::class, $this->now); $this->assertInstanceOf(Carbon::class, $this->now); } public function testCarbonIsMacroableWhenNotCalledStatically() { Carbon::macro('diffInDecades', function (Carbon $dt = null, $abs = true) { return (int) ($this->diffInYears($dt, $abs) / 10); }); $this->assertSame(2, $this->now->diffInDecades(Carbon::now()->addYears(25))); } public function testCarbonIsMacroableWhenCalledStatically() { Carbon::macro('twoDaysAgoAtNoon', function () { return Carbon::now()->subDays(2)->setTime(12, 0, 0); }); $this->assertSame('2017-06-25 12:00:00', Carbon::twoDaysAgoAtNoon()->toDateTimeString()); } public function testCarbonRaisesExceptionWhenStaticMacroIsNotFound() { $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage('nonExistingStaticMacro does not exist.'); Carbon::nonExistingStaticMacro(); } public function testCarbonRaisesExceptionWhenMacroIsNotFound() { $this->expectException(BadMethodCallException::class); $this->expectExceptionMessage('nonExistingMacro does not exist.'); Carbon::now()->nonExistingMacro(); } public function testCarbonAllowsCustomSerializer() { Carbon::serializeUsing(function (Carbon $carbon) { return $carbon->getTimestamp(); }); $result = json_decode(json_encode($this->now), true); $this->assertSame(1498569255, $result); } public function testCarbonCanSerializeToJson() { $this->assertSame(class_exists(CarbonImmutable::class) ? '2017-06-27T13:14:15.000000Z' : [ 'date' => '2017-06-27 13:14:15.000000', 'timezone_type' => 3, 'timezone' => 'UTC', ], $this->now->jsonSerialize()); } public function testSetStateReturnsCorrectType() { $carbon = Carbon::__set_state([ 'date' => '2017-06-27 13:14:15.000000', 'timezone_type' => 3, 'timezone' => 'UTC', ]); $this->assertInstanceOf(Carbon::class, $carbon); } public function testDeserializationOccursCorrectly() { $carbon = new Carbon('2017-06-27 13:14:15.000000'); $serialized = 'return '.var_export($carbon, true).';'; $deserialized = eval($serialized); $this->assertInstanceOf(Carbon::class, $deserialized); } }
cviebrock/framework
tests/Support/SupportCarbonTest.php
PHP
mit
3,356
local yui_path = (...):match('(.-)[^%.]+$') local Object = require(yui_path .. 'UI.classic.classic') local FlatDropdown = Object:extend('FlatDropdown') function FlatDropdown:new(yui, settings) self.yui = yui self.x, self.y = 0, 0 self.name = settings.name self.size = settings.size or 20 self.options = settings.options self.font = love.graphics.newFont(self.yui.Theme.open_sans_regular, math.floor(self.size*0.7)) self.font:setFallbacks(love.graphics.newFont(self.yui.Theme.font_awesome_path, math.floor(self.size*0.7))) self.icon = self.yui.Theme.font_awesome['fa-sort-desc'] self.current_option = settings.current_option or 1 self.title = settings.title or '' self.drop_up = settings.drop_up self.show_dropdown = false local min_w = 0 for i = 1, #self.options do local w = self.font:getWidth(self.options[i]) + 2*self.size if w > min_w then min_w = w end end self.w = settings.w or math.max(min_w, self.font:getWidth(self.options[self.current_option] .. ' ' .. self.icon) + 2*self.size) self.h = self.font:getHeight() + math.floor(self.size)*0.7 self.main_button = self.yui.UI.Button(0, 0, self.w, self.h, { yui = self.yui, extensions = {self.yui.Theme.FlatDropdown}, font = self.font, parent = self, icon = self.icon, }) local h = self.font:getHeight() self.down_area = self.yui.UI.Scrollarea(0, 0, math.max(min_w, self.w), #self.options*h, { yui = self.yui, extensions = {self.yui.Theme.FlatDropdownScrollarea}, parent = self, size = self.size, show_scrollbars = true, }) for i, option in ipairs(self.options) do self.down_area:addElement(self.yui.UI.Button(0, 1 + (i-1)*h, math.max(min_w, self.w), h, { yui = self.yui, extensions = {self.yui.Theme.FlatDropdownButton}, font = love.graphics.newFont(self.yui.Theme.open_sans_regular, math.floor(self.size*0.7)), text = self.options[i], size = self.size, })) end self.onSelect = settings.onSelect end function FlatDropdown:update(dt) self.main_button.x, self.main_button.y = self.x, self.y if self.drop_up then self.down_area.ix, self.down_area.iy = self.x, self.y - self.down_area.h else self.down_area.ix, self.down_area.iy = self.x, self.y + self.h end for i, element in ipairs(self.down_area.elements) do if element.released and element.hot then self.current_option = i self.show_dropdown = false if self.onSelect then self:onSelect(self.options[self.current_option]) end self.down_area:update(0) self.down_area.hot = false end end if self.main_button.pressed then self.show_dropdown = not self.show_dropdown end local any_hot = false if self.main_button.hot then any_hot = true end for i, element in ipairs(self.down_area.elements) do if element.hot then any_hot = true end if i == self.current_option then element.dropdown_selected = true else element.dropdown_selected = false end end if self.main_button.input:pressed('left-click') and not any_hot then self.show_dropdown = false self.down_area:update(0) self.down_area.hot = false end for i, element in ipairs(self.down_area.elements) do if any_hot then element.dropdown_selected = false end end self.main_button:update(dt) if self.show_dropdown then self.down_area:update(dt) end if self.main_button.hot then love.mouse.setCursor(self.yui.Theme.hand_cursor) end end function FlatDropdown:draw() self.main_button:draw() end function FlatDropdown:postDraw() if self.show_dropdown then self.down_area:draw() end end return FlatDropdown
adonaac/yaoui
yaoui/FlatDropdown.lua
Lua
mit
3,846
// // MTFontMathTable.h // iosMath // // Created by Kostub Deshmukh on 8/28/13. // Copyright (C) 2013 MathChat // // This software may be modified and distributed under the terms of the // MIT license. See the LICENSE file for details. // @import Foundation; @import CoreText; @class MTFont; /** MTGlyphPart represents a part of a glyph used for assembling a large vertical or horizontal glyph. */ @interface MTGlyphPart : NSObject /// The glyph that represents this part @property (nonatomic, readonly) CGGlyph glyph; /// Full advance width/height for this part, in the direction of the extension in points. @property (nonatomic, readonly) CGFloat fullAdvance; /// Advance width/ height of the straight bar connector material at the beginning of the glyph in points. @property (nonatomic, readonly) CGFloat startConnectorLength; /// Advance width/ height of the straight bar connector material at the end of the glyph in points. @property (nonatomic, readonly) CGFloat endConnectorLength; /// If this part is an extender. If set, the part can be skipped or repeated. @property (nonatomic, readonly) BOOL isExtender; @end /** This class represents the Math table of an open type font. The math table is documented here: https://www.microsoft.com/typography/otspec/math.htm How the constants in this class affect the display is documented here: http://www.tug.org/TUGboat/tb30-1/tb94vieth.pdf @note We don't parse the math table from the open type font. Rather we parse it in python and convert it to a .plist file which is easily consumed by this class. This approach is preferable to spending an inordinate amount of time figuring out how to parse the returned NSData object using the open type rules. @remark This class is not meant to be used outside of this library. */ @interface MTFontMathTable : NSObject - (nonnull instancetype) initWithFont:(nonnull MTFont*) font mathTable:(nonnull NSDictionary*) mathTable NS_DESIGNATED_INITIALIZER; - (nonnull instancetype) init NS_UNAVAILABLE; /** MU unit in points */ @property (nonatomic, readonly) CGFloat muUnit; // Math Font Metrics from the opentype specification #pragma mark Fractions @property (nonatomic, readonly) CGFloat fractionNumeratorDisplayStyleShiftUp; // \sigma_8 in TeX @property (nonatomic, readonly) CGFloat fractionNumeratorShiftUp; // \sigma_9 in TeX @property (nonatomic, readonly) CGFloat fractionDenominatorDisplayStyleShiftDown; // \sigma_11 in TeX @property (nonatomic, readonly) CGFloat fractionDenominatorShiftDown; // \sigma_12 in TeX @property (nonatomic, readonly) CGFloat fractionNumeratorDisplayStyleGapMin; // 3 * \xi_8 in TeX @property (nonatomic, readonly) CGFloat fractionNumeratorGapMin; // \xi_8 in TeX @property (nonatomic, readonly) CGFloat fractionDenominatorDisplayStyleGapMin; // 3 * \xi_8 in TeX @property (nonatomic, readonly) CGFloat fractionDenominatorGapMin; // \xi_8 in TeX @property (nonatomic, readonly) CGFloat fractionRuleThickness; // \xi_8 in TeX @property (nonatomic, readonly) CGFloat fractionDelimiterDisplayStyleSize; // \sigma_20 in TeX @property (nonatomic, readonly) CGFloat fractionDelimiterSize; // \sigma_21 in TeX #pragma mark Stacks @property (nonatomic, readonly) CGFloat stackTopDisplayStyleShiftUp; // \sigma_8 in TeX @property (nonatomic, readonly) CGFloat stackTopShiftUp; // \sigma_10 in TeX @property (nonatomic, readonly) CGFloat stackDisplayStyleGapMin; // 7 \xi_8 in TeX @property (nonatomic, readonly) CGFloat stackGapMin; // 3 \xi_8 in TeX @property (nonatomic, readonly) CGFloat stackBottomDisplayStyleShiftDown; // \sigma_11 in TeX @property (nonatomic, readonly) CGFloat stackBottomShiftDown; // \sigma_12 in TeX #pragma mark super/sub scripts @property (nonatomic, readonly) CGFloat superscriptShiftUp; // \sigma_13, \sigma_14 in TeX @property (nonatomic, readonly) CGFloat superscriptShiftUpCramped; // \sigma_15 in TeX @property (nonatomic, readonly) CGFloat subscriptShiftDown; // \sigma_16, \sigma_17 in TeX @property (nonatomic, readonly) CGFloat superscriptBaselineDropMax; // \sigma_18 in TeX @property (nonatomic, readonly) CGFloat subscriptBaselineDropMin; // \sigma_19 in TeX @property (nonatomic, readonly) CGFloat superscriptBottomMin; // 1/4 \sigma_5 in TeX @property (nonatomic, readonly) CGFloat subscriptTopMax; // 4/5 \sigma_5 in TeX @property (nonatomic, readonly) CGFloat subSuperscriptGapMin; // 4 \xi_8 in TeX @property (nonatomic, readonly) CGFloat superscriptBottomMaxWithSubscript; // 4/5 \sigma_5 in TeX @property (nonatomic, readonly) CGFloat spaceAfterScript; #pragma mark radicals @property (nonatomic, readonly) CGFloat radicalExtraAscender; // \xi_8 in Tex @property (nonatomic, readonly) CGFloat radicalRuleThickness; // \xi_8 in Tex @property (nonatomic, readonly) CGFloat radicalDisplayStyleVerticalGap; // \xi_8 + 1/4 \sigma_5 in Tex @property (nonatomic, readonly) CGFloat radicalVerticalGap; // 5/4 \xi_8 in Tex @property (nonatomic, readonly) CGFloat radicalKernBeforeDegree; // 5 mu in Tex @property (nonatomic, readonly) CGFloat radicalKernAfterDegree; // -10 mu in Tex @property (nonatomic, readonly) CGFloat radicalDegreeBottomRaisePercent; // 60% in Tex #pragma mark Limits @property (nonatomic, readonly) CGFloat upperLimitBaselineRiseMin; // \xi_11 in TeX @property (nonatomic, readonly) CGFloat upperLimitGapMin; // \xi_9 in TeX @property (nonatomic, readonly) CGFloat lowerLimitGapMin; // \xi_10 in TeX @property (nonatomic, readonly) CGFloat lowerLimitBaselineDropMin; // \xi_12 in TeX @property (nonatomic, readonly) CGFloat limitExtraAscenderDescender; // \xi_13 in TeX, not present in OpenType so we always set it to 0. #pragma mark Underline @property (nonatomic, readonly) CGFloat underbarVerticalGap; // 3 \xi_8 in TeX @property (nonatomic, readonly) CGFloat underbarRuleThickness; // \xi_8 in TeX @property (nonatomic, readonly) CGFloat underbarExtraDescender; // \xi_8 in TeX #pragma mark Overline @property (nonatomic, readonly) CGFloat overbarVerticalGap; // 3 \xi_8 in TeX @property (nonatomic, readonly) CGFloat overbarRuleThickness; // \xi_8 in TeX @property (nonatomic, readonly) CGFloat overbarExtraAscender; // \xi_8 in TeX #pragma mark Constants @property (nonatomic, readonly) CGFloat axisHeight; // \sigma_22 in TeX @property (nonatomic, readonly) CGFloat scriptScaleDown; @property (nonatomic, readonly) CGFloat scriptScriptScaleDown; #pragma mark Accent @property (nonatomic, readonly) CGFloat accentBaseHeight; // \fontdimen5 in TeX (x-height) #pragma mark Variants /** Returns an NSArray of all the vertical variants of the glyph if any. If there are no variants for the glyph, the array contains the given glyph. */ - (nonnull NSArray<NSNumber*>*) getVerticalVariantsForGlyph:(CGGlyph) glyph; /** Returns an NSArray of all the horizontal variants of the glyph if any. If there are no variants for the glyph, the array contains the given glyph. */ - (nonnull NSArray<NSNumber*>*) getHorizontalVariantsForGlyph:(CGGlyph) glyph; /** Returns a larger vertical variant of the given glyph if any. If there is no larger version, this returns the current glyph. */ - (CGGlyph) getLargerGlyph:(CGGlyph) glyph; #pragma mark Italic Correction /** Returns the italic correction for the given glyph if any. If there isn't any this returns 0. */ - (CGFloat) getItalicCorrection:(CGGlyph) glyph; #pragma mark Accents /** Returns the adjustment to the top accent for the given glyph if any. If there isn't any this returns -1. */ - (CGFloat) getTopAccentAdjustment:(CGGlyph) glyph; #pragma mark Glyph Construction /** Minimum overlap of connecting glyphs during glyph construction */ @property (nonatomic, readonly) CGFloat minConnectorOverlap; /** Returns an array of the glyph parts to be used for constructing vertical variants of this glyph. If there is no glyph assembly defined, returns nil. */ - (nullable NSArray<MTGlyphPart*>*) getVerticalGlyphAssemblyForGlyph:(CGGlyph) glyph; @end
kostub/iosMath
iosMath/render/internal/MTFontMathTable.h
C
mit
8,951
from __future__ import print_function from .patchpipette import PatchPipette
pbmanis/acq4
acq4/devices/PatchPipette/__init__.py
Python
mit
77
# Acknowledgements This application makes use of the following third party libraries: ## TFBubbleItUp Copyright (c) 2015 Ales Kocur <ales@thefuntasty.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Generated by CocoaPods - http://cocoapods.org
beeth0ven/TFBubbleItUp
Example/Pods/Target Support Files/Pods-TFBubbleItUp_Tests/Pods-TFBubbleItUp_Tests-acknowledgements.markdown
Markdown
mit
1,228
// // LOTPlatformCompat.h // Lottie // // Created by Oleksii Pavlovskyi on 2/2/17. // Copyright (c) 2017 Airbnb. All rights reserved. // #ifndef LOTPlatformCompat_h #define LOTPlatformCompat_h #import "TargetConditionals.h" #if TARGET_OS_IPHONE || TARGET_OS_SIMULATOR #import <UIKit/UIKit.h> #else #import <AppKit/AppKit.h> #import "UIColor.h" #import "CALayer+Compat.h" #import "NSValue+Compat.h" NS_INLINE NSString *NSStringFromCGRect(CGRect rect) { return NSStringFromRect(rect); } NS_INLINE NSString *NSStringFromCGPoint(CGPoint point) { return NSStringFromPoint(point); } typedef NSEdgeInsets UIEdgeInsets; #endif #endif
NewSpring/Apollos
ios/Pods/lottie-ios/lottie-ios/Classes/MacCompatability/LOTPlatformCompat.h
C
mit
648
<?php /** * Subclass for representing a row from the 'sf_simple_forum_category' table. * * * * @package plugins.sfSimpleForumPlugin.lib.model */ class sfSimpleForumCategory extends PluginsfSimpleForumCategory { }
Symfony-Plugins/sfSimpleForum2Plugin
lib/model/sfSimpleForumCategory.php
PHP
mit
222
var _ = require('underscore'); /* A rule should contain explain and rule methods */ // TODO explain explain // TODO explain missing // TODO explain assert function assert (options, password) { return !!password && options.minLength <= password.length; } function explain(options) { if (options.minLength === 1) { return { message: 'Non-empty password required', code: 'nonEmpty' }; } return { message: 'At least %d characters in length', format: [options.minLength], code: 'lengthAtLeast' }; } module.exports = { validate: function (options) { if (!_.isObject(options)) { throw new Error('options should be an object'); } if (!_.isNumber(options.minLength) || _.isNaN(options.minLength)) { throw new Error('length expects minLength to be a non-zero number'); } return true; }, explain: explain, missing: function (options, password) { var explained = explain(options); explained.verified = !!assert(options, password); return explained; }, assert: assert };
nherzalla/ProfileX-1
node_modules/password-sheriff/lib/rules/length.js
JavaScript
mit
1,063
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>placeholders::signal_number</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../reference.html" title="Reference"> <link rel="prev" href="placeholders__iterator.html" title="placeholders::iterator"> <link rel="next" href="posix__basic_descriptor.html" title="posix::basic_descriptor"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="placeholders__iterator.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="posix__basic_descriptor.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h3 class="title"> <a name="boost_asio.reference.placeholders__signal_number"></a><a class="link" href="placeholders__signal_number.html" title="placeholders::signal_number">placeholders::signal_number</a> </h3></div></div></div> <p> <a class="indexterm" name="id1453506"></a> An argument placeholder, for use with boost::bind(), that corresponds to the signal_number argument of a handler for asynchronous functions such as <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">signal_set</span><span class="special">::</span><span class="identifier">async_wait</span></code>. </p> <pre class="programlisting"><span class="identifier">unspecified</span> <span class="identifier">signal_number</span><span class="special">;</span> </pre> <h5> <a name="boost_asio.reference.placeholders__signal_number.h0"></a> <span><a name="boost_asio.reference.placeholders__signal_number.requirements"></a></span><a class="link" href="placeholders__signal_number.html#boost_asio.reference.placeholders__signal_number.requirements">Requirements</a> </h5> <p> <span class="bold"><strong>Header: </strong></span><code class="literal">boost/asio/placeholders.hpp</code> </p> <p> <span class="bold"><strong>Convenience header: </strong></span><code class="literal">boost/asio.hpp</code> </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2012 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="placeholders__iterator.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../reference.html"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../boost_asio.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="posix__basic_descriptor.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
djsedulous/namecoind
libs/boost_1_50_0/doc/html/boost_asio/reference/placeholders__signal_number.html
HTML
mit
4,190
// // RZTCustomErrorViewController.h // RaisinToast // // Created by Adam Howitt on 1/7/15. // Copyright (c) 2015 adamhrz. All rights reserved. // #import "RZErrorMessagingViewController.h" @interface RZTCustomErrorViewController : UIViewController <RZMessagingViewController> @end
Raizlabs/RaisinToast
Example/RaisinToast/RZTCustomErrorViewController.h
C
mit
289
<?php /** * @package CleverStyle CMS * @author Nazar Mokrynskyi <nazar@mokrynskyi.com> * @copyright Copyright (c) 2011-2014, Nazar Mokrynskyi * @license MIT License, see license.txt */ namespace cs; use ArrayAccess, SimpleXMLElement; /** * False_class is used for chained calling, when some method may return false. * * Usage of class is simple, just return his instance instead of real boolean <i>false</i>. * On every call of any method or getting of any property or getting any element of array instance of the this class will be returned. * Access to anything of this class instance will be casted to boolean <i>false</i> * * Inherits SimpleXMLElement in order to be casted from object to boolean as <i>false</i> * * @property string $error */ class False_class extends SimpleXMLElement implements ArrayAccess { /** * Use this method to obtain correct instance * * @return False_class */ static function instance () { static $instance; if (!isset($instance)) { $instance = new self('<?xml version=\'1.0\'?><cs></cs>'); } return $instance; } /** * Getting any property * * @param string $item * * @return False_class */ function __get ($item) { return $this; } /** * Calling of any method * * @param string $method * @param mixed[] $params * * @return False_class */ function __call ($method, $params) { return $this; } /** * @return string */ function __toString () { return '0'; } /** * If item exists */ function offsetExists ($offset) { return false; } /** * Get item */ function offsetGet ($offset) { return $this; } /** * Set item */ public function offsetSet ($offset, $value) {} /** * Delete item */ public function offsetUnset ($offset) {} }
nazar-pc/cherrytea.org-old
core/classes/False_class.php
PHP
mit
1,775
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is JavaScript Engine testing utilities. * * The Initial Developer of the Original Code is * Mozilla Foundation. * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): Jesse Ruderman * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var gTestfile = 'regress-463259.js'; //----------------------------------------------------------------------------- var BUGNUMBER = 463259; var summary = 'Do not assert: VALUE_IS_FUNCTION(cx, fval)'; var actual = ''; var expect = ''; printBugNumber(BUGNUMBER); printStatus (summary); jit(true); try { (function(){ eval("(function(){ for (var j=0;j<4;++j) if (j==3) undefined(); })();"); })(); } catch(ex) { } jit(false); reportCompare(expect, actual, summary);
jubos/meguro
deps/spidermonkey/tests/js1_5/Regress/regress-463259.js
JavaScript
mit
2,273
$hidden=true This is a sticky notice that should appear on the homepage!
w-oertl/Luapress
tests/sticky/pages/sticky.md
Markdown
mit
74
/* * Farseer Physics Engine: * Copyright (c) 2012 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Diagnostics; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { // 1-D rained system // m (v2 - v1) = lambda // v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass. // x2 = x1 + h * v2 // 1-D mass-damper-spring system // m (v2 - v1) + h * d * v2 + h * k * // C = norm(p2 - p1) - L // u = (p2 - p1) / norm(p2 - p1) // Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) // J = [-u -cross(r1, u) u cross(r2, u)] // K = J * invM * JT // = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 /// <summary> /// A distance joint rains two points on two bodies /// to remain at a fixed distance from each other. You can view /// this as a massless, rigid rod. /// </summary> public class DistanceJoint : Joint { #region Properties/Fields /// <summary> /// The local anchor point relative to bodyA's origin. /// </summary> public Vector2 localAnchorA; /// <summary> /// The local anchor point relative to bodyB's origin. /// </summary> public Vector2 localAnchorB; public override sealed Vector2 worldAnchorA { get { return bodyA.getWorldPoint( localAnchorA ); } set { Debug.Assert( false, "You can't set the world anchor on this joint type." ); } } public override sealed Vector2 worldAnchorB { get { return bodyB.getWorldPoint( localAnchorB ); } set { Debug.Assert( false, "You can't set the world anchor on this joint type." ); } } /// <summary> /// The natural length between the anchor points. /// Manipulating the length can lead to non-physical behavior when the frequency is zero. /// </summary> public float length; /// <summary> /// The mass-spring-damper frequency in Hertz. A value of 0 /// disables softness. /// </summary> public float frequency; /// <summary> /// The damping ratio. 0 = no damping, 1 = critical damping. /// </summary> public float dampingRatio; // Solver shared float _bias; float _gamma; float _impulse; // Solver temp int _indexA; int _indexB; Vector2 _u; Vector2 _rA; Vector2 _rB; Vector2 _localCenterA; Vector2 _localCenterB; float _invMassA; float _invMassB; float _invIA; float _invIB; float _mass; #endregion internal DistanceJoint() { jointType = JointType.Distance; } /// <summary> /// This requires defining an /// anchor point on both bodies and the non-zero length of the /// distance joint. If you don't supply a length, the local anchor points /// is used so that the initial configuration can violate the constraint /// slightly. This helps when saving and loading a game. /// Warning Do not use a zero or short length. /// </summary> /// <param name="bodyA">The first body</param> /// <param name="bodyB">The second body</param> /// <param name="anchorA">The first body anchor</param> /// <param name="anchorB">The second body anchor</param> /// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param> public DistanceJoint( Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, bool useWorldCoordinates = false ) : base( bodyA, bodyB ) { jointType = JointType.Distance; if( useWorldCoordinates ) { localAnchorA = bodyA.getLocalPoint( ref anchorA ); localAnchorB = bodyB.getLocalPoint( ref anchorB ); length = ( anchorB - anchorA ).Length(); } else { localAnchorA = anchorA; localAnchorB = anchorB; length = ( base.bodyB.getWorldPoint( ref anchorB ) - base.bodyA.getWorldPoint( ref anchorA ) ).Length(); } } /// <summary> /// Get the reaction force given the inverse time step. Unit is N. /// </summary> /// <param name="invDt"></param> /// <returns></returns> public override Vector2 getReactionForce( float invDt ) { Vector2 F = ( invDt * _impulse ) * _u; return F; } /// <summary> /// Get the reaction torque given the inverse time step. /// Unit is N*m. This is always zero for a distance joint. /// </summary> /// <param name="invDt"></param> /// <returns></returns> public override float getReactionTorque( float invDt ) { return 0.0f; } internal override void initVelocityConstraints( ref SolverData data ) { _indexA = bodyA.islandIndex; _indexB = bodyB.islandIndex; _localCenterA = bodyA._sweep.localCenter; _localCenterB = bodyB._sweep.localCenter; _invMassA = bodyA._invMass; _invMassB = bodyB._invMass; _invIA = bodyA._invI; _invIB = bodyB._invI; Vector2 cA = data.positions[_indexA].c; float aA = data.positions[_indexA].a; Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; Vector2 cB = data.positions[_indexB].c; float aB = data.positions[_indexB].a; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; Rot qA = new Rot( aA ), qB = new Rot( aB ); _rA = MathUtils.mul( qA, localAnchorA - _localCenterA ); _rB = MathUtils.mul( qB, localAnchorB - _localCenterB ); _u = cB + _rB - cA - _rA; // Handle singularity. float length = _u.Length(); if( length > Settings.linearSlop ) { _u *= 1.0f / length; } else { _u = Vector2.Zero; } float crAu = MathUtils.cross( _rA, _u ); float crBu = MathUtils.cross( _rB, _u ); float invMass = _invMassA + _invIA * crAu * crAu + _invMassB + _invIB * crBu * crBu; // Compute the effective mass matrix. _mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; if( frequency > 0.0f ) { float C = length - this.length; // Frequency float omega = 2.0f * Settings.pi * frequency; // Damping coefficient float d = 2.0f * _mass * dampingRatio * omega; // Spring stiffness float k = _mass * omega * omega; // magic formulas float h = data.step.dt; _gamma = h * ( d + h * k ); _gamma = _gamma != 0.0f ? 1.0f / _gamma : 0.0f; _bias = C * h * k * _gamma; invMass += _gamma; _mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; } else { _gamma = 0.0f; _bias = 0.0f; } if( Settings.enableWarmstarting ) { // Scale the impulse to support a variable time step. _impulse *= data.step.dtRatio; Vector2 P = _impulse * _u; vA -= _invMassA * P; wA -= _invIA * MathUtils.cross( _rA, P ); vB += _invMassB * P; wB += _invIB * MathUtils.cross( _rB, P ); } else { _impulse = 0.0f; } data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override void solveVelocityConstraints( ref SolverData data ) { Vector2 vA = data.velocities[_indexA].v; float wA = data.velocities[_indexA].w; Vector2 vB = data.velocities[_indexB].v; float wB = data.velocities[_indexB].w; // Cdot = dot(u, v + cross(w, r)) Vector2 vpA = vA + MathUtils.cross( wA, _rA ); Vector2 vpB = vB + MathUtils.cross( wB, _rB ); float Cdot = Vector2.Dot( _u, vpB - vpA ); float impulse = -_mass * ( Cdot + _bias + _gamma * _impulse ); _impulse += impulse; Vector2 P = impulse * _u; vA -= _invMassA * P; wA -= _invIA * MathUtils.cross( _rA, P ); vB += _invMassB * P; wB += _invIB * MathUtils.cross( _rB, P ); data.velocities[_indexA].v = vA; data.velocities[_indexA].w = wA; data.velocities[_indexB].v = vB; data.velocities[_indexB].w = wB; } internal override bool solvePositionConstraints( ref SolverData data ) { if( frequency > 0.0f ) { // There is no position correction for soft distance constraints. return true; } var cA = data.positions[_indexA].c; var aA = data.positions[_indexA].a; var cB = data.positions[_indexB].c; var aB = data.positions[_indexB].a; Rot qA = new Rot( aA ), qB = new Rot( aB ); var rA = MathUtils.mul( qA, localAnchorA - _localCenterA ); var rB = MathUtils.mul( qB, localAnchorB - _localCenterB ); var u = cB + rB - cA - rA; var length = u.Length(); Nez.Vector2Ext.normalize( ref u ); var C = length - this.length; C = MathUtils.clamp( C, -Settings.maxLinearCorrection, Settings.maxLinearCorrection ); var impulse = -_mass * C; var P = impulse * u; cA -= _invMassA * P; aA -= _invIA * MathUtils.cross( rA, P ); cB += _invMassB * P; aB += _invIB * MathUtils.cross( rB, P ); data.positions[_indexA].c = cA; data.positions[_indexA].a = aA; data.positions[_indexB].c = cB; data.positions[_indexB].a = aB; return Math.Abs( C ) < Settings.linearSlop; } } }
Blucky87/Nez
Nez.FarseerPhysics/Farseer/Dynamics/Joints/DistanceJoint.cs
C#
mit
9,625
<?php /* WebProfilerBundle:Profiler:toolbar_js.html.twig */ class __TwigTemplate_5c613b42836f9a825aea4138cba148e6 extends Twig_Template { protected function doGetParent(array $context) { return false; } protected function doDisplay(array $context, array $blocks = array()) { // line 1 echo "<div id=\"sfwdt"; echo twig_escape_filter($this->env, $this->getContext($context, "token"), "html", null, true); echo "\" style=\"display: none\"></div> <script type=\"text/javascript\">/*<![CDATA[*/ (function () { var wdt, xhr; wdt = document.getElementById('sfwdt"; // line 5 echo twig_escape_filter($this->env, $this->getContext($context, "token"), "html", null, true); echo "'); if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } xhr.open('GET', '"; // line 11 echo twig_escape_filter($this->env, $this->env->getExtension('routing')->getPath("_wdt", array("token" => $this->getContext($context, "token"))), "html", null, true); echo "', true); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onreadystatechange = function(state) { if (4 === xhr.readyState && 200 === xhr.status && -1 !== xhr.responseText.indexOf('sf-toolbarreset')) { wdt.innerHTML = xhr.responseText; wdt.style.display = 'block'; } }; xhr.send(''); })(); /*]]>*/</script> "; } public function getTemplateName() { return "WebProfilerBundle:Profiler:toolbar_js.html.twig"; } public function isTraitable() { return false; } }
ksrinivasancomo/symfony2
app/cache/dev_old/twig/5c/61/3b42836f9a825aea4138cba148e6.php
PHP
mit
1,789
package utils import ( "io/ioutil" "net/http" "encoding/json" "fmt" "github.com/juju/errors" ) // GetRequestBody reads request and returns bytes func GetRequestBody(r *http.Request) ([]byte, error) { body, err := ioutil.ReadAll(r.Body) if err != nil { return nil, errors.Trace(err) } return body, nil } // Respond sends HTTP response func Respond(w http.ResponseWriter, data interface{}, code int) error { w.WriteHeader(code) var resp []byte var err error resp, err = json.Marshal(data) // No need HAL, if input is not valid JSON if err != nil { return errors.Trace(err) } fmt.Fprintln(w, string(resp)) return nil } // UnmarshalRequest unmarshal HTTP request to given struct func UnmarshalRequest(r *http.Request, v interface{}) error { body, err := GetRequestBody(r) if err != nil { return errors.Trace(err) } if err := json.Unmarshal(body, v); err != nil { return errors.Trace(err) } return nil }
nildev/tools
vendor/github.com/nildev/lib/utils/http.go
GO
mit
943
--- author: jeffatwood comments: true date: 2010-12-17 06:28:45+00:00 layout: post redirect_from: /2010/12/introducing-programmers-stackexchange-com hero: slug: introducing-programmers-stackexchange-com title: Introducing programmers.stackexchange.com wordpress_id: 6383 tags: - company - stackexchange - community --- One of the [more popular Stack Exchange beta sites](http://stackexchange.com/sites) just came out of beta with a final public design: ## [programmers.stackexchange.com](http://programmers.stackexchange.com) [![](https://i.stack.imgur.com/IZLAR.png)](http://programmers.stackexchange.com) Now watch closely as I read your mind. ## I don't get it! What's the difference between Programmers and Stack Overflow? I'm so glad you asked! In a nutshell, **Stack Overflow is for when you're front of your compiler or editor** working through code issues. **Programmers is for when you're in front of a whiteboard** working through higher level conceptual programming issues. _Hence the (awesome) whiteboard inspired design!_ Stated another way, Stack Overflow questions almost all have **actual source code in the questions or answers**. It's much rarer (though certainly OK) for a Programmers question to contain source code. ![](/images/wordpress/whiteboard-code.jpg) Remember, these are just guidelines, not hard and fast arbitrary rules; refer to the [first few paragraphs of the FAQ](http://programmers.stackexchange.com/help/on-topic) if you want specifics about what Programmers is for: > Programmers - Stack Exchange is for expert programmers who are interested in subjective discussions on software development. > This can include topics such as: > > > * Software engineering > * Developer testing > * Algorithm and data structure concepts > * Design patterns > * Architecture > * Development methodologies > * Quality assurance > * Software law > * Freelancing and business concerns _Editorial note: the FAQ guidance has changed significantly over the years to better reflect the sorts of conceptual questions that actually **work** - please refer to [the latest version in the help center](http://programmers.stackexchange.com/help/on-topic) before asking._ Although I fully supported this site when it was just [a baby Area 51 site proposal](http://area51.stackexchange.com/proposals/3352/not-programming-related), we've endured a lot of angst over it -- mainly because **it veered so heavily into the realm of the subjective**. It forced us to think deeply about what makes a _useful_ subjective question, which we formalized into a set of 6 guidelines in [Good Subjective, Bad Subjective](http://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective/). Constructive subjective questions … 1. inspire answers that explain “why” and “how”. 2. tend to have long, not short, answers. 3. have a constructive, fair, and impartial tone. 4. invite sharing experiences over opinions. 5. insist that opinion be backed up with facts and references. 6. are more than just mindless social fun. Ultimately, with a little extra discipline and moderation, I think the site turned out great. So, go forth and ask your **high level, conceptual, software development questions** on [programmers.stackexchange.com](http://programmers.stackexchange.com)! Just make sure they're [professional and constructive](http://blog.stackoverflow.com/2010/09/good-subjective-bad-subjective), please - refer to [help center](http://programmers.stackexchange.com/help/on-topic) for more guidance there.
dgrtwo/stack-blog
_posts/2010-12-17-introducing-programmers-stackexchange-com.markdown
Markdown
mit
3,607
# hookshot ![](http://i.cloudup.com/i_vGKjtQcY2.png) "You found the *hookshot*! It's a spring-loaded chain that you can cast out to hook things." ## Intro **hookshot** is a tiny library and companion CLI tool for handling [GitHub post-receive hooks](https://help.github.com/articles/post-receive-hooks). ## Examples ### Library ```javascript var hookshot = require('hookshot'); hookshot('refs/heads/master', 'git pull && make').listen(3000) ``` ### CLI Tool ```bash hookshot -r refs/heads/master 'git pull && make' ``` ## Usage The library exposes a single function, `hookshot()`. When called, this functions returns an express instance configured to handle post-receive hooks from GitHub. You can react to pushes to specific branches by listening to specific events on the returned instance, or by providing optional arguments to the `hookshot()` function. ```javascript hookshot() .on('refs/heads/master', 'git pull && make') .listen(3000) ``` ```javascript hookshot('refs/heads/master', 'git pull && make').listen(3000) ``` ### Actions Actions can either be shell commands or JavaScript functions. ```javascript hookshot('refs/heads/master', 'git pull && make').listen(3000) ``` ```javascript hookshot('refs/heads/master', function(info) { // do something with push info ... }).listen(3000) ``` ### Mounting to existing express servers **hookshot** can be mounted to a custom route on your existing express server: ```javascript // ... app.use('/my-github-hook', hookshot('refs/heads/master', 'git pull && make')); // ... ``` ### Special Events Special events are fired when branches/tags are created, deleted: ```javascript hookshot() .on('create', function(info) { console.log('ref ' + info.ref + ' was created.') }) .on('delete', function(info) { console.log('ref ' + info.ref + ' was deleted.') }) ``` The `push` event is fired when a push is made to any ref: ```javascript hookshot() .on('push', function(info) { console.log('ref ' + info.ref + ' was pushed.') }) ``` Finally, the `hook` event is fired for every post-receive hook that is send by GitHub. ```javascript hookshot() .on('push', function(info) { console.log('ref ' + info.ref + ' was pushed.') }) ``` ### CLI Tool A companion CLI tool is provided for convenience. To use it, install **hookshot** via npm using the `-g` flag: ```bash npm install -g hookshot ``` The CLI tool takes as argument a command to execute upon GitHub post-receive hook: ```bash hookshot 'echo "PUSHED!"' ``` You can optionally specify an HTTP port via the `-p` flag (defaults to 3000) and a ref via the `-r` flag (defaults to all refs): ```bash hookshot -r refs/heads/master -p 9001 'echo "pushed to master!"' ```
NYPL/labs.nypl.org
node_modules/hookshot/README.md
Markdown
mit
2,703
#import <Cocoa/Cocoa.h> #import "SpectacleShortcutRecorderDelegate.h" @class SpectacleShortcutManager; @interface SpectacleShortcutRecorderCell : NSCell @property (nonatomic) SpectacleShortcutRecorder *shortcutRecorder; @property (nonatomic) NSString *shortcutName; @property (nonatomic) SpectacleShortcut *shortcut; @property (nonatomic, assign) id<SpectacleShortcutRecorderDelegate> delegate; @property (nonatomic) NSArray *additionalShortcutValidators; @property (nonatomic) SpectacleShortcutManager *shortcutManager; #pragma mark - - (BOOL)resignFirstResponder; #pragma mark - - (BOOL)performKeyEquivalent:(NSEvent *)event; - (void)flagsChanged:(NSEvent *)event; @end
LEONID-DOROGIN/simply-apple
compilation/macports/office/simply-spectacle/files/Spectacle/Sources/SpectacleShortcutRecorderCell.h
C
mit
682
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_datagram_socket::send (2 of 3 overloads)</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../send.html" title="basic_datagram_socket::send"> <link rel="prev" href="overload1.html" title="basic_datagram_socket::send (1 of 3 overloads)"> <link rel="next" href="overload3.html" title="basic_datagram_socket::send (3 of 3 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../send.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload3.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.basic_datagram_socket.send.overload2"></a><a class="link" href="overload2.html" title="basic_datagram_socket::send (2 of 3 overloads)">basic_datagram_socket::send (2 of 3 overloads)</a> </h5></div></div></div> <p> Send some data on a connected socket. </p> <pre class="programlisting"><span class="keyword">template</span><span class="special">&lt;</span> <span class="keyword">typename</span> <a class="link" href="../../ConstBufferSequence.html" title="Constant buffer sequence requirements">ConstBufferSequence</a><span class="special">&gt;</span> <span class="identifier">std</span><span class="special">::</span><span class="identifier">size_t</span> <span class="identifier">send</span><span class="special">(</span> <span class="keyword">const</span> <span class="identifier">ConstBufferSequence</span> <span class="special">&amp;</span> <span class="identifier">buffers</span><span class="special">,</span> <span class="identifier">socket_base</span><span class="special">::</span><span class="identifier">message_flags</span> <span class="identifier">flags</span><span class="special">);</span> </pre> <p> This function is used to send data on the datagram socket. The function call will block until the data has been sent successfully or an error occurs. </p> <h6> <a name="boost_asio.reference.basic_datagram_socket.send.overload2.h0"></a> <span><a name="boost_asio.reference.basic_datagram_socket.send.overload2.parameters"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_datagram_socket.send.overload2.parameters">Parameters</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl> <dt><span class="term">buffers</span></dt> <dd><p> One ore more data buffers to be sent on the socket. </p></dd> <dt><span class="term">flags</span></dt> <dd><p> Flags specifying how the send call is to be made. </p></dd> </dl> </div> <h6> <a name="boost_asio.reference.basic_datagram_socket.send.overload2.h1"></a> <span><a name="boost_asio.reference.basic_datagram_socket.send.overload2.return_value"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_datagram_socket.send.overload2.return_value">Return Value</a> </h6> <p> The number of bytes sent. </p> <h6> <a name="boost_asio.reference.basic_datagram_socket.send.overload2.h2"></a> <span><a name="boost_asio.reference.basic_datagram_socket.send.overload2.exceptions"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_datagram_socket.send.overload2.exceptions">Exceptions</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl> <dt><span class="term">boost::system::system_error</span></dt> <dd><p> Thrown on failure. </p></dd> </dl> </div> <h6> <a name="boost_asio.reference.basic_datagram_socket.send.overload2.h3"></a> <span><a name="boost_asio.reference.basic_datagram_socket.send.overload2.remarks"></a></span><a class="link" href="overload2.html#boost_asio.reference.basic_datagram_socket.send.overload2.remarks">Remarks</a> </h6> <p> The send operation can only be used with a connected socket. Use the send_to function to send data on an unconnected datagram socket. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2015 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="overload1.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../send.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload3.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
yinchunlong/abelkhan-1
ext/c++/thirdpart/c++/boost/libs/asio/doc/html/boost_asio/reference/basic_datagram_socket/send/overload2.html
HTML
mit
6,331
// +build linux // +build 386 amd64 arm arm64 package ras import ( "database/sql" "fmt" "os" "strconv" "strings" "time" _ "modernc.org/sqlite" //to register SQLite driver "github.com/influxdata/telegraf" "github.com/influxdata/telegraf/plugins/inputs" ) // Ras plugin gathers and counts errors provided by RASDaemon type Ras struct { DBPath string `toml:"db_path"` Log telegraf.Logger `toml:"-"` db *sql.DB `toml:"-"` latestTimestamp time.Time `toml:"-"` cpuSocketCounters map[int]metricCounters `toml:"-"` serverCounters metricCounters `toml:"-"` } type machineCheckError struct { ID int Timestamp string SocketID int ErrorMsg string MciStatusMsg string } type metricCounters map[string]int64 const ( mceQuery = ` SELECT id, timestamp, error_msg, mcistatus_msg, socketid FROM mce_record WHERE timestamp > ? ` defaultDbPath = "/var/lib/rasdaemon/ras-mc_event.db" dateLayout = "2006-01-02 15:04:05 -0700" memoryReadCorrected = "memory_read_corrected_errors" memoryReadUncorrected = "memory_read_uncorrectable_errors" memoryWriteCorrected = "memory_write_corrected_errors" memoryWriteUncorrected = "memory_write_uncorrectable_errors" instructionCache = "cache_l0_l1_errors" instructionTLB = "tlb_instruction_errors" levelTwoCache = "cache_l2_errors" upi = "upi_errors" processorBase = "processor_base_errors" processorBus = "processor_bus_errors" internalTimer = "internal_timer_errors" smmHandlerCode = "smm_handler_code_access_violation_errors" internalParity = "internal_parity_errors" frc = "frc_errors" externalMCEBase = "external_mce_errors" microcodeROMParity = "microcode_rom_parity_errors" unclassifiedMCEBase = "unclassified_mce_errors" ) // SampleConfig returns sample configuration for this plugin. func (r *Ras) SampleConfig() string { return ` ## Optional path to RASDaemon sqlite3 database. ## Default: /var/lib/rasdaemon/ras-mc_event.db # db_path = "" ` } // Description returns the plugin description. func (r *Ras) Description() string { return "RAS plugin exposes counter metrics for Machine Check Errors provided by RASDaemon (sqlite3 output is required)." } // Start initializes connection to DB, metrics are gathered in Gather func (r *Ras) Start(telegraf.Accumulator) error { err := validateDbPath(r.DBPath) if err != nil { return err } r.db, err = connectToDB(r.DBPath) if err != nil { return err } return nil } // Stop closes any existing DB connection func (r *Ras) Stop() { if r.db != nil { err := r.db.Close() if err != nil { r.Log.Errorf("Error appeared during closing DB (%s): %v", r.DBPath, err) } } } // Gather reads the stats provided by RASDaemon and writes it to the Accumulator. func (r *Ras) Gather(acc telegraf.Accumulator) error { rows, err := r.db.Query(mceQuery, r.latestTimestamp) if err != nil { return err } defer rows.Close() for rows.Next() { mcError, err := fetchMachineCheckError(rows) if err != nil { return err } tsErr := r.updateLatestTimestamp(mcError.Timestamp) if tsErr != nil { return err } r.updateCounters(mcError) } addCPUSocketMetrics(acc, r.cpuSocketCounters) addServerMetrics(acc, r.serverCounters) return nil } func (r *Ras) updateLatestTimestamp(timestamp string) error { ts, err := parseDate(timestamp) if err != nil { return err } if ts.After(r.latestTimestamp) { r.latestTimestamp = ts } return nil } func (r *Ras) updateCounters(mcError *machineCheckError) { if strings.Contains(mcError.ErrorMsg, "No Error") { return } r.initializeCPUMetricDataIfRequired(mcError.SocketID) r.updateSocketCounters(mcError) r.updateServerCounters(mcError) } func newMetricCounters() *metricCounters { return &metricCounters{ memoryReadCorrected: 0, memoryReadUncorrected: 0, memoryWriteCorrected: 0, memoryWriteUncorrected: 0, instructionCache: 0, instructionTLB: 0, processorBase: 0, processorBus: 0, internalTimer: 0, smmHandlerCode: 0, internalParity: 0, frc: 0, externalMCEBase: 0, microcodeROMParity: 0, unclassifiedMCEBase: 0, } } func (r *Ras) updateServerCounters(mcError *machineCheckError) { if strings.Contains(mcError.ErrorMsg, "CACHE Level-2") && strings.Contains(mcError.ErrorMsg, "Error") { r.serverCounters[levelTwoCache]++ } if strings.Contains(mcError.ErrorMsg, "UPI:") { r.serverCounters[upi]++ } } func validateDbPath(dbPath string) error { pathInfo, err := os.Stat(dbPath) if os.IsNotExist(err) { return fmt.Errorf("provided db_path does not exist: [%s]", dbPath) } if err != nil { return fmt.Errorf("cannot get system information for db_path file: [%s] - %v", dbPath, err) } if mode := pathInfo.Mode(); !mode.IsRegular() { return fmt.Errorf("provided db_path does not point to a regular file: [%s]", dbPath) } return nil } func connectToDB(dbPath string) (*sql.DB, error) { return sql.Open("sqlite", dbPath) } func (r *Ras) initializeCPUMetricDataIfRequired(socketID int) { if _, ok := r.cpuSocketCounters[socketID]; !ok { r.cpuSocketCounters[socketID] = *newMetricCounters() } } func (r *Ras) updateSocketCounters(mcError *machineCheckError) { r.updateMemoryCounters(mcError) r.updateProcessorBaseCounters(mcError) if strings.Contains(mcError.ErrorMsg, "Instruction TLB") && strings.Contains(mcError.ErrorMsg, "Error") { r.cpuSocketCounters[mcError.SocketID][instructionTLB]++ } if strings.Contains(mcError.ErrorMsg, "BUS") && strings.Contains(mcError.ErrorMsg, "Error") { r.cpuSocketCounters[mcError.SocketID][processorBus]++ } if (strings.Contains(mcError.ErrorMsg, "CACHE Level-0") || strings.Contains(mcError.ErrorMsg, "CACHE Level-1")) && strings.Contains(mcError.ErrorMsg, "Error") { r.cpuSocketCounters[mcError.SocketID][instructionCache]++ } } func (r *Ras) updateProcessorBaseCounters(mcError *machineCheckError) { if strings.Contains(mcError.ErrorMsg, "Internal Timer error") { r.cpuSocketCounters[mcError.SocketID][internalTimer]++ r.cpuSocketCounters[mcError.SocketID][processorBase]++ } if strings.Contains(mcError.ErrorMsg, "SMM Handler Code Access Violation") { r.cpuSocketCounters[mcError.SocketID][smmHandlerCode]++ r.cpuSocketCounters[mcError.SocketID][processorBase]++ } if strings.Contains(mcError.ErrorMsg, "Internal parity error") { r.cpuSocketCounters[mcError.SocketID][internalParity]++ r.cpuSocketCounters[mcError.SocketID][processorBase]++ } if strings.Contains(mcError.ErrorMsg, "FRC error") { r.cpuSocketCounters[mcError.SocketID][frc]++ r.cpuSocketCounters[mcError.SocketID][processorBase]++ } if strings.Contains(mcError.ErrorMsg, "External error") { r.cpuSocketCounters[mcError.SocketID][externalMCEBase]++ r.cpuSocketCounters[mcError.SocketID][processorBase]++ } if strings.Contains(mcError.ErrorMsg, "Microcode ROM parity error") { r.cpuSocketCounters[mcError.SocketID][microcodeROMParity]++ r.cpuSocketCounters[mcError.SocketID][processorBase]++ } if strings.Contains(mcError.ErrorMsg, "Unclassified") || strings.Contains(mcError.ErrorMsg, "Internal unclassified") { r.cpuSocketCounters[mcError.SocketID][unclassifiedMCEBase]++ r.cpuSocketCounters[mcError.SocketID][processorBase]++ } } func (r *Ras) updateMemoryCounters(mcError *machineCheckError) { if strings.Contains(mcError.ErrorMsg, "Memory read error") { if strings.Contains(mcError.MciStatusMsg, "Corrected_error") { r.cpuSocketCounters[mcError.SocketID][memoryReadCorrected]++ } else { r.cpuSocketCounters[mcError.SocketID][memoryReadUncorrected]++ } } if strings.Contains(mcError.ErrorMsg, "Memory write error") { if strings.Contains(mcError.MciStatusMsg, "Corrected_error") { r.cpuSocketCounters[mcError.SocketID][memoryWriteCorrected]++ } else { r.cpuSocketCounters[mcError.SocketID][memoryWriteUncorrected]++ } } } func addCPUSocketMetrics(acc telegraf.Accumulator, cpuSocketCounters map[int]metricCounters) { for socketID, data := range cpuSocketCounters { tags := map[string]string{ "socket_id": strconv.Itoa(socketID), } fields := make(map[string]interface{}) for errorName, count := range data { fields[errorName] = count } acc.AddCounter("ras", fields, tags) } } func addServerMetrics(acc telegraf.Accumulator, counters map[string]int64) { fields := make(map[string]interface{}) for errorName, count := range counters { fields[errorName] = count } acc.AddCounter("ras", fields, map[string]string{}) } func fetchMachineCheckError(rows *sql.Rows) (*machineCheckError, error) { mcError := &machineCheckError{} err := rows.Scan(&mcError.ID, &mcError.Timestamp, &mcError.ErrorMsg, &mcError.MciStatusMsg, &mcError.SocketID) if err != nil { return nil, err } return mcError, nil } func parseDate(date string) (time.Time, error) { return time.Parse(dateLayout, date) } func init() { inputs.Add("ras", func() telegraf.Input { defaultTimestamp, _ := parseDate("1970-01-01 00:00:01 -0700") return &Ras{ DBPath: defaultDbPath, latestTimestamp: defaultTimestamp, cpuSocketCounters: map[int]metricCounters{ 0: *newMetricCounters(), }, serverCounters: map[string]int64{ levelTwoCache: 0, upi: 0, }, } }) }
m4ce/telegraf
plugins/inputs/ras/ras.go
GO
mit
9,486
using Marten.Testing.Documents; namespace Marten.Testing.Linq.Compatibility.Support { public class DefaultQueryFixture: TargetSchemaFixture { public DefaultQueryFixture() { Store = provisionStore("linq_querying"); DuplicatedFieldStore = provisionStore("duplicate_fields", o => { o.Schema.For<Target>() .Duplicate(x => x.Number) .Duplicate(x => x.Long) .Duplicate(x => x.String) .Duplicate(x => x.Date) .Duplicate(x => x.Double) .Duplicate(x => x.Flag) .Duplicate(x => x.Color); }); } public DocumentStore DuplicatedFieldStore { get; set; } public DocumentStore Store { get; set; } } }
mdissel/Marten
src/Marten.Testing/Linq/Compatibility/Support/DefaultQueryFixture.cs
C#
mit
845
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using Cake.Core; using Cake.Core.IO; namespace Cake.Common.Tools.Chocolatey { /// <summary> /// Contains Chocolatey path resolver functionality. /// </summary> public sealed class ChocolateyToolResolver : IChocolateyToolResolver { private readonly IFileSystem _fileSystem; private readonly ICakeEnvironment _environment; private IFile _cachedPath; /// <summary> /// Initializes a new instance of the <see cref="ChocolateyToolResolver" /> class. /// </summary> /// <param name="fileSystem">The file system.</param> /// <param name="environment">The environment.</param> public ChocolateyToolResolver(IFileSystem fileSystem, ICakeEnvironment environment) { _fileSystem = fileSystem; _environment = environment; if (fileSystem == null) { throw new ArgumentNullException(nameof(fileSystem)); } if (environment == null) { throw new ArgumentNullException(nameof(environment)); } } /// <inheritdoc/> public FilePath ResolvePath() { // Check if path already resolved if (_cachedPath != null && _cachedPath.Exists) { return _cachedPath.Path; } // Check if path set to environment variable var chocolateyInstallationFolder = _environment.GetEnvironmentVariable("ChocolateyInstall"); if (!string.IsNullOrWhiteSpace(chocolateyInstallationFolder)) { var envFile = _fileSystem.GetFile(PathHelper.Combine(chocolateyInstallationFolder, "choco.exe")); if (envFile.Exists) { _cachedPath = envFile; return _cachedPath.Path; } } // Last resort try path var envPath = _environment.GetEnvironmentVariable("path"); if (!string.IsNullOrWhiteSpace(envPath)) { var pathFile = envPath .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries) .Select(path => _fileSystem.GetDirectory(path)) .Where(path => path.Exists) .Select(path => path.Path.CombineWithFilePath("choco.exe")) .Select(_fileSystem.GetFile) .FirstOrDefault(file => file.Exists); if (pathFile != null) { _cachedPath = pathFile; return _cachedPath.Path; } } throw new CakeException("Could not locate choco.exe."); } } }
patriksvensson/cake
src/Cake.Common/Tools/Chocolatey/ChocolateyToolResolver.cs
C#
mit
3,004
#region Copyright // // DotNetNuke® - http://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; namespace Dnn.ExportImport.Dto.Users { public class ExportUser : BasicExportImportDto { public int RowId { get; set; } public int UserId { get; set; } public string Username { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public bool IsSuperUser { get; set; } public int? AffiliateId { get; set; } public string Email { get; set; } public string DisplayName { get; set; } public bool UpdatePassword { get; set; } public string LastIpAddress { get; set; } public bool IsDeletedPortal { get; set; } public int CreatedByUserId { get; set; } //How do we insert this value? public string CreatedByUserName { get; set; }//This could be used to find "CreatedByUserId" public DateTime? CreatedOnDate { get; set; } public int LastModifiedByUserId { get; set; } //How do we insert this value? public string LastModifiedByUserName { get; set; }//This could be used to find "LastModifiedByUserId" public DateTime? LastModifiedOnDate { get; set; } public Guid? PasswordResetToken { get; set; } public DateTime? PasswordResetExpiration { get; set; } } }
RichardHowells/Dnn.Platform
DNN Platform/Modules/DnnExportImportLibrary/Dto/Users/ExportUser.cs
C#
mit
2,486
<!doctype html> <html> <head> <meta charset="utf-8"/> </head> <body> <select multiple id="s"> <option value="1" id="one" selected>one</option> <option id="two" selected>two</option> </select> <script> alert(document.getElementById('s').value); </script> </body> </html>
110035/kissy
src/dom/sub-modules/ie/tests/manual/select.html
HTML
mit
301
<?php /* * This file is part of PhpSpec, A php toolset to drive emergent * design by specification. * * (c) Marcello Duarte <marcello.duarte@gmail.com> * (c) Konstantin Kudryashov <ever.zet@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PhpSpec\CodeGenerator\Generator; use PhpSpec\CodeGenerator\TemplateRenderer; use ReflectionMethod; class ExistingConstructorTemplate { private $templates; private $class; private $className; private $arguments; private $methodName; public function __construct(TemplateRenderer $templates, string $methodName, array $arguments, string $className, string $class) { $this->templates = $templates; $this->class = $class; $this->className = $className; $this->arguments = $arguments; $this->methodName = $methodName; } public function getContent() : string { if (!$this->numberOfConstructorArgumentsMatchMethod()) { return $this->getExceptionContent(); } return $this->getCreateObjectContent(); } private function numberOfConstructorArgumentsMatchMethod() : bool { $constructorArguments = 0; $constructor = new ReflectionMethod($this->class, '__construct'); $params = $constructor->getParameters(); foreach ($params as $param) { if (!$param->isOptional()) { $constructorArguments++; } } return $constructorArguments == \count($this->arguments); } private function getExceptionContent() : string { $values = $this->getValues(); if (!$content = $this->templates->render('named_constructor_exception', $values)) { $content = $this->templates->renderString( $this->getExceptionTemplate(), $values ); } return $content; } private function getCreateObjectContent() : string { $values = $this->getValues(true); if (!$content = $this->templates->render('named_constructor_create_object', $values)) { $content = $this->templates->renderString( $this->getCreateObjectTemplate(), $values ); } return $content; } /** * @return string[] */ private function getValues(bool $constructorArguments = false) : array { $argString = \count($this->arguments) ? '$argument'.implode(', $argument', range(1, \count($this->arguments))) : '' ; return array( '%methodName%' => $this->methodName, '%arguments%' => $argString, '%returnVar%' => '$'.lcfirst($this->className), '%className%' => $this->className, '%constructorArguments%' => $constructorArguments ? $argString : '' ); } /** * @return string */ private function getCreateObjectTemplate(): string { return file_get_contents(__DIR__.'/templates/named_constructor_create_object.template'); } /** * @return string */ private function getExceptionTemplate(): string { return file_get_contents(__DIR__.'/templates/named_constructor_exception.template'); } }
mheki/phpspec
src/PhpSpec/CodeGenerator/Generator/ExistingConstructorTemplate.php
PHP
mit
3,432
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Services.Connections { public enum ConnectorCategories { Social = 0, FileSystem = 1, Analytics = 2, Marketting = 3, Other = 4, } }
dnnsoftware/Dnn.Platform
DNN Platform/Library/Services/Connections/ConnectorCategories.cs
C#
mit
414
package run_test import ( "fmt" "net/url" "strings" "testing" "time" ) var tests Tests // Load all shared tests func init() { tests = make(map[string]Test) tests["database_commands"] = Test{ queries: []*Query{ &Query{ name: "create database should succeed", command: `CREATE DATABASE db0`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "create database with retention duration should succeed", command: `CREATE DATABASE db0_r WITH DURATION 24h REPLICATION 2 NAME db0_r_policy`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "create database with retention policy should fail with invalid name", command: `CREATE DATABASE db1 WITH NAME "."`, exp: `{"results":[{"statement_id":0,"error":"invalid name"}]}`, once: true, }, &Query{ name: "create database should error with some unquoted names", command: `CREATE DATABASE 0xdb0`, exp: `{"error":"error parsing query: found 0xdb0, expected identifier at line 1, char 17"}`, }, &Query{ name: "create database should error with invalid characters", command: `CREATE DATABASE "."`, exp: `{"results":[{"statement_id":0,"error":"invalid name"}]}`, }, &Query{ name: "create database with retention duration should error with bad retention duration", command: `CREATE DATABASE db0 WITH DURATION xyz`, exp: `{"error":"error parsing query: found xyz, expected duration at line 1, char 35"}`, }, &Query{ name: "create database with retention replication should error with bad retention replication number", command: `CREATE DATABASE db0 WITH REPLICATION xyz`, exp: `{"error":"error parsing query: found xyz, expected integer at line 1, char 38"}`, }, &Query{ name: "create database with retention name should error with missing retention name", command: `CREATE DATABASE db0 WITH NAME`, exp: `{"error":"error parsing query: found EOF, expected identifier at line 1, char 31"}`, }, &Query{ name: "show database should succeed", command: `SHOW DATABASES`, exp: `{"results":[{"statement_id":0,"series":[{"name":"databases","columns":["name"],"values":[["db0"],["db0_r"]]}]}]}`, }, &Query{ name: "create database should not error with existing database", command: `CREATE DATABASE db0`, exp: `{"results":[{"statement_id":0}]}`, }, &Query{ name: "create database should create non-existing database", command: `CREATE DATABASE db1`, exp: `{"results":[{"statement_id":0}]}`, }, &Query{ name: "create database with retention duration should error if retention policy is different", command: `CREATE DATABASE db1 WITH DURATION 24h`, exp: `{"results":[{"statement_id":0,"error":"retention policy conflicts with an existing policy"}]}`, }, &Query{ name: "create database should error with bad retention duration", command: `CREATE DATABASE db1 WITH DURATION xyz`, exp: `{"error":"error parsing query: found xyz, expected duration at line 1, char 35"}`, }, &Query{ name: "show database should succeed", command: `SHOW DATABASES`, exp: `{"results":[{"statement_id":0,"series":[{"name":"databases","columns":["name"],"values":[["db0"],["db0_r"],["db1"]]}]}]}`, }, &Query{ name: "drop database db0 should succeed", command: `DROP DATABASE db0`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "drop database db0_r should succeed", command: `DROP DATABASE db0_r`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "drop database db1 should succeed", command: `DROP DATABASE db1`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "drop database should not error if it does not exists", command: `DROP DATABASE db1`, exp: `{"results":[{"statement_id":0}]}`, }, &Query{ name: "drop database should not error with non-existing database db1", command: `DROP DATABASE db1`, exp: `{"results":[{"statement_id":0}]}`, }, &Query{ name: "show database should have no results", command: `SHOW DATABASES`, exp: `{"results":[{"statement_id":0,"series":[{"name":"databases","columns":["name"]}]}]}`, }, &Query{ name: "create database with shard group duration should succeed", command: `CREATE DATABASE db0 WITH SHARD DURATION 61m`, exp: `{"results":[{"statement_id":0}]}`, }, &Query{ name: "create database with shard group duration and duration should succeed", command: `CREATE DATABASE db1 WITH DURATION 60m SHARD DURATION 30m`, exp: `{"results":[{"statement_id":0}]}`, }, }, } tests["drop_and_recreate_database"] = Test{ db: "db0", rp: "rp0", writes: Writes{ &Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())}, }, queries: []*Query{ &Query{ name: "Drop database after data write", command: `DROP DATABASE db0`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "Recreate database", command: `CREATE DATABASE db0`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "Recreate retention policy", command: `CREATE RETENTION POLICY rp0 ON db0 DURATION 365d REPLICATION 1 DEFAULT`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "Show measurements after recreate", command: `SHOW MEASUREMENTS`, exp: `{"results":[{"statement_id":0}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Query data after recreate", command: `SELECT * FROM cpu`, exp: `{"results":[{"statement_id":0}]}`, params: url.Values{"db": []string{"db0"}}, }, }, } tests["drop_database_isolated"] = Test{ db: "db0", rp: "rp0", writes: Writes{ &Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())}, }, queries: []*Query{ &Query{ name: "Query data from 1st database", command: `SELECT * FROM cpu`, exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Query data from 1st database with GROUP BY *", command: `SELECT * FROM cpu GROUP BY *`, exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","tags":{"host":"serverA","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:00Z",23.2]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Drop other database", command: `DROP DATABASE db1`, once: true, exp: `{"results":[{"statement_id":0}]}`, }, &Query{ name: "Query data from 1st database and ensure it's still there", command: `SELECT * FROM cpu`, exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Query data from 1st database and ensure it's still there with GROUP BY *", command: `SELECT * FROM cpu GROUP BY *`, exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","tags":{"host":"serverA","region":"uswest"},"columns":["time","val"],"values":[["2000-01-01T00:00:00Z",23.2]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, }, } tests["delete_series"] = Test{ db: "db0", rp: "rp0", writes: Writes{ &Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())}, &Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=100 %d`, mustParseTime(time.RFC3339Nano, "2000-01-02T00:00:00Z").UnixNano())}, &Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=200 %d`, mustParseTime(time.RFC3339Nano, "2000-01-03T00:00:00Z").UnixNano())}, &Write{db: "db1", data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())}, }, queries: []*Query{ &Query{ name: "Show series is present", command: `SHOW SERIES`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["cpu,host=serverA,region=uswest"]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Delete series", command: `DELETE FROM cpu WHERE time < '2000-01-03T00:00:00Z'`, exp: `{"results":[{"statement_id":0}]}`, params: url.Values{"db": []string{"db0"}}, once: true, }, &Query{ name: "Show series still exists", command: `SHOW SERIES`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["cpu,host=serverA,region=uswest"]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Make sure last point still exists", command: `SELECT * FROM cpu`, exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-03T00:00:00Z","serverA","uswest",200]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Make sure data wasn't deleted from other database.", command: `SELECT * FROM cpu`, exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`, params: url.Values{"db": []string{"db1"}}, }, }, } tests["drop_and_recreate_series"] = Test{ db: "db0", rp: "rp0", writes: Writes{ &Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())}, &Write{db: "db1", data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())}, }, queries: []*Query{ &Query{ name: "Show series is present", command: `SHOW SERIES`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["cpu,host=serverA,region=uswest"]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Drop series after data write", command: `DROP SERIES FROM cpu`, exp: `{"results":[{"statement_id":0}]}`, params: url.Values{"db": []string{"db0"}}, once: true, }, &Query{ name: "Show series is gone", command: `SHOW SERIES`, exp: `{"results":[{"statement_id":0}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Make sure data wasn't deleted from other database.", command: `SELECT * FROM cpu`, exp: `{"results":[{"statement_id":0,"series":[{"name":"cpu","columns":["time","host","region","val"],"values":[["2000-01-01T00:00:00Z","serverA","uswest",23.2]]}]}]}`, params: url.Values{"db": []string{"db1"}}, }, }, } tests["drop_and_recreate_series_retest"] = Test{ db: "db0", rp: "rp0", writes: Writes{ &Write{data: fmt.Sprintf(`cpu,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano())}, }, queries: []*Query{ &Query{ name: "Show series is present again after re-write", command: `SHOW SERIES`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["cpu,host=serverA,region=uswest"]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, }, } tests["drop_series_from_regex"] = Test{ db: "db0", rp: "rp0", writes: Writes{ &Write{data: strings.Join([]string{ fmt.Sprintf(`a,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), fmt.Sprintf(`aa,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), fmt.Sprintf(`b,host=serverA,region=uswest val=23.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), fmt.Sprintf(`c,host=serverA,region=uswest val=30.2 %d`, mustParseTime(time.RFC3339Nano, "2000-01-01T00:00:00Z").UnixNano()), }, "\n")}, }, queries: []*Query{ &Query{ name: "Show series is present", command: `SHOW SERIES`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["a,host=serverA,region=uswest"],["aa,host=serverA,region=uswest"],["b,host=serverA,region=uswest"],["c,host=serverA,region=uswest"]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Drop series after data write", command: `DROP SERIES FROM /a.*/`, exp: `{"results":[{"statement_id":0}]}`, params: url.Values{"db": []string{"db0"}}, once: true, }, &Query{ name: "Show series is gone", command: `SHOW SERIES`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["b,host=serverA,region=uswest"],["c,host=serverA,region=uswest"]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Drop series from regex that matches no measurements", command: `DROP SERIES FROM /a.*/`, exp: `{"results":[{"statement_id":0}]}`, params: url.Values{"db": []string{"db0"}}, once: true, }, &Query{ name: "make sure DROP SERIES doesn't delete anything when regex doesn't match", command: `SHOW SERIES`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["b,host=serverA,region=uswest"],["c,host=serverA,region=uswest"]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Drop series with WHERE field should error", command: `DROP SERIES FROM c WHERE val > 50.0`, exp: `{"results":[{"statement_id":0,"error":"fields not supported in WHERE clause during deletion"}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "make sure DROP SERIES with field in WHERE didn't delete data", command: `SHOW SERIES`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["key"],"values":[["b,host=serverA,region=uswest"],["c,host=serverA,region=uswest"]]}]}]}`, params: url.Values{"db": []string{"db0"}}, }, &Query{ name: "Drop series with WHERE time should error", command: `DROP SERIES FROM c WHERE time > now() - 1d`, exp: `{"results":[{"statement_id":0,"error":"DROP SERIES doesn't support time in WHERE clause"}]}`, params: url.Values{"db": []string{"db0"}}, }, }, } tests["retention_policy_commands"] = Test{ db: "db0", queries: []*Query{ &Query{ name: "create retention policy with invalid name should return an error", command: `CREATE RETENTION POLICY "." ON db0 DURATION 1d REPLICATION 1`, exp: `{"results":[{"statement_id":0,"error":"invalid name"}]}`, once: true, }, &Query{ name: "create retention policy should succeed", command: `CREATE RETENTION POLICY rp0 ON db0 DURATION 1h REPLICATION 1`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "show retention policy should succeed", command: `SHOW RETENTION POLICIES ON db0`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","1h0m0s","1h0m0s",1,false]]}]}]}`, }, &Query{ name: "alter retention policy should succeed", command: `ALTER RETENTION POLICY rp0 ON db0 DURATION 2h REPLICATION 3 DEFAULT`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "show retention policy should have new altered information", command: `SHOW RETENTION POLICIES ON db0`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true]]}]}]}`, }, &Query{ name: "show retention policy should still show policy", command: `SHOW RETENTION POLICIES ON db0`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true]]}]}]}`, }, &Query{ name: "create a second non-default retention policy", command: `CREATE RETENTION POLICY rp2 ON db0 DURATION 1h REPLICATION 1`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "show retention policy should show both", command: `SHOW RETENTION POLICIES ON db0`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true],["rp2","1h0m0s","1h0m0s",1,false]]}]}]}`, }, &Query{ name: "dropping non-default retention policy succeed", command: `DROP RETENTION POLICY rp2 ON db0`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "create a third non-default retention policy", command: `CREATE RETENTION POLICY rp3 ON db0 DURATION 1h REPLICATION 1 SHARD DURATION 30m`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "create retention policy with default on", command: `CREATE RETENTION POLICY rp3 ON db0 DURATION 1h REPLICATION 1 SHARD DURATION 30m DEFAULT`, exp: `{"results":[{"statement_id":0,"error":"retention policy conflicts with an existing policy"}]}`, once: true, }, &Query{ name: "show retention policy should show both with custom shard", command: `SHOW RETENTION POLICIES ON db0`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true],["rp3","1h0m0s","1h0m0s",1,false]]}]}]}`, }, &Query{ name: "dropping non-default custom shard retention policy succeed", command: `DROP RETENTION POLICY rp3 ON db0`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "show retention policy should show just default", command: `SHOW RETENTION POLICIES ON db0`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rp0","2h0m0s","1h0m0s",3,true]]}]}]}`, }, &Query{ name: "Ensure retention policy with unacceptable retention cannot be created", command: `CREATE RETENTION POLICY rp4 ON db0 DURATION 1s REPLICATION 1`, exp: `{"results":[{"statement_id":0,"error":"retention policy duration must be at least 1h0m0s"}]}`, once: true, }, &Query{ name: "Check error when deleting retention policy on non-existent database", command: `DROP RETENTION POLICY rp1 ON mydatabase`, exp: `{"results":[{"statement_id":0}]}`, }, &Query{ name: "Ensure retention policy for non existing db is not created", command: `CREATE RETENTION POLICY rp0 ON nodb DURATION 1h REPLICATION 1`, exp: `{"results":[{"statement_id":0,"error":"database not found: nodb"}]}`, once: true, }, &Query{ name: "drop rp0", command: `DROP RETENTION POLICY rp0 ON db0`, exp: `{"results":[{"statement_id":0}]}`, }, // INF Shard Group Duration will normalize to the Retention Policy Duration Default &Query{ name: "create retention policy with inf shard group duration", command: `CREATE RETENTION POLICY rpinf ON db0 DURATION INF REPLICATION 1 SHARD DURATION 0s`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, // 0s Shard Group Duration will normalize to the Replication Policy Duration &Query{ name: "create retention policy with 0s shard group duration", command: `CREATE RETENTION POLICY rpzero ON db0 DURATION 1h REPLICATION 1 SHARD DURATION 0s`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, // 1s Shard Group Duration will normalize to the MinDefaultRetentionPolicyDuration &Query{ name: "create retention policy with 1s shard group duration", command: `CREATE RETENTION POLICY rponesecond ON db0 DURATION 2h REPLICATION 1 SHARD DURATION 1s`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "show retention policy: validate normalized shard group durations are working", command: `SHOW RETENTION POLICIES ON db0`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["rpinf","0s","168h0m0s",1,false],["rpzero","1h0m0s","1h0m0s",1,false],["rponesecond","2h0m0s","1h0m0s",1,false]]}]}]}`, }, }, } tests["retention_policy_auto_create"] = Test{ queries: []*Query{ &Query{ name: "create database should succeed", command: `CREATE DATABASE db0`, exp: `{"results":[{"statement_id":0}]}`, once: true, }, &Query{ name: "show retention policies should return auto-created policy", command: `SHOW RETENTION POLICIES ON db0`, exp: `{"results":[{"statement_id":0,"series":[{"columns":["name","duration","shardGroupDuration","replicaN","default"],"values":[["autogen","0s","168h0m0s",1,true]]}]}]}`, }, }, } } func (tests Tests) load(t *testing.T, key string) Test { test, ok := tests[key] if !ok { t.Fatalf("no test %q", key) } return test.duplicate() }
swhsiang/pathfinder
vendor/github.com/influxdata/influxdb/cmd/influxd/run/server_suite_test.go
GO
mit
21,973
<? header('Location: http://www.diridarek.com'); ?>
seriux55/loweeb00069
src/Base/DiridarekBundle/Resources/public/images/press/index.php
PHP
mit
51
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using Azure; using Azure.Core; namespace Azure.Storage.Files.DataLake { internal partial class FileSystemGetPropertiesHeaders { private readonly Response _response; public FileSystemGetPropertiesHeaders(Response response) { _response = response; } /// <summary> The data and time the filesystem was last modified. Changes to filesystem properties update the last modified time, but operations on files and directories do not. </summary> public DateTimeOffset? LastModified => _response.Headers.TryGetValue("Last-Modified", out DateTimeOffset? value) ? value : null; /// <summary> The version of the REST protocol used to process the request. </summary> public string Version => _response.Headers.TryGetValue("x-ms-version", out string value) ? value : null; /// <summary> The user-defined properties associated with the filesystem. A comma-separated list of name and value pairs in the format &quot;n1=v1, n2=v2, ...&quot;, where each value is a base64 encoded string. Note that the string may only contain ASCII characters in the ISO-8859-1 character set. </summary> public string Properties => _response.Headers.TryGetValue("x-ms-properties", out string value) ? value : null; /// <summary> A bool string indicates whether the namespace feature is enabled. If &quot;true&quot;, the namespace is enabled for the filesystem. </summary> public string NamespaceEnabled => _response.Headers.TryGetValue("x-ms-namespace-enabled", out string value) ? value : null; } }
Azure/azure-sdk-for-net
sdk/storage/Azure.Storage.Files.DataLake/src/Generated/FileSystemGetPropertiesHeaders.cs
C#
mit
1,739
/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ console.c ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Forrest Yu, 2005 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/ /* 回车键: 把光标移到第一列 换行键: 把光标前进到下一行 */ #include "type.h" #include "const.h" #include "protect.h" #include "string.h" #include "proc.h" #include "tty.h" #include "console.h" #include "global.h" #include "keyboard.h" #include "proto.h" PRIVATE void set_cursor(unsigned int position); /*======================================================================* is_current_console *======================================================================*/ PUBLIC int is_current_console(CONSOLE* p_con) { return (p_con == &console_table[nr_current_console]); } /*======================================================================* out_char *======================================================================*/ PUBLIC void out_char(CONSOLE* p_con, char ch) { u8* p_vmem = (u8*)(V_MEM_BASE + disp_pos); *p_vmem++ = ch; *p_vmem++ = DEFAULT_CHAR_COLOR; disp_pos += 2; set_cursor(disp_pos/2); } /*======================================================================* set_cursor *======================================================================*/ PRIVATE void set_cursor(unsigned int position) { disable_int(); out_byte(CRTC_ADDR_REG, CURSOR_H); out_byte(CRTC_DATA_REG, (position >> 8) & 0xFF); out_byte(CRTC_ADDR_REG, CURSOR_L); out_byte(CRTC_DATA_REG, position & 0xFF); enable_int(); }
RongbinZhuang/simpleOS
ver0/reference/chapter7/i/kernel/console.c
C
mit
1,638
// // NSDataAES.h // // Created by cheng on 15/12/25. // Copyright © 2015年 cheng. All rights reserved. // #import <Foundation/Foundation.h> extern NSString * kCryptorKey; #pragma mark - @interface NSData (AES128) @interface NSData (AES128) + (NSData *)dataFromBase64String:(NSString *)aString; - (NSString *)base64EncodedString; @end #pragma mark - @interface NSString (Encrypt) @interface NSString (Encrypt) - (NSString *)AES128EncryptWithKey:(NSString *)key; - (NSString *)AES128DecryptWithKey:(NSString *)key; - (NSString *)stringByURLEncodingStringParameter; - (NSString *)MD5String; // base64 加密 - (NSString *)base64Encrypt; // base64 解密 - (NSString *)base64Decrypt; - (NSString *)sha1; @end
Excalibur-CT/CTCoreCategory
CTCoreCategoryDemo/Pods/CTCoreCategory/CTCoreCategory/NSString/NSDataAES.h
C
mit
725
from io import BytesIO import tempfile import os import time import shutil from contextlib import contextmanager import six import sys from netlib import utils, tcp, http def treader(bytes): """ Construct a tcp.Read object from bytes. """ fp = BytesIO(bytes) return tcp.Reader(fp) @contextmanager def tmpdir(*args, **kwargs): orig_workdir = os.getcwd() temp_workdir = tempfile.mkdtemp(*args, **kwargs) os.chdir(temp_workdir) yield temp_workdir os.chdir(orig_workdir) shutil.rmtree(temp_workdir) def _check_exception(expected, actual, exc_tb): if isinstance(expected, six.string_types): if expected.lower() not in str(actual).lower(): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s" % ( repr(expected), repr(actual) ) ), exc_tb) else: if not isinstance(actual, expected): six.reraise(AssertionError, AssertionError( "Expected %s, but caught %s %s" % ( expected.__name__, actual.__class__.__name__, repr(actual) ) ), exc_tb) def raises(expected_exception, obj=None, *args, **kwargs): """ Assert that a callable raises a specified exception. :exc An exception class or a string. If a class, assert that an exception of this type is raised. If a string, assert that the string occurs in the string representation of the exception, based on a case-insenstivie match. :obj A callable object. :args Arguments to be passsed to the callable. :kwargs Arguments to be passed to the callable. """ if obj is None: return RaisesContext(expected_exception) else: try: ret = obj(*args, **kwargs) except Exception as actual: _check_exception(expected_exception, actual, sys.exc_info()[2]) else: raise AssertionError("No exception raised. Return value: {}".format(ret)) class RaisesContext(object): def __init__(self, expected_exception): self.expected_exception = expected_exception def __enter__(self): return def __exit__(self, exc_type, exc_val, exc_tb): if not exc_type: raise AssertionError("No exception raised.") else: _check_exception(self.expected_exception, exc_val, exc_tb) return True test_data = utils.Data(__name__) # FIXME: Temporary workaround during repo merge. test_data.dirname = os.path.join(test_data.dirname, "..", "test", "netlib") def treq(**kwargs): """ Returns: netlib.http.Request """ default = dict( first_line_format="relative", method=b"GET", scheme=b"http", host=b"address", port=22, path=b"/path", http_version=b"HTTP/1.1", headers=http.Headers(((b"header", b"qvalue"), (b"content-length", b"7"))), content=b"content" ) default.update(kwargs) return http.Request(**default) def tresp(**kwargs): """ Returns: netlib.http.Response """ default = dict( http_version=b"HTTP/1.1", status_code=200, reason=b"OK", headers=http.Headers(((b"header-response", b"svalue"), (b"content-length", b"7"))), content=b"message", timestamp_start=time.time(), timestamp_end=time.time(), ) default.update(kwargs) return http.Response(**default)
tdickers/mitmproxy
netlib/tutils.py
Python
mit
3,536
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #pragma once class FunctionJITRuntimeInfo { public: FunctionJITRuntimeInfo(FunctionJITRuntimeIDL * data); intptr_t GetClonedInlineCache(uint index) const; bool HasClonedInlineCaches() const; private: FunctionJITRuntimeIDL m_data; };
mrkmarron/ChakraCore
lib/Backend/FunctionJITRuntimeInfo.h
C
mit
620
#ifndef __NET_IP_WRAPPER_H #define __NET_IP_WRAPPER_H 1 #include_next <net/ip.h> #include <linux/version.h> #if LINUX_VERSION_CODE < KERNEL_VERSION(3,1,0) static inline bool ip_is_fragment(const struct iphdr *iph) { return (iph->frag_off & htons(IP_MF | IP_OFFSET)) != 0; } #endif #if LINUX_VERSION_CODE < KERNEL_VERSION(3,13,0) static inline void rpl_inet_get_local_port_range(struct net *net, int *low, int *high) { inet_get_local_port_range(low, high); } #define inet_get_local_port_range rpl_inet_get_local_port_range #endif #endif
kspviswa/dpi-enabled-ovs
ovs/datapath/linux/compat/include/net/ip.h
C
mit
554
# Configure EPEL (Extra Repository for Enterprise Linux) # Note This is the last release that will support anything before Puppet 4. # About This module basically just mimics the epel-release rpm. The same repos are enabled/disabled and the GPG key is imported. In the end you will end up with the EPEL repos configured. The following Repos will be setup and enabled by default: * epel Other repositories that will setup but disabled (as per the epel-release setup) * epel-debuginfo * epel-source * epel-testing * epel-testing-debuginfo * epel-testing-source # Usage In nearly all cases, you can simply _include epel_ or classify your nodes with the epel class. There are quite a few parameters available if you need to modify the default settings for the epel repository such as having your own mirror, an http proxy, or disable gpg checking. You can also use a puppet one-liner to get epel onto a system. puppet apply -e 'include epel' # Proxy If you have a http proxy required to access the internet, you can use either a class parameter in the _epel_ class (epel_proxy), or edit the $proxy variable in the params.pp file. By default no proxy is assumed. # Why? I am a big fan of EPEL. I actually was one of the people who helped get it going. I am also the owner of the epel-release package, so in general this module should stay fairly up to date with the official upstream package. I just got sick of coding Puppet modules and basically having an assumption that EPEL was setup or installed. I can now depend on this module instead. I realize it is fairly trivial to get EPEL setup. Every now-and-then however the path to epel-release changes because something changes in the package (mass rebuild, rpm build macros updates, etc). This module will bypass the changing URL and just setup the package mirrors. This does mean that if you are looking for RPM macros that are normally included with EPEL release, this will not have them. # Further Information * [EPEL Wiki](http://fedoraproject.org/wiki/EPEL) * [epel-release package information](http://mirrors.servercentral.net/fedora/epel/6/i386/repoview/epel-release.html) # ChangeLog ======= 1.3.0 * Add ability to disable and not define any resources from this module. This is useful if another module pulls in this module, but you already have epel managed another way. * Ability to specify your own TLS certs * repo files are now templated instead of sourced. * properly use metalink vs mirrorlist 1.2.2 * Add dep on stdlib for getvar function call 1.2.1 * Minor fix that lets facter 1.6 still work * Enforce strict variables 1.2.0 * Rework testing to use TravisCI * If you specify a baseurl, disable mirrorlist 1.1.1 * Ensure that GPG keys are using short IDs (issue #33) 1.1.0 * Default URLs to be https * Add ability to include/exclude packages 1.0.2 * Update README with usage section. * Fix regression when os_maj_version fact was required * Ready for 1.0 - replace Modulefile with metadata.json * Replace os_maj_version custom fact with operatingsystemmajrelease * Works for EPEL7 now as well. # Testing * This is commonly used on Puppet Enterprise 3.x * This was tested using Puppet 3.3.0 on Centos5/6 * This was tested using Puppet 3.1.1 on Amazon's AWS Linux * This was tested using Puppet 3.8 and Puppet 4 now as well! * Note Ruby 2.2 and Puppet 3.8 are not yet friends. * I assume it will work on any RHEL variant (Amazon Linux is debatable as a variant) * Amazon Linux compatability not promised, as EPEL doesn't always work with it. # Lifecycle * No functionality has been introduced that should break Puppet 2.6 or 2.7, but I am no longer testing these versions of Puppet as they are end-of-lifed from Puppet Labs. * This also assumes a facter of greater than 1.7.0 -- at least from a testing perspective. * I'm not actively fixing bugs for anything in facter < 2 or puppet < 3.8 ## Unit tests Install the necessary gems bundle install --path vendor --without system_tests Run the RSpec and puppet-lint tests bundle exec rake test ## System tests If you have Vagrant >=1.1.0 you can also run system tests: RSPEC_SET=centos-64-x64 bundle exec rake spec:system Available RSPEC_SET options are in .nodeset.yml # License Apache Software License 2.0 # Author/Contributors * Aaron <slapula@users.noreply.github.com> * Alex Harvey <Alex_Harvey@amp.com.au> * Chad Metcalf <metcalfc@gmail.com> * Ewoud Kohl van Wijngaarden <e.kohlvanwijngaarden@oxilion.nl> * Jeffrey Clark <jclark@nmi.com> * Joseph Swick <joseph.swick@meltwater.com> * Matthaus Owens <mlitteken@gmail.com> * Michael Hanselmann <hansmi@vshn.ch> * Michael Stahnke <stahnma@fedoraproject.org> * Michael Stahnke <stahnma@puppet.com> * Michael Stahnke <stahnma@puppetlabs.com> * Michael Stahnke <stahnma@websages.com> * Mickaël Canévet <mickael.canevet@camptocamp.com> * Nick Le Mouton <nick@noodles.net.nz> * Pro Cabales <proletaryo@gmail.com> * Proletaryo Cabales <proletaryo@gmail.com> * Riccardo Calixte <rcalixte@broadinstitute.org> * Robert Story <rstory@localhost> * Rob Nelson <rnelson0@gmail.com> * Stefan Goethals <stefan@zipkid.eu> * Tim Rupp <caphrim007@gmail.com> * Toni Schmidbauer <toni@stderr.at> * Trey Dockendorf <treydock@gmail.com> * Troy Bollinger <troy@us.ibm.com> * Vlastimil Holer <holer@ics.muni.cz> # Alternatives If you're on CentOS 7, you can just `yum install epel-release` as it's in centos-extras.
integratedfordevelopers/integrated-puphpet
puppet/modules/epel/README.md
Markdown
mit
5,511
import { rectangle } from 'leaflet'; import boundsType from './types/bounds'; import Path from './Path'; export default class Rectangle extends Path { static propTypes = { bounds: boundsType.isRequired, }; componentWillMount() { super.componentWillMount(); const { bounds, map, ...props } = this.props; this.leafletElement = rectangle(bounds, props); } componentDidUpdate(prevProps) { if (this.props.bounds !== prevProps.bounds) { this.leafletElement.setBounds(this.props.bounds); } this.setStyleIfChanged(prevProps, this.props); } }
TaiwanStat/react-leaflet
src/Rectangle.js
JavaScript
mit
584
/* GWEN Copyright (c) 2010 Facepunch Studios See license in Gwen.h */ #pragma once #ifndef GWEN_CONTROLS_CHECKBOX_H #define GWEN_CONTROLS_CHECKBOX_H #include "Gwen/Controls/Base.h" #include "Gwen/Controls/Button.h" #include "Gwen/Gwen.h" #include "Gwen/Skin.h" #include "Gwen/Controls/Symbol.h" #include "Gwen/Controls/LabelClickable.h" namespace Gwen { namespace Controls { class GWEN_EXPORT CheckBox : public Button { public: GWEN_CONTROL(CheckBox, Button); virtual void Render(Skin::Base* skin); virtual void OnPress(); virtual void SetChecked(bool Checked); virtual void Toggle() { SetChecked(!IsChecked()); } virtual bool IsChecked() { return m_bChecked; } Gwen::Event::Caller onChecked; Gwen::Event::Caller onUnChecked; Gwen::Event::Caller onCheckChanged; private: // For derived controls virtual bool AllowUncheck() { return true; } void OnCheckStatusChanged(); bool m_bChecked; }; class GWEN_EXPORT CheckBoxWithLabel : public Base { public: GWEN_CONTROL_INLINE(CheckBoxWithLabel, Base) { SetSize(200, 19); m_Checkbox = new CheckBox(this); m_Checkbox->Dock(Pos::Left); m_Checkbox->SetMargin(Margin(0, 3, 3, 3)); m_Checkbox->SetTabable(false); m_Label = new LabelClickable(this); m_Label->Dock(Pos::Fill); m_Label->onPress.Add(m_Checkbox, &CheckBox::ReceiveEventPress); m_Label->SetTabable(false); SetTabable(false); } virtual CheckBox* Checkbox() { return m_Checkbox; } virtual LabelClickable* Label() { return m_Label; } virtual bool OnKeySpace(bool bDown) { if (bDown) m_Checkbox->SetChecked(!m_Checkbox->IsChecked()); return true; } private: CheckBox* m_Checkbox; LabelClickable* m_Label; }; } // namespace Controls } // namespace Gwen #endif
MadManRises/Madgine
shared/bullet3-2.89/examples/ThirdPartyLibs/Gwen/Controls/CheckBox.h
C
mit
1,720
require 'spec_helper' require Rails.root.join('db', 'post_migrate', '20170921101004_normalize_ldap_extern_uids') describe NormalizeLdapExternUids, :migration, :sidekiq do let!(:identities) { table(:identities) } around do |example| Timecop.freeze { example.run } end before do stub_const("Gitlab::Database::MigrationHelpers::BACKGROUND_MIGRATION_BATCH_SIZE", 2) stub_const("Gitlab::Database::MigrationHelpers::BACKGROUND_MIGRATION_JOB_BUFFER_SIZE", 2) # LDAP identities (1..4).each do |i| identities.create!(id: i, provider: 'ldapmain', extern_uid: " uid = foo #{i}, ou = People, dc = example, dc = com ", user_id: i) end # Non-LDAP identity identities.create!(id: 5, provider: 'foo', extern_uid: " uid = foo 5, ou = People, dc = example, dc = com ", user_id: 5) end it 'correctly schedules background migrations' do Sidekiq::Testing.fake! do Timecop.freeze do migrate! expect(BackgroundMigrationWorker.jobs[0]['args']).to eq([described_class::MIGRATION, [1, 2]]) expect(BackgroundMigrationWorker.jobs[0]['at']).to eq(2.minutes.from_now.to_f) expect(BackgroundMigrationWorker.jobs[1]['args']).to eq([described_class::MIGRATION, [3, 4]]) expect(BackgroundMigrationWorker.jobs[1]['at']).to eq(4.minutes.from_now.to_f) expect(BackgroundMigrationWorker.jobs[2]['args']).to eq([described_class::MIGRATION, [5, 5]]) expect(BackgroundMigrationWorker.jobs[2]['at']).to eq(6.minutes.from_now.to_f) expect(BackgroundMigrationWorker.jobs.size).to eq 3 end end end it 'migrates the LDAP identities' do perform_enqueued_jobs do migrate! identities.where(id: 1..4).each do |identity| expect(identity.extern_uid).to eq("uid=foo #{identity.id},ou=people,dc=example,dc=com") end end end it 'does not modify non-LDAP identities' do perform_enqueued_jobs do migrate! identity = identities.last expect(identity.extern_uid).to eq(" uid = foo 5, ou = People, dc = example, dc = com ") end end end
iiet/iiet-git
spec/migrations/normalize_ldap_extern_uids_spec.rb
Ruby
mit
2,088
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\WebProfilerBundle\Csp; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; /** * Handles Content-Security-Policy HTTP header for the WebProfiler Bundle. * * @author Romain Neutron <imprec@gmail.com> * * @internal */ class ContentSecurityPolicyHandler { private $nonceGenerator; private $cspDisabled = false; public function __construct(NonceGenerator $nonceGenerator) { $this->nonceGenerator = $nonceGenerator; } /** * Returns an array of nonces to be used in Twig templates and Content-Security-Policy headers. * * Nonce can be provided by; * - The request - In case HTML content is fetched via AJAX and inserted in DOM, it must use the same nonce as origin * - The response - A call to getNonces() has already been done previously. Same nonce are returned * - They are otherwise randomly generated */ public function getNonces(Request $request, Response $response): array { if ($request->headers->has('X-SymfonyProfiler-Script-Nonce') && $request->headers->has('X-SymfonyProfiler-Style-Nonce')) { return [ 'csp_script_nonce' => $request->headers->get('X-SymfonyProfiler-Script-Nonce'), 'csp_style_nonce' => $request->headers->get('X-SymfonyProfiler-Style-Nonce'), ]; } if ($response->headers->has('X-SymfonyProfiler-Script-Nonce') && $response->headers->has('X-SymfonyProfiler-Style-Nonce')) { return [ 'csp_script_nonce' => $response->headers->get('X-SymfonyProfiler-Script-Nonce'), 'csp_style_nonce' => $response->headers->get('X-SymfonyProfiler-Style-Nonce'), ]; } $nonces = [ 'csp_script_nonce' => $this->generateNonce(), 'csp_style_nonce' => $this->generateNonce(), ]; $response->headers->set('X-SymfonyProfiler-Script-Nonce', $nonces['csp_script_nonce']); $response->headers->set('X-SymfonyProfiler-Style-Nonce', $nonces['csp_style_nonce']); return $nonces; } /** * Disables Content-Security-Policy. * * All related headers will be removed. */ public function disableCsp() { $this->cspDisabled = true; } /** * Cleanup temporary headers and updates Content-Security-Policy headers. * * @return array Nonces used by the bundle in Content-Security-Policy header */ public function updateResponseHeaders(Request $request, Response $response): array { if ($this->cspDisabled) { $this->removeCspHeaders($response); return []; } $nonces = $this->getNonces($request, $response); $this->cleanHeaders($response); $this->updateCspHeaders($response, $nonces); return $nonces; } private function cleanHeaders(Response $response) { $response->headers->remove('X-SymfonyProfiler-Script-Nonce'); $response->headers->remove('X-SymfonyProfiler-Style-Nonce'); } private function removeCspHeaders(Response $response) { $response->headers->remove('X-Content-Security-Policy'); $response->headers->remove('Content-Security-Policy'); $response->headers->remove('Content-Security-Policy-Report-Only'); } /** * Updates Content-Security-Policy headers in a response. */ private function updateCspHeaders(Response $response, array $nonces = []): array { $nonces = array_replace([ 'csp_script_nonce' => $this->generateNonce(), 'csp_style_nonce' => $this->generateNonce(), ], $nonces); $ruleIsSet = false; $headers = $this->getCspHeaders($response); foreach ($headers as $header => $directives) { foreach (['script-src' => 'csp_script_nonce', 'script-src-elem' => 'csp_script_nonce', 'style-src' => 'csp_style_nonce', 'style-src-elem' => 'csp_style_nonce'] as $type => $tokenName) { if ($this->authorizesInline($directives, $type)) { continue; } if (!isset($headers[$header][$type])) { if (isset($headers[$header]['default-src'])) { $headers[$header][$type] = $headers[$header]['default-src']; } else { // If there is no script-src/style-src and no default-src, no additional rules required. continue; } } $ruleIsSet = true; if (!\in_array('\'unsafe-inline\'', $headers[$header][$type], true)) { $headers[$header][$type][] = '\'unsafe-inline\''; } $headers[$header][$type][] = sprintf('\'nonce-%s\'', $nonces[$tokenName]); } } if (!$ruleIsSet) { return $nonces; } foreach ($headers as $header => $directives) { $response->headers->set($header, $this->generateCspHeader($directives)); } return $nonces; } /** * Generates a valid Content-Security-Policy nonce. */ private function generateNonce(): string { return $this->nonceGenerator->generate(); } /** * Converts a directive set array into Content-Security-Policy header. */ private function generateCspHeader(array $directives): string { return array_reduce(array_keys($directives), function ($res, $name) use ($directives) { return ('' !== $res ? $res.'; ' : '').sprintf('%s %s', $name, implode(' ', $directives[$name])); }, ''); } /** * Converts a Content-Security-Policy header value into a directive set array. */ private function parseDirectives(string $header): array { $directives = []; foreach (explode(';', $header) as $directive) { $parts = explode(' ', trim($directive)); if (\count($parts) < 1) { continue; } $name = array_shift($parts); $directives[$name] = $parts; } return $directives; } /** * Detects if the 'unsafe-inline' is prevented for a directive within the directive set. */ private function authorizesInline(array $directivesSet, string $type): bool { if (isset($directivesSet[$type])) { $directives = $directivesSet[$type]; } elseif (isset($directivesSet['default-src'])) { $directives = $directivesSet['default-src']; } else { return false; } return \in_array('\'unsafe-inline\'', $directives, true) && !$this->hasHashOrNonce($directives); } private function hasHashOrNonce(array $directives): bool { foreach ($directives as $directive) { if ('\'' !== substr($directive, -1)) { continue; } if ('\'nonce-' === substr($directive, 0, 7)) { return true; } if (\in_array(substr($directive, 0, 8), ['\'sha256-', '\'sha384-', '\'sha512-'], true)) { return true; } } return false; } /** * Retrieves the Content-Security-Policy headers (either X-Content-Security-Policy or Content-Security-Policy) from * a response. */ private function getCspHeaders(Response $response): array { $headers = []; if ($response->headers->has('Content-Security-Policy')) { $headers['Content-Security-Policy'] = $this->parseDirectives($response->headers->get('Content-Security-Policy')); } if ($response->headers->has('Content-Security-Policy-Report-Only')) { $headers['Content-Security-Policy-Report-Only'] = $this->parseDirectives($response->headers->get('Content-Security-Policy-Report-Only')); } if ($response->headers->has('X-Content-Security-Policy')) { $headers['X-Content-Security-Policy'] = $this->parseDirectives($response->headers->get('X-Content-Security-Policy')); } return $headers; } }
localheinz/symfony
src/Symfony/Bundle/WebProfilerBundle/Csp/ContentSecurityPolicyHandler.php
PHP
mit
8,478
using System; using Ionic.Zlib; using UnityEngine; namespace VoiceChat { public static class VoiceChatUtils { static void ToShortArray(this float[] input, short[] output) { if (output.Length < input.Length) { throw new System.ArgumentException("in: " + input.Length + ", out: " + output.Length); } for (int i = 0; i < input.Length; ++i) { output[i] = (short)Mathf.Clamp((int)(input[i] * 32767.0f), short.MinValue, short.MaxValue); } } static void ToFloatArray(this short[] input, float[] output, int length) { if (output.Length < length || input.Length < length) { throw new System.ArgumentException(); } for (int i = 0; i < length; ++i) { output[i] = input[i] / (float)short.MaxValue; } } static byte[] ZlibCompress(byte[] input, int length) { using (var ms = new System.IO.MemoryStream()) { using (var compressor = new Ionic.Zlib.ZlibStream(ms, CompressionMode.Compress, CompressionLevel.BestCompression)) { compressor.Write(input, 0, length); } return ms.ToArray(); } } static byte[] ZlibDecompress(byte[] input, int length) { using (var ms = new System.IO.MemoryStream()) { using (var compressor = new Ionic.Zlib.ZlibStream(ms, CompressionMode.Decompress, CompressionLevel.BestCompression)) { compressor.Write(input, 0, length); } return ms.ToArray(); } } static byte[] ALawCompress(float[] input) { byte[] output = VoiceChatBytePool.Instance.Get(); for (int i = 0; i < input.Length; ++i) { int scaled = (int)(input[i] * 32767.0f); short clamped = (short)Mathf.Clamp(scaled, short.MinValue, short.MaxValue); output[i] = NAudio.Codecs.ALawEncoder.LinearToALawSample(clamped); } return output; } static float[] ALawDecompress(byte[] input, int length) { float[] output = VoiceChatFloatPool.Instance.Get(); for (int i = 0; i < length; ++i) { short alaw = NAudio.Codecs.ALawDecoder.ALawToLinearSample(input[i]); output[i] = alaw / (float)short.MaxValue; } return output; } static NSpeex.SpeexEncoder speexEnc = new NSpeex.SpeexEncoder(NSpeex.BandMode.Narrow); static byte[] SpeexCompress(float[] input, out int length) { short[] shortBuffer = VoiceChatShortPool.Instance.Get(); byte[] encoded = VoiceChatBytePool.Instance.Get(); input.ToShortArray(shortBuffer); length = speexEnc.Encode(shortBuffer, 0, input.Length, encoded, 0, encoded.Length); VoiceChatShortPool.Instance.Return(shortBuffer); return encoded; } static float[] SpeexDecompress(NSpeex.SpeexDecoder speexDec, byte[] data, int dataLength) { float[] decoded = VoiceChatFloatPool.Instance.Get(); short[] shortBuffer = VoiceChatShortPool.Instance.Get(); speexDec.Decode(data, 0, dataLength, shortBuffer, 0, false); shortBuffer.ToFloatArray(decoded, shortBuffer.Length); VoiceChatShortPool.Instance.Return(shortBuffer); return decoded; } public static VoiceChatPacket Compress(float[] sample) { VoiceChatPacket packet = new VoiceChatPacket(); packet.Compression = VoiceChatSettings.Instance.Compression; switch (packet.Compression) { /* case VoiceChatCompression.Raw: { short[] buffer = VoiceChatShortPool.Instance.Get(); packet.Length = sample.Length * 2; sample.ToShortArray(shortBuffer); Buffer.BlockCopy(shortBuffer, 0, byteBuffer, 0, packet.Length); } break; case VoiceChatCompression.RawZlib: { packet.Length = sample.Length * 2; sample.ToShortArray(shortBuffer); Buffer.BlockCopy(shortBuffer, 0, byteBuffer, 0, packet.Length); packet.Data = ZlibCompress(byteBuffer, packet.Length); packet.Length = packet.Data.Length; } break; */ case VoiceChatCompression.Alaw: { packet.Length = sample.Length; packet.Data = ALawCompress(sample); } break; case VoiceChatCompression.AlawZlib: { byte[] alaw = ALawCompress(sample); packet.Data = ZlibCompress(alaw, sample.Length); packet.Length = packet.Data.Length; VoiceChatBytePool.Instance.Return(alaw); } break; case VoiceChatCompression.Speex: { packet.Data = SpeexCompress(sample, out packet.Length); } break; } return packet; } public static int Decompress(VoiceChatPacket packet, out float[] data) { return Decompress(null, packet, out data); } public static int Decompress(NSpeex.SpeexDecoder speexDecoder, VoiceChatPacket packet, out float[] data) { switch (packet.Compression) { /* case VoiceChatCompression.Raw: { short[9 buffer Buffer.BlockCopy(packet.Data, 0, shortBuffer, 0, packet.Length); shortBuffer.ToFloatArray(data, packet.Length / 2); return packet.Length / 2; } case VoiceChatCompression.RawZlib: { byte[] unzipedData = ZlibDecompress(packet.Data, packet.Length); Buffer.BlockCopy(unzipedData, 0, shortBuffer, 0, unzipedData.Length); shortBuffer.ToFloatArray(data, unzipedData.Length / 2); return unzipedData.Length / 2; } */ case VoiceChatCompression.Speex: { data = SpeexDecompress(speexDecoder, packet.Data, packet.Length); return data.Length; } case VoiceChatCompression.Alaw: { data = ALawDecompress(packet.Data, packet.Length); return packet.Length; } case VoiceChatCompression.AlawZlib: { byte[] alaw = ZlibDecompress(packet.Data, packet.Length); data = ALawDecompress(alaw, alaw.Length); return alaw.Length; } } data = new float[0]; return 0; } public static int ClosestPowerOfTwo(int value) { int i = 1; while (i < value) { i <<= 1; } return i; } } }
jonathanrlouie/unity-vr-livestream
TutorClient/Assets/VoiceChat/Scripts/VoiceChatUtils.cs
C#
mit
7,916
/* YUI 3.8.0pr2 (build 154) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("dd-drop-plugin",function(e,t){var n=function(e){e.node=e.host,n.superclass.constructor.apply(this,arguments)};n.NAME="dd-drop-plugin",n.NS="drop",e.extend(n,e.DD.Drop),e.namespace("Plugin"),e.Plugin.Drop=n},"3.8.0pr2",{requires:["dd-drop"]});
SHMEDIALIMITED/tallest-tower
node_modules/grunt-contrib/node_modules/grunt-contrib-yuidoc/node_modules/yuidocjs/node_modules/yui/dd-drop-plugin/dd-drop-plugin-min.js
JavaScript
mit
394
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <!-- template designed by Marco Von Ballmoos --> <title>Docs for page smarty_internal_compile_extends.php</title> <link rel="stylesheet" href="../../media/stylesheet.css" /> <meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'/> </head> <body> <div class="page-body"> <h2 class="file-name">/libs/sysplugins/smarty_internal_compile_extends.php</h2> <a name="sec-description"></a> <div class="info-box"> <div class="info-box-title">Description</div> <div class="nav-bar"> <span class="disabled">Description</span> | <a href="#sec-classes">Classes</a> </div> <div class="info-box-body"> <!-- ========== Info from phpDoc block ========= --> <p class="short-description">Smarty Internal Plugin Compile extend</p> <p class="description"><p>Compiles the {extends} tag</p></p> <ul class="tags"> <li><span class="field">author:</span> Uwe Tews</li> </ul> </div> </div> <a name="sec-classes"></a> <div class="info-box"> <div class="info-box-title">Classes</div> <div class="nav-bar"> <a href="#sec-description">Description</a> | <span class="disabled">Classes</span> </div> <div class="info-box-body"> <table cellpadding="2" cellspacing="0" class="class-table"> <tr> <th class="class-table-header">Class</th> <th class="class-table-header">Description</th> </tr> <tr> <td style="padding-right: 2em; vertical-align: top"> <a href="../../Smarty/Compiler/Smarty_Internal_Compile_Extends.html">Smarty_Internal_Compile_Extends</a> </td> <td> Smarty Internal Plugin Compile extend Class </td> </tr> </table> </div> </div> <p class="notes" id="credit"> Documentation generated on Sat, 24 Sep 2011 20:23:41 +0200 by <a href="http://www.phpdoc.org" target="_blank">phpDocumentor 1.4.1</a> </p> </div></body> </html>
YuheiNakasaka/sharememo
vendor/smarty/smarty/development/Smarty3Doc/Smarty/Compiler/_libs---sysplugins---smarty_internal_compile_extends.php.html
HTML
mit
2,140
/* This file was generated by SableCC (http://www.sablecc.org/). */ package com.bju.cps450.node; import com.bju.cps450.analysis.*; @SuppressWarnings("nls") public final class TPlus extends Token { public TPlus() { super.setText("+"); } public TPlus(int line, int pos) { super.setText("+"); setLine(line); setPos(pos); } @Override public Object clone() { return new TPlus(getLine(), getPos()); } @Override public void apply(Switch sw) { ((Analysis) sw).caseTPlus(this); } @Override public void setText(@SuppressWarnings("unused") String text) { throw new RuntimeException("Cannot change TPlus text."); } }
asdfzt/CPS450-MiniJava
MiniJavaParserWithAST/gen-src/com/bju/cps450/node/TPlus.java
Java
mit
738
# https://github.com/plataformatec/devise#test-helpers RSpec.configure do |config| config.include Devise::TestHelpers, :type => :controller end
cngondo/bestmix
server/spec/support/devise.rb
Ruby
mit
146
<?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>parse_extension_args (OpenID::SReg::Request)</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" href="../../../.././rdoc-style.css" type="text/css" media="screen" /> </head> <body class="standalone-code"> <pre><span class="ruby-comment cmt"># File lib/openid/extensions/sreg.rb, line 126</span> <span class="ruby-keyword kw">def</span> <span class="ruby-identifier">parse_extension_args</span>(<span class="ruby-identifier">args</span>, <span class="ruby-identifier">strict</span> = <span class="ruby-keyword kw">false</span>) <span class="ruby-identifier">required_items</span> = <span class="ruby-identifier">args</span>[<span class="ruby-value str">'required'</span>] <span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">required_items</span>.<span class="ruby-identifier">nil?</span> <span class="ruby-keyword kw">or</span> <span class="ruby-identifier">required_items</span>.<span class="ruby-identifier">empty?</span> <span class="ruby-identifier">required_items</span>.<span class="ruby-identifier">split</span>(<span class="ruby-value str">','</span>).<span class="ruby-identifier">each</span>{<span class="ruby-operator">|</span><span class="ruby-identifier">field_name</span><span class="ruby-operator">|</span> <span class="ruby-keyword kw">begin</span> <span class="ruby-identifier">request_field</span>(<span class="ruby-identifier">field_name</span>, <span class="ruby-keyword kw">true</span>, <span class="ruby-identifier">strict</span>) <span class="ruby-keyword kw">rescue</span> <span class="ruby-constant">ArgumentError</span> <span class="ruby-identifier">raise</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">strict</span> <span class="ruby-keyword kw">end</span> } <span class="ruby-keyword kw">end</span> <span class="ruby-identifier">optional_items</span> = <span class="ruby-identifier">args</span>[<span class="ruby-value str">'optional'</span>] <span class="ruby-keyword kw">unless</span> <span class="ruby-identifier">optional_items</span>.<span class="ruby-identifier">nil?</span> <span class="ruby-keyword kw">or</span> <span class="ruby-identifier">optional_items</span>.<span class="ruby-identifier">empty?</span> <span class="ruby-identifier">optional_items</span>.<span class="ruby-identifier">split</span>(<span class="ruby-value str">','</span>).<span class="ruby-identifier">each</span>{<span class="ruby-operator">|</span><span class="ruby-identifier">field_name</span><span class="ruby-operator">|</span> <span class="ruby-keyword kw">begin</span> <span class="ruby-identifier">request_field</span>(<span class="ruby-identifier">field_name</span>, <span class="ruby-keyword kw">false</span>, <span class="ruby-identifier">strict</span>) <span class="ruby-keyword kw">rescue</span> <span class="ruby-constant">ArgumentError</span> <span class="ruby-identifier">raise</span> <span class="ruby-keyword kw">if</span> <span class="ruby-identifier">strict</span> <span class="ruby-keyword kw">end</span> } <span class="ruby-keyword kw">end</span> <span class="ruby-ivar">@policy_url</span> = <span class="ruby-identifier">args</span>[<span class="ruby-value str">'policy_url'</span>] <span class="ruby-keyword kw">end</span></pre> </body> </html>
agrimm/eol
vendor/gems/ruby-openid-2.0.4/doc/classes/OpenID/SReg/Request.src/M000089.html
HTML
mit
3,728
class ChangeOrderAttributes < ActiveRecord::Migration def up change_column_default :orders, :front_end_change, nil rename_column :orders, :front_end_change, :change remove_column :orders, :refunded remove_column :orders, :total_is_locked remove_column :orders, :tax_is_locked remove_column :orders, :subtotal_is_locked remove_column :orders, :cash_register_daily_id remove_column :orders, :by_card remove_column :orders, :refunded_at remove_column :orders, :refunded_by remove_column :orders, :refunded_by_type remove_column :orders, :discount_amount remove_column :orders, :tax_free change_column_default :orders, :qnr, nil end def down end end
a0ali0taha/pos
vendor/db/migrate/20130701104221_change_order_attributes.rb
Ruby
mit
711
# extension imports from _NetworKit import PageRankNibble, GCE
fmaschler/networkit
networkit/scd.py
Python
mit
62
//= require d3/d3 //= require jquery.qtip.min //= require simple_statistics gfw.ui.model.CountriesEmbedOverview = cdb.core.Model.extend({ defaults: { graph: 'total_loss', years: true, class: null } }); gfw.ui.view.CountriesEmbedOverview = cdb.core.View.extend({ el: document.body, events: { 'click .graph_tab': '_updateGraph' }, initialize: function() { this.model = new gfw.ui.model.CountriesEmbedOverview(); this.$graph = $('.overview_graph__area'); this.$years = $('.overview_graph__years'); var m = this.m = 40, w = this.w = this.$graph.width()+(m*2), h = this.h = this.$graph.height(), vertical_m = this.vertical_m = 20; this.x_scale = d3.scale.linear() .range([m, w-m]) .domain([2001, 2012]); this.grid_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain([0, 1]); this.model.bind('change:graph', this._redrawGraph, this); this.model.bind('change:years', this._toggleYears, this); this.model.bind('change:class', this._toggleClass, this); this._initViews(); }, _initViews: function() { this.tooltip = d3.select('body') .append('div') .attr('class', 'tooltip'); this._drawYears(); this._drawGraph(); }, _toggleYears: function() { var that = this; if(this.model.get('years') === false) { this.$years.slideUp(250, function() { $('.overview_graph__axis').slideDown(); }); } else { $('.overview_graph__axis').slideUp(250, function() { that.$years.slideDown(); }); } }, _showYears: function() { if (!this.model.get('years')) { this.model.set('years', true); } }, _hideYears: function() { if (this.model.get('years')) { this.model.set('years', false); } }, _updateGraph: function(e) { e.preventDefault(); var $target = $(e.target).closest('.graph_tab'), graph = $target.attr('data-slug'); if (graph === this.model.get('graph')) { return; } else { $('.graph_tab').removeClass('selected'); $target.addClass('selected'); this.model.set('graph', graph); } }, _redrawGraph: function() { var graph = this.model.get('graph'); $('.overview_graph__title').html(config.GRAPHS[graph].title); $('.overview_graph__legend p').html(config.GRAPHS[graph].subtitle); $('.overview_graph__legend .info').attr('data-source', graph); this.$graph.find('.'+graph); this.$graph.find('.chart').hide(); this.$graph.find('.'+graph).fadeIn(); this._drawGraph(); }, _drawYears: function() { var markup_years = ''; for (var y = 2001; y<=2012; y += 1) { var y_ = this.x_scale(y); if (y === 2001) { y_ -= 25; } else if (y === 2012) { y_ -= 55; } else { y_ -= 40; } markup_years += '<span class="year" style="left:'+y_+'px">'+y+'</span>'; } this.$years.html(markup_years); }, _drawGraph: function() { var that = this; var w = this.w, h = this.h, vertical_m = this.vertical_m, m = this.m, x_scale = this.x_scale; var grid_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain([1, 0]); d3.select('#chart').remove(); var svg = d3.select('.overview_graph__area') .append('svg:svg') .attr('id', 'chart') .attr('width', w) .attr('height', h); // grid svg.selectAll('line.grid_h') .data(grid_scale.ticks(4)) .enter() .append('line') .attr({ 'class': 'grid grid_h', 'x1': 0, 'x2': w, 'y1': function(d, i) { return grid_scale(d); }, 'y2': function(d, i) { return grid_scale(d); } }); svg.selectAll('line.grid_v') .data(x_scale.ticks(12)) .enter() .append('line') .attr({ 'class': 'grid grid_v', 'y1': h, 'y2': 0, 'x1': function(d) { return x_scale(d); }, 'x2': function(d) { return x_scale(d); } }); var gradient = svg.append('svg:defs') .append('svg:linearGradient') .attr('id', 'gradient') .attr('x1', '0%') .attr('y1', '0%') .attr('x2', '0%') .attr('y2', '100%') .attr('spreadMethod', 'pad'); gradient.append('svg:stop') .attr('offset', '0%') .attr('stop-color', '#CA46FF') .attr('stop-opacity', .5); gradient.append('svg:stop') .attr('offset', '100%') .attr('stop-color', '#D24DFF') .attr('stop-opacity', 1); if (this.model.get('graph') === 'total_loss') { this._showYears(); svg.append('text') .attr('class', 'axis') .attr('id', 'axis_y') .text('Mha') .attr('x', -h/2) .attr('y', 30) .attr('transform', 'rotate(-90)'); var sql = 'SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(y'+y+') as y'+y+', ' } sql += 'SUM(y2012) as y2012, (SELECT SUM(y2001_y2012)\ FROM countries_gain) as gain\ FROM loss_gt_0'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(error, json) { var data = json.rows[0]; var data_ = [], gain = null; _.each(data, function(val, key) { if (key === 'gain') { gain = val/12; } else { data_.push({ 'year': key.replace('y',''), 'value': val }); } }); var y_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain([d3.max(data_, function(d) { return d.value; }), 0]); // area var area = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(h) .y1(function(d) { return y_scale(d.value); }); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area) .style('fill', 'url(#gradient)'); // circles svg.selectAll('circle') .data(data_) .enter() .append('svg:circle') .attr('class', 'linedot') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); var data_gain_ = [ { year: 2001, value: gain }, { year: 2012, value: gain } ]; // line svg.selectAll('line.overview_line') .data(data_gain_) .enter() .append('line') .attr({ 'class': 'overview_line', 'x1': m, 'x2': w-m, 'y1': function(d) { return y_scale(gain); }, 'y2': function(d) { return y_scale(gain); } }); svg.selectAll('circle.gain') .data(data_gain_) .enter() .append('svg:circle') .attr('class', 'linedot gain') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>2001-2012</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip gain_tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); }); } else if (this.model.get('graph') === 'percent_loss') { this._showYears(); svg.append('text') .attr('class', 'axis') .attr('id', 'axis_y') .text('%') .attr('x', -h/2) .attr('y', 30) .attr('transform', 'rotate(-90)'); var sql = 'WITH loss as (SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(y'+y+') as sum_loss_y'+y+', '; } sql += 'SUM(y2012) as sum_loss_y2012\ FROM loss_gt_25), extent as (SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(y'+y+') as sum_extent_y'+y+', '; } sql += 'SUM(y2012) as sum_extent_y2012\ FROM extent_gt_25)\ SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'sum_loss_y'+y+'/sum_extent_y'+y+' as percent_loss_'+y+', '; } sql += 'sum_loss_y2012/sum_extent_y2012 as percent_loss_2012, (SELECT SUM(y2001_y2012)/('; for(var y = 2001; y < 2012; y++) { sql += 'sum_extent_y'+y+' + '; } sql += 'sum_extent_y2012)\ FROM countries_gain) as gain\ FROM loss, extent'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { var data = json.rows[0]; var data_ = [], gain = null; _.each(data, function(val, key) { if (key === 'gain') { gain = val/12; } else { data_.push({ 'year': key.replace('percent_loss_',''), 'value': val }); } }); var y_scale = grid_scale; // area var area = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(h) .y1(function(d) { return y_scale(d.value*100); }); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area) .style('fill', 'url(#gradient)'); // circles svg.selectAll('circle') .data(data_) .enter() .append('svg:circle') .attr('class', 'linedot') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value*100); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+parseFloat(d.value*100).toFixed(2)+' %'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); var data_gain_ = [ { year: 2001, value: gain }, { year: 2012, value: gain } ]; // line svg.selectAll('line.overview_line') .data(data_gain_) .enter() .append('line') .attr({ 'class': 'overview_line', 'x1': m, 'x2': w-m, 'y1': function(d) { return y_scale(gain*100); }, 'y2': function(d) { return y_scale(gain*100); } }); // circles svg.selectAll('circle.gain') .data(data_gain_) .enter() .append('svg:circle') .attr('class', 'linedot gain') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value*100); }) .attr('r', 6) .attr('name', function(d) { return '<span>2001-2012</span>'+parseFloat(d.value*100).toFixed(2)+' %'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip gain_tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); }); } else if (this.model.get('graph') === 'total_extent') { this._showYears(); svg.append('text') .attr('class', 'axis') .attr('id', 'axis_y') .text('Mha') .attr('x', -h/2) .attr('y', 30) .attr('transform', 'rotate(-90)'); var gradient_extent = svg.append('svg:defs') .append('svg:linearGradient') .attr('id', 'gradient_extent') .attr('x1', '0%') .attr('y1', '0%') .attr('x2', '0%') .attr('y2', '100%') .attr('spreadMethod', 'pad'); gradient_extent.append('svg:stop') .attr('offset', '0%') .attr('stop-color', '#98BD17') .attr('stop-opacity', .5); gradient_extent.append('svg:stop') .attr('offset', '100%') .attr('stop-color', '#98BD17') .attr('stop-opacity', 1); var sql = 'SELECT '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(loss.y'+y+') as loss_y'+y+', '; } sql += 'SUM(loss.y2012) as loss_y2012, '; for(var y = 2001; y < 2012; y++) { sql += 'SUM(extent.y'+y+') as extent_y'+y+', '; } sql += 'SUM(extent.y2012) as extent_y2012\ FROM loss_gt_25 loss, extent_gt_25 extent\ WHERE loss.iso = extent.iso'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { var data = json.rows[0]; var data_ = [], data_loss_ = [], data_extent_ = []; _.each(data, function(val, key) { var year = key.split('_y')[1]; var obj = _.find(data_, function(obj) { return obj.year == year; }); if(obj === undefined) { data_.push({ 'year': year }); } if (key.indexOf('loss_y') != -1) { data_loss_.push({ 'year': key.split('_y')[1], 'value': val }); } if (key.indexOf('extent_y') != -1) { data_extent_.push({ 'year': key.split('extent_y')[1], 'value': val }); } }); _.each(data_, function(val) { var loss = _.find(data_loss_, function(obj) { return obj.year == val.year; }), extent = _.find(data_extent_, function(obj) { return obj.year == val.year; }); _.extend(val, { 'loss': loss.value, 'extent': extent.value }); }); var domain = [d3.max(data_, function(d) { return d.extent; }), 0]; var y_scale = d3.scale.linear() .range([vertical_m, h-vertical_m]) .domain(domain); // area var area_loss = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(h) .y1(function(d) { return y_scale(d.loss); }); var area_extent = d3.svg.area() .x(function(d) { return x_scale(d.year); }) .y0(function(d) { return y_scale(d.extent); }) .y1(function(d) { return y_scale(d.loss); }); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area_loss) .style('fill', 'url(#gradient)'); svg.append('path') .datum(data_) .attr('class', 'area') .attr('d', area_extent) .style('fill', 'url(#gradient_extent)'); // circles svg.selectAll('circle') .data(data_loss_) .enter() .append('svg:circle') .attr('class', 'linedot') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); svg.selectAll('circle.gain') .data(data_extent_) .enter() .append('svg:circle') .attr('class', 'linedot gain') .attr('cx', function(d) { return x_scale(d.year); }) .attr('cy', function(d){ return y_scale(d.value); }) .attr('r', 6) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .on('mouseover', function(d) { that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', $(this).offset().top-100+'px') .style('left', $(this).offset().left-$('.tooltip').width()/2-4+'px') .attr('class', 'tooltip gain_tooltip'); d3.select(this) .transition() .duration(100) .attr('r', 7); // TODO: highlighting the legend }) .on('mouseout', function(d) { that.tooltip.style('visibility', 'hidden'); d3.select(this) .transition() .duration(100) .attr('r', 6); // TODO: highlighting the legend }); }); } else if (this.model.get('graph') === 'ratio') { this._hideYears(); svg.append('text') .attr('class', 'axis light') .attr('id', 'axis_y') .text('Cover gain 2001-2012') .attr('x', -(h/2)) .attr('y', 30) .attr('transform', 'rotate(-90)'); var shadow = svg.append('svg:defs') .append('svg:filter') .attr('id', 'shadow') .attr('x', '0%') .attr('y', '0%') .attr('width', '200%') .attr('height', '200%') shadow.append('svg:feOffset') .attr('result', 'offOut') .attr('in', 'SourceAlpha') .attr('dx', 0) .attr('dy', 0); shadow.append('svg:feGaussianBlur') .attr('result', 'blurOut') .attr('in', 'offOut') .attr('stdDeviation', 1); shadow.append('svg:feBlend') .attr('in', 'SourceGraphic') .attr('in2', 'blurOut') .attr('mode', 'normal'); var sql = 'WITH loss as (SELECT iso, SUM('; for(var y = 2001; y < 2012; y++) { sql += 'loss.y'+y+' + '; } sql += 'loss.y2012) as sum_loss\ FROM loss_gt_50 loss\ GROUP BY iso), gain as (SELECT g.iso, SUM(y2001_y2012) as sum_gain\ FROM countries_gain g, loss_gt_50 loss\ WHERE loss.iso = g.iso\ GROUP BY g.iso), ratio as ('; sql += 'SELECT c.iso, c.name, c.enabled, loss.sum_loss as loss, gain.sum_gain as gain, loss.sum_loss/gain.sum_gain as ratio\ FROM loss, gain, gfw2_countries c\ WHERE sum_gain IS NOT null\ AND NOT sum_gain = 0\ AND c.iso = gain.iso\ AND c.iso = loss.iso\ ORDER BY loss.sum_loss DESC\ LIMIT 50) '; sql += 'SELECT *\ FROM ratio\ WHERE ratio IS NOT null\ ORDER BY ratio DESC'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { var data = json.rows; var log_m = 50; var y_scale = d3.scale.linear() .range([h, 0]) .domain([0, d3.max(data, function(d) { return d.gain; })]); var x_scale = d3.scale.linear() .range([m, w-m]) .domain([d3.min(data, function(d) { return d.loss; }), d3.max(data, function(d) { return d.loss; })]); var x_log_scale = d3.scale.log() .range([m, w-m]) .domain([d3.min(data, function(d) { return d.loss; }), d3.max(data, function(d) { return d.loss; })]); var y_log_scale = d3.scale.log() .range([h-log_m, m]) .domain([d3.min(data, function(d) { return d.gain; }), d3.max(data, function(d) { return d.gain; })]); var r_scale = d3.scale.linear() .range(['yellow', 'red']) .domain([0, d3.max(data, function(d) { return d.ratio; })]); that.linearRegressionLine(svg, json, x_scale, y_scale); // circles w/ magic numbers :( var circle_attr = { 'cx': function(d) { return d.loss >= 1 ? x_log_scale(d.loss) : m; }, 'cy': function(d) { return d.gain >= 1 ? y_log_scale(d.gain) : h-log_m; }, 'r': '5', 'name': function(d) { return d.name; }, 'class': function(d) { return d.enabled ? 'ball ball_link' : 'ball ball_nolink'; } }; var data_ = [], data_link_ = [], exclude = ['Saint Barthélemy', 'Saint Kitts and Nevis', 'Saint Pierre and Miquelon', 'Virgin Islands', 'Oman', 'Gibraltar', 'Saudi Arabia', 'French Polynesia', 'Samoa', 'Western Sahara', 'United Arab Emirates']; _.each(data, function(row) { if (!_.contains(exclude, row.name)) { if (row.enabled === true) { data_link_.push(row); } else { data_.push(row); } } }); var circles_link = svg.selectAll('circle.ball_link') .data(data_link_) .enter() .append('a') .attr('xlink:href', function(d) { return '/country/' + d.iso }) .attr('target', '_blank') .append('svg:circle') .attr(circle_attr) .style('fill', function(d) { return r_scale(d.ratio); }) .style('filter', 'url(#shadow)') .on('mouseover', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseenter', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseout', function() { d3.select(d3.event.target) .transition() .attr('r', '5') .style('opacity', .8); that.tooltip.style('visibility', 'hidden'); }); var circles = svg.selectAll('circle.ball_nolink') .data(data_) .enter() .append('svg:circle') .attr(circle_attr) .style('filter', 'url(#shadow)') .on('mouseover', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseenter', function() { d3.select(d3.event.target) .transition() .attr('r', '7') .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2; that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)+'px') .attr('class', 'tooltip gain_tooltip'); }) .on('mouseout', function() { d3.select(d3.event.target) .transition() .attr('r', '5') .style('opacity', .8); that.tooltip.style('visibility', 'hidden'); }); }); } else if (this.model.get('graph') === 'domains') { this._showYears(); var sql = 'SELECT name, '; for(var y = 2001; y < 2012; y++) { sql += 'y'+y+', ' } sql += 'y2012, GREATEST(' for(var y = 2001; y < 2012; y++) { sql += 'y'+y+', ' } sql += 'y2012) as max\ FROM countries_domains'; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(error, json) { var data = json.rows; var r_scale = d3.scale.linear() .range([5, 30]) // max ball radius .domain([0, d3.max(data, function(d) { return d.max; })]) for(var j = 0; j < data.length; j++) { var data_ = [], domain = ''; _.each(data[j], function(val, key) { if (key !== 'max') { if (key === 'name') { domain = val.toLowerCase(); } else { data_.push({ 'year': key.replace('y',''), 'value': val }); } } }); svg.append('text') .attr('class', 'label') .attr('id', 'label_'+domain) .text(domain) .attr('x', function() { var l = x_scale(2002) - $(this).width()/2; return l; }) .attr('y', (h/5)*(j+.6)); var circle_attr = { 'cx': function(d, i) { return x_scale(2001 + i); }, 'cy': function(d) { return (h/5)*(j+1); }, 'r': function(d) { return r_scale(d.value); }, 'class': function(d) { return 'ball'; } }; svg.selectAll('circle.domain_'+domain) .data(data_) .enter() .append('svg:circle') .attr(circle_attr) .attr('data-slug', domain) .attr('name', function(d) { return '<span>'+d.year+'</span>'+formatNumber(parseFloat(d.value/1000000).toFixed(1))+' Mha'; }) .style('fill', function(d) { return config.GRAPHCOLORS[domain]; }) .on('mouseover', function() { d3.select(d3.event.target) .transition() .attr('r', function(d) { return circle_attr.r(d) + 2; }) .style('opacity', 1); var t = $(this).offset().top - 100, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2, slug = $(this).attr('data-slug'); that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip') .attr('data-slug', 'tooltip') .style('color', function() { if (slug === 'subtropical') { return '#FFC926' } else { return config.GRAPHCOLORS[slug]; } }); }) .on('mouseenter', function() { d3.select(d3.event.target) .transition() .attr('r', function(d) { return circle_attr.r(d) + 2; }) .style('opacity', 1); var t = $(this).offset().top - 80, l = $(this).offset().left, r = $(this).attr('r'), tip = $('.tooltip').width()/2, slug = $(this).attr('data-slug'); that.tooltip.html($(this).attr('name')) .style('visibility', 'visible') .style('top', parseInt(t, 10)+'px') .style('left', parseInt(l, 10)+parseInt(r, 10)-parseInt(tip, 10)-10+'px') .attr('class', 'tooltip') .attr('data-slug', 'tooltip') .style('color', function() { if (domain === 'subtropical') { return config.GRAPHCOLORS[domain]; } }); }) .on('mouseout', function() { d3.select(d3.event.target) .transition() .attr('r', function(d) { return circle_attr.r(d); }) .style('opacity', .8); that.tooltip .style('color', '') .style('visibility', 'hidden'); }); } }); } }, linearRegressionLine: function(svg, dataset, x_log_scale, y_log_scale) { var that = this; // linear regresion line var lr_line = ss.linear_regression() .data(dataset.rows.map(function(d) { return [d.loss, d.gain]; })) .line(); var line = d3.svg.line() .x(x_log_scale) .y(function(d) { return that.y_log_scale(lr_line(d));} ) var x0 = x_log_scale.domain()[0]; var x1 = x_log_scale.domain()[1]; var lr = svg.selectAll('.linear_regression').data([0]); var attrs = { "x1": x_log_scale(x0), "y1": y_log_scale(lr_line(x0)), "x2": x_log_scale(x1), "y2": y_log_scale(lr_line(x1)), "stroke-width": 1.3, "stroke": "white", "stroke-dasharray": "7,5" }; lr.enter() .append("line") .attr('class', 'linear_regression') .attr(attrs); lr.transition().attr(attrs); } }); gfw.ui.view.CountriesEmbedShow = cdb.core.View.extend({ el: document.body, events: { 'click .forma_dropdown-link': '_openDropdown', 'click .hansen_dropdown-link': '_openDropdown', 'click .hansen_dropdown-menu a': '_redrawCircle' }, initialize: function() { this.iso = this.options.iso; this._initViews(); this._initHansenDropdown(); }, _initViews: function() { this._drawCircle('forma', 'lines', { iso: this.iso }); this._drawCircle('forest_loss', 'bars', { iso: this.iso, dataset: 'loss' }); }, _initFormaDropdown: function() { $('.forma_dropdown-link').qtip({ show: 'click', hide: { event: 'click unfocus' }, content: { text: $('.forma_dropdown-menu') }, position: { my: 'bottom right', at: 'top right', target: $('.forma_dropdown-link'), adjust: { x: -10 } }, style: { tip: { corner: 'bottom right', mimic: 'bottom center', border: 1, width: 10, height: 6 } } }); }, _initHansenDropdown: function() { this.dropdown = $('.hansen_dropdown-link').qtip({ show: 'click', hide: { event: 'click unfocus' }, content: { text: $('.hansen_dropdown-menu') }, position: { my: 'top right', at: 'bottom right', target: $('.hansen_dropdown-link'), adjust: { x: 10 } }, style: { tip: { corner: 'top right', mimic: 'top center', border: 1, width: 10, height: 6 } } }); }, _openDropdown: function(e) { e.preventDefault(); }, _redrawCircle: function(e) { e.preventDefault(); var dataset = $(e.target).attr('data-slug'), subtitle = $(e.target).text(); var api = this.dropdown.qtip('api'); api.hide(); $('.hansen_dropdown-link').html(subtitle); if(dataset === 'countries_gain') { this._drawCircle('forest_loss', 'comp', { iso: this.iso }); } else { this._drawCircle('forest_loss', 'bars', { iso: this.iso, dataset: dataset }); } }, _drawCircle: function(id, type, options) { var that = this; var $graph = $('.'+id), $amount = $('.'+id+' .graph-amount'), $date = $('.'+id+' .graph-date'), $coming_soon = $('.'+id+' .coming_soon'), $action = $('.'+id+' .action'); $('.graph.'+id+' .frame_bkg').empty(); $graph.addClass('ghost'); $amount.html(''); $date.html(''); $coming_soon.hide(); var width = options.width || 256, height = options.height || width, h = 100, // maxHeight radius = width / 2; var graph = d3.select('.graph.'+id+' .frame_bkg') .append('svg:svg') .attr('class', type) .attr('width', width) .attr('height', height); var dashedLines = [ { x1:17, y:height/4, x2:239, color: '#ccc' }, { x1:0, y:height/2, x2:width, color: '#ccc' }, { x1:17, y:3*height/4, x2:239, color: '#ccc' } ]; // Adds the dotted lines _.each(dashedLines, function(line) { graph.append('svg:line') .attr('x1', line.x1) .attr('y1', line.y) .attr('x2', line.x2) .attr('y2', line.y) .style('stroke-dasharray', '2,2') .style('stroke', line.color); }); var sql = ["SELECT date_trunc('month', date) as date, COUNT(*) as alerts", 'FROM forma_api', "WHERE iso = '"+options.iso+"'", "GROUP BY date_trunc('month', date)", "ORDER BY date_trunc('month', date) ASC"].join(' '); if (type === 'lines') { d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(json) { if(json && json.rows.length > 0) { $graph.removeClass('ghost'); $action.removeClass('disabled'); that._initFormaDropdown(); var data = json.rows.slice(1, json.rows.length - 1); } else { $coming_soon.show(); return; } var x_scale = d3.scale.linear() .domain([0, data.length - 1]) .range([0, width - 80]); var max = d3.max(data, function(d) { return parseFloat(d.alerts); }); if (max === d3.min(data, function(d) { return parseFloat(d.alerts); })) { h = h/2; } var y_scale = d3.scale.linear() .domain([0, max]) .range([0, h]); var line = d3.svg.line() .x(function(d, i) { return x_scale(i); }) .y(function(d, i) { return h - y_scale(d.alerts); }) .interpolate('basis'); var marginLeft = 40, marginTop = radius - h/2; $amount.html('<span>'+formatNumber(data[data.length - 1].alerts)+'</span>'); var date = new Date(data[data.length - 1].date), form_date = 'Alerts in ' + config.MONTHNAMES[date.getMonth()] + ' ' + date.getFullYear(); $date.html(form_date); graph.append('svg:path') .attr('transform', 'translate(' + marginLeft + ',' + marginTop + ')') .attr('d', line(data)) .on('mousemove', function(d) { var index = Math.round(x_scale.invert(d3.mouse(this)[0])); if (data[index]) { // if there's data $amount.html('<span>'+formatNumber(data[index].alerts)+'</span>'); var date = new Date(data[index].date), form_date = 'Alerts in ' + config.MONTHNAMES[date.getMonth()] + ' ' + date.getFullYear(); $date.html(form_date); var cx = d3.mouse(this)[0] + marginLeft; var cy = h - y_scale(data[index].alerts) + marginTop; graph.select('.forma_marker') .attr('cx', cx) .attr('cy', cy); } }); graph.append('svg:circle') .attr('class', 'forma_marker') .attr('cx', -10000) .attr('cy',100) .attr('r', 5); }); } else if (type === 'bars') { var sql = "SELECT "; if (options.dataset === 'loss') { sql += "year, loss_gt_0 loss FROM umd WHERE iso='"+options.iso+"'"; } else if (options.dataset === 'extent') { sql += "year, extent_gt_25 extent FROM umd WHERE iso='"+options.iso+"'"; } d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+sql, function(json) { if(json) { $graph.removeClass('ghost'); var data = json.rows; } else { $coming_soon.show(); return; } var data_ = []; _.each(data, function(val, key) { if (val.year >= 2001) { data_.push({ 'year': val.year, 'value': eval('val.'+options.dataset) }); } }); $amount.html('<span>'+formatNumber(parseInt(data_[data_.length - 1].value, 10))+'</span>'); $date.html('Hectares in ' + data_[data_.length - 1].year); var marginLeft = 40, marginTop = radius - h/2 + 5; var y_scale = d3.scale.linear() .domain([0, d3.max(data_, function(d) { return parseFloat(d.value); })]) .range([height, marginTop*2]); var barWidth = (width - 80) / data_.length; var bar = graph.selectAll('g') .data(data_) .enter() .append('g') .attr('transform', function(d, i) { return 'translate(' + (marginLeft + i * barWidth) + ','+ -marginTop+')'; }); bar.append('svg:rect') .attr('class', function(d, i) { if(i === 11) { // last year index return 'last bar' } else { return 'bar' } }) .attr('y', function(d) { return y_scale(d.value); }) .attr('height', function(d) { return height - y_scale(d.value); }) .attr('width', barWidth - 1) .on('mouseover', function(d) { d3.selectAll('.bar').style('opacity', '.5'); d3.select(this).style('opacity', '1'); $amount.html('<span>'+formatNumber(parseInt(d.value, 10))+'</span>'); $date.html('Hectares in ' + d.year); }); }); } else if (type === 'comp') { var sql = "SELECT iso, sum(umd.loss_gt_0) loss, max(umd.gain) gain FROM umd WHERE iso='"+options.iso+"' GROUP BY iso"; d3.json('https://wri-01.cartodb.com/api/v2/sql?q='+encodeURIComponent(sql), function(json) { if(json) { $graph.removeClass('ghost'); var data = json.rows[0]; } else { $coming_soon.show(); return; } var data_ = [{ 'key': 'Tree cover gain', 'value': data.gain }, { 'key': 'Tree cover loss', 'value': data.loss }]; $amount.html('<span>'+formatNumber(parseInt(data_[data_.length - 1].value, 10))+'</span>'); $date.html('Ha '+data_[data_.length - 1].key); var barWidth = (width - 80) / 12; var marginLeft = 40 + barWidth*5, marginTop = radius - h/2 + 5; var y_scale = d3.scale.linear() .domain([0, d3.max(data_, function(d) { return parseFloat(d.value); })]) .range([height, marginTop*2]); var bar = graph.selectAll('g') .data(data_) .enter() .append('g') .attr('transform', function(d, i) { return 'translate(' + (marginLeft + i * barWidth) + ',' + -marginTop + ')'; }); bar.append('svg:rect') .attr('class', function(d, i) { if (i === 1) { // last bar index return 'last bar' } else { return 'bar' } }) .attr('y', function(d) { return y_scale(d.value); }) .attr('height', function(d) { return height - y_scale(d.value); }) .attr('width', barWidth - 1) .style('fill', '#FFC926') .style('shape-rendering', 'crispEdges') .on('mouseover', function(d) { d3.selectAll('.bar').style('opacity', '.5'); d3.select(this).style('opacity', '1'); $amount.html('<span>'+formatNumber(parseFloat(d.value).toFixed(1))+'</span>'); $date.html('Ha '+d.key); }); }); } } });
apercas/gfw
app/assets/javascripts/embed_countries.js
JavaScript
mit
43,948
/* * @(#)LayouterSample.java * * Copyright (c) 1996-2010 by the original authors of JHotDraw and all its * contributors. All rights reserved. * * You may not use, copy or modify this file, except in compliance with the * license agreement you entered into with the copyright holders. For details * see accompanying license terms. */ package org.jhotdraw.samples.mini; import org.jhotdraw.draw.tool.DelegationSelectionTool; import org.jhotdraw.draw.layouter.VerticalLayouter; import javax.swing.*; import org.jhotdraw.draw.*; /** * Example showing how to layout two editable text figures and a line figure * within a graphical composite figure. * * @author Werner Randelshofer * @version $Id: LayouterSample.java 718 2010-11-21 17:49:53Z rawcoder $ */ public class LayouterSample { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { // Create a graphical composite figure. GraphicalCompositeFigure composite = new GraphicalCompositeFigure(); // Add child figures to the composite figure composite.add(new TextFigure("Above the line")); composite.add(new LineFigure()); composite.add(new TextFigure("Below the line")); // Set a layouter and perform the layout composite.setLayouter(new VerticalLayouter()); composite.layout(); // Add the composite figure to a drawing Drawing drawing = new DefaultDrawing(); drawing.add(composite); // Create a frame with a drawing view and a drawing editor JFrame f = new JFrame("My Drawing"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(400, 300); DrawingView view = new DefaultDrawingView(); view.setDrawing(drawing); f.getContentPane().add(view.getComponent()); DrawingEditor editor = new DefaultDrawingEditor(); editor.add(view); editor.setTool(new DelegationSelectionTool()); f.setVisible(true); } }); } }
ahmedvc/umple
Umplificator/UmplifiedProjects/jhotdraw7/src/main/java/org/jhotdraw/samples/mini/LayouterSample.java
Java
mit
2,276
package com.iluwatar.front.controller; /** * * Command for archers. * */ public class ArcherCommand implements Command { @Override public void process() { new ArcherView().display(); } }
dlee0113/java-design-patterns
front-controller/src/main/java/com/iluwatar/front/controller/ArcherCommand.java
Java
mit
204
declare module 'fast-memoize' { declare type Cache<K, V> = { get: (key: K) => V, set: (key: K, value: V) => void, has: (key: K) => boolean } declare type Options = { cache?: Cache<*, *>; serializer?: (...args: any[]) => any; strategy?: <T>(fn: T, options?: Options) => T; } declare module.exports: <T>(fn: T, options?: Options) => T; }
splodingsocks/FlowTyped
definitions/npm/fast-memoize_v2.x.x/flow_v0.53.x-v0.103.x/fast-memoize_v2.x.x.js
JavaScript
mit
374
angular.module('ualib.imageCarousel', ['angular-carousel']) .constant('VIEW_IMAGES_URL', '//wwwdev2.lib.ua.edu/erCarousel/api/slides/active') .factory('imageCarouselFactory', ['$http', 'VIEW_IMAGES_URL', function imageCarouselFactory($http, url){ return { getData: function(){ return $http({method: 'GET', url: url, params: {}}); } }; }]) .controller('imageCarouselCtrl', ['$scope', '$q', 'imageCarouselFactory', function imageCarouselCtrl($scope, $q, imageCarouselFactory){ $scope.slides = null; function loadImages(slides, i, len, deferred){ i = i ? i : 0; len = len ? len : slides.length; deferred = deferred ? deferred : $q.defer(); if (len < 1){ deferred.resolve(slides); } else{ var image = new Image(); image.onload = function(){ slides[i].styles = 'url('+this.src+')'; slides[i].image = this; if (i+1 === len){ deferred.resolve(slides); } else { i++; loadImages(slides, i, len, deferred); } }; image.src = slides[i].image; } return deferred.promise; } imageCarouselFactory.getData() .success(function(data) { loadImages(data.slides).then(function(slides){ $scope.slides = slides; }); }) .error(function(data, status, headers, config) { console.log(data); }); }]) .directive('ualibImageCarousel', [ function() { return { restrict: 'AC', controller: 'imageCarouselCtrl', link: function(scope, elm, attrs, Ctrl){ var toggleLock = false; scope.isLocked = false; scope.pause = function(){ toggleLock = true; scope.isLocked = true; }; scope.play = function(){ toggleLock = false; scope.isLocked = false; }; scope.mouseToggle = function(){ if (!toggleLock){ scope.isLocked = !scope.isLocked; } }; } }; }]);
8bitsquid/roots-ualib
assets/js/_ualib_imageCarousel.js
JavaScript
mit
2,702
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>basic_socket_streambuf::cancel (1 of 2 overloads)</title> <link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../cancel.html" title="basic_socket_streambuf::cancel"> <link rel="prev" href="../cancel.html" title="basic_socket_streambuf::cancel"> <link rel="next" href="overload2.html" title="basic_socket_streambuf::cancel (2 of 2 overloads)"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td> <td align="center"><a href="../../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../cancel.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../cancel.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h5 class="title"> <a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1"></a><a class="link" href="overload1.html" title="basic_socket_streambuf::cancel (1 of 2 overloads)">basic_socket_streambuf::cancel (1 of 2 overloads)</a> </h5></div></div></div> <p> <span class="emphasis"><em>Inherited from basic_socket.</em></span> </p> <p> Cancel all asynchronous operations associated with the socket. </p> <pre class="programlisting"><span class="keyword">void</span> <span class="identifier">cancel</span><span class="special">();</span> </pre> <p> This function causes all outstanding asynchronous connect, send and receive operations to finish immediately, and the handlers for cancelled operations will be passed the <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">operation_aborted</span></code> error. </p> <h6> <a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1.h0"></a> <span><a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1.exceptions"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_socket_streambuf.cancel.overload1.exceptions">Exceptions</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl> <dt><span class="term">boost::system::system_error</span></dt> <dd><p> Thrown on failure. </p></dd> </dl> </div> <h6> <a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1.h1"></a> <span><a name="boost_asio.reference.basic_socket_streambuf.cancel.overload1.remarks"></a></span><a class="link" href="overload1.html#boost_asio.reference.basic_socket_streambuf.cancel.overload1.remarks">Remarks</a> </h6> <p> Calls to <code class="computeroutput"><span class="identifier">cancel</span><span class="special">()</span></code> will always fail with <code class="computeroutput"><span class="identifier">boost</span><span class="special">::</span><span class="identifier">asio</span><span class="special">::</span><span class="identifier">error</span><span class="special">::</span><span class="identifier">operation_not_supported</span></code> when run on Windows XP, Windows Server 2003, and earlier versions of Windows, unless BOOST_ASIO_ENABLE_CANCELIO is defined. However, the CancelIo function has two issues that should be considered before enabling its use: </p> <div class="itemizedlist"><ul class="itemizedlist" type="disc"> <li class="listitem"> It will only cancel asynchronous operations that were initiated in the current thread. </li> <li class="listitem"> It can appear to complete without error, but the request to cancel the unfinished operations may be silently ignored by the operating system. Whether it works or not seems to depend on the drivers that are installed. </li> </ul></div> <p> For portable cancellation, consider using one of the following alternatives: </p> <div class="itemizedlist"><ul class="itemizedlist" type="disc"> <li class="listitem"> Disable asio's I/O completion port backend by defining BOOST_ASIO_DISABLE_IOCP. </li> <li class="listitem"> Use the <code class="computeroutput"><span class="identifier">close</span><span class="special">()</span></code> function to simultaneously cancel the outstanding operations and close the socket. </li> </ul></div> <p> When running on Windows Vista, Windows Server 2008, and later, the CancelIoEx function is always used. This function does not have the problems described above. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2015 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="../cancel.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../cancel.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../../boost_asio.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="overload2.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
yinchunlong/abelkhan-1
ext/c++/thirdpart/c++/boost/libs/asio/doc/html/boost_asio/reference/basic_socket_streambuf/cancel/overload1.html
HTML
mit
6,942
import { ListWrapper } from 'angular2/src/facade/collection'; import { stringify, isBlank } from 'angular2/src/facade/lang'; import { BaseException, WrappedException } from 'angular2/src/facade/exceptions'; function findFirstClosedCycle(keys) { var res = []; for (var i = 0; i < keys.length; ++i) { if (ListWrapper.contains(res, keys[i])) { res.push(keys[i]); return res; } else { res.push(keys[i]); } } return res; } function constructResolvingPath(keys) { if (keys.length > 1) { var reversed = findFirstClosedCycle(ListWrapper.reversed(keys)); var tokenStrs = reversed.map(k => stringify(k.token)); return " (" + tokenStrs.join(' -> ') + ")"; } else { return ""; } } /** * Base class for all errors arising from misconfigured providers. */ export class AbstractProviderError extends BaseException { constructor(injector, key, constructResolvingMessage) { super("DI Exception"); this.keys = [key]; this.injectors = [injector]; this.constructResolvingMessage = constructResolvingMessage; this.message = this.constructResolvingMessage(this.keys); } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); this.message = this.constructResolvingMessage(this.keys); } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when trying to retrieve a dependency by `Key` from {@link Injector}, but the * {@link Injector} does not have a {@link Provider} for {@link Key}. * * ### Example ([live demo](http://plnkr.co/edit/vq8D3FRB9aGbnWJqtEPE?p=preview)) * * ```typescript * class A { * constructor(b:B) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` */ export class NoProviderError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { var first = stringify(ListWrapper.first(keys).token); return `No provider for ${first}!${constructResolvingPath(keys)}`; }); } } /** * Thrown when dependencies form a cycle. * * ### Example ([live demo](http://plnkr.co/edit/wYQdNos0Tzql3ei1EV9j?p=info)) * * ```typescript * var injector = Injector.resolveAndCreate([ * provide("one", {useFactory: (two) => "two", deps: [[new Inject("two")]]}), * provide("two", {useFactory: (one) => "one", deps: [[new Inject("one")]]}) * ]); * * expect(() => injector.get("one")).toThrowError(); * ``` * * Retrieving `A` or `B` throws a `CyclicDependencyError` as the graph above cannot be constructed. */ export class CyclicDependencyError extends AbstractProviderError { constructor(injector, key) { super(injector, key, function (keys) { return `Cannot instantiate cyclic dependency!${constructResolvingPath(keys)}`; }); } } /** * Thrown when a constructing type returns with an Error. * * The `InstantiationError` class contains the original error plus the dependency graph which caused * this object to be instantiated. * * ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview)) * * ```typescript * class A { * constructor() { * throw new Error('message'); * } * } * * var injector = Injector.resolveAndCreate([A]); * try { * injector.get(A); * } catch (e) { * expect(e instanceof InstantiationError).toBe(true); * expect(e.originalException.message).toEqual("message"); * expect(e.originalStack).toBeDefined(); * } * ``` */ export class InstantiationError extends WrappedException { constructor(injector, originalException, originalStack, key) { super("DI Exception", originalException, originalStack, null); this.keys = [key]; this.injectors = [injector]; } addKey(injector, key) { this.injectors.push(injector); this.keys.push(key); } get wrapperMessage() { var first = stringify(ListWrapper.first(this.keys).token); return `Error during instantiation of ${first}!${constructResolvingPath(this.keys)}.`; } get causeKey() { return this.keys[0]; } get context() { return this.injectors[this.injectors.length - 1].debugContext(); } } /** * Thrown when an object other then {@link Provider} (or `Type`) is passed to {@link Injector} * creation. * * ### Example ([live demo](http://plnkr.co/edit/YatCFbPAMCL0JSSQ4mvH?p=preview)) * * ```typescript * expect(() => Injector.resolveAndCreate(["not a type"])).toThrowError(); * ``` */ export class InvalidProviderError extends BaseException { constructor(provider) { super("Invalid provider - only instances of Provider and Type are allowed, got: " + provider.toString()); } } /** * Thrown when the class has no annotation information. * * Lack of annotation information prevents the {@link Injector} from determining which dependencies * need to be injected into the constructor. * * ### Example ([live demo](http://plnkr.co/edit/rHnZtlNS7vJOPQ6pcVkm?p=preview)) * * ```typescript * class A { * constructor(b) {} * } * * expect(() => Injector.resolveAndCreate([A])).toThrowError(); * ``` * * This error is also thrown when the class not marked with {@link Injectable} has parameter types. * * ```typescript * class B {} * * class A { * constructor(b:B) {} // no information about the parameter types of A is available at runtime. * } * * expect(() => Injector.resolveAndCreate([A,B])).toThrowError(); * ``` */ export class NoAnnotationError extends BaseException { constructor(typeOrFunc, params) { super(NoAnnotationError._genMessage(typeOrFunc, params)); } static _genMessage(typeOrFunc, params) { var signature = []; for (var i = 0, ii = params.length; i < ii; i++) { var parameter = params[i]; if (isBlank(parameter) || parameter.length == 0) { signature.push('?'); } else { signature.push(parameter.map(stringify).join(' ')); } } return "Cannot resolve all parameters for " + stringify(typeOrFunc) + "(" + signature.join(', ') + "). " + 'Make sure they all have valid type or annotations.'; } } /** * Thrown when getting an object by index. * * ### Example ([live demo](http://plnkr.co/edit/bRs0SX2OTQiJzqvjgl8P?p=preview)) * * ```typescript * class A {} * * var injector = Injector.resolveAndCreate([A]); * * expect(() => injector.getAt(100)).toThrowError(); * ``` */ export class OutOfBoundsError extends BaseException { constructor(index) { super(`Index ${index} is out-of-bounds.`); } } // TODO: add a working example after alpha38 is released /** * Thrown when a multi provider and a regular provider are bound to the same token. * * ### Example * * ```typescript * expect(() => Injector.resolveAndCreate([ * new Provider("Strings", {useValue: "string1", multi: true}), * new Provider("Strings", {useValue: "string2", multi: false}) * ])).toThrowError(); * ``` */ export class MixingMultiProvidersWithRegularProvidersError extends BaseException { constructor(provider1, provider2) { super("Cannot mix multi providers and regular providers, got: " + provider1.toString() + " " + provider2.toString()); } } //# sourceMappingURL=exceptions.js.map
binariedMe/blogging
node_modules/angular2/es6/prod/src/core/di/exceptions.js
JavaScript
mit
7,494
Map Navigation Hash (History) ====================== #### Overview Uses dojo/router to enable zooming to next or previous extent using the browser forward and back buttons. The geographic map center and map zoom level is placed on the url. #### CMV Configuration Include the following code in js/config/viewer.js: ```javascript navhash: { include: true, id: 'navhash', type: 'invisible', path: 'viewer/dijit/MapNavigationHash/MapNavigationHash', title: 'Map Navigation Hash', options: { map: true } } ``` #### Usage Example appurl.com/index.htlm#/_longitude_/_latitude_/_zoomLevel_ The application will automatically update the url hash on pan and zoom. Users may also manually edit the route to go to a specific long, lat, and zoom level. A user can bookmark the url in the browser and, on load, the app will zoom and pan to the bookmarked location. [Click for demo](http://brianbunker.github.com/cmv-widgets) Screen from Sample page: ![Screenshot](./screenshot.png)
tmcgee/brian-bunker-cmv-widgets
MapNavigationHash/README.md
Markdown
mit
993
function SendItemsToOutput { Param ( [parameter()] [PSObject[]]$items, [parameter(Mandatory=$true)] [string[]]$typeName ) foreach ($i in $items) { $i.PSObject.TypeNames.Insert(0, $typeName) Write-Output $i } }
mariuszwojcik/RabbitMQTools
SendItemsToOutput.ps1
PowerShell
mit
286
<?php namespace Codeception\Command; use Codeception\Configuration; use Codeception\Lib\Generator\Snapshot as SnapshotGenerator; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; /** * Generates Snapshot. * Snapshot can be used to test dynamical data. * If suite name is provided, an actor class will be included into placeholder * * * `codecept g:snapshot UserEmails` * * `codecept g:snapshot Products` * * `codecept g:snapshot acceptance UserEmails` */ class GenerateSnapshot extends Command { use Shared\FileSystem; use Shared\Config; protected function configure() { $this->setDefinition([ new InputArgument('suite', InputArgument::REQUIRED, 'Suite name or snapshot name)'), new InputArgument('snapshot', InputArgument::OPTIONAL, 'Name of snapshot'), ]); parent::configure(); } public function getDescription() { return 'Generates empty Snapshot class'; } public function execute(InputInterface $input, OutputInterface $output) { $suite = $input->getArgument('suite'); $class = $input->getArgument('snapshot'); if (!$class) { $class = $suite; $suite = null; } $conf = $suite ? $this->getSuiteConfig($suite) : $this->getGlobalConfig(); if ($suite) { $suite = DIRECTORY_SEPARATOR . ucfirst($suite); } $path = $this->createDirectoryFor(Configuration::supportDir() . 'Snapshot' . $suite, $class); $filename = $path . $this->getShortClassName($class) . '.php'; $output->writeln($filename); $gen = new SnapshotGenerator($conf, ucfirst($suite) . '\\' . $class); $res = $this->createFile($filename, $gen->produce()); if (!$res) { $output->writeln("<error>Snapshot $filename already exists</error>"); exit; } $output->writeln("<info>Snapshot was created in $filename</info>"); } }
Codeception/base
src/Codeception/Command/GenerateSnapshot.php
PHP
mit
2,155
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {ENTER} from '@angular/cdk/keycodes'; import {CommonModule} from '@angular/common'; import {NgModule} from '@angular/core'; import { ErrorStateMatcher, MatCommonModule, MatRippleModule, } from '@angular/material-experimental/mdc-core'; import {MatChip, MatChipCssInternalOnly} from './chip'; import {MAT_CHIPS_DEFAULT_OPTIONS, MatChipsDefaultOptions} from './chip-default-options'; import {MatChipEditInput} from './chip-edit-input'; import {MatChipGrid} from './chip-grid'; import {MatChipAvatar, MatChipRemove, MatChipTrailingIcon} from './chip-icons'; import {MatChipInput} from './chip-input'; import {MatChipListbox} from './chip-listbox'; import {MatChipRow} from './chip-row'; import {MatChipOption} from './chip-option'; import {MatChipSet} from './chip-set'; const CHIP_DECLARATIONS = [ MatChip, MatChipAvatar, MatChipCssInternalOnly, MatChipEditInput, MatChipGrid, MatChipInput, MatChipListbox, MatChipOption, MatChipRemove, MatChipRow, MatChipSet, MatChipTrailingIcon, ]; @NgModule({ imports: [MatCommonModule, CommonModule, MatRippleModule], exports: [MatCommonModule, CHIP_DECLARATIONS], declarations: CHIP_DECLARATIONS, providers: [ ErrorStateMatcher, { provide: MAT_CHIPS_DEFAULT_OPTIONS, useValue: { separatorKeyCodes: [ENTER] } as MatChipsDefaultOptions } ] }) export class MatChipsModule { }
josephperrott/material2
src/material-experimental/mdc-chips/module.ts
TypeScript
mit
1,601
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2014 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Net; using System.Net.Http; using System.Threading; using System.Web; using System.Web.Http; using DotNetNuke.Application; using DotNetNuke.Common; using DotNetNuke.Entities.Controllers; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.Localization; using DotNetNuke.Web.Api; namespace DotNetNuke.Web.InternalServices { [RequireHost] public class GettingStartedController : DnnApiController { private const string GettingStartedHideKey = "GettingStarted_Hide_{0}"; private const string GettingStartedDisplayKey = "GettingStarted_Display_{0}"; public class ClosePageDto { public bool IsHidden { get; set; } } public class EmailDto { public string Email { get; set; } } [HttpGet] public HttpResponseMessage GetGettingStartedPageSettings() { var isHidden = HostController.Instance.GetBoolean(String.Format(GettingStartedHideKey, PortalSettings.UserId), false); var userEmailAddress = PortalSettings.UserInfo.Email; var request = HttpContext.Current.Request; var builder = new UriBuilder { Scheme = request.Url.Scheme, Host = "www.dnnsoftware.com", Path = "Community/Download/Manuals", Query = "src=dnn" // parameter to judge the effectiveness of this as a channel (i.e. the number of click through) }; var userManualUrl = builder.Uri.AbsoluteUri; return Request.CreateResponse(HttpStatusCode.OK, new { IsHidden = isHidden, EmailAddress = userEmailAddress, UserManualUrl = userManualUrl }); } [HttpPost] public HttpResponseMessage CloseGettingStartedPage(ClosePageDto dto) { HostController.Instance.Update(String.Format(GettingStartedHideKey, PortalSettings.UserId), dto.IsHidden.ToString()); HostController.Instance.Update(String.Format(GettingStartedDisplayKey, PortalSettings.UserId), "false"); return Request.CreateResponse(HttpStatusCode.OK, "Success"); } [HttpPost] public HttpResponseMessage SubscribeToNewsletter(EmailDto dto) { HostController.Instance.Update("NewsletterSubscribeEmail", dto.Email); return Request.CreateResponse(HttpStatusCode.OK, "Success"); } [HttpGet] public HttpResponseMessage GetContentUrl() { var request = HttpContext.Current.Request; var builder = new UriBuilder { Scheme = request.Url.Scheme, Host = "www.dnnsoftware.com", Path = String.Format("DesktopModules/DNNCorp/GettingStarted/{0}/{1}/index.html", DotNetNukeContext.Current.Application.Name.Replace(".", "_"), DotNetNukeContext.Current.Application.Version.ToString(3)), Query = String.Format("locale={0}", Thread.CurrentThread.CurrentUICulture) }; var contentUrl = builder.Uri.AbsoluteUri; var fallbackUrl = Globals.AddHTTP(request.Url.Host + Globals.ResolveUrl("~/Portals/_default/GettingStartedFallback.htm")); var isValid = IsValidUrl(contentUrl); return Request.CreateResponse(HttpStatusCode.OK, new { Url = isValid ? contentUrl : fallbackUrl }); } /// <summary> /// Checks if url does not return server or protocol errors /// </summary> /// <param name="url">Url to check</param> /// <returns></returns> private static bool IsValidUrl(string url) { HttpWebResponse response = null; try { var request = WebRequest.Create(url); request.Timeout = 5000; // set the timeout to 5 seconds to keep the user from waiting too long for the page to load request.Method = "HEAD"; // get only the header information - no need to download any content response = request.GetResponse() as HttpWebResponse; if (response == null) { return false; } var statusCode = (int)response.StatusCode; if (statusCode >= 500 && statusCode <= 510) // server errors { return false; } } catch { return false; } finally { if (response != null) { response.Close(); } } return true; } } }
raphael-m/Dnn.Platform
DNN Platform/DotNetNuke.Web/InternalServices/GettingStartedController.cs
C#
mit
6,016
// Help functions /* * Return a string with all helper functions whose name contains the 'substring'; * if the 'searchDescription' is true, then also search the function description"); */ function getHelp(substring, searchDescription) { return framework.getJavaScriptHelp(".*(?i:" + substring + ").*", searchDescription); } framework.addJavaScriptHelp("help", "substring, fileName", "output all the helper functions whose name contains the given 'substring'"); function help(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, false), fileName); } else if (arguments.length > 0) { write(getHelp(substring, false)); } else { write(getHelp("", false)); } } framework.addJavaScriptHelp("apropos", "substring, fileName", "output all the helper functions whose name or description contains the given 'substring'"); function apropos(substring, fileName) { if (arguments.length > 1) { write(getHelp(substring, true), fileName); } else if (arguments.length > 0) { write(getHelp(substring, true)); } else { write(getHelp("", true)); } } framework.addJavaScriptHelp("helpRegex", "regex, fileName", "output all helper functions whose name matches 'regex'"); function helpRegex(regex, fileName) { if (arguments.length > 1) { write(framework.getJavaScriptHelp(regex, false), fileName); } else if (arguments.length > 0) { write(framework.getJavaScriptHelp(regex, false)); } }
workcraft/workcraft
workcraft/WorkcraftCore/res/scripts/core-help.js
JavaScript
mit
1,523
FullCalendar.globalLocales.push(function () { 'use strict'; var it = { code: 'it', week: { dow: 1, // Monday is the first day of the week. doy: 4, // The week that contains Jan 4th is the first week of the year. }, buttonText: { prev: 'Prec', next: 'Succ', today: 'Oggi', month: 'Mese', week: 'Settimana', day: 'Giorno', list: 'Agenda', }, weekText: 'Sm', allDayText: 'Tutto il giorno', moreLinkText(n) { return '+altri ' + n }, noEventsText: 'Non ci sono eventi da visualizzare', }; return it; }());
unaio/una
upgrade/files/11.0.4-12.0.0.B1/files/plugins_public/fullcalendar/locale/it.js
JavaScript
mit
612
// Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package get import ( "errors" "internal/testenv" "io/ioutil" "os" "path" "path/filepath" "testing" "cmd/go/internal/web" ) // Test that RepoRootForImportPath creates the correct RepoRoot for a given importPath. // TODO(cmang): Add tests for SVN and BZR. func TestRepoRootForImportPath(t *testing.T) { testenv.MustHaveExternalNetwork(t) tests := []struct { path string want *repoRoot }{ { "github.com/golang/groupcache", &repoRoot{ vcs: vcsGit, repo: "https://github.com/golang/groupcache", }, }, // Unicode letters in directories (issue 18660). { "github.com/user/unicode/испытание", &repoRoot{ vcs: vcsGit, repo: "https://github.com/user/unicode", }, }, // IBM DevOps Services tests { "hub.jazz.net/git/user1/pkgname", &repoRoot{ vcs: vcsGit, repo: "https://hub.jazz.net/git/user1/pkgname", }, }, { "hub.jazz.net/git/user1/pkgname/submodule/submodule/submodule", &repoRoot{ vcs: vcsGit, repo: "https://hub.jazz.net/git/user1/pkgname", }, }, { "hub.jazz.net", nil, }, { "hub2.jazz.net", nil, }, { "hub.jazz.net/someotherprefix", nil, }, { "hub.jazz.net/someotherprefix/user1/pkgname", nil, }, // Spaces are not valid in user names or package names { "hub.jazz.net/git/User 1/pkgname", nil, }, { "hub.jazz.net/git/user1/pkg name", nil, }, // Dots are not valid in user names { "hub.jazz.net/git/user.1/pkgname", nil, }, { "hub.jazz.net/git/user/pkg.name", &repoRoot{ vcs: vcsGit, repo: "https://hub.jazz.net/git/user/pkg.name", }, }, // User names cannot have uppercase letters { "hub.jazz.net/git/USER/pkgname", nil, }, // OpenStack tests { "git.openstack.org/openstack/swift", &repoRoot{ vcs: vcsGit, repo: "https://git.openstack.org/openstack/swift", }, }, // Trailing .git is less preferred but included for // compatibility purposes while the same source needs to // be compilable on both old and new go { "git.openstack.org/openstack/swift.git", &repoRoot{ vcs: vcsGit, repo: "https://git.openstack.org/openstack/swift.git", }, }, { "git.openstack.org/openstack/swift/go/hummingbird", &repoRoot{ vcs: vcsGit, repo: "https://git.openstack.org/openstack/swift", }, }, { "git.openstack.org", nil, }, { "git.openstack.org/openstack", nil, }, // Spaces are not valid in package name { "git.apache.org/package name/path/to/lib", nil, }, // Should have ".git" suffix { "git.apache.org/package-name/path/to/lib", nil, }, { "git.apache.org/package-name.git", &repoRoot{ vcs: vcsGit, repo: "https://git.apache.org/package-name.git", }, }, { "git.apache.org/package-name_2.x.git/path/to/lib", &repoRoot{ vcs: vcsGit, repo: "https://git.apache.org/package-name_2.x.git", }, }, { "chiselapp.com/user/kyle/repository/fossilgg", &repoRoot{ vcs: vcsFossil, repo: "https://chiselapp.com/user/kyle/repository/fossilgg", }, }, { // must have a user/$name/repository/$repo path "chiselapp.com/kyle/repository/fossilgg", nil, }, { "chiselapp.com/user/kyle/fossilgg", nil, }, } for _, test := range tests { got, err := repoRootForImportPath(test.path, web.Secure) want := test.want if want == nil { if err == nil { t.Errorf("repoRootForImportPath(%q): Error expected but not received", test.path) } continue } if err != nil { t.Errorf("repoRootForImportPath(%q): %v", test.path, err) continue } if got.vcs.name != want.vcs.name || got.repo != want.repo { t.Errorf("repoRootForImportPath(%q) = VCS(%s) Repo(%s), want VCS(%s) Repo(%s)", test.path, got.vcs, got.repo, want.vcs, want.repo) } } } // Test that vcsFromDir correctly inspects a given directory and returns the right VCS and root. func TestFromDir(t *testing.T) { tempDir, err := ioutil.TempDir("", "vcstest") if err != nil { t.Fatal(err) } defer os.RemoveAll(tempDir) for j, vcs := range vcsList { dir := filepath.Join(tempDir, "example.com", vcs.name, "."+vcs.cmd) if j&1 == 0 { err := os.MkdirAll(dir, 0755) if err != nil { t.Fatal(err) } } else { err := os.MkdirAll(filepath.Dir(dir), 0755) if err != nil { t.Fatal(err) } f, err := os.Create(dir) if err != nil { t.Fatal(err) } f.Close() } want := repoRoot{ vcs: vcs, root: path.Join("example.com", vcs.name), } var got repoRoot got.vcs, got.root, err = vcsFromDir(dir, tempDir) if err != nil { t.Errorf("FromDir(%q, %q): %v", dir, tempDir, err) continue } if got.vcs.name != want.vcs.name || got.root != want.root { t.Errorf("FromDir(%q, %q) = VCS(%s) Root(%s), want VCS(%s) Root(%s)", dir, tempDir, got.vcs, got.root, want.vcs, want.root) } } } func TestIsSecure(t *testing.T) { tests := []struct { vcs *vcsCmd url string secure bool }{ {vcsGit, "http://example.com/foo.git", false}, {vcsGit, "https://example.com/foo.git", true}, {vcsBzr, "http://example.com/foo.bzr", false}, {vcsBzr, "https://example.com/foo.bzr", true}, {vcsSvn, "http://example.com/svn", false}, {vcsSvn, "https://example.com/svn", true}, {vcsHg, "http://example.com/foo.hg", false}, {vcsHg, "https://example.com/foo.hg", true}, {vcsGit, "ssh://user@example.com/foo.git", true}, {vcsGit, "user@server:path/to/repo.git", false}, {vcsGit, "user@server:", false}, {vcsGit, "server:repo.git", false}, {vcsGit, "server:path/to/repo.git", false}, {vcsGit, "example.com:path/to/repo.git", false}, {vcsGit, "path/that/contains/a:colon/repo.git", false}, {vcsHg, "ssh://user@example.com/path/to/repo.hg", true}, {vcsFossil, "http://example.com/foo", false}, {vcsFossil, "https://example.com/foo", true}, } for _, test := range tests { secure := test.vcs.isSecure(test.url) if secure != test.secure { t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure) } } } func TestIsSecureGitAllowProtocol(t *testing.T) { tests := []struct { vcs *vcsCmd url string secure bool }{ // Same as TestIsSecure to verify same behavior. {vcsGit, "http://example.com/foo.git", false}, {vcsGit, "https://example.com/foo.git", true}, {vcsBzr, "http://example.com/foo.bzr", false}, {vcsBzr, "https://example.com/foo.bzr", true}, {vcsSvn, "http://example.com/svn", false}, {vcsSvn, "https://example.com/svn", true}, {vcsHg, "http://example.com/foo.hg", false}, {vcsHg, "https://example.com/foo.hg", true}, {vcsGit, "user@server:path/to/repo.git", false}, {vcsGit, "user@server:", false}, {vcsGit, "server:repo.git", false}, {vcsGit, "server:path/to/repo.git", false}, {vcsGit, "example.com:path/to/repo.git", false}, {vcsGit, "path/that/contains/a:colon/repo.git", false}, {vcsHg, "ssh://user@example.com/path/to/repo.hg", true}, // New behavior. {vcsGit, "ssh://user@example.com/foo.git", false}, {vcsGit, "foo://example.com/bar.git", true}, {vcsHg, "foo://example.com/bar.hg", false}, {vcsSvn, "foo://example.com/svn", false}, {vcsBzr, "foo://example.com/bar.bzr", false}, } defer os.Unsetenv("GIT_ALLOW_PROTOCOL") os.Setenv("GIT_ALLOW_PROTOCOL", "https:foo") for _, test := range tests { secure := test.vcs.isSecure(test.url) if secure != test.secure { t.Errorf("%s isSecure(%q) = %t; want %t", test.vcs, test.url, secure, test.secure) } } } func TestMatchGoImport(t *testing.T) { tests := []struct { imports []metaImport path string mi metaImport err error }{ { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo", mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/", mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo", mi: metaImport{Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/fooa", mi: metaImport{Prefix: "example.com/user/fooa", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar/baz", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar/baz/qux", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com/user/foo/bar/baz/", err: errors.New("should not be allowed to create nested repo"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, {Prefix: "example.com/user/foo/bar", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "example.com", err: errors.New("pathologically short path"), }, { imports: []metaImport{ {Prefix: "example.com/user/foo", VCS: "git", RepoRoot: "https://example.com/repo/target"}, }, path: "different.example.com/user/foo", err: errors.New("meta tags do not match import path"), }, } for _, test := range tests { mi, err := matchGoImport(test.imports, test.path) if mi != test.mi { t.Errorf("unexpected metaImport; got %v, want %v", mi, test.mi) } got := err want := test.err if (got == nil) != (want == nil) { t.Errorf("unexpected error; got %v, want %v", got, want) } } } func TestValidateRepoRootScheme(t *testing.T) { tests := []struct { root string err string }{ { root: "", err: "no scheme", }, { root: "http://", err: "", }, { root: "a://", err: "", }, { root: "a#://", err: "invalid scheme", }, { root: "-config://", err: "invalid scheme", }, } for _, test := range tests { err := validateRepoRootScheme(test.root) if err == nil { if test.err != "" { t.Errorf("validateRepoRootScheme(%q) = nil, want %q", test.root, test.err) } } else if test.err == "" { if err != nil { t.Errorf("validateRepoRootScheme(%q) = %q, want nil", test.root, test.err) } } else if err.Error() != test.err { t.Errorf("validateRepoRootScheme(%q) = %q, want %q", test.root, err, test.err) } } }
christopher-henderson/Go
src/cmd/go/internal/get/vcs_test.go
GO
mit
12,175
{% if site.staticman.repository and site.staticman.branch %} <div class="staticman-comments"> <div class="page__comments"> <!-- Start static comments --> <div class="js-comments"> {% if site.data.comments[page.slug] %} <h3 class="page__comments-title">{{ site.data.ui-text[site.locale].comments_title | default: "Comments" }}</h3> {% assign comments = site.data.comments[page.slug] | sort %} {% for comment in comments %} {% assign email = comment[1].email %} {% assign name = comment[1].name %} {% assign url = comment[1].url %} {% assign date = comment[1].date %} {% assign message = comment[1].message %} {% include staticman-comment.html index=forloop.index email=email name=name url=url date=date message=message %} {% endfor %} {% endif %} </div> <!-- End static comments --> <!-- Start new comment form --> <div class="page__comments-form"> <h3 class="page__comments-title">{{ site.data.ui-text[site.locale].comments_label | default: "Leave a Comment" }}</h3> <p class="small">{{ site.data.ui-text[site.locale].comment_form_info | default: "Your email address will not be published. Required fields are marked" }} <span class="required">*</span></p> <form id="new_comment" class="page__comments-form js-form form" method="post"> <div class="form-group"> <label for="comment-form-message">{{ site.data.ui-text[site.locale].comment_form_comment_label | default: "Comment" }} <small class="required">*</small></label><br> <textarea type="text" rows="12" cols="36" id="comment-form-message" name="fields[message]" tabindex="1"></textarea> <div class="small help-block"><a href="https://daringfireball.net/projects/markdown/">{{ site.data.ui-text[site.locale].comment_form_md_info | default: "Markdown is supported." }}</a></div> </div> <div class="form-group"> <label for="comment-form-name">{{ site.data.ui-text[site.locale].comment_form_name_label | default: "Name" }} <small class="required">*</small></label> <input type="text" id="comment-form-name" name="fields[name]" tabindex="2" /> </div> <div class="form-group"> <label for="comment-form-email">{{ site.data.ui-text[site.locale].comment_form_email_label | default: "Email address" }} <small class="required">*</small></label> <input type="email" id="comment-form-email" name="fields[email]" tabindex="3" /> </div> <div class="form-group"> <label for="comment-form-url">{{ site.data.ui-text[site.locale].comment_form_website_label | default: "Website (optional)" }}</label> <input type="url" id="comment-form-url" name="fields[url]" tabindex="4"/> </div> <div class="form-group hidden" style="display: none;"> <input type="hidden" name="options[origin]" value="{{ page.url | absolute_url }}"> <input type="hidden" name="options[slug]" value="{{ page.slug }}"> <label for="comment-form-location">Not used. Leave blank if you are a human.</label> <input type="text" id="comment-form-location" name="fields[hidden]" autocomplete="off"/> {% if site.staticman.reCaptcha.siteKey %}<input type="hidden" name="options[reCaptcha][siteKey]" value="{{ site.staticman.reCaptcha.siteKey }}">{% endif %} {% if site.staticman.reCaptcha.secret %}<input type="hidden" name="options[reCaptcha][secret]" value="{{ site.staticman.reCaptcha.secret }}">{% endif %} </div> <!-- Start comment form alert messaging --> <p class="hidden js-notice"> <strong class="js-notice-text-success hidden">{{ site.data.ui-text[site.locale].comment_success_msg | default: "Thanks for your comment! It will show on the site once it has been approved." }}</strong> <strong class="js-notice-text-failure hidden">{{ site.data.ui-text[site.locale].comment_error_msg | default: "Sorry, there was an error with your submission. Please make sure all required fields have been completed and try again." }}</strong> </p> <!-- End comment form alert messaging --> {% if site.staticman.reCaptcha.siteKey %} <div class="form-group"> <div class="g-recaptcha" data-sitekey="{{ site.staticman.reCaptcha.siteKey }}"></div> </div> {% endif %} <div class="form-group"> <button type="submit" id="comment-form-submit" tabindex="5" class="btn btn--primary btn--large">{{ site.data.ui-text[site.locale].comment_btn_submit | default: "Submit Comment" }}</button> <button type="submit" id="comment-form-submitted" tabindex="5" class="btn btn--primary btn--large hidden" disabled>{{ site.data.ui-text[site.locale].comment_btn_submitted | default: "Submitted" }}</button> </div> </form> </div> <!-- End new comment form --> <!-- Load reCaptcha if site key is set --> {% if site.staticman.reCaptcha.siteKey %} <script async src="https://www.google.com/recaptcha/api.js"></script> {% endif %} </div> <!-- Load script to handle comment form submission --> <!-- doing something a bit funky here because I want to be careful not to include JQuery twice! --> <script> if (typeof jQuery == 'undefined') { document.write('<script src="{{ "/js/jquery-1.11.2.min.js" | relative_url }}"></scr' + 'ipt>'); } </script> <script src="{{ "/js/staticman.js" | relative_url }}"></script> </div> {% endif %}
igordcsouza/igordcsouza.github.io
_includes/staticman-comments.html
HTML
mit
5,559
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData // package to your project. ////#define Handle_PageResultOfT using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Web; using System.Web.Http; #if Handle_PageResultOfT using System.Web.Http.OData; #endif namespace TheBigCatProject.Server.Areas.HelpPage { /// <summary> /// Use this class to customize the Help Page. /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation /// or you can provide the samples for the requests/responses. /// </summary> public static class HelpPageConfig { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "TheBigCatProject.Server.Areas.HelpPage.TextSample.#ctor(System.String)", Justification = "End users may choose to merge this string with existing localized resources.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "bsonspec", Justification = "Part of a URI.")] public static void Register(HttpConfiguration config) { //// Uncomment the following to use the documentation from XML documentation file. //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type //// formats by the available formatters. //config.SetSampleObjects(new Dictionary<Type, object> //{ // {typeof(string), "sample string"}, // {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}} //}); // Extend the following to provide factories for types not handled automatically (those lacking parameterless // constructors) or for which you prefer to use non-default property values. Line below provides a fallback // since automatic handling will fail and GeneratePageResult handles only a single type. #if Handle_PageResultOfT config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); #endif // Extend the following to use a preset object directly as the sample for all actions that support a media // type, regardless of the body parameter or return type. The lines below avoid display of binary content. // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. config.SetSampleForMediaType( new TextSample("Binary JSON content. See http://bsonspec.org for details."), new MediaTypeHeaderValue("application/bson")); //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format //// and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" //// and action named "Put". //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" //// on the controller named "Values" and action named "Get" with parameter "id". //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. //config.SetActualRequestType(typeof(string), "Values", "Get"); //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. //config.SetActualResponseType(typeof(string), "Values", "Post"); } #if Handle_PageResultOfT private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) { if (type.IsGenericType) { Type openGenericType = type.GetGenericTypeDefinition(); if (openGenericType == typeof(PageResult<>)) { // Get the T in PageResult<T> Type[] typeParameters = type.GetGenericArguments(); Debug.Assert(typeParameters.Length == 1); // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor Type itemsType = typeof(List<>).MakeGenericType(typeParameters); object items = sampleGenerator.GetSampleObject(itemsType); // Fill in the other information needed to invoke the PageResult<T> constuctor Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor ConstructorInfo constructor = type.GetConstructor(parameterTypes); return constructor.Invoke(parameters); } } return null; } #endif } }
EmilMitev/Telerik-Academy
Single Page Applications/07. AngularJS Workshop/TheBigCatProject/TheBigCatProject.Server/Areas/HelpPage/App_Start/HelpPageConfig.cs
C#
mit
6,517
<?php namespace Hateoas\Tests\Expression; use Symfony\Component\ExpressionLanguage\ExpressionLanguage; use Symfony\Component\ExpressionLanguage\Node\Node; use Symfony\Component\ExpressionLanguage\ParsedExpression; use Hateoas\Tests\TestCase; use Hateoas\Expression\ExpressionEvaluator; use Hateoas\Expression\ExpressionFunctionInterface; class ExpressionEvaluatorTest extends TestCase { public function testNullEvaluate() { $expressionLanguageProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $expressionLanguageProphecy ->parse($this->arg->any()) ->shouldNotBeCalled() ; $expressionEvaluator = new ExpressionEvaluator($expressionLanguageProphecy->reveal()); $this ->string($expressionEvaluator->evaluate('hello', null)) ->isEqualTo('hello') ; } public function testEvaluate() { $data = new \StdClass(); $expressionLanguageProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $expressionLanguageProphecy ->parse('"42"', array('object')) ->willReturn($parsedExpression = new ParsedExpression('', new Node())) ; $expressionLanguageProphecy ->evaluate($parsedExpression, array('object' => $data)) ->willReturn('42') ; $expressionEvaluator = new ExpressionEvaluator($expressionLanguageProphecy->reveal()); $this ->string($expressionEvaluator->evaluate('expr("42")', $data)) ->isEqualTo('42') ; } public function testEvaluateArray() { $parsedExpressions = array( new ParsedExpression('a', new Node()), new ParsedExpression('aa', new Node()), new ParsedExpression('aaa', new Node()), ); $data = new \StdClass(); $ELProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $ELProphecy->parse('a', array('object'))->willReturn($parsedExpressions[0])->shouldBeCalledTimes(1); $ELProphecy->parse('aa', array('object'))->willReturn($parsedExpressions[1])->shouldBeCalledTimes(1); $ELProphecy->parse('aaa', array('object'))->willReturn($parsedExpressions[2])->shouldBeCalledTimes(1); $ELProphecy->evaluate($parsedExpressions[0], array('object' => $data))->willReturn(1); $ELProphecy->evaluate($parsedExpressions[1], array('object' => $data))->willReturn(2); $ELProphecy->evaluate($parsedExpressions[2], array('object' => $data))->willReturn(3); $expressionEvaluator = new ExpressionEvaluator($ELProphecy->reveal()); $array = array( 'expr(a)' => 'expr(aa)', 'hello' => array('expr(aaa)'), ); $this ->array($expressionEvaluator->evaluateArray($array, $data)) ->isEqualTo(array( 1 => 2, 'hello' => array(3), )) ; } public function testSetContextVariable() { $data = new \StdClass(); $expressionLanguageProphecy = $this->prophesize('Symfony\Component\ExpressionLanguage\ExpressionLanguage'); $expressionLanguageProphecy ->parse('name', array('name', 'object')) ->willReturn($parsedExpression = new ParsedExpression('', new Node())) ->shouldBeCalledTimes(1) ; $expressionLanguageProphecy ->evaluate($parsedExpression, array('object' => $data, 'name' => 'Adrien')) ->willReturn('Adrien') ->shouldBeCalledTimes(1) ; $expressionEvaluator = new ExpressionEvaluator($expressionLanguageProphecy->reveal()); $expressionEvaluator->setContextVariable('name', 'Adrien'); $this ->string($expressionEvaluator->evaluate('expr(name)', $data)) ->isEqualTo('Adrien') ; } public function testRegisterFunction() { $expressionEvaluator = new ExpressionEvaluator(new ExpressionLanguage()); $expressionEvaluator->registerFunction(new HelloExpressionFunction()); $this ->string($expressionEvaluator->evaluate('expr(hello("toto"))', null)) ->isEqualTo('Hello, toto!') ; } } class HelloExpressionFunction implements ExpressionFunctionInterface { public function getName() { return 'hello'; } public function getCompiler() { return function ($value) { return sprintf('$hello_helper->hello(%s)', $value); }; } public function getEvaluator() { return function (array $context, $value) { return $context['hello_helper']->hello($value); }; } public function getContextVariables() { return array('hello_helper' => $this); } public function hello($name) { return sprintf('Hello, %s!', $name); } }
witalikkowal/Store
vendor/willdurand/hateoas/tests/Hateoas/Tests/Expression/ExpressionEvaluatorTest.php
PHP
mit
5,029
<?php /** * Pro customizer section. * * @since 1.0.0 * @access public */ class Epsilon_Section_Pro extends WP_Customize_Section { /** * The type of customize section being rendered. * * @since 1.0.0 * @access public * @var string */ public $type = 'epsilon-section-pro'; /** * Custom pro button URL. * * @since 1.0.0 * @access public * @var string */ public $button_url = ''; /** * Custom pro button text. * * @since 1.0.0 * @access public * @var string */ public $button_text = ''; /** * Used to disable the upsells * * @var bool */ public $allowed = true; /** * Epsilon_Section_Pro constructor. * * @param WP_Customize_Manager $manager * @param string $id * @param array $args */ public function __construct( WP_Customize_Manager $manager, $id, array $args = array() ) { $this->allowed = apply_filters( 'epsilon_upsell_section_display', true ); $manager->register_section_type( 'Epsilon_Section_Pro' ); parent::__construct( $manager, $id, $args ); } /** * Add custom parameters to pass to the JS via JSON. * * @since 1.0.0 * @access public */ public function json() { $json = parent::json(); $json['button_url'] = $this->button_url; $json['button_text'] = esc_html( $this->button_text ); $json['allowed'] = $this->allowed; return $json; } /** * Outputs the Underscore.js template. * * @since 1.0.0 * @access public * @return void */ protected function render_template() { ?> <?php if ( $this->allowed ) : //@formatter:off ?> <li id="accordion-section-{{ data.id }}" class="accordion-section control-section control-section-{{ data.type }} cannot-expand"> <h3 class="accordion-section-title epsilon-pro-section-title"> {{ data.title }} <# if ( data.button_url ) { #> <a href="{{ data.button_url }}" class="button alignright" target="_blank"> {{ data.button_text }}</a> <# } #> </h3> </li> <?php //@formatter:on ?> <?php endif; ?> <?php } }
jmelgarejo/Clan
wordpress/wp-content/themes/sparkling/inc/libraries/epsilon-framework/sections/class-epsilon-section-pro.php
PHP
mit
2,068
/// <summary> /// This class handles user ID, session ID, time stamp, and sends a user message, optionally including system specs, when the game starts /// </summary> using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System; using System.Net; #if !UNITY_WEBPLAYER && !UNITY_NACL && !UNITY_FLASH && !UNITY_WP8 && !UNITY_METRO && !UNITY_PS3 using System.Net.NetworkInformation; using System.Security.Cryptography; using System.Text; #endif public class GA_GenericInfo { #region public values /// <summary> /// The ID of the user/player. A unique ID will be determined the first time the player plays. If an ID has already been created for a player this ID will be used. /// </summary> public string UserID { get { if ((_userID == null || _userID == string.Empty) && !GA.SettingsGA.CustomUserID) { _userID = GetUserUUID(); } return _userID; } } /// <summary> /// The ID of the current session. A unique ID will be determined when the game starts. This ID will be used for the remainder of the play session. /// </summary> public string SessionID { get { if (_sessionID == null) { _sessionID = GetSessionUUID(); } return _sessionID; } } /// <summary> /// The current UTC date/time in seconds /// </summary> /*public string TimeStamp { get { return ((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000).ToString(); } }*/ #endregion #region private values private string _userID = string.Empty; private string _sessionID; private bool _settingUserID; #endregion #region public methods /// <summary> /// Gets generic system information at the beginning of a play session /// </summary> /// <param name="inclSpecs"> /// Determines if all the system specs should be included <see cref="System.Bool"/> /// </param> /// <returns> /// The message to submit to the GA server is a dictionary of all the relevant parameters (containing user ID, session ID, system information, language information, date/time, build version) <see cref="Dictionary<System.String, System.Object>"/> /// </returns> public List<Hashtable> GetGenericInfo(string message) { List<Hashtable> systemspecs = new List<Hashtable>(); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "unity_sdk " + GA_Settings.VERSION, message)); /* * Apple does not allow tracking of device specific data: * "You may not use analytics software in your application to collect and send device data to a third party" * - iOS Developer Program License Agreement: http://www.scribd.com/doc/41213383/iOS-Developer-Program-License-Agreement */ #if !UNITY_IPHONE systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:"+SystemInfo.operatingSystem, message)); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "processor_type:"+SystemInfo.processorType, message)); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_name:"+SystemInfo.graphicsDeviceName, message)); systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_version:"+SystemInfo.graphicsDeviceVersion, message)); // Unity provides lots of additional system info which might be worth tracking for some games: //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "process_count:"+SystemInfo.processorCount.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sys_mem_size:"+SystemInfo.systemMemorySize.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_mem_size:"+SystemInfo.graphicsMemorySize.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor:"+SystemInfo.graphicsDeviceVendor, message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_id:"+SystemInfo.graphicsDeviceID.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_vendor_id:"+SystemInfo.graphicsDeviceVendorID.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_shader_level:"+SystemInfo.graphicsShaderLevel.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "gfx_pixel_fillrate:"+SystemInfo.graphicsPixelFillrate.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_shadows:"+SystemInfo.supportsShadows.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_render_textures:"+SystemInfo.supportsRenderTextures.ToString(), message)); //systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "sup_image_effects:"+SystemInfo.supportsImageEffects.ToString(), message)); #else systemspecs.Add(AddSystemSpecs(GA_Error.SeverityType.info, "os:iOS", message)); #endif return systemspecs; } /// <summary> /// Gets a universally unique ID to represent the user. User ID should be device specific to allow tracking across different games on the same device: /// -- Android uses deviceUniqueIdentifier. /// -- iOS/PC/Mac uses the first MAC addresses available. /// -- Webplayer uses deviceUniqueIdentifier. /// Note: The unique user ID is based on the ODIN specifications. See http://code.google.com/p/odinmobile/ for more information on ODIN. /// </summary> /// <returns> /// The generated UUID <see cref="System.String"/> /// </returns> public static string GetUserUUID() { #if UNITY_IPHONE && !UNITY_EDITOR string uid = GA.SettingsGA.GetUniqueIDiOS(); if (uid == null) { return ""; } else if (uid != "OLD") { if (uid.StartsWith("VENDOR-")) return uid.Remove(0, 7); else return uid; } #endif #if UNITY_ANDROID && !UNITY_EDITOR string uid = GA.SettingsGA.GetAdvertisingIDAndroid(); if (!string.IsNullOrEmpty(uid)) { return uid; } #endif #if UNITY_WEBPLAYER || UNITY_NACL || UNITY_WP8 || UNITY_METRO || UNITY_PS3 return SystemInfo.deviceUniqueIdentifier; #elif !UNITY_FLASH try { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); string mac = ""; foreach (NetworkInterface adapter in nics) { PhysicalAddress address = adapter.GetPhysicalAddress(); if (address.ToString() != "" && mac == "") { mac = GA_Submit.CreateSha1Hash(address.ToString()); } } return mac; } catch { return SystemInfo.deviceUniqueIdentifier; } #else return GetSessionUUID(); #endif } /// <summary> /// Gets a universally unique ID to represent the session. /// </summary> /// <returns> /// The generated UUID <see cref="System.String"/> /// </returns> public static string GetSessionUUID() { #if !UNITY_FLASH return Guid.NewGuid().ToString(); #else string returnValue = ""; for (int i = 0; i < 12; i++) { returnValue += UnityEngine.Random.Range(0, 10).ToString(); } return returnValue; #endif } /// <summary> /// Sets the session ID. If newSessionID is null then a random UUID will be generated, otherwise newSessionID will be used as the session ID. /// </summary> /// <param name="newSessionID">New session I.</param> public void SetSessionUUID(string newSessionID) { if (newSessionID == null) { _sessionID = GetSessionUUID(); } else { _sessionID = newSessionID; } } /// <summary> /// Do not call this method (instead use GA_static_api.Settings.SetCustomUserID)! Only the GA class should call this method. /// </summary> /// <param name="customID"> /// The custom user ID - this should be unique for each user /// </param> public void SetCustomUserID(string customID) { _userID = customID; } #endregion #region private methods /// <summary> /// Adds detailed system specifications regarding the users/players device to the parameters. /// </summary> /// <param name="parameters"> /// The parameters which will be sent to the server <see cref="Dictionary<System.String, System.Object>"/> /// </param> private Hashtable AddSystemSpecs(GA_Error.SeverityType severity, string type, string message) { string addmessage = ""; if (message != "") addmessage = ": " + message; Hashtable parameters = new Hashtable() { { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Severity], severity.ToString() }, { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Message], type + addmessage }, { GA_ServerFieldTypes.Fields[GA_ServerFieldTypes.FieldType.Level], GA.SettingsGA.CustomArea.Equals(string.Empty)?Application.loadedLevelName:GA.SettingsGA.CustomArea } }; return parameters; } /// <summary> /// Gets the users system type /// </summary> /// <returns> /// String determining the system the user is currently running <see cref="System.String"/> /// </returns> public static string GetSystem() { #if UNITY_STANDALONE_OSX return "MAC"; #elif UNITY_STANDALONE_WIN return "PC"; #elif UNITY_WEBPLAYER return "WEBPLAYER"; #elif UNITY_WII return "WII"; #elif UNITY_IPHONE return "IPHONE"; #elif UNITY_ANDROID return "ANDROID"; #elif UNITY_PS3 return "PS3"; #elif UNITY_XBOX360 return "XBOX"; #elif UNITY_FLASH return "FLASH"; #elif UNITY_STANDALONE_LINUX return "LINUX"; #elif UNITY_NACL return "NACL"; #elif UNITY_DASHBOARD_WIDGET return "DASHBOARD_WIDGET"; #elif UNITY_METRO return "WINDOWS_STORE_APP"; #elif UNITY_WP8 return "WINDOWS_PHONE_8"; #elif UNITY_BLACKBERRY return "BLACKBERRY"; #else return "UNKNOWN"; #endif } #endregion }
samoatesgames/Ludumdare30
Unity/Assets/GameAnalytics/Plugins/Framework/Scripts/GA_GenericInfo.cs
C#
mit
9,640