text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
define(function(require, exports, module) { /** * ControlUtil * @class ControlUtil * @constructor */ var ControlUtil = exports; /** * SimpleTimer * @class ControlUtil.SimpleTimer * @constructor * @param {Number} _gapTime timer gap * @param {Object} _callbackScope scope object * @param {Function} _callbackFunc callback function * @param {Array} _callbackFuncArgumentsArr callback function arguments array * @example //EXAMPLE 1. perform function function timerTestFunc() { console.log('private timerTestFunc'); } var _function = timerTestFunc; //단일 function var _simpleTimer = new ControlUtil.SimpleTimer( 1000, this, _function ); _simpleTimer.start(); //_simpleTimer.stop(); //EXAMPLE 2. perform Object function include arguments var _functionObj = {}; _functionObj.timerTestFuncIncludeArgument = function(_param_1, _param_2, _param_3) { console.log('function Object function included Object : ', _param_1, _param_2, _param_3); }; var _function = _functionObj.timerTestFuncIncludeArgument; //객체에 귀속된 function var _simpleTimer = new ControlUtil.SimpleTimer( 1000, this, _function, [0, "dragmove", {x:100, y:200}] ); _simpleTimer.start(); //_simpleTimer.stop(); //EXAMPLE 3. perform function include arguments function timerTestFuncIncludeArgument(_param_1, _param_2, _param_3) { console.log('private function : ', _param_1, _param_2, _param_3); } var _function = timerTestFuncIncludeArgument; //단일 function var _simpleTimer = new ControlUtil.SimpleTimer( 1000, this, _function, [0, "dragmove", {x:100, y:200}] ); _simpleTimer.start(); //_simpleTimer.stop(); */ ControlUtil.SimpleTimer = function(_gapTime, _callbackScope, _callbackFunc, _callbackFuncArgumentsArr) { var _this = this; //variables var gapTime = _gapTime; var callbackScope = _callbackScope; var callbackFunc = _callbackFunc; var callbackFuncArgumentsArr = _callbackFuncArgumentsArr; var _timer; //setTimeout var flag_protectRepeatTimeout = false; //public function _this.destroy = function() { destroyInternalTimer(); gapTime = null; callbackScope = null; callbackFunc = null; callbackFuncArgumentsArr = null; _timer = null; flag_protectRepeatTimeout = false; }; _this.start = function() { destroyInternalTimer(); _timer = setTimeout(performTimeout, gapTime); flag_protectRepeatTimeout = true; }; _this.stop = function() { flag_protectRepeatTimeout = false; destroyInternalTimer(); }; //private function function performTimeout() { if(!callbackFuncArgumentsArr) { _callbackFunc.call(callbackScope); } else { _callbackFunc.apply(callbackScope, callbackFuncArgumentsArr); } repeatTimeout(); } function repeatTimeout() { if(!flag_protectRepeatTimeout) return; destroyInternalTimer(); _timer = setTimeout(performTimeout, gapTime); } function destroyInternalTimer() { if(_timer) { clearTimeout(_timer); _timer = null; } } return _this; }; return ControlUtil; });
{'content_hash': 'fb3c8071f06246cf08c3888f26751e88', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 106, 'avg_line_length': 27.710526315789473, 'alnum_prop': 0.671415004748338, 'repo_name': 'dragmove/DRAGMOVE_JS_API', 'id': '0f313ecec35b785e7ca06d00844e2a8db0a05a36', 'size': '4335', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/js/com/dragmove/util/ControlUtil.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '36332'}, {'name': 'JavaScript', 'bytes': '215587'}]}
/* We need to add display:inline in order to align the '>>' of the 'read more' link */ .post-excerpt p { display:inline; } img.emoji { margin: 0px !important; display: inline !important; } // Import partials from `sass_dir` (defaults to `_sass`) @import "syntax" ; @import "accordion";
{'content_hash': 'c0a58fb5605440f2066d54b858f68bd5', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 86, 'avg_line_length': 17.529411764705884, 'alnum_prop': 0.6610738255033557, 'repo_name': 'linearza/linearza.github.io', 'id': '72620f0c16a2a0bee02c3ea959802f2d51f57dcd', 'size': '298', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'assets/css/main.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '41410'}, {'name': 'HTML', 'bytes': '11290'}, {'name': 'JavaScript', 'bytes': '5773'}]}
package httpservice.handlers; public class HttpContentTypes { public final static String TEXT = "text/html; charset=utf-8"; public final static String JSON = "application/json"; public final static String CSV= "text/csv"; }
{'content_hash': '6c5922a15897f03fd90e7866213d9d5c', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 62, 'avg_line_length': 33.57142857142857, 'alnum_prop': 0.7404255319148936, 'repo_name': 'jaamal/overclocking', 'id': '121156c2694a43e73d934553df6340d73859a645', 'size': '235', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'sources/HttpService/src/httpservice/handlers/HttpContentTypes.java', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '2990'}, {'name': 'C++', 'bytes': '8729'}, {'name': 'Java', 'bytes': '926976'}, {'name': 'TeX', 'bytes': '6505694'}]}
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example84-production</title> <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.24/angular.min.js"></script> <script src="script.js"></script> </head> <body ng-app="docsTransclusionDirective"> <div ng-controller="Controller"> <my-dialog>Check out the contents, {{name}}!</my-dialog> </div> </body> </html>
{'content_hash': '0847584f9c268cbc81c19e04145abedb', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 89, 'avg_line_length': 22.63157894736842, 'alnum_prop': 0.6604651162790698, 'repo_name': 'Zyckzto/angularjs-app', 'id': '97292693dabedb96339454443965d510aad9d31a', 'size': '430', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'angular/docs/examples/example-example84/index-production.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '47035'}, {'name': 'HTML', 'bytes': '2225102'}, {'name': 'JavaScript', 'bytes': '196267'}]}
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': 'd9758154c1f7b09c758894181d436c06', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': 'b9ff428ebe218aaadff555180448b2a61a5e313f', 'size': '179', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Apiales/Apiaceae/Sison/Sison cernuum/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<div class="container"> <div class="header"> <ul class="breadcrumb"> <li><a href='/'>主页</a><span class="divider"></span></li> <li class="active">登录</li> </ul> </div> <div class="inner"> <% if (typeof(error) !== 'undefined' && error) { %> <div class="alert alert-danger"> <button type="button" class="close" data-dismiss="alert" arial-label="Close"> <span arial-hidden="true">&times;</span> </button> <%= error %> </div> <% } %> <form id="signin_form" class="form-horizontal" action="/login" method="post" novalidate autocomplete="off"> <div class="form-group"> <label class="col-md-2 control-label" for="loginname">用户名</label> <div class="col-md-10"> <input type="text" id="loginname" name="loginname" class="form-control input-text" /> </div> </div> <div class="form-group"> <label class="col-md-2 control-label" for="pass">密码</label> <div class="col-md-10"> <input type="password" id="pass" name="pass" class="form-control input-text" /> </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" class="btn btn-primary" value="登录" /> </div> </div> </form> </div> </div>
{'content_hash': 'd8bfc2fa925632b405e155be047012c2', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 115, 'avg_line_length': 42.2972972972973, 'alnum_prop': 0.46645367412140576, 'repo_name': 'grj1046/nodejs-guorj', 'id': 'daab4c937ba34dba6621d88a2292e29a4c2ed4fd', 'size': '1587', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'views/account/login.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2623'}, {'name': 'HTML', 'bytes': '25616'}, {'name': 'JavaScript', 'bytes': '51118'}]}
// Copyright 2012 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/display/test/display_manager_test_api.h" #include <cstdarg> #include <vector> #include "base/logging.h" #include "base/ranges/algorithm.h" #include "base/strings/string_split.h" #include "build/chromeos_buildflags.h" #include "ui/display/display_layout_builder.h" #include "ui/display/manager/display_manager.h" #include "ui/display/manager/display_manager_utilities.h" #include "ui/display/manager/managed_display_info.h" #include "ui/display/screen.h" #include "ui/display/util/display_util.h" namespace display { namespace test { namespace { // Indicates the default maximum of displays that chrome device can support. constexpr size_t kDefaultMaxSupportDisplayTest = 10; DisplayInfoList CreateDisplayInfoListFromString( const std::string specs, DisplayManager* display_manager) { DisplayInfoList display_info_list; std::vector<std::string> parts = base::SplitString( specs, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); size_t index = 0; Displays list = display_manager->IsInUnifiedMode() ? display_manager->software_mirroring_display_list() : display_manager->active_display_list(); for (std::vector<std::string>::const_iterator iter = parts.begin(); iter != parts.end(); ++iter, ++index) { int64_t id = (index < list.size()) ? list[index].id() : kInvalidDisplayId; display_info_list.push_back( ManagedDisplayInfo::CreateFromSpecWithID(*iter, id)); } return display_info_list; } // Gets the display |mode| for |resolution|. Returns false if no display // mode matches the resolution, or the display is an internal display. bool GetDisplayModeForResolution(const ManagedDisplayInfo& info, const gfx::Size& resolution, ManagedDisplayMode* mode) { if (IsInternalDisplayId(info.id())) return false; const ManagedDisplayInfo::ManagedDisplayModeList& modes = info.display_modes(); DCHECK_NE(0u, modes.size()); auto iter = base::ranges::find(modes, resolution, &ManagedDisplayMode::size); if (iter == modes.end()) { DLOG(WARNING) << "Unsupported resolution was requested:" << resolution.ToString(); return false; } *mode = *iter; return true; } } // namespace size_t DisplayManagerTestApi::maximum_support_display_ = kDefaultMaxSupportDisplayTest; DisplayManagerTestApi::DisplayManagerTestApi(DisplayManager* display_manager) : display_manager_(display_manager) { DCHECK(display_manager); } DisplayManagerTestApi::~DisplayManagerTestApi() {} void DisplayManagerTestApi::ResetMaximumDisplay() { maximum_support_display_ = kDefaultMaxSupportDisplayTest; } void DisplayManagerTestApi::UpdateDisplay(const std::string& display_specs) { DisplayInfoList display_info_list = CreateDisplayInfoListFromString(display_specs, display_manager_); #if BUILDFLAG(IS_CHROMEOS_ASH) if (display_info_list.size() > maximum_support_display_) { display_manager_->configurator()->has_unassociated_display_ = true; while (display_info_list.size() > maximum_support_display_) display_info_list.pop_back(); } else { display_manager_->configurator()->has_unassociated_display_ = false; } #endif bool is_host_origin_set = false; for (const ManagedDisplayInfo& display_info : display_info_list) { if (display_info.bounds_in_native().origin() != gfx::Point(0, 0)) { is_host_origin_set = true; break; } } // Start from (1,1) so that windows won't overlap with native mouse cursor. // See |AshTestBase::SetUp()|. int next_y = 1; for (auto& info : display_info_list) { // On non-testing environment, when a secondary display is connected, a new // native (i.e. X) window for the display is always created below the // previous one for GPU performance reasons. Try to emulate the behavior // unless host origins are explicitly set. if (!is_host_origin_set) { gfx::Rect bounds(info.bounds_in_native().size()); bounds.set_x(1); bounds.set_y(next_y); next_y += bounds.height(); info.SetBounds(bounds); } // Overcan and native resolution are excluded for now as they require // special handing (has_overscan flag. resolution change makes sense // only on external). display_manager_->RegisterDisplayProperty( info.id(), info.GetRotation(Display::RotationSource::USER), /*overscan_insets=*/nullptr, /*native_resolution=*/gfx::Size(), info.device_scale_factor(), info.zoom_factor(), info.refresh_rate(), info.is_interlaced()); } display_manager_->OnNativeDisplaysChanged(display_info_list); display_manager_->UpdateInternalManagedDisplayModeListForTest(); display_manager_->RunPendingTasksForTest(); } int64_t DisplayManagerTestApi::SetFirstDisplayAsInternalDisplay() { const Display& internal = display_manager_->active_display_list_[0]; SetInternalDisplayIds({internal.id()}); return Display::InternalDisplayId(); } void DisplayManagerTestApi::SetInternalDisplayId(int64_t id) { SetInternalDisplayIds({id}); display_manager_->UpdateInternalManagedDisplayModeListForTest(); } void DisplayManagerTestApi::DisableChangeDisplayUponHostResize() { display_manager_->set_change_display_upon_host_resize(false); } const ManagedDisplayInfo& DisplayManagerTestApi::GetInternalManagedDisplayInfo( int64_t display_id) { return display_manager_->display_info_[display_id]; } void DisplayManagerTestApi::SetTouchSupport( int64_t display_id, Display::TouchSupport touch_support) { display_manager_->FindDisplayForId(display_id) ->set_touch_support(touch_support); } const Display& DisplayManagerTestApi::GetSecondaryDisplay() const { CHECK_GE(display_manager_->GetNumDisplays(), 2U); const int64_t primary_display_id = Screen::GetScreen()->GetPrimaryDisplay().id(); auto primary_display_iter = base::ranges::find( display_manager_->active_display_list_, primary_display_id, &Display::id); DCHECK(primary_display_iter != display_manager_->active_display_list_.end()); ++primary_display_iter; // If we've reach the end of |active_display_list_|, wrap back around to the // front. if (primary_display_iter == display_manager_->active_display_list_.end()) return *display_manager_->active_display_list_.begin(); return *primary_display_iter; } ScopedSetInternalDisplayId::ScopedSetInternalDisplayId( DisplayManager* display_manager, int64_t id) { DisplayManagerTestApi(display_manager).SetInternalDisplayId(id); } ScopedSetInternalDisplayId::~ScopedSetInternalDisplayId() { SetInternalDisplayIds({}); } bool SetDisplayResolution(DisplayManager* display_manager, int64_t display_id, const gfx::Size& resolution) { const ManagedDisplayInfo& info = display_manager->GetDisplayInfo(display_id); ManagedDisplayMode mode; if (!GetDisplayModeForResolution(info, resolution, &mode)) return false; return display_manager->SetDisplayMode(display_id, mode); } std::unique_ptr<DisplayLayout> CreateDisplayLayout( DisplayManager* display_manager, DisplayPlacement::Position position, int offset) { DisplayLayoutBuilder builder(Screen::GetScreen()->GetPrimaryDisplay().id()); builder.SetSecondaryPlacement( DisplayManagerTestApi(display_manager).GetSecondaryDisplay().id(), position, offset); return builder.Build(); } DisplayIdList CreateDisplayIdList2(int64_t id1, int64_t id2) { DisplayIdList list; list.push_back(id1); list.push_back(id2); SortDisplayIdList(&list); return list; } DisplayIdList CreateDisplayIdListN(int64_t start_id, size_t count) { DisplayIdList list; list.push_back(start_id); int64_t id = start_id; size_t N = count; while (count-- > 1) { id = display::GetNextSynthesizedDisplayId(id); list.push_back(id); } SortDisplayIdList(&list); DCHECK_EQ(N, list.size()); return list; } } // namespace test } // namespace display
{'content_hash': '1cf19110191440f3c42631526e3d14ad', 'timestamp': '', 'source': 'github', 'line_count': 239, 'max_line_length': 80, 'avg_line_length': 34.24267782426778, 'alnum_prop': 0.7106549364613881, 'repo_name': 'chromium/chromium', 'id': '49af77a67b54afc6d9ab5fea381dbef21f19cb9e', 'size': '8184', 'binary': False, 'copies': '5', 'ref': 'refs/heads/main', 'path': 'ui/display/test/display_manager_test_api.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package org.kohsuke.github.extras; import com.github.tomakehurst.wiremock.core.WireMockConfiguration; import com.squareup.okhttp.Cache; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.OkUrlFactory; import org.apache.commons.io.FileUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.kohsuke.github.*; import java.io.File; import java.io.IOException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.hamcrest.core.Is.is; import static org.junit.Assume.assumeFalse; import static org.junit.Assume.assumeTrue; /** * Test showing the behavior of OkHttpGitHubConnector with and without cache. * <p> * Key take aways: * * <ul> * <li>These tests are artificial and intended to highlight the differences in behavior between scenarios. However, the * differences they indicate are stark.</li> * <li>Caching reduces rate limit consumption by at least a factor of two in even the simplest case.</li> * <li>The OkHttp cache is pretty smart and will often connect read and write requests made on the same client and * invalidate caches.</li> * <li>Changes made outside the current client cause the OkHttp cache to return stale data. This is expected and correct * behavior.</li> * <li>"max-age=0" addresses the problem of external changes by revalidating caches for each request. This produces the * same number of requests as OkHttp without caching, but those requests only count towards the GitHub rate limit if * data has changes.</li> * </ul> * * @author Liam Newman */ public class OkHttpConnectorTest extends AbstractGitHubWireMockTest { public OkHttpConnectorTest() { useDefaultGitHub = false; } private static int defaultRateLimitUsed = 17; private static int okhttpRateLimitUsed = 17; private static int maxAgeZeroRateLimitUsed = 7; private static int maxAgeThreeRateLimitUsed = 7; private static int maxAgeNoneRateLimitUsed = 4; private static int userRequestCount = 0; private static int defaultNetworkRequestCount = 16; private static int okhttpNetworkRequestCount = 16; private static int maxAgeZeroNetworkRequestCount = 16; private static int maxAgeThreeNetworkRequestCount = 9; private static int maxAgeNoneNetworkRequestCount = 5; private static int maxAgeZeroHitCount = 10; private static int maxAgeThreeHitCount = 10; private static int maxAgeNoneHitCount = 11; private GHRateLimit rateLimitBefore; @Override protected WireMockConfiguration getWireMockOptions() { return super.getWireMockOptions().extensions(templating.newResponseTransformer()); } @Before public void setupRepo() throws Exception { if (mockGitHub.isUseProxy()) { GHRepository repo = getRepository(getNonRecordingGitHub()); repo.setDescription("Resetting"); // Let things settle a bit between tests when working against the live site Thread.sleep(5000); userRequestCount = 1; } } @Test public void DefaultConnector() throws Exception { this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()).build(); doTestActions(); // Testing behavior after change // Uncached connection gets updated correctly but at cost of rate limit assertThat(getRepository(gitHub).getDescription(), is("Tricky")); checkRequestAndLimit(defaultNetworkRequestCount, defaultRateLimitUsed); } @Test public void OkHttpConnector_NoCache() throws Exception { OkHttpClient client = createClient(false); OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client)); this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) .withConnector(connector) .build(); doTestActions(); // Testing behavior after change // Uncached okhttp connection gets updated correctly but at cost of rate limit assertThat(getRepository(gitHub).getDescription(), is("Tricky")); checkRequestAndLimit(okhttpNetworkRequestCount, okhttpRateLimitUsed); Cache cache = client.getCache(); assertThat("Cache", cache, is(nullValue())); } @Test public void OkHttpConnector_Cache_MaxAgeNone() throws Exception { // The responses were recorded from github, but the Date headers // have been templated to make caching behavior work as expected. // This is reasonable as long as the number of network requests matches up. snapshotNotAllowed(); OkHttpClient client = createClient(true); OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client), -1); this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) .withConnector(connector) .build(); doTestActions(); // Testing behavior after change // NOTE: this is wrong! The live data changed! // Due to max-age (default 60 from response) the cache returns the old data. assertThat(getRepository(gitHub).getDescription(), is(mockGitHub.getMethodName())); checkRequestAndLimit(maxAgeNoneNetworkRequestCount, maxAgeNoneRateLimitUsed); Cache cache = client.getCache(); // NOTE: this is actually bad. // This elevated hit count is the stale requests returning bad data took longer to detect a change. assertThat("getHitCount", cache.getHitCount(), is(maxAgeNoneHitCount)); } @Test public void OkHttpConnector_Cache_MaxAge_Three() throws Exception { // NOTE: This test is very timing sensitive. // It can be run locally to verify behavior but snapshot data is to touchy assumeFalse("Test only valid when not taking a snapshot", mockGitHub.isTakeSnapshot()); assumeTrue("Test only valid when proxying (-Dtest.github.useProxy to enable)", mockGitHub.isUseProxy()); OkHttpClient client = createClient(true); OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client), 3); this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) .withConnector(connector) .build(); doTestActions(); // Due to max-age=3 this eventually checks the site and gets updated information. Yay? assertThat(getRepository(gitHub).getDescription(), is("Tricky")); checkRequestAndLimit(maxAgeThreeNetworkRequestCount, maxAgeThreeRateLimitUsed); Cache cache = client.getCache(); assertThat("getHitCount", cache.getHitCount(), is(maxAgeThreeHitCount)); } @Ignore("ISSUE #597 - Correctly formatted Last-Modified headers cause this test to fail") @Test public void OkHttpConnector_Cache_MaxAgeDefault_Zero() throws Exception { // The responses were recorded from github, but the Date headers // have been templated to make caching behavior work as expected. // This is reasonable as long as the number of network requests matches up. snapshotNotAllowed(); OkHttpClient client = createClient(true); OkHttpConnector connector = new OkHttpConnector(new OkUrlFactory(client)); this.gitHub = getGitHubBuilder().withEndpoint(mockGitHub.apiServer().baseUrl()) .withConnector(connector) .build(); doTestActions(); // Testing behavior after change // NOTE: max-age=0 produces the same result at uncached without added rate-limit use. assertThat(getRepository(gitHub).getDescription(), is("Tricky")); checkRequestAndLimit(maxAgeZeroNetworkRequestCount, maxAgeZeroRateLimitUsed); Cache cache = client.getCache(); assertThat("getHitCount", cache.getHitCount(), is(maxAgeZeroHitCount)); } private void checkRequestAndLimit(int networkRequestCount, int rateLimitUsed) throws IOException { GHRateLimit rateLimitAfter = gitHub.rateLimit(); assertThat("Request Count", mockGitHub.getRequestCount(), is(networkRequestCount + userRequestCount)); // Rate limit must be under this value, but if it wiggles we don't care assertThat("Rate Limit Change", rateLimitBefore.remaining - rateLimitAfter.remaining, is(lessThanOrEqualTo(rateLimitUsed + userRequestCount))); } private OkHttpClient createClient(boolean useCache) throws IOException { OkHttpClient client = new OkHttpClient(); if (useCache) { File cacheDir = new File("target/cache/" + baseFilesClassPath + "/" + mockGitHub.getMethodName()); cacheDir.mkdirs(); FileUtils.cleanDirectory(cacheDir); Cache cache = new Cache(cacheDir, 100 * 1024L * 1024L); client.setCache(cache); } return client; } /** * This is a standard set of actions to be performed with each connector * * @throws Exception */ private void doTestActions() throws Exception { rateLimitBefore = gitHub.getRateLimit(); String name = mockGitHub.getMethodName(); GHRepository repo = getRepository(gitHub); // Testing behavior when nothing has changed. pollForChange("Resetting"); assertThat(getRepository(gitHub).getDescription(), is("Resetting")); repo.setDescription(name); pollForChange(name); // Test behavior after change assertThat(getRepository(gitHub).getDescription(), is(name)); // Get Tricky - make a change via a different client if (mockGitHub.isUseProxy()) { GHRepository altRepo = getRepository(getNonRecordingGitHub()); altRepo.setDescription("Tricky"); } // Testing behavior after change pollForChange("Tricky"); } private void pollForChange(String name) throws IOException, InterruptedException { getRepository(gitHub).getDescription(); Thread.sleep(500); getRepository(gitHub).getDescription(); // This is only interesting when running the max-age=3 test which currently only runs with proxy // Disabled to speed up the tests if (mockGitHub.isUseProxy()) { Thread.sleep(1000); } getRepository(gitHub).getDescription(); // This is only interesting when running the max-age=3 test which currently only runs with proxy // Disabled to speed up the tests if (mockGitHub.isUseProxy()) { Thread.sleep(4000); } } private static GHRepository getRepository(GitHub gitHub) throws IOException { return gitHub.getOrganization("hub4j-test-org").getRepository("github-api"); } }
{'content_hash': '2865b85b91ef05acce4bd9da9b4a02f2', 'timestamp': '', 'source': 'github', 'line_count': 284, 'max_line_length': 120, 'avg_line_length': 38.28169014084507, 'alnum_prop': 0.6903973509933775, 'repo_name': 'kohsuke/github-api', 'id': '761cf32b5520f715b122c1593a2633f5f1e81d06', 'size': '10872', 'binary': False, 'copies': '1', 'ref': 'refs/heads/dependabot/maven/com.fasterxml.jackson.core-jackson-databind-2.13.1', 'path': 'src/test/java/org/kohsuke/github/extras/OkHttpConnectorTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '562686'}]}
@interface WeiboProgressTwoUITests : XCTestCase @end @implementation WeiboProgressTwoUITests - (void)setUp { [super setUp]; // Put setup code here. This method is called before the invocation of each test method in the class. // In UI tests it is usually best to stop immediately when a failure occurs. self.continueAfterFailure = NO; // UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method. [[[XCUIApplication alloc] init] launch]; // In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this. } - (void)tearDown { // Put teardown code here. This method is called after the invocation of each test method in the class. [super tearDown]; } - (void)testExample { // Use recording to get started writing UI tests. // Use XCTAssert and related functions to verify your tests produce the correct results. } @end
{'content_hash': '033704535cf11183547f4648db879454', 'timestamp': '', 'source': 'github', 'line_count': 30, 'max_line_length': 178, 'avg_line_length': 35.1, 'alnum_prop': 0.7217473884140551, 'repo_name': 'yuanyi911026/First-repository', 'id': '38fc8d538c13f97c98f3856fa4ba50a2296e3076', 'size': '1245', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'WeiboProgressTwo/WeiboProgressTwoUITests/WeiboProgressTwoUITests.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '320'}, {'name': 'Objective-C', 'bytes': '356542'}]}
#include "gtest/gtest.h" #include <string> #include "DisambiguatorInterface.h" #include "DictionaryInterface.h" #include "tagsetConstants.h" #include "Tools.h" #include "Inflector.h" using Disambiguation::DisambiguatorInterface; class TestInflector : public :: testing::Test { protected: static void SetUpTestCase() { #ifdef MSVC system("chcp 1251"); std::locale::global(std::locale("Russian")); #else setlocale(LC_ALL,""); #endif dict = shared_ptr<DictionaryInterface>( DictionaryInterface::CreateDictionary()); dict->setMainWordFormFromLinkedLemmas(false); disambiguator = DisambiguatorInterface::CreateDisambiguator(dict); } static void TearDownTestCase() { // delete disambiguator; // delete dict; } void SetUp() { inflector = new inflector::Inflector(dict, disambiguator, std::string(INFLECTOR_CONFIG_PATH)); } void TearDown() { delete inflector; } static shared_ptr<DictionaryInterface> dict; static shared_ptr<DisambiguatorInterface> disambiguator; inflector::Inflector* inflector; }; shared_ptr<DictionaryInterface> TestInflector::dict; shared_ptr<DisambiguatorInterface> TestInflector::disambiguator; /*TEST_F (TestInflector, Noun_phrase_singular_to_genitive_singular) { std::wstring result = inflector->inflect(L"синий мяч", inflector::GENITIVE, inflector::NUMBER_UNSPEC); EXPECT_STREQ(L"синего мяча", result.c_str()); } TEST_F (TestInflector, Noun_phrase_singular_to_genitive_plural) { std::wstring result = inflector->inflect(L"синий мяч", inflector::GENITIVE, inflector::PLURAL); EXPECT_STREQ(L"синих мячей", result.c_str()); } TEST_F (TestInflector, Longer_group) { std::wstring result = inflector->inflect(L"маленький стол из стали", inflector::GENITIVE); EXPECT_STREQ(L"маленького стола из стали", result.c_str()); } TEST_F (TestInflector, Longer_group_super) { std::wstring result = inflector->inflect(L"малейший стол из стали", inflector::GENITIVE, inflector::SINGULAR); EXPECT_STREQ(L"малейшего стола из стали", result.c_str()); } TEST_F (TestInflector, Pronoun_singular) { std::wstring result = inflector->inflect(L"я", inflector::GENITIVE, inflector::SINGULAR); EXPECT_STREQ(L"меня", result.c_str()); } TEST_F (TestInflector, Pronoun_singular_to_plural) { std::wstring result = inflector->inflect(L"я", inflector::GENITIVE, inflector::PLURAL); EXPECT_STREQ(L"нас", result.c_str()); } TEST_F (TestInflector, Pronoun_plural) { std::wstring result = inflector->inflect(L"все возрасты", inflector::GENITIVE); EXPECT_STREQ(L"всех возрастов", result.c_str()); } TEST_F (TestInflector, stuff) { std::wstring result = inflector->inflect(L"лёд", inflector::GENITIVE); EXPECT_STREQ(L"льда", result.c_str()); }*/
{'content_hash': '5eb9d1026e90d3b0c9d0e7eb059626b4', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 114, 'avg_line_length': 27.00943396226415, 'alnum_prop': 0.6950750960530911, 'repo_name': 'zy4kamu/Coda', 'id': '2c805a2afe85aa29ede0571ea8b289e66fbc6dfd', 'size': '3021', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/test-inflector.cpp', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '48'}, {'name': 'C', 'bytes': '6587769'}, {'name': 'C++', 'bytes': '20957504'}, {'name': 'CMake', 'bytes': '50801'}, {'name': 'Makefile', 'bytes': '778300'}, {'name': 'Objective-C', 'bytes': '78643'}, {'name': 'Python', 'bytes': '46732'}, {'name': 'Shell', 'bytes': '40147'}]}
[![Documentation][godoc-img]][godoc-url] ![License][license-img] [![Build Status][travis-img]][travis-url] [![Coverage Status][coverage-img]][coverage-url] [![Report Status][goreport-img]][goreport-url] An engine to manage your components lifecycle. [![Lemon][lemon-img]][lemon-url] ## Introduction Lemon is an engine that manage your components lifecycle using a startup and shutdown mechanism. It will start every registered hook _(or daemon, service, etc...)_ and block until it receives a signal (**SIGINT**, **SIGTERM** and **SIGQUIT** for example) or when a parent context is terminated... > **NOTE:** startup and shutdown procedure will be executed in separated goroutine: so be very careful with any race conditions or deadlocks. ## Example ```go package main import ( "context" "fmt" "os" "time" "github.com/novln/lemon" ) // Let's define a simple Ping hook... type Ping struct {} // Start will be executed when lemon's engine will try to start this Hook. // Your hook can perfectly use the given context (see example), or any blocking operation... func (p *Ping) Start(ctx context.Context) error { fmt.Println("[ping] Start") for { select { case <-ctx.Done(): return nil case <-time.After(2 * time.Second): fmt.Println("[ping] Echo Request") } } } // However, if you don't use <-ctx.Done(), you must cancel your blocking operation in Stop. func (p *Ping) Stop(ctx context.Context) error { fmt.Println("[ping] Stop") return nil } func main() { timeout := 5 * time.Second ctx := context.Background() engine, err := lemon.New(ctx, lemon.Timeout(timeout), lemon.Logger(func(err error) { fmt.Fprintln(os.Stderr, err) })) if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(255) } engine.Register(&Ping{}) engine.Start() } ``` ## Versioning or Vendoring Expect compatibility break from `master` branch. Using [Go dependency management tool](https://github.com/golang/dep) is **highly recommended**. > **NOTE:** semver tags or branches could be provided, if needed. ## License This is Free Software, released under the [`MIT License`](LICENSE). [lemon-url]: https://github.com/novln/lemon [lemon-img]: https://raw.githubusercontent.com/novln/lemon/master/lemon.png [godoc-url]: https://godoc.org/github.com/novln/lemon [godoc-img]: https://godoc.org/github.com/novln/lemon?status.svg [license-img]: https://img.shields.io/badge/license-MIT-blue.svg [travis-url]: https://travis-ci.org/novln/lemon [travis-img]: https://travis-ci.org/novln/lemon.svg?branch=master [coverage-url]: https://codecov.io/gh/novln/lemon [coverage-img]: https://codecov.io/gh/novln/lemon/branch/master/graph/badge.svg [goreport-url]: https://goreportcard.com/report/novln/lemon [goreport-img]: https://goreportcard.com/badge/novln/lemon
{'content_hash': 'b316a8b030b52317f9c0ca9c56dea5fa', 'timestamp': '', 'source': 'github', 'line_count': 103, 'max_line_length': 107, 'avg_line_length': 27.019417475728154, 'alnum_prop': 0.7132590729428674, 'repo_name': 'november-eleven/lemon', 'id': 'a4e67c7b92eeaa4146926040dee731659d201245', 'size': '2792', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '32971'}]}
package com.vladsch.smart; import org.jetbrains.annotations.NotNull; public interface SmartVersionedPropertyArrayHolder<V> extends SmartVersionedPropertyHolder<V>, Iterable<SmartVersionedPropertyHolder<V>> { @NotNull SmartVersionedPropertyHolder<V> get(int index); }
{'content_hash': '1d1013fe4dfd0ea9fe70e36c0b182641', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 138, 'avg_line_length': 30.555555555555557, 'alnum_prop': 0.8254545454545454, 'repo_name': 'vsch/SmartData', 'id': 'd2e58793f47e6674108b2f13f296d6dd725e7043', 'size': '1162', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/com/vladsch/smart/SmartVersionedPropertyArrayHolder.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '78957'}, {'name': 'Kotlin', 'bytes': '551022'}]}
ACCEPTED #### According to International Plant Names Index #### Published in null #### Original name null ### Remarks null
{'content_hash': 'a1da68e49758a544890a97210da3fea5', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 31, 'avg_line_length': 9.692307692307692, 'alnum_prop': 0.7063492063492064, 'repo_name': 'mdoering/backbone', 'id': 'c3db5a629c9cc668b13e3e2a3681e89c9b75377d', 'size': '175', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Liliopsida/Poales/Poaceae/Apera/Apera arundinacea/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
/* * rt_zcfcn.c * * Real-Time Workshop code generation for Simulink model "NLPID.mdl". * * Model Version : 1.31 * Real-Time Workshop version : 7.3 (R2009a) 15-Jan-2009 * C source code generated on : Mon Mar 17 14:06:18 2014 * * Target selection: nidll_vxworks.tlc * Note: GRT includes extra infrastructure and instrumentation for prototyping * Embedded hardware selection: 32-bit Generic * Code generation objectives: Unspecified * Validation result: Not run * */ #include "rt_zcfcn.h" /* Function: rt_ZCFcn ======================================================= * Abstract: * Detect zero crossings events. */ ZCEventType rt_ZCFcn(ZCDirection zcDir, ZCSigState* prevZc, real_T currValue) { slZcEventType zcsDir; slZcEventType tempEv; ZCEventType zcEvent = NO_ZCEVENT; /* assume */ /* zcEvent matrix */ static const slZcEventType eventMatrix[4][4] = { /* ZER POS NEG UNK */ { SL_ZCS_EVENT_NUL, SL_ZCS_EVENT_Z2P, SL_ZCS_EVENT_Z2N, SL_ZCS_EVENT_NUL },/* ZER */ { SL_ZCS_EVENT_P2Z, SL_ZCS_EVENT_NUL, SL_ZCS_EVENT_P2N, SL_ZCS_EVENT_NUL },/* POS */ { SL_ZCS_EVENT_N2Z, SL_ZCS_EVENT_N2P, SL_ZCS_EVENT_NUL, SL_ZCS_EVENT_NUL },/* NEG */ { SL_ZCS_EVENT_NUL, SL_ZCS_EVENT_NUL, SL_ZCS_EVENT_NUL, SL_ZCS_EVENT_NUL }/* UNK */ }; /* get prevZcEvent and prevZcSign from prevZc */ slZcEventType prevEv = (slZcEventType)(((uint8_T)(*prevZc)) >> 2); slZcSignalSignType prevSign = (slZcSignalSignType)(((uint8_T)(*prevZc)) & 0x03); /* get current zcSignal sign from current zcSignal value */ slZcSignalSignType currSign = (slZcSignalSignType)((currValue) > 0.0 ? SL_ZCS_SIGN_POS : ((currValue) < 0.0 ? SL_ZCS_SIGN_NEG : SL_ZCS_SIGN_ZERO)); /* get current zcEvent based on prev and current zcSignal value */ slZcEventType currEv = eventMatrix[prevSign][currSign]; /* get slZcEventType from ZCDirection */ switch (zcDir) { case ANY_ZERO_CROSSING: zcsDir = SL_ZCS_EVENT_ALL; break; case FALLING_ZERO_CROSSING: zcsDir = SL_ZCS_EVENT_ALL_DN; break; case RISING_ZERO_CROSSING: zcsDir = SL_ZCS_EVENT_ALL_UP; break; default: zcsDir = SL_ZCS_EVENT_NUL; break; } /*had event, check if double zc happend remove double detection. */ if (slZcHadEvent(currEv, zcsDir)) { currEv = (slZcEventType)(slZcUnAliasEvents(prevEv, currEv)); } else { currEv = SL_ZCS_EVENT_NUL; } /* Update prevZc */ tempEv = currEv << 2; /* shift left by 2 bits */ *prevZc = (ZCSigState)((currSign) | (tempEv)); if (currEv & SL_ZCS_EVENT_ALL_DN) { zcEvent = FALLING_ZCEVENT; } else if (currEv & SL_ZCS_EVENT_ALL_UP) { zcEvent = RISING_ZCEVENT; } else { zcEvent = NO_ZCEVENT; } return zcEvent; } /* rt_ZCFcn */
{'content_hash': 'd27428e9e4d19c96de91f9d61431d303', 'timestamp': '', 'source': 'github', 'line_count': 92, 'max_line_length': 88, 'avg_line_length': 31.065217391304348, 'alnum_prop': 0.622113365990203, 'repo_name': 'NTNU-MCS/CS_EnterpriseI', 'id': 'a83fc156c984d8e48e0e7b736f63d7f84649232c', 'size': '2858', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'old files/Simulink kopier/simulink/Old/NLPID_nidll_vxworks_rtw/rt_zcfcn.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'AGS Script', 'bytes': '116448'}, {'name': 'Batchfile', 'bytes': '28199'}, {'name': 'C', 'bytes': '42454968'}, {'name': 'C++', 'bytes': '179753'}, {'name': 'HTML', 'bytes': '90461'}, {'name': 'LabVIEW', 'bytes': '726855'}, {'name': 'Makefile', 'bytes': '789944'}, {'name': 'Matlab', 'bytes': '134137'}, {'name': 'Objective-C', 'bytes': '1128875'}, {'name': 'XSLT', 'bytes': '23994'}]}
<!DOCTYPE HTML> <html> <head> <script type="text/javascript" src="{{ STATIC_URL }}js/jquery-1.11.0.min.js"></script> <link href="//vjs.zencdn.net/4.5/video-js.css" rel="stylesheet"> <script src="//vjs.zencdn.net/4.5/video.js"></script> <script> $(document).ready(function(){ var myPlayer = videojs('sign'); var aspectRatio = {{aspectRatio}}; // Make up an aspect ratio function resizeVideoJS(){ // Get the parent element's actual width var width = document.getElementById('signbody').offsetWidth; // Set width to fill parent element, Set height myPlayer.width(width).height( width * aspectRatio ); } myPlayer.ready(function(){ resizeVideoJS(); // Initialize the function window.onresize = resizeVideoJS; // Call the function on resize }); }); </script> <style> video-container { height: 100%; width: 100%; left: 0; top: 0; overflow: hidden; position: absolute; } video-container #track, #video-container #track_html5_api { min-height: 100%; min-width: 100%; height: auto !important; width: auto !important; position: absolute; left: 0; top: 0; } </style> </head> <body id='signbody'> {% if videourl %} <video id='sign' class='video-js vjs-default-skin' poster='{{posterurl}}' autoplay playsinline muted controls="true" preload='auto'> <source src='{{videourl}}' type='video/mp4' codecs='avc1.42E01E, mp4a.40.2'></source> </video> {% else %} <img src='{{ STATIC_URL }}images/no-video.png'> {% endif %} </body> </html>
{'content_hash': '75e26d8b95aa655dca5775d4e7cf2c52', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 122, 'avg_line_length': 32.23076923076923, 'alnum_prop': 0.5900954653937948, 'repo_name': 'Signbank/BSL-signbank', 'id': 'a222d6f17201d97f193f6980725f8f34dfea01a6', 'size': '1676', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'signbank/video/templates/iframe.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': '1C Enterprise', 'bytes': '1846'}, {'name': 'CSS', 'bytes': '480831'}, {'name': 'HTML', 'bytes': '244006'}, {'name': 'JavaScript', 'bytes': '1011248'}, {'name': 'PHP', 'bytes': '1052'}, {'name': 'Python', 'bytes': '986206'}]}
ACCEPTED #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': 'a832c0c09452a7b9333f36f2a3a37047', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.307692307692308, 'alnum_prop': 0.6940298507462687, 'repo_name': 'mdoering/backbone', 'id': '097c3af9354c2e1720ba9dd270a721851b4d201a', 'size': '187', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Malpighiales/Phyllanthaceae/Phyllanthus/Phyllanthus urceolatus/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
import "pixi.js"; export default class Particle extends PIXI.Graphics { constructor(data, x, y, size, speed, shape, color) { super(); this.color = color.RGBToHSL(); this.size = size; this.margin = 1; this.alpha = 1; this.destination = new PIXI.Point(x, y); this.isAnimating = false; this.distanceRatio = 0; this.speed = speed; this.aimedSize = { "width": size, "height": size }; this.aimedAlpha = 1; this.data = data; this.id = this.data["Row ID"]; this.shape = shape; this.redraw(); this.addClickListeners(); } redraw(){ this.lineStyle(0, 0xFFFFFF, 0); this.beginFill(this.color.HSLToHex(), 1); if(this.shape === "rectangle"){ this.drawRect(0, 0, this.size, this.size); } else { console.log("circle"); this.drawCircle(0, 0, this.size/2); } } transitionTo(x, y, width, height, type) { switch (type) { case "none": this.isAnimating = false; this.setPosition(x, y); this.setDestination(x, y); this.setSize(width, height); this.setAimedSize(width, height); break; case "linear": this.isAnimating = true; this.setDestination(x, y); this.setAimedSize(width, height); break; default: throw new Error(`Particles transition type not handled: ${type}`); } } animate() { if (!this.isAnimating) { return false; } if (this.x !== this.destination.x || this.y !== this.destination.y) { let deltaX = this.destination.x - this.position.x; let deltaY = this.destination.y - this.position.y; let distance = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2)); if (distance <= this.speed) { this.position.set(this.destination.x, this.destination.y); } else { this.distanceRatio = this.speed / distance; this.position.set(this.position.x + deltaX * this.distanceRatio, this.position.y + deltaY * this.distanceRatio); } } if (this.width != this.aimedSize.width || this.height != this.aimedSize.height) { let deltaX = this.aimedSize.width - this.width; let deltaY = this.aimedSize.height - this.height; if (Math.abs(this.width - this.aimedSize.width) < this.speed) { this.setSize(this.aimedSize.width, this.aimedSize.height); } else { this.setSize(this.width + deltaX * this.distanceRatio, this.height + deltaY * this.distanceRatio); } } if ( (this.aimedAlpha !== null && this.aimedAlpha !== undefined) && this.aimedAlpha !== this.alpha ) { if (Math.abs(this.alpha - this.aimedAlpha) < this.speed * 2 / 100) { this.alpha = this.aimedAlpha; } else if (this.aimedAlpha < this.alpha) { this.alpha -= this.speed * 2 / 100; } else { this.alpha += this.speed * 2 / 100; } } if ( this.x === this.destination.x && this.y === this.destination.y && this._width == this.aimedSize.width && this._height == this.aimedSize.height && this.alpha === this.aimedAlpha ) { this.isAnimating = false; } return this.isAnimating; } setPosition(x, y) { this.position.set(x, y); return this; } setAlpha(e) { this.alpha = e; return this; } setDestination(x, y) { this.destination.set(x, y); return this; } setSize(width, height) { this.width = width; this.height = height; return this; } setAimedSize(width, height) { this.aimedSize.width = width; this.aimedSize.height = height; return this; } addClickListeners(stage) { this.interactive = true; this.buttonMode = true; this.on("mouseover", function (ev) { this.color[2] = Math.max(this.color[2] + 0.1, 0); this.redraw(); }.bind(this)); this.on("mouseout", function (ev) { this.color[2] = Math.min(this.color[2] - 0.1, 1); this.redraw(); }.bind(this)); } fade(type) { this.isAnimating = true; if (type === 'in') this.aimedAlpha = 1; if (type === 'out') this.aimedAlpha = 0; return this; } }
{'content_hash': 'a038c71a7b7e95518a3f5ae871fab48e', 'timestamp': '', 'source': 'github', 'line_count': 169, 'max_line_length': 128, 'avg_line_length': 28.59171597633136, 'alnum_prop': 0.5014486754966887, 'repo_name': 'particles-masterthesis/transition', 'id': '8ec83d3b6fd6fb48b751c24267e109d8022799b6', 'size': '4832', 'binary': False, 'copies': '1', 'ref': 'refs/heads/gh-pages', 'path': 'src/js/visualization/particle.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '150107'}, {'name': 'HTML', 'bytes': '5070'}, {'name': 'JavaScript', 'bytes': '5143329'}, {'name': 'Makefile', 'bytes': '1114'}]}
.class final Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord; .super Landroid/media/session/MediaController$Callback; .source "MediaSessions.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Lcom/android/systemui/volume/MediaSessions; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x12 name = "MediaControllerRecord" .end annotation # instance fields .field private final controller:Landroid/media/session/MediaController; .field private name:Ljava/lang/String; .field private sentRemote:Z .field final synthetic this$0:Lcom/android/systemui/volume/MediaSessions; # direct methods .method static synthetic -get0(Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;)Landroid/media/session/MediaController; .locals 1 iget-object v0, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->controller:Landroid/media/session/MediaController; return-object v0 .end method .method static synthetic -get1(Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;)Ljava/lang/String; .locals 1 iget-object v0, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->name:Ljava/lang/String; return-object v0 .end method .method static synthetic -get2(Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;)Z .locals 1 iget-boolean v0, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->sentRemote:Z return v0 .end method .method static synthetic -set0(Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;Ljava/lang/String;)Ljava/lang/String; .locals 0 iput-object p1, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->name:Ljava/lang/String; return-object p1 .end method .method static synthetic -set1(Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;Z)Z .locals 0 iput-boolean p1, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->sentRemote:Z return p1 .end method .method private constructor <init>(Lcom/android/systemui/volume/MediaSessions;Landroid/media/session/MediaController;)V .locals 0 iput-object p1, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->this$0:Lcom/android/systemui/volume/MediaSessions; invoke-direct {p0}, Landroid/media/session/MediaController$Callback;-><init>()V iput-object p2, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->controller:Landroid/media/session/MediaController; return-void .end method .method synthetic constructor <init>(Lcom/android/systemui/volume/MediaSessions;Landroid/media/session/MediaController;Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;)V .locals 0 invoke-direct {p0, p1, p2}, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;-><init>(Lcom/android/systemui/volume/MediaSessions;Landroid/media/session/MediaController;)V return-void .end method .method private cb(Ljava/lang/String;)Ljava/lang/String; .locals 2 new-instance v0, Ljava/lang/StringBuilder; invoke-direct {v0}, Ljava/lang/StringBuilder;-><init>()V invoke-virtual {v0, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v0 const-string/jumbo v1, " " invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v0 iget-object v1, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->controller:Landroid/media/session/MediaController; invoke-virtual {v1}, Landroid/media/session/MediaController;->getPackageName()Ljava/lang/String; move-result-object v1 invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v0 const-string/jumbo v1, " " invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v0 invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v0 return-object v0 .end method # virtual methods .method public onAudioInfoChanged(Landroid/media/session/MediaController$PlaybackInfo;)V .locals 4 sget-boolean v1, Lcom/android/systemui/volume/D;->BUG:Z if-eqz v1, :cond_0 invoke-static {}, Lcom/android/systemui/volume/MediaSessions;->-get0()Ljava/lang/String; move-result-object v1 new-instance v2, Ljava/lang/StringBuilder; invoke-direct {v2}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v3, "onAudioInfoChanged" invoke-direct {p0, v3}, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->cb(Ljava/lang/String;)Ljava/lang/String; move-result-object v3 invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v2 invoke-static {p1}, Lcom/android/systemui/volume/Util;->playbackInfoToString(Landroid/media/session/MediaController$PlaybackInfo;)Ljava/lang/String; move-result-object v3 invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v2 const-string/jumbo v3, " sentRemote=" invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v2 iget-boolean v3, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->sentRemote:Z invoke-virtual {v2, v3}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder; move-result-object v2 invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v2 invoke-static {v1, v2}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I :cond_0 invoke-static {p1}, Lcom/android/systemui/volume/MediaSessions;->-wrap0(Landroid/media/session/MediaController$PlaybackInfo;)Z move-result v0 if-nez v0, :cond_2 iget-boolean v1, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->sentRemote:Z if-eqz v1, :cond_2 iget-object v1, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->this$0:Lcom/android/systemui/volume/MediaSessions; invoke-static {v1}, Lcom/android/systemui/volume/MediaSessions;->-get1(Lcom/android/systemui/volume/MediaSessions;)Lcom/android/systemui/volume/MediaSessions$Callbacks; move-result-object v1 iget-object v2, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->controller:Landroid/media/session/MediaController; invoke-virtual {v2}, Landroid/media/session/MediaController;->getSessionToken()Landroid/media/session/MediaSession$Token; move-result-object v2 invoke-interface {v1, v2}, Lcom/android/systemui/volume/MediaSessions$Callbacks;->onRemoteRemoved(Landroid/media/session/MediaSession$Token;)V const/4 v1, 0x0 iput-boolean v1, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->sentRemote:Z :cond_1 :goto_0 return-void :cond_2 if-eqz v0, :cond_1 iget-object v1, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->this$0:Lcom/android/systemui/volume/MediaSessions; iget-object v2, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->controller:Landroid/media/session/MediaController; invoke-virtual {v2}, Landroid/media/session/MediaController;->getSessionToken()Landroid/media/session/MediaSession$Token; move-result-object v2 iget-object v3, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->name:Ljava/lang/String; invoke-static {v1, v2, v3, p1}, Lcom/android/systemui/volume/MediaSessions;->-wrap3(Lcom/android/systemui/volume/MediaSessions;Landroid/media/session/MediaSession$Token;Ljava/lang/String;Landroid/media/session/MediaController$PlaybackInfo;)V const/4 v1, 0x1 iput-boolean v1, p0, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->sentRemote:Z goto :goto_0 .end method .method public onExtrasChanged(Landroid/os/Bundle;)V .locals 3 sget-boolean v0, Lcom/android/systemui/volume/D;->BUG:Z if-eqz v0, :cond_0 invoke-static {}, Lcom/android/systemui/volume/MediaSessions;->-get0()Ljava/lang/String; move-result-object v0 new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v2, "onExtrasChanged" invoke-direct {p0, v2}, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->cb(Ljava/lang/String;)Ljava/lang/String; move-result-object v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I :cond_0 return-void .end method .method public onMetadataChanged(Landroid/media/MediaMetadata;)V .locals 3 sget-boolean v0, Lcom/android/systemui/volume/D;->BUG:Z if-eqz v0, :cond_0 invoke-static {}, Lcom/android/systemui/volume/MediaSessions;->-get0()Ljava/lang/String; move-result-object v0 new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v2, "onMetadataChanged" invoke-direct {p0, v2}, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->cb(Ljava/lang/String;)Ljava/lang/String; move-result-object v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-static {p1}, Lcom/android/systemui/volume/Util;->mediaMetadataToString(Landroid/media/MediaMetadata;)Ljava/lang/String; move-result-object v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I :cond_0 return-void .end method .method public onPlaybackStateChanged(Landroid/media/session/PlaybackState;)V .locals 3 sget-boolean v0, Lcom/android/systemui/volume/D;->BUG:Z if-eqz v0, :cond_0 invoke-static {}, Lcom/android/systemui/volume/MediaSessions;->-get0()Ljava/lang/String; move-result-object v0 new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v2, "onPlaybackStateChanged" invoke-direct {p0, v2}, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->cb(Ljava/lang/String;)Ljava/lang/String; move-result-object v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-static {p1}, Lcom/android/systemui/volume/Util;->playbackStateToString(Landroid/media/session/PlaybackState;)Ljava/lang/String; move-result-object v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I :cond_0 return-void .end method .method public onQueueChanged(Ljava/util/List;)V .locals 3 .annotation system Ldalvik/annotation/Signature; value = { "(", "Ljava/util/List", "<", "Landroid/media/session/MediaSession$QueueItem;", ">;)V" } .end annotation sget-boolean v0, Lcom/android/systemui/volume/D;->BUG:Z if-eqz v0, :cond_0 invoke-static {}, Lcom/android/systemui/volume/MediaSessions;->-get0()Ljava/lang/String; move-result-object v0 new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v2, "onQueueChanged" invoke-direct {p0, v2}, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->cb(Ljava/lang/String;)Ljava/lang/String; move-result-object v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I :cond_0 return-void .end method .method public onQueueTitleChanged(Ljava/lang/CharSequence;)V .locals 3 sget-boolean v0, Lcom/android/systemui/volume/D;->BUG:Z if-eqz v0, :cond_0 invoke-static {}, Lcom/android/systemui/volume/MediaSessions;->-get0()Ljava/lang/String; move-result-object v0 new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v2, "onQueueTitleChanged" invoke-direct {p0, v2}, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->cb(Ljava/lang/String;)Ljava/lang/String; move-result-object v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/CharSequence;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I :cond_0 return-void .end method .method public onSessionDestroyed()V .locals 2 sget-boolean v0, Lcom/android/systemui/volume/D;->BUG:Z if-eqz v0, :cond_0 invoke-static {}, Lcom/android/systemui/volume/MediaSessions;->-get0()Ljava/lang/String; move-result-object v0 const-string/jumbo v1, "onSessionDestroyed" invoke-direct {p0, v1}, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->cb(Ljava/lang/String;)Ljava/lang/String; move-result-object v1 invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I :cond_0 return-void .end method .method public onSessionEvent(Ljava/lang/String;Landroid/os/Bundle;)V .locals 3 sget-boolean v0, Lcom/android/systemui/volume/D;->BUG:Z if-eqz v0, :cond_0 invoke-static {}, Lcom/android/systemui/volume/MediaSessions;->-get0()Ljava/lang/String; move-result-object v0 new-instance v1, Ljava/lang/StringBuilder; invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V const-string/jumbo v2, "onSessionEvent" invoke-direct {p0, v2}, Lcom/android/systemui/volume/MediaSessions$MediaControllerRecord;->cb(Ljava/lang/String;)Ljava/lang/String; move-result-object v2 invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 const-string/jumbo v2, "event=" invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 const-string/jumbo v2, " extras=" invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder; move-result-object v1 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v1 invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I :cond_0 return-void .end method
{'content_hash': '65f4472dbeb98d07b4c1b8679405eb5e', 'timestamp': '', 'source': 'github', 'line_count': 524, 'max_line_length': 245, 'avg_line_length': 31.68320610687023, 'alnum_prop': 0.7409348271292615, 'repo_name': 'BatMan-Rom/ModdedFiles', 'id': '91d2b658c87cdca6ed6b568b32812308b4afe235', 'size': '16602', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'SystemUI/smali/com/android/systemui/volume/MediaSessions$MediaControllerRecord.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'GLSL', 'bytes': '15069'}, {'name': 'HTML', 'bytes': '139176'}, {'name': 'Smali', 'bytes': '541934400'}]}
<?php class Edge_CatalogFilter_Model_Resource_Layer_Filter_Price extends Mage_Catalog_Model_Resource_Layer_Filter_Price { /** * Apply price range filter to product collection * * @param Mage_Catalog_Model_Layer_Filter_Price $filter * @return Mage_Catalog_Model_Resource_Layer_Filter_Price */ public function applyPriceRange($filter) { if (!Mage::helper('catalogfilter')->priceIsSlider()) { return parent::applyPriceRange($filter); } $interval = $filter->getInterval(); if (!$interval) { return $this; } list($from, $to) = $interval; if ($from === '' && $to === '') { return $this; } $select = $filter->getLayer()->getProductCollection()->getSelect(); $priceExpr = $this->_getPriceExpression($filter, $select, false); if ($to !== '') { $to = (float)$to; if ($from == $to) { $to += self::MIN_POSSIBLE_PRICE; } } if ($from !== '') { $select->where($priceExpr . ' >= ' . $this->_getComparingValue($from, $filter)); } if ($to !== '') { $select->where($priceExpr . ' <= ' . $this->_getComparingValue($to, $filter, false)); } return $this; } /** * Load range of product prices * * @param Mage_Catalog_Model_Layer_Filter_Price $filter * @param int $limit * @param null|int $offset * @param null|int $lowerPrice * @param null|int $upperPrice * @return array */ public function loadPrices($filter, $limit, $offset = null, $lowerPrice = null, $upperPrice = null) { if (!Mage::helper('catalogfilter')->priceIsSlider()) { return parent::loadPrices($filter, $limit, $offset, $lowerPrice, $upperPrice); } $select = $this->_getSelect($filter); $priceExpression = $this->_getPriceExpression($filter, $select); $select->columns(array( 'min_price_expr' => $this->_getFullPriceExpression($filter, $select) )); if (!is_null($lowerPrice)) { $select->where("$priceExpression >= " . $this->_getComparingValue($lowerPrice, $filter)); } if (!is_null($upperPrice)) { $select->where("$priceExpression <= " . $this->_getComparingValue($upperPrice, $filter, false)); } $select->order("$priceExpression ASC")->limit($limit, $offset); return $this->_getReadAdapter()->fetchCol($select); } /** * Load range of product prices, preceding the price * * @param Mage_Catalog_Model_Layer_Filter_Price $filter * @param float $price * @param int $index * @return array|false */ public function loadPreviousPrices($filter, $price, $index, $lowerPrice = null) { if (!Mage::helper('catalogfilter')->priceIsSlider()) { return parent::loadPreviousPrices($filter, $price, $index, $lowerPrice); } $select = $this->_getSelect($filter); $priceExpression = $this->_getPriceExpression($filter, $select); $select->columns('COUNT(*)')->where("$priceExpression <= " . $this->_getComparingValue($price, $filter, false)); if (!is_null($lowerPrice)) { $select->where("$priceExpression >= " . $this->_getComparingValue($lowerPrice, $filter)); } $offset = $this->_getReadAdapter()->fetchOne($select); if (!$offset) { return false; } return $this->loadPrices($filter, $index - $offset + 1, $offset - 1, $lowerPrice); } /** * Load range of product prices, next to the price * * @param Mage_Catalog_Model_Layer_Filter_Price $filter * @param float $price * @param int $rightIndex * @param null|int $upperPrice * @return array */ public function loadNextPrices($filter, $price, $rightIndex, $upperPrice = null) { if (!Mage::helper('catalogfilter')->priceIsSlider()) { return parent::loadNextPrices($filter, $price, $rightIndex, $upperPrice); } $select = $this->_getSelect($filter); $pricesSelect = clone $select; $priceExpression = $this->_getPriceExpression($filter, $pricesSelect); $select->columns('COUNT(*)')->where("$priceExpression > " . $this->_getComparingValue($price, $filter, false)); if (!is_null($upperPrice)) { $select->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter, false)); } $offset = $this->_getReadAdapter()->fetchOne($select); if (!$offset) { return false; } $pricesSelect ->columns(array( 'min_price_expr' => $this->_getFullPriceExpression($filter, $pricesSelect) )) ->where("$priceExpression >= " . $this->_getComparingValue($price, $filter)); if (!is_null($upperPrice)) { $pricesSelect->where("$priceExpression < " . $this->_getComparingValue($upperPrice, $filter)); } $pricesSelect->order("$priceExpression DESC")->limit($rightIndex - $offset + 1, $offset - 1); return array_reverse($this->_getReadAdapter()->fetchCol($pricesSelect)); } /** * Apply attribute filter to product collection * * @deprecated since 1.7.0.0 * @param Mage_Catalog_Model_Layer_Filter_Price $filter * @param int $range * @param int $index the range factor * @return Mage_Catalog_Model_Resource_Layer_Filter_Price */ public function applyFilterToCollection($filter, $range, $index) { if (!Mage::helper('catalogfilter')->priceIsSlider()) { return parent::applyFilterToCollection($filter, $range, $index); } $select = $filter->getLayer()->getProductCollection()->getSelect(); $priceExpr = $this->_getPriceExpression($filter, $select); $filter->getLayer()->getProductCollection() ->getSelect() ->where($priceExpr . ' >= ' . $this->_getComparingValue(($range * ($index - 1)), $filter)) ->where($priceExpr . ' <= ' . $this->_getComparingValue(($range * $index), $filter, false)); return $this; } }
{'content_hash': 'a3f327ece0045b9713bb28d40c5fa977', 'timestamp': '', 'source': 'github', 'line_count': 173, 'max_line_length': 120, 'avg_line_length': 36.335260115606935, 'alnum_prop': 0.5680878141902641, 'repo_name': 'outeredge/edge-magento-module-catalogfilter', 'id': '2fc0a6a14d30f0464159624cb1d09ccb5e66ef85', 'size': '6286', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/code/local/Edge/CatalogFilter/Model/Resource/Layer/Filter/Price.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '5331'}, {'name': 'PHP', 'bytes': '31824'}]}
<!DOCTYPE html> <!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]--> <!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]--> <!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]--> <!--[if (gte IE 9)|!(IE)]><!--><html lang="en"> <!--<![endif]--> <head> <!-- Basic Page Needs ================================================== --> <meta charset="utf-8"> <title>UWCL</title> <meta name="description" content=""> <meta name="author" content=""> <style> #results{ min-height: 100%!important; overflow: auto; margin-bottom: 50px!important; padding-bottom: 50px!important; } #ajaxloader{ display: block; margin-left: auto; margin-right: auto; } ol li:before{ background-color: none !important; } footer{ margin-top: 50px; } .img-responsive{ position: relative; margin-right:0%!important; margin-left:22.5%!important; padding:0px!important; } .carousel-inner > .item > img { margin: 0 auto!important; } .row{ margin-right:0%!important; margin-left:0%!important; } </style> <!-- Mobile Specific Metas ================================================== --> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <!-- CSS ================================================== --> <link rel="stylesheet" type="text/css" href="../css/bootstrap.css"> <link rel="stylesheet" type="text/css" href="../css/style.css"> <!-- Fonts ================================================== --> <link href='https://fonts.googleapis.com/css?family=Lato:300,400,700' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:700,400,300,200' rel='stylesheet' type='text/css'> <!-- Javascript ================================================== --> <script type="text/javascript" src="../js/modernizr.custom.79639.js"></script> <!-- Favicons ================================================== --> <link rel="shortcut icon" href="../img/favicon.ico"> <link rel="apple-touch-icon" href="../img/apple-touch-icon.png"> <link rel="apple-touch-icon" sizes="57x57" href="../img/apple-touch-icon-57x57.png"> <link rel="apple-touch-icon" sizes="72x72" href="../img/apple-touch-icon-72x72.png"> <link rel="apple-touch-icon" sizes="114x114" href="../img/apple-touch-icon-114x114.png"> <link rel="apple-touch-icon" sizes="144x144" href="../img/apple-touch-icon-144x144.png"> </head> <body> <!--Collapsing NavBar --> <nav class="navbar"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"><img src="../img/UWCL_logo_white.png" alt="UW Cartography Lab" style="width:80px;height:auto;"></a> </div> <div class="collapse navbar-collapse navbar-right" id="myNavbar"> <ul class="nav navbar-nav navText"> <li><a href="../production/index.html" id="navText">Production</a></li> <li><a href="../research/index.html" id="navText">Research</a></li> <li><a href="index.html" id="navText">Education</a></li> <li><a href="../people/index.html" id="navText">People</a></li> </ul> </div> </div> </nav> <!--end of header --> <div class='container'> <div class='col-md-12'> <h1 class='page-header'>Education</h1> <div id="productionCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#productionCarousel" data-slide-to="0" class="active"></li> <li data-target="#productionCarousel" data-slide-to="1"></li> <li data-target="#productionCarousel" data-slide-to="2"></li> <li data-target="#productionCarousel" data-slide-to="3"></li> <li data-target="#productionCarousel" data-slide-to="4"></li> <li data-target="#productionCarousel" data-slide-to="5"></li> <li data-target="#productionCarousel" data-slide-to="6"></li> <li data-target="#productionCarousel" data-slide-to="7"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner" role="listbox"> <div class="item active"> <img src="img/Spring2017_HumanTrafficking.png" class='img-responsive' alt="..."> <div class="carousel-caption"> <h1 id="caption-light">NACIS 2017 Student Dynamic Map Award Winner!</h1> <p><i>Human Trafficking at Home</i> by Leanne Abraham, Alicia Iverson, and Ross Thorn</p> </div> </div> <div class="item"> <img src="img/Spring2016_WoodenShips.png" class='img-responsive' alt="..."> <div class="carousel-caption"> <h1 id="caption-light">NACIS 2016 Student Dynamic Map Award Winner!</h1> <p><i>Wooden Ships</i> by Scott Farley, Meghan Kelly, Starr Moss</p> </div> </div> <div class="item"> <img src="img/Fall2014_EvanApplegate.png" class='img-responsive' alt="..."> <div class="carousel-caption" id="caption-box"> <h1 id="caption-dark">NACIS 2015 Student Award Winner!</h1> <p><i>Bay Area California</i> by Evan Applegate</p> </div> </div> <div class="item"> <img src="img/Fall2015_ClareTrainor.jpg" class='img-responsive' alt="..."> </div> <div class="item"> <img src="img/Fall2013_Abplanalp.jpg" class='img-responsive' alt="..."> </div> <div class="item"> <img src="img/Fall2015_KatieKowalsky.jpg" class='img-responsive' alt="..."> </div> <div class="item"> <img src="img/Fall2015_CallaLittle.jpg" class='img-responsive' alt="..."> </div> <div class="item"> <img src="img/Fall2016_ZihanSong.png" class='img-responsive' alt="..."> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#productionCarousel" role="button" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#productionCarousel" role="button" data-slide="next"> <span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> </div> <div class='container'> <div class='overview'> <div class='col-md-8'> <p>At its core, the Cart Lab is a space for students to make and learn. We support a range of formal and informal educational activities to help students mold themselves into well-rounded professionals. The Cart Lab participates in the development and maintenance of four cartography courses offered by the UW Geography Department. We also collaborate with a number of Geography faculty to enrich non-design courses with mapping exercises and materials. </p> <p class='nomargin'>Beyond curriculum, we organize a number of workshops and hosted meet-up events, enabling students to come together with faculty, staff, and professionals to exchange ideas and support each other. Across activities, the Cart Lab as a “maker”-space emphasizes collaborative learning experiences and the building of community across graduate, undergraduate, and certificate students. We are proud to report a 95% placement rate for our students in the profession. <a href="../people/index.html">Please contact the leadership team if you are a UW student who would like to get involved in the Cart Lab…</a> </p> </div> <div class='col-md-4'> <h3>Education</h3> <div> <p> <a href="curriculum.html">Curriculum Overview</a><br> <a href="G370/G370FA2019.html">G370: Introduction to Cart</a><br> <a href="G572/G572FA2019.html">G572: Graphic Design</a><br> <a href="G575/G575SP2020.html">G575: Interactive Cart</a><br> <a href="G970.html">G970: Cartography Seminar</a><br> <a href="designChallenge.html">Design Challenge</a><br> <a href="CLES.html">Cart Lab Education Series (CLES)</a><br> <a href="eduResources.html">Educational Resources </a><br> <a href="../contact.html">Contact Us</a><br> </div> <h3>Featured Education Projects</h3> <ul style="list-style-type: square; margin-left: 25px;"> <li style="padding-bottom: 10px"> <a href="https://rossthorn.github.io/human-trafficking-viz/" target="_block">Human Trafficking at Home: Reporting and Legislating in the United States by <i>Leanne Abraham, Alicia Iverson, and Ross Thorn</i></a> </li> <li style="padding-bottom: 10px"> <a href="https://nacis.org/awards/2016-winner-wooden-ships/" target="_block">Wooden Ships by <i>Scott Farley, Meghan Kelly and Starr Moss</i></a> </li> </ul> </div> </div> </div> <div class='container'> <div class='row'> <div class='col-md-8'> <h2>Maker-space and Cart Lab Policy</h2> <p>A maker-space is driven by a collective, defined by the needs and expectations of its members and contributors. Each year, Cart Labbers old and new come together to define how we want to make use of the space. As cartographic practice and professional expectations change, so too does the composition of the space. <!--<a>View our most recent Cart Lab policy…</a> --> </p> <h2>Pedagogical Research in Cartography</h2> <p>We constantly strive to teach better, and our location within the UW Geography Department enables us to complement our basic research profile with pedagogical research on cartography for k-12 and higher education. To date, we have completed pedagogical research on active and situated learning, collaborative learning, scaffolded instructional design, spiraled curricula, distance education, and the role of maps in geographic and place-based education. </p> <h2>Cartography Courses at UW Geography</h2> <p>The first cartography course at UW–Madison dates to 1937, and today the UW Geography Department offers five courses that partially or fully cover cartography: G170 Our Digital Globe, G370 Introduction to Cartography, G572 Graphic Design in Cartography, G575 Interactive Cartography & Geovisualization, and G970 Seminar in Cartography. The cartography courses support undergraduate majors in Geography and Cartography/GIS, certificates in GIS and Visual Cultures, and both resident and online masters in Cartography/GIS. <a href="curriculum.html#cartcourses">Learn more about courses in the UW Geography Department…</a> </p> <h2>Cartography Curriculum at UW Geography</h2> <p>The cartography curriculum continues to evolve as modern cartography continues to advance at an unprecedented rate. The curriculum emphasizes a broad understanding of cartography/GIS paired with explicit geography courses. We offer six programs, so you can find the right one to fit your needs.</p> <a href="curriculum.html">Learn more about the UW Cartography Curriculum...</a> </p> <h2>Cart Lab Education Series</h2> <p>The Cart Lab Education Series (CLES) is a weekly series of short (10–15 minute), highly informal presentations, in which we share tips, tricks, fun map things, professional skills, past projects, etc. CLES presentations are student-driven, and include occasional guest presentations from professionals and alum. CLES is open to all Cart Lab students and friends! <a href="CLES.html">View our CLES schedule and explore resources from prior meetings…</a> </p> <h2>Design Challenge</h2> <p>The best way to learn about design is by designing. The Cart Lab Design Challenge gives students a focused, “lock-in”-like experience that mimics the daily design constraints they will experience in the real world. The Cart Lab collaborates with Geography faculty to define the geographic problem context, giving the department an opportunity to come together as a community around an important and timely issue. <a href="designChallenge.html">Learn more about the Design Challenge and see the results from prior years…</a> </p> <h2>Educational Resources </h2> <p>There are far too many conceptual and technical competencies in cartography for any single program to maintain. We strongly believe in sharing the load collectively by using and contributing to Educational Resources . We are a <a href="http://www.geoforall.org/">Geo For All</a> lab, an educational initiative of OSGeo and the International Cartography Association, and share formal and informal tutorials and resources from our cartography curriculum. <a href="eduResources.html">View our Educational Resources …</a> </p> <h6><a href="../contact.html">Contact Us About Education</a></h6> </div> </div> </div> <footer class="footer navbar-fixed-bottom"> <div class="container"> <div class="row"> <div class="align-center"> <br> <img src="../img/UWCL_logo_gray.png"> <p>Copyright 2019&copy; All Rights Reserved.</p> </div> </div> </div> </div> <!--End Boxed Container--> </footer> <script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <script src="../js/jquery.cookie.js" type="text/javascript"> </script> <script src="../js/jquery.ba-cond.min.js" type="text/javascript"> </script> <script src="../js/jquery.slitslider.js" type="text/javascript"> </script> <script src="../js/jquery.prettyPhoto.js" type="text/javascript"> </script> <script src="../js/custom.js" type="text/javascript"> </script> <script src="../js/main.js" type="text/javascript"> </script> </body> </html>
{'content_hash': '767d8785b0b8d0e4db06f8411d1f748c', 'timestamp': '', 'source': 'github', 'line_count': 335, 'max_line_length': 526, 'avg_line_length': 42.6179104477612, 'alnum_prop': 0.6541990614274708, 'repo_name': 'uwcartlab/uwcl.preview', 'id': '2f5a9e1ea8af6b3aba4110080c08fb41ebcd4fd1', 'size': '14301', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'education/index.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4282744'}, {'name': 'HTML', 'bytes': '2193375'}, {'name': 'Hack', 'bytes': '946'}, {'name': 'JavaScript', 'bytes': '13145213'}, {'name': 'PHP', 'bytes': '19117702'}, {'name': 'Python', 'bytes': '13695'}, {'name': 'R', 'bytes': '2652'}, {'name': 'Ruby', 'bytes': '821'}, {'name': 'Shell', 'bytes': '4608'}, {'name': 'Smarty', 'bytes': '34428'}]}
<DocInternals> <AlwaysLoose> <bool>false</bool> <bool>false</bool> <bool>false</bool> <bool>false</bool> <bool>false</bool> <bool>false</bool> <bool>false</bool> </AlwaysLoose> <FieldSrcTables> <String>6</String> <String>1</String> <String>Rights</String> <String>7</String> <String>1</String> <String>Rights</String> <String>8</String> <String>1</String> <String>Rights</String> <String>9</String> <String>1</String> <String>Rights</String> <String>10</String> <String>1</String> <String>Rights</String> <String>11</String> <String>2</String> <String>R_Groups</String> <String>OnlyOriginalPersona</String> <String>12</String> <String>1</String> <String>R_Groups</String> <String>13</String> <String>1</String> <String>R_Groups</String> <String>14</String> <String>1</String> <String>R_Groups</String> <String>15</String> <String>1</String> <String>R_Groups</String> <String>16</String> <String>1</String> <String>R_Groups</String> <String>17</String> <String>1</String> <String>R_Groups</String> <String>18</String> <String>1</String> <String>R_Groups</String> <String>19</String> <String>1</String> <String>R_Groups</String> <String>20</String> <String>1</String> <String>R_Groups</String> <String>21</String> <String>1</String> <String>R_Groups</String> <String>22</String> <String>1</String> <String>R_Groups</String> <String>23</String> <String>1</String> <String>OnlyOriginalPersona</String> <String>24</String> <String>1</String> <String>OnlyOriginalPersona</String> <String>25</String> <String>1</String> <String>OnlyOriginalPersona</String> <String>26</String> <String>1</String> <String>OnlyOriginalPersona</String> <String>27</String> <String>1</String> <String>OnlyOriginalPersona</String> <String>28</String> <String>1</String> <String>OnlyOriginalPersona</String> <String>29</String> <String>1</String> <String>OnlyOriginalPersona</String> <String>30</String> <String>1</String> <String>OnlyOriginalPersona</String> <String>31</String> <String>1</String> <String>OnlyOriginalPersona</String> <String>32</String> <String>1</String> <String>Testdatentabelle</String> <String>33</String> <String>1</String> <String>Testdatentabelle</String> </FieldSrcTables> <TableViewData> <Pos></Pos> <CtlInfo> <InternalView> <Tables> <TableViewTableWinSaveInfo> <Pos> <Left>742</Left> <Top>394</Top> <Width>414</Width> <Height>118</Height> </Pos> <Caption>FRENZELSRV2008</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>840</Left> <Top>621</Top> <Width>100</Width> <Height>46</Height> </Pos> <Caption>$orphan_FRENZELSRV2008.Document</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>1079</Left> <Top>621</Top> <Width>100</Width> <Height>46</Height> </Pos> <Caption>$orphan_FRENZELSRV2008.ObjectID</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>1081</Left> <Top>392</Top> <Width>272</Width> <Height>100</Height> </Pos> <Caption>Rights</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>1111</Left> <Top>498</Top> <Width>100</Width> <Height>64</Height> </Pos> <Caption>Rights-1</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>602</Left> <Top>181</Top> <Width>100</Width> <Height>100</Height> </Pos> <Caption>Tmp_R_Groups</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>1070</Left> <Top>560</Top> <Width>273</Width> <Height>190</Height> </Pos> <Caption>R_Groups</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>528</Left> <Top>459</Top> <Width>146</Width> <Height>154</Height> </Pos> <Caption>TmpPersona</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>829</Left> <Top>741</Top> <Width>100</Width> <Height>46</Height> </Pos> <Caption>CleanInternalPersonalReference</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>1012</Left> <Top>649</Top> <Width>100</Width> <Height>64</Height> </Pos> <Caption>CleanInternalPersonalReference-1</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>1075</Left> <Top>421</Top> <Width>273</Width> <Height>118</Height> </Pos> <Caption>$Syn 1 Table</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>525</Left> <Top>116</Top> <Width>189</Width> <Height>190</Height> </Pos> <Caption>TablePersona</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>713</Left> <Top>473</Top> <Width>100</Width> <Height>64</Height> </Pos> <Caption>TablePersona-1</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>568</Left> <Top>561</Top> <Width>363</Width> <Height>208</Height> </Pos> <Caption>OnlyOriginalPersona</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>506</Left> <Top>278</Top> <Width>193</Width> <Height>64</Height> </Pos> <Caption>OnlyOriginalPersona-1</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>933</Left> <Top>292</Top> <Width>100</Width> <Height>64</Height> </Pos> <Caption>Testdatentabelle</Caption> </TableViewTableWinSaveInfo> <TableViewTableWinSaveInfo> <Pos> <Left>670</Left> <Top>298</Top> <Width>299</Width> <Height>64</Height> </Pos> <Caption>TmpGroupToUser</Caption> </TableViewTableWinSaveInfo> </Tables> <BroomPoints></BroomPoints> <ConnectionPoints></ConnectionPoints> <ZoomFactor>3FF0000000000000</ZoomFactor> </InternalView> <SourceView></SourceView> </CtlInfo> <Mode>0</Mode> </TableViewData> <Bookmarks></Bookmarks> <SavedByVersion>11.20.11922.0409</SavedByVersion> <ForceBackEndMacroExecution>false</ForceBackEndMacroExecution> <FieldTags> <ScriptBased> <FieldTagData> <Tag>$key</Tag> <FieldNames> <String>$Field</String> <String>$Table</String> <String>ID</String> </FieldNames> </FieldTagData> <FieldTagData> <Tag>$hidden</Tag> <FieldNames> <String>$Field</String> <String>$Table</String> <String>$Rows</String> <String>$Fields</String> <String>$FieldNo</String> <String>$Info</String> </FieldNames> </FieldTagData> <FieldTagData> <Tag>$system</Tag> <FieldNames> <String>$Field</String> <String>$Table</String> <String>$Rows</String> <String>$Fields</String> <String>$FieldNo</String> <String>$Info</String> </FieldNames> </FieldTagData> <FieldTagData> <Tag>$ascii</Tag> <FieldNames> <String>$Field</String> <String>$Table</String> <String>$Info</String> <String>RightObjectId</String> <String>Suffix_RightRule</String> <String>Name1</String> <String>Name4</String> <String>Name5</String> <String>Name6</String> <String>Pers_Name</String> <String>Pers_Vorname</String> <String>Email</String> <String>OSUser</String> <String>MatchCriteria</String> <String>F1</String> <String>F2</String> </FieldNames> </FieldTagData> <FieldTagData> <Tag>$text</Tag> <FieldNames> <String>$Field</String> <String>$Table</String> <String>$Info</String> <String>RightUser</String> <String>RightRule</String> <String>RightObjectId</String> <String>Suffix_RightRule</String> <String>Name</String> <String>Name1</String> <String>Name2</String> <String>Name3</String> <String>Name4</String> <String>Name5</String> <String>Name6</String> <String>Path</String> <String>RightsOrgaComparission</String> <String>Pers_Name</String> <String>Pers_Vorname</String> <String>Email</String> <String>OSUser</String> <String>MatchCriteria</String> <String>F1</String> <String>F2</String> </FieldNames> </FieldTagData> <FieldTagData> <Tag>$numeric</Tag> <FieldNames> <String>$Rows</String> <String>$Fields</String> <String>$FieldNo</String> <String>RightAccess</String> <String>ID</String> <String>ParentID</String> <String>Deep</String> <String>PersonalNr</String> <String>DateDeleted</String> <String>RIGHTSCOUNT</String> <String>ControlSum</String> </FieldNames> </FieldTagData> <FieldTagData> <Tag>$integer</Tag> <FieldNames> <String>$Rows</String> <String>$Fields</String> <String>$FieldNo</String> <String>RightAccess</String> <String>ID</String> <String>ParentID</String> <String>Deep</String> <String>PersonalNr</String> <String>DateDeleted</String> <String>RIGHTSCOUNT</String> <String>ControlSum</String> </FieldNames> </FieldTagData> </ScriptBased> <Interactive></Interactive> </FieldTags> <FieldComments></FieldComments> <TableComments></TableComments> <CreatePrjFolder>false</CreatePrjFolder> <LinkedTables></LinkedTables> </DocInternals>
{'content_hash': '6a50a905f68c88668461aec955959e89', 'timestamp': '', 'source': 'github', 'line_count': 388, 'max_line_length': 64, 'avg_line_length': 30.15463917525773, 'alnum_prop': 0.5287179487179487, 'repo_name': 'FrenzelGmbH/QVRights', 'id': '06b739d29ebcbc7c37a547586f65a0482581d8db', 'size': '11702', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Rights/Solution Rights-prj/DocInternals.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
require 'spec_helper' require 'vk/api/fave/methods/add_user' RSpec.describe Vk::API::Fave::Methods::AddUser do subject(:model) { described_class } it { is_expected.to be < Dry::Struct } it { is_expected.to be < Vk::Schema::Method } describe 'attributes' do subject(:attributes) { model.instance_methods(false) } it { is_expected.to include :user_id } end end
{'content_hash': 'fc77508221cc3f0773a66767c4eb5164', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 58, 'avg_line_length': 27.142857142857142, 'alnum_prop': 0.6868421052631579, 'repo_name': 'alsemyonov/vk', 'id': '5818cb3f5831f034506c3c681a8180e679ce0819', 'size': '410', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/vk/api/fave/methods/add_user_spec.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '2302334'}, {'name': 'Shell', 'bytes': '389'}]}
require File.dirname(__FILE__) + '/../../test_helper' module TableHelper class TableTest < ActiveSupport::TestCase def test_new table = Table.new(:events, []) assert_not_nil(table.columns, "columns") assert_not_nil(table.collection, "collection") end def test_new_with_args table = Table.new(:racers, [], :caption => "Members") assert_not_nil(table.columns, "columns") assert_equal(:racers, table.collection_symbol, "collection_symbol") assert_equal(:racer, table.record_symbol, "record_symbol") assert_not_nil(table.collection, "collection") end def test_column table = Table.new(:events, []) table.column(:name) table.column(:member) assert_equal(2, table.columns.size, "columns") end end end
{'content_hash': '8a47a3361ed794faa54ae6644400f577', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 73, 'avg_line_length': 31.115384615384617, 'alnum_prop': 0.6341161928306551, 'repo_name': 'alpendergrass/montanacycling', 'id': '48c880fc181462cd695125b673a5dba045ab0505', 'size': '809', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/functional/table_helper/table_test.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '2445692'}, {'name': 'PHP', 'bytes': '66548'}, {'name': 'Perl', 'bytes': '38839'}, {'name': 'Python', 'bytes': '47933'}, {'name': 'Ruby', 'bytes': '1117765'}]}
class MessagesController < ApplicationController before_filter :require_user def show @message = current_user.messages.find(params[:id]) if !current_user.read_messages.exists?(:message_id => @message.id) @read = current_user.read_messages.build(:message_id => @message.id) @read.save! end respond_to do |format| format.json { render :json => @message } end end def index per_page = params[:per_page].to_i if per_page < 1 per_page = 5 elsif per_page > 50 per_page = 50 end page = params[:page].to_i if page < 1 page = 1 end folder = "inbox" folder = params[:folder] if ['inbox', 'sent'].include?(params[:folder]) if folder == 'inbox' @messages = current_user.received_messages.where({}) elsif folder == 'sent' @messages = current_user.sent_messages.where({}) end @messages = @messages.order('created_at DESC, id ASC') @messages = @messages.paginate(:page => page, :per_page => per_page) messages = [] @messages.each do |message| messages << message.serializable_hash_for_user(current_user) end respond_to do |format| format.json { render :json => { :results => messages, :count => @messages.total_entries, :pages => @messages.total_pages, :page => @messages.current_page } } end end def create @message = current_user.sent_messages.build(params[:message]) respond_to do |format| if @message.save format.json { render :json => @message } else format.json { render :json => { :errors => @message.errors.full_messages }, :status => :unprocessable_entity } end end end def destroy @deleted = current_user.deleted_messages.build(:message_id => params[:id]) respond_to do |format| format.json { if @deleted.save render :json => { :success => true } else render :json => { :success => false }, :status => :unprocessable_entity end } end end end
{'content_hash': 'b46d61aad22483fb3e93d0e3f89322e8', 'timestamp': '', 'source': 'github', 'line_count': 91, 'max_line_length': 145, 'avg_line_length': 21.560439560439562, 'alnum_prop': 0.6279306829765545, 'repo_name': 'eugeniodepalo/manistone-api', 'id': '69c82b2487d20c46442cb5a25c21378644dfbf3e', 'size': '1962', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/controllers/messages_controller.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '3177'}, {'name': 'JavaScript', 'bytes': '5998'}, {'name': 'Ruby', 'bytes': '89448'}]}
var JSON5 = require('json5'); module.exports = function(grunt) { grunt.registerMultiTask('json-minify', 'JSON minification task', function() { var totalInBytes = 0; var totalOutBytes = 0; var totalProfitPercents = 0; var files = grunt.file.expand(this.data.files); function calcCompression(inBytes, outBytes) { var profitPercents = 100 - outBytes * 100 / inBytes; return (Math.round((inBytes / 1024) * 1000) / 1000) + ' KiB - ' + ((Math.round(profitPercents * 10) / 10) + '%').green + ' = ' + (Math.round((outBytes / 1024) * 1000) / 1000) + ' KiB'; } files.forEach(function(filepath) { var data = grunt.file.read(filepath); var compressed; try { compressed = JSON5.stringify(JSON5.parse(data)); } catch (err) { grunt.fail.warn(err); } grunt.file.write(filepath, compressed); // and print profit info grunt.log.writeln('File "' + filepath + '":'); grunt.log.ok(calcCompression(data.length, compressed.length)); totalInBytes += data.length; totalOutBytes += compressed.length; }); grunt.log.writeln('\nTotal compressed: ' + files.length + ' files'); grunt.log.ok(calcCompression(totalInBytes, totalOutBytes)); }); };
{'content_hash': 'b5a5df6c8e51b191df6874fe3f52fa77', 'timestamp': '', 'source': 'github', 'line_count': 41, 'max_line_length': 79, 'avg_line_length': 31.170731707317074, 'alnum_prop': 0.6142410015649452, 'repo_name': 'hortonworks-gallery/hortonworks-gallery.github.io', 'id': '62707cb6e3380c87a68fcecd4ee3ff67747bda39', 'size': '1436', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'node_modules/grunt-json-minify/tasks/json-minify.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '21991'}, {'name': 'HTML', 'bytes': '39269'}, {'name': 'JavaScript', 'bytes': '18563'}, {'name': 'Python', 'bytes': '1157'}]}
Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **defaultSyntax** | [**SolaceTopicsDTO**](SolaceTopicsDTO.md) | | [optional] **mqttSyntax** | [**SolaceTopicsDTO**](SolaceTopicsDTO.md) | | [optional]
{'content_hash': '65233bb657b0c1a3739164290b17ed5e', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 78, 'avg_line_length': 36.142857142857146, 'alnum_prop': 0.5019762845849802, 'repo_name': 'wso2/product-apim', 'id': '1e97c0f32c32ef90b1322660eb08e8cf5739ea73', 'size': '321', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'modules/integration/tests-common/clients/store/docs/AdditionalSubscriptionInfoSolaceTopicsObjectDTO.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '34412'}, {'name': 'CSS', 'bytes': '62967'}, {'name': 'HTML', 'bytes': '19955'}, {'name': 'Handlebars', 'bytes': '2861'}, {'name': 'Java', 'bytes': '14978005'}, {'name': 'JavaScript', 'bytes': '306906'}, {'name': 'Jinja', 'bytes': '465120'}, {'name': 'Jupyter Notebook', 'bytes': '4346'}, {'name': 'Less', 'bytes': '199838'}, {'name': 'Mustache', 'bytes': '71460'}, {'name': 'Python', 'bytes': '39021'}, {'name': 'Scala', 'bytes': '3419'}, {'name': 'Shell', 'bytes': '45764'}, {'name': 'XSLT', 'bytes': '8193'}]}
package org.springframework.ldap.odm.core.impl; import org.springframework.ldap.odm.annotations.DnAttribute; import org.springframework.ldap.odm.annotations.Entry; import org.springframework.ldap.odm.annotations.Id; import javax.naming.Name; /** * @author Mattias Hellborg Arthursson */ @Entry(objectClasses = {"inetOrgPerson", "organizationalPerson", "person", "top"}) public class UnitTestPersonWithIndexedDnAttributes { @Id private Name dn; @DnAttribute(value = "cn", index=2) private String fullName; @DnAttribute(value = "ou", index=1) private String company; @DnAttribute(value= "c", index=0) private String country; public void setFullName(String fullName) { this.fullName = fullName; } public void setCompany(String company) { this.company = company; } public void setCountry(String country) { this.country = country; } }
{'content_hash': 'b9b6962c6f2ffddf0d4be90c0f30f836', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 82, 'avg_line_length': 23.666666666666668, 'alnum_prop': 0.7020585048754063, 'repo_name': 'thomasdarimont/spring-ldap', 'id': 'ca33b6cea572820c3244715525e1716f09c23210', 'size': '1543', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'core/src/test/java/org/springframework/ldap/odm/core/impl/UnitTestPersonWithIndexedDnAttributes.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '727'}, {'name': 'HTML', 'bytes': '4289'}, {'name': 'Java', 'bytes': '2233284'}, {'name': 'PHP', 'bytes': '367'}, {'name': 'Python', 'bytes': '2635'}, {'name': 'Ruby', 'bytes': '531'}, {'name': 'Shell', 'bytes': '135'}, {'name': 'XSLT', 'bytes': '1220'}]}
<?php if (!defined('IN_CKFINDER')) exit; /** * @package CKFinder * @subpackage Core * @copyright CKSource - Frederico Knabben */ /** * Include file system utils class */ require_once CKFINDER_CONNECTOR_LIB_DIR . "/Utils/FileSystem.php"; /** * @package CKFinder * @subpackage Core * @copyright CKSource - Frederico Knabben */ class CKFinder_Connector_Core_FolderHandler { /** * CKFinder_Connector_Core_ResourceTypeConfig object * * @var CKFinder_Connector_Core_ResourceTypeConfig * @access private */ private $_resourceTypeConfig; /** * ResourceType name * * @var string * @access private */ private $_resourceTypeName = ""; /** * Client path * * @var string * @access private */ private $_clientPath = "/"; /** * Url * * @var string * @access private */ private $_url; /** * Server path * * @var string * @access private */ private $_serverPath; /** * Thumbnails server path * * @var string * @access private */ private $_thumbsServerPath; /** * ACL mask * * @var int * @access private */ private $_aclMask; /** * Folder info * * @var mixed * @access private */ private $_folderInfo; /** * Thumbnails folder info * * @var mized * @access private */ private $_thumbsFolderInfo; function __construct() { if (isset($_GET["type"])) { $this->_resourceTypeName = (string)$_GET["type"]; } if (isset($_GET["currentFolder"])) { $this->_clientPath = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding((string)$_GET["currentFolder"]); } if (!strlen($this->_clientPath)) { $this->_clientPath = "/"; } else { if (substr($this->_clientPath, -1, 1) != "/") { $this->_clientPath .= "/"; } if (substr($this->_clientPath, 0, 1) != "/") { $this->_clientPath = "/" . $this->_clientPath; } } $this->_aclMask = -1; } /** * Get resource type config * * @return CKFinder_Connector_Core_ResourceTypeConfig * @access public */ public function &getResourceTypeConfig() { if (!isset($this->_resourceTypeConfig)) { $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $this->_resourceTypeConfig = $_config->getResourceTypeConfig($this->_resourceTypeName); } if (is_null($this->_resourceTypeConfig)) { $connector =& CKFinder_Connector_Core_Factory::getInstance("Core_Connector"); $oErrorHandler =& $connector->getErrorHandler(); $oErrorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_TYPE); } return $this->_resourceTypeConfig; } /** * Get resource type name * * @return string * @access public */ public function getResourceTypeName() { return $this->_resourceTypeName; } /** * Get Client path * * @return string * @access public */ public function getClientPath() { return $this->_clientPath; } /** * Get Url * * @return string * @access public */ public function getUrl() { if (is_null($this->_url)) { $this->_resourceTypeConfig = $this->getResourceTypeConfig(); if (is_null($this->_resourceTypeConfig)) { $connector =& CKFinder_Connector_Core_Factory::getInstance("Core_Connector"); $oErrorHandler =& $connector->getErrorHandler(); $oErrorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_TYPE); $this->_url = ""; } else { $this->_url = $this->_resourceTypeConfig->getUrl() . ltrim($this->getClientPath(), "/"); } } return $this->_url; } /** * Get server path * * @return string * @access public */ public function getServerPath() { if (is_null($this->_serverPath)) { $this->_resourceTypeConfig = $this->getResourceTypeConfig(); $this->_serverPath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_resourceTypeConfig->getDirectory(), ltrim($this->_clientPath, "/")); } return $this->_serverPath; } /** * Get server path to thumbnails directory * * @access public * @return string */ public function getThumbsServerPath() { if (is_null($this->_thumbsServerPath)) { $this->_resourceTypeConfig = $this->getResourceTypeConfig(); $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $_thumbnailsConfig = $_config->getThumbnailsConfig(); // Get the resource type directory. $this->_thumbsServerPath = CKFinder_Connector_Utils_FileSystem::combinePaths($_thumbnailsConfig->getDirectory(), $this->_resourceTypeConfig->getName()); // Return the resource type directory combined with the required path. $this->_thumbsServerPath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_thumbsServerPath, ltrim($this->_clientPath, '/')); if (!is_dir($this->_thumbsServerPath)) { if(!CKFinder_Connector_Utils_FileSystem::createDirectoryRecursively($this->_thumbsServerPath)) { /** * @todo Ckfinder_Connector_Utils_Xml::raiseError(); perhaps we should return error * */ } } } return $this->_thumbsServerPath; } /** * Get ACL Mask * * @return int * @access public */ public function getAclMask() { $_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config"); $_aclConfig = $_config->getAccessControlConfig(); if ($this->_aclMask == -1) { $this->_aclMask = $_aclConfig->getComputedMask($this->_resourceTypeName, $this->_clientPath); } return $this->_aclMask; } /** * Check ACL * * @access public * @param int $aclToCkeck * @return boolean */ public function checkAcl($aclToCkeck) { $aclToCkeck = intval($aclToCkeck); $maska = $this->getAclMask(); return (($maska & $aclToCkeck) == $aclToCkeck); } }
{'content_hash': 'b1524ade642d6a0b350a9d642b67f1de', 'timestamp': '', 'source': 'github', 'line_count': 261, 'max_line_length': 164, 'avg_line_length': 26.528735632183906, 'alnum_prop': 0.5209416522241479, 'repo_name': 'choeng/admin', 'id': 'ba5bec3dc3fa15809821d37e7bcc2db67b0e163c', 'size': '7361', 'binary': False, 'copies': '35', 'ref': 'refs/heads/master', 'path': 'public/vendor/ckfinder/core/connector/php/php5/Core/FolderHandler.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '120'}, {'name': 'CSS', 'bytes': '920510'}, {'name': 'HTML', 'bytes': '1254975'}, {'name': 'JavaScript', 'bytes': '1530946'}, {'name': 'PHP', 'bytes': '154752'}]}
package net.ripe.db.whois.common.dao.jdbc.index; import net.ripe.db.whois.common.dao.RpslObjectInfo; import net.ripe.db.whois.common.rpsl.AttributeType; import net.ripe.db.whois.common.rpsl.ObjectType; import net.ripe.db.whois.common.rpsl.RpslObject; import org.junit.Before; import org.junit.Test; import java.util.List; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; public class IndexWithLocalAsTest extends IndexTestBase { private IndexWithLocalAs subject; @Before public void setup() { subject = new IndexWithLocalAs(AttributeType.LOCAL_AS); } @Test public void add_to_index() { RpslObject rpslObject = RpslObject.parse("inet-rtr: test\nlocal-as: AS1234"); final int objectId = addObject(rpslObject); RpslObjectInfo rpslObjectInfo = new RpslObjectInfo(objectId, ObjectType.INET_RTR, rpslObject.getKey()); checkIndex(objectId, ""); final int rows = subject.addToIndex(whoisTemplate, rpslObjectInfo, rpslObject, "AS1234"); assertThat(rows, is(1)); checkIndex(objectId, "AS1234"); } @Test public void find_in_index() { RpslObject rpslObject = RpslObject.parse("inet-rtr: test\nlocal-as: AS1234"); final int objectId = addObject(rpslObject); addLocalAsToIndex(rpslObject, "AS1234"); RpslObjectInfo rpslObjectInfo = new RpslObjectInfo(objectId, ObjectType.INET_RTR, rpslObject.getKey()); final List<RpslObjectInfo> results = subject.findInIndex(whoisTemplate, "invalid"); checkIndex(objectId, "AS1234"); } @Test public void not_found_in_index() throws Exception { final List<RpslObjectInfo> results = subject.findInIndex(whoisTemplate, "invalid"); assertThat(results.size(), is(0)); } private int addObject(final RpslObject rpslObject) { databaseHelper.addObject("inet-rtr: " + rpslObject.findAttribute(AttributeType.INET_RTR).getValue()); return getObjectId(rpslObject); } private int addLocalAsToIndex(final RpslObject rpslObject, final String localAs) { return whoisTemplate.update("UPDATE inet_rtr SET local_as = ? WHERE object_id = ?", localAs, getObjectId(rpslObject)); } private void checkIndex(final int objectId, final String localAs) { assertThat(whoisTemplate.queryForObject("SELECT local_as FROM inet_rtr WHERE object_id = ?", String.class, objectId), is(localAs)); } }
{'content_hash': '93c0f2d5ebb4dd157d6020af00228423', 'timestamp': '', 'source': 'github', 'line_count': 68, 'max_line_length': 139, 'avg_line_length': 36.3235294117647, 'alnum_prop': 0.7072874493927126, 'repo_name': 'michelafrinic/WHOIS', 'id': 'd5081563b8f25a99009b1e33bc6e5c05aaf1090d', 'size': '2470', 'binary': False, 'copies': '3', 'ref': 'refs/heads/afrinic', 'path': 'whois-commons/src/test/java/net/ripe/db/whois/common/dao/jdbc/index/IndexWithLocalAsTest.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Groovy', 'bytes': '4006685'}, {'name': 'Java', 'bytes': '4501182'}, {'name': 'Shell', 'bytes': '1939'}]}
module DropletKit class ContainerRegistryResource < ResourceKit::Resource include ErrorHandlingResourcable resources do action :get, 'GET /v2/registry' do handler(200) { |response| ContainerRegistryMapping.extract_single(response.body, :read) } end action :create, 'POST /v2/registry' do body { |object| ContainerRegistryMapping.representation_for(:create, object) } handler(201) { |response, registry| ContainerRegistryMapping.extract_into_object(registry, response.body, :read) } handler(422) { |response| ErrorMapping.fail_with(FailedCreate, response.body) } end action :delete, 'DELETE /v2/registry' do handler(204) { |response| true } end action :docker_credentials, 'GET /v2/registry/docker-credentials' do handler(200) { |response| response.body } end end end end
{'content_hash': '6768cae8d9e548c0cd13829ab86c5441', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 122, 'avg_line_length': 35.48, 'alnum_prop': 0.6809470124013529, 'repo_name': 'digitalocean/droplet_kit', 'id': 'bf267e14170cba32968f4c1689a38920e326fc97', 'size': '918', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'lib/droplet_kit/resources/container_registry_resource.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '313808'}]}
(function($) { /** * Extending default values */ $.extend($.datepicker._defaults, { 'stepMinutes': 1, // Number of minutes to step up/down 'stepHours': 1, // Number of hours to step up/down 'time24h': false, // True if 24h time 'showTime': false, // Show timepicker with datepicker 'altTimeField': '' // Selector for an alternate field to store time into }); /** * _hideDatepicker must be called with null */ $.datepicker._connectDatepickerOverride = $.datepicker._connectDatepicker; $.datepicker._connectDatepicker = function(target, inst) { $.datepicker._connectDatepickerOverride(target, inst); // showButtonPanel is required with timepicker if (this._get(inst, 'showTime')) { inst.settings['showButtonPanel'] = true; } var showOn = this._get(inst, 'showOn'); if (showOn == 'button' || showOn == 'both') { // Unbind all click events inst.trigger.unbind('click'); // Bind new click event inst.trigger.click(function() { if ($.datepicker._datepickerShowing && $.datepicker._lastInput == target) $.datepicker._hideDatepicker(null); // This override is all about the "null" else $.datepicker._showDatepicker(target); return false; }); } }; /** * Datepicker does not have an onShow event so I need to create it. * What I actually doing here is copying original _showDatepicker * method to _showDatepickerOverload method. */ $.datepicker._showDatepickerOverride = $.datepicker._showDatepicker; $.datepicker._showDatepicker = function (input) { // keep the current value var originalval = input.value; // Keep the first 10 chars for now yyyy-mm-dd - this removes the time part which was breaking the standardDatePicker parsing code input.value = originalval.length>10 ? originalval.substring(0, 10) : originalval; // Call the original method which will show the datepicker $.datepicker._showDatepickerOverride(input); // Put it back input.value = originalval; input = input.target || input; // find from button/image trigger if (input.nodeName.toLowerCase() != 'input') input = $('input', input.parentNode)[0]; // Do not show timepicker if datepicker is disabled if ($.datepicker._isDisabledDatepicker(input)) return; // Get instance to datepicker var inst = $.datepicker._getInst(input); var showTime = $.datepicker._get(inst, 'showTime'); // If showTime = True show the timepicker if (showTime) $.timepicker.show(input); }; /** * Same as above. Here I need to extend the _checkExternalClick method * because I don't want to close the datepicker when the sliders get focus. */ $.datepicker._checkExternalClickOverride = $.datepicker._checkExternalClick; $.datepicker._checkExternalClick = function (event) { if (!$.datepicker._curInst) return; var $target = $(event.target); if (($target.parents('#' + $.timepicker._mainDivId).length == 0)) { $.datepicker._checkExternalClickOverride(event); } }; /** * Datepicker has onHide event but I just want to make it simple for you * so I hide the timepicker when datepicker hides. */ $.datepicker._hideDatepickerOverride = $.datepicker._hideDatepicker; $.datepicker._hideDatepicker = function(input, duration) { // Some lines from the original method var inst = this._curInst; if (!inst || (input && inst != $.data(input, PROP_NAME))) return; // Get the value of showTime property var showTime = this._get(inst, 'showTime'); if (input === undefined && showTime) { if (inst.input) { inst.input.val(this._formatDate(inst)); inst.input.trigger('change'); // fire the change event } this._updateAlternate(inst); if (showTime) $.timepicker.update(this._formatDate(inst)); } // Hide datepicker $.datepicker._hideDatepickerOverride(input, duration); // Hide the timepicker if enabled if (showTime) { $.timepicker.hide(); } }; /** * This is a complete replacement of the _selectDate method. * If showed with timepicker do not close when date is selected. */ $.datepicker._selectDate = function(id, dateStr) { var target = $(id); var inst = this._getInst(target[0]); var showTime = this._get(inst, 'showTime'); dateStr = (dateStr != null ? dateStr : this._formatDate(inst)); if (!showTime) { if (inst.input) inst.input.val(dateStr); this._updateAlternate(inst); } var onSelect = this._get(inst, 'onSelect'); if (onSelect) onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback else if (inst.input && !showTime) inst.input.trigger('change'); // fire the change event if (inst.inline) this._updateDatepicker(inst); else if (!inst.stayOpen) { if (showTime) { this._updateDatepicker(inst); } else { this._hideDatepicker(null, this._get(inst, 'duration')); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) != 'object') inst.input[0].focus(); // restore focus this._lastInput = null; } } }; /** * We need to resize the timepicker when the datepicker has been changed. */ $.datepicker._updateDatepickerOverride = $.datepicker._updateDatepicker; $.datepicker._updateDatepicker = function(inst) { $.datepicker._updateDatepickerOverride(inst); $.timepicker.resize(); }; function Timepicker() {} Timepicker.prototype = { init: function() { this._mainDivId = 'ui-timepicker-div'; this._inputId = null; this._orgValue = null; this._orgHour = null; this._orgMinute = null; this._colonPos = -1; this._visible = false; this.tpDiv = $('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible" style="width: 100px; display: none; position: absolute;"></div>'); this._generateHtml(); }, show: function (input) { // Get instance to datepicker var inst = $.datepicker._getInst(input); this._time24h = $.datepicker._get(inst, 'time24h'); this._altTimeField = $.datepicker._get(inst, 'altTimeField'); var stepMinutes = parseInt($.datepicker._get(inst, 'stepMinutes'), 10) || 1; var stepHours = parseInt($.datepicker._get(inst, 'stepHours'), 10) || 1; if (60 % stepMinutes != 0) { stepMinutes = 1; } if (24 % stepHours != 0) { stepHours = 1; } $('#hourSlider').slider('option', 'max', 24 - stepHours); $('#hourSlider').slider('option', 'step', stepHours); $('#minuteSlider').slider('option', 'max', 60 - stepMinutes); $('#minuteSlider').slider('option', 'step', stepMinutes); this._inputId = input.id; if (!this._visible) { this._parseTime(); this._orgValue = $('#' + this._inputId).val(); } this.resize(); $('#' + this._mainDivId).show(); this._visible = true; var dpDiv = $('#' + $.datepicker._mainDivId); var dpDivPos = dpDiv.position(); var viewWidth = (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth) + $(document).scrollLeft(); var tpRight = this.tpDiv.offset().left + this.tpDiv.outerWidth(); if (tpRight > viewWidth) { dpDiv.css('left', dpDivPos.left - (tpRight - viewWidth) - 5); this.tpDiv.css('left', dpDiv.offset().left + dpDiv.outerWidth() + 'px'); } }, update: function (fd) { var curTime = $('#' + this._mainDivId + ' span.fragHours').text() + ':' + $('#' + this._mainDivId + ' span.fragMinutes').text(); if (!this._time24h) { curTime += ' ' + $('#' + this._mainDivId + ' span.fragAmpm').text(); } var curDate = $('#' + this._inputId).val(); $('#' + this._inputId).val(fd + ' ' + curTime); if (this._altTimeField) { $(this._altTimeField).each(function() { $(this).val(curTime); }); } }, hide: function () { this._visible = false; $('#' + this._mainDivId).hide(); }, resize: function () { var dpDiv = $('#' + $.datepicker._mainDivId); var dpDivPos = dpDiv.position(); var hdrHeight = $('#' + $.datepicker._mainDivId + ' > div.ui-datepicker-header:first-child').height(); $('#' + this._mainDivId + ' > div.ui-datepicker-header:first-child').css('height', hdrHeight); this.tpDiv.css({ 'height': dpDiv.height(), 'top' : dpDivPos.top, 'left' : dpDivPos.left + dpDiv.outerWidth() + 'px' }); $('#hourSlider').css('height', this.tpDiv.height() - (3.5 * hdrHeight)); $('#minuteSlider').css('height', this.tpDiv.height() - (3.5 * hdrHeight)); }, _generateHtml: function () { var html = ''; html += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix ui-corner-all">'; html += '<div class="ui-datepicker-title" style="margin:0">'; html += '<span class="fragHours">08</span><span class="delim">:</span><span class="fragMinutes">45</span> <span class="fragAmpm"></span></div></div><table>'; html += '<tr><th>Hour</th><th>Minute</th></tr>'; html += '<tr><td align="center"><div id="hourSlider" class="slider"></div></td><td align="center"><div id="minuteSlider" class="slider"></div></td></tr>'; html += '</table>'; this.tpDiv.empty().append(html); $('body').append(this.tpDiv); var self = this; $('#hourSlider').slider({ orientation: "vertical", range: 'min', min: 0, max: 23, step: 1, slide: function(event, ui) { self._writeTime('hour', ui.value); }, stop: function(event, ui) { $('#' + self._inputId).focus(); } }); $('#minuteSlider').slider({ orientation: "vertical", range: 'min', min: 0, max: 59, step: 1, slide: function(event, ui) { self._writeTime('minute', ui.value); }, stop: function(event, ui) { $('#' + self._inputId).focus(); } }); $('#hourSlider > a').css('padding', 0); $('#minuteSlider > a').css('padding', 0); }, _writeTime: function (type, value) { if (type == 'hour') { if (!this._time24h) { if (value < 12) { $('#' + this._mainDivId + ' span.fragAmpm').text('am'); } else { $('#' + this._mainDivId + ' span.fragAmpm').text('pm'); value -= 12; } if (value == 0) value = 12; } else { $('#' + this._mainDivId + ' span.fragAmpm').text(''); } if (value < 10) value = '0' + value; $('#' + this._mainDivId + ' span.fragHours').text(value); } if (type == 'minute') { if (value < 10) value = '0' + value; $('#' + this._mainDivId + ' span.fragMinutes').text(value); } }, _parseTime: function () { var dt = $('#' + this._inputId).val(); this._colonPos = dt.search(':'); var m = 0, h = 0, a = ''; if (this._colonPos != -1) { h = parseInt(dt.substr(this._colonPos - 2, 2), 10); m = parseInt(dt.substr(this._colonPos + 1, 2), 10); a = jQuery.trim(dt.substr(this._colonPos + 3, 3)); } a = a.toLowerCase(); if (a != 'am' && a != 'pm') { a = ''; } if (h < 0) h = 0; if (m < 0) m = 0; if (h > 23) h = 23; if (m > 59) m = 59; if (a == 'pm' && h < 12) h += 12; if (a == 'am' && h == 12) h = 0; this._setTime('hour', h); this._setTime('minute', m); this._orgHour = h; this._orgMinute = m; }, _setTime: function (type, value) { if (isNaN(value)) value = 0; if (value < 0) value = 0; if (value > 23 && type == 'hour') value = 23; if (value > 59 && type == 'minute') value = 59; if (type == 'hour') { $('#hourSlider').slider('value', value); } if (type == 'minute') { $('#minuteSlider').slider('value', value); } this._writeTime(type, value); } }; $.timepicker = new Timepicker(); $('document').ready(function () {$.timepicker.init();}); })(jQuery);
{'content_hash': 'e2bb2e5ad3b45d1e9aa9f74de3592235', 'timestamp': '', 'source': 'github', 'line_count': 409, 'max_line_length': 240, 'avg_line_length': 31.78484107579462, 'alnum_prop': 0.5453846153846154, 'repo_name': 'aadfPT/Umbraco-CMS', 'id': 'f5034b47070f378bbf5626d0e34ef7187e573f18', 'size': '13311', 'binary': False, 'copies': '66', 'ref': 'refs/heads/dev-v7.8', 'path': 'src/Umbraco.Web.UI/umbraco_client/DateTimePicker/timepicker.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '254057'}, {'name': 'Batchfile', 'bytes': '11092'}, {'name': 'C#', 'bytes': '18530968'}, {'name': 'CSS', 'bytes': '576950'}, {'name': 'HTML', 'bytes': '740242'}, {'name': 'JavaScript', 'bytes': '3678842'}, {'name': 'PLpgSQL', 'bytes': '80494'}, {'name': 'PowerShell', 'bytes': '69174'}, {'name': 'XSLT', 'bytes': '50045'}]}
/// <reference path='fourslash.ts' /> //// class A { //// /*a*/private _a: string;/*b*/ //// } goTo.select("a", "b"); edit.applyRefactor({ refactorName: "Generate 'get' and 'set' accessors", actionName: "Generate 'get' and 'set' accessors", actionDescription: "Generate 'get' and 'set' accessors", newContent: `class A { private _a: string; public get /*RENAME*/a(): string { return this._a; } public set a(value: string) { this._a = value; } }`, });
{'content_hash': '72af1692bc9b14862b8e13944943187f', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 60, 'avg_line_length': 24.238095238095237, 'alnum_prop': 0.5618860510805501, 'repo_name': 'Microsoft/TypeScript', 'id': 'ed01e35964febc20a4d2e9b7f5da053837974a6f', 'size': '509', 'binary': False, 'copies': '13', 'ref': 'refs/heads/main', 'path': 'tests/cases/fourslash/refactorConvertToGetAccessAndSetAccess4.ts', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '6254'}, {'name': 'JavaScript', 'bytes': '202322'}, {'name': 'Shell', 'bytes': '53'}, {'name': 'TypeScript', 'bytes': '139268941'}]}
class Reference attr_reader :kind, :number def initialize(kind, number) @kind = kind @number = number end def resolve(hashTable, bangTable) case @kind when "#" result = hashTable[@number] when "!" result = bangTable[@number] else raise end raise unless result result end end def parse(string) result = [] until string.empty? before, match, string = string.partition(/[!#]([0-9]+)/) result << before if match.empty? result << string break end result << Reference.new(match[0..0], match[1..-1].to_i) end result end class MetaData attr_reader :index, :name, :parent def initialize(index, name, parent) @index = index @name = name @parent = parent end end $definitions = [] $declarations = {} $attributes = [] $metaData = {} $attributesBackMap = {} $count = 0 loop { line = $stdin.readline if line =~ /^; NOTE: THIS IS A COMBINED MODULE/ puts line puts $stdin.read exit 0 end break if line =~ /^define/ } puts "; NOTE: THIS IS A COMBINED MODULE" # Loop over all definitions. shouldContinue = true while shouldContinue # We're starting a new definition. body = "" loop { line = $stdin.readline break if line.chomp == "}" body += line } body = parse(body) declarations=[] metaDataMap=[] attributeMap = [] unresolvedMetaData = [] loop { line = $stdin.gets if not line shouldContinue = false break elsif line =~ /^define/ break elsif line =~ /^declare/ declarations << parse(line) elsif line =~ /!([0-9]+) = metadata !{metadata !\"([a-zA-Z0-9_]+)\"}/ index = $1.to_i name = $2 unless $metaData[name] $metaData[name] = MetaData.new($metaData.size, name, nil) end metaDataMap[index] = $metaData[$2].index elsif line =~ /!([0-9]+) = metadata !{metadata !\"([a-zA-Z0-9_]+)\", metadata !([0-9]+)/ metaData = MetaData.new($1.to_i, $2, $3.to_i) unresolvedMetaData << metaData elsif line =~ /attributes #([0-9]+) = / attributeNumber = $1.to_i attributeBody = $~.post_match if $attributesBackMap[attributeBody] attributeMap[attributeNumber] = $attributesBackMap[attributeBody] else attributeMap[attributeNumber] = $attributes.size $attributesBackMap[attributeBody] = $attributes.size $attributes << attributeBody end end } # Iteratively resolve meta-data references until unresolvedMetaData.empty? index = 0 while index < unresolvedMetaData.size metaData = unresolvedMetaData[index] if $metaData[metaData.name] metaDataMap[metaData.index] = $metaData[metaData.name].index unresolvedMetaData[index] = unresolvedMetaData[-1] unresolvedMetaData.pop elsif metaDataMap[metaData.parent] metaDataMap[metaData.index] = $metaData.size $metaData[metaData.name] = MetaData.new($metaData.size, metaData.name, metaDataMap[metaData.parent]) unresolvedMetaData[index] = unresolvedMetaData[-1] unresolvedMetaData.pop else index += 1 end end end # Output the body with all of the things remapped. puts "define i64 @jsBody_#{$count += 1}(i64) {" body.each { | thing | if thing.is_a? Reference print(thing.kind + thing.resolve(attributeMap, metaDataMap).to_s) else print(thing) end } puts "}" # Figure out what to do with declarations. declarations.each { | declaration | declaration = declaration.map { | thing | if thing.is_a? Reference thing.kind + thing.resolve(attributeMap, metaDataMap).to_s else thing end } declaration = declaration.join('') next if $declarations[declaration] $declarations[declaration] = true } end $declarations.each_key { | declaration | puts declaration } $attributes.each_with_index { | attribute, index | puts "attributes ##{index} = #{attribute}" } $metaData.each_value { | metaData | print "!#{metaData.index} = metadata !{metadata !\"#{metaData.name}\"" if metaData.parent print ", metadata !#{metaData.parent}" end puts "}" }
{'content_hash': 'e3ad87d7ad3ab9c778eaff293691ad5a', 'timestamp': '', 'source': 'github', 'line_count': 186, 'max_line_length': 116, 'avg_line_length': 26.231182795698924, 'alnum_prop': 0.5380200860832137, 'repo_name': 'klim-iv/phantomjs-qt5', 'id': 'c3f2efe150b7b4b3d46534271c9084239cd42342', 'size': '6227', 'binary': False, 'copies': '3', 'ref': 'refs/heads/qt5', 'path': 'src/webkit/Tools/ReducedFTL/combineModules.rb', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '291913'}, {'name': 'Awk', 'bytes': '3965'}, {'name': 'C', 'bytes': '42431954'}, {'name': 'C++', 'bytes': '128347641'}, {'name': 'CSS', 'bytes': '778535'}, {'name': 'CoffeeScript', 'bytes': '46367'}, {'name': 'D', 'bytes': '1931'}, {'name': 'Emacs Lisp', 'bytes': '8191'}, {'name': 'IDL', 'bytes': '191984'}, {'name': 'Java', 'bytes': '232840'}, {'name': 'JavaScript', 'bytes': '16127527'}, {'name': 'Objective-C', 'bytes': '10465655'}, {'name': 'PHP', 'bytes': '1223'}, {'name': 'Perl', 'bytes': '1296504'}, {'name': 'Python', 'bytes': '5916339'}, {'name': 'Ruby', 'bytes': '381483'}, {'name': 'Shell', 'bytes': '1005210'}, {'name': 'Smalltalk', 'bytes': '1308'}, {'name': 'VimL', 'bytes': '3731'}, {'name': 'XSLT', 'bytes': '50637'}]}
package internal import ( "context" "errors" "fmt" "strings" "sync" "github.com/Azure/azure-sdk-for-go/sdk/internal/log" "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/amqpwrap" "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/exported" "github.com/Azure/azure-sdk-for-go/sdk/messaging/azservicebus/internal/utils" ) type LinksWithID struct { Sender AMQPSender Receiver AMQPReceiver RPC RPCLink ID LinkID } type RetryWithLinksFn func(ctx context.Context, lwid *LinksWithID, args *utils.RetryFnArgs) error type AMQPLinks interface { EntityPath() string ManagementPath() string Audience() string // Get will initialize a session and call its link.linkCreator function. // If this link has been closed via Close() it will return an non retriable error. Get(ctx context.Context) (*LinksWithID, error) // Retry will run your callback, recovering links when necessary. Retry(ctx context.Context, name log.Event, operation string, fn RetryWithLinksFn, o exported.RetryOptions) error // RecoverIfNeeded will check if an error requires recovery, and will recover // the link or, possibly, the connection. RecoverIfNeeded(ctx context.Context, linkID LinkID, err error) error // Close will close the the link. // If permanent is true the link will not be auto-recreated if Get/Recover // are called. All functions will return `ErrLinksClosed` Close(ctx context.Context, permanent bool) error // CloseIfNeeded closes the links or connection if the error is recoverable. // Use this if you don't want to recreate the connection/links at this point. CloseIfNeeded(ctx context.Context, err error) RecoveryKind // ClosedPermanently is true if AMQPLinks.Close(ctx, true) has been called. ClosedPermanently() bool } // AMQPLinksImpl manages the set of AMQP links (and detritus) typically needed to work // within Service Bus: // // - An *goamqp.Sender or *goamqp.Receiver AMQP link (could also be 'both' if needed) // - A `$management` link // - an *goamqp.Session // // State management can be done through Recover (close and reopen), Close (close permanently, return failures) // and Get() (retrieve latest version of all AMQPLinksImpl, or create if needed). type AMQPLinksImpl struct { // NOTE: values need to be 64-bit aligned. Simplest way to make sure this happens // is just to make it the first value in the struct // See: // Godoc: https://pkg.go.dev/sync/atomic#pkg-note-BUG // PR: https://github.com/Azure/azure-sdk-for-go/pull/16847 id LinkID entityPath string managementPath string audience string createLink CreateLinkFunc getRecoveryKindFunc func(err error) RecoveryKind mu sync.RWMutex // RPCLink lets you interact with the $management link for your entity. RPCLink RPCLink // the AMQP session for either the 'sender' or 'receiver' link session amqpwrap.AMQPSession // these are populated by your `createLinkFunc` when you construct // the amqpLinks Sender AMQPSenderCloser Receiver AMQPReceiverCloser // whether this links set has been closed permanently (via Close) // Recover() does not affect this value. closedPermanently bool cancelAuthRefreshLink func() cancelAuthRefreshMgmtLink func() ns NamespaceForAMQPLinks } // CreateLinkFunc creates the links, using the given session. Typically you'll only create either an // *amqp.Sender or a *amqp.Receiver. AMQPLinks handles it either way. type CreateLinkFunc func(ctx context.Context, session amqpwrap.AMQPSession) (AMQPSenderCloser, AMQPReceiverCloser, error) type NewAMQPLinksArgs struct { NS NamespaceForAMQPLinks EntityPath string CreateLinkFunc CreateLinkFunc GetRecoveryKindFunc func(err error) RecoveryKind } // NewAMQPLinks creates a session, starts the claim refresher and creates an associated // management link for a specific entity path. func NewAMQPLinks(args NewAMQPLinksArgs) AMQPLinks { l := &AMQPLinksImpl{ entityPath: args.EntityPath, managementPath: fmt.Sprintf("%s/$management", args.EntityPath), audience: args.NS.GetEntityAudience(args.EntityPath), createLink: args.CreateLinkFunc, closedPermanently: false, getRecoveryKindFunc: args.GetRecoveryKindFunc, ns: args.NS, } return l } // ManagementPath is the management path for the associated entity. func (links *AMQPLinksImpl) ManagementPath() string { return links.managementPath } // recoverLink will recycle all associated links (mgmt, receiver, sender and session) // and recreate them using the link.linkCreator function. func (links *AMQPLinksImpl) recoverLink(ctx context.Context, theirLinkRevision LinkID) error { log.Writef(exported.EventConn, "Recovering link only") links.mu.RLock() closedPermanently := links.closedPermanently ourLinkRevision := links.id links.mu.RUnlock() if closedPermanently { return NewErrNonRetriable("link was closed by user") } // cheap check before we do the lock if ourLinkRevision.Link != theirLinkRevision.Link { // we've already recovered past their failure. return nil } links.mu.Lock() defer links.mu.Unlock() // check once more, just in case someone else modified it before we took // the lock. if links.id.Link != theirLinkRevision.Link { // we've already recovered past their failure. return nil } err := links.initWithoutLocking(ctx) if err != nil { return err } return nil } // Recover will recover the links or the connection, depending // on the severity of the error. func (links *AMQPLinksImpl) RecoverIfNeeded(ctx context.Context, theirID LinkID, origErr error) error { if origErr == nil || IsCancelError(origErr) { return nil } log.Writef(exported.EventConn, "Recovering link for error %s", origErr.Error()) select { case <-ctx.Done(): return ctx.Err() default: } rk := links.getRecoveryKindFunc(origErr) if rk == RecoveryKindLink { if err := links.recoverLink(ctx, theirID); err != nil { log.Writef(exported.EventConn, "failed to recreate link: %s", err.Error()) return err } log.Writef(exported.EventConn, "Recovered links") return nil } else if rk == RecoveryKindConn { if err := links.recoverConnection(ctx, theirID); err != nil { log.Writef(exported.EventConn, "failed to recreate connection: %s", err.Error()) return err } log.Writef(exported.EventConn, "Recovered connection and links") return nil } log.Writef(exported.EventConn, "Recovered, no action needed") return nil } func (links *AMQPLinksImpl) recoverConnection(ctx context.Context, theirID LinkID) error { log.Writef(exported.EventConn, "Recovering connection (and links)") links.mu.Lock() defer links.mu.Unlock() created, err := links.ns.Recover(ctx, uint64(theirID.Conn)) if err != nil { log.Writef(exported.EventConn, "Recover connection failure: %s", err) return err } // We'll recreate the link if: // - `created` is true, meaning we recreated the AMQP connection (ie, all old links are invalid) // - the link they received an error on is our current link, so it needs to be recreated. // (if it wasn't the same then we've already recovered and created a new link, // so no recovery would be needed) if created || theirID.Link == links.id.Link { log.Writef(exported.EventConn, "recreating link: c: %v, current:%v, old:%v", created, links.id, theirID) if err := links.initWithoutLocking(ctx); err != nil { return err } } return nil } // LinkID is ID that represent our current link and the client used to create it. // These are used when trying to determine what parts need to be recreated when // an error occurs, to prevent recovering a connection/link repeatedly. // See amqpLinks.RecoverIfNeeded() for usage. type LinkID struct { // Conn is the ID of the connection we used to create our links. Conn uint64 // Link is the ID of our current link. Link uint64 } // Get will initialize a session and call its link.linkCreator function. // If this link has been closed via Close() it will return an non retriable error. func (l *AMQPLinksImpl) Get(ctx context.Context) (*LinksWithID, error) { l.mu.RLock() sender, receiver, mgmtLink, revision, closedPermanently := l.Sender, l.Receiver, l.RPCLink, l.id, l.closedPermanently l.mu.RUnlock() if closedPermanently { return nil, NewErrNonRetriable("link was closed by user") } if sender != nil || receiver != nil { return &LinksWithID{ Sender: sender, Receiver: receiver, RPC: mgmtLink, ID: revision, }, nil } l.mu.Lock() defer l.mu.Unlock() if err := l.initWithoutLocking(ctx); err != nil { return nil, err } return &LinksWithID{ Sender: l.Sender, Receiver: l.Receiver, RPC: l.RPCLink, ID: l.id, }, nil } func (l *AMQPLinksImpl) Retry(ctx context.Context, eventName log.Event, operation string, fn RetryWithLinksFn, o exported.RetryOptions) error { var lastID LinkID didQuickRetry := false isFatalErrorFunc := func(err error) bool { return l.getRecoveryKindFunc(err) == RecoveryKindFatal } return utils.Retry(ctx, eventName, operation, func(ctx context.Context, args *utils.RetryFnArgs) error { if err := l.RecoverIfNeeded(ctx, lastID, args.LastErr); err != nil { return err } linksWithVersion, err := l.Get(ctx) if err != nil { return err } lastID = linksWithVersion.ID if err := fn(ctx, linksWithVersion, args); err != nil { if args.I == 0 && !didQuickRetry && IsDetachError(err) { // go-amqp will asynchronously handle detaches. This means errors that you get // back from Send(), for instance, can actually be from much earlier in time // depending on the last time you called into Send(). // // This means we'll sometimes do an unneeded sleep after a failed retry when // it would have just immediately worked. To counteract that we'll do a one-time // quick attempt to recreate link immediately if we see a detach error. This might // waste a bit of time attempting to do the creation, but since it's just link creation // it should be fairly fast. // // So when we've received a detach is: // 0th attempt // extra immediate 0th attempt (if last error was detach) // (actual retries) // // Whereas normally you'd do (for non-detach errors): // 0th attempt // (actual retries) log.Writef(exported.EventConn, "(%s) Link was previously detached. Attempting quick reconnect to recover from error: %s", operation, err.Error()) didQuickRetry = true args.ResetAttempts() } return err } return nil }, isFatalErrorFunc, o) } // EntityPath is the full entity path for the queue/topic/subscription. func (l *AMQPLinksImpl) EntityPath() string { return l.entityPath } // EntityPath is the audience for the queue/topic/subscription. func (l *AMQPLinksImpl) Audience() string { return l.audience } // ClosedPermanently is true if AMQPLinks.Close(ctx, true) has been called. func (l *AMQPLinksImpl) ClosedPermanently() bool { l.mu.RLock() defer l.mu.RUnlock() return l.closedPermanently } // Close will close the the link permanently. // Any further calls to Get()/Recover() to return ErrLinksClosed. func (l *AMQPLinksImpl) Close(ctx context.Context, permanent bool) error { l.mu.Lock() defer l.mu.Unlock() return l.closeWithoutLocking(ctx, permanent) } // CloseIfNeeded closes the links or connection if the error is recoverable. // Use this if you want to make it so the _next_ call on your Sender/Receiver // eats the cost of recovery, instead of doing it immediately. This is useful // if you're trying to exit out of a function quickly but still need to react // to a returned error. func (l *AMQPLinksImpl) CloseIfNeeded(ctx context.Context, err error) RecoveryKind { l.mu.Lock() defer l.mu.Unlock() if IsCancelError(err) { log.Writef(exported.EventConn, "No close needed for cancellation") return RecoveryKindNone } rk := l.getRecoveryKindFunc(err) switch rk { case RecoveryKindLink: log.Writef(exported.EventConn, "Closing links for error %s", err.Error()) _ = l.closeWithoutLocking(ctx, false) return rk case RecoveryKindFatal: log.Writef(exported.EventConn, "Fatal error cleanup") fallthrough case RecoveryKindConn: log.Writef(exported.EventConn, "Closing connection AND links for error %s", err.Error()) _ = l.ns.Close(ctx, false) _ = l.closeWithoutLocking(ctx, false) return rk case RecoveryKindNone: return rk default: panic(fmt.Sprintf("Unhandled recovery kind %s for error %s", rk, err.Error())) } } // initWithoutLocking will create a new link, unconditionally. func (l *AMQPLinksImpl) initWithoutLocking(ctx context.Context) error { // shut down any links we have _ = l.closeWithoutLocking(ctx, false) tmpCancelAuthRefreshLink, _, err := l.ns.NegotiateClaim(ctx, l.entityPath) if err != nil { if err := l.closeWithoutLocking(ctx, false); err != nil { log.Writef(exported.EventConn, "Failure during link cleanup after negotiateClaim: %s", err.Error()) } return err } l.cancelAuthRefreshLink = tmpCancelAuthRefreshLink tmpCancelAuthRefreshMgmtLink, _, err := l.ns.NegotiateClaim(ctx, l.managementPath) if err != nil { if err := l.closeWithoutLocking(ctx, false); err != nil { log.Writef(exported.EventConn, "Failure during link cleanup after negotiate claim for mgmt link: %s", err.Error()) } return err } l.cancelAuthRefreshMgmtLink = tmpCancelAuthRefreshMgmtLink tmpSession, cr, err := l.ns.NewAMQPSession(ctx) if err != nil { if err := l.closeWithoutLocking(ctx, false); err != nil { log.Writef(exported.EventConn, "Failure during link cleanup after creating AMQP session: %s", err.Error()) } return err } l.session = tmpSession l.id.Conn = cr tmpSender, tmpReceiver, err := l.createLink(ctx, l.session) if err != nil { if err := l.closeWithoutLocking(ctx, false); err != nil { log.Writef(exported.EventConn, "Failure during link cleanup after creating link: %s", err.Error()) } return err } l.Sender, l.Receiver = tmpSender, tmpReceiver tmpRPCLink, err := l.ns.NewRPCLink(ctx, l.ManagementPath()) if err != nil { if err := l.closeWithoutLocking(ctx, false); err != nil { log.Writef("Failure during link cleanup after creating mgmt client: %s", err.Error()) } return err } l.RPCLink = tmpRPCLink l.id.Link++ return nil } // close closes the link. // NOTE: No locking is done in this function, call `Close` if you require locking. func (l *AMQPLinksImpl) closeWithoutLocking(ctx context.Context, permanent bool) error { if l.closedPermanently { return nil } defer func() { if permanent { l.closedPermanently = true } }() var messages []string if l.cancelAuthRefreshLink != nil { l.cancelAuthRefreshLink() l.cancelAuthRefreshLink = nil } if l.cancelAuthRefreshMgmtLink != nil { l.cancelAuthRefreshMgmtLink() l.cancelAuthRefreshMgmtLink = nil } if l.Sender != nil { if err := l.Sender.Close(ctx); err != nil { messages = append(messages, fmt.Sprintf("amqp sender close error: %s", err.Error())) } l.Sender = nil } if l.Receiver != nil { if err := l.Receiver.Close(ctx); err != nil { messages = append(messages, fmt.Sprintf("amqp receiver close error: %s", err.Error())) } l.Receiver = nil } if l.session != nil { if err := l.session.Close(ctx); err != nil { messages = append(messages, fmt.Sprintf("amqp session close error: %s", err.Error())) } l.session = nil } if l.RPCLink != nil { if err := l.RPCLink.Close(ctx); err != nil { messages = append(messages, fmt.Sprintf("$management link close error: %s", err.Error())) } l.RPCLink = nil } if len(messages) > 0 { return errors.New(strings.Join(messages, "\n")) } return nil }
{'content_hash': 'f3cd02e27c2fa5aa4990d0ac9264125a', 'timestamp': '', 'source': 'github', 'line_count': 524, 'max_line_length': 149, 'avg_line_length': 30.12786259541985, 'alnum_prop': 0.7176791030594794, 'repo_name': 'Azure/azure-sdk-for-go', 'id': '7e640fe9b56a4982e97659e3a5fddd014ad0dac1', 'size': '15884', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'sdk/messaging/azservicebus/internal/amqpLinks.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1629'}, {'name': 'Bicep', 'bytes': '8394'}, {'name': 'CSS', 'bytes': '6089'}, {'name': 'Dockerfile', 'bytes': '1435'}, {'name': 'Go', 'bytes': '5463500'}, {'name': 'HTML', 'bytes': '8933'}, {'name': 'JavaScript', 'bytes': '8137'}, {'name': 'PowerShell', 'bytes': '504494'}, {'name': 'Shell', 'bytes': '3893'}, {'name': 'Smarty', 'bytes': '1723'}]}
dojo.provide("dojox.gfx3d.vector"); dojo.mixin(dojox.gfx3d.vector, { sum: function(){ // summary: sum of the vectors var v = {x: 0, y: 0, z:0}; dojo.forEach(arguments, function(item){ v.x += item.x; v.y += item.y; v.z += item.z; }); return v; }, center: function(){ // summary: center of the vectors var l = arguments.length; if(l == 0){ return {x: 0, y: 0, z: 0}; } var v = dojox.gfx3d.vector.sum(arguments); return {x: v.x/l, y: v.y/l, z: v.z/l}; }, substract: function(/* Pointer */a, /* Pointer */b){ return {x: a.x - b.x, y: a.y - b.y, z: a.z - b.z}; }, _crossProduct: function(x, y, z, u, v, w){ // summary: applies a cross product of two vectorss, (x, y, z) and (u, v, w) // x: Number: an x coordinate of a point // y: Number: a y coordinate of a point // z: Number: a z coordinate of a point // u: Number: an x coordinate of a point // v: Number: a y coordinate of a point // w: Number: a z coordinate of a point return {x: y * w - z * v, y: z * u - x * w, z: x * v - y * u}; // Object }, crossProduct: function(/* Number||Point */ a, /* Number||Point */ b, /* Number, optional */ c, /* Number, optional */ d, /* Number, optional */ e, /* Number, optional */ f){ // summary: applies a matrix to a point // matrix: dojox.gfx3d.matrix.Matrix3D: a 3D matrix object to be applied // a: Number: an x coordinate of a point // b: Number: a y coordinate of a point // c: Number: a z coordinate of a point // d: Number: an x coordinate of a point // e: Number: a y coordinate of a point // f: Number: a z coordinate of a point if(arguments.length == 6 && dojo.every(arguments, function(item){ return typeof item == "number"; })){ return dojox.gfx3d.vector._crossProduct(a, b, c, d, e, f); // Object } // branch // a: Object: a point // b: Object: a point // c: null // d: null // e: null // f: null return dojox.gfx3d.vector._crossProduct(a.x, a.y, a.z, b.x, b.y, b.z); // Object }, _dotProduct: function(x, y, z, u, v, w){ // summary: applies a cross product of two vectorss, (x, y, z) and (u, v, w) // x: Number: an x coordinate of a point // y: Number: a y coordinate of a point // z: Number: a z coordinate of a point // u: Number: an x coordinate of a point // v: Number: a y coordinate of a point // w: Number: a z coordinate of a point return x * u + y * v + z * w; // Number }, dotProduct: function(/* Number||Point */ a, /* Number||Point */ b, /* Number, optional */ c, /* Number, optional */ d, /* Number, optional */ e, /* Number, optional */ f){ // summary: applies a matrix to a point // matrix: dojox.gfx3d.matrix.Matrix3D: a 3D matrix object to be applied // a: Number: an x coordinate of a point // b: Number: a y coordinate of a point // c: Number: a z coordinate of a point // d: Number: an x coordinate of a point // e: Number: a y coordinate of a point // f: Number: a z coordinate of a point if(arguments.length == 6 && dojo.every(arguments, function(item){ return typeof item == "number"; })){ return dojox.gfx3d.vector._dotProduct(a, b, c, d, e, f); // Object } // branch // a: Object: a point // b: Object: a point // c: null // d: null // e: null // f: null return dojox.gfx3d.vector._dotProduct(a.x, a.y, a.z, b.x, b.y, b.z); // Object }, normalize: function(/* Point||Array*/ a, /* Point */ b, /* Point */ c){ // summary: find the normal of the implicit surface // a: Object: a point // b: Object: a point // c: Object: a point var l, m, n; if(a instanceof Array){ l = a[0]; m = a[1]; n = a[2]; }else{ l = a; m = b; n = c; } var u = dojox.gfx3d.vector.substract(m, l); var v = dojox.gfx3d.vector.substract(n, l); return dojox.gfx3d.vector.crossProduct(u, v); } });
{'content_hash': '8c0ca00db17d0881dbf9613ed1d1de48', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 174, 'avg_line_length': 35.66981132075472, 'alnum_prop': 0.5961385876752182, 'repo_name': 'interFace-dk/ZendFramework', 'id': 'f2cbcf64161086f317c5eda8457fa651d9f880a5', 'size': '3781', 'binary': False, 'copies': '37', 'ref': 'refs/heads/release-1.12', 'path': 'externals/dojo/dojox/gfx3d/vector.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ActionScript', 'bytes': '19954'}, {'name': 'CSS', 'bytes': '631809'}, {'name': 'Java', 'bytes': '123492'}, {'name': 'JavaScript', 'bytes': '7954442'}, {'name': 'PHP', 'bytes': '31900901'}, {'name': 'Perl', 'bytes': '182'}, {'name': 'PowerShell', 'bytes': '1028'}, {'name': 'Puppet', 'bytes': '770'}, {'name': 'Ruby', 'bytes': '921'}, {'name': 'Shell', 'bytes': '30144'}, {'name': 'TypeScript', 'bytes': '3445'}, {'name': 'XSLT', 'bytes': '104232'}]}
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-7.js * @description Array.prototype.reduce - the exception is not thrown if exception was thrown by step 2 */ function testcase() { var obj = {}; Object.defineProperty(obj, "length", { get: function () { throw new SyntaxError(); }, configurable: true }); try { Array.prototype.reduce.call(obj, function () { }); return false; } catch (ex) { return !(ex instanceof TypeError); } } runTestCase(testcase);
{'content_hash': '47443673e8c351f3cd3f35ce9b221c1e', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 102, 'avg_line_length': 25.76923076923077, 'alnum_prop': 0.5373134328358209, 'repo_name': 'Oceanswave/NiL.JS', 'id': '6001e6f62128cceef180c064b179f010d2109052', 'size': '670', 'binary': False, 'copies': '18', 'ref': 'refs/heads/develop', 'path': 'Tests/tests/sputnik/ch15/15.4/15.4.4/15.4.4.21/15.4.4.21-8-c-7.js', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'C#', 'bytes': '1430725'}, {'name': 'CSS', 'bytes': '1167'}, {'name': 'HTML', 'bytes': '26708'}, {'name': 'JavaScript', 'bytes': '15602387'}, {'name': 'Smalltalk', 'bytes': '2118'}]}
/* */ "format cjs"; "use strict"; var _toolsProtectJs2 = require("./../../../tools/protect.js"); var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2); exports.__esModule = true; var _lodashCollectionSortBy = require("lodash/collection/sortBy"); var _lodashCollectionSortBy2 = _interopRequireDefault(_lodashCollectionSortBy); _toolsProtectJs3["default"](module); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var metadata = { group: "builtin-trailing" }; exports.metadata = metadata; // Priority: // // - 0 We want this to be at the **very** bottom // - 1 Default node position // - 2 Priority over normal nodes // - 3 We want this to be at the **very** top var visitor = { Block: { exit: function exit(node) { var hasChange = false; for (var i = 0; i < node.body.length; i++) { var bodyNode = node.body[i]; if (bodyNode && bodyNode._blockHoist != null) hasChange = true; } if (!hasChange) return; node.body = _lodashCollectionSortBy2["default"](node.body, function (bodyNode) { var priority = bodyNode && bodyNode._blockHoist; if (priority == null) priority = 1; if (priority === true) priority = 2; // Higher priorities should move toward the top. return -1 * priority; }); } } }; exports.visitor = visitor;
{'content_hash': '65dacf3e80fb4fd6aeb6a43a89cdfed6', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 97, 'avg_line_length': 26.807692307692307, 'alnum_prop': 0.6355810616929699, 'repo_name': 'lasconic/aureliatest', 'id': '80a3a7d1379cd0cee6b897d9084ddf125bb548f8', 'size': '1394', 'binary': False, 'copies': '9', 'ref': 'refs/heads/gh-pages', 'path': 'jspm_packages/npm/[email protected]/lib/babel/transformation/transformers/internal/block-hoist.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '121599'}, {'name': 'CoffeeScript', 'bytes': '2294'}, {'name': 'HTML', 'bytes': '9393'}, {'name': 'JavaScript', 'bytes': '5533471'}, {'name': 'LiveScript', 'bytes': '5561'}, {'name': 'Makefile', 'bytes': '880'}, {'name': 'Shell', 'bytes': '1052'}]}
<?xml version="1.0" encoding="utf-8"?> <application id="Dummy" Mode="Debug"> <paths> <using namespace="Application.common.*" /> <using namespace="System.I18N.*" /> </paths> <modules> <module id="globalization" class="Application.common.BlogTutorialGlobalization" Charset="UTF-8"/> </modules> <services> <service id="page" class="TPageService" DefaultPage="Overview"> <pages MasterClass="Application.layout.MainLayout" Theme="PradoSoft" /> </service> </services> <parameters> <parameter id="languages" value="('en'=>'English', 'fr'=>'Français', 'id'=>'Indonesian')" /> </parameters> </application>
{'content_hash': 'e52ef6e7e8a8c8bcad32c8b0c47a6c43', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 98, 'avg_line_length': 34.1578947368421, 'alnum_prop': 0.6548536209553159, 'repo_name': 'tel8618217223380/prado3', 'id': '3c56adcc4f6deab027e2969c735b9f823bb5771c', 'size': '650', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'demos/blog-tutorial/protected/application.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '645'}, {'name': 'Batchfile', 'bytes': '7687'}, {'name': 'CSS', 'bytes': '253063'}, {'name': 'HTML', 'bytes': '383134'}, {'name': 'JavaScript', 'bytes': '947078'}, {'name': 'PHP', 'bytes': '9084496'}, {'name': 'Shell', 'bytes': '4520'}, {'name': 'Smarty', 'bytes': '875025'}, {'name': 'TeX', 'bytes': '13304'}, {'name': 'XSLT', 'bytes': '184085'}]}
<html> <script src="../../resources/js-test.js"></script> <body style="min-height: 5000px"> <span id="elt">&nbsp;</span> <script> description('Checks that clicking on scrollbar works when tickmarks are added.'); onload = function() { if (window.testRunner) testRunner.dumpAsText(); var range = document.createRange(); var elt = document.getElementById('elt'); range.selectNodeContents(elt); if (window.internals) { window.internals.settings.setOverlayScrollbarsEnabled(true); window.internals.addTextMatchMarker(range, true); } if (window.eventSender) { eventSender.mouseMoveTo(window.innerWidth - 1, window.innerHeight - 1); eventSender.mouseDown(); eventSender.mouseUp(); } } onscroll = function() { testPassed('did scroll'); finishJSTest(); } var jsTestIsAsync = true; </script> </body> </html>
{'content_hash': '0811093dc713fd2a40b47b7ef42bf806', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 81, 'avg_line_length': 24.10810810810811, 'alnum_prop': 0.6647982062780269, 'repo_name': 'primiano/blink-gitcs', 'id': '0974a65948cded7befc8e016693518cb6812afdf', 'size': '892', 'binary': False, 'copies': '39', 'ref': 'refs/heads/master', 'path': 'LayoutTests/fast/scrolling/scrollbar-tickmarks-hittest.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '14584'}, {'name': 'Bison', 'bytes': '64736'}, {'name': 'C', 'bytes': '241029'}, {'name': 'C++', 'bytes': '42205756'}, {'name': 'CSS', 'bytes': '542759'}, {'name': 'CoffeeScript', 'bytes': '163'}, {'name': 'Java', 'bytes': '74992'}, {'name': 'JavaScript', 'bytes': '26765495'}, {'name': 'Objective-C', 'bytes': '79920'}, {'name': 'Objective-C++', 'bytes': '342572'}, {'name': 'PHP', 'bytes': '171194'}, {'name': 'Perl', 'bytes': '583379'}, {'name': 'Python', 'bytes': '3781501'}, {'name': 'Ruby', 'bytes': '141818'}, {'name': 'Shell', 'bytes': '8923'}, {'name': 'XSLT', 'bytes': '49926'}]}
package com.amazonaws.services.simpleworkflow.flow.worker; import java.util.HashMap; import java.util.Map; import java.util.concurrent.CancellationException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.amazonaws.services.simpleworkflow.flow.StartTimerFailedException; import com.amazonaws.services.simpleworkflow.flow.WorkflowClock; import com.amazonaws.services.simpleworkflow.flow.common.FlowHelpers; import com.amazonaws.services.simpleworkflow.flow.core.ExternalTask; import com.amazonaws.services.simpleworkflow.flow.core.ExternalTaskCancellationHandler; import com.amazonaws.services.simpleworkflow.flow.core.ExternalTaskCompletionHandle; import com.amazonaws.services.simpleworkflow.flow.core.Promise; import com.amazonaws.services.simpleworkflow.model.HistoryEvent; import com.amazonaws.services.simpleworkflow.model.StartTimerDecisionAttributes; import com.amazonaws.services.simpleworkflow.model.StartTimerFailedEventAttributes; import com.amazonaws.services.simpleworkflow.model.TimerCanceledEventAttributes; import com.amazonaws.services.simpleworkflow.model.TimerFiredEventAttributes; class WorkflowClockImpl implements WorkflowClock { private static final Log log = LogFactory.getLog(WorkflowClockImpl.class); private final class TimerCancellationHandler implements ExternalTaskCancellationHandler { private final String timerId; private TimerCancellationHandler(String timerId) { this.timerId = timerId; } @Override public void handleCancellation(Throwable cause) { decisions.cancelTimer(timerId, new Runnable() { @Override public void run() { OpenRequestInfo<?, ?> scheduled = scheduledTimers.remove(timerId); ExternalTaskCompletionHandle context = scheduled.getCompletionHandle(); context.complete(); } }); } } private final DecisionsHelper decisions; private final Map<String, OpenRequestInfo<?, ?>> scheduledTimers = new HashMap<String, OpenRequestInfo<?, ?>>(); private long replayCurrentTimeMilliseconds; private boolean replaying = true; WorkflowClockImpl(DecisionsHelper decisions) { this.decisions = decisions; } @Override public long currentTimeMillis() { return replayCurrentTimeMilliseconds; } void setReplayCurrentTimeMilliseconds(long replayCurrentTimeMilliseconds) { this.replayCurrentTimeMilliseconds = replayCurrentTimeMilliseconds; } @Override public boolean isReplaying() { return replaying; } void setReplaying(boolean replaying) { this.replaying = replaying; } @Override public Promise<Void> createTimer(long delaySeconds) { return createTimer(delaySeconds, null); } @Override public <T> Promise<T> createTimer(final long delaySeconds, final T userContext) { if (delaySeconds < 0) { throw new IllegalArgumentException("Negative delaySeconds: " + delaySeconds); } if (delaySeconds == 0) { return Promise.asPromise(userContext); } final OpenRequestInfo<T, Object> context = new OpenRequestInfo<T, Object>(userContext); final StartTimerDecisionAttributes timer = new StartTimerDecisionAttributes(); timer.setStartToFireTimeout(FlowHelpers.secondsToDuration(delaySeconds)); final String timerId = decisions.getNextId(); timer.setTimerId(timerId); String taskName = "timerId=" + timer.getTimerId() + ", delaySeconds=" + timer.getStartToFireTimeout(); new ExternalTask() { @Override protected ExternalTaskCancellationHandler doExecute(ExternalTaskCompletionHandle handle) throws Throwable { decisions.startTimer(timer, userContext); context.setCompletionHandle(handle); scheduledTimers.put(timerId, context); return new TimerCancellationHandler(timerId); } }.setName(taskName); context.setResultDescription("createTimer " + taskName); return context.getResult(); } @SuppressWarnings({ "rawtypes", "unchecked" }) void handleTimerFired(Long eventId, TimerFiredEventAttributes attributes) { String timerId = attributes.getTimerId(); if (decisions.handleTimerClosed(timerId)) { OpenRequestInfo scheduled = scheduledTimers.remove(timerId); if (scheduled != null) { ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); scheduled.getResult().set(scheduled.getUserContext()); completionHandle.complete(); } } else { log.debug("handleTimerFired not complete"); } } @SuppressWarnings({ "rawtypes" }) void handleStartTimerFailed(HistoryEvent event) { StartTimerFailedEventAttributes attributes = event.getStartTimerFailedEventAttributes(); String timerId = attributes.getTimerId(); if (decisions.handleStartTimerFailed(event)) { OpenRequestInfo scheduled = scheduledTimers.remove(timerId); if (scheduled != null) { ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); Object createTimerUserContext = scheduled.getUserContext(); String cause = attributes.getCause(); Throwable failure = new StartTimerFailedException(event.getEventId(), timerId, createTimerUserContext, cause); completionHandle.fail(failure); } } else { log.debug("handleStartTimerFailed not complete"); } } void handleTimerCanceled(HistoryEvent event) { TimerCanceledEventAttributes attributes = event.getTimerCanceledEventAttributes(); String timerId = attributes.getTimerId(); if (decisions.handleTimerCanceled(event)) { OpenRequestInfo<?, ?> scheduled = scheduledTimers.remove(timerId); if (scheduled != null) { ExternalTaskCompletionHandle completionHandle = scheduled.getCompletionHandle(); CancellationException exception = new CancellationException(); completionHandle.fail(exception); } } else { log.debug("handleTimerCanceled not complete"); } } }
{'content_hash': '3a78332374b7aa63dbf94567a058f599', 'timestamp': '', 'source': 'github', 'line_count': 165, 'max_line_length': 126, 'avg_line_length': 39.654545454545456, 'alnum_prop': 0.6879107443068928, 'repo_name': 'sheofir/aws-sdk-java', 'id': 'f8739fc80149be302a75765b7d667969fccb8cf5', 'size': '7129', 'binary': False, 'copies': '28', 'ref': 'refs/heads/master', 'path': 'aws-java-sdk-swf-libraries/src/main/java/com/amazonaws/services/simpleworkflow/flow/worker/WorkflowClockImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '88113149'}, {'name': 'Scilab', 'bytes': '2354'}]}
/** * @fileoverview Validate closing bracket location in JSX * @author Yannick Croissant */ 'use strict'; const has = require('object.hasown/polyfill')(); const docsUrl = require('../util/docsUrl'); const report = require('../util/report'); // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ const messages = { bracketLocation: 'The closing bracket must be {{location}}{{details}}', }; module.exports = { meta: { docs: { description: 'Validate closing bracket location in JSX', category: 'Stylistic Issues', recommended: false, url: docsUrl('jsx-closing-bracket-location'), }, fixable: 'code', messages, schema: [{ oneOf: [ { enum: ['after-props', 'props-aligned', 'tag-aligned', 'line-aligned'], }, { type: 'object', properties: { location: { enum: ['after-props', 'props-aligned', 'tag-aligned', 'line-aligned'], }, }, additionalProperties: false, }, { type: 'object', properties: { nonEmpty: { enum: ['after-props', 'props-aligned', 'tag-aligned', 'line-aligned', false], }, selfClosing: { enum: ['after-props', 'props-aligned', 'tag-aligned', 'line-aligned', false], }, }, additionalProperties: false, }, ], }], }, create(context) { const MESSAGE_LOCATION = { 'after-props': 'placed after the last prop', 'after-tag': 'placed after the opening tag', 'props-aligned': 'aligned with the last prop', 'tag-aligned': 'aligned with the opening tag', 'line-aligned': 'aligned with the line containing the opening tag', }; const DEFAULT_LOCATION = 'tag-aligned'; const config = context.options[0]; const options = { nonEmpty: DEFAULT_LOCATION, selfClosing: DEFAULT_LOCATION, }; if (typeof config === 'string') { // simple shorthand [1, 'something'] options.nonEmpty = config; options.selfClosing = config; } else if (typeof config === 'object') { // [1, {location: 'something'}] (back-compat) if (has(config, 'location')) { options.nonEmpty = config.location; options.selfClosing = config.location; } // [1, {nonEmpty: 'something'}] if (has(config, 'nonEmpty')) { options.nonEmpty = config.nonEmpty; } // [1, {selfClosing: 'something'}] if (has(config, 'selfClosing')) { options.selfClosing = config.selfClosing; } } /** * Get expected location for the closing bracket * @param {Object} tokens Locations of the opening bracket, closing bracket and last prop * @return {String} Expected location for the closing bracket */ function getExpectedLocation(tokens) { let location; // Is always after the opening tag if there is no props if (typeof tokens.lastProp === 'undefined') { location = 'after-tag'; // Is always after the last prop if this one is on the same line as the opening bracket } else if (tokens.opening.line === tokens.lastProp.lastLine) { location = 'after-props'; // Else use configuration dependent on selfClosing property } else { location = tokens.selfClosing ? options.selfClosing : options.nonEmpty; } return location; } /** * Get the correct 0-indexed column for the closing bracket, given the * expected location. * @param {Object} tokens Locations of the opening bracket, closing bracket and last prop * @param {String} expectedLocation Expected location for the closing bracket * @return {?Number} The correct column for the closing bracket, or null */ function getCorrectColumn(tokens, expectedLocation) { switch (expectedLocation) { case 'props-aligned': return tokens.lastProp.column; case 'tag-aligned': return tokens.opening.column; case 'line-aligned': return tokens.openingStartOfLine.column; default: return null; } } /** * Check if the closing bracket is correctly located * @param {Object} tokens Locations of the opening bracket, closing bracket and last prop * @param {String} expectedLocation Expected location for the closing bracket * @return {Boolean} True if the closing bracket is correctly located, false if not */ function hasCorrectLocation(tokens, expectedLocation) { switch (expectedLocation) { case 'after-tag': return tokens.tag.line === tokens.closing.line; case 'after-props': return tokens.lastProp.lastLine === tokens.closing.line; case 'props-aligned': case 'tag-aligned': case 'line-aligned': { const correctColumn = getCorrectColumn(tokens, expectedLocation); return correctColumn === tokens.closing.column; } default: return true; } } /** * Get the characters used for indentation on the line to be matched * @param {Object} tokens Locations of the opening bracket, closing bracket and last prop * @param {String} expectedLocation Expected location for the closing bracket * @param {Number} [correctColumn] Expected column for the closing bracket. Default to 0 * @return {String} The characters used for indentation */ function getIndentation(tokens, expectedLocation, correctColumn) { correctColumn = correctColumn || 0; let indentation; let spaces = []; switch (expectedLocation) { case 'props-aligned': indentation = /^\s*/.exec(context.getSourceCode().lines[tokens.lastProp.firstLine - 1])[0]; break; case 'tag-aligned': case 'line-aligned': indentation = /^\s*/.exec(context.getSourceCode().lines[tokens.opening.line - 1])[0]; break; default: indentation = ''; } if (indentation.length + 1 < correctColumn) { // Non-whitespace characters were included in the column offset spaces = new Array(+correctColumn + 1 - indentation.length); } return indentation + spaces.join(' '); } /** * Get the locations of the opening bracket, closing bracket, last prop, and * start of opening line. * @param {ASTNode} node The node to check * @return {Object} Locations of the opening bracket, closing bracket, last * prop and start of opening line. */ function getTokensLocations(node) { const sourceCode = context.getSourceCode(); const opening = sourceCode.getFirstToken(node).loc.start; const closing = sourceCode.getLastTokens(node, node.selfClosing ? 2 : 1)[0].loc.start; const tag = sourceCode.getFirstToken(node.name).loc.start; let lastProp; if (node.attributes.length) { lastProp = node.attributes[node.attributes.length - 1]; lastProp = { column: sourceCode.getFirstToken(lastProp).loc.start.column, firstLine: sourceCode.getFirstToken(lastProp).loc.start.line, lastLine: sourceCode.getLastToken(lastProp).loc.end.line, }; } const openingLine = sourceCode.lines[opening.line - 1]; const closingLine = sourceCode.lines[closing.line - 1]; const isTab = { openTab: /^\t/.test(openingLine), closeTab: /^\t/.test(closingLine), }; const openingStartOfLine = { column: /^\s*/.exec(openingLine)[0].length, line: opening.line, }; return { isTab, tag, opening, closing, lastProp, selfClosing: node.selfClosing, openingStartOfLine, }; } /** * Get an unique ID for a given JSXOpeningElement * * @param {ASTNode} node The AST node being checked. * @returns {String} Unique ID (based on its range) */ function getOpeningElementId(node) { return node.range.join(':'); } const lastAttributeNode = {}; return { JSXAttribute(node) { lastAttributeNode[getOpeningElementId(node.parent)] = node; }, JSXSpreadAttribute(node) { lastAttributeNode[getOpeningElementId(node.parent)] = node; }, 'JSXOpeningElement:exit'(node) { const attributeNode = lastAttributeNode[getOpeningElementId(node)]; const cachedLastAttributeEndPos = attributeNode ? attributeNode.range[1] : null; let expectedNextLine; const tokens = getTokensLocations(node); const expectedLocation = getExpectedLocation(tokens); let usingSameIndentation = true; if (expectedLocation === 'tag-aligned') { usingSameIndentation = tokens.isTab.openTab === tokens.isTab.closeTab; } if (hasCorrectLocation(tokens, expectedLocation) && usingSameIndentation) { return; } const data = { location: MESSAGE_LOCATION[expectedLocation] }; const correctColumn = getCorrectColumn(tokens, expectedLocation); if (correctColumn !== null) { expectedNextLine = tokens.lastProp && (tokens.lastProp.lastLine === tokens.closing.line); data.details = ` (expected column ${correctColumn + 1}${expectedNextLine ? ' on the next line)' : ')'}`; } report(context, messages.bracketLocation, 'bracketLocation', { node, loc: tokens.closing, data, fix(fixer) { const closingTag = tokens.selfClosing ? '/>' : '>'; switch (expectedLocation) { case 'after-tag': if (cachedLastAttributeEndPos) { return fixer.replaceTextRange([cachedLastAttributeEndPos, node.range[1]], (expectedNextLine ? '\n' : '') + closingTag); } return fixer.replaceTextRange([node.name.range[1], node.range[1]], (expectedNextLine ? '\n' : ' ') + closingTag); case 'after-props': return fixer.replaceTextRange([cachedLastAttributeEndPos, node.range[1]], (expectedNextLine ? '\n' : '') + closingTag); case 'props-aligned': case 'tag-aligned': case 'line-aligned': return fixer.replaceTextRange([cachedLastAttributeEndPos, node.range[1]], `\n${getIndentation(tokens, expectedLocation, correctColumn)}${closingTag}`); default: return true; } }, }); }, }; }, };
{'content_hash': '16f73d8a4cd717bfc1ceeaca436f419c', 'timestamp': '', 'source': 'github', 'line_count': 308, 'max_line_length': 114, 'avg_line_length': 35.185064935064936, 'alnum_prop': 0.5903847928393466, 'repo_name': 'GoogleCloudPlatform/prometheus-engine', 'id': '324d0e76424f187c260d493e563540806df0c9c0', 'size': '10837', 'binary': False, 'copies': '6', 'ref': 'refs/heads/main', 'path': 'third_party/prometheus_ui/base/web/ui/node_modules/eslint-plugin-react/lib/rules/jsx-closing-bracket-location.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '4035'}, {'name': 'Go', 'bytes': '574177'}, {'name': 'Makefile', 'bytes': '5189'}, {'name': 'Shell', 'bytes': '11915'}]}
<?php /** * @package WPSEO\Admin|Google_Search_Console */ /** * Class WPSEO_GSC_Issue */ class WPSEO_GSC_Issue { /** * @var string */ private $url; /** * @var DateTime */ private $first_detected; /** * @var DateTime */ private $last_crawled; /** * @var string */ private $response_code; /** * Search Console issue class constructor. * * @param string $url URL of the issue. * @param DateTime $first_detected Time of first discovery. * @param DateTime $last_crawled Time of last crawl. * @param string $response_code HTTP response code. */ public function __construct( $url, DateTime $first_detected, DateTime $last_crawled, $response_code ) { $this->url = $url; $this->first_detected = $first_detected; $this->last_crawled = $last_crawled; $this->response_code = $response_code; } /** * Put the class properties in array * * @return array */ public function to_array() { return array( 'url' => $this->url, 'first_detected' => $this->to_date_format( $this->first_detected ), 'first_detected_raw' => $this->to_timestamp( $this->first_detected ), 'last_crawled' => $this->to_date_format( $this->last_crawled ), 'last_crawled_raw' => $this->to_timestamp( $this->last_crawled ), 'response_code' => $this->response_code, ); } /** * Converting the date to a date format * * @param DateTime $date_to_convert Date instance. * @param string $format Format string. * * @return string */ private function to_date_format( DateTime $date_to_convert, $format = '' ) { if ( empty( $format ) ) { $format = get_option( 'date_format' ); } return date_i18n( $format, $date_to_convert->format( 'U' ) ); } /** * Converting the date to a timestamp * * @param DateTime $date_to_convert Date object instance. * * @return string */ private function to_timestamp( DateTime $date_to_convert ) { return $date_to_convert->format( 'U' ); } }
{'content_hash': '3435e55380c7f60abb8dd8ae6f26f179', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 104, 'avg_line_length': 22.764044943820224, 'alnum_prop': 0.6056268509378084, 'repo_name': 'darbymanning/Family-Church', 'id': 'b6ea06d4cdf15a4c526bfea93572fc955ce60295', 'size': '2026', 'binary': False, 'copies': '250', 'ref': 'refs/heads/master', 'path': 'wordpress/wp-content/plugins/wordpress-seo/admin/google_search_console/class-gsc-issue.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6177313'}, {'name': 'HTML', 'bytes': '610318'}, {'name': 'JavaScript', 'bytes': '5342604'}, {'name': 'PHP', 'bytes': '31571710'}, {'name': 'Shell', 'bytes': '513'}, {'name': 'Smarty', 'bytes': '33'}]}
<?php /** * @see Zend_Date */ // require_once 'Zend/Date.php'; /** * @see Zend_Date */ // require_once 'Zend/Uri.php'; /** * @see Zend_Feed_Writer */ // require_once 'Zend/Feed/Writer.php'; /** * @see Zend_Feed_Writer_Entry */ // require_once 'Zend/Feed/Writer/Entry.php'; /** * @see Zend_Feed_Writer_Renderer_Feed_Atom */ // require_once 'Zend/Feed/Writer/Renderer/Feed/Atom.php'; /** * @see Zend_Feed_Writer_Renderer_Feed_Rss */ // require_once 'Zend/Feed/Writer/Renderer/Feed/Rss.php'; /** * @category Zend * @package Zend_Feed_Writer * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Feed_Writer_Feed_FeedAbstract { /** * Contains all Feed level date to append in feed output * * @var array */ protected $_data = array(); /** * Holds the value "atom" or "rss" depending on the feed type set when * when last exported. * * @var string */ protected $_type = null; /** * Constructor: Primarily triggers the registration of core extensions and * loads those appropriate to this data container. * * @return void */ public function __construct() { Zend_Feed_Writer::registerCoreExtensions(); $this->_loadExtensions(); } /** * Set a single author * * @param int $index * @return string|null */ public function addAuthor($name, $email = null, $uri = null) { $author = array(); if (is_array($name)) { if (!array_key_exists('name', $name) || empty($name['name']) || !is_string($name['name'])) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: author array must include a "name" key with a non-empty string value'); } $author['name'] = $name['name']; if (isset($name['email'])) { if (empty($name['email']) || !is_string($name['email'])) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "email" array value must be a non-empty string'); } $author['email'] = $name['email']; } if (isset($name['uri'])) { if (empty($name['uri']) || !is_string($name['uri']) || !Zend_Uri::check($name['uri'])) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "uri" array value must be a non-empty string and valid URI/IRI'); } $author['uri'] = $name['uri']; } } else { if (empty($name['name']) || !is_string($name['name'])) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "name" must be a non-empty string value'); } $author['name'] = $name; if (isset($email)) { if (empty($email) || !is_string($email)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "email" value must be a non-empty string'); } $author['email'] = $email; } if (isset($uri)) { if (empty($uri) || !is_string($uri) || !Zend_Uri::check($uri)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "uri" value must be a non-empty string and valid URI/IRI'); } $author['uri'] = $uri; } } $this->_data['authors'][] = $author; } /** * Set an array with feed authors * * @return array */ public function addAuthors(array $authors) { foreach($authors as $author) { $this->addAuthor($author); } } /** * Set the copyright entry * * @return string|null */ public function setCopyright($copyright) { if (empty($copyright) || !is_string($copyright)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: parameter must be a non-empty string'); } $this->_data['copyright'] = $copyright; } /** * Set the feed creation date * * @param null|integer|Zend_Date */ public function setDateCreated($date = null) { $zdate = null; if (is_null($date)) { $zdate = new Zend_Date; } elseif (ctype_digit($date) && strlen($date) == 10) { $zdate = new Zend_Date($date, Zend_Date::TIMESTAMP); } elseif ($date instanceof Zend_Date) { $zdate = $date; } else { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid Zend_Date object or UNIX Timestamp passed as parameter'); } $this->_data['dateCreated'] = $zdate; } /** * Set the feed modification date * * @param null|integer|Zend_Date */ public function setDateModified($date = null) { $zdate = null; if (is_null($date)) { $zdate = new Zend_Date; } elseif (ctype_digit($date) && strlen($date) == 10) { $zdate = new Zend_Date($date, Zend_Date::TIMESTAMP); } elseif ($date instanceof Zend_Date) { $zdate = $date; } else { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid Zend_Date object or UNIX Timestamp passed as parameter'); } $this->_data['dateModified'] = $zdate; } /** * Set the feed description * * @return string|null */ public function setDescription($description) { if (empty($description) || !is_string($description)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: parameter must be a non-empty string'); } $this->_data['description'] = $description; } /** * Set the feed generator entry * * @return string|null */ public function setGenerator($name, $version = null, $uri = null) { if (empty($name) || !is_string($name)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "name" must be a non-empty string'); } $generator = array('name' => $name); if (isset($version)) { if (empty($version) || !is_string($version)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "version" must be a non-empty string'); } $generator['version'] = $version; } if (isset($uri)) { if (empty($uri) || !is_string($uri) || !Zend_Uri::check($uri)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "uri" must be a non-empty string and a valid URI/IRI'); } $generator['uri'] = $uri; } $this->_data['generator'] = $generator; } /** * Set the feed ID - URI or URN (via PCRE pattern) supported * * @return string|null */ public function setId($id) { if ((empty($id) || !is_string($id) || !Zend_Uri::check($id)) && !preg_match("#^urn:[a-zA-Z0-9][a-zA-Z0-9\-]{1,31}:([a-zA-Z0-9\(\)\+\,\.\:\=\@\;\$\_\!\*\-]|%[0-9a-fA-F]{2})*#", $id)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: parameter must be a non-empty string and valid URI/IRI'); } $this->_data['id'] = $id; } /** * Set the feed language * * @return string|null */ public function setLanguage($language) { if (empty($language) || !is_string($language)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: parameter must be a non-empty string'); } $this->_data['language'] = $language; } /** * Set a link to the HTML source * * @return string|null */ public function setLink($link) { if (empty($link) || !is_string($link) || !Zend_Uri::check($link)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: parameter must be a non-empty string and valid URI/IRI'); } $this->_data['link'] = $link; } /** * Set a link to an XML feed for any feed type/version * * @return string|null */ public function setFeedLink($link, $type) { if (empty($link) || !is_string($link) || !Zend_Uri::check($link)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "link"" must be a non-empty string and valid URI/IRI'); } if (!in_array(strtolower($type), array('rss', 'rdf', 'atom'))) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "type"; You must declare the type of feed the link points to, i.e. RSS, RDF or Atom'); } $this->_data['feedLinks'][strtolower($type)] = $link; } /** * Set the feed title * * @return string|null */ public function setTitle($title) { if (empty($title) || !is_string($title)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: parameter must be a non-empty string'); } $this->_data['title'] = $title; } /** * Set the feed character encoding * * @param string $encoding */ public function setEncoding($encoding) { if (empty($encoding) || !is_string($encoding)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: parameter must be a non-empty string'); } $this->_data['encoding'] = $encoding; } /** * Set the feed's base URL * * @param string $url */ public function setBaseUrl($url) { if (empty($url) || !is_string($url) || !Zend_Uri::check($url)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "url" array value' . ' must be a non-empty string and valid URI/IRI'); } $this->_data['baseUrl'] = $url; } /** * Add a Pubsubhubbub hub endpoint URL * * @param string $url */ public function addHub($url) { if (empty($url) || !is_string($url) || !Zend_Uri::check($url)) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Invalid parameter: "url" array value' . ' must be a non-empty string and valid URI/IRI'); } if (!isset($this->_data['hubs'])) { $this->_data['hubs'] = array(); } $this->_data['hubs'][] = $url; } /** * Add Pubsubhubbub hub endpoint URLs * * @param array $urls */ public function addHubs(array $urls) { foreach ($urls as $url) { $this->addHub($url); } } /** * Add a feed category * * @param string $category */ public function addCategory(array $category) { if (!isset($category['term'])) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Each category must be an array and ' . 'contain at least a "term" element containing the machine ' . ' readable category name'); } if (isset($category['scheme'])) { if (empty($category['scheme']) || !is_string($category['scheme']) || !Zend_Uri::check($category['scheme']) ) { // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('The Atom scheme or RSS domain of' . ' a category must be a valid URI'); } } if (!isset($this->_data['categories'])) { $this->_data['categories'] = array(); } $this->_data['categories'][] = $category; } /** * Set an array of feed categories * * @param array $categories */ public function addCategories(array $categories) { foreach ($categories as $category) { $this->addCategory($category); } } /** * Get a single author * * @param int $index * @return string|null */ public function getAuthor($index = 0) { if (isset($this->_data['authors'][$index])) { return $this->_data['authors'][$index]; } else { return null; } } /** * Get an array with feed authors * * @return array */ public function getAuthors() { if (!array_key_exists('authors', $this->_data)) { return null; } return $this->_data['authors']; } /** * Get the copyright entry * * @return string|null */ public function getCopyright() { if (!array_key_exists('copyright', $this->_data)) { return null; } return $this->_data['copyright']; } /** * Get the feed creation date * * @return string|null */ public function getDateCreated() { if (!array_key_exists('dateCreated', $this->_data)) { return null; } return $this->_data['dateCreated']; } /** * Get the feed modification date * * @return string|null */ public function getDateModified() { if (!array_key_exists('dateModified', $this->_data)) { return null; } return $this->_data['dateModified']; } /** * Get the feed description * * @return string|null */ public function getDescription() { if (!array_key_exists('description', $this->_data)) { return null; } return $this->_data['description']; } /** * Get the feed generator entry * * @return string|null */ public function getGenerator() { if (!array_key_exists('generator', $this->_data)) { return null; } return $this->_data['generator']; } /** * Get the feed ID * * @return string|null */ public function getId() { if (!array_key_exists('id', $this->_data)) { return null; } return $this->_data['id']; } /** * Get the feed language * * @return string|null */ public function getLanguage() { if (!array_key_exists('language', $this->_data)) { return null; } return $this->_data['language']; } /** * Get a link to the HTML source * * @return string|null */ public function getLink() { if (!array_key_exists('link', $this->_data)) { return null; } return $this->_data['link']; } /** * Get a link to the XML feed * * @return string|null */ public function getFeedLinks() { if (!array_key_exists('feedLinks', $this->_data)) { return null; } return $this->_data['feedLinks']; } /** * Get the feed title * * @return string|null */ public function getTitle() { if (!array_key_exists('title', $this->_data)) { return null; } return $this->_data['title']; } /** * Get the feed character encoding * * @return string|null */ public function getEncoding() { if (!array_key_exists('encoding', $this->_data)) { return 'UTF-8'; } return $this->_data['encoding']; } /** * Get the feed's base url * * @return string|null */ public function getBaseUrl() { if (!array_key_exists('baseUrl', $this->_data)) { return null; } return $this->_data['baseUrl']; } /** * Get the URLs used as Pubsubhubbub hubs endpoints * * @return string|null */ public function getHubs() { if (!array_key_exists('hubs', $this->_data)) { return null; } return $this->_data['hubs']; } /** * Get the feed categories * * @return string|null */ public function getCategories() { if (!array_key_exists('categories', $this->_data)) { return null; } return $this->_data['categories']; } /** * Resets the instance and deletes all data * * @return void */ public function reset() { $this->_data = array(); } /** * Set the current feed type being exported to "rss" or "atom". This allows * other objects to gracefully choose whether to execute or not, depending * on their appropriateness for the current type, e.g. renderers. * * @param string $type */ public function setType($type) { $this->_type = $type; } /** * Retrieve the current or last feed type exported. * * @return string Value will be "rss" or "atom" */ public function getType() { return $this->_type; } /** * Unset a specific data point * * @param string $name */ public function remove($name) { if (isset($this->_data[$name])) { unset($this->_data[$name]); } } /** * Method overloading: call given method on first extension implementing it * * @param string $method * @param array $args * @return mixed * @throws Zend_Feed_Exception if no extensions implements the method */ public function __call($method, $args) { foreach ($this->_extensions as $extension) { try { return call_user_func_array(array($extension, $method), $args); } catch (Zend_Feed_Writer_Exception_InvalidMethodException $e) { } } // require_once 'Zend/Feed/Exception.php'; throw new Zend_Feed_Exception('Method: ' . $method . ' does not exist and could not be located on a registered Extension'); } /** * Load extensions from Zend_Feed_Writer * * @return void */ protected function _loadExtensions() { $all = Zend_Feed_Writer::getExtensions(); $exts = $all['feed']; foreach ($exts as $ext) { $className = Zend_Feed_Writer::getPluginLoader()->getClassName($ext); $this->_extensions[$ext] = new $className(); $this->_extensions[$ext]->setEncoding($this->getEncoding()); } } }
{'content_hash': '50712ca8e263907eabfbb6aaae9727f2', 'timestamp': '', 'source': 'github', 'line_count': 698, 'max_line_length': 148, 'avg_line_length': 27.982808022922637, 'alnum_prop': 0.5154106082326438, 'repo_name': 'nslod/frapi', 'id': '6ab6e91b2cc0aacb30ade617336906cba4739972', 'size': '20275', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'src/frapi/library/Zend/Feed/Writer/Feed/FeedAbstract.php', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'ApacheConf', 'bytes': '17176'}, {'name': 'CSS', 'bytes': '55601'}, {'name': 'HTML', 'bytes': '71336'}, {'name': 'JavaScript', 'bytes': '48653'}, {'name': 'PHP', 'bytes': '14857257'}, {'name': 'Shell', 'bytes': '802'}, {'name': 'Smarty', 'bytes': '17214'}]}
-webkit-panda
{'content_hash': '730cbaa3252aea579bdce4276b2d0a8e', 'timestamp': '', 'source': 'github', 'line_count': 1, 'max_line_length': 13, 'avg_line_length': 14.0, 'alnum_prop': 0.7857142857142857, 'repo_name': 'tonyganch/gonzales-pe', 'id': '84491b2302a7eca8140c32f02c6b13494ecc6489', 'size': '14', 'binary': False, 'copies': '8', 'ref': 'refs/heads/dev', 'path': 'test/css/value/5.css', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '83311'}, {'name': 'CoffeeScript', 'bytes': '62175'}, {'name': 'JavaScript', 'bytes': '563696'}, {'name': 'Shell', 'bytes': '4885'}]}
ironman package =============== Subpackages ----------- .. toctree:: ironman.constructs Submodules ---------- ironman.communicator module ~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. automodule:: ironman.communicator :members: :undoc-members: :show-inheritance: ironman.globals module ~~~~~~~~~~~~~~~~~~~~~~ .. automodule:: ironman.globals :members: :undoc-members: :show-inheritance: ironman.hardware module ~~~~~~~~~~~~~~~~~~~~~~~ .. automodule:: ironman.hardware :members: :undoc-members: :show-inheritance: ironman.history module ~~~~~~~~~~~~~~~~~~~~~~ .. automodule:: ironman.history :members: :undoc-members: :show-inheritance: ironman.interfaces module ~~~~~~~~~~~~~~~~~~~~~~~~~ .. automodule:: ironman.interfaces :members: :undoc-members: :show-inheritance: ironman.packet module ~~~~~~~~~~~~~~~~~~~~~ .. automodule:: ironman.packet :members: :undoc-members: :show-inheritance: ironman.server module ~~~~~~~~~~~~~~~~~~~~~ .. automodule:: ironman.server :members: :undoc-members: :show-inheritance: ironman.utilities module ~~~~~~~~~~~~~~~~~~~~~~~~ .. automodule:: ironman.utilities :members: :undoc-members: :show-inheritance:
{'content_hash': '92ad791f759a9d7690fa891495a3f60d', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 36, 'avg_line_length': 16.32894736842105, 'alnum_prop': 0.564867042707494, 'repo_name': 'kratsg/ironman', 'id': '8576915da49e675015a8b2ceecb0bc602cfc7e39', 'size': '1241', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/ironman.rst', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Makefile', 'bytes': '1044'}, {'name': 'Python', 'bytes': '54663'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" > <title>Pittsburgh 2014 - Proposal</title> <meta name="author" content="Alex Henthorn-Iwane" > <link rel="alternate" type="application/rss+xml" title="devopsdays RSS Feed" href="http://www.devopsdays.org/feed/" > <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load('jquery', '1.3.2'); function initialize() { return; } </script> <!---This is a combined jAmpersand, jqwindont , jPullquote --> <script type="text/javascript" src="/js/devops.js"></script> <!--- Blueprint CSS Framework Screen + Fancytype-Screen + jedi.css --> <link rel="stylesheet" href="/css/devops.min.css" type="text/css" media="screen, projection"> <link rel="stylesheet" href="/css/blueprint/print.css" type="text/css" media="print"> <!--[if IE]> <link rel="stylesheet" href="/css/blueprint/ie.css" type="text/css" media="screen, projection"> <![endif]--> </head> <body onload="initialize()"> <div class="container "> <div class="span-24 last" id="header"> <div class="span-16 first"> <img src="/images/devopsdays-banner.png" title="devopsdays banner" width="801" height="115" alt="devopdays banner" ><br> </div> <div class="span-8 last"> </div> </div> <div class="span-24 last"> <div class="span-15 first"> <div id="headermenu"> <table > <tr> <td> <a href="/"><img alt="home" title="home" src="/images/home.png"></a> <a href="/">Home</a> </td> <td> <a href="/contact/"><img alt="contact" title="contact" src="/images/contact.png"></a> <a href="/contact/">Contact</a> </td> <td> <a href="/events/"><img alt="events" title="events" src="/images/events.png"></a> <a href="/events/">Events</a> </td> <td> <a href="/presentations/"><img alt="presentations" title="presentations" src="/images/presentations.png"></a> <a href="/presentations/">Presentations</a> </td> <td> <a href="/blog/"><img alt="blog" title="blog" src="/images/blog.png"></a> <a href="/blog/">Blog</a> </td> </tr> </table> </div> </div> <div class="span-8 last"> </div> <div class="span-24 last" id="header"> <div class="span-15 first"> <h1>Pittsburgh 2014 - Proposal </h1> </div> <div class="span-8 last"> </div> <h1><font color ="gray">Steel</font> sponsors</h1> </div> <div class="span-15 "> <div class="span-15 last "> <div class="submenu"> <h3> <a href="/events/2014-pittsburgh/">welcome</a>&nbsp; <a href="/events/2014-pittsburgh/propose">propose</a>&nbsp; <a href="/events/2014-pittsburgh/program">program</a>&nbsp; <a href="/events/2014-pittsburgh/location">location</a>&nbsp; <a href="/events/2014-pittsburgh/registration">register</a>&nbsp; <a href="/events/2014-pittsburgh/sponsor">sponsor</a>&nbsp; <a href="/events/2014-pittsburgh/contact">contact</a>&nbsp; <a href="/events/2014-pittsburgh/conduct">conduct</a>&nbsp; </h3> </div> Back to <a href='..'>proposals overview</a> - <a href='../../program'>program</a> <hr> <h3>DevOps Meets Complex IT Infrastructure</h3> <p><strong>Abstract:</strong></p> <p>To scale DevOps to enterprise IT requires dealing with the complexities of enterprise infrastructure. Not everything is virtualized or in the public cloud, so how can automation address this reality? This talk will propose some ways to understand the challenges and what’s needed from automation to make truly hybrid IT infrastructure elastic, efficient, self-service and able to integrate into automated processes like continuous integration.</p> <p><strong>Speaker:</strong> Alex Henthorn-Iwane</p> </div> <div class="span-15 first last"> <script type="text/javascript"> // var disqus_developer = 1; </script> <div id="disqus_thread"></div> <script type="text/javascript"> var disqus_shortname = 'devopsdays'; (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = 'http://' + disqus_shortname + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); </script> <noscript>Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript> <a href="http://disqus.com" class="dsq-brlink">blog comments powered by <span class="logo-disqus">Disqus</span></a> <hr> </div> </div> <div class="span-8 last"> <div class="span-8 last"> <a href='http://www.gopivotal.com/'><img border=0 alt='Pivotal' title='Pivotal' width=100px height=100px src='/events/2014-pittsburgh/logos/pivotal.png'></a> <a href='http://www.showclix.com/'><img border=0 alt='ShowClix' title='ShowClix' width=100px height=100px src='/events/2014-pittsburgh/logos/showclix.png'></a> <a href='http://www.saul.com/'><img border=0 alt='Saul Ewing' title='Saul Ewing' width=100px height=100px src='/events/2014-pittsburgh/logos/saul.png'></a> <a href='http://www.ibm.com/'><img border=0 alt='IBM' title='IBM' width=100px height=100px src='/events/2014-pittsburgh/logos/ibm.png'></a> <a href='http://www.vmware.com/'><img border=0 alt='VMware' title='VMware' width=100px height=100px src='/events/2014-pittsburgh/logos/vmware.png'></a> <a href='http://www.getchef.com/'><img border=0 alt='Chef' title='Chef' width=100px height=100px src='/events/2014-pittsburgh/logos/chef.png'></a> <a href='http://www.ca.com/'><img border=0 alt='CA Technologies' title='CA Technologies' width=100px height=100px src='/events/2014-pittsburgh/logos/ca.png'></a> <a href='http://www.modcloth.com/'><img border=0 alt='ModCloth' title='ModCloth' width=100px height=100px src='/events/2014-pittsburgh/logos/modcloth.jpg'></a> <a href='http://www.sumologic.com/'><img border=0 alt='Sumo Logic' title='Sumo Logic' width=100px height=100px src='/events/2014-pittsburgh/logos/sumologic.png'></a> <a href='http://www.pghtech.org/'><img border=0 alt='Pittsburgh Technology Council' title='Pittsburgh Technology Council' width=100px height=100px src='/events/2014-pittsburgh/logos/ptc.png'></a> <a href='http://www.puppetlabs.com/'><img border=0 alt='Puppet Labs' title='Puppet Labs' width=100px height=100px src='/events/2014-pittsburgh/logos/puppetlabs.png'></a> <a href='http://www.xebialabs.com/'><img border=0 alt='Xebia Labs' title='Xebia Labs' width=100px height=100px src='/events/2014-pittsburgh/logos/xebialabs.png'></a> <a href='http://www.cfengine.com/'><img border=0 alt='CFEngine' title='CFEngine' width=100px height=100px src='/events/2014-pittsburgh/logos/cfengine.png'></a> <br/> <br/> <h1><font color="Gainsboro">Aluminum</font> sponsors</h1> <a href='http://www.dyn.com/'><img border=0 alt='Dyn' title='Dyn' width=100px height=100px src='/events/2014-pittsburgh/logos/dyn.png'></a> <a href='http://www.jfrog.com/'><img border=0 alt='JFrog' title='JFrog' width=100px height=100px src='/events/2014-pittsburgh/logos/jfrog.png'></a> <a href='http://www.digitalocean.com/'><img border=0 alt='Digital Ocean' title='Digital Ocean' width=100px height=100px src='/events/2014-pittsburgh/logos/digitalocean.png'></a> <a href='http://www.pagerduty.com/'><img border=0 alt='PagerDuty' title='PagerDuty' width=100px height=100px src='/events/2014-pittsburgh/logos/pagerduty.png'></a> <a href='http://www.ansible.com/'><img border=0 alt='Ansible' title='Ansible' width=100px height=100px src='/events/2014-pittsburgh/logos/ansible.png'></a> <br/> <br/> <h1><font color="MediumTurquoise">Glass</font> sponsors</h1> <a href='http://www.maxcdn.com/'><img border=0 alt='MaxCDN' title='MaxCDN' width=100px height=100px src='/events/2014-pittsburgh/logos/maxcdn.png'></a> <a href='http://www.joyent.com/'><img border=0 alt='Joyent' title='Joyent' width=100px height=100px src='/events/2014-pittsburgh/logos/joyent.png'></a> <a href='http://www.brandingbrand.com/'><img border=0 alt='Branding Brand' title='Branding Brand' width=100px height=100px src='/events/2014-pittsburgh/logos/branding-brand.png'></a> <a href='http://www.apcera.com/'><img border=0 alt='Apcera' title='Apcera' width=100px height=100px src='/events/2014-pittsburgh/logos/apcera.png'></a> <a href='http://www.innovationworks.org/'><img border=0 alt='Innovations Works' title='Innovations Works' width=100px height=100px src='/events/2014-pittsburgh/logos/iw.png'></a> <a href='http://www.gothrive.io/'><img border=0 alt='THRIVE' title='THRIVE' width=100px height=100px src='/events/2014-pittsburgh/logos/thrive.png'></a> <a href='http://www.quickleft.com/'><img border=0 alt='Quick Left' title='Quick Left' width=100px height=100px src='/events/2014-pittsburgh/logos/quickleft.png'></a> <br/> <br/> <h1>Media sponsors</h1> <a href='http://www.rustbuilt.com/'><img border=0 alt='RUSTBUILT' title='RUSTBUILT' width=100px height=100px src='/events/2014-pittsburgh/logos/rustbuilt.png'></a> <a href='http://www.revvoakland.com/'><img border=0 alt='Revv Oakland' title='Revv Oakland' width=100px height=100px src='/events/2014-pittsburgh/logos/revv.png'></a> <a href='http://www.velocityconf.com/'><img border=0 alt='Velocity Conf' title='Velocity Conf' width=100px height=100px src='/events/2014-pittsburgh/logos/velocity.png'></a> <a href='http://www.meetup.com/Pittsburgh-Code-Supply/'><img border=0 alt='Pittsburgh Code & Supply' title='Pittsburgh Code & Supply' width=100px height=100px src='/events/2014-pittsburgh/logos/code_and_supply.png'></a> <a href='http://www.oreilly.com/'><img border=0 alt='O-Reilly Media' title='O-Reilly Media' width=100px height=100px src='/events/2014-pittsburgh/logos/oreilly.png'></a> <br/> <br/> <h1>Host sponsor</h1> <a href='http://www.cs.pitt.edu/'><img border=0 alt='University of Pittsburgh Computer Science' title='University of Pittsburgh Computer Science' width=100px height=100px src='/events/2014-pittsburgh/logos/pittCS.jpg'></a> </div> <div class="span-8 last"> </div> </div> </div> <script type="text/javascript"> var _gaq = _gaq || []; _gaq.push(['_setAccount', 'UA-9713393-1']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); </script> </body> </html>
{'content_hash': '1566d19fcd7efabf2c61562e4e11abe7', 'timestamp': '', 'source': 'github', 'line_count': 238, 'max_line_length': 452, 'avg_line_length': 44.424369747899156, 'alnum_prop': 0.692424099120401, 'repo_name': 'benjohnson77/devopsdays-web', 'id': '114aed84cd74957cf149037c75a07ab07a2fd94b', 'size': '10579', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'static/events/2014-pittsburgh/proposals/DevOps Meets Complex IT Infrastructure/index.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '805234'}, {'name': 'HTML', 'bytes': '22605132'}, {'name': 'JavaScript', 'bytes': '425827'}, {'name': 'Ruby', 'bytes': '650'}, {'name': 'Shell', 'bytes': '2938'}]}
<concrete5-cif version="1.0"> <area name="Main"> <blocks> <block type="core_theme_documentation_breadcrumb" name=""> <style> <backgroundColor/> <backgroundRepeat/> <backgroundSize/> <backgroundPosition/> <borderWidth/> <borderColor/> <borderStyle/> <borderRadius/> <baseFontSize/> <alignment/> <textColor/> <linkColor/> <paddingTop/> <paddingBottom/> <paddingLeft/> <paddingRight/> <marginTop/> <marginBottom/> <marginLeft/> <marginRight/> <rotate/> <boxShadowHorizontal/> <boxShadowVertical/> <boxShadowBlur/> <boxShadowSpread/> <boxShadowColor/> <customClass>mt-5</customClass> <customID/> <customElementAttribute/> <hideOnExtraSmallDevice/> <hideOnSmallDevice/> <hideOnMediumDevice/> <hideOnLargeDevice/> </style> </block> <block type="content" name=""> <data table="btContentLocal"> <record> <content><![CDATA[<h1>Calendar & Events</h1> <p class="lead">Turn your site into a collaborative calendar with the following block types.</p> <p>(Note: you will have to modify the existing block types within this documentation to point to your installed calendar and its events.</p> ]]></content> </record> </data> </block> <block type="content" name=""> <data table="btContentLocal"> <record> <content><![CDATA[<h2 class="text-primary">Calendar</h2> ]]></content> </record> </data> </block> <block type="calendar" name=""> <data table="btCalendar"> <record> <caID><![CDATA[0]]></caID> <chooseCalendar><![CDATA[]]></chooseCalendar> <calendarAttributeKeyHandle><![CDATA[]]></calendarAttributeKeyHandle> <filterByTopicAttributeKeyID><![CDATA[0]]></filterByTopicAttributeKeyID> <filterByTopicID><![CDATA[0]]></filterByTopicID> <viewTypes><![CDATA[["month","basicWeek","basicDay"]]]></viewTypes> <viewTypesOrder> <![CDATA[["month_Month","basicWeek_Week","basicDay_Day"]]]></viewTypesOrder> <defaultView><![CDATA[month]]></defaultView> <navLinks><![CDATA[0]]></navLinks> <eventLimit><![CDATA[0]]></eventLimit> <lightboxProperties><![CDATA[[]]]></lightboxProperties> </record> </data> </block> <block type="content" name=""> <data table="btContentLocal"> <record> <content><![CDATA[<h2 class="text-primary">Event List</h2> ]]></content> </record> </data> </block> <block type="event_list" name=""> <data table="btEventList"> <record> <caID><![CDATA[0]]></caID> <chooseCalendar><![CDATA[]]></chooseCalendar> <calendarAttributeKeyHandle><![CDATA[]]></calendarAttributeKeyHandle> <totalToRetrieve><![CDATA[9]]></totalToRetrieve> <totalPerPage><![CDATA[3]]></totalPerPage> <filterByTopicAttributeKeyID><![CDATA[0]]></filterByTopicAttributeKeyID> <filterByTopic>none</filterByTopic> <filterByTopicID><![CDATA[0]]></filterByTopicID> <filterByPageTopicAttributeKeyHandle><![CDATA[]]></filterByPageTopicAttributeKeyHandle> <filterByFeatured><![CDATA[0]]></filterByFeatured> <eventListTitle><![CDATA[Featured Events]]></eventListTitle> <linkToPage><![CDATA[0]]></linkToPage> <titleFormat><![CDATA[h5]]></titleFormat> </record> </data> </block> <block type="content" name=""> <data table="btContentLocal"> <record> <content><![CDATA[<h2 class="text-primary">Calendar Event</h2> ]]></content> </record> </data> </block> <block type="calendar_event" name=""> <data table="btCalendarEvent"> <record> <mode><![CDATA[S]]></mode> <calendarEventAttributeKeyHandle><![CDATA[]]></calendarEventAttributeKeyHandle> <calendarID><![CDATA[0]]></calendarID> <eventID><![CDATA[0]]></eventID> <displayEventAttributes><![CDATA[[]]]></displayEventAttributes> <allowExport>1</allowExport> <enableLinkToPage><![CDATA[0]]></enableLinkToPage> <displayEventName>1</displayEventName> <displayEventDate>1</displayEventDate> <displayEventDescription>1</displayEventDescription> </record> </data> </block> </blocks> </area> </concrete5-cif>
{'content_hash': '7d39c8b4fe62d77c5a967d871304c09c', 'timestamp': '', 'source': 'github', 'line_count': 131, 'max_line_length': 140, 'avg_line_length': 46.152671755725194, 'alnum_prop': 0.4439298709890837, 'repo_name': 'biplobice/concrete5', 'id': 'efb4f12b44bf32a3394ee7d8a5ec0fe4abad906e', 'size': '6046', 'binary': False, 'copies': '7', 'ref': 'refs/heads/develop', 'path': 'concrete/themes/atomik/documentation/calendar.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '74'}, {'name': 'CSS', 'bytes': '140170'}, {'name': 'HTML', 'bytes': '312828'}, {'name': 'Hack', 'bytes': '45'}, {'name': 'JavaScript', 'bytes': '915053'}, {'name': 'Less', 'bytes': '472475'}, {'name': 'PHP', 'bytes': '15060224'}, {'name': 'PowerShell', 'bytes': '4292'}, {'name': 'SCSS', 'bytes': '788558'}, {'name': 'Shell', 'bytes': '31663'}]}
<?php declare(strict_types=1); namespace Sylius\Component\User\Model; interface CredentialsHolderInterface { /** * @return string|null */ public function getPlainPassword(): ?string; /** * @param string|null $plainPassword */ public function setPlainPassword(?string $plainPassword): void; /** * Returns the password used to authenticate the user. * * This should be the encoded password. On authentication, a plain-text * password will be salted, encoded, and then compared to this value. * * @return string|null */ public function getPassword(); /** * @param string|null $encodedPassword */ public function setPassword(?string $encodedPassword): void; /** * Returns the salt that was originally used to encode the password. * * This can return null if the password was not encoded using a salt. * * @return string|null */ public function getSalt(); /** * Removes sensitive data from the user. * * This is important if, at any given point, sensitive information like * the plain-text password is stored on this object. */ public function eraseCredentials(); }
{'content_hash': '3cd4cf2fb2f667d514142eb4de103464', 'timestamp': '', 'source': 'github', 'line_count': 52, 'max_line_length': 75, 'avg_line_length': 23.826923076923077, 'alnum_prop': 0.6432606941081518, 'repo_name': 'videni/Sylius', 'id': '0278dcb4130676a390a05e89b24d65d38930e7e5', 'size': '1450', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'src/Sylius/Component/User/Model/CredentialsHolderInterface.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '2192'}, {'name': 'Gherkin', 'bytes': '843736'}, {'name': 'HTML', 'bytes': '308877'}, {'name': 'JavaScript', 'bytes': '74462'}, {'name': 'PHP', 'bytes': '6793548'}, {'name': 'Shell', 'bytes': '29715'}]}
<!DOCTYPE html> <html> <head> <title>polymer-meta</title> <script src="../platform/platform.js"></script> <link rel="import" href="polymer-meta.html"> </head> <body> <polymer-meta id="x-foo" label="foo"></polymer-meta> <polymer-meta id="x-bar" label="bar"></polymer-meta> <polymer-meta id="x-zot" label="zot"> <template> <div>[zot's metadata]</div> </template> </polymer-meta> <template repeat="{{metadata}}"> <div>{{label}}</div> </template> <hr> <script> document.addEventListener('polymer-ready', function() { var meta = document.createElement('polymer-meta'); document.querySelector('template[repeat]').model = { metadata: meta.list }; var archetype = meta.byId('x-zot').archetype; document.body.appendChild(archetype.createInstance().querySelector('*')); }); </script> </body> </html>
{'content_hash': 'd1144f5bd6b12431bf32078086a3668d', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 79, 'avg_line_length': 25.542857142857144, 'alnum_prop': 0.6140939597315436, 'repo_name': 'googlearchive/labs', 'id': 'a30d18ada5841e955788906866e1e8fe1ae7b380', 'size': '894', 'binary': False, 'copies': '30', 'ref': 'refs/heads/master', 'path': 'sjmiles/demos/segmented-app-min/components/polymer-meta/smoke.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ApacheConf', 'bytes': '2979'}, {'name': 'CSS', 'bytes': '298886'}, {'name': 'HTML', 'bytes': '9672921'}, {'name': 'JavaScript', 'bytes': '2370396'}, {'name': 'PHP', 'bytes': '2151'}, {'name': 'Python', 'bytes': '7016'}, {'name': 'Shell', 'bytes': '19655'}]}
package org.instantlogic.designer.event; import org.instantlogic.designer.AttributeDesignEntityGenerator; import org.instantlogic.designer.DesignerApplicationGenerator; import org.instantlogic.designer.EventDesign; public class AttributeDetailsEventGenerator extends EventDesign { public static AttributeDetailsEventGenerator EVENT = new AttributeDetailsEventGenerator(); private AttributeDetailsEventGenerator() { DesignerApplicationGenerator.APPLICATION.addToEvents(this); setName("AttributeDetails"); addToParameters(AttributeDesignEntityGenerator.ENTITY); } }
{'content_hash': '1bc88fe2409510b800b88629dd945ebe', 'timestamp': '', 'source': 'github', 'line_count': 16, 'max_line_length': 91, 'avg_line_length': 36.125, 'alnum_prop': 0.856401384083045, 'repo_name': 'johan-gorter/Instantlogic', 'id': 'd5c1644c7b3115e0660674056069a89acd71b1aa', 'size': '578', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'bootstrappers/designer/src/main/java/org/instantlogic/designer/event/AttributeDetailsEventGenerator.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '196'}, {'name': 'CSS', 'bytes': '17961'}, {'name': 'FreeMarker', 'bytes': '30056'}, {'name': 'HTML', 'bytes': '65473'}, {'name': 'Java', 'bytes': '1672816'}, {'name': 'JavaScript', 'bytes': '331610'}, {'name': 'Shell', 'bytes': '186'}]}
if (Meteor.isClient) { Template.resolution.helpers({ isOwner: function(){ return this.owner === Meteor.userId() } }); Template.resolution.events({ 'click .toggle-checked': function(){ Meteor.call("updateResolution", this._id, !this.checked) }, 'click .delete': function(){ Meteor.call('deleteResolution', this._id); }, 'click .toggle-private': function(){ Meteor.call("setPrivate", this._id, !this.private) } }); }
{'content_hash': '9e442f6a3d00c0e341c0a5f27c60bb3c', 'timestamp': '', 'source': 'github', 'line_count': 21, 'max_line_length': 62, 'avg_line_length': 22.952380952380953, 'alnum_prop': 0.6016597510373444, 'repo_name': 'sachin87/Resolutions', 'id': 'ec9180ccaab10e335d62af3eb058e7f276cc8930', 'size': '482', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'components/resolutions/resolutions.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1357'}, {'name': 'HTML', 'bytes': '1089'}, {'name': 'JavaScript', 'bytes': '2480'}]}
package resources // Copyright (c) Microsoft and contributors. All rights reserved. // // 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. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. import ( "context" "github.com/Azure/go-autorest/autorest" "github.com/Azure/go-autorest/autorest/azure" "github.com/Azure/go-autorest/autorest/validation" "github.com/Azure/go-autorest/tracing" "net/http" ) // DeploymentOperationsClient is the provides operations for working with resources and resource groups. type DeploymentOperationsClient struct { BaseClient } // NewDeploymentOperationsClient creates an instance of the DeploymentOperationsClient client. func NewDeploymentOperationsClient(subscriptionID string) DeploymentOperationsClient { return NewDeploymentOperationsClientWithBaseURI(DefaultBaseURI, subscriptionID) } // NewDeploymentOperationsClientWithBaseURI creates an instance of the DeploymentOperationsClient client. func NewDeploymentOperationsClientWithBaseURI(baseURI string, subscriptionID string) DeploymentOperationsClient { return DeploymentOperationsClient{NewWithBaseURI(baseURI, subscriptionID)} } // Get gets a deployments operation. // Parameters: // resourceGroupName - the name of the resource group. The name is case insensitive. // deploymentName - the name of the deployment. // operationID - the ID of the operation to get. func (client DeploymentOperationsClient) Get(ctx context.Context, resourceGroupName string, deploymentName string, operationID string) (result DeploymentOperation, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsClient.Get") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}, {TargetValue: deploymentName, Constraints: []validation.Constraint{{Target: "deploymentName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "deploymentName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "deploymentName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentOperationsClient", "Get", err.Error()) } req, err := client.GetPreparer(ctx, resourceGroupName, deploymentName, operationID) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "Get", nil, "Failure preparing request") return } resp, err := client.GetSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "Get", resp, "Failure sending request") return } result, err = client.GetResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "Get", resp, "Failure responding to request") } return } // GetPreparer prepares the Get request. func (client DeploymentOperationsClient) GetPreparer(ctx context.Context, resourceGroupName string, deploymentName string, operationID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "deploymentName": autorest.Encode("path", deploymentName), "operationId": autorest.Encode("path", operationID), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-03-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations/{operationId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetSender sends the Get request. The method will close the // http.Response Body if it receives an error. func (client DeploymentOperationsClient) GetSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // GetResponder handles the response to the Get request. The method always // closes the http.Response Body. func (client DeploymentOperationsClient) GetResponder(resp *http.Response) (result DeploymentOperation, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // GetAtSubscriptionScope gets a deployments operation. // Parameters: // deploymentName - the name of the deployment. // operationID - the ID of the operation to get. func (client DeploymentOperationsClient) GetAtSubscriptionScope(ctx context.Context, deploymentName string, operationID string) (result DeploymentOperation, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsClient.GetAtSubscriptionScope") defer func() { sc := -1 if result.Response.Response != nil { sc = result.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: deploymentName, Constraints: []validation.Constraint{{Target: "deploymentName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "deploymentName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "deploymentName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentOperationsClient", "GetAtSubscriptionScope", err.Error()) } req, err := client.GetAtSubscriptionScopePreparer(ctx, deploymentName, operationID) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "GetAtSubscriptionScope", nil, "Failure preparing request") return } resp, err := client.GetAtSubscriptionScopeSender(req) if err != nil { result.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "GetAtSubscriptionScope", resp, "Failure sending request") return } result, err = client.GetAtSubscriptionScopeResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "GetAtSubscriptionScope", resp, "Failure responding to request") } return } // GetAtSubscriptionScopePreparer prepares the GetAtSubscriptionScope request. func (client DeploymentOperationsClient) GetAtSubscriptionScopePreparer(ctx context.Context, deploymentName string, operationID string) (*http.Request, error) { pathParameters := map[string]interface{}{ "deploymentName": autorest.Encode("path", deploymentName), "operationId": autorest.Encode("path", operationID), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-03-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations/{operationId}", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // GetAtSubscriptionScopeSender sends the GetAtSubscriptionScope request. The method will close the // http.Response Body if it receives an error. func (client DeploymentOperationsClient) GetAtSubscriptionScopeSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // GetAtSubscriptionScopeResponder handles the response to the GetAtSubscriptionScope request. The method always // closes the http.Response Body. func (client DeploymentOperationsClient) GetAtSubscriptionScopeResponder(resp *http.Response) (result DeploymentOperation, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // List gets all deployments operations for a deployment. // Parameters: // resourceGroupName - the name of the resource group. The name is case insensitive. // deploymentName - the name of the deployment with the operation to get. // top - the number of results to return. func (client DeploymentOperationsClient) List(ctx context.Context, resourceGroupName string, deploymentName string, top *int32) (result DeploymentOperationsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsClient.List") defer func() { sc := -1 if result.dolr.Response.Response != nil { sc = result.dolr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: resourceGroupName, Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil}, {Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\p{L}\._\(\)\w]+$`, Chain: nil}}}, {TargetValue: deploymentName, Constraints: []validation.Constraint{{Target: "deploymentName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "deploymentName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "deploymentName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentOperationsClient", "List", err.Error()) } result.fn = client.listNextResults req, err := client.ListPreparer(ctx, resourceGroupName, deploymentName, top) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "List", nil, "Failure preparing request") return } resp, err := client.ListSender(req) if err != nil { result.dolr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "List", resp, "Failure sending request") return } result.dolr, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "List", resp, "Failure responding to request") } return } // ListPreparer prepares the List request. func (client DeploymentOperationsClient) ListPreparer(ctx context.Context, resourceGroupName string, deploymentName string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "deploymentName": autorest.Encode("path", deploymentName), "resourceGroupName": autorest.Encode("path", resourceGroupName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-03-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if top != nil { queryParameters["$top"] = autorest.Encode("query", *top) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/deployments/{deploymentName}/operations", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListSender sends the List request. The method will close the // http.Response Body if it receives an error. func (client DeploymentOperationsClient) ListSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListResponder handles the response to the List request. The method always // closes the http.Response Body. func (client DeploymentOperationsClient) ListResponder(resp *http.Response) (result DeploymentOperationsListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listNextResults retrieves the next set of results, if any. func (client DeploymentOperationsClient) listNextResults(ctx context.Context, lastResults DeploymentOperationsListResult) (result DeploymentOperationsListResult, err error) { req, err := lastResults.deploymentOperationsListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "listNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "listNextResults", resp, "Failure sending next results request") } result, err = client.ListResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "listNextResults", resp, "Failure responding to next results request") } return } // ListComplete enumerates all values, automatically crossing page boundaries as required. func (client DeploymentOperationsClient) ListComplete(ctx context.Context, resourceGroupName string, deploymentName string, top *int32) (result DeploymentOperationsListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsClient.List") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.List(ctx, resourceGroupName, deploymentName, top) return } // ListAtSubscriptionScope gets all deployments operations for a deployment. // Parameters: // deploymentName - the name of the deployment with the operation to get. // top - the number of results to return. func (client DeploymentOperationsClient) ListAtSubscriptionScope(ctx context.Context, deploymentName string, top *int32) (result DeploymentOperationsListResultPage, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsClient.ListAtSubscriptionScope") defer func() { sc := -1 if result.dolr.Response.Response != nil { sc = result.dolr.Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } if err := validation.Validate([]validation.Validation{ {TargetValue: deploymentName, Constraints: []validation.Constraint{{Target: "deploymentName", Name: validation.MaxLength, Rule: 64, Chain: nil}, {Target: "deploymentName", Name: validation.MinLength, Rule: 1, Chain: nil}, {Target: "deploymentName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil { return result, validation.NewError("resources.DeploymentOperationsClient", "ListAtSubscriptionScope", err.Error()) } result.fn = client.listAtSubscriptionScopeNextResults req, err := client.ListAtSubscriptionScopePreparer(ctx, deploymentName, top) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "ListAtSubscriptionScope", nil, "Failure preparing request") return } resp, err := client.ListAtSubscriptionScopeSender(req) if err != nil { result.dolr.Response = autorest.Response{Response: resp} err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "ListAtSubscriptionScope", resp, "Failure sending request") return } result.dolr, err = client.ListAtSubscriptionScopeResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "ListAtSubscriptionScope", resp, "Failure responding to request") } return } // ListAtSubscriptionScopePreparer prepares the ListAtSubscriptionScope request. func (client DeploymentOperationsClient) ListAtSubscriptionScopePreparer(ctx context.Context, deploymentName string, top *int32) (*http.Request, error) { pathParameters := map[string]interface{}{ "deploymentName": autorest.Encode("path", deploymentName), "subscriptionId": autorest.Encode("path", client.SubscriptionID), } const APIVersion = "2019-03-01" queryParameters := map[string]interface{}{ "api-version": APIVersion, } if top != nil { queryParameters["$top"] = autorest.Encode("query", *top) } preparer := autorest.CreatePreparer( autorest.AsGet(), autorest.WithBaseURL(client.BaseURI), autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.Resources/deployments/{deploymentName}/operations", pathParameters), autorest.WithQueryParameters(queryParameters)) return preparer.Prepare((&http.Request{}).WithContext(ctx)) } // ListAtSubscriptionScopeSender sends the ListAtSubscriptionScope request. The method will close the // http.Response Body if it receives an error. func (client DeploymentOperationsClient) ListAtSubscriptionScopeSender(req *http.Request) (*http.Response, error) { sd := autorest.GetSendDecorators(req.Context(), azure.DoRetryWithRegistration(client.Client)) return autorest.SendWithSender(client, req, sd...) } // ListAtSubscriptionScopeResponder handles the response to the ListAtSubscriptionScope request. The method always // closes the http.Response Body. func (client DeploymentOperationsClient) ListAtSubscriptionScopeResponder(resp *http.Response) (result DeploymentOperationsListResult, err error) { err = autorest.Respond( resp, client.ByInspecting(), azure.WithErrorUnlessStatusCode(http.StatusOK), autorest.ByUnmarshallingJSON(&result), autorest.ByClosing()) result.Response = autorest.Response{Response: resp} return } // listAtSubscriptionScopeNextResults retrieves the next set of results, if any. func (client DeploymentOperationsClient) listAtSubscriptionScopeNextResults(ctx context.Context, lastResults DeploymentOperationsListResult) (result DeploymentOperationsListResult, err error) { req, err := lastResults.deploymentOperationsListResultPreparer(ctx) if err != nil { return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "listAtSubscriptionScopeNextResults", nil, "Failure preparing next results request") } if req == nil { return } resp, err := client.ListAtSubscriptionScopeSender(req) if err != nil { result.Response = autorest.Response{Response: resp} return result, autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "listAtSubscriptionScopeNextResults", resp, "Failure sending next results request") } result, err = client.ListAtSubscriptionScopeResponder(resp) if err != nil { err = autorest.NewErrorWithError(err, "resources.DeploymentOperationsClient", "listAtSubscriptionScopeNextResults", resp, "Failure responding to next results request") } return } // ListAtSubscriptionScopeComplete enumerates all values, automatically crossing page boundaries as required. func (client DeploymentOperationsClient) ListAtSubscriptionScopeComplete(ctx context.Context, deploymentName string, top *int32) (result DeploymentOperationsListResultIterator, err error) { if tracing.IsEnabled() { ctx = tracing.StartSpan(ctx, fqdn+"/DeploymentOperationsClient.ListAtSubscriptionScope") defer func() { sc := -1 if result.Response().Response.Response != nil { sc = result.page.Response().Response.Response.StatusCode } tracing.EndSpan(ctx, sc, err) }() } result.page, err = client.ListAtSubscriptionScope(ctx, deploymentName, top) return }
{'content_hash': '71b5773d835eafe11bb7e112f1d5f39d', 'timestamp': '', 'source': 'github', 'line_count': 474, 'max_line_length': 196, 'avg_line_length': 44.529535864978904, 'alnum_prop': 0.7650068697588478, 'repo_name': 'pecameron/origin', 'id': '7b0413e9395cadc1f5e2cdda13f2f875f2aa1277', 'size': '21107', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2019-03-01/resources/deploymentoperations.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '921'}, {'name': 'Dockerfile', 'bytes': '2240'}, {'name': 'Go', 'bytes': '2260347'}, {'name': 'Makefile', 'bytes': '6395'}, {'name': 'Python', 'bytes': '14593'}, {'name': 'Shell', 'bytes': '310150'}]}
static NSString* RNPStatusUndetermined = @"undetermined"; static NSString* RNPStatusDenied = @"denied"; static NSString* RNPStatusAuthorized = @"authorized"; static NSString* RNPStatusRestricted = @"restricted"; typedef NS_ENUM(NSInteger, RNPType) { RNPTypeUnknown, RNPTypeLocation, RNPTypeCamera, RNPTypeMicrophone, RNPTypePhoto, RNPTypeContacts, RNPTypeEvent, RNPTypeReminder, RNPTypeBluetooth, RNPTypeNotification, RNPTypeBackgroundRefresh }; @interface RCTConvert (RNPStatus) @end
{'content_hash': '40686d2e0ef2ed256be0eb9ac1c5e912', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 57, 'avg_line_length': 23.17391304347826, 'alnum_prop': 0.7504690431519699, 'repo_name': 'designrad/Jotunheimen-tracking', 'id': 'ad1287d3b149d53b8158e1c9e18124964e4753c1', 'size': '721', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'JotunheimenPlaces/node_modules/react-native-permissions/RCTConvert+RNPStatus.h', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '15982'}, {'name': 'CSS', 'bytes': '562808'}, {'name': 'HTML', 'bytes': '740'}, {'name': 'Java', 'bytes': '1544'}, {'name': 'JavaScript', 'bytes': '635445'}, {'name': 'Objective-C', 'bytes': '4444'}, {'name': 'PHP', 'bytes': '37322'}, {'name': 'Python', 'bytes': '1748'}]}
using Orchard.Messaging.Services; namespace Orchard.Email.Services { public interface ISmtpChannel : IMessageChannel { } }
{'content_hash': '9f01e12405422cf3ddb5d954ffc6c754', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 53, 'avg_line_length': 22.833333333333332, 'alnum_prop': 0.7299270072992701, 'repo_name': 'jdages/AndrewsHouse', 'id': '222a218b2b5df62750fc820e48b529e0867fd037', 'size': '139', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/Orchard.Web/Modules/Orchard.Email/Services/ISmtpChannel.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '3324'}, {'name': 'C', 'bytes': '4964'}, {'name': 'C#', 'bytes': '8881940'}, {'name': 'CSS', 'bytes': '870507'}, {'name': 'JavaScript', 'bytes': '5362009'}, {'name': 'Shell', 'bytes': '6131'}, {'name': 'TypeScript', 'bytes': '98654'}, {'name': 'XSLT', 'bytes': '123490'}]}
name: Bug report about: Create a report to help us improve --- :bus: This library has moved to [google-cloud-java/java-network-management]( https://github.com/googleapis/google-cloud-java/tree/main/java-network-management). This repository will be archived in the future. Thanks for stopping by to let us know something could be better! **PLEASE READ**: If you have a support contract with Google, please create an issue in the [support console](https://cloud.google.com/support/) instead of filing on GitHub. This will ensure a timely response. Please run down the following list and make sure you've tried the usual "quick fixes": - Search the issues already opened: https://github.com/googleapis/java-network-management/issues - Check for answers on StackOverflow: http://stackoverflow.com/questions/tagged/google-cloud-platform If you are still having issues, please include as much information as possible: #### Environment details 1. Specify the API at the beginning of the title. For example, "BigQuery: ..."). General, Core, and Other are also allowed as types 2. OS type and version: 3. Java version: 4. version(s): #### Steps to reproduce 1. ? 2. ? #### Code example ```java // example ``` #### Stack trace ``` Any relevant stacktrace here. ``` #### External references such as API reference guides - ? #### Any additional information below Following these steps guarantees the quickest resolution possible. Thanks!
{'content_hash': 'ab5757a10c7308b64878c4eae1b0c727', 'timestamp': '', 'source': 'github', 'line_count': 55, 'max_line_length': 208, 'avg_line_length': 26.509090909090908, 'alnum_prop': 0.7434842249657064, 'repo_name': 'googleapis/java-network-management', 'id': 'ab304499674e803f74b8e11e85b4645c4adaf150', 'size': '1462', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': '.github/ISSUE_TEMPLATE/bug_report.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '801'}, {'name': 'Java', 'bytes': '4308486'}, {'name': 'Python', 'bytes': '787'}, {'name': 'Shell', 'bytes': '20477'}]}
package org.owasp.esapi.reference.validation; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.owasp.esapi.errors.ConfigurationException; import org.owasp.esapi.ESAPI; import org.owasp.esapi.Encoder; import org.owasp.esapi.Logger; import org.owasp.esapi.StringUtilities; import org.owasp.esapi.errors.ValidationException; import org.owasp.validator.html.AntiSamy; import org.owasp.validator.html.CleanResults; import org.owasp.validator.html.Policy; import org.owasp.validator.html.PolicyException; import org.owasp.validator.html.ScanException; /** * A validator performs syntax and possibly semantic validation of a single * piece of data from an untrusted source. * * @author Jeff Williams (jeff.williams .at. aspectsecurity.com) <a * href="http://www.aspectsecurity.com">Aspect Security</a> * @since June 1, 2007 * @see org.owasp.esapi.Validator */ public class HTMLValidationRule extends StringValidationRule { /** OWASP AntiSamy markup verification policy */ private static Policy antiSamyPolicy = null; private static final Logger LOGGER = ESAPI.getLogger( "HTMLValidationRule" ); static { InputStream resourceStream = null; try { resourceStream = ESAPI.securityConfiguration().getResourceStream("antisamy-esapi.xml"); } catch (IOException e) { throw new ConfigurationException("Couldn't find antisamy-esapi.xml", e); } if (resourceStream != null) { try { antiSamyPolicy = Policy.getInstance(resourceStream); } catch (PolicyException e) { throw new ConfigurationException("Couldn't parse antisamy policy", e); } } } public HTMLValidationRule( String typeName ) { super( typeName ); } public HTMLValidationRule( String typeName, Encoder encoder ) { super( typeName, encoder ); } public HTMLValidationRule( String typeName, Encoder encoder, String whitelistPattern ) { super( typeName, encoder, whitelistPattern ); } /** * {@inheritDoc} */ @Override public String getValid( String context, String input ) throws ValidationException { return invokeAntiSamy( context, input ); } /** * {@inheritDoc} */ @Override public String sanitize( String context, String input ) { String safe = ""; try { safe = invokeAntiSamy( context, input ); } catch( ValidationException e ) { // just return safe } return safe; } private String invokeAntiSamy( String context, String input ) throws ValidationException { // CHECKME should this allow empty Strings? " " us IsBlank instead? if ( StringUtilities.isEmpty(input) ) { if (allowNull) { return null; } throw new ValidationException( context + " is required", "AntiSamy validation error: context=" + context + ", input=" + input, context ); } String canonical = super.getValid( context, input ); try { AntiSamy as = new AntiSamy(); CleanResults test = as.scan(canonical, antiSamyPolicy); List<String> errors = test.getErrorMessages(); if ( !errors.isEmpty() ) { LOGGER.info( Logger.SECURITY_FAILURE, "Cleaned up invalid HTML input: " + errors ); } return test.getCleanHTML().trim(); } catch (ScanException e) { throw new ValidationException( context + ": Invalid HTML input", "Invalid HTML input: context=" + context + " error=" + e.getMessage(), e, context ); } catch (PolicyException e) { throw new ValidationException( context + ": Invalid HTML input", "Invalid HTML input does not follow rules in antisamy-esapi.xml: context=" + context + " error=" + e.getMessage(), e, context ); } } }
{'content_hash': '6fd8981191959be9b7b93d34600fa1c9', 'timestamp': '', 'source': 'github', 'line_count': 115, 'max_line_length': 196, 'avg_line_length': 32.608695652173914, 'alnum_prop': 0.6810666666666667, 'repo_name': 'anouza/owasp-esapi-java', 'id': 'e08e2b0f527dde0d7b2a0027c6b9456be69ec85d', 'size': '4367', 'binary': False, 'copies': '34', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/owasp/esapi/reference/validation/HTMLValidationRule.java', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'HTML', 'bytes': '9662'}, {'name': 'Java', 'bytes': '1917721'}, {'name': 'Shell', 'bytes': '21263'}]}
import sys from typing import Any, Callable, Dict, IO, Optional, TypeVar, Union, overload from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse from azure.core.rest import HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from azure.mgmt.core.exceptions import ARMErrorFormat from ... import models as _models from ..._vendor import _convert_request from ...operations._sql_vulnerability_assessment_baselines_operations import build_create_or_update_request if sys.version_info >= (3, 8): from typing import Literal # pylint: disable=no-name-in-module, ungrouped-imports else: from typing_extensions import Literal # type: ignore # pylint: disable=ungrouped-imports T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class SqlVulnerabilityAssessmentBaselinesOperations: """ .. warning:: **DO NOT** instantiate this class directly. Instead, you should access the following operations through :class:`~azure.mgmt.sql.aio.SqlManagementClient`'s :attr:`sql_vulnerability_assessment_baselines` attribute. """ models = _models def __init__(self, *args, **kwargs) -> None: input_args = list(args) self._client = input_args.pop(0) if input_args else kwargs.pop("client") self._config = input_args.pop(0) if input_args else kwargs.pop("config") self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") @overload async def create_or_update( self, resource_group_name: str, server_name: str, vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName], baseline_name: Union[str, _models.BaselineName], parameters: _models.DatabaseSqlVulnerabilityAssessmentRuleBaselineListInput, *, content_type: str = "application/json", **kwargs: Any ) -> _models.DatabaseSqlVulnerabilityAssessmentBaselineSet: """Add a database's vulnerability assessment rule baseline list. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str :param server_name: The name of the server. Required. :type server_name: str :param vulnerability_assessment_name: The name of the vulnerability assessment. "default" Required. :type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName :param baseline_name: "default" Required. :type baseline_name: str or ~azure.mgmt.sql.models.BaselineName :param parameters: The requested rule baseline resource. Required. :type parameters: ~azure.mgmt.sql.models.DatabaseSqlVulnerabilityAssessmentRuleBaselineListInput :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str :keyword system_database_name: The vulnerability assessment system database name. Default value is "master". Note that overriding this default value may result in unsupported behavior. :paramtype system_database_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DatabaseSqlVulnerabilityAssessmentBaselineSet or the result of cls(response) :rtype: ~azure.mgmt.sql.models.DatabaseSqlVulnerabilityAssessmentBaselineSet :raises ~azure.core.exceptions.HttpResponseError: """ @overload async def create_or_update( self, resource_group_name: str, server_name: str, vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName], baseline_name: Union[str, _models.BaselineName], parameters: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.DatabaseSqlVulnerabilityAssessmentBaselineSet: """Add a database's vulnerability assessment rule baseline list. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str :param server_name: The name of the server. Required. :type server_name: str :param vulnerability_assessment_name: The name of the vulnerability assessment. "default" Required. :type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName :param baseline_name: "default" Required. :type baseline_name: str or ~azure.mgmt.sql.models.BaselineName :param parameters: The requested rule baseline resource. Required. :type parameters: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str :keyword system_database_name: The vulnerability assessment system database name. Default value is "master". Note that overriding this default value may result in unsupported behavior. :paramtype system_database_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DatabaseSqlVulnerabilityAssessmentBaselineSet or the result of cls(response) :rtype: ~azure.mgmt.sql.models.DatabaseSqlVulnerabilityAssessmentBaselineSet :raises ~azure.core.exceptions.HttpResponseError: """ @distributed_trace_async async def create_or_update( self, resource_group_name: str, server_name: str, vulnerability_assessment_name: Union[str, _models.VulnerabilityAssessmentName], baseline_name: Union[str, _models.BaselineName], parameters: Union[_models.DatabaseSqlVulnerabilityAssessmentRuleBaselineListInput, IO], **kwargs: Any ) -> _models.DatabaseSqlVulnerabilityAssessmentBaselineSet: """Add a database's vulnerability assessment rule baseline list. :param resource_group_name: The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. Required. :type resource_group_name: str :param server_name: The name of the server. Required. :type server_name: str :param vulnerability_assessment_name: The name of the vulnerability assessment. "default" Required. :type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName :param baseline_name: "default" Required. :type baseline_name: str or ~azure.mgmt.sql.models.BaselineName :param parameters: The requested rule baseline resource. Is either a model type or a IO type. Required. :type parameters: ~azure.mgmt.sql.models.DatabaseSqlVulnerabilityAssessmentRuleBaselineListInput or IO :keyword system_database_name: The vulnerability assessment system database name. Default value is "master". Note that overriding this default value may result in unsupported behavior. :paramtype system_database_name: str :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. Default value is None. :paramtype content_type: str :keyword callable cls: A custom type or function that will be passed the direct response :return: DatabaseSqlVulnerabilityAssessmentBaselineSet or the result of cls(response) :rtype: ~azure.mgmt.sql.models.DatabaseSqlVulnerabilityAssessmentBaselineSet :raises ~azure.core.exceptions.HttpResponseError: """ error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, 304: ResourceNotModifiedError, } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) system_database_name = kwargs.pop( "system_database_name", _params.pop("systemDatabaseName", "master") ) # type: Literal["master"] api_version = kwargs.pop( "api_version", _params.pop("api-version", "2022-02-01-preview") ) # type: Literal["2022-02-01-preview"] content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] cls = kwargs.pop("cls", None) # type: ClsType[_models.DatabaseSqlVulnerabilityAssessmentBaselineSet] content_type = content_type or "application/json" _json = None _content = None if isinstance(parameters, (IO, bytes)): _content = parameters else: _json = self._serialize.body(parameters, "DatabaseSqlVulnerabilityAssessmentRuleBaselineListInput") request = build_create_or_update_request( resource_group_name=resource_group_name, server_name=server_name, vulnerability_assessment_name=vulnerability_assessment_name, baseline_name=baseline_name, subscription_id=self._config.subscription_id, system_database_name=system_database_name, api_version=api_version, content_type=content_type, json=_json, content=_content, template_url=self.create_or_update.metadata["url"], headers=_headers, params=_params, ) request = _convert_request(request) request.url = self._client.format_url(request.url) # type: ignore pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access request, stream=False, **kwargs ) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, error_format=ARMErrorFormat) deserialized = self._deserialize("DatabaseSqlVulnerabilityAssessmentBaselineSet", pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized create_or_update.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/sqlVulnerabilityAssessments/{vulnerabilityAssessmentName}/baselines/{baselineName}"} # type: ignore
{'content_hash': '8e0f304cf3babe67becc33f252a704cc', 'timestamp': '', 'source': 'github', 'line_count': 227, 'max_line_length': 253, 'avg_line_length': 49.72246696035242, 'alnum_prop': 0.6928324621245681, 'repo_name': 'Azure/azure-sdk-for-python', 'id': '549585ee83051acbe09323c2bcaaadfd648de5f1', 'size': '11787', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'sdk/sql/azure-mgmt-sql/azure/mgmt/sql/aio/operations/_sql_vulnerability_assessment_baselines_operations.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1224'}, {'name': 'Bicep', 'bytes': '24196'}, {'name': 'CSS', 'bytes': '6089'}, {'name': 'Dockerfile', 'bytes': '4892'}, {'name': 'HTML', 'bytes': '12058'}, {'name': 'JavaScript', 'bytes': '8137'}, {'name': 'Jinja', 'bytes': '10377'}, {'name': 'Jupyter Notebook', 'bytes': '272022'}, {'name': 'PowerShell', 'bytes': '518535'}, {'name': 'Python', 'bytes': '715484989'}, {'name': 'Shell', 'bytes': '3631'}]}
--TEST-- Test posix_kill() function : usage variations - second parameter type --SKIPIF-- <?php if(!extension_loaded("posix")) print "skip - POSIX extension not loaded"; ?> --FILE-- <?php /* Prototype : proto bool posix_kill(int pid, int sig) * Description: Send a signal to a process (POSIX.1, 3.3.2) * Source code: ext/posix/posix.c * Alias to functions: */ echo "*** Testing posix_kill() : usage variations ***\n"; // Initialise function arguments not being substituted (if any) $pid = -999; //get an unset variable $unset_var = 10; unset ($unset_var); //array of values to iterate over $values = array( // float data 10.5, -10.5, 10.1234567e10, 10.7654321E-10, .5, // array data array(), array(0), array(1), array(1, 2), array('color' => 'red', 'item' => 'pen'), // null data NULL, null, // boolean data true, false, TRUE, FALSE, // empty data "", '', // string data "string", 'string', // undefined data $undefined_var, // unset data $unset_var, // object data new stdclass(), ); // loop through each element of the array for sig foreach($values as $value) { echo "\nArg value $value \n"; var_dump( posix_kill($pid, $value) ); }; echo "Done"; ?> --EXPECTF-- *** Testing posix_kill() : usage variations *** Notice: Undefined variable: undefined_var in %s on line %d Notice: Undefined variable: unset_var in %s on line %d Arg value 10.5 bool(false) Arg value -10.5 bool(false) Arg value 101234567000 bool(false) Arg value 1.07654321E-9 bool(false) Arg value 0.5 bool(false) Notice: Array to string conversion in %sposix_kill_variation2.php on line %d Arg value Array Warning: posix_kill() expects parameter 2 to be long, array given in %s on line %d bool(false) Notice: Array to string conversion in %sposix_kill_variation2.php on line %d Arg value Array Warning: posix_kill() expects parameter 2 to be long, array given in %s on line %d bool(false) Notice: Array to string conversion in %sposix_kill_variation2.php on line %d Arg value Array Warning: posix_kill() expects parameter 2 to be long, array given in %s on line %d bool(false) Notice: Array to string conversion in %sposix_kill_variation2.php on line %d Arg value Array Warning: posix_kill() expects parameter 2 to be long, array given in %s on line %d bool(false) Notice: Array to string conversion in %sposix_kill_variation2.php on line %d Arg value Array Warning: posix_kill() expects parameter 2 to be long, array given in %s on line %d bool(false) Arg value bool(false) Arg value bool(false) Arg value 1 bool(false) Arg value bool(false) Arg value 1 bool(false) Arg value bool(false) Arg value Warning: posix_kill() expects parameter 2 to be long, string given in %s on line %d bool(false) Arg value Warning: posix_kill() expects parameter 2 to be long, string given in %s on line %d bool(false) Arg value string Warning: posix_kill() expects parameter 2 to be long, string given in %s on line %d bool(false) Arg value string Warning: posix_kill() expects parameter 2 to be long, string given in %s on line %d bool(false) Arg value bool(false) Arg value bool(false) Catchable fatal error: Object of class stdClass could not be converted to string in %s on line %d
{'content_hash': '1f739e021d8bfe767c329c91d079c220', 'timestamp': '', 'source': 'github', 'line_count': 179, 'max_line_length': 97, 'avg_line_length': 19.212290502793294, 'alnum_prop': 0.6583309101482989, 'repo_name': 'anindoasaha/php_nginx', 'id': 'c03ead9a4bbc446ccd1b491a894d036ed7c7c8b3', 'size': '3439', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'php-5.5.16/ext/posix/tests/posix_kill_variation2.phpt', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '1050'}, {'name': 'Awk', 'bytes': '15007'}, {'name': 'Bison', 'bytes': '69182'}, {'name': 'C', 'bytes': '53217026'}, {'name': 'C++', 'bytes': '2492956'}, {'name': 'CMake', 'bytes': '28491'}, {'name': 'DTrace', 'bytes': '2194'}, {'name': 'GAP', 'bytes': '4'}, {'name': 'GLSL', 'bytes': '239'}, {'name': 'Groff', 'bytes': '504611'}, {'name': 'HTML', 'bytes': '569653'}, {'name': 'JavaScript', 'bytes': '108172'}, {'name': 'Makefile', 'bytes': '56241'}, {'name': 'Nginx', 'bytes': '3817'}, {'name': 'Objective-C', 'bytes': '7678'}, {'name': 'PHP', 'bytes': '24647829'}, {'name': 'Pascal', 'bytes': '26071'}, {'name': 'Perl', 'bytes': '39455'}, {'name': 'Python', 'bytes': '165'}, {'name': 'Ruby', 'bytes': '357716'}, {'name': 'Shell', 'bytes': '731299'}, {'name': 'VimL', 'bytes': '32089'}, {'name': 'XS', 'bytes': '21306'}, {'name': 'XSLT', 'bytes': '7946'}]}
// 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. #nullable disable using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Symbols { public class DocumentSymbolsTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGetDocumentSymbolsAsync() { var markup = @"{|class:class {|classSelection:A|} { {|method:void {|methodSelection:M|}() { }|} }|}"; using var workspace = CreateTestWorkspace(markup, out var locations); var expected = new LSP.DocumentSymbol[] { CreateDocumentSymbol(LSP.SymbolKind.Class, "A", "A", locations["class"].Single(), locations["classSelection"].Single()) }; CreateDocumentSymbol(LSP.SymbolKind.Method, "M", "M()", locations["method"].Single(), locations["methodSelection"].Single(), expected.First()); var results = await RunGetDocumentSymbolsAsync(workspace.CurrentSolution, true); AssertJsonEquals(expected, results); } [Fact] public async Task TestGetDocumentSymbolsAsync__WithoutHierarchicalSupport() { var markup = @"class {|class:A|} { void {|method:M|}() { } }"; using var workspace = CreateTestWorkspace(markup, out var locations); var expected = new LSP.SymbolInformation[] { CreateSymbolInformation(LSP.SymbolKind.Class, "A", locations["class"].Single()), CreateSymbolInformation(LSP.SymbolKind.Method, "M()", locations["method"].Single(), "A") }; var results = await RunGetDocumentSymbolsAsync(workspace.CurrentSolution, false); AssertJsonEquals(expected, results); } [Fact(Skip = "GetDocumentSymbolsAsync does not yet support locals.")] // TODO - Remove skip & modify once GetDocumentSymbolsAsync is updated to support more than 2 levels. // https://github.com/dotnet/roslyn/projects/45#card-20033869 public async Task TestGetDocumentSymbolsAsync__WithLocals() { var markup = @"class A { void Method() { int i = 1; } }"; using var workspace = CreateTestWorkspace(markup, out var _); var results = await RunGetDocumentSymbolsAsync(workspace.CurrentSolution, false).ConfigureAwait(false); Assert.Equal(3, results.Length); } [Fact] public async Task TestGetDocumentSymbolsAsync__NoSymbols() { using var workspace = CreateTestWorkspace(string.Empty, out var _); var results = await RunGetDocumentSymbolsAsync(workspace.CurrentSolution, true); Assert.Empty(results); } private static async Task<object[]> RunGetDocumentSymbolsAsync(Solution solution, bool hierarchicalSupport) { var document = solution.Projects.First().Documents.First(); var request = new LSP.DocumentSymbolParams { TextDocument = CreateTextDocumentIdentifier(new Uri(document.FilePath)) }; var clientCapabilities = new LSP.ClientCapabilities() { TextDocument = new LSP.TextDocumentClientCapabilities() { DocumentSymbol = new LSP.DocumentSymbolSetting() { HierarchicalDocumentSymbolSupport = hierarchicalSupport } } }; var queue = CreateRequestQueue(solution); return await GetLanguageServer(solution).ExecuteRequestAsync<LSP.DocumentSymbolParams, object[]>(queue, LSP.Methods.TextDocumentDocumentSymbolName, request, clientCapabilities, null, CancellationToken.None); } private static void AssertDocumentSymbolEquals(LSP.DocumentSymbol expected, LSP.DocumentSymbol actual) { Assert.Equal(expected.Kind, actual.Kind); Assert.Equal(expected.Name, actual.Name); Assert.Equal(expected.Range, actual.Range); Assert.Equal(expected.Children.Length, actual.Children.Length); for (var i = 0; i < actual.Children.Length; i++) { AssertDocumentSymbolEquals(expected.Children[i], actual.Children[i]); } } private static LSP.DocumentSymbol CreateDocumentSymbol(LSP.SymbolKind kind, string name, string detail, LSP.Location location, LSP.Location selection, LSP.DocumentSymbol parent = null) { var documentSymbol = new LSP.DocumentSymbol() { Kind = kind, Name = name, Range = location.Range, Children = new LSP.DocumentSymbol[0], Detail = detail, Deprecated = false, SelectionRange = selection.Range }; if (parent != null) { var children = parent.Children.ToList(); children.Add(documentSymbol); parent.Children = children.ToArray(); } return documentSymbol; } } }
{'content_hash': '713bb04b3e3d001b2d00ad958ace663b', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 159, 'avg_line_length': 37.4527027027027, 'alnum_prop': 0.6097780985026159, 'repo_name': 'brettfo/roslyn', 'id': 'a05f516cf2887c4d98d4c2d3d8fbc17c2480e2f4', 'size': '5545', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/Features/LanguageServer/ProtocolUnitTests/Symbols/DocumentSymbolsTests.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': '1C Enterprise', 'bytes': '289100'}, {'name': 'Batchfile', 'bytes': '8643'}, {'name': 'C#', 'bytes': '110983902'}, {'name': 'C++', 'bytes': '5392'}, {'name': 'Dockerfile', 'bytes': '1905'}, {'name': 'F#', 'bytes': '508'}, {'name': 'PowerShell', 'bytes': '105474'}, {'name': 'Shell', 'bytes': '22163'}, {'name': 'Smalltalk', 'bytes': '622'}, {'name': 'Visual Basic', 'bytes': '68586535'}]}
package org.kasource.validation.email.impl; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.kasource.validation.email.Email; public class ArrayEmailValidator extends AbstractEmailValidator implements ConstraintValidator<Email, Object[]> { @Override public void initialize(Email annotation) { super.initialize(annotation); } @Override public boolean isValid(Object[] value, ConstraintValidatorContext context) { return isValidArray(value); } }
{'content_hash': '1752992b1ad4dccdf1b456ef28828aa6', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 113, 'avg_line_length': 27.95, 'alnum_prop': 0.7567084078711985, 'repo_name': 'wigforss/Ka-Validation', 'id': '9336517c41652009a0f1eadcfe641ef1efd838a3', 'size': '559', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/org/kasource/validation/email/impl/ArrayEmailValidator.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '416976'}]}
/* * GET home page. */ module.exports = { index: function(req,res){ res.render('index.html'); }, chat : function(req,res){ res.render('chat.html'); } }
{'content_hash': '34ad30157296a8f47df7b853dc6a4cc9', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 33, 'avg_line_length': 15.5, 'alnum_prop': 0.5161290322580645, 'repo_name': 'carlosbu/ibm-100-anos-bot', 'id': 'd804bcd641adade75918ba32c6656ec1405ce609', 'size': '186', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'routes/index.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '6633'}, {'name': 'HTML', 'bytes': '1645'}, {'name': 'JavaScript', 'bytes': '21076'}]}
<?php namespace Symfony\Component\Routing; use Symfony\Component\Config\Loader\LoaderInterface; use Symfony\Component\Config\ConfigCacheInterface; use Symfony\Component\Config\ConfigCacheFactoryInterface; use Symfony\Component\Config\ConfigCacheFactory; use Psr\Log\LoggerInterface; use Symfony\Component\Routing\Generator\ConfigurableRequirementsInterface; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Symfony\Component\Routing\Generator\Dumper\GeneratorDumperInterface; use Symfony\Component\Routing\Matcher\RequestMatcherInterface; use Symfony\Component\Routing\Matcher\UrlMatcherInterface; use Symfony\Component\Routing\Matcher\Dumper\MatcherDumperInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\ExpressionLanguage\ExpressionFunctionProviderInterface; /** * The Router class is an example of the integration of all pieces of the * routing system for easier use. * * @author Fabien Potencier <[email protected]> */ class Router implements RouterInterface, RequestMatcherInterface { /** * @var UrlMatcherInterface|null */ protected $matcher; /** * @var UrlGeneratorInterface|null */ protected $generator; /** * @var RequestContext */ protected $context; /** * @var LoaderInterface */ protected $loader; /** * @var RouteCollection|null */ protected $collection; /** * @var mixed */ protected $resource; /** * @var array */ protected $options = array(); /** * @var LoggerInterface|null */ protected $logger; /** * @var ConfigCacheFactoryInterface|null */ private $configCacheFactory; /** * @var ExpressionFunctionProviderInterface[] */ private $expressionLanguageProviders = array(); /** * @param LoaderInterface $loader A LoaderInterface instance * @param mixed $resource The main resource to load * @param array $options An array of options * @param RequestContext $context The context * @param LoggerInterface $logger A logger instance */ public function __construct(LoaderInterface $loader, $resource, array $options = array(), RequestContext $context = null, LoggerInterface $logger = null) { $this->loader = $loader; $this->resource = $resource; $this->logger = $logger; $this->context = $context ?: new RequestContext(); $this->setOptions($options); } /** * Sets options. * * Available options: * * * cache_dir: The cache directory (or null to disable caching) * * debug: Whether to enable debugging or not (false by default) * * generator_class: The name of a UrlGeneratorInterface implementation * * generator_base_class: The base class for the dumped generator class * * generator_cache_class: The class name for the dumped generator class * * generator_dumper_class: The name of a GeneratorDumperInterface implementation * * matcher_class: The name of a UrlMatcherInterface implementation * * matcher_base_class: The base class for the dumped matcher class * * matcher_dumper_class: The class name for the dumped matcher class * * matcher_cache_class: The name of a MatcherDumperInterface implementation * * resource_type: Type hint for the main resource (optional) * * strict_requirements: Configure strict requirement checking for generators * implementing ConfigurableRequirementsInterface (default is true) * * @param array $options An array of options * * @throws \InvalidArgumentException When unsupported option is provided */ public function setOptions(array $options) { $this->options = array( 'cache_dir' => null, 'debug' => false, 'generator_class' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator', 'generator_base_class' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator', 'generator_dumper_class' => 'Symfony\\Component\\Routing\\Generator\\Dumper\\PhpGeneratorDumper', 'generator_cache_class' => 'ProjectUrlGenerator', 'matcher_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher', 'matcher_base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher', 'matcher_dumper_class' => 'Symfony\\Component\\Routing\\Matcher\\Dumper\\PhpMatcherDumper', 'matcher_cache_class' => 'ProjectUrlMatcher', 'resource_type' => null, 'strict_requirements' => true, ); // check option names and live merge, if errors are encountered Exception will be thrown $invalid = array(); foreach ($options as $key => $value) { if (array_key_exists($key, $this->options)) { $this->options[$key] = $value; } else { $invalid[] = $key; } } if ($invalid) { throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".', implode('", "', $invalid))); } } /** * Sets an option. * * @param string $key The key * @param mixed $value The value * * @throws \InvalidArgumentException */ public function setOption($key, $value) { if (!array_key_exists($key, $this->options)) { throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key)); } $this->options[$key] = $value; } /** * Gets an option value. * * @param string $key The key * * @return mixed The value * * @throws \InvalidArgumentException */ public function getOption($key) { if (!array_key_exists($key, $this->options)) { throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key)); } return $this->options[$key]; } /** * {@inheritdoc} */ public function getRouteCollection() { if (null === $this->collection) { $this->collection = $this->loader->load($this->resource, $this->options['resource_type']); } return $this->collection; } /** * {@inheritdoc} */ public function setContext(RequestContext $context) { $this->context = $context; if (null !== $this->matcher) { $this->getMatcher()->setContext($context); } if (null !== $this->generator) { $this->getGenerator()->setContext($context); } } /** * {@inheritdoc} */ public function getContext() { return $this->context; } /** * Sets the ConfigCache factory to use. * * @param ConfigCacheFactoryInterface $configCacheFactory The factory to use */ public function setConfigCacheFactory(ConfigCacheFactoryInterface $configCacheFactory) { $this->configCacheFactory = $configCacheFactory; } /** * {@inheritdoc} */ public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH) { return $this->getGenerator()->generate($name, $parameters, $referenceType); } /** * {@inheritdoc} */ public function match($pathinfo) { return $this->getMatcher()->match($pathinfo); } /** * {@inheritdoc} */ public function matchRequest(Request $request) { $matcher = $this->getMatcher(); if (!$matcher instanceof RequestMatcherInterface) { // fallback to the default UrlMatcherInterface return $matcher->match($request->getPathInfo()); } return $matcher->matchRequest($request); } /** * Gets the UrlMatcher instance associated with this Router. * * @return UrlMatcherInterface A UrlMatcherInterface instance */ public function getMatcher() { if (null !== $this->matcher) { return $this->matcher; } if (null === $this->options['cache_dir'] || null === $this->options['matcher_cache_class']) { $this->matcher = new $this->options['matcher_class']($this->getRouteCollection(), $this->context); if (method_exists($this->matcher, 'addExpressionLanguageProvider')) { foreach ($this->expressionLanguageProviders as $provider) { $this->matcher->addExpressionLanguageProvider($provider); } } return $this->matcher; } $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$this->options['matcher_cache_class'].'.php', function (ConfigCacheInterface $cache) { $dumper = $this->getMatcherDumperInstance(); if (method_exists($dumper, 'addExpressionLanguageProvider')) { foreach ($this->expressionLanguageProviders as $provider) { $dumper->addExpressionLanguageProvider($provider); } } $options = array( 'class' => $this->options['matcher_cache_class'], 'base_class' => $this->options['matcher_base_class'], ); $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources()); } ); require_once $cache->getPath(); return $this->matcher = new $this->options['matcher_cache_class']($this->context); } /** * Gets the UrlGenerator instance associated with this Router. * * @return UrlGeneratorInterface A UrlGeneratorInterface instance */ public function getGenerator() { if (null !== $this->generator) { return $this->generator; } if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) { $this->generator = new $this->options['generator_class']($this->getRouteCollection(), $this->context, $this->logger); } else { $cache = $this->getConfigCacheFactory()->cache($this->options['cache_dir'].'/'.$this->options['generator_cache_class'].'.php', function (ConfigCacheInterface $cache) { $dumper = $this->getGeneratorDumperInstance(); $options = array( 'class' => $this->options['generator_cache_class'], 'base_class' => $this->options['generator_base_class'], ); $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources()); } ); require_once $cache->getPath(); $this->generator = new $this->options['generator_cache_class']($this->context, $this->logger); } if ($this->generator instanceof ConfigurableRequirementsInterface) { $this->generator->setStrictRequirements($this->options['strict_requirements']); } return $this->generator; } public function addExpressionLanguageProvider(ExpressionFunctionProviderInterface $provider) { $this->expressionLanguageProviders[] = $provider; } /** * @return GeneratorDumperInterface */ protected function getGeneratorDumperInstance() { return new $this->options['generator_dumper_class']($this->getRouteCollection()); } /** * @return MatcherDumperInterface */ protected function getMatcherDumperInstance() { return new $this->options['matcher_dumper_class']($this->getRouteCollection()); } /** * Provides the ConfigCache factory implementation, falling back to a * default implementation if necessary. * * @return ConfigCacheFactoryInterface $configCacheFactory */ private function getConfigCacheFactory() { if (null === $this->configCacheFactory) { $this->configCacheFactory = new ConfigCacheFactory($this->options['debug']); } return $this->configCacheFactory; } }
{'content_hash': '2bdcca57b47070543694cef641a428ec', 'timestamp': '', 'source': 'github', 'line_count': 379, 'max_line_length': 157, 'avg_line_length': 32.68073878627968, 'alnum_prop': 0.5984175682221864, 'repo_name': 'Amo/symfony', 'id': 'e93cd65ca2b840a2f8a5f42532d8dcbb67c1befe', 'size': '12615', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'src/Symfony/Component/Routing/Router.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '8656'}, {'name': 'HTML', 'bytes': '329037'}, {'name': 'JavaScript', 'bytes': '345'}, {'name': 'M4', 'bytes': '2250'}, {'name': 'PHP', 'bytes': '14548649'}, {'name': 'Shell', 'bytes': '375'}]}
package com.polydes.paint.app.pages; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JSplitPane; import com.polydes.common.comp.MiniSplitPane; import com.polydes.common.nodes.DefaultBranch; import com.polydes.common.nodes.DefaultLeaf; import com.polydes.common.nodes.HierarchyModel; import com.polydes.common.nodes.NodeSelection; import com.polydes.common.nodes.NodeSelectionEvent; import com.polydes.common.nodes.NodeSelectionListener; import com.polydes.common.ui.darktree.DarkTree; public class BasicPage extends JPanel implements NodeSelectionListener<DefaultLeaf,DefaultBranch> { protected Boolean listEditEnabled; protected MiniSplitPane splitPane; protected HierarchyModel<DefaultLeaf,DefaultBranch> folderModel; protected DarkTree<DefaultLeaf,DefaultBranch> tree; protected NodeSelection<DefaultLeaf,DefaultBranch> selection; protected BasicPage() { super(new BorderLayout()); } protected BasicPage(final DefaultBranch rootFolder) { super(new BorderLayout()); folderModel = new HierarchyModel<DefaultLeaf,DefaultBranch>(rootFolder, DefaultLeaf.class, DefaultBranch.class); tree = new DarkTree<DefaultLeaf,DefaultBranch>(folderModel); splitPane = new MiniSplitPane(); splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT); splitPane.setLeftComponent(tree); add(splitPane); splitPane.setDividerLocation(DarkTree.DEF_WIDTH); folderModel.getSelection().addSelectionListener(this); tree.forceRerender(); } public void setListEditEnabled(boolean value) { if(listEditEnabled == null || listEditEnabled != value) { listEditEnabled = value; if(listEditEnabled) { tree.setListEditEnabled(true); } else { tree.setListEditEnabled(false); } } } @Override public void selectionChanged(NodeSelectionEvent<DefaultLeaf, DefaultBranch> e) { } class HorizontalDivider extends JComponent { public int height; public Color color; public HorizontalDivider(int height) { color = new Color(0x4F4F4F); this.height = height; } @Override public Dimension getMinimumSize() { return new Dimension(1, height); } @Override public Dimension getPreferredSize() { return new Dimension(1, height); } @Override public Dimension getMaximumSize() { return new Dimension(Short.MAX_VALUE, height); } @Override public void paint(Graphics g) { g.setColor(color); g.fillRect(0, 0, getWidth(), getHeight()); } } }
{'content_hash': '4eef1e849005363e0bbba0abf4fae120', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 114, 'avg_line_length': 22.86842105263158, 'alnum_prop': 0.7537399309551208, 'repo_name': 'justin-espedal/polydes', 'id': '56ed19209c3e0f7a898131a10efdaed9f5b27edf', 'size': '2607', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Paint Extension/src/com/polydes/paint/app/pages/BasicPage.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ANTLR', 'bytes': '3795'}, {'name': 'Haxe', 'bytes': '187386'}, {'name': 'Java', 'bytes': '1247351'}]}
"""Keras index lookup preprocessing layer.""" # pylint: disable=g-classes-have-attributes from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import json import operator import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.framework import tensor_shape from tensorflow.python.framework import tensor_spec from tensorflow.python.keras.engine import base_preprocessing_layer from tensorflow.python.keras.layers.preprocessing import category_encoding from tensorflow.python.keras.layers.preprocessing import table_utils from tensorflow.python.keras.utils import layer_utils from tensorflow.python.ops import lookup_ops from tensorflow.python.ops import math_ops from tensorflow.python.util import compat INT = "int" BINARY = "binary" COUNT = "count" # The string tokens in the extracted vocabulary _VOCAB_NAME = "vocab" # The string tokens in the full vocabulary _ACCUMULATOR_VOCAB_NAME = "vocab" # The total counts of each token in the vocabulary _ACCUMULATOR_COUNTS_NAME = "counts" class IndexLookup(base_preprocessing_layer.CombinerPreprocessingLayer): """Maps values from a vocabulary to integer indices. This layer translates a set of arbitrary hashables into an integer output via a table-based lookup, with optional out-of-vocabulary handling. This is the basis layer for both IntegerLookup and StringLookup; it holds the common logic but is not intended to be exported as part of the Keras API. If desired, the user can call this layer's `adapt()` method on a data set, which will analyze the data set, determine the frequency of individual hashable values, and create a vocabulary from them. This vocabulary can have unlimited size or be capped, depending on the configuration options for this layer; if there are more unique values in the input than the maximum vocabulary size, the most frequent terms will be used to create the vocabulary. Arguments: max_tokens: The maximum size of the vocabulary for this layer. If None, there is no cap on the size of the vocabulary. Note that this vocabulary includes the OOV and mask tokens, so the effective number of tokens is (max_tokens - num_oov_indices - (1 if mask_token else 0)) num_oov_indices: The number of out-of-vocabulary tokens to use. If this value is more than 1, OOV inputs are hashed to determine their OOV value; if this value is 0, passing an OOV input will result in a '-1' being returned for that value in the output tensor. (Note that, because the value is -1 and not 0, this will allow you to effectively drop OOV values from categorical encodings.) mask_token: A token that represents masked values, and which is mapped to index 0. If set to None, no mask term will be added and the OOV tokens, if any, will be indexed from (0...num_oov_indices) instead of (1...num_oov_indices+1). oov_token: The token representing an out-of-vocabulary value. This token is only used when performing an inverse lookup. vocabulary: An optional list of vocabulary terms. If the list contains the same token multiple times, an error will be thrown. invert: If true, this layer will map indices to vocabulary items instead of mapping vocabulary items to indices. output_mode: Specification for the output of the layer. Only applicable when `invert` is False. Defaults to "int". Values can be "int", "binary", or "count", configuring the layer as follows: "int": Return the raw integer indices of the input values. "binary": Outputs a single int array per batch, of either vocab_size or max_tokens size, containing 1s in all elements where the token mapped to that index exists at least once in the batch item. "count": Like "binary", but the int array contains a count of the number of times the token at that index appeared in the batch item. sparse: Boolean. Only applicable to "binary" and "count" output modes. If true, returns a `SparseTensor` instead of a dense `Tensor`. Defaults to `False`. """ def __init__(self, max_tokens, num_oov_indices, mask_token, oov_token, vocabulary=None, invert=False, output_mode=INT, sparse=False, **kwargs): # If max_tokens is set, the value must be greater than 1 - otherwise we # are creating a 0-element vocab, which doesn't make sense. if max_tokens is not None and max_tokens <= 1: raise ValueError("If set, max_tokens must be greater than 1. " "You passed %s" % (max_tokens,)) if num_oov_indices < 0: raise ValueError("`num_oov_indices` must be greater than 0. You passed " "%s" % (num_oov_indices,)) if invert and num_oov_indices != 1: raise ValueError("`num_oov_tokens` must be 1 when `invert` is True.") # 'output_mode' must be one of (INT, BINARY, COUNT) layer_utils.validate_string_arg( output_mode, allowable_strings=(INT, BINARY, COUNT), layer_name=self.__class__.__name__, arg_name="output_mode") self.invert = invert self.max_tokens = max_tokens self.num_oov_indices = num_oov_indices self.oov_token = oov_token self.mask_token = mask_token self.output_mode = output_mode self.sparse = sparse # If there is only one OOV bucket, we can determine the OOV value (either 0 # or 1 depending on whether 0 is reserved) and set that as the default # value of the index_lookup table. If we hav multiple OOV values, we need to # do a further hashing step; to make this easier, we set the OOV value to # -1. (This lets us do a vectorized add and cast to boolean to determine # locations where we need to do extra hashing.) if self.num_oov_indices == 1: self._oov_value = 0 if mask_token is None else 1 else: self._oov_value = -1 if max_tokens is not None: num_mask_tokens = (0 if mask_token is None else 1) vocab_size = max_tokens - (num_oov_indices + num_mask_tokens) else: vocab_size = None super(IndexLookup, self).__init__( combiner=_IndexLookupCombiner(vocab_size, self.mask_token), **kwargs) self._output_dtype = dtypes.int64 # We need to save the key dtype so that we know if we're expecting int64 # keys. If we are, we will cast int32 inputs to int64 as well. if invert: self._key_dtype = self._output_dtype value_dtype = self.dtype oov_value = self.oov_token else: self._key_dtype = self.dtype value_dtype = self._output_dtype oov_value = self._oov_value self._table = lookup_ops.MutableHashTable( key_dtype=self._key_dtype, value_dtype=value_dtype, default_value=oov_value, name=(self._name + "_index_table")) tracked_table = self._add_trackable(self._table, trainable=False) # This is a workaround for summary() on this layer. Because the table is # not mutable during training, the effective number of parameters (and so # the weight shape) is 0; we add this as an attr so that the parameter # counting code in the Model object doesn't throw an attribute error. tracked_table.shape = tensor_shape.TensorShape((0,)) if self.num_oov_indices <= 1: oov_indices = None else: oov_start = 1 if mask_token is not None else 0 oov_end = oov_start + num_oov_indices oov_indices = list(range(oov_start, oov_end)) self._table_handler = table_utils.TableHandler( table=self._table, oov_tokens=oov_indices, use_v1_apis=self._use_v1_apis()) if vocabulary is not None: self.set_vocabulary(vocabulary) def compute_output_shape(self, input_shape): return input_shape def compute_output_signature(self, input_spec): output_shape = self.compute_output_shape(input_spec.shape.as_list()) output_dtype = self.dtype if self.invert else self._output_dtype return tensor_spec.TensorSpec(shape=output_shape, dtype=output_dtype) def adapt(self, data, reset_state=True): """Fits the state of the preprocessing layer to the dataset. Overrides the default adapt method to apply relevant preprocessing to the inputs before passing to the combiner. Arguments: data: The data to train on. It can be passed either as a tf.data Dataset, or as a numpy array. reset_state: Optional argument specifying whether to clear the state of the layer at the start of the call to `adapt`. This must be True for this layer, which does not support repeated calls to `adapt`. """ if not reset_state: raise ValueError("IndexLookup does not support streaming adapts.") super(IndexLookup, self).adapt(data, reset_state) self.max_tokens = int(self._table_handler.vocab_size()) def get_vocabulary(self): if self._table_handler.vocab_size() == 0: return [] keys, values = self._table_handler.data() # This is required because the MutableHashTable doesn't preserve insertion # order, but we rely on the order of the array to assign indices. if self.invert: # If we are inverting, the vocabulary is in the values instead of keys. return [x for _, x in sorted(zip(keys, values))] else: return [x for _, x in sorted(zip(values, keys))] def vocab_size(self): return int(self._table_handler.vocab_size()) def get_config(self): config = { "invert": self.invert, "max_tokens": self.max_tokens, "num_oov_indices": self.num_oov_indices, "oov_token": self.oov_token, "mask_token": self.mask_token, } base_config = super(IndexLookup, self).get_config() return dict(list(base_config.items()) + list(config.items())) def count_params(self): # This method counts the number of scalars in the weights of this layer. # Since this layer doesn't have any /actual/ weights (in that there's # nothing in this layer that can be trained - we only use the weight # abstraction for ease of saving!) we return 0. return 0 def _set_forward_vocabulary(self, vocab): """Sets vocabulary data for this layer when inverse is False.""" table_utils.validate_vocabulary_is_unique(vocab) should_have_mask = self.mask_token is not None has_mask = vocab[0] == self.mask_token oov_start = 1 if should_have_mask else 0 should_have_oov = (self.num_oov_indices > 0) and not self.invert if should_have_oov: oov_end = oov_start + self.num_oov_indices expected_oov = [self.oov_token] * self.num_oov_indices has_oov = vocab[oov_start:oov_end] == expected_oov # If we get a numpy array, then has_oov may end up being a numpy array # instead of a bool. Fix this by collapsing the variable if it's not bool. if not isinstance(has_oov, bool): has_oov = any(has_oov) else: has_oov = False if all([should_have_mask, has_mask, should_have_oov]) and not has_oov: raise ValueError("Invalid vocabulary format. The layer was created with " "`mask_token=%s` and `oov_token=%s`. These tokens should" " be included in the provided vocabulary. " "The passed vocabulary has the correct mask token `%s` " "at index 0, but does not have the OOV token `%s` in " "indices [%s:%s]. Instead, we found `%s`. Was this " "vocabulary generated by a layer with incompatible " "settings?" % (self.mask_token, self.oov_token, self.mask_token, self.oov_token, oov_start, oov_end, vocab[oov_start:oov_end])) if all([should_have_oov, has_oov, should_have_mask]) and not has_mask: raise ValueError( "Invalid vocabulary format. The layer was created with " "`mask_token=%s` and `oov_token=%s`. These tokens should " "be included in the provided vocabulary. " "The passed vocabulary has the correct OOV token `%s` at " "indices [%s:%s], but does not have the mask token `%s` in " "index 0. Instead, we found `%s`. Was this vocabulary " "generated by a layer with incompatible settings?" % (self.mask_token, self.oov_token, self.oov_token, oov_start, oov_end, self.mask_token, vocab[0])) insert_special_tokens = not has_oov and not has_mask special_tokens = [] if self.mask_token is None else [self.mask_token] special_tokens.extend([self.oov_token] * self.num_oov_indices) num_special_tokens = len(special_tokens) tokens = vocab if insert_special_tokens else vocab[num_special_tokens:] if self.mask_token in tokens: raise ValueError("Reserved mask token %s was found in the passed " "vocabulary at index %s. Please either remove the " "reserved token from the vocabulary or change the " "mask token for this layer." % (self.mask_token, tokens.index(self.mask_token))) if self.oov_token in tokens: raise ValueError("Reserved OOV token %s was found in the passed " "vocabulary at index %s. Please either remove the " "reserved token from the vocabulary or change the " "OOV token for this layer." % (self.oov_token, tokens.index(self.oov_token))) if insert_special_tokens: total_vocab_size = len(vocab) + num_special_tokens else: total_vocab_size = len(vocab) if self.max_tokens is not None and total_vocab_size > self.max_tokens: raise ValueError( "Attempted to set a vocabulary larger than the maximum vocab size. " "Passed vocab size is %s, max vocab size is %s." % (total_vocab_size, self.max_tokens)) start_index = num_special_tokens values = np.arange(start_index, len(vocab) + start_index, dtype=np.int64) self._table_handler.clear() self._table_handler.insert(vocab, values) if insert_special_tokens and num_special_tokens > 0: special_token_values = np.arange(num_special_tokens, dtype=np.int64) self._table_handler.insert(special_tokens, special_token_values) return total_vocab_size def _set_inverse_vocabulary(self, vocab): """Sets vocabulary data for this layer when inverse is True.""" table_utils.validate_vocabulary_is_unique(vocab) should_have_mask = self.mask_token is not None has_mask = vocab[0] == self.mask_token insert_special_tokens = should_have_mask and not has_mask special_tokens = [] if self.mask_token is None else [self.mask_token] num_special_tokens = len(special_tokens) tokens = vocab if insert_special_tokens else vocab[num_special_tokens:] if self.mask_token in tokens: raise ValueError("Reserved mask token %s was found in the passed " "vocabulary at index %s. Please either remove the " "reserved token from the vocabulary or change the " "mask token for this layer." % (self.mask_token, tokens.index(self.mask_token))) if insert_special_tokens: total_vocab_size = len(vocab) + num_special_tokens else: total_vocab_size = len(vocab) if self.max_tokens is not None and total_vocab_size > self.max_tokens: raise ValueError( "Attempted to set a vocabulary larger than the maximum vocab size. " "Passed vocab size is %s, max vocab size is %s." % (total_vocab_size, self.max_tokens)) start_index = num_special_tokens if insert_special_tokens else 0 values = np.arange(start_index, len(vocab) + start_index, dtype=np.int64) self._table_handler.clear() self._table_handler.insert(values, vocab) if insert_special_tokens and num_special_tokens > 0: special_token_values = np.arange(num_special_tokens, dtype=np.int64) self._table_handler.insert(special_token_values, special_tokens) return total_vocab_size def set_vocabulary(self, vocab): """Sets vocabulary data for this layer. This method sets the vocabulary for this layer directly, instead of analyzing a dataset through 'adapt'. It should be used whenever the vocab information is already known. If vocabulary data is already present in the layer, this method will either replace it Arguments: vocab: An array of hashable tokens. Raises: ValueError: If there are too many inputs, the inputs do not match, or input data is missing. """ if self.invert: vocab_size = self._set_inverse_vocabulary(vocab) else: vocab_size = self._set_forward_vocabulary(vocab) self.max_tokens = vocab_size def _set_state_variables(self, updates): if not self.built: raise RuntimeError("_set_state_variables() must be called after build().") self.set_vocabulary(updates[_VOCAB_NAME]) def call(self, inputs): if not self.max_tokens: raise ValueError("You must set the layer's vocabulary before calling it. " "Either pass a `vocabulary` argument to the layer, or " "call `layer.adapt(dataset)` with some sample data.") if self._key_dtype == dtypes.int64 and inputs.dtype == dtypes.int32: inputs = math_ops.cast(inputs, dtypes.int64) lookup_result = self._table_handler.lookup(inputs) if self.output_mode == INT: return lookup_result binary_output = (self.output_mode == BINARY) if self.sparse: return category_encoding.sparse_bincount( lookup_result, self.max_tokens, binary_output) else: return category_encoding.dense_bincount( lookup_result, self.max_tokens, binary_output) def _use_v1_apis(self): return False class _IndexLookupAccumulator( collections.namedtuple("Accumulator", ["count_dict"])): pass class _IndexLookupCombiner(base_preprocessing_layer.Combiner): """Combiner for the IndexLookup preprocessing layer. This class encapsulates the logic for computing a vocabulary based on the frequency of each token. Attributes: vocab_size: (Optional) If set, only the top `vocab_size` tokens (based on frequency across the dataset) are retained in the vocabulary. If None, or set to a value greater than the total number of distinct tokens in the dataset, all tokens are retained. """ def __init__(self, vocab_size=None, mask_value=None): self._vocab_size = vocab_size self._mask_value = mask_value def compute(self, values, accumulator=None): """Compute a step in this computation, returning a new accumulator.""" values = base_preprocessing_layer.convert_to_list( values, sparse_default_value=self._mask_value) if accumulator is None: accumulator = self._create_accumulator() # TODO(momernick): Benchmark improvements to this algorithm. if isinstance(values, (str, bytes, np.int64)): accumulator.count_dict[values] += 1 else: for document in values: if not isinstance(document, list): accumulator.count_dict[document] += 1 else: for token in document: accumulator.count_dict[token] += 1 return accumulator def merge(self, accumulators): """Merge several accumulators to a single accumulator.""" if not accumulators: return accumulators base_accumulator = accumulators[0] for accumulator in accumulators[1:]: for token, value in accumulator.count_dict.items(): base_accumulator.count_dict[token] += value return base_accumulator def extract(self, accumulator): """Convert an accumulator into a dict of output values. Args: accumulator: An accumulator aggregating over the full dataset. Returns: A dict of: "vocab": A list of the retained items in the vocabulary. """ vocab_counts = accumulator.count_dict if self._mask_value in vocab_counts: del vocab_counts[self._mask_value] sorted_counts = sorted( vocab_counts.items(), key=operator.itemgetter(1, 0), reverse=True) vocab_data = ( sorted_counts[:self._vocab_size] if self._vocab_size else sorted_counts) vocab = [data[0] for data in vocab_data] return {_VOCAB_NAME: vocab} def restore(self, output): """Create an accumulator based on 'output'.""" raise NotImplementedError( "IndexLookup does not restore or support streaming updates.") def serialize(self, accumulator): """Serialize an accumulator for a remote call.""" output_dict = {} output_dict["vocab"] = list(accumulator.count_dict.keys()) output_dict["vocab_counts"] = list(accumulator.count_dict.values()) return compat.as_bytes(json.dumps(output_dict)) def deserialize(self, encoded_accumulator): """Deserialize an accumulator received from 'serialize()'.""" accumulator_dict = json.loads(compat.as_text(encoded_accumulator)) accumulator = self._create_accumulator() count_dict = dict( zip(accumulator_dict["vocab"], accumulator_dict["vocab_counts"])) accumulator.count_dict.update(count_dict) return accumulator def _create_accumulator(self): """Accumulate a sorted array of vocab tokens and corresponding counts.""" count_dict = collections.defaultdict(int) return _IndexLookupAccumulator(count_dict)
{'content_hash': 'a19275959788a75fe8196cf4b99b4714', 'timestamp': '', 'source': 'github', 'line_count': 525, 'max_line_length': 80, 'avg_line_length': 41.40190476190476, 'alnum_prop': 0.6676481413323518, 'repo_name': 'freedomtan/tensorflow', 'id': 'db358a1400e42fb1d993e00ec3f3026213990265', 'size': '22425', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'tensorflow/python/keras/layers/preprocessing/index_lookup.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '32479'}, {'name': 'Batchfile', 'bytes': '38366'}, {'name': 'C', 'bytes': '1035837'}, {'name': 'C#', 'bytes': '13395'}, {'name': 'C++', 'bytes': '99324075'}, {'name': 'CMake', 'bytes': '107781'}, {'name': 'Dockerfile', 'bytes': '283435'}, {'name': 'Go', 'bytes': '2013128'}, {'name': 'HTML', 'bytes': '4686483'}, {'name': 'Java', 'bytes': '928595'}, {'name': 'Jupyter Notebook', 'bytes': '981916'}, {'name': 'LLVM', 'bytes': '6536'}, {'name': 'MLIR', 'bytes': '4489624'}, {'name': 'Makefile', 'bytes': '97500'}, {'name': 'NASL', 'bytes': '8048'}, {'name': 'Objective-C', 'bytes': '141623'}, {'name': 'Objective-C++', 'bytes': '360423'}, {'name': 'PHP', 'bytes': '20570'}, {'name': 'Pawn', 'bytes': '32277'}, {'name': 'Perl', 'bytes': '7536'}, {'name': 'Python', 'bytes': '42762396'}, {'name': 'RobotFramework', 'bytes': '2661'}, {'name': 'Roff', 'bytes': '2515'}, {'name': 'Ruby', 'bytes': '6723'}, {'name': 'Shell', 'bytes': '647623'}, {'name': 'Smarty', 'bytes': '52687'}, {'name': 'Starlark', 'bytes': '4632847'}, {'name': 'Swift', 'bytes': '56924'}, {'name': 'Vim Snippet', 'bytes': '58'}]}
local shell = require("shell") local args = shell.parse(...) if #args == 0 then io.write("Usage: cd <dirname>") else local result, reason = shell.setWorkingDirectory(shell.resolve(args[1])) if not result then io.stderr:write(reason) end end
{'content_hash': '1a4c0ec424ea83258d69d04dd6095a8f', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 74, 'avg_line_length': 23.09090909090909, 'alnum_prop': 0.6889763779527559, 'repo_name': 'vonflynee/opencomputersserver', 'id': '6080c1b06782267841dd21bbfdd9a152e517d7c6', 'size': '254', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'world/opencomputers/689b9f29-1d36-4106-bf0e-c06a2ebfb1ef/bin/cd.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Groff', 'bytes': '1568'}, {'name': 'Lua', 'bytes': '3539063'}, {'name': 'Shell', 'bytes': '5733'}]}
#ifndef CONSTANTS_H #define CONSTANTS_H #include "data_types.h" /* * * Cipher characteristics: * BLOCK_SIZE - the cipher block size in bytes * KEY_SIZE - the cipher key size in bytes * ROUND_KEY_SIZE - the cipher round keys size in bytes * NUMBER_OF_ROUNDS - the cipher number of rounds * */ #define BLOCK_SIZE 8 #define KEY_SIZE 16 #define ROUND_KEYS_SIZE 24 #define NUMBER_OF_ROUNDS 12 /* * * Cipher constants * */ extern SBOX_BYTE S0[16]; extern INVERSE_SBOX_BYTE S1[16]; extern ROUND_CONSTANT_BYTE RC[96]; #endif /* CONSTANTS_H */
{'content_hash': 'f8573b6fd3089036f114ef6870264208', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 55, 'avg_line_length': 16.0, 'alnum_prop': 0.6892857142857143, 'repo_name': 'GaloisInc/hacrypto', 'id': '74d11ea13a3044858555f97fee2771b6cff1add9', 'size': '1517', 'binary': False, 'copies': '24', 'ref': 'refs/heads/master', 'path': 'src/C/FELICS/block_ciphers/source/ciphers/PRINCE_64_128_v13/source/constants.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'AGS Script', 'bytes': '62991'}, {'name': 'Ada', 'bytes': '443'}, {'name': 'AppleScript', 'bytes': '4518'}, {'name': 'Assembly', 'bytes': '25398957'}, {'name': 'Awk', 'bytes': '36188'}, {'name': 'Batchfile', 'bytes': '530568'}, {'name': 'C', 'bytes': '344517599'}, {'name': 'C#', 'bytes': '7553169'}, {'name': 'C++', 'bytes': '36635617'}, {'name': 'CMake', 'bytes': '213895'}, {'name': 'CSS', 'bytes': '139462'}, {'name': 'Coq', 'bytes': '320964'}, {'name': 'Cuda', 'bytes': '103316'}, {'name': 'DIGITAL Command Language', 'bytes': '1545539'}, {'name': 'DTrace', 'bytes': '33228'}, {'name': 'Emacs Lisp', 'bytes': '22827'}, {'name': 'GDB', 'bytes': '93449'}, {'name': 'Gnuplot', 'bytes': '7195'}, {'name': 'Go', 'bytes': '393057'}, {'name': 'HTML', 'bytes': '41466430'}, {'name': 'Hack', 'bytes': '22842'}, {'name': 'Haskell', 'bytes': '64053'}, {'name': 'IDL', 'bytes': '3205'}, {'name': 'Java', 'bytes': '49060925'}, {'name': 'JavaScript', 'bytes': '3476841'}, {'name': 'Jolie', 'bytes': '412'}, {'name': 'Lex', 'bytes': '26290'}, {'name': 'Logos', 'bytes': '108920'}, {'name': 'Lua', 'bytes': '427'}, {'name': 'M4', 'bytes': '2508986'}, {'name': 'Makefile', 'bytes': '29393197'}, {'name': 'Mathematica', 'bytes': '48978'}, {'name': 'Mercury', 'bytes': '2053'}, {'name': 'Module Management System', 'bytes': '1313'}, {'name': 'NSIS', 'bytes': '19051'}, {'name': 'OCaml', 'bytes': '981255'}, {'name': 'Objective-C', 'bytes': '4099236'}, {'name': 'Objective-C++', 'bytes': '243505'}, {'name': 'PHP', 'bytes': '22677635'}, {'name': 'Pascal', 'bytes': '99565'}, {'name': 'Perl', 'bytes': '35079773'}, {'name': 'Prolog', 'bytes': '350124'}, {'name': 'Python', 'bytes': '1242241'}, {'name': 'Rebol', 'bytes': '106436'}, {'name': 'Roff', 'bytes': '16457446'}, {'name': 'Ruby', 'bytes': '49694'}, {'name': 'Scheme', 'bytes': '138999'}, {'name': 'Shell', 'bytes': '10192290'}, {'name': 'Smalltalk', 'bytes': '22630'}, {'name': 'Smarty', 'bytes': '51246'}, {'name': 'SourcePawn', 'bytes': '542790'}, {'name': 'SystemVerilog', 'bytes': '95379'}, {'name': 'Tcl', 'bytes': '35696'}, {'name': 'TeX', 'bytes': '2351627'}, {'name': 'Verilog', 'bytes': '91541'}, {'name': 'Visual Basic', 'bytes': '88541'}, {'name': 'XS', 'bytes': '38300'}, {'name': 'Yacc', 'bytes': '132970'}, {'name': 'eC', 'bytes': '33673'}, {'name': 'q', 'bytes': '145272'}, {'name': 'sed', 'bytes': '1196'}]}
/** * This class implements the controller event domain. All classes extending from * {@link Ext.app.Controller} are included in this domain. The selectors are simply id's or the * wildcard "*" to match any controller. * * @private */ Ext.define('Ext.app.domain.Controller', { extend: 'Ext.app.EventDomain', singleton: true, requires: [ 'Ext.app.Controller' ], type: 'controller', prefix: 'controller.', idMatchRe: /^\#/, constructor: function() { var me = this; me.callParent(); me.monitor(Ext.app.BaseController); }, match: function(target, selector) { var result = false, alias = target.alias; if (selector === '*') { result = true; } else if (selector === '#') { result = !!target.isApplication; } else if (this.idMatchRe.test(selector)) { result = target.getId() === selector.substring(1); } else if (alias) { result = Ext.Array.indexOf(alias, this.prefix + selector) > -1; } return result; } });
{'content_hash': '4e571d674298a9413fa76ae3c4a11a39', 'timestamp': '', 'source': 'github', 'line_count': 42, 'max_line_length': 95, 'avg_line_length': 26.833333333333332, 'alnum_prop': 0.551907719609583, 'repo_name': 'mrtinkz/ef-scm', 'id': '274b8ee2526858b07d7ca8a49c4f63fb459eb2c7', 'size': '1127', 'binary': False, 'copies': '19', 'ref': 'refs/heads/master', 'path': 'ef-sencha/ext/src/app/domain/Controller.js', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '14298537'}, {'name': 'JavaScript', 'bytes': '38594691'}, {'name': 'Python', 'bytes': '3330'}, {'name': 'Ruby', 'bytes': '8144'}]}
BUILD_STRATEGY = 'build' CREATE_STRATEGY = 'create' STUB_STRATEGY = 'stub'
{'content_hash': '0dc8b81aff7250a8e6ac0576a0e855c9', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 26, 'avg_line_length': 25.0, 'alnum_prop': 0.72, 'repo_name': 'kamotos/factory_boy', 'id': '387828e467cd57520161e528235359406efc6216', 'size': '148', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'factory/enums.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Makefile', 'bytes': '1193'}, {'name': 'Python', 'bytes': '294322'}]}
<?xml version="1.0" encoding="utf-8"?> <Product xmlns='http://code.google.com/p/open-zwave/'> <!-- Wayne Dalton Thermostat Model WDTC-20 --> <!-- This thermostat's setpoint descriptions are 0 based, not 1 --> <CommandClass id="67" base="0" /> </Product>
{'content_hash': '54df7a54f6748a2113e3b7cdca87c4ef', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 68, 'avg_line_length': 32.375, 'alnum_prop': 0.6602316602316602, 'repo_name': 'MasayukiNagase/samples', 'id': '720d10503e3f4792166becda6aea3b8c91e30c83', 'size': '259', 'binary': False, 'copies': '68', 'ref': 'refs/heads/develop', 'path': 'AllJoyn/Samples/ZWaveAdapter/open-zwave/config/waynedalton/WDTC-20.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Arduino', 'bytes': '3990'}, {'name': 'Assembly', 'bytes': '430189'}, {'name': 'Batchfile', 'bytes': '33219'}, {'name': 'C', 'bytes': '19222895'}, {'name': 'C#', 'bytes': '2139403'}, {'name': 'C++', 'bytes': '14382775'}, {'name': 'CSS', 'bytes': '197551'}, {'name': 'CoffeeScript', 'bytes': '1029'}, {'name': 'Eagle', 'bytes': '838290'}, {'name': 'GDB', 'bytes': '536'}, {'name': 'Groff', 'bytes': '16568'}, {'name': 'HTML', 'bytes': '332537'}, {'name': 'Java', 'bytes': '1868425'}, {'name': 'JavaScript', 'bytes': '207444'}, {'name': 'M4', 'bytes': '31251'}, {'name': 'Makefile', 'bytes': '314303'}, {'name': 'NSIS', 'bytes': '2451'}, {'name': 'Objective-C', 'bytes': '58272'}, {'name': 'OpenSCAD', 'bytes': '29297'}, {'name': 'Perl', 'bytes': '40845'}, {'name': 'Prolog', 'bytes': '72'}, {'name': 'Python', 'bytes': '491481'}, {'name': 'QMake', 'bytes': '3523'}, {'name': 'RAML', 'bytes': '2097'}, {'name': 'Ruby', 'bytes': '1979'}, {'name': 'Shell', 'bytes': '52454'}, {'name': 'Visual Basic', 'bytes': '7115'}, {'name': 'XSLT', 'bytes': '6724'}]}
package org.apache.flink.configuration; import org.apache.flink.util.InstantiationUtil; import org.apache.flink.util.TestLogger; import org.junit.Test; import static org.hamcrest.Matchers.containsString; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * This class contains test for the configuration package. In particular, the serialization of {@link Configuration} * objects is tested. */ public class ConfigurationTest extends TestLogger { private static final byte[] EMPTY_BYTES = new byte[0]; private static final long TOO_LONG = Integer.MAX_VALUE + 10L; private static final double TOO_LONG_DOUBLE = Double.MAX_VALUE; /** * This test checks the serialization/deserialization of configuration objects. */ @Test public void testConfigurationSerializationAndGetters() { try { final Configuration orig = new Configuration(); orig.setString("mykey", "myvalue"); orig.setInteger("mynumber", 100); orig.setLong("longvalue", 478236947162389746L); orig.setFloat("PI", 3.1415926f); orig.setDouble("E", Math.E); orig.setBoolean("shouldbetrue", true); orig.setBytes("bytes sequence", new byte[] { 1, 2, 3, 4, 5 }); orig.setClass("myclass", this.getClass()); final Configuration copy = InstantiationUtil.createCopyWritable(orig); assertEquals("myvalue", copy.getString("mykey", "null")); assertEquals(100, copy.getInteger("mynumber", 0)); assertEquals(478236947162389746L, copy.getLong("longvalue", 0L)); assertEquals(3.1415926f, copy.getFloat("PI", 3.1415926f), 0.0); assertEquals(Math.E, copy.getDouble("E", 0.0), 0.0); assertEquals(true, copy.getBoolean("shouldbetrue", false)); assertArrayEquals(new byte[] { 1, 2, 3, 4, 5 }, copy.getBytes("bytes sequence", null)); assertEquals(getClass(), copy.getClass("myclass", null, getClass().getClassLoader())); assertEquals(orig, copy); assertEquals(orig.keySet(), copy.keySet()); assertEquals(orig.hashCode(), copy.hashCode()); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testConversions() { try { Configuration pc = new Configuration(); pc.setInteger("int", 5); pc.setLong("long", 15); pc.setLong("too_long", TOO_LONG); pc.setFloat("float", 2.1456775f); pc.setDouble("double", Math.PI); pc.setDouble("negative_double", -1.0); pc.setDouble("zero", 0.0); pc.setDouble("too_long_double", TOO_LONG_DOUBLE); pc.setString("string", "42"); pc.setString("non_convertible_string", "bcdefg&&"); pc.setBoolean("boolean", true); // as integer assertEquals(5, pc.getInteger("int", 0)); assertEquals(5L, pc.getLong("int", 0)); assertEquals(5f, pc.getFloat("int", 0), 0.0); assertEquals(5.0, pc.getDouble("int", 0), 0.0); assertEquals(false, pc.getBoolean("int", true)); assertEquals("5", pc.getString("int", "0")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("int", EMPTY_BYTES)); // as long assertEquals(15, pc.getInteger("long", 0)); assertEquals(15L, pc.getLong("long", 0)); assertEquals(15f, pc.getFloat("long", 0), 0.0); assertEquals(15.0, pc.getDouble("long", 0), 0.0); assertEquals(false, pc.getBoolean("long", true)); assertEquals("15", pc.getString("long", "0")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("long", EMPTY_BYTES)); // as too long assertEquals(0, pc.getInteger("too_long", 0)); assertEquals(TOO_LONG, pc.getLong("too_long", 0)); assertEquals((float) TOO_LONG, pc.getFloat("too_long", 0), 10.0); assertEquals((double) TOO_LONG, pc.getDouble("too_long", 0), 10.0); assertEquals(false, pc.getBoolean("too_long", true)); assertEquals(String.valueOf(TOO_LONG), pc.getString("too_long", "0")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("too_long", EMPTY_BYTES)); // as float assertEquals(0, pc.getInteger("float", 0)); assertEquals(0L, pc.getLong("float", 0)); assertEquals(2.1456775f, pc.getFloat("float", 0), 0.0); assertEquals(2.1456775, pc.getDouble("float", 0), 0.0000001); assertEquals(false, pc.getBoolean("float", true)); assertTrue(pc.getString("float", "0").startsWith("2.145677")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("float", EMPTY_BYTES)); // as double assertEquals(0, pc.getInteger("double", 0)); assertEquals(0L, pc.getLong("double", 0)); assertEquals(3.141592f, pc.getFloat("double", 0), 0.000001); assertEquals(Math.PI, pc.getDouble("double", 0), 0.0); assertEquals(false, pc.getBoolean("double", true)); assertTrue(pc.getString("double", "0").startsWith("3.1415926535")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("double", EMPTY_BYTES)); // as negative double assertEquals(0, pc.getInteger("negative_double", 0)); assertEquals(0L, pc.getLong("negative_double", 0)); assertEquals(-1f, pc.getFloat("negative_double", 0), 0.000001); assertEquals(-1, pc.getDouble("negative_double", 0), 0.0); assertEquals(false, pc.getBoolean("negative_double", true)); assertTrue(pc.getString("negative_double", "0").startsWith("-1")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("negative_double", EMPTY_BYTES)); // as zero assertEquals(-1, pc.getInteger("zero", -1)); assertEquals(-1L, pc.getLong("zero", -1)); assertEquals(0f, pc.getFloat("zero", -1), 0.000001); assertEquals(0.0, pc.getDouble("zero", -1), 0.0); assertEquals(false, pc.getBoolean("zero", true)); assertTrue(pc.getString("zero", "-1").startsWith("0")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("zero", EMPTY_BYTES)); // as too long double assertEquals(0, pc.getInteger("too_long_double", 0)); assertEquals(0L, pc.getLong("too_long_double", 0)); assertEquals(0f, pc.getFloat("too_long_double", 0f), 0.000001); assertEquals(TOO_LONG_DOUBLE, pc.getDouble("too_long_double", 0), 0.0); assertEquals(false, pc.getBoolean("too_long_double", true)); assertEquals(String.valueOf(TOO_LONG_DOUBLE), pc.getString("too_long_double", "0")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("too_long_double", EMPTY_BYTES)); // as string assertEquals(42, pc.getInteger("string", 0)); assertEquals(42L, pc.getLong("string", 0)); assertEquals(42f, pc.getFloat("string", 0f), 0.000001); assertEquals(42.0, pc.getDouble("string", 0), 0.0); assertEquals(false, pc.getBoolean("string", true)); assertEquals("42", pc.getString("string", "0")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("string", EMPTY_BYTES)); // as non convertible string assertEquals(0, pc.getInteger("non_convertible_string", 0)); assertEquals(0L, pc.getLong("non_convertible_string", 0)); assertEquals(0f, pc.getFloat("non_convertible_string", 0f), 0.000001); assertEquals(0.0, pc.getDouble("non_convertible_string", 0), 0.0); assertEquals(false, pc.getBoolean("non_convertible_string", true)); assertEquals("bcdefg&&", pc.getString("non_convertible_string", "0")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("non_convertible_string", EMPTY_BYTES)); // as boolean assertEquals(0, pc.getInteger("boolean", 0)); assertEquals(0L, pc.getLong("boolean", 0)); assertEquals(0f, pc.getFloat("boolean", 0f), 0.000001); assertEquals(0.0, pc.getDouble("boolean", 0), 0.0); assertEquals(true, pc.getBoolean("boolean", false)); assertEquals("true", pc.getString("boolean", "0")); assertArrayEquals(EMPTY_BYTES, pc.getBytes("boolean", EMPTY_BYTES)); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testCopyConstructor() { try { final String key = "theKey"; Configuration cfg1 = new Configuration(); cfg1.setString(key, "value"); Configuration cfg2 = new Configuration(cfg1); cfg2.setString(key, "another value"); assertEquals("value", cfg1.getString(key, "")); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } @Test public void testOptionWithDefault() { Configuration cfg = new Configuration(); cfg.setInteger("int-key", 11); cfg.setString("string-key", "abc"); ConfigOption<String> presentStringOption = ConfigOptions.key("string-key").defaultValue("my-beautiful-default"); ConfigOption<Integer> presentIntOption = ConfigOptions.key("int-key").defaultValue(87); assertEquals("abc", cfg.getString(presentStringOption)); assertEquals("abc", cfg.getValue(presentStringOption)); assertEquals(11, cfg.getInteger(presentIntOption)); assertEquals("11", cfg.getValue(presentIntOption)); // test getting default when no value is present ConfigOption<String> stringOption = ConfigOptions.key("test").defaultValue("my-beautiful-default"); ConfigOption<Integer> intOption = ConfigOptions.key("test2").defaultValue(87); // getting strings with default value should work assertEquals("my-beautiful-default", cfg.getValue(stringOption)); assertEquals("my-beautiful-default", cfg.getString(stringOption)); // overriding the default should work assertEquals("override", cfg.getString(stringOption, "override")); // getting a primitive with a default value should work assertEquals(87, cfg.getInteger(intOption)); assertEquals("87", cfg.getValue(intOption)); } @Test public void testOptionWithNoDefault() { Configuration cfg = new Configuration(); cfg.setInteger("int-key", 11); cfg.setString("string-key", "abc"); ConfigOption<String> presentStringOption = ConfigOptions.key("string-key").noDefaultValue(); assertEquals("abc", cfg.getString(presentStringOption)); assertEquals("abc", cfg.getValue(presentStringOption)); // test getting default when no value is present ConfigOption<String> stringOption = ConfigOptions.key("test").noDefaultValue(); // getting strings for null should work assertNull(cfg.getValue(stringOption)); assertNull(cfg.getString(stringOption)); // overriding the null default should work assertEquals("override", cfg.getString(stringOption, "override")); } @Test public void testDeprecatedKeys() { Configuration cfg = new Configuration(); cfg.setInteger("the-key", 11); cfg.setInteger("old-key", 12); cfg.setInteger("older-key", 13); ConfigOption<Integer> matchesFirst = ConfigOptions .key("the-key") .defaultValue(-1) .withDeprecatedKeys("old-key", "older-key"); ConfigOption<Integer> matchesSecond = ConfigOptions .key("does-not-exist") .defaultValue(-1) .withDeprecatedKeys("old-key", "older-key"); ConfigOption<Integer> matchesThird = ConfigOptions .key("does-not-exist") .defaultValue(-1) .withDeprecatedKeys("foo", "older-key"); ConfigOption<Integer> notContained = ConfigOptions .key("does-not-exist") .defaultValue(-1) .withDeprecatedKeys("not-there", "also-not-there"); assertEquals(11, cfg.getInteger(matchesFirst)); assertEquals(12, cfg.getInteger(matchesSecond)); assertEquals(13, cfg.getInteger(matchesThird)); assertEquals(-1, cfg.getInteger(notContained)); } @Test public void testFallbackKeys() { Configuration cfg = new Configuration(); cfg.setInteger("the-key", 11); cfg.setInteger("old-key", 12); cfg.setInteger("older-key", 13); ConfigOption<Integer> matchesFirst = ConfigOptions .key("the-key") .defaultValue(-1) .withFallbackKeys("old-key", "older-key"); ConfigOption<Integer> matchesSecond = ConfigOptions .key("does-not-exist") .defaultValue(-1) .withFallbackKeys("old-key", "older-key"); ConfigOption<Integer> matchesThird = ConfigOptions .key("does-not-exist") .defaultValue(-1) .withFallbackKeys("foo", "older-key"); ConfigOption<Integer> notContained = ConfigOptions .key("does-not-exist") .defaultValue(-1) .withFallbackKeys("not-there", "also-not-there"); assertEquals(11, cfg.getInteger(matchesFirst)); assertEquals(12, cfg.getInteger(matchesSecond)); assertEquals(13, cfg.getInteger(matchesThird)); assertEquals(-1, cfg.getInteger(notContained)); } @Test public void testFallbackAndDeprecatedKeys() { final ConfigOption<Integer> fallback = ConfigOptions .key("fallback") .defaultValue(-1); final ConfigOption<Integer> deprecated = ConfigOptions .key("deprecated") .defaultValue(-1); final ConfigOption<Integer> mainOption = ConfigOptions .key("main") .defaultValue(-1) .withFallbackKeys(fallback.key()) .withDeprecatedKeys(deprecated.key()); final Configuration fallbackCfg = new Configuration(); fallbackCfg.setInteger(fallback, 1); assertEquals(1, fallbackCfg.getInteger(mainOption)); final Configuration deprecatedCfg = new Configuration(); deprecatedCfg.setInteger(deprecated, 2); assertEquals(2, deprecatedCfg.getInteger(mainOption)); // reverse declaration of fallback and deprecated keys, fallback keys should always be used first final ConfigOption<Integer> reversedMainOption = ConfigOptions .key("main") .defaultValue(-1) .withDeprecatedKeys(deprecated.key()) .withFallbackKeys(fallback.key()); final Configuration deprecatedAndFallBackConfig = new Configuration(); deprecatedAndFallBackConfig.setInteger(fallback, 1); deprecatedAndFallBackConfig.setInteger(deprecated, 2); assertEquals(1, deprecatedAndFallBackConfig.getInteger(mainOption)); assertEquals(1, deprecatedAndFallBackConfig.getInteger(reversedMainOption)); } @Test public void testRemove(){ Configuration cfg = new Configuration(); cfg.setInteger("a", 1); cfg.setInteger("b", 2); ConfigOption<Integer> validOption = ConfigOptions .key("a") .defaultValue(-1); ConfigOption<Integer> deprecatedOption = ConfigOptions .key("c") .defaultValue(-1) .withDeprecatedKeys("d", "b"); ConfigOption<Integer> unexistedOption = ConfigOptions .key("e") .defaultValue(-1) .withDeprecatedKeys("f", "g", "j"); assertEquals("Wrong expectation about size", cfg.keySet().size(), 2); assertTrue("Expected 'validOption' is removed", cfg.removeConfig(validOption)); assertEquals("Wrong expectation about size", cfg.keySet().size(), 1); assertTrue("Expected 'existedOption' is removed", cfg.removeConfig(deprecatedOption)); assertEquals("Wrong expectation about size", cfg.keySet().size(), 0); assertFalse("Expected 'unexistedOption' is not removed", cfg.removeConfig(unexistedOption)); } @Test public void testShouldParseValidStringToEnum() { final ConfigOption<String> configOption = createStringConfigOption(); final Configuration configuration = new Configuration(); configuration.setString(configOption.key(), TestEnum.VALUE1.toString()); final TestEnum parsedEnumValue = configuration.getEnum(TestEnum.class, configOption); assertEquals(TestEnum.VALUE1, parsedEnumValue); } @Test public void testShouldParseValidStringToEnumIgnoringCase() { final ConfigOption<String> configOption = createStringConfigOption(); final Configuration configuration = new Configuration(); configuration.setString(configOption.key(), TestEnum.VALUE1.toString().toLowerCase()); final TestEnum parsedEnumValue = configuration.getEnum(TestEnum.class, configOption); assertEquals(TestEnum.VALUE1, parsedEnumValue); } @Test public void testThrowsExceptionIfTryingToParseInvalidStringForEnum() { final ConfigOption<String> configOption = createStringConfigOption(); final Configuration configuration = new Configuration(); final String invalidValueForTestEnum = "InvalidValueForTestEnum"; configuration.setString(configOption.key(), invalidValueForTestEnum); try { configuration.getEnum(TestEnum.class, configOption); fail("Expected exception not thrown"); } catch (IllegalArgumentException e) { final String expectedMessage = "Value for config option " + configOption.key() + " must be one of [VALUE1, VALUE2] (was " + invalidValueForTestEnum + ")"; assertThat(e.getMessage(), containsString(expectedMessage)); } } enum TestEnum { VALUE1, VALUE2 } private static ConfigOption<String> createStringConfigOption() { return ConfigOptions .key("test-string-key") .noDefaultValue(); } }
{'content_hash': 'cd4b78cc1d777b4afdbe953212a7d908', 'timestamp': '', 'source': 'github', 'line_count': 444, 'max_line_length': 116, 'avg_line_length': 36.48873873873874, 'alnum_prop': 0.7158817356953274, 'repo_name': 'shaoxuan-wang/flink', 'id': '9727b44ee16a9486be647cc9da2b71c0f64ba604', 'size': '17006', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'flink-core/src/test/java/org/apache/flink/configuration/ConfigurationTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4588'}, {'name': 'CSS', 'bytes': '57936'}, {'name': 'Clojure', 'bytes': '90539'}, {'name': 'Dockerfile', 'bytes': '10807'}, {'name': 'FreeMarker', 'bytes': '11851'}, {'name': 'HTML', 'bytes': '224454'}, {'name': 'Java', 'bytes': '46844396'}, {'name': 'JavaScript', 'bytes': '1829'}, {'name': 'Makefile', 'bytes': '5134'}, {'name': 'Python', 'bytes': '733285'}, {'name': 'Scala', 'bytes': '12596192'}, {'name': 'Shell', 'bytes': '461101'}, {'name': 'TypeScript', 'bytes': '243702'}]}
<?xml version="1.0" encoding="UTF-8"?> <project version="4"> <component name="ProjectModuleManager"> <modules> <module fileurl="file://$PROJECT_DIR$/app/app.iml" filepath="$PROJECT_DIR$/app/app.iml" /> <module fileurl="file://$PROJECT_DIR$/project-Waiting-in-Line-Stack.iml" filepath="$PROJECT_DIR$/project-Waiting-in-Line-Stack.iml" /> </modules> </component> </project>
{'content_hash': 'f9692884aa8a765d7a3db7f633cfcca2', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 140, 'avg_line_length': 43.888888888888886, 'alnum_prop': 0.6734177215189874, 'repo_name': 'NaughtySpiritAcademy/introduction-to-programming-with-android', 'id': '6e954d928f553eda91c5f039d49e2bc33d89ca9f', 'size': '395', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'week3-collections-and-classes/project-Waiting-in-Line-Stack/.idea/modules.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '186511'}, {'name': 'HTML', 'bytes': '956646'}, {'name': 'Java', 'bytes': '195525'}, {'name': 'JavaScript', 'bytes': '117052'}]}
guid: 59b48aaf-5f50-48a9-af97-9d74d3360398 type: Live reformat: True shortenReferences: True categories: mnemonics scopes: InVBTypeMember(languageLevel=Vb8); InVBTypeAndNamespace(languageLevel=Vb8) parameterOrder: fieldname fieldname-expression: constant("fieldname") --- # o~m A readonly field of type System.Collections.Generic.IEnumerable(Of Decimal) initialized to the default value. ``` Private ReadOnly $fieldname$ As System.Collections.Generic.IEnumerable(Of Decimal) = new System.Collections.Generic.IEnumerable(Of Decimal)() ```
{'content_hash': '9b642f538fdbd619c2e4b53682d81e56', 'timestamp': '', 'source': 'github', 'line_count': 17, 'max_line_length': 141, 'avg_line_length': 31.823529411764707, 'alnum_prop': 0.8096118299445472, 'repo_name': 'citizenmatt/resharper-template-compiler', 'id': 'a782ef8445eb8274630196f9aab3fa31989e46fe', 'size': '545', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'samples/mnemonics/o~m.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C#', 'bytes': '82018'}]}
DESCRIPTION =========== Installs packages required for compiling C software from source. LICENSE AND AUTHOR ================== Author:: Joshua Timberman (<[email protected]>) Copyright 2009, Opscode, 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.
{'content_hash': '06a6f94dcc6c7dbf75818f309602d93c', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 72, 'avg_line_length': 31.956521739130434, 'alnum_prop': 0.7591836734693878, 'repo_name': 'WebUI-Dp-032/VDE', 'id': '3e72caad9cc0890956f7c481ffceafef60b008a3', 'size': '735', 'binary': False, 'copies': '20', 'ref': 'refs/heads/master', 'path': 'cookbooks/build-essential/README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '13519'}]}
require "polarssl" class EncryptedValue cattr_accessor :encryption_key def self.dump(obj) EncryptedValue.new(obj).dump end def self.load(encrypted_data) EncryptedValue.new(encrypted_data).load end def initialize(data) @data = data end def dump if @data.blank? @data = nil # Hmm this seems weird end initialization_vector = SecureRandom.random_bytes(16) cipher = PolarSSL::Cipher.new("AES-128-CTR") cipher.setkey(encryption_key, 128, PolarSSL::Cipher::OPERATION_ENCRYPT) cipher.set_iv(initialization_vector, 16) encoded_object = ActiveSupport::JSON.encode(@data) cipher.update(encoded_object) encrypted_object = cipher.finish encrypted_column = "#{initialization_vector}#{encrypted_object}" encrypted_column end def load if @data.blank? nil else initialization_vector = @data[0..15] encrypted_object = @data[16..-1] cipher = PolarSSL::Cipher.new("AES-128-CTR") cipher.setkey(encryption_key, 128, PolarSSL::Cipher::OPERATION_ENCRYPT) cipher.set_iv(initialization_vector, 16) cipher.update(encrypted_object) json = cipher.finish ActiveSupport::JSON.decode(json) end end private def encryption_key hex_to_bin(Settings.intercity.encryption_key) end def hex_to_bin(hex) hex.scan(/../).map { |x| x.hex.chr }.join end end
{'content_hash': '944ac8a488b539a5a0bb1e4fb152515e', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 77, 'avg_line_length': 21.523076923076925, 'alnum_prop': 0.6733380986418871, 'repo_name': 'intercity/intercity', 'id': '670555b4c35a33d317bbf97bd5fe9b32180c31fa', 'size': '1399', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'app/encryptors/encrypted_value.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '42540'}, {'name': 'CoffeeScript', 'bytes': '5158'}, {'name': 'HTML', 'bytes': '93190'}, {'name': 'JavaScript', 'bytes': '891'}, {'name': 'Nginx', 'bytes': '1691'}, {'name': 'Ruby', 'bytes': '220687'}, {'name': 'Shell', 'bytes': '7998'}]}
import * as i0 from '@angular/core'; import { Component, ChangeDetectionStrategy, ViewEncapsulation, Input, NgModule } from '@angular/core'; import * as i1 from '@angular/common'; import { CommonModule } from '@angular/common'; import { Calendar } from '@fullcalendar/core'; class FullCalendar { constructor(el) { this.el = el; } ngOnInit() { this.config = { theme: true }; if (this.options) { for (let prop in this.options) { this.config[prop] = this.options[prop]; } } } ngAfterViewChecked() { if (!this.initialized && this.el.nativeElement.offsetParent) { this.initialize(); } } get events() { return this._events; } set events(value) { this._events = value; if (this._events && this.calendar) { this.calendar.removeAllEventSources(); this.calendar.addEventSource(this._events); } } get options() { return this._options; } set options(value) { this._options = value; if (this._options && this.calendar) { for (let prop in this._options) { let optionValue = this._options[prop]; this.config[prop] = optionValue; this.calendar.setOption(prop, optionValue); } } } initialize() { this.calendar = new Calendar(this.el.nativeElement.children[0], this.config); this.calendar.render(); this.initialized = true; if (this.events) { this.calendar.removeAllEventSources(); this.calendar.addEventSource(this.events); } } getCalendar() { return this.calendar; } ngOnDestroy() { if (this.calendar) { this.calendar.destroy(); this.initialized = false; this.calendar = null; } } } FullCalendar.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: FullCalendar, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Component }); FullCalendar.ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "12.0.0", version: "12.0.5", type: FullCalendar, selector: "p-fullCalendar", inputs: { style: "style", styleClass: "styleClass", events: "events", options: "options" }, host: { classAttribute: "p-element" }, ngImport: i0, template: '<div [ngStyle]="style" [class]="styleClass"></div>', isInline: true, directives: [{ type: i1.NgStyle, selector: "[ngStyle]", inputs: ["ngStyle"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: FullCalendar, decorators: [{ type: Component, args: [{ selector: 'p-fullCalendar', template: '<div [ngStyle]="style" [class]="styleClass"></div>', changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, host: { 'class': 'p-element' } }] }], ctorParameters: function () { return [{ type: i0.ElementRef }]; }, propDecorators: { style: [{ type: Input }], styleClass: [{ type: Input }], events: [{ type: Input }], options: [{ type: Input }] } }); class FullCalendarModule { } FullCalendarModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: FullCalendarModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); FullCalendarModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: FullCalendarModule, declarations: [FullCalendar], imports: [CommonModule], exports: [FullCalendar] }); FullCalendarModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: FullCalendarModule, imports: [[CommonModule]] }); i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.0.5", ngImport: i0, type: FullCalendarModule, decorators: [{ type: NgModule, args: [{ imports: [CommonModule], exports: [FullCalendar], declarations: [FullCalendar] }] }] }); /** * Generated bundle index. Do not edit. */ export { FullCalendar, FullCalendarModule }; //# sourceMappingURL=primeng-fullcalendar.js.map
{'content_hash': '5e2fbd12422484236047526b390df124', 'timestamp': '', 'source': 'github', 'line_count': 110, 'max_line_length': 536, 'avg_line_length': 42.10909090909091, 'alnum_prop': 0.5777202072538861, 'repo_name': 'cdnjs/cdnjs', 'id': '76a11d026fb872657fbe77e0ad706b21e4c8f81c', 'size': '4655', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'ajax/libs/primeng/12.2.0-rc.1/fesm2015/primeng-fullcalendar.js', 'mode': '33188', 'license': 'mit', 'language': []}
require "spec_helper" describe Chef::Knife::SubcommandLoader::CustomManifestLoader do let(:ec2_server_create_plugin) { "/usr/lib/ruby/gems/knife-ec2-0.5.12/lib/chef/knife/ec2_server_create.rb" } let(:manifest_content) do { "plugins" => { "knife-ec2" => { "paths" => [ ec2_server_create_plugin, ], }, }, } end let(:loader) do Chef::Knife::SubcommandLoader::CustomManifestLoader.new(File.join(CHEF_SPEC_DATA, "knife-site-subcommands"), manifest_content) end it "uses paths from the manifest instead of searching gems" do expect(Gem::Specification).not_to receive(:latest_specs).and_call_original expect(loader.subcommand_files).to include(ec2_server_create_plugin) end end
{'content_hash': '685fdf51ec06744fefa75c433b3a21d5', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 112, 'avg_line_length': 35.083333333333336, 'alnum_prop': 0.5997624703087886, 'repo_name': 'mikedodge04/chef', 'id': '814ac8a027c6885835fefccca46a038aff78061d', 'size': '1487', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'spec/unit/knife/core/custom_manifest_loader_spec.rb', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '1792'}, {'name': 'CSS', 'bytes': '21552'}, {'name': 'HTML', 'bytes': '566116'}, {'name': 'JavaScript', 'bytes': '49788'}, {'name': 'Makefile', 'bytes': '1326'}, {'name': 'Perl6', 'bytes': '64'}, {'name': 'PowerShell', 'bytes': '15894'}, {'name': 'Python', 'bytes': '12284'}, {'name': 'Roff', 'bytes': '270440'}, {'name': 'Ruby', 'bytes': '8924174'}, {'name': 'Shell', 'bytes': '23276'}]}
<!DOCTYPE html> <html> <body> <script src="../../resources/js-test.js"></script> <script> description("This tests if TypeError is thrown or not when we call a constructor as a normal function."); var test_constructors = ["ArrayBuffer", "AudioContext", "FormData", "DataView", "EventSource", "FileReader", "Float32Array", "Float64Array", "Audio", "Image", "Option", "Int16Array", "Int32Array", "Int8Array", "MessageChannel", "SharedWorker", "Uint16Array", "Uint32Array", "Uint8Array", "WebKitCSSMatrix", "WebSocket", "Worker", "XMLHttpRequest", "XSLTProcessor"]; test_constructors.forEach(function (constructor) { if (eval("window." + constructor)) shouldThrow(constructor + "()"); else debug("SKIP " + constructor + " is not implemented."); }); </script> </body> </html>
{'content_hash': 'f324e9063ee7bab79a3308348e28a490', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 365, 'avg_line_length': 42.0, 'alnum_prop': 0.681704260651629, 'repo_name': 'heke123/chromium-crosswalk', 'id': '6d0888a8bcfa816d0248f7ab982d3c5075a70098', 'size': '798', 'binary': False, 'copies': '51', 'ref': 'refs/heads/master', 'path': 'third_party/WebKit/LayoutTests/fast/dom/call-a-constructor-as-a-function.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
.oo-ui-icon-userActive { background-image: url('themes/mediawiki/images/icons/userActive-rtl.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userActive-rtl.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userActive-rtl.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userActive-rtl.png'); } .oo-ui-image-invert.oo-ui-icon-userActive { background-image: url('themes/mediawiki/images/icons/userActive-rtl-invert.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userActive-rtl-invert.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userActive-rtl-invert.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userActive-rtl-invert.png'); } .oo-ui-image-progressive.oo-ui-icon-userActive { background-image: url('themes/mediawiki/images/icons/userActive-rtl-progressive.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userActive-rtl-progressive.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userActive-rtl-progressive.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userActive-rtl-progressive.png'); } .oo-ui-icon-userAvatar { background-image: url('themes/mediawiki/images/icons/userAvatar.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userAvatar.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userAvatar.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userAvatar.png'); } .oo-ui-image-invert.oo-ui-icon-userAvatar { background-image: url('themes/mediawiki/images/icons/userAvatar-invert.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userAvatar-invert.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userAvatar-invert.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userAvatar-invert.png'); } .oo-ui-image-progressive.oo-ui-icon-userAvatar { background-image: url('themes/mediawiki/images/icons/userAvatar-progressive.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userAvatar-progressive.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userAvatar-progressive.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userAvatar-progressive.png'); } .oo-ui-icon-userInactive { background-image: url('themes/mediawiki/images/icons/userInactive-rtl.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userInactive-rtl.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userInactive-rtl.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userInactive-rtl.png'); } .oo-ui-image-invert.oo-ui-icon-userInactive { background-image: url('themes/mediawiki/images/icons/userInactive-rtl-invert.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userInactive-rtl-invert.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userInactive-rtl-invert.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userInactive-rtl-invert.png'); } .oo-ui-image-progressive.oo-ui-icon-userInactive { background-image: url('themes/mediawiki/images/icons/userInactive-rtl-progressive.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userInactive-rtl-progressive.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userInactive-rtl-progressive.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userInactive-rtl-progressive.png'); } .oo-ui-icon-userTalk { background-image: url('themes/mediawiki/images/icons/userTalk-rtl.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userTalk-rtl.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userTalk-rtl.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userTalk-rtl.png'); } .oo-ui-image-invert.oo-ui-icon-userTalk { background-image: url('themes/mediawiki/images/icons/userTalk-rtl-invert.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userTalk-rtl-invert.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userTalk-rtl-invert.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userTalk-rtl-invert.png'); } .oo-ui-image-progressive.oo-ui-icon-userTalk { background-image: url('themes/mediawiki/images/icons/userTalk-rtl-progressive.png'); background-image: -webkit-linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userTalk-rtl-progressive.svg'); background-image: linear-gradient(transparent, transparent), /* @embed */ url('themes/mediawiki/images/icons/userTalk-rtl-progressive.svg'); background-image: -o-linear-gradient(transparent, transparent), url('themes/mediawiki/images/icons/userTalk-rtl-progressive.png'); }
{'content_hash': 'f576bf2c24fbe652edea8c189d0488d8', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 154, 'avg_line_length': 90.36986301369863, 'alnum_prop': 0.7536759132939215, 'repo_name': 'wout/cdnjs', 'id': 'e19e7fa236bf0bf30a48b2c167ec46bc5ab4e966', 'size': '6845', 'binary': False, 'copies': '25', 'ref': 'refs/heads/master', 'path': 'ajax/libs/oojs-ui/0.19.3/oojs-ui-mediawiki-icons-user.rtl.css', 'mode': '33188', 'license': 'mit', 'language': []}
(function($, undefined) { /** * Unobtrusive scripting adapter for jQuery * https://github.com/rails/jquery-ujs * * Requires jQuery 1.8.0 or later. * * Released under the MIT license * */ // Cut down on the number of issues from people inadvertently including jquery_ujs twice // by detecting and raising an error when it happens. 'use strict'; if ( $.rails !== undefined ) { $.error('jquery-ujs has already been loaded!'); } // Shorthand to make it a little easier to call public rails functions from within rails.js var rails; var $document = $(document); $.rails = rails = { // Link elements bound by jquery-ujs linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote], a[data-disable-with], a[data-disable]', // Button elements bound by jquery-ujs buttonClickSelector: 'button[data-remote]:not(form button), button[data-confirm]:not(form button)', // Select elements bound by jquery-ujs inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]', // Form elements bound by jquery-ujs formSubmitSelector: 'form', // Form input elements bound by jquery-ujs formInputClickSelector: 'form input[type=submit], form input[type=image], form button[type=submit], form button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])', // Form input elements disabled during form submission disableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled', // Form input elements re-enabled after form submission enableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled', // Form required input elements requiredInputSelector: 'input[name][required]:not([disabled]),textarea[name][required]:not([disabled])', // Form file input elements fileInputSelector: 'input[type=file]:not([disabled])', // Link onClick disable selector with possible reenable after remote submission linkDisableSelector: 'a[data-disable-with], a[data-disable]', // Button onClick disable selector with possible reenable after remote submission buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]', // Up-to-date Cross-Site Request Forgery token csrfToken: function() { return $('meta[name=csrf-token]').attr('content'); }, // URL param that must contain the CSRF token csrfParam: function() { return $('meta[name=csrf-param]').attr('content'); }, // Make sure that every Ajax request sends the CSRF token CSRFProtection: function(xhr) { var token = rails.csrfToken(); if (token) xhr.setRequestHeader('X-CSRF-Token', token); }, // Make sure that all forms have actual up-to-date tokens (cached forms contain old ones) refreshCSRFTokens: function(){ $('form input[name="' + rails.csrfParam() + '"]').val(rails.csrfToken()); }, // Triggers an event on an element and returns false if the event result is false fire: function(obj, name, data) { var event = $.Event(name); obj.trigger(event, data); return event.result !== false; }, // Default confirm dialog, may be overridden with custom confirm dialog in $.rails.confirm confirm: function(message) { return confirm(message); }, // Default ajax function, may be overridden with custom function in $.rails.ajax ajax: function(options) { return $.ajax(options); }, // Default way to get an element's href. May be overridden at $.rails.href. href: function(element) { return element[0].href; }, // Checks "data-remote" if true to handle the request through a XHR request. isRemote: function(element) { return element.data('remote') !== undefined && element.data('remote') !== false; }, // Submits "remote" forms and links with ajax handleRemote: function(element) { var method, url, data, withCredentials, dataType, options; if (rails.fire(element, 'ajax:before')) { withCredentials = element.data('with-credentials') || null; dataType = element.data('type') || ($.ajaxSettings && $.ajaxSettings.dataType); if (element.is('form')) { method = element.attr('method'); url = element.attr('action'); data = element.serializeArray(); // memoized value from clicked submit button var button = element.data('ujs:submit-button'); if (button) { data.push(button); element.data('ujs:submit-button', null); } } else if (element.is(rails.inputChangeSelector)) { method = element.data('method'); url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + '&' + element.data('params'); } else if (element.is(rails.buttonClickSelector)) { method = element.data('method') || 'get'; url = element.data('url'); data = element.serialize(); if (element.data('params')) data = data + '&' + element.data('params'); } else { method = element.data('method'); url = rails.href(element); data = element.data('params') || null; } options = { type: method || 'GET', data: data, dataType: dataType, // stopping the "ajax:beforeSend" event will cancel the ajax request beforeSend: function(xhr, settings) { if (settings.dataType === undefined) { xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script); } if (rails.fire(element, 'ajax:beforeSend', [xhr, settings])) { element.trigger('ajax:send', xhr); } else { return false; } }, success: function(data, status, xhr) { element.trigger('ajax:success', [data, status, xhr]); }, complete: function(xhr, status) { element.trigger('ajax:complete', [xhr, status]); }, error: function(xhr, status, error) { element.trigger('ajax:error', [xhr, status, error]); }, crossDomain: rails.isCrossDomain(url) }; // There is no withCredentials for IE6-8 when // "Enable native XMLHTTP support" is disabled if (withCredentials) { options.xhrFields = { withCredentials: withCredentials }; } // Only pass url to `ajax` options if not blank if (url) { options.url = url; } return rails.ajax(options); } else { return false; } }, // Determines if the request is a cross domain request. isCrossDomain: function(url) { var originAnchor = document.createElement('a'); originAnchor.href = location.href; var urlAnchor = document.createElement('a'); try { urlAnchor.href = url; // This is a workaround to a IE bug. urlAnchor.href = urlAnchor.href; // If URL protocol is false or is a string containing a single colon // *and* host are false, assume it is not a cross-domain request // (should only be the case for IE7 and IE compatibility mode). // Otherwise, evaluate protocol and host of the URL against the origin // protocol and host. return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') && !urlAnchor.host) || (originAnchor.protocol + '//' + originAnchor.host === urlAnchor.protocol + '//' + urlAnchor.host)); } catch (e) { // If there is an error parsing the URL, assume it is crossDomain. return true; } }, // Handles "data-method" on links such as: // <a href="/users/5" data-method="delete" rel="nofollow" data-confirm="Are you sure?">Delete</a> handleMethod: function(link) { var href = rails.href(link), method = link.data('method'), target = link.attr('target'), csrfToken = rails.csrfToken(), csrfParam = rails.csrfParam(), form = $('<form method="post" action="' + href + '"></form>'), metadataInput = '<input name="_method" value="' + method + '" type="hidden" />'; if (csrfParam !== undefined && csrfToken !== undefined && !rails.isCrossDomain(href)) { metadataInput += '<input name="' + csrfParam + '" value="' + csrfToken + '" type="hidden" />'; } if (target) { form.attr('target', target); } form.hide().append(metadataInput).appendTo('body'); form.submit(); }, // Helper function that returns form elements that match the specified CSS selector // If form is actually a "form" element this will return associated elements outside the from that have // the html form attribute set formElements: function(form, selector) { return form.is('form') ? $(form[0].elements).filter(selector) : form.find(selector); }, /* Disables form elements: - Caches element value in 'ujs:enable-with' data store - Replaces element text with value of 'data-disable-with' attribute - Sets disabled property to true */ disableFormElements: function(form) { rails.formElements(form, rails.disableSelector).each(function() { rails.disableFormElement($(this)); }); }, disableFormElement: function(element) { var method, replacement; method = element.is('button') ? 'html' : 'val'; replacement = element.data('disable-with'); element.data('ujs:enable-with', element[method]()); if (replacement !== undefined) { element[method](replacement); } element.prop('disabled', true); }, /* Re-enables disabled form elements: - Replaces element text with cached value from 'ujs:enable-with' data store (created in `disableFormElements`) - Sets disabled property to false */ enableFormElements: function(form) { rails.formElements(form, rails.enableSelector).each(function() { rails.enableFormElement($(this)); }); }, enableFormElement: function(element) { var method = element.is('button') ? 'html' : 'val'; if (typeof element.data('ujs:enable-with') !== 'undefined') element[method](element.data('ujs:enable-with')); element.prop('disabled', false); }, /* For 'data-confirm' attribute: - Fires `confirm` event - Shows the confirmation dialog - Fires the `confirm:complete` event Returns `true` if no function stops the chain and user chose yes; `false` otherwise. Attaching a handler to the element's `confirm` event that returns a `falsy` value cancels the confirmation dialog. Attaching a handler to the element's `confirm:complete` event that returns a `falsy` value makes this function return false. The `confirm:complete` event is fired whether or not the user answered true or false to the dialog. */ allowAction: function(element) { var message = element.data('confirm'), answer = false, callback; if (!message) { return true; } if (rails.fire(element, 'confirm')) { try { answer = rails.confirm(message); } catch (e) { (console.error || console.log).call(console, e.stack || e); } callback = rails.fire(element, 'confirm:complete', [answer]); } return answer && callback; }, // Helper function which checks for blank inputs in a form that match the specified CSS selector blankInputs: function(form, specifiedSelector, nonBlank) { var inputs = $(), input, valueToCheck, selector = specifiedSelector || 'input,textarea', allInputs = form.find(selector); allInputs.each(function() { input = $(this); valueToCheck = input.is('input[type=checkbox],input[type=radio]') ? input.is(':checked') : !!input.val(); if (valueToCheck === nonBlank) { // Don't count unchecked required radio if other radio with same name is checked if (input.is('input[type=radio]') && allInputs.filter('input[type=radio]:checked[name="' + input.attr('name') + '"]').length) { return true; // Skip to next input } inputs = inputs.add(input); } }); return inputs.length ? inputs : false; }, // Helper function which checks for non-blank inputs in a form that match the specified CSS selector nonBlankInputs: function(form, specifiedSelector) { return rails.blankInputs(form, specifiedSelector, true); // true specifies nonBlank }, // Helper function, needed to provide consistent behavior in IE stopEverything: function(e) { $(e.target).trigger('ujs:everythingStopped'); e.stopImmediatePropagation(); return false; }, // Replace element's html with the 'data-disable-with' after storing original html // and prevent clicking on it disableElement: function(element) { var replacement = element.data('disable-with'); element.data('ujs:enable-with', element.html()); // store enabled state if (replacement !== undefined) { element.html(replacement); } element.bind('click.railsDisable', function(e) { // prevent further clicking return rails.stopEverything(e); }); }, // Restore element to its original state which was disabled by 'disableElement' above enableElement: function(element) { if (element.data('ujs:enable-with') !== undefined) { element.html(element.data('ujs:enable-with')); // set to old enabled state element.removeData('ujs:enable-with'); // clean up cache } element.unbind('click.railsDisable'); // enable element } }; if (rails.fire($document, 'rails:attachBindings')) { $.ajaxPrefilter(function(options, originalOptions, xhr){ if ( !options.crossDomain ) { rails.CSRFProtection(xhr); }}); // This event works the same as the load event, except that it fires every // time the page is loaded. // // See https://github.com/rails/jquery-ujs/issues/357 // See https://developer.mozilla.org/en-US/docs/Using_Firefox_1.5_caching $(window).on('pageshow.rails', function () { $($.rails.enableSelector).each(function () { var element = $(this); if (element.data('ujs:enable-with')) { $.rails.enableFormElement(element); } }); $($.rails.linkDisableSelector).each(function () { var element = $(this); if (element.data('ujs:enable-with')) { $.rails.enableElement(element); } }); }); $document.delegate(rails.linkDisableSelector, 'ajax:complete', function() { rails.enableElement($(this)); }); $document.delegate(rails.buttonDisableSelector, 'ajax:complete', function() { rails.enableFormElement($(this)); }); $document.delegate(rails.linkClickSelector, 'click.rails', function(e) { var link = $(this), method = link.data('method'), data = link.data('params'), metaClick = e.metaKey || e.ctrlKey; if (!rails.allowAction(link)) return rails.stopEverything(e); if (!metaClick && link.is(rails.linkDisableSelector)) rails.disableElement(link); if (rails.isRemote(link)) { if (metaClick && (!method || method === 'GET') && !data) { return true; } var handleRemote = rails.handleRemote(link); // Response from rails.handleRemote() will either be false or a deferred object promise. if (handleRemote === false) { rails.enableElement(link); } else { handleRemote.fail( function() { rails.enableElement(link); } ); } return false; } else if (method) { rails.handleMethod(link); return false; } }); $document.delegate(rails.buttonClickSelector, 'click.rails', function(e) { var button = $(this); if (!rails.allowAction(button) || !rails.isRemote(button)) return rails.stopEverything(e); if (button.is(rails.buttonDisableSelector)) rails.disableFormElement(button); var handleRemote = rails.handleRemote(button); // Response from rails.handleRemote() will either be false or a deferred object promise. if (handleRemote === false) { rails.enableFormElement(button); } else { handleRemote.fail( function() { rails.enableFormElement(button); } ); } return false; }); $document.delegate(rails.inputChangeSelector, 'change.rails', function(e) { var link = $(this); if (!rails.allowAction(link) || !rails.isRemote(link)) return rails.stopEverything(e); rails.handleRemote(link); return false; }); $document.delegate(rails.formSubmitSelector, 'submit.rails', function(e) { var form = $(this), remote = rails.isRemote(form), blankRequiredInputs, nonBlankFileInputs; if (!rails.allowAction(form)) return rails.stopEverything(e); // Skip other logic when required values are missing or file upload is present if (form.attr('novalidate') === undefined) { blankRequiredInputs = rails.blankInputs(form, rails.requiredInputSelector, false); if (blankRequiredInputs && rails.fire(form, 'ajax:aborted:required', [blankRequiredInputs])) { return rails.stopEverything(e); } } if (remote) { nonBlankFileInputs = rails.nonBlankInputs(form, rails.fileInputSelector); if (nonBlankFileInputs) { // Slight timeout so that the submit button gets properly serialized // (make it easy for event handler to serialize form without disabled values) setTimeout(function(){ rails.disableFormElements(form); }, 13); var aborted = rails.fire(form, 'ajax:aborted:file', [nonBlankFileInputs]); // Re-enable form elements if event bindings return false (canceling normal form submission) if (!aborted) { setTimeout(function(){ rails.enableFormElements(form); }, 13); } return aborted; } rails.handleRemote(form); return false; } else { // Slight timeout so that the submit button gets properly serialized setTimeout(function(){ rails.disableFormElements(form); }, 13); } }); $document.delegate(rails.formInputClickSelector, 'click.rails', function(event) { var button = $(this); if (!rails.allowAction(button)) return rails.stopEverything(event); // Register the pressed submit button var name = button.attr('name'), data = name ? {name:name, value:button.val()} : null; button.closest('form').data('ujs:submit-button', data); }); $document.delegate(rails.formSubmitSelector, 'ajax:send.rails', function(event) { if (this === event.target) rails.disableFormElements($(this)); }); $document.delegate(rails.formSubmitSelector, 'ajax:complete.rails', function(event) { if (this === event.target) rails.enableFormElements($(this)); }); $(function(){ rails.refreshCSRFTokens(); }); } })( jQuery );
{'content_hash': '2a8e81bfd5d3729434ceb94b7fa6b450', 'timestamp': '', 'source': 'github', 'line_count': 510, 'max_line_length': 233, 'avg_line_length': 38.319607843137256, 'alnum_prop': 0.628767333572123, 'repo_name': 'tonytomov/cdnjs', 'id': '490a760cc373bf51154f8707654e737ba037c0fd', 'size': '19543', 'binary': False, 'copies': '68', 'ref': 'refs/heads/master', 'path': 'ajax/libs/jquery-ujs/1.1.0/rails.js', 'mode': '33188', 'license': 'mit', 'language': []}
license: > Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --- # accelerometer.clearWatch Stop watching the `Acceleration` referenced by the `watchID` parameter. navigator.accelerometer.clearWatch(watchID); - __watchID__: The ID returned by `accelerometer.watchAcceleration`. ## Supported Platforms - Android - BlackBerry WebWorks (OS 5.0 and higher) - iOS - Tizen - Windows Phone 7 and 8 - Windows 8 ## Quick Example var watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options); // ... later on ... navigator.accelerometer.clearWatch(watchID); ## Full Example <!DOCTYPE html> <html> <head> <title>Acceleration Example</title> <script type="text/javascript" charset="utf-8" src="cordova.js"></script> <script type="text/javascript" charset="utf-8"> // The watch id references the current `watchAcceleration` var watchID = null; // Wait for device API libraries to load // document.addEventListener("deviceready", onDeviceReady, false); // device APIs are available // function onDeviceReady() { startWatch(); } // Start watching the acceleration // function startWatch() { // Update acceleration every 3 seconds var options = { frequency: 3000 }; watchID = navigator.accelerometer.watchAcceleration(onSuccess, onError, options); } // Stop watching the acceleration // function stopWatch() { if (watchID) { navigator.accelerometer.clearWatch(watchID); watchID = null; } } // onSuccess: Get a snapshot of the current acceleration // function onSuccess(acceleration) { var element = document.getElementById('accelerometer'); element.innerHTML = 'Acceleration X: ' + acceleration.x + '<br />' + 'Acceleration Y: ' + acceleration.y + '<br />' + 'Acceleration Z: ' + acceleration.z + '<br />' + 'Timestamp: ' + acceleration.timestamp + '<br />'; } // onError: Failed to get the acceleration // function onError() { alert('onError!'); } </script> </head> <body> <div id="accelerometer">Waiting for accelerometer...</div> <button onclick="stopWatch();">Stop Watching</button> </body> </html>
{'content_hash': '1a220b4ed6925fe150af2e6b7f6f75ae', 'timestamp': '', 'source': 'github', 'line_count': 110, 'max_line_length': 93, 'avg_line_length': 30.381818181818183, 'alnum_prop': 0.6101137043686415, 'repo_name': 'drbeermann/cordova-docs', 'id': 'db5abea2e9da3cac70332c1709b34fe03af027fc', 'size': '3346', 'binary': False, 'copies': '5', 'ref': 'refs/heads/master', 'path': 'docs/en/3.1.0/cordova/accelerometer/accelerometer.clearWatch.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '5116'}, {'name': 'CSS', 'bytes': '11129'}, {'name': 'HTML', 'bytes': '113105'}, {'name': 'JavaScript', 'bytes': '69082'}]}
import enqueueNotifications from 'src/server/modules/mail'; import * as Queries from 'src/server/modules/queries'; export default async (req, res, next) => { const post = await Queries.post(req.params.id); const subscribers = await Queries.subscribers(); return enqueueNotifications(post, subscribers) .then(() => { res.send('OK'); }) .catch(err => next(err)); }
{'content_hash': '513b73a4982e0416ad1dc039f91672d2', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 59, 'avg_line_length': 29.923076923076923, 'alnum_prop': 0.6786632390745502, 'repo_name': 'tuelsch/bolg', 'id': '2f4cbd413a15461f1237c17765e7fd727d58a216', 'size': '389', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/server/api/notify-api.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '20531'}, {'name': 'HTML', 'bytes': '18324'}, {'name': 'JavaScript', 'bytes': '100418'}, {'name': 'Vue', 'bytes': '91407'}]}
<!DOCTYPE html> <div style="height: 2px"></div> &nbsp;&nbsp;<input id="input" style="outline: none"> <script> onload = function() { input.focus(); }; </script>
{'content_hash': '5fd6762a7fc3ad1f6b69d748a166779e', 'timestamp': '', 'source': 'github', 'line_count': 8, 'max_line_length': 52, 'avg_line_length': 20.25, 'alnum_prop': 0.6358024691358025, 'repo_name': 'nwjs/chromium.src', 'id': 'e3df8dd2165a7a381614ed3a3db3af08b45969a8', 'size': '162', 'binary': False, 'copies': '10', 'ref': 'refs/heads/nw70', 'path': 'third_party/blink/web_tests/paint/invalidation/caret-change-paint-offset-keep-visual-expected.html', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package org.bouncycastle.crypto; /** * General interface for a stream cipher that supports skipping. */ public interface SkippingStreamCipher extends StreamCipher, SkippingCipher { }
{'content_hash': '52f79c5c395b153da922bf3f0caf20e5', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 64, 'avg_line_length': 21.11111111111111, 'alnum_prop': 0.7789473684210526, 'repo_name': 'alphallc/connectbot', 'id': 'a707a8108fbc1a0e2e9a2cb580f6585bb3995510', 'size': '190', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'src/org/bouncycastle/crypto/SkippingStreamCipher.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C++', 'bytes': '5383'}, {'name': 'Java', 'bytes': '8679024'}]}
This is the vertx 2.x portion of a [benchmarking test suite](../) comparing a variety of web development platforms. ### Plaintext Test * [Plaintext test source](WebServer.java) ### JSON Serialization Test * [JSON test source](WebServer.java) ### Database Single query Test * [Database Single query test source](WebServer.java) ### Database Multiple queries Test * [Database Multiple queries test source](WebServer.java) ### Database Data updates Test * [Database Data updates test source](WebServer.java) ### Fortunes Test * [Fortunes test source](WebServer.java) ## Versions * [Java OpenJDK 1.7.0_79](http://openjdk.java.net/) * [vertx 2.1.5](http://vertx.io/) ## Test URLs ### Plaintext Test http://localhost:8080/plaintext ### JSON Encoding Test http://localhost:8080/json ### Database Mapping Test http://localhost:8080/db?queries=5 ### Database Single query Test http://localhost:8080/db ### Database Multiple queries Test http://localhost:8080/queries?queries=5 ### Database Data updates Test http://localhost:8080/updates?queries=3 ### Fortunes Test http://localhost:8080/fortunes
{'content_hash': '2e913b970af5dd2da9ee17c70c1584af', 'timestamp': '', 'source': 'github', 'line_count': 61, 'max_line_length': 115, 'avg_line_length': 18.78688524590164, 'alnum_prop': 0.7085514834205934, 'repo_name': 'denkab/FrameworkBenchmarks', 'id': '05e4608512e14621f1873a6467459f1b933032e8', 'size': '1177', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'frameworks/Java/vertx/README.md', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '838'}, {'name': 'ApacheConf', 'bytes': '21505'}, {'name': 'Batchfile', 'bytes': '1458'}, {'name': 'C', 'bytes': '39790'}, {'name': 'C#', 'bytes': '129545'}, {'name': 'C++', 'bytes': '40927'}, {'name': 'CMake', 'bytes': '498'}, {'name': 'CSS', 'bytes': '200805'}, {'name': 'Clojure', 'bytes': '36450'}, {'name': 'Crystal', 'bytes': '3642'}, {'name': 'DIGITAL Command Language', 'bytes': '34'}, {'name': 'Dart', 'bytes': '36881'}, {'name': 'Elixir', 'bytes': '7484'}, {'name': 'Erlang', 'bytes': '8237'}, {'name': 'Go', 'bytes': '42477'}, {'name': 'Groff', 'bytes': '49'}, {'name': 'Groovy', 'bytes': '18156'}, {'name': 'HTML', 'bytes': '66618'}, {'name': 'Handlebars', 'bytes': '484'}, {'name': 'Haskell', 'bytes': '14573'}, {'name': 'Java', 'bytes': '350574'}, {'name': 'JavaScript', 'bytes': '448754'}, {'name': 'Lua', 'bytes': '8818'}, {'name': 'Makefile', 'bytes': '1257'}, {'name': 'MoonScript', 'bytes': '2398'}, {'name': 'Nginx', 'bytes': '128753'}, {'name': 'Nim', 'bytes': '5106'}, {'name': 'PHP', 'bytes': '1661445'}, {'name': 'Perl', 'bytes': '10767'}, {'name': 'PowerShell', 'bytes': '35514'}, {'name': 'Python', 'bytes': '281866'}, {'name': 'QMake', 'bytes': '2056'}, {'name': 'Racket', 'bytes': '5298'}, {'name': 'Ruby', 'bytes': '76870'}, {'name': 'Rust', 'bytes': '1561'}, {'name': 'Scala', 'bytes': '95026'}, {'name': 'Shell', 'bytes': '237207'}, {'name': 'Smarty', 'bytes': '436'}, {'name': 'Volt', 'bytes': '769'}]}
package cn.edu.sjtu.omnilab.kalin.tests import cn.edu.sjtu.omnilab.kalin.hz.DataSchema import cn.edu.sjtu.omnilab.kalin.stlab.{MPoint, CleanseMob} import org.apache.spark.SparkContext.rddToPairRDDFunctions import org.apache.spark.rdd.RDD class CleanseMobTest extends SparkJobSpec { "Spark Correlation implementations" should { val testFile = this.getClass.getResource("/hzlogs.txt").getPath() def extractMov(inputRDD: RDD[String]): RDD[MPoint] = { val movement = inputRDD .map( line => { val tuple = line.split("\t") val imsi = tuple(DataSchema.IMSI) val time = tuple(DataSchema.TTime).toDouble val cell = tuple(DataSchema.BS) MPoint(imsi, time, cell) }).sortBy(_.time) movement } "case 0: join action works normally" in { val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3) val b = a.keyBy(_.length) val c = sc.parallelize(List("dog","cat","gnu","salmon","rabbit","turkey","wolf","bear","bee"), 3) val d = c.keyBy(_.length) b.join(d) true must_== true } "case 1: return with correct test log number (#14)" in { val inputRDD = sc.textFile(testFile) val count = inputRDD.count() count must_== 20 } "case 2: return correct format of tidied data" in { val inputRDD = sc.textFile(testFile) val movement = extractMov(inputRDD) val cleaned = CleanseMob.cleanse(movement, 0, 0, 0, 0, 8, false) cleaned.count() == 4 } "case 3: adding night logs works well in TidyMovement" in { val inputRDD = sc.textFile(testFile) val movement = extractMov(inputRDD) val cleaned = CleanseMob.cleanse(movement, 0, 0, 0, 0, 8, true) cleaned.count() == 4 } } }
{'content_hash': '0776dfd3350fce17a171b36d1ca8e34d', 'timestamp': '', 'source': 'github', 'line_count': 58, 'max_line_length': 103, 'avg_line_length': 31.24137931034483, 'alnum_prop': 0.6236203090507726, 'repo_name': 'caesar0301/MDMS', 'id': 'e595c0ab9b0b703cccec21da41b707e8960b6999', 'size': '1812', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'kalin-etl/src/test/scala/cn/edu/sjtu/omnilab/kalin/tests/CleanseMobTest.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '155'}, {'name': 'Scala', 'bytes': '32144'}, {'name': 'Shell', 'bytes': '2358'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_17) on Mon Apr 12 12:09:32 PDT 2010 --> <TITLE> Uses of Package org.apache.hadoop.chukwa.datacollection.agent (chukwa 0.4.0 API) </TITLE> <META NAME="date" CONTENT="2010-04-12"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Package org.apache.hadoop.chukwa.datacollection.agent (chukwa 0.4.0 API)"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/chukwa/datacollection/agent/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Package<br>org.apache.hadoop.chukwa.datacollection.agent</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/package-summary.html">org.apache.hadoop.chukwa.datacollection.agent</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.chukwa.datacollection.adaptor"><B>org.apache.hadoop.chukwa.datacollection.adaptor</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.chukwa.datacollection.agent"><B>org.apache.hadoop.chukwa.datacollection.agent</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.chukwa.datacollection.connector.http"><B>org.apache.hadoop.chukwa.datacollection.connector.http</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.chukwa.datacollection.sender"><B>org.apache.hadoop.chukwa.datacollection.sender</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.chukwa.datacollection.test"><B>org.apache.hadoop.chukwa.datacollection.test</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.hadoop.chukwa.util"><B>org.apache.hadoop.chukwa.util</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.chukwa.datacollection.adaptor"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/package-summary.html">org.apache.hadoop.chukwa.datacollection.agent</A> used by <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/adaptor/package-summary.html">org.apache.hadoop.chukwa.datacollection.adaptor</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/AdaptorManager.html#org.apache.hadoop.chukwa.datacollection.adaptor"><B>AdaptorManager</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The interface to the agent that is exposed to adaptors.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.chukwa.datacollection.agent"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/package-summary.html">org.apache.hadoop.chukwa.datacollection.agent</A> used by <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/package-summary.html">org.apache.hadoop.chukwa.datacollection.agent</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/AdaptorManager.html#org.apache.hadoop.chukwa.datacollection.agent"><B>AdaptorManager</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The interface to the agent that is exposed to adaptors.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/ChukwaAgent.html#org.apache.hadoop.chukwa.datacollection.agent"><B>ChukwaAgent</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The local agent daemon that runs on each machine.</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/ChukwaAgent.AlreadyRunningException.html#org.apache.hadoop.chukwa.datacollection.agent"><B>ChukwaAgent.AlreadyRunningException</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/ChukwaAgent.Offset.html#org.apache.hadoop.chukwa.datacollection.agent"><B>ChukwaAgent.Offset</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.chukwa.datacollection.connector.http"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/package-summary.html">org.apache.hadoop.chukwa.datacollection.agent</A> used by <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/connector/http/package-summary.html">org.apache.hadoop.chukwa.datacollection.connector.http</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/ChukwaAgent.html#org.apache.hadoop.chukwa.datacollection.connector.http"><B>ChukwaAgent</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The local agent daemon that runs on each machine.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.chukwa.datacollection.sender"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/package-summary.html">org.apache.hadoop.chukwa.datacollection.agent</A> used by <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/sender/package-summary.html">org.apache.hadoop.chukwa.datacollection.sender</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/AdaptorResetThread.html#org.apache.hadoop.chukwa.datacollection.sender"><B>AdaptorResetThread</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/ChukwaAgent.html#org.apache.hadoop.chukwa.datacollection.sender"><B>ChukwaAgent</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The local agent daemon that runs on each machine.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.chukwa.datacollection.test"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/package-summary.html">org.apache.hadoop.chukwa.datacollection.agent</A> used by <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/test/package-summary.html">org.apache.hadoop.chukwa.datacollection.test</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/ChukwaAgent.html#org.apache.hadoop.chukwa.datacollection.test"><B>ChukwaAgent</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The local agent daemon that runs on each machine.</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.hadoop.chukwa.util"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Classes in <A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/package-summary.html">org.apache.hadoop.chukwa.datacollection.agent</A> used by <A HREF="../../../../../../org/apache/hadoop/chukwa/util/package-summary.html">org.apache.hadoop.chukwa.util</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><B><A HREF="../../../../../../org/apache/hadoop/chukwa/datacollection/agent/class-use/AdaptorManager.html#org.apache.hadoop.chukwa.util"><B>AdaptorManager</B></A></B> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;The interface to the agent that is exposed to adaptors.</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/hadoop/chukwa/datacollection/agent/package-use.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-use.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &copy; ${year} The Apache Software Foundation </BODY> </HTML>
{'content_hash': 'c5b444012c84034df14012d91626aa61', 'timestamp': '', 'source': 'github', 'line_count': 289, 'max_line_length': 338, 'avg_line_length': 49.43944636678201, 'alnum_prop': 0.6602743561030235, 'repo_name': 'intel-hadoop/HiTune', 'id': '62e98a9452d8318c613e48ffde05f9ad34e622fe', 'size': '14288', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'chukwa-hitune-dist/docs/api/org/apache/hadoop/chukwa/datacollection/agent/package-use.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2358813'}, {'name': 'JavaScript', 'bytes': '815932'}, {'name': 'Perl', 'bytes': '9633'}, {'name': 'Racket', 'bytes': '3118'}, {'name': 'Shell', 'bytes': '67322'}, {'name': 'XML', 'bytes': '1335'}]}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_26) on Sat Jun 21 06:31:08 UTC 2014 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> org.apache.hadoop.streaming (Apache Hadoop Main 2.4.1 API) </TITLE> <META NAME="date" CONTENT="2014-06-21"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../org/apache/hadoop/streaming/package-summary.html" target="classFrame">org.apache.hadoop.streaming</A></FONT> </BODY> </HTML>
{'content_hash': 'fa1ca856404e4a1d1ec68b7b65960409', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 129, 'avg_line_length': 32.09090909090909, 'alnum_prop': 0.669971671388102, 'repo_name': 'devansh2015/hadoop-2.4.1', 'id': '8e313c68e7625c1470b0b0a3b7416ed80e558d8f', 'size': '706', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'share/doc/hadoop/api/org/apache/hadoop/streaming/package-frame.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '94903'}, {'name': 'C', 'bytes': '29267'}, {'name': 'C++', 'bytes': '16604'}, {'name': 'CSS', 'bytes': '430608'}, {'name': 'HTML', 'bytes': '61553856'}, {'name': 'JavaScript', 'bytes': '15941'}, {'name': 'Shell', 'bytes': '170866'}, {'name': 'XSLT', 'bytes': '21772'}]}
<h1><?php tre("Caching") ?></h1> <?php trhe(" <p> Since pages may contain numerous translation keys, it is crucial that Tml is backed by a caching mechanism. The caching mechanism provides a local cache of the Tml objects retrieved from the service. When users view the pages in non-translation mode, the translations will be served from the cache. For translators, who enable inline translation mode, the SDK will always request the Tml service to get the most recent translations. </p> <p> Tml supports a number of various Cache adapters. To change cache settings, modify config/config.json file. </p> ") ?> <pre><code class="language-javascript">"cache": { "enabled": true, "adapter": "memcache", "host": "localhost", "port": "11211", "version": 1, "timeout": 3600 }</code></pre> <?php include('_file.php'); ?> <?php include('_chdb.php'); ?> <?php include('_apc.php'); ?> <?php include('_memcache.php'); ?> <?php include('_memcached.php'); ?> <?php include('_redis.php'); ?>
{'content_hash': 'a56a4e45444c871fc72091c9bcea178a', 'timestamp': '', 'source': 'github', 'line_count': 33, 'max_line_length': 198, 'avg_line_length': 31.666666666666668, 'alnum_prop': 0.6593301435406699, 'repo_name': 'translationexchange/tml-php', 'id': '7f6114a767e293ac39de45d611000493a0cba63e', 'size': '1045', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'public/www/caching/_index.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '27381'}, {'name': 'HTML', 'bytes': '176652'}, {'name': 'JavaScript', 'bytes': '25866'}, {'name': 'PHP', 'bytes': '625551'}, {'name': 'Ruby', 'bytes': '3405'}, {'name': 'Shell', 'bytes': '52'}]}
#pragma once #include <exception> #include <string> namespace tiny_cnn { /** * basic exception class for tiny-cnn **/ class nn_error : public std::exception { public: explicit nn_error(const std::string& msg) : msg_(msg) {} const char* what() const throw() override { return msg_.c_str(); } private: std::string msg_; }; class nn_not_implemented_error : public nn_error { public: explicit nn_not_implemented_error(const std::string& msg = "not implemented") : nn_error(msg) {} }; } // namespace tiny_cnn
{'content_hash': 'd60c803203fe6f91c9a55712240dd9c0', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 100, 'avg_line_length': 21.958333333333332, 'alnum_prop': 0.6679316888045541, 'repo_name': 'nladuo/captcha-break', 'id': '0e84540abe6ab15f61970a22fe7ae2d309eaaa70', 'size': '2106', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'weibo.cn/cpp/recognizer/tiny_cnn/util/nn_error.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C++', 'bytes': '745570'}, {'name': 'CMake', 'bytes': '5078'}, {'name': 'Jupyter Notebook', 'bytes': '42961'}, {'name': 'Python', 'bytes': '61370'}]}
cask 'fantastical' do version '2.5.5' sha256 '8742c31b5d1697b847ec97ae9a847cb6f3b6168b12786005cad468df5ff9df19' url "http://cdn.flexibits.com/Fantastical_#{version}.zip" appcast "https://flexibits.com/fantastical/appcast#{version.major}.php" name 'Fantastical' homepage 'https://flexibits.com/fantastical' auto_updates true app "Fantastical #{version.major}.app" uninstall launchctl: "com.flexibits.fantastical#{version.major}.mac.launcher", quit: "com.flexibits.fantastical#{version.major}.mac" zap trash: [ '~/Library/Preferences/com.flexibits.fantastical.plist', '~/Library/Application Scripts/com.flexibits.fbcaldav.*', "~/Library/Application Scripts/com.flexibits.fantastical#{version.major}.*", '~/Library/Containers/com.flexibits.fbcaldav.*', "~/Library/Containers/com.flexibits.fantastical#{version.major}.*", ] end
{'content_hash': 'b919dc3f4fbb5387a152166cb0f32e8d', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 91, 'avg_line_length': 39.75, 'alnum_prop': 0.6802935010482181, 'repo_name': 'victorpopkov/homebrew-cask', 'id': 'a932bbd6627ea01c6ba033dc73f69624e2d834dd', 'size': '954', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'Casks/fantastical.rb', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Ruby', 'bytes': '2195663'}, {'name': 'Shell', 'bytes': '35032'}]}
package ttyname import ( "os" "path/filepath" "github.com/EricLagergren/go-gnulib/dirent" "github.com/EricLagergren/go-gnulib/util" "golang.org/x/sys/unix" ) const ( dev = "/dev/" proc = "/proc/self/fd/0" ) var ( searchDevs = []string{ "/dev/pts/", "/dev/console", "/dev/wscons", "/dev/vt/", "/dev/term/", "/dev/zcons/", } stat = &unix.Stat_t{} ) // recursively walk through the directory at path until the correct device // is found. Directories in searchDevs are automatically skipped. func checkDirs(path string) (string, error) { var ( rs string nameBuf = make([]byte, 256) ) stream, err := dirent.Open(path) if err != nil { return "", err } defer stream.Close() dirBuf := stream.ReadAll() for _, v := range dirBuf { // quickly skip most entries if v.Ino != stat.Ino { continue } _ = copy(nameBuf, util.Int8ToByte(v.Name[:])) name := filepath.Join(path, string(nameBuf[:util.Clen(nameBuf)])) // Directories to skip if name == "/dev/stderr" || name == "/dev/stdin" || name == "/dev/stdout" || (len(name) >= 8 && name[0:8] == "/dev/fd/") { continue } // We have to stat the file to determine its Rdev fstat := &unix.Stat_t{} err = unix.Stat(name, fstat) if err != nil { continue } // file mode sans permission bits if os.FileMode(fstat.Mode).IsDir() { rs, err = checkDirs(name) if err != nil { continue } return rs, nil } if isProperDevice(fstat, stat) { return name, nil } } return "", ErrNotFound } func isProperDevice(fstat, stat *unix.Stat_t) bool { return os.FileMode(fstat.Mode)&os.ModeCharDevice == 0 && fstat.Ino == stat.Ino && fstat.Dev == stat.Dev } // Returns a string from a uintptr describing a file descriptor func ttyname(fd uintptr) (string, error) { var name string // Does `fd` even describe a terminal? ;) if !IsAtty(fd) { return "", ErrNotTty } // Gather inode and rdev info about fd err := unix.Fstat(int(fd), stat) if err != nil { return "", err } // Needs to be a character device if os.FileMode(stat.Mode)&os.ModeCharDevice != 0 { return "", ErrNotTty } // strace of GNU's tty stats the return of readlink(/proc/self/fd) // let's do that instead, and fall back on searching /dev/ if ret, _ := os.Readlink(proc); ret != "" { fstat := &unix.Stat_t{} _ = unix.Stat(ret, fstat) if isProperDevice(fstat, stat) { return ret, nil } } // Loop over most likely directories second for _, v := range searchDevs { name, _ = checkDirs(v) if name != "" { return name, nil } } // If we can't find it above, do full scan of /dev/ if name == "" { return checkDirs("/dev/") } return "", ErrNotFound }
{'content_hash': 'c9c2c19ae04755333ceb5e6de65dde9f', 'timestamp': '', 'source': 'github', 'line_count': 141, 'max_line_length': 74, 'avg_line_length': 19.23404255319149, 'alnum_prop': 0.6194690265486725, 'repo_name': 'stephane-martin/skewer', 'id': '11d298a73d876ae43114f7b24a126c8690342c8a', 'size': '2712', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'vendor/github.com/EricLagergren/go-gnulib/ttyname/ttyname_linux.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '1917'}, {'name': 'Go', 'bytes': '986780'}, {'name': 'Makefile', 'bytes': '5739'}]}
Psycopg is the most popular PostgreSQL database adapter for the Python programming language. Its main features are the complete implementation of the Python DB API 2.0 specification and the thread safety (several threads can share the same connection). It was designed for heavily multi-threaded applications that create and destroy lots of cursors and make a large number of concurrent "INSERT"s or "UPDATE"s. Psycopg 2 is mostly implemented in C as a libpq wrapper, resulting in being both efficient and secure. It features client-side and server-side cursors, asynchronous communication and notifications, "COPY TO/COPY FROM" support. Many Python types are supported out-of-the-box and adapted to matching PostgreSQL data types; adaptation can be extended and customized thanks to a flexible objects adaptation system. Psycopg 2 is both Unicode and Python 3 friendly. Documentation ------------- Documentation is included in the 'doc' directory and is `available online`__. .. __: http://initd.org/psycopg/docs/ Installation ------------ If your ``pip`` version supports wheel_ packages it should be possible to install a binary version of Psycopg including all the dependencies. Just run:: pip install psycopg2 If you want to build Psycopg from source you will need some prerequisite (a C compiler, Python and libpq development packages). If you have what you need the standard:: python setup.py build sudo python setup.py install should work no problem. In case you have any problem check the 'install' and the 'faq' documents in the docs or online__. .. _wheel: http://pythonwheels.com/ .. __: http://initd.org/psycopg/docs/install.html#install-from-source For any other resource (source code repository, bug tracker, mailing list) please check the `project homepage`__. .. __: http://initd.org/psycopg/ :Linux/OSX: |travis| :Windows: |appveyor| .. |travis| image:: https://travis-ci.org/psycopg/psycopg2.svg?branch=master :target: https://travis-ci.org/psycopg/psycopg2 :alt: Linux and OSX build status .. |appveyor| image:: https://ci.appveyor.com/api/projects/status/github/psycopg/psycopg2?branch=master&svg=true :target: https://ci.appveyor.com/project/psycopg/psycopg2 :alt: Windows build status
{'content_hash': '028dd3acabe5ea417098e76b1d7eee13', 'timestamp': '', 'source': 'github', 'line_count': 64, 'max_line_length': 112, 'avg_line_length': 35.34375, 'alnum_prop': 0.7586206896551724, 'repo_name': 'IKholopov/HackUPC2017', 'id': '8948310a3d2c82ac15c94673ed883cf9516d6106', 'size': '2262', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'hackupc/env/lib/python3.5/site-packages/psycopg2-2.7.dist-info/DESCRIPTION.rst', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '63043'}, {'name': 'HTML', 'bytes': '40996'}, {'name': 'JavaScript', 'bytes': '272171'}, {'name': 'Python', 'bytes': '40280'}]}
const alertInstance = ( <Alert bsStyle="warning"> <strong>Holy guacamole!</strong> Best check yo self, you're not looking too good. </Alert> ); ReactDOM.render(alertInstance, mountNode);
{'content_hash': '69cbe93122a3472e359b6595e8b9df2d', 'timestamp': '', 'source': 'github', 'line_count': 7, 'max_line_length': 85, 'avg_line_length': 28.0, 'alnum_prop': 0.7142857142857143, 'repo_name': 'apkiernan/react-bootstrap', 'id': 'f6d723b856d8f17d5dfca9e0207c918ad372359d', 'size': '196', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'docs/examples/AlertBasic.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '462841'}]}
'use strict'; let savingIndicatorTimeout; function resetSettings() { browser.storage.sync.clear().then(getSettings).then(resetViewState, logError).then(_showSavingIndicator); } function init() { const clearButton = document.getElementById('clear'); if (clearButton) { clearButton.addEventListener('click', resetSettings); } return getSettings().then((settings) => { const checkboxes = document.querySelectorAll('input[type=checkbox]'); checkboxes.forEach((checkbox) => { checkbox.addEventListener('change', _onCheckboxChange); }); const textinputs = document.querySelectorAll('input[type=text]'); textinputs.forEach((textinput) => { textinput.addEventListener('input', _onTextinputChange); }); resetViewState(settings); console.log('Options initialized'); }, logError); } function resetViewState(settings) { _setCheckboxes(settings); _setTextinputs(settings); console.log('Options view set to settings.'); } function _setCheckboxes(result) { Object.keys(result).forEach((key) => { const checkbox = document.getElementById(key); if (checkbox) { checkbox.checked = !!result[key]; } }); } function _onCheckboxChange(event) { _saveSetting(event.target.id, event.target.checked); } function _saveSetting(id, value) { const update = {}; update[id] = value; browser.storage.sync.set(update).then(_showSavingIndicator); } function _setTextinputs(result) { Object.keys(result).forEach((key) => { const textinput = document.getElementById(key); if (textinput) { textinput.value = result[key]; } }); } function _onTextinputChange(event) { _saveSetting(event.target.id, event.target.value); } function _showSavingIndicator() { const indicator = document.getElementById('savingindicator'); indicator.classList.add('saved'); if (savingIndicatorTimeout) { clearTimeout(savingIndicatorTimeout); } savingIndicatorTimeout = setTimeout(() => { indicator.classList.remove('saved'); }, 1000); } window.addEventListener('load', init); window.tests = { options: { init, _onTextinputChange, _showSavingIndicator, }, };
{'content_hash': 'e0b6bffe15ab417e9ea9423a54cfff68', 'timestamp': '', 'source': 'github', 'line_count': 88, 'max_line_length': 109, 'avg_line_length': 26.386363636363637, 'alnum_prop': 0.64900947459087, 'repo_name': 'gopasspw/gopassbridge', 'id': '39f292175a6fbbffaef12a471c99fabe5856e933', 'size': '2322', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'web-extension/options.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5230'}, {'name': 'Go', 'bytes': '247'}, {'name': 'HTML', 'bytes': '74113'}, {'name': 'JavaScript', 'bytes': '141551'}, {'name': 'Makefile', 'bytes': '1379'}, {'name': 'Shell', 'bytes': '167'}]}
<form name="alForm"> <div class="w3-margin-bottom"> <label>Namn: </label> <input type="text" class="w3-input w3-border w3-hover-border-black" required ng-model="allergenForm.data.name"> </div> <div class="w3-row w3-margin-bottom"> <button class="w3-btn w3-green" ng-click="submitAllergenForm()">Spara</button> </div> </form>
{'content_hash': 'a74b4f2c3342b6b8fad5ebf4675bccd5', 'timestamp': '', 'source': 'github', 'line_count': 12, 'max_line_length': 113, 'avg_line_length': 27.75, 'alnum_prop': 0.6966966966966966, 'repo_name': 'lacrossebjorne/ServiceExperienceTool', 'id': 'fcc9a9da25971c984bdff7a1e692dd6db827792a', 'size': '334', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ServiceExperienceTool/WebContent/app/menu/edit/allergenform.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '150591'}, {'name': 'HTML', 'bytes': '135465'}, {'name': 'Java', 'bytes': '180867'}, {'name': 'JavaScript', 'bytes': '646299'}]}
throw new Error( 'In Angular CLI >6.0 the Karma plugin is now exported by "@angular-devkit/build-angular" instead.\n' + 'Please replace "@angular/cli" with "@angular-devkit/build-angular" in your "karma.conf.js" file.' );
{'content_hash': '3f48f9b0b21b55d0a3184f6cb2f9920c', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 102, 'avg_line_length': 56.5, 'alnum_prop': 0.7168141592920354, 'repo_name': 'maxime1992/angular-cli', 'id': '821352a15b43a9bebe6a90499167e8e0add8ea28', 'size': '226', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'packages/@angular/cli/plugins/karma.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '414'}, {'name': 'HTML', 'bytes': '2927'}, {'name': 'JavaScript', 'bytes': '40723'}, {'name': 'TypeScript', 'bytes': '427211'}]}
require File.expand_path('../boot', __FILE__) require 'rails/all' Bundler.require(*Rails.groups) require "view_data" module Dummy class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de end end
{'content_hash': '3220247366595d72bded1aafc475bba6', 'timestamp': '', 'source': 'github', 'line_count': 23, 'max_line_length': 99, 'avg_line_length': 38.391304347826086, 'alnum_prop': 0.7078142695356738, 'repo_name': 'halenohi/view_data', 'id': '2cc2c41c3ec886d7d9770eaa333de34cbb933945', 'size': '883', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'spec/dummy/config/application.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1366'}, {'name': 'JavaScript', 'bytes': '1198'}, {'name': 'Ruby', 'bytes': '36154'}]}
import os import sys sys.path.insert(0, os.path.abspath(os.path.join('..', 'src'))) import alabaster import rr.opt.mcts.simple as mcts # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = ["alabaster", "sphinx.ext.autodoc", "sphinx.ext.napoleon", "sphinx.ext.mathjax"] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. # # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = 'rr.opt.mcts.simple' copyright = '2016, Rui Rei' author = 'Rui Rei' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = mcts.__version__ # The full version, including alpha/beta/rc tags. release = mcts.__version__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # # today = '' # # Else, today_fmt is used as the format for a strftime call. # # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. # This patterns also effect to html_static_path and html_extra_path exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store'] # The reST default role (used for this markup: `text`) to use for all # documents. # # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. # html_theme = 'alabaster' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # # html_theme_options = {} html_theme_options = { 'logo': 'logo.png', 'logo_name': True, 'logo_text_align': 'center', 'body_text_align': 'justify', 'description': 'Simple Monte Carlo tree search for optimization.', 'show_related': True, 'page_width': '75%', } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = [alabaster.get_path()] # The name for this set of Sphinx documents. # "<project> v<release> documentation" by default. # # html_title = 'rr.opt.mcts.simple v0.1.0' # A shorter title for the navigation bar. Default is the same as html_title. # # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # # html_logo = None # The name of an image file (relative to this directory) to use as a favicon of # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = "_static/favicon.ico" # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # # html_extra_path = [] # If not None, a 'Last updated on:' timestamp is inserted at every page # bottom, using the given strftime format. # The empty string is equivalent to '%b %d, %Y'. # # html_last_updated_fmt = None # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = { '**': [ 'about.html', 'localtoc.html', 'relations.html', 'searchbox.html', ], } # Additional templates that should be rendered to pages, maps page names to # template names. # # html_additional_pages = {} # If false, no module index is generated. # # html_domain_indices = True # If false, no index is generated. # html_use_index = False # If true, the index is split into individual pages for each letter. # # html_split_index = False # If true, links to the reST sources are added to the pages. # # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr', 'zh' # # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # 'ja' uses this config value. # 'zh' user can custom change `jieba` dictionary path. # # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'rroptmctssimpledoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # # 'preamble': '', # Latex figure (float) alignment # # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'rroptmctssimple.tex', 'rr.opt.mcts.simple Documentation', 'Rui Jorge Rei', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. # # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # # latex_use_parts = False # If true, show page references after internal links. # # latex_show_pagerefs = False # If true, show URL addresses after external links. # # latex_show_urls = False # Documents to append as an appendix to all manuals. # # latex_appendices = [] # If false, no module index is generated. # # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'rroptmctssimple', 'rr.opt.mcts.simple Documentation', [author], 1) ] # If true, show URL addresses after external links. # # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'rroptmctssimple', 'rr.opt.mcts.simple Documentation', author, 'rroptmctssimple', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. # # texinfo_appendices = [] # If false, no module index is generated. # # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # # texinfo_no_detailmenu = False
{'content_hash': '65237f6f2a43ac34c951df56e3bcab61', 'timestamp': '', 'source': 'github', 'line_count': 332, 'max_line_length': 93, 'avg_line_length': 28.771084337349397, 'alnum_prop': 0.6841499162479062, 'repo_name': '2xR/rr.opt.mcts.basic', 'id': 'a9a6eae6f073e3c0ae12a6406b543607b97613be', 'size': '10246', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'docs/conf.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Python', 'bytes': '42407'}]}
#include "globus_common.h" #include "globus_error.h" #include "globus_gsi_cert_utils.h" #include "globus_gsi_system_config.h" #include "globus_gsi_proxy.h" #include "globus_gsi_credential.h" #include "globus_stdio_ui.h" #include "openssl/asn1.h" #define PROXYCERTINFO_OLD_OID "1.3.6.1.4.1.3536.1.222" #define SHORT_USAGE_FORMAT \ "\nSyntax: %s [-help][-pwstdin][-limited][-valid H:M] ...\n" static int quiet = 0; static int debug = 0; static char * LONG_USAGE = \ "\n" \ " Options\n" \ " -help, -usage Displays usage\n" \ " -version Displays version\n" \ " -debug Enables extra debug output\n" \ " -q Quiet mode, minimal output\n" \ " -verify Verifies certificate to make proxy for\n" \ " -pwstdin Allows passphrase from stdin\n" \ " -limited Creates a limited proxy\n" \ " -independent Creates a independent proxy\n" \ " -draft Creates a draft (GSI-3) proxy\n" \ " -old Creates a legacy globus proxy\n" \ " -rfc Creates a RFC 3820 compliant proxy\n" \ " -valid <h:m> Proxy is valid for h hours and m \n" \ " minutes (default:12:00)\n" \ " -hours <hours> Deprecated support of hours option\n" \ " -bits <bits> Number of bits in key {512|1024|2048|4096}\n" \ " -policy <policyfile> File containing policy to store in the\n" \ " ProxyCertInfo extension\n" \ " -pl <oid>, OID string for the policy language\n" \ " -policy-language <oid> used in the policy file\n" \ " -path-length <l> Allow a chain of at most l proxies to be \n" \ " generated from this one\n" \ " -cert <certfile> Non-standard location of user certificate\n" \ " -key <keyfile> Non-standard location of user key\n" \ " -certdir <certdir> Non-standard location of trusted cert dir\n" \ " -out <proxyfile> Non-standard location of new proxy cert\n" \ "\n" ; # define args_show_version() \ { \ char buf[64]; \ sprintf( buf, \ "%s-%s", \ PACKAGE, \ VERSION); \ fprintf(stderr, "%s\n", buf); \ globus_module_deactivate_all(); \ exit(0); \ } # define args_show_short_help() \ { \ fprintf(stderr, \ SHORT_USAGE_FORMAT \ "\nUse -help to display full usage.\n", \ program); \ globus_module_deactivate_all(); \ } # define args_show_full_usage() \ { \ fprintf(stderr, SHORT_USAGE_FORMAT \ "%s", \ program, \ LONG_USAGE); \ globus_module_deactivate_all(); \ exit(0); \ } # define args_error_message(errmsg) \ { \ fprintf(stderr, "\nERROR: %s\n", errmsg); \ args_show_short_help(); \ globus_module_deactivate_all(); \ exit(1); \ } # define args_error(argval, errmsg) \ { \ char buf[1024]; \ sprintf(buf, "option %s : %s", argval, errmsg); \ args_error_message(buf); \ } # define args_verify_next(argnum, argval, errmsg) \ { \ if ((argnum+1 >= argc) || (argv[argnum+1][0] == '-')) \ args_error(argval,errmsg); \ } void globus_i_gsi_proxy_utils_print_error( globus_result_t result, int debug, const char * filename, int line, const char * fmt, ...); static int globus_i_gsi_proxy_utils_pwstdin_callback( char * buf, int num, int w); static void globus_i_gsi_proxy_utils_key_gen_callback( int p, int n, void * dummy); static int globus_l_gsi_proxy_utils_extension_callback( globus_gsi_callback_data_t callback_data, X509_EXTENSION * extension); int main( int argc, char ** argv) { globus_result_t result = GLOBUS_SUCCESS; /* default proxy to 2048 bits */ int key_bits = 2048; /* default to a 12 hour cert */ int valid = 12*60; int verify = 0; int arg_index; char * user_cert_filename = NULL; char * user_key_filename = NULL; char * tmp_user_cert_filename = NULL; char * tmp_user_key_filename = NULL; char * proxy_out_filename = NULL; char * ca_cert_dir = NULL; char * argp; char * program = NULL; globus_gsi_proxy_handle_t proxy_handle = NULL; globus_gsi_proxy_handle_attrs_t proxy_handle_attrs = NULL; globus_gsi_callback_data_t callback_data = NULL; globus_gsi_cred_handle_t cred_handle = NULL; globus_gsi_cred_handle_t proxy_cred_handle = NULL; globus_gsi_cert_utils_cert_type_t cert_type = 0; BIO * pem_proxy_bio = NULL; time_t goodtill; time_t lifetime; unsigned char * policy_buf = NULL; size_t policy_buf_len = 0; char * policy_filename = NULL; char * policy_language = NULL; int policy_NID; long path_length = -1; int (*pw_cb)() = NULL; int return_value = 0; if(globus_module_activate(GLOBUS_GSI_PROXY_MODULE) != (int)GLOBUS_SUCCESS) { globus_libc_fprintf( stderr, "\nERROR: Couldn't load module: GLOBUS_GSI_PROXY_MODULE.\n" "Make sure Globus is installed correctly.\n\n"); exit(1); } if(globus_module_activate(GLOBUS_GSI_CALLBACK_MODULE) != (int)GLOBUS_SUCCESS) { globus_libc_fprintf( stderr, "\nERROR: Couldn't load module: GLOBUS_GSI_CALLBACK_MODULE.\n" "Make sure Globus is installed correctly.\n\n"); globus_module_deactivate_all(); exit(1); } /* get the program name */ if (strrchr(argv[0], '/')) { program = strrchr(argv[0], '/') + 1; } else { program = argv[0]; } /* parse the arguments */ for(arg_index = 1; arg_index < argc; ++arg_index) { argp = argv[arg_index]; if (strncmp(argp, "--", 2) == 0) { if (argp[2] != '\0') { args_error(argp, "double-dashed options are not allowed"); } else { /* no more parsing */ arg_index = argc + 1; continue; } } if((strcmp(argp, "-help") == 0) || (strcmp(argp, "-usage") == 0)) { args_show_full_usage(); } else if(strcmp(argp, "-version") == 0) { args_show_version(); } else if(strcmp(argp, "-cert") == 0) { args_verify_next(arg_index, argp, "need a file name argument"); user_cert_filename = argv[++arg_index]; result = GLOBUS_GSI_SYSCONFIG_CHECK_CERTFILE(user_cert_filename); if(result != GLOBUS_SUCCESS) { args_error(argp, globus_error_print_friendly( globus_error_get(result))); } } else if(strcmp(argp, "-certdir") == 0) { args_verify_next(arg_index, argp, "need a file name argument"); ca_cert_dir = strdup(argv[++arg_index]); result = GLOBUS_GSI_SYSCONFIG_DIR_EXISTS(ca_cert_dir); if(result != GLOBUS_SUCCESS) { args_error(argp, globus_error_print_friendly( globus_error_get(result))); } } else if(strcmp(argp, "-out") == 0) { args_verify_next(arg_index, argp, "need a file name argument"); proxy_out_filename = strdup(argv[++arg_index]); } else if(strcmp(argp, "-key") == 0) { args_verify_next(arg_index, argp, "need a file name argument"); user_key_filename = argv[++arg_index]; result = GLOBUS_GSI_SYSCONFIG_CHECK_KEYFILE(user_key_filename); if(result != GLOBUS_SUCCESS) { args_error(argp, globus_error_print_friendly( globus_error_get(result))); } } else if(strcmp(argp, "-valid") == 0) { int hours; int minutes; args_verify_next(arg_index, argp, "valid time argument H:M missing"); if(sscanf(argv[++arg_index], "%d:%d", &hours, &minutes) < 2) { args_error(argp, "value must be in the format: H:M"); } if(hours < 0) { args_error(argp, "specified hours must be a non-negative integer"); } if(minutes < 0 || minutes > 60) { args_error(argp, "specified minutes must " "be in the range 0-60"); } /* error on overflow */ if(hours > (((time_t)(~0U>>1))/3600-1)) { hours = (((time_t)(~0U>>1))/3600-1); } valid = (hours * 60) + minutes; } else if(strcmp(argp, "-hours") == 0) { int hours; args_verify_next(arg_index, argp, "integer argument missing"); hours = atoi(argv[arg_index + 1]); /* error on overflow */ if(hours > ((time_t)(~0U>>1))/3600) { hours = ((time_t)(~0U>>1))/3600; } valid = hours * 60; arg_index++; } else if(strcmp(argp, "-bits") == 0) { args_verify_next(arg_index, argp, "integer argument missing"); key_bits = atoi(argv[arg_index + 1]); if((key_bits != 512) && (key_bits != 1024) && (key_bits != 2048) && (key_bits != 4096)) { args_error(argp, "value must be one of 512,1024,2048,4096"); } arg_index++; } else if(strcmp(argp, "-debug") == 0) { debug++; } else if(strcmp(argp, "-limited") == 0) { if (cert_type & GLOBUS_GSI_CERT_UTILS_TYPE_PROXY_MASK) { args_error(argp, "-independent, -limited and -policy/-policy-language are mutually exclusive"); } else { cert_type |= GLOBUS_GSI_CERT_UTILS_TYPE_LIMITED_PROXY; } } else if(strcmp(argp, "-independent") == 0) { if (cert_type & GLOBUS_GSI_CERT_UTILS_TYPE_PROXY_MASK) { args_error(argp, "-independent, -limited and -policy/-policy-language are mutually exclusive"); } else { cert_type |= GLOBUS_GSI_CERT_UTILS_TYPE_INDEPENDENT_PROXY; } } else if(strcmp(argp, "-old") == 0) { if ((cert_type & GLOBUS_GSI_CERT_UTILS_TYPE_FORMAT_MASK) != 0) { args_error(argp, "-old, -rfc, and -draft are mutually exclusive"); } else { cert_type |= GLOBUS_GSI_CERT_UTILS_TYPE_GSI_2; } } else if(strcmp(argp, "-rfc") == 0) { if ((cert_type & GLOBUS_GSI_CERT_UTILS_TYPE_FORMAT_MASK) != 0) { args_error(argp, "-old, -rfc, and -draft are mutually exclusive"); } else { cert_type |= GLOBUS_GSI_CERT_UTILS_TYPE_RFC; } } else if(strcmp(argp, "-draft") == 0) { if ((cert_type & GLOBUS_GSI_CERT_UTILS_TYPE_FORMAT_MASK) != 0) { args_error(argp, "-old, -rfc, and -draft are mutually exclusive"); } else { cert_type |= GLOBUS_GSI_CERT_UTILS_TYPE_GSI_3; } } else if(strcmp(argp, "-verify") == 0) { verify++; } else if(strcmp(argp, "-q") == 0) { quiet++; } else if(strcmp(argp, "-pwstdin") == 0) { pw_cb = globus_i_gsi_proxy_utils_pwstdin_callback; } else if(strcmp(argp, "-policy") == 0) { if ((cert_type & GLOBUS_GSI_CERT_UTILS_TYPE_PROXY_MASK) != 0 && (cert_type & GLOBUS_GSI_CERT_UTILS_TYPE_PROXY_MASK) != GLOBUS_GSI_CERT_UTILS_TYPE_RESTRICTED_PROXY) { args_error(argp, "-independent, -limited and -policy/-policy-language are mutually exclusive"); } args_verify_next(arg_index, argp, "policy file name missing"); policy_filename = argv[++arg_index]; cert_type |= GLOBUS_GSI_CERT_UTILS_TYPE_RESTRICTED_PROXY; } else if(strcmp(argp, "-pl") == 0 || strcmp(argp, "-policy-language") == 0) { if ((cert_type & GLOBUS_GSI_CERT_UTILS_TYPE_PROXY_MASK) != 0 && (cert_type & GLOBUS_GSI_CERT_UTILS_TYPE_PROXY_MASK) != GLOBUS_GSI_CERT_UTILS_TYPE_RESTRICTED_PROXY) { args_error(argp, "-independent, -limited and -policy/-policy-language are mutually exclusive"); } args_verify_next(arg_index, argp, "policy language missing"); policy_language = argv[++arg_index]; cert_type |= GLOBUS_GSI_CERT_UTILS_TYPE_RESTRICTED_PROXY; } else if(strcmp(argp, "-path-length") == 0) { char * remaining; args_verify_next(arg_index, argp, "integer argument missing"); path_length = strtol(argv[arg_index + 1], &remaining, 0); if(*remaining != '\0') { args_error(argp, "requires an integer argument"); } arg_index++; } else { args_error(argp, "unrecognized option"); } } umask(0077); /* A few sanity checks */ if(policy_filename && !policy_language) { globus_libc_fprintf(stderr, "\nERROR: If you specify a policy file " "you also need to specify a policy language.\n"); exit(1); } result = globus_gsi_proxy_handle_attrs_init(&proxy_handle_attrs); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error(result, debug, __FILE__, __LINE__, "Couldn't initialize " "the proxy handle attributes."); } /* set the key bits for the proxy cert in the proxy handle * attributes */ result = globus_gsi_proxy_handle_attrs_set_keybits( proxy_handle_attrs, key_bits); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't set the key bits for " "the private key of the proxy certificate."); } result = globus_gsi_proxy_handle_attrs_set_key_gen_callback( proxy_handle_attrs, globus_i_gsi_proxy_utils_key_gen_callback); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't set the key generation callback function."); } result = globus_gsi_proxy_handle_init(&proxy_handle, proxy_handle_attrs); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't initialize the proxy handle."); } result = globus_gsi_proxy_handle_attrs_destroy(proxy_handle_attrs); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't destroy proxy handle attributes."); } /* set the time valid in the proxy handle * used to be hours - now the time valid needs to be set in minutes */ result = globus_gsi_proxy_handle_set_time_valid(proxy_handle, valid); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't set the validity time of the proxy cert to %d minutes.", valid); } /* set the type of proxy to be generated */ result = globus_gsi_proxy_handle_set_type(proxy_handle, cert_type); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't set the type of the proxy cert."); } if(!user_cert_filename || !user_key_filename) { result = GLOBUS_GSI_SYSCONFIG_GET_USER_CERT_FILENAME( user_cert_filename ? NULL : &tmp_user_cert_filename, user_key_filename ? NULL : &tmp_user_key_filename); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't find valid credentials to generate a proxy."); } if(tmp_user_cert_filename && tmp_user_cert_filename == tmp_user_key_filename) { /* supposed to be a pkcs12 formated credential */ user_cert_filename = user_key_filename = tmp_user_key_filename; } } if(!user_cert_filename) { user_cert_filename = tmp_user_cert_filename; } if(!user_key_filename) { user_key_filename = tmp_user_key_filename; } if(debug) { globus_libc_fprintf(stderr, "\nUser Cert File: %s\nUser Key File: %s\n", user_cert_filename, user_key_filename); } if (!strncmp(user_cert_filename, "SC:", 3)) { EVP_set_pw_prompt("Enter card pin:"); } else { EVP_set_pw_prompt(quiet? "Enter GRID pass phrase:" : "Enter GRID pass phrase for this identity:"); } if(!ca_cert_dir && verify) { result = GLOBUS_GSI_SYSCONFIG_GET_CERT_DIR(&ca_cert_dir); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't find a valid trusted certificate " "directory."); } } if(debug) { globus_libc_fprintf(stderr, "\nTrusted CA Cert Dir: %s\n", ca_cert_dir ? ca_cert_dir : "(null)"); } if(!proxy_out_filename) { result = GLOBUS_GSI_SYSCONFIG_GET_PROXY_FILENAME( &proxy_out_filename, GLOBUS_PROXY_FILE_OUTPUT); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't find a valid location " "to write the proxy file."); } } else { /* verify that the directory path of proxy_out_filename * exists and is writeable */ char * proxy_absolute_path = NULL; char * temp_filename = NULL; char * temp_dir = NULL; /* first, make absolute path */ result = GLOBUS_GSI_SYSCONFIG_MAKE_ABSOLUTE_PATH_FOR_FILENAME( proxy_out_filename, &proxy_absolute_path); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Can't create the absolute path " "of the proxy filename: %s", proxy_out_filename); } if(proxy_out_filename) { free(proxy_out_filename); } proxy_out_filename = proxy_absolute_path; /* then split */ result = GLOBUS_GSI_SYSCONFIG_SPLIT_DIR_AND_FILENAME( proxy_absolute_path, &temp_dir, &temp_filename); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Can't split the full path into " "directory and filename. The full path is: %s", proxy_absolute_path); if(proxy_absolute_path) { free(proxy_absolute_path); proxy_absolute_path = NULL; } } result = GLOBUS_GSI_SYSCONFIG_DIR_EXISTS(temp_dir); if(result != GLOBUS_SUCCESS) { if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "%s is not a valid directory for writing the " "proxy certificate.", temp_dir); } else { globus_module_deactivate_all(); exit(1); } } if(temp_dir) { free(temp_dir); temp_dir = NULL; } if(temp_filename) { free(temp_filename); temp_filename = NULL; } } if(debug) { globus_libc_fprintf(stderr, "\nOutput File: %s\n", proxy_out_filename); } result = globus_gsi_cred_handle_init(&cred_handle, NULL); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't initialize credential handle."); } if(strstr(user_cert_filename, ".p12")) { if (pw_cb != NULL) { globus_module_activate(GLOBUS_STDIO_UI_MODULE); } /* we have a pkcs12 credential */ result = globus_gsi_cred_read_pkcs12( cred_handle, user_cert_filename); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't read in PKCS12 credential " "from file: %s\n", user_cert_filename); } if (pw_cb != NULL) { globus_module_deactivate(GLOBUS_STDIO_UI_MODULE); } if (!quiet) { char * subject = NULL; result = globus_gsi_cred_get_identity_name(cred_handle, &subject); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "The subject name of the " "user certificate could " "not be retrieved."); } printf("Your identity: %s\n", subject); if(subject) { free(subject); subject = NULL; } } } else { result = globus_gsi_cred_read_cert( cred_handle, user_cert_filename); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't read user certificate\n" "cert file location: %s.", user_cert_filename); } if (!quiet) { char * subject = NULL; result = globus_gsi_cred_get_identity_name(cred_handle, &subject); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "The subject name of the " "user certificate could " "not be retrieved."); } printf("Your identity: %s\n", subject); if(subject) { #ifdef WIN32 X509_free((void *) subject); #else free(subject); #endif subject = NULL; } } result = globus_gsi_cred_read_key( cred_handle, user_key_filename, pw_cb); if(result != GLOBUS_SUCCESS) { globus_object_t * error; error = globus_error_peek(result); if(globus_error_match_openssl_error(error, ERR_LIB_PEM, PEM_F_PEM_DO_HEADER, PEM_R_BAD_DECRYPT) == GLOBUS_TRUE) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't read user key: Bad passphrase for key in %s", user_key_filename); } else { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't read user key in %s.", user_key_filename); } } } /* add path length constraint */ if(path_length >= 0) { result = globus_gsi_proxy_handle_set_pathlen(proxy_handle, path_length); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Can't set the path length in the proxy handle."); } } /* add policies now */ if(policy_filename) { int policy_buf_size = 0; FILE * policy_fp = NULL; policy_fp = fopen(policy_filename, "r"); if(!policy_fp) { fprintf(stderr, "\nERROR: Unable to open policies " " file: %s\n\n", policy_filename); exit(1); } do { policy_buf_size += 512; /* First time through this is a essentially a malloc() */ policy_buf = realloc(policy_buf, policy_buf_size); if (policy_buf == NULL) { fprintf(stderr, "\nAllocation of space for " "policy buffer failed\n\n"); exit(1); } policy_buf_len += fread(&policy_buf[policy_buf_len], 1, 512, policy_fp); /* * If we read 512 bytes then policy_buf_len and * policy_buf_size will be equal and there is * probably more to read. Even if there isn't more * to read, no harm is done, we just allocate 512 * bytes we don't end up using. */ } while (policy_buf_len == policy_buf_size); if (policy_buf_len > 0) { policy_NID = OBJ_create(policy_language, policy_language, policy_language); result = globus_gsi_proxy_handle_set_policy( proxy_handle, policy_buf, policy_buf_len, policy_NID); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Can't set the policy in the proxy handle."); } } fclose(policy_fp); } if (!quiet) { printf("Creating proxy "); fflush(stdout); } result = globus_gsi_proxy_create_signed( proxy_handle, cred_handle, &proxy_cred_handle); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't create proxy certificate."); } if (!quiet) { fprintf(stdout, " Done\n"); } if(verify) { result = globus_gsi_callback_data_init(&callback_data); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't initialize callback data for credential " "verification."); } result = globus_gsi_callback_set_extension_cb( callback_data, globus_l_gsi_proxy_utils_extension_callback); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't set the X.509 extension callback in the callback " "data."); } result = globus_gsi_callback_set_cert_dir( callback_data, ca_cert_dir); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't set the trusted certificate directory in the " "callback data."); } result = globus_gsi_cred_verify_cert_chain( proxy_cred_handle, callback_data); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Couldn't verify the authenticity of the user's " "credential to generate a proxy from."); } globus_libc_fprintf( stdout, "Proxy Verify OK\n"); } else { result = globus_gsi_cred_verify(proxy_cred_handle); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Could not verify the signature of the generated " "proxy certificate.\n" "This is likely due to a non-matching user key and cert."); } } if(ca_cert_dir) { free(ca_cert_dir); ca_cert_dir = NULL; } result = globus_gsi_cred_write_proxy(proxy_cred_handle, proxy_out_filename); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "The proxy credential could not be " "written to the output file: %s.", globus_error_print_friendly(globus_error_peek(result))); } if(proxy_out_filename) { free(proxy_out_filename); proxy_out_filename = NULL; } result = globus_gsi_cred_get_lifetime( cred_handle, &lifetime); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Can't get the lifetime of the proxy credential."); } result = globus_gsi_cred_get_goodtill( proxy_cred_handle, &goodtill); if(result != GLOBUS_SUCCESS) { globus_i_gsi_proxy_utils_print_error( result, debug, __FILE__, __LINE__, "Can't get the expiration date of the proxy credential."); } if(lifetime < 0) { globus_libc_fprintf( stderr, "\nERROR: Your certificate has expired: %s\n\n", asctime(localtime(&goodtill))); globus_module_deactivate_all(); exit(2); } else if(lifetime < (valid * 60)) { globus_libc_fprintf( stderr, "\nWarning: your certificate and proxy will expire %s " "which is within the requested lifetime of the proxy\n", asctime(localtime(&goodtill))); } else if(!quiet) { globus_libc_fprintf( stdout, "Your proxy is valid until: %s", asctime(localtime(&goodtill))); } BIO_free(pem_proxy_bio); globus_gsi_proxy_handle_destroy(proxy_handle); globus_gsi_cred_handle_destroy(cred_handle); globus_gsi_cred_handle_destroy(proxy_cred_handle); globus_gsi_callback_data_destroy(callback_data); if(tmp_user_cert_filename) { free(tmp_user_cert_filename); } if(tmp_user_key_filename) { free(tmp_user_key_filename); } globus_module_deactivate_all(); exit(return_value); } static int globus_i_gsi_proxy_utils_pwstdin_callback( char * buf, int num, int w) { int i; setvbuf(stdin, (char *)NULL, _IONBF, 0); if (!(fgets(buf, num, stdin))) { fprintf(stderr, "Failed to read pass-phrase from stdin\n"); return -1; } i = strlen(buf); if (buf[i-1] == '\n') { buf[i-1] = '\0'; i--; } return i; } static void globus_i_gsi_proxy_utils_key_gen_callback(int p, int n, void * dummy) { char c='B'; if (quiet) return; if (p == 0) c='.'; if (p == 1) c='+'; if (p == 2) c='*'; if (p == 3) c='\n'; if (!debug) c = '.'; fputc(c, stdout); fflush(stdout); } void globus_i_gsi_proxy_utils_print_error( globus_result_t result, int debug, const char * filename, int line, const char * fmt, ...) { globus_object_t * error_obj; char * error_string = NULL; va_list ap; if (fmt == NULL) { debug++; } else { fprintf(stderr, "Error: "); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fprintf(stderr, "\n"); } error_obj = globus_error_get(result); error_string = globus_error_print_chain(error_obj); if(debug) { globus_libc_fprintf(stderr, " %s:%d: %s", filename, line, error_string); } else { globus_libc_fprintf(stderr, "Use -debug for further information.\n"); } if(error_string) { globus_libc_free(error_string); } globus_object_free(error_obj); globus_module_deactivate_all(); exit(1); } static int globus_l_gsi_proxy_utils_extension_callback( globus_gsi_callback_data_t callback_data, X509_EXTENSION * extension) { ASN1_OBJECT * extension_object = NULL; int nid = NID_undef; int pci_old_NID = NID_undef; pci_old_NID = OBJ_txt2nid(PROXYCERTINFO_OLD_OID); extension_object = X509_EXTENSION_get_object(extension); nid = OBJ_obj2nid(extension_object); if (nid == NID_proxyCertInfo || nid == pci_old_NID) { /* Assume that we either put it there or that it will be recognized */ return GLOBUS_TRUE; } else { /* not a PCI extension */ return GLOBUS_FALSE; } }
{'content_hash': 'c34a59c7a9c346fe4744089a31b78e30', 'timestamp': '', 'source': 'github', 'line_count': 1163, 'max_line_length': 115, 'avg_line_length': 31.798796216680998, 'alnum_prop': 0.46252230814991074, 'repo_name': 'ellert/globus-toolkit', 'id': 'd77ba152c703cf297889557e32ed82c5dcfac673', 'size': '37590', 'binary': False, 'copies': '2', 'ref': 'refs/heads/globus_6_branch', 'path': 'gsi/proxy/proxy_utils/source/programs/grid_proxy_init.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '718'}, {'name': 'C', 'bytes': '17148135'}, {'name': 'C++', 'bytes': '114320'}, {'name': 'CSS', 'bytes': '2045'}, {'name': 'HTML', 'bytes': '28754'}, {'name': 'JavaScript', 'bytes': '3884'}, {'name': 'Lex', 'bytes': '18165'}, {'name': 'M4', 'bytes': '198153'}, {'name': 'Makefile', 'bytes': '416932'}, {'name': 'Objective-C', 'bytes': '6886'}, {'name': 'Perl', 'bytes': '970807'}, {'name': 'Perl 6', 'bytes': '1744'}, {'name': 'PowerShell', 'bytes': '7649'}, {'name': 'Python', 'bytes': '286572'}, {'name': 'Roff', 'bytes': '392097'}, {'name': 'Shell', 'bytes': '545199'}, {'name': 'XSLT', 'bytes': '22872'}, {'name': 'Yacc', 'bytes': '23583'}]}
from __future__ import unicode_literals import os.path from taggit.managers import TaggableManager from django.db import models from django.db.models.signals import pre_delete from django.dispatch.dispatcher import receiver from django.dispatch import Signal from django.core.urlresolvers import reverse from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from wagtail.wagtailadmin.taggable import TagSearchable from wagtail.wagtailadmin.utils import get_object_usage from wagtail.wagtailsearch import index @python_2_unicode_compatible class Document(models.Model, TagSearchable): title = models.CharField(max_length=255, verbose_name=_('Title')) file = models.FileField(upload_to='documents', verbose_name=_('File')) created_at = models.DateTimeField(verbose_name=_('Created at'), auto_now_add=True) uploaded_by_user = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name=_('Uploaded by user'), null=True, blank=True, editable=False) tags = TaggableManager(help_text=None, blank=True, verbose_name=_('Tags')) search_fields = TagSearchable.search_fields + ( index.FilterField('uploaded_by_user'), ) def __str__(self): return self.title @property def filename(self): return os.path.basename(self.file.name) @property def file_extension(self): parts = self.filename.split('.') if len(parts) > 1: return parts[-1] else: return '' @property def url(self): return reverse('wagtaildocs_serve', args=[self.id, self.filename]) def get_usage(self): return get_object_usage(self) @property def usage_url(self): return reverse('wagtaildocs_document_usage', args=(self.id,)) def is_editable_by_user(self, user): if user.has_perm('wagtaildocs.change_document'): # user has global permission to change documents return True elif user.has_perm('wagtaildocs.add_document') and self.uploaded_by_user == user: # user has document add permission, which also implicitly provides permission to edit their own documents return True else: return False class Meta: verbose_name = _('Document') # Receive the pre_delete signal and delete the file associated with the model instance. @receiver(pre_delete, sender=Document) def image_delete(sender, instance, **kwargs): # Pass false so FileField doesn't save the model. instance.file.delete(False) document_served = Signal(providing_args=['request'])
{'content_hash': '5b76ab5b0a824ed23661aefe6b3c13d6', 'timestamp': '', 'source': 'github', 'line_count': 82, 'max_line_length': 141, 'avg_line_length': 32.84146341463415, 'alnum_prop': 0.6917935388043075, 'repo_name': 'taedori81/wagtail', 'id': '4919bd78604d91976435e2cadaa821249d34eb4b', 'size': '2693', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'wagtail/wagtaildocs/models.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '148553'}, {'name': 'HTML', 'bytes': '235976'}, {'name': 'JavaScript', 'bytes': '78718'}, {'name': 'Makefile', 'bytes': '548'}, {'name': 'Python', 'bytes': '1336741'}, {'name': 'Ruby', 'bytes': '1275'}, {'name': 'Shell', 'bytes': '11292'}]}