text
stringlengths
4
5.48M
meta
stringlengths
14
6.54k
<?xml version="1.0" encoding="utf-8"?> <!-- ~ Copyright (c) 2020, Nordic Semiconductor ~ All rights reserved. ~ ~ Redistribution and use in source and binary forms, with or without modification, ~ are permitted provided that the following conditions are met: ~ ~ 1. Redistributions of source code must retain the above copyright notice, this ~ list of conditions and the following disclaimer. ~ ~ 2. Redistributions in binary form must reproduce the above copyright notice, this ~ list of conditions and the following disclaimer in the documentation and/or ~ other materials provided with the distribution. ~ ~ 3. Neither the name of the copyright holder nor the names of its contributors may ~ be used to endorse or promote products derived from this software without ~ specific prior written permission. ~ ~ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ~ ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ~ WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ~ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, ~ INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ~ NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR ~ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ~ WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ~ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE ~ POSSIBILITY OF SUCH DAMAGE. ~ --> <adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android"> <background android:drawable="@color/ic_launcher_background"/> <foreground android:drawable="@mipmap/ic_launcher_foreground"/> </adaptive-icon>
{'content_hash': '659fe302c3c0a65891bbbe8dbb0bfdb1', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 86, 'avg_line_length': 52.5, 'alnum_prop': 0.7486772486772487, 'repo_name': 'NordicSemiconductor/nRF-Logger-API', 'id': '7204d5fb1bdc6f41e34d9dc776abcb0b76b370ed', 'size': '1890', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sample/src/main/res/mipmap-anydpi-v26/ic_launcher.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Java', 'bytes': '91165'}]}
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/sync_device_info/device_info_sync_service_impl.h" #include <utility> #include "base/bind_helpers.h" #include "components/sync/base/report_unrecoverable_error.h" #include "components/sync/model_impl/client_tag_based_model_type_processor.h" #include "components/sync_device_info/device_info.h" #include "components/sync_device_info/device_info_prefs.h" #include "components/sync_device_info/device_info_sync_bridge.h" #include "components/sync_device_info/device_info_sync_client.h" #include "components/sync_device_info/device_info_tracker.h" #include "components/sync_device_info/local_device_info_provider.h" namespace syncer { DeviceInfoSyncServiceImpl::DeviceInfoSyncServiceImpl( OnceModelTypeStoreFactory model_type_store_factory, std::unique_ptr<MutableLocalDeviceInfoProvider> local_device_info_provider, std::unique_ptr<DeviceInfoPrefs> device_info_prefs, std::unique_ptr<DeviceInfoSyncClient> device_info_sync_client) : device_info_sync_client_(std::move(device_info_sync_client)) { DCHECK(local_device_info_provider); DCHECK(device_info_prefs); DCHECK(device_info_sync_client_); // Make a copy of the channel to avoid relying on argument evaluation order. const version_info::Channel channel = local_device_info_provider->GetChannel(); bridge_ = std::make_unique<DeviceInfoSyncBridge>( std::move(local_device_info_provider), std::move(model_type_store_factory), std::make_unique<ClientTagBasedModelTypeProcessor>( DEVICE_INFO, /*dump_stack=*/base::BindRepeating(&ReportUnrecoverableError, channel)), std::move(device_info_prefs)); } DeviceInfoSyncServiceImpl::~DeviceInfoSyncServiceImpl() {} LocalDeviceInfoProvider* DeviceInfoSyncServiceImpl::GetLocalDeviceInfoProvider() { return bridge_->GetLocalDeviceInfoProvider(); } DeviceInfoTracker* DeviceInfoSyncServiceImpl::GetDeviceInfoTracker() { return bridge_.get(); } base::WeakPtr<ModelTypeControllerDelegate> DeviceInfoSyncServiceImpl::GetControllerDelegate() { return bridge_->change_processor()->GetControllerDelegate(); } void DeviceInfoSyncServiceImpl::RefreshLocalDeviceInfo() { bridge_->RefreshLocalDeviceInfo(); } } // namespace syncer
{'content_hash': '27db0140f5966ba7da05c2e861d59054', 'timestamp': '', 'source': 'github', 'line_count': 65, 'max_line_length': 79, 'avg_line_length': 37.52307692307692, 'alnum_prop': 0.7548175481754817, 'repo_name': 'endlessm/chromium-browser', 'id': 'ace1de6654ed9affcff4bcd11ad2bb2871743639', 'size': '2439', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'components/sync_device_info/device_info_sync_service_impl.cc', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
static NSString * const STShareTitleKey = @"STShareTitleKey"; ///< 分享标题的 key (title 是 NSString) static NSString * const STShareImageKey = @"STShareImageKey"; ///< 分享图片的 key (传入的是字典,所以这个作为key)(image 是 UIImage) static NSString * const STShareContentKey = @"STShareContentKey"; ///< 分享内容的 key (content 是 NSString) static NSString * const STShareURLKey = @"STShareURLKey"; ///< 分享 url 的 key (url 是 NSString) static NSString * const STShareURL = @"http://www.swift.gg"; ///< 分享的url,实际没用到,写在这占位 static NSString * const STShareQQAppId = @"1105183300"; static NSString * const STShareQQAppKey = @"7xG5PEYoHCx41Es6"; static NSString * const STShareWeiboAppKey = @"2862032238"; static NSString * const STShareWeiboAppSecret = @"2a61af7b29c8562fe440226364cea0b6"; static NSString * const STShareWeiboCallbackURL = @"http://sns.whalecloud.com/sina2/callback"; ///< 微博回调的 url,就是微博申请高级信息里面那个 static NSString * const STShareWechatAppId = @"wx133f6244ca123bb6"; static NSString * const STShareWechatAppSecret = @"ce54fbb731edd5f9f50b12ca8d864405"; static NSString * const STShareUMAppKey = @"507fcab25270157b37000010"; @interface STShareTool : NSObject @property (nonatomic, copy) dispatch_block_t success; ///< 成功回调 @property (nonatomic, copy) dispatch_block_t failure; ///< 失败回调 + (instancetype)toolWithViewController:(UIViewController *)viewController; + (BOOL)canSendMail; - (void)shareToQQ:(NSDictionary *)shareContent; - (void)shareToQZone:(NSDictionary *)shareContent; - (void)shareToWeChatSession:(NSDictionary *)shareContent; - (void)shareToWeChatTimeline:(NSDictionary *)shareContent; - (void)shareToWeibo:(NSDictionary *)shareContent; - (void)shareToMail:(NSDictionary *)shareContent; @end
{'content_hash': '95f77b39c1de2895b2861ea2a8bc6f5a', 'timestamp': '', 'source': 'github', 'line_count': 36, 'max_line_length': 124, 'avg_line_length': 47.111111111111114, 'alnum_prop': 0.7712264150943396, 'repo_name': 'saitjr/STShareTool', 'id': '2d54bed293507c0079bbd387fdd6638e2d4b7289', 'size': '2022', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'example/STShareTool/STShareTool/STShareTool/STShareTool.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '4555'}, {'name': 'Objective-C', 'bytes': '277103'}]}
package com.example.simple; import java.math.BigDecimal; import java.util.*; /** * java基本程序hello,world * @author zhaoliang * */ public class HelloWorld { public static void main(String[] args) { Scanner scan = new Scanner(System.in); double x = scan.nextInt(); double y = scan.nextInt(); double a = scan.nextInt(); double b = scan.nextInt(); java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.000000000000"); double k = (x * a + y * b) * 1.0 / ( a * a + b * b); double n = (a * k - x) * 1.0 / b; System.out.println(myformat.format(k)); System.out.println(myformat.format(n)); } }
{'content_hash': 'ffb80391399a9a3cbb66f537671459a7', 'timestamp': '', 'source': 'github', 'line_count': 25, 'max_line_length': 88, 'avg_line_length': 27.52, 'alnum_prop': 0.5872093023255814, 'repo_name': 'our880tom/java-example', 'id': '672a4a8162ef0e111eebba93ef4511beb9109268', 'size': '698', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/com/example/simple/HelloWorld.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '27884'}, {'name': 'Thrift', 'bytes': '103'}]}
package watch import ( "fmt" "io" "sync" "github.com/armon/consul-api" ) // WatchPlan is the parsed version of a watch specification. A watch provides // the details of a query, which generates a view into the Consul data store. // This view is watched for changes and a handler is invoked to take any // appropriate actions. type WatchPlan struct { Datacenter string Token string Type string Exempt map[string]interface{} Func WatchFunc Handler HandlerFunc LogOutput io.Writer address string client *consulapi.Client lastIndex uint64 lastResult interface{} stop bool stopCh chan struct{} stopLock sync.Mutex } // WatchFunc is used to watch for a diff type WatchFunc func(*WatchPlan) (uint64, interface{}, error) // HandlerFunc is used to handle new data type HandlerFunc func(uint64, interface{}) // Parse takes a watch query and compiles it into a WatchPlan or an error func Parse(params map[string]interface{}) (*WatchPlan, error) { return ParseExempt(params, nil) } // ParseExempt takes a watch query and compiles it into a WatchPlan or an error // Any exempt parameters are stored in the Exempt map func ParseExempt(params map[string]interface{}, exempt []string) (*WatchPlan, error) { plan := &WatchPlan{ stopCh: make(chan struct{}), } // Parse the generic parameters if err := assignValue(params, "datacenter", &plan.Datacenter); err != nil { return nil, err } if err := assignValue(params, "token", &plan.Token); err != nil { return nil, err } if err := assignValue(params, "type", &plan.Type); err != nil { return nil, err } // Ensure there is a watch type if plan.Type == "" { return nil, fmt.Errorf("Watch type must be specified") } // Look for a factory function factory := watchFuncFactory[plan.Type] if factory == nil { return nil, fmt.Errorf("Unsupported watch type: %s", plan.Type) } // Get the watch func fn, err := factory(params) if err != nil { return nil, err } plan.Func = fn // Remove the exempt parameters if len(exempt) > 0 { plan.Exempt = make(map[string]interface{}) for _, ex := range exempt { val, ok := params[ex] if ok { plan.Exempt[ex] = val delete(params, ex) } } } // Ensure all parameters are consumed if len(params) != 0 { var bad []string for key := range params { bad = append(bad, key) } return nil, fmt.Errorf("Invalid parameters: %v", bad) } return plan, nil } // assignValue is used to extract a value ensuring it is a string func assignValue(params map[string]interface{}, name string, out *string) error { if raw, ok := params[name]; ok { val, ok := raw.(string) if !ok { return fmt.Errorf("Expecting %s to be a string") } *out = val delete(params, name) } return nil } // assignValueBool is used to extract a value ensuring it is a bool func assignValueBool(params map[string]interface{}, name string, out *bool) error { if raw, ok := params[name]; ok { val, ok := raw.(bool) if !ok { return fmt.Errorf("Expecting %s to be a boolean") } *out = val delete(params, name) } return nil }
{'content_hash': 'd7b4cf63ea0e2b97813818aeef6ecb6e', 'timestamp': '', 'source': 'github', 'line_count': 129, 'max_line_length': 86, 'avg_line_length': 24.108527131782946, 'alnum_prop': 0.6787781350482315, 'repo_name': 'akash1808/consul', 'id': '0b0a69a32ec04f5610cc887eca1d3b09b9b3ddcd', 'size': '3110', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'watch/watch.go', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '88266'}, {'name': 'Go', 'bytes': '834094'}, {'name': 'HTML', 'bytes': '65209'}, {'name': 'JavaScript', 'bytes': '68768'}, {'name': 'Makefile', 'bytes': '4076'}, {'name': 'Ruby', 'bytes': '9402'}, {'name': 'Shell', 'bytes': '3388'}]}
package org.apache.camel.component.infinispan; import java.util.List; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.infinispan.processor.query.HavingQueryBuilderStrategy; import org.apache.camel.impl.JndiRegistry; import org.apache.camel.test.junit4.CamelTestSupport; import org.infinispan.commons.api.BasicCache; import org.infinispan.commons.api.BasicCacheContainer; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.DefaultCacheManager; import org.junit.Before; import org.junit.Test; import static org.hamcrest.core.Is.is; public class InfinispanEmbeddedQueryTest extends CamelTestSupport { protected BasicCacheContainer basicCacheContainer; protected HavingQueryBuilderStrategy queryBuilderStrategy = new HavingQueryBuilderStrategy(Book.class, "title", "Camel"); @Override @Before public void setUp() throws Exception { Configuration infinispanConfiguration = new ConfigurationBuilder() .indexing() .enable() .indexLocalOnly(true) .addProperty("default.directory_provider", "ram") .build(); basicCacheContainer = new DefaultCacheManager(infinispanConfiguration); basicCacheContainer.start(); super.setUp(); } @Override public void tearDown() throws Exception { basicCacheContainer.stop(); super.tearDown(); } @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry registry = super.createRegistry(); registry.bind("cacheContainer", basicCacheContainer); registry.bind("queryBuilderStrategy", queryBuilderStrategy); return registry; } protected BasicCache<Object, Object> currentCache() { return basicCacheContainer.getCache(); } @Test public void findsCacheEntryBasedOnTheValue() throws Exception { Book camelBook = new Book("1", "Camel", "123"); Book activeMQBook = new Book("2", "ActiveMQ", "124"); currentCache().put(camelBook.getId(), camelBook); currentCache().put(activeMQBook.getId(), activeMQBook); Exchange exchange = template.send("direct:start", new Processor() { @Override public void process(Exchange exchange) throws Exception { exchange.getIn().setHeader(InfinispanConstants.OPERATION, InfinispanConstants.QUERY); } }); List<Book> result = exchange.getIn().getHeader(InfinispanConstants.RESULT, List.class); assertThat(result.size(), is(1)); assertThat(result.get(0), is(camelBook)); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() { from("direct:start") .to("infinispan://localhost?cacheContainer=#cacheContainer&queryBuilderStrategy=#queryBuilderStrategy"); } }; } }
{'content_hash': 'b369ae372be231386df6f065062ffb05', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 128, 'avg_line_length': 35.93258426966292, 'alnum_prop': 0.6863664790494058, 'repo_name': 'igarashitm/camel', 'id': '3caaaace3fcf51867747e2dd6603a5d70d60885a', 'size': '4001', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'components/camel-infinispan/src/test/java/org/apache/camel/component/infinispan/InfinispanEmbeddedQueryTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ActionScript', 'bytes': '20202'}, {'name': 'CSS', 'bytes': '221391'}, {'name': 'Elm', 'bytes': '5970'}, {'name': 'Groovy', 'bytes': '18886'}, {'name': 'Java', 'bytes': '37040626'}, {'name': 'JavaScript', 'bytes': '3695475'}, {'name': 'PHP', 'bytes': '88860'}, {'name': 'Ruby', 'bytes': '11588'}, {'name': 'Scala', 'bytes': '266906'}, {'name': 'Shell', 'bytes': '13168'}, {'name': 'TypeScript', 'bytes': '715'}, {'name': 'XQuery', 'bytes': '1483'}, {'name': 'XSLT', 'bytes': '72262'}]}
/****************************/ /** CUSTOMIZER CLASS **/ /****************************/ var gridCustomizer; // eslint-disable-line no-unused-vars gridCustomizer = function (baseOptions, baseInitializer) { return function CustomizedGrid(overrideOptions, overrideInitializer) { var realOptions = {}; var result; return loadBaseOptions() .then(loadOverrideOptions) .then(addTemplates) .then(function () { result = new Grid(realOptions); return result.ready; }) .then(function () { return result; }) .catch(function (err) { console.error('Failed to initialize grid', (err && err.message ? err.message : err)); }); // ////////////////////// function loadBaseOptions() { deepReplace(realOptions, baseOptions); if (typeof baseInitializer === 'function') { baseInitializer(realOptions); } return loadAllDependencies(realOptions); } function loadOverrideOptions() { deepReplace(realOptions, overrideOptions); if (typeof overrideInitializer === 'function') { overrideInitializer(realOptions); } } function addTemplates() { deepReplace(templates, realOptions.templates); } }; }; function loadAllDependencies(options) { var initPromises = []; walkObject(options, isPromise, function (value, key, obj) { initPromises.push(value.then(function (resolvedValue) { obj[key] = resolvedValue; // eslint-disable-line no-param-reassign })); }); return Promise.all(initPromises); }
{'content_hash': '1b73f98f54e57a2ab12d711451ca697f', 'timestamp': '', 'source': 'github', 'line_count': 53, 'max_line_length': 101, 'avg_line_length': 33.735849056603776, 'alnum_prop': 0.5391498881431768, 'repo_name': 'simonlevasseur/ko-grid', 'id': '50e06371d312b991901fe8c70cfec1cb705cd718', 'size': '1788', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/classes/gridCustomizer.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '6671'}, {'name': 'HTML', 'bytes': '4778'}, {'name': 'JavaScript', 'bytes': '204099'}]}
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![allow(non_camel_case_types)] // FIXME: remove this after snapshot, and Results are handled #![allow(unused_must_use)] use c = metadata::common; use cstore = metadata::cstore; use driver::session::Session; use metadata::decoder; use middle::def; use e = metadata::encoder; use middle::freevars::freevar_entry; use middle::region; use metadata::tydecode; use metadata::tydecode::{DefIdSource, NominalType, TypeWithId, TypeParameter, RegionParameter}; use metadata::tyencode; use middle::subst; use middle::subst::VecPerParamSpace; use middle::typeck::{MethodCall, MethodCallee, MethodOrigin}; use middle::{ty, typeck}; use util::ppaux::ty_to_str; use syntax::{ast, ast_map, ast_util, codemap, fold}; use syntax::codemap::Span; use syntax::fold::Folder; use syntax::parse::token; use syntax; use libc; use std::io::Seek; use std::io::MemWriter; use std::mem; use std::gc::GC; use serialize::ebml::reader; use serialize::ebml; use serialize; use serialize::{Encoder, Encodable, EncoderHelpers, DecoderHelpers}; use serialize::{Decoder, Decodable}; use writer = serialize::ebml::writer; #[cfg(test)] use syntax::parse; #[cfg(test)] use syntax::print::pprust; #[cfg(test)] use std::gc::Gc; struct DecodeContext<'a> { cdata: &'a cstore::crate_metadata, tcx: &'a ty::ctxt, } struct ExtendedDecodeContext<'a> { dcx: &'a DecodeContext<'a>, from_id_range: ast_util::IdRange, to_id_range: ast_util::IdRange } trait tr { fn tr(&self, xcx: &ExtendedDecodeContext) -> Self; } trait tr_intern { fn tr_intern(&self, xcx: &ExtendedDecodeContext) -> ast::DefId; } pub type Encoder<'a> = writer::Encoder<'a, MemWriter>; // ______________________________________________________________________ // Top-level methods. pub fn encode_inlined_item(ecx: &e::EncodeContext, ebml_w: &mut Encoder, ii: e::InlinedItemRef) { let id = match ii { e::IIItemRef(i) => i.id, e::IIForeignRef(i) => i.id, e::IIMethodRef(_, _, m) => m.id, }; debug!("> Encoding inlined item: {} ({})", ecx.tcx.map.path_to_str(id), ebml_w.writer.tell()); let ii = simplify_ast(ii); let id_range = ast_util::compute_id_range_for_inlined_item(&ii); ebml_w.start_tag(c::tag_ast as uint); id_range.encode(ebml_w); encode_ast(ebml_w, ii); encode_side_tables_for_ii(ecx, ebml_w, &ii); ebml_w.end_tag(); debug!("< Encoded inlined fn: {} ({})", ecx.tcx.map.path_to_str(id), ebml_w.writer.tell()); } pub fn decode_inlined_item(cdata: &cstore::crate_metadata, tcx: &ty::ctxt, path: Vec<ast_map::PathElem>, par_doc: ebml::Doc) -> Result<ast::InlinedItem, Vec<ast_map::PathElem>> { let dcx = &DecodeContext { cdata: cdata, tcx: tcx, }; match par_doc.opt_child(c::tag_ast) { None => Err(path), Some(ast_doc) => { let mut path_as_str = None; debug!("> Decoding inlined fn: {}::?", { // Do an Option dance to use the path after it is moved below. let s = ast_map::path_to_str(ast_map::Values(path.iter())); path_as_str = Some(s); path_as_str.as_ref().map(|x| x.as_slice()) }); let mut ast_dsr = reader::Decoder::new(ast_doc); let from_id_range = Decodable::decode(&mut ast_dsr).unwrap(); let to_id_range = reserve_id_range(&dcx.tcx.sess, from_id_range); let xcx = &ExtendedDecodeContext { dcx: dcx, from_id_range: from_id_range, to_id_range: to_id_range }; let raw_ii = decode_ast(ast_doc); let ii = renumber_and_map_ast(xcx, &dcx.tcx.map, path, raw_ii); let ident = match ii { ast::IIItem(i) => i.ident, ast::IIForeign(i) => i.ident, ast::IIMethod(_, _, m) => m.ident, }; debug!("Fn named: {}", token::get_ident(ident)); debug!("< Decoded inlined fn: {}::{}", path_as_str.unwrap(), token::get_ident(ident)); region::resolve_inlined_item(&tcx.sess, &tcx.region_maps, &ii); decode_side_tables(xcx, ast_doc); match ii { ast::IIItem(i) => { debug!(">>> DECODED ITEM >>>\n{}\n<<< DECODED ITEM <<<", syntax::print::pprust::item_to_str(&*i)); } _ => { } } Ok(ii) } } } // ______________________________________________________________________ // Enumerating the IDs which appear in an AST fn reserve_id_range(sess: &Session, from_id_range: ast_util::IdRange) -> ast_util::IdRange { // Handle the case of an empty range: if from_id_range.empty() { return from_id_range; } let cnt = from_id_range.max - from_id_range.min; let to_id_min = sess.reserve_node_ids(cnt); let to_id_max = to_id_min + cnt; ast_util::IdRange { min: to_id_min, max: to_id_max } } impl<'a> ExtendedDecodeContext<'a> { pub fn tr_id(&self, id: ast::NodeId) -> ast::NodeId { /*! * Translates an internal id, meaning a node id that is known * to refer to some part of the item currently being inlined, * such as a local variable or argument. All naked node-ids * that appear in types have this property, since if something * might refer to an external item we would use a def-id to * allow for the possibility that the item resides in another * crate. */ // from_id_range should be non-empty assert!(!self.from_id_range.empty()); (id - self.from_id_range.min + self.to_id_range.min) } pub fn tr_def_id(&self, did: ast::DefId) -> ast::DefId { /*! * Translates an EXTERNAL def-id, converting the crate number * from the one used in the encoded data to the current crate * numbers.. By external, I mean that it be translated to a * reference to the item in its original crate, as opposed to * being translated to a reference to the inlined version of * the item. This is typically, but not always, what you * want, because most def-ids refer to external things like * types or other fns that may or may not be inlined. Note * that even when the inlined function is referencing itself * recursively, we would want `tr_def_id` for that * reference--- conceptually the function calls the original, * non-inlined version, and trans deals with linking that * recursive call to the inlined copy. * * However, there are a *few* cases where def-ids are used but * we know that the thing being referenced is in fact *internal* * to the item being inlined. In those cases, you should use * `tr_intern_def_id()` below. */ decoder::translate_def_id(self.dcx.cdata, did) } pub fn tr_intern_def_id(&self, did: ast::DefId) -> ast::DefId { /*! * Translates an INTERNAL def-id, meaning a def-id that is * known to refer to some part of the item currently being * inlined. In that case, we want to convert the def-id to * refer to the current crate and to the new, inlined node-id. */ assert_eq!(did.krate, ast::LOCAL_CRATE); ast::DefId { krate: ast::LOCAL_CRATE, node: self.tr_id(did.node) } } pub fn tr_span(&self, _span: Span) -> Span { codemap::DUMMY_SP // FIXME (#1972): handle span properly } } impl tr_intern for ast::DefId { fn tr_intern(&self, xcx: &ExtendedDecodeContext) -> ast::DefId { xcx.tr_intern_def_id(*self) } } impl tr for ast::DefId { fn tr(&self, xcx: &ExtendedDecodeContext) -> ast::DefId { xcx.tr_def_id(*self) } } impl tr for Option<ast::DefId> { fn tr(&self, xcx: &ExtendedDecodeContext) -> Option<ast::DefId> { self.map(|d| xcx.tr_def_id(d)) } } impl tr for Span { fn tr(&self, xcx: &ExtendedDecodeContext) -> Span { xcx.tr_span(*self) } } trait def_id_encoder_helpers { fn emit_def_id(&mut self, did: ast::DefId); } impl<S:serialize::Encoder<E>, E> def_id_encoder_helpers for S { fn emit_def_id(&mut self, did: ast::DefId) { did.encode(self).ok().unwrap() } } trait def_id_decoder_helpers { fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId; fn read_def_id_noxcx(&mut self, cdata: &cstore::crate_metadata) -> ast::DefId; } impl<D:serialize::Decoder<E>, E> def_id_decoder_helpers for D { fn read_def_id(&mut self, xcx: &ExtendedDecodeContext) -> ast::DefId { let did: ast::DefId = Decodable::decode(self).ok().unwrap(); did.tr(xcx) } fn read_def_id_noxcx(&mut self, cdata: &cstore::crate_metadata) -> ast::DefId { let did: ast::DefId = Decodable::decode(self).ok().unwrap(); decoder::translate_def_id(cdata, did) } } // ______________________________________________________________________ // Encoding and decoding the AST itself // // The hard work is done by an autogenerated module astencode_gen. To // regenerate astencode_gen, run src/etc/gen-astencode. It will // replace astencode_gen with a dummy file and regenerate its // contents. If you get compile errors, the dummy file // remains---resolve the errors and then rerun astencode_gen. // Annoying, I know, but hopefully only temporary. // // When decoding, we have to renumber the AST so that the node ids that // appear within are disjoint from the node ids in our existing ASTs. // We also have to adjust the spans: for now we just insert a dummy span, // but eventually we should add entries to the local codemap as required. fn encode_ast(ebml_w: &mut Encoder, item: ast::InlinedItem) { ebml_w.start_tag(c::tag_tree as uint); item.encode(ebml_w); ebml_w.end_tag(); } struct NestedItemsDropper; impl Folder for NestedItemsDropper { fn fold_block(&mut self, blk: ast::P<ast::Block>) -> ast::P<ast::Block> { let stmts_sans_items = blk.stmts.iter().filter_map(|stmt| { match stmt.node { ast::StmtExpr(_, _) | ast::StmtSemi(_, _) => Some(*stmt), ast::StmtDecl(decl, _) => { match decl.node { ast::DeclLocal(_) => Some(*stmt), ast::DeclItem(_) => None, } } ast::StmtMac(..) => fail!("unexpanded macro in astencode") } }).collect(); let blk_sans_items = ast::P(ast::Block { view_items: Vec::new(), // I don't know if we need the view_items // here, but it doesn't break tests! stmts: stmts_sans_items, expr: blk.expr, id: blk.id, rules: blk.rules, span: blk.span, }); fold::noop_fold_block(blk_sans_items, self) } } // Produces a simplified copy of the AST which does not include things // that we do not need to or do not want to export. For example, we // do not include any nested items: if these nested items are to be // inlined, their AST will be exported separately (this only makes // sense because, in Rust, nested items are independent except for // their visibility). // // As it happens, trans relies on the fact that we do not export // nested items, as otherwise it would get confused when translating // inlined items. fn simplify_ast(ii: e::InlinedItemRef) -> ast::InlinedItem { let mut fld = NestedItemsDropper; match ii { // HACK we're not dropping items. e::IIItemRef(i) => ast::IIItem(fold::noop_fold_item(i, &mut fld) .expect_one("expected one item")), e::IIMethodRef(d, p, m) => ast::IIMethod(d, p, fold::noop_fold_method(m, &mut fld)), e::IIForeignRef(i) => ast::IIForeign(fold::noop_fold_foreign_item(i, &mut fld)) } } fn decode_ast(par_doc: ebml::Doc) -> ast::InlinedItem { let chi_doc = par_doc.get(c::tag_tree as uint); let mut d = reader::Decoder::new(chi_doc); Decodable::decode(&mut d).unwrap() } struct AstRenumberer<'a> { xcx: &'a ExtendedDecodeContext<'a>, } impl<'a> ast_map::FoldOps for AstRenumberer<'a> { fn new_id(&self, id: ast::NodeId) -> ast::NodeId { if id == ast::DUMMY_NODE_ID { // Used by ast_map to map the NodeInlinedParent. self.xcx.dcx.tcx.sess.next_node_id() } else { self.xcx.tr_id(id) } } fn new_span(&self, span: Span) -> Span { self.xcx.tr_span(span) } } fn renumber_and_map_ast(xcx: &ExtendedDecodeContext, map: &ast_map::Map, path: Vec<ast_map::PathElem> , ii: ast::InlinedItem) -> ast::InlinedItem { ast_map::map_decoded_item(map, path.move_iter().collect(), AstRenumberer { xcx: xcx }, |fld| { match ii { ast::IIItem(i) => { ast::IIItem(fld.fold_item(i).expect_one("expected one item")) } ast::IIMethod(d, is_provided, m) => { ast::IIMethod(xcx.tr_def_id(d), is_provided, fld.fold_method(m)) } ast::IIForeign(i) => ast::IIForeign(fld.fold_foreign_item(i)) } }) } // ______________________________________________________________________ // Encoding and decoding of ast::def fn decode_def(xcx: &ExtendedDecodeContext, doc: ebml::Doc) -> def::Def { let mut dsr = reader::Decoder::new(doc); let def: def::Def = Decodable::decode(&mut dsr).unwrap(); def.tr(xcx) } impl tr for def::Def { fn tr(&self, xcx: &ExtendedDecodeContext) -> def::Def { match *self { def::DefFn(did, p) => def::DefFn(did.tr(xcx), p), def::DefStaticMethod(did, wrapped_did2, p) => { def::DefStaticMethod(did.tr(xcx), match wrapped_did2 { def::FromTrait(did2) => { def::FromTrait(did2.tr(xcx)) } def::FromImpl(did2) => { def::FromImpl(did2.tr(xcx)) } }, p) } def::DefMethod(did0, did1) => { def::DefMethod(did0.tr(xcx), did1.map(|did1| did1.tr(xcx))) } def::DefSelfTy(nid) => { def::DefSelfTy(xcx.tr_id(nid)) } def::DefMod(did) => { def::DefMod(did.tr(xcx)) } def::DefForeignMod(did) => { def::DefForeignMod(did.tr(xcx)) } def::DefStatic(did, m) => { def::DefStatic(did.tr(xcx), m) } def::DefArg(nid, b) => { def::DefArg(xcx.tr_id(nid), b) } def::DefLocal(nid, b) => { def::DefLocal(xcx.tr_id(nid), b) } def::DefVariant(e_did, v_did, is_s) => { def::DefVariant(e_did.tr(xcx), v_did.tr(xcx), is_s) }, def::DefTrait(did) => def::DefTrait(did.tr(xcx)), def::DefTy(did) => def::DefTy(did.tr(xcx)), def::DefPrimTy(p) => def::DefPrimTy(p), def::DefTyParam(s, did, v) => def::DefTyParam(s, did.tr(xcx), v), def::DefBinding(nid, bm) => def::DefBinding(xcx.tr_id(nid), bm), def::DefUse(did) => def::DefUse(did.tr(xcx)), def::DefUpvar(nid1, def, nid2, nid3) => { def::DefUpvar(xcx.tr_id(nid1), box(GC) (*def).tr(xcx), xcx.tr_id(nid2), xcx.tr_id(nid3)) } def::DefStruct(did) => def::DefStruct(did.tr(xcx)), def::DefRegion(nid) => def::DefRegion(xcx.tr_id(nid)), def::DefTyParamBinder(nid) => { def::DefTyParamBinder(xcx.tr_id(nid)) } def::DefLabel(nid) => def::DefLabel(xcx.tr_id(nid)) } } } // ______________________________________________________________________ // Encoding and decoding of adjustment information impl tr for ty::AutoDerefRef { fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::AutoDerefRef { ty::AutoDerefRef { autoderefs: self.autoderefs, autoref: match self.autoref { Some(ref autoref) => Some(autoref.tr(xcx)), None => None } } } } impl tr for ty::AutoRef { fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::AutoRef { self.map_region(|r| r.tr(xcx)) } } impl tr for ty::Region { fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::Region { match *self { ty::ReLateBound(id, br) => { ty::ReLateBound(xcx.tr_id(id), br.tr(xcx)) } ty::ReEarlyBound(id, space, index, ident) => { ty::ReEarlyBound(xcx.tr_id(id), space, index, ident) } ty::ReScope(id) => { ty::ReScope(xcx.tr_id(id)) } ty::ReEmpty | ty::ReStatic | ty::ReInfer(..) => { *self } ty::ReFree(ref fr) => { ty::ReFree(ty::FreeRegion {scope_id: xcx.tr_id(fr.scope_id), bound_region: fr.bound_region.tr(xcx)}) } } } } impl tr for ty::BoundRegion { fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::BoundRegion { match *self { ty::BrAnon(_) | ty::BrFresh(_) => *self, ty::BrNamed(id, ident) => ty::BrNamed(xcx.tr_def_id(id), ident), } } } impl tr for ty::TraitStore { fn tr(&self, xcx: &ExtendedDecodeContext) -> ty::TraitStore { match *self { ty::RegionTraitStore(r, m) => { ty::RegionTraitStore(r.tr(xcx), m) } ty::UniqTraitStore => ty::UniqTraitStore } } } // ______________________________________________________________________ // Encoding and decoding of freevar information fn encode_freevar_entry(ebml_w: &mut Encoder, fv: &freevar_entry) { (*fv).encode(ebml_w).unwrap(); } trait ebml_decoder_helper { fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext) -> freevar_entry; } impl<'a> ebml_decoder_helper for reader::Decoder<'a> { fn read_freevar_entry(&mut self, xcx: &ExtendedDecodeContext) -> freevar_entry { let fv: freevar_entry = Decodable::decode(self).unwrap(); fv.tr(xcx) } } impl tr for freevar_entry { fn tr(&self, xcx: &ExtendedDecodeContext) -> freevar_entry { freevar_entry { def: self.def.tr(xcx), span: self.span.tr(xcx), } } } // ______________________________________________________________________ // Encoding and decoding of MethodCallee trait read_method_callee_helper { fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (typeck::ExprAdjustment, MethodCallee); } fn encode_method_callee(ecx: &e::EncodeContext, ebml_w: &mut Encoder, adjustment: typeck::ExprAdjustment, method: &MethodCallee) { ebml_w.emit_struct("MethodCallee", 4, |ebml_w| { ebml_w.emit_struct_field("adjustment", 0u, |ebml_w| { adjustment.encode(ebml_w) }); ebml_w.emit_struct_field("origin", 1u, |ebml_w| { method.origin.encode(ebml_w) }); ebml_w.emit_struct_field("ty", 2u, |ebml_w| { Ok(ebml_w.emit_ty(ecx, method.ty)) }); ebml_w.emit_struct_field("substs", 3u, |ebml_w| { Ok(ebml_w.emit_substs(ecx, &method.substs)) }) }).unwrap(); } impl<'a> read_method_callee_helper for reader::Decoder<'a> { fn read_method_callee(&mut self, xcx: &ExtendedDecodeContext) -> (typeck::ExprAdjustment, MethodCallee) { self.read_struct("MethodCallee", 4, |this| { let adjustment = this.read_struct_field("adjustment", 0, |this| { Decodable::decode(this) }).unwrap(); Ok((adjustment, MethodCallee { origin: this.read_struct_field("origin", 1, |this| { let method_origin: MethodOrigin = Decodable::decode(this).unwrap(); Ok(method_origin.tr(xcx)) }).unwrap(), ty: this.read_struct_field("ty", 2, |this| { Ok(this.read_ty(xcx)) }).unwrap(), substs: this.read_struct_field("substs", 3, |this| { Ok(this.read_substs(xcx)) }).unwrap() })) }).unwrap() } } impl tr for MethodOrigin { fn tr(&self, xcx: &ExtendedDecodeContext) -> MethodOrigin { match *self { typeck::MethodStatic(did) => typeck::MethodStatic(did.tr(xcx)), typeck::MethodParam(ref mp) => { typeck::MethodParam( typeck::MethodParam { trait_id: mp.trait_id.tr(xcx), .. *mp } ) } typeck::MethodObject(ref mo) => { typeck::MethodObject( typeck::MethodObject { trait_id: mo.trait_id.tr(xcx), .. *mo } ) } } } } // ______________________________________________________________________ // Encoding and decoding vtable_res fn encode_vtable_res_with_key(ecx: &e::EncodeContext, ebml_w: &mut Encoder, adjustment: typeck::ExprAdjustment, dr: &typeck::vtable_res) { ebml_w.emit_struct("VtableWithKey", 2, |ebml_w| { ebml_w.emit_struct_field("adjustment", 0u, |ebml_w| { adjustment.encode(ebml_w) }); ebml_w.emit_struct_field("vtable_res", 1u, |ebml_w| { Ok(encode_vtable_res(ecx, ebml_w, dr)) }) }).unwrap() } pub fn encode_vtable_res(ecx: &e::EncodeContext, ebml_w: &mut Encoder, dr: &typeck::vtable_res) { // can't autogenerate this code because automatic code of // ty::t doesn't work, and there is no way (atm) to have // hand-written encoding routines combine with auto-generated // ones. perhaps we should fix this. encode_vec_per_param_space( ebml_w, dr, |ebml_w, param_tables| encode_vtable_param_res(ecx, ebml_w, param_tables)) } pub fn encode_vtable_param_res(ecx: &e::EncodeContext, ebml_w: &mut Encoder, param_tables: &typeck::vtable_param_res) { ebml_w.emit_from_vec(param_tables.as_slice(), |ebml_w, vtable_origin| { Ok(encode_vtable_origin(ecx, ebml_w, vtable_origin)) }).unwrap() } pub fn encode_vtable_origin(ecx: &e::EncodeContext, ebml_w: &mut Encoder, vtable_origin: &typeck::vtable_origin) { ebml_w.emit_enum("vtable_origin", |ebml_w| { match *vtable_origin { typeck::vtable_static(def_id, ref substs, ref vtable_res) => { ebml_w.emit_enum_variant("vtable_static", 0u, 3u, |ebml_w| { ebml_w.emit_enum_variant_arg(0u, |ebml_w| { Ok(ebml_w.emit_def_id(def_id)) }); ebml_w.emit_enum_variant_arg(1u, |ebml_w| { Ok(ebml_w.emit_substs(ecx, substs)) }); ebml_w.emit_enum_variant_arg(2u, |ebml_w| { Ok(encode_vtable_res(ecx, ebml_w, vtable_res)) }) }) } typeck::vtable_param(pn, bn) => { ebml_w.emit_enum_variant("vtable_param", 1u, 3u, |ebml_w| { ebml_w.emit_enum_variant_arg(0u, |ebml_w| { pn.encode(ebml_w) }); ebml_w.emit_enum_variant_arg(1u, |ebml_w| { ebml_w.emit_uint(bn) }) }) } typeck::vtable_error => { ebml_w.emit_enum_variant("vtable_error", 2u, 3u, |_ebml_w| { Ok(()) }) } } }).unwrap() } pub trait vtable_decoder_helpers { fn read_vec_per_param_space<T>(&mut self, f: |&mut Self| -> T) -> VecPerParamSpace<T>; fn read_vtable_res_with_key(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> (typeck::ExprAdjustment, typeck::vtable_res); fn read_vtable_res(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> typeck::vtable_res; fn read_vtable_param_res(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> typeck::vtable_param_res; fn read_vtable_origin(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> typeck::vtable_origin; } impl<'a> vtable_decoder_helpers for reader::Decoder<'a> { fn read_vec_per_param_space<T>(&mut self, f: |&mut reader::Decoder<'a>| -> T) -> VecPerParamSpace<T> { let types = self.read_to_vec(|this| Ok(f(this))).unwrap(); let selfs = self.read_to_vec(|this| Ok(f(this))).unwrap(); let fns = self.read_to_vec(|this| Ok(f(this))).unwrap(); VecPerParamSpace::new(types, selfs, fns) } fn read_vtable_res_with_key(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> (typeck::ExprAdjustment, typeck::vtable_res) { self.read_struct("VtableWithKey", 2, |this| { let adjustment = this.read_struct_field("adjustment", 0, |this| { Decodable::decode(this) }).unwrap(); Ok((adjustment, this.read_struct_field("vtable_res", 1, |this| { Ok(this.read_vtable_res(tcx, cdata)) }).unwrap())) }).unwrap() } fn read_vtable_res(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> typeck::vtable_res { self.read_vec_per_param_space( |this| this.read_vtable_param_res(tcx, cdata)) } fn read_vtable_param_res(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> typeck::vtable_param_res { self.read_to_vec(|this| Ok(this.read_vtable_origin(tcx, cdata))) .unwrap().move_iter().collect() } fn read_vtable_origin(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> typeck::vtable_origin { self.read_enum("vtable_origin", |this| { this.read_enum_variant(["vtable_static", "vtable_param", "vtable_error"], |this, i| { Ok(match i { 0 => { typeck::vtable_static( this.read_enum_variant_arg(0u, |this| { Ok(this.read_def_id_noxcx(cdata)) }).unwrap(), this.read_enum_variant_arg(1u, |this| { Ok(this.read_substs_noxcx(tcx, cdata)) }).unwrap(), this.read_enum_variant_arg(2u, |this| { Ok(this.read_vtable_res(tcx, cdata)) }).unwrap() ) } 1 => { typeck::vtable_param( this.read_enum_variant_arg(0u, |this| { Decodable::decode(this) }).unwrap(), this.read_enum_variant_arg(1u, |this| { this.read_uint() }).unwrap() ) } 2 => { typeck::vtable_error } _ => fail!("bad enum variant") }) }) }).unwrap() } } // ___________________________________________________________________________ // fn encode_vec_per_param_space<T>(ebml_w: &mut Encoder, v: &subst::VecPerParamSpace<T>, f: |&mut Encoder, &T|) { for &space in subst::ParamSpace::all().iter() { ebml_w.emit_from_vec(v.get_vec(space).as_slice(), |ebml_w, n| Ok(f(ebml_w, n))).unwrap(); } } // ______________________________________________________________________ // Encoding and decoding the side tables trait get_ty_str_ctxt { fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a>; } impl<'a> get_ty_str_ctxt for e::EncodeContext<'a> { fn ty_str_ctxt<'a>(&'a self) -> tyencode::ctxt<'a> { tyencode::ctxt { diag: self.tcx.sess.diagnostic(), ds: e::def_to_str, tcx: self.tcx, abbrevs: &self.type_abbrevs } } } trait ebml_writer_helpers { fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t); fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]); fn emit_type_param_def(&mut self, ecx: &e::EncodeContext, type_param_def: &ty::TypeParameterDef); fn emit_polytype(&mut self, ecx: &e::EncodeContext, pty: ty::Polytype); fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &subst::Substs); fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment); } impl<'a> ebml_writer_helpers for Encoder<'a> { fn emit_ty(&mut self, ecx: &e::EncodeContext, ty: ty::t) { self.emit_opaque(|this| Ok(e::write_type(ecx, this, ty))); } fn emit_tys(&mut self, ecx: &e::EncodeContext, tys: &[ty::t]) { self.emit_from_vec(tys, |this, ty| Ok(this.emit_ty(ecx, *ty))); } fn emit_type_param_def(&mut self, ecx: &e::EncodeContext, type_param_def: &ty::TypeParameterDef) { self.emit_opaque(|this| { Ok(tyencode::enc_type_param_def(this.writer, &ecx.ty_str_ctxt(), type_param_def)) }); } fn emit_polytype(&mut self, ecx: &e::EncodeContext, pty: ty::Polytype) { self.emit_struct("Polytype", 2, |this| { this.emit_struct_field("generics", 0, |this| { this.emit_struct("Generics", 2, |this| { this.emit_struct_field("types", 0, |this| { Ok(encode_vec_per_param_space( this, &pty.generics.types, |this, def| this.emit_type_param_def(ecx, def))) }); this.emit_struct_field("regions", 1, |this| { Ok(encode_vec_per_param_space( this, &pty.generics.regions, |this, def| def.encode(this).unwrap())) }) }) }); this.emit_struct_field("ty", 1, |this| { Ok(this.emit_ty(ecx, pty.ty)) }) }); } fn emit_substs(&mut self, ecx: &e::EncodeContext, substs: &subst::Substs) { self.emit_opaque(|this| Ok(tyencode::enc_substs(this.writer, &ecx.ty_str_ctxt(), substs))); } fn emit_auto_adjustment(&mut self, ecx: &e::EncodeContext, adj: &ty::AutoAdjustment) { self.emit_enum("AutoAdjustment", |this| { match *adj { ty::AutoAddEnv(store) => { this.emit_enum_variant("AutoAddEnv", 0, 1, |this| { this.emit_enum_variant_arg(0, |this| store.encode(this)) }) } ty::AutoDerefRef(ref auto_deref_ref) => { this.emit_enum_variant("AutoDerefRef", 1, 1, |this| { this.emit_enum_variant_arg(0, |this| auto_deref_ref.encode(this)) }) } ty::AutoObject(store, b, def_id, ref substs) => { this.emit_enum_variant("AutoObject", 2, 4, |this| { this.emit_enum_variant_arg(0, |this| store.encode(this)); this.emit_enum_variant_arg(1, |this| b.encode(this)); this.emit_enum_variant_arg(2, |this| def_id.encode(this)); this.emit_enum_variant_arg(3, |this| Ok(this.emit_substs(ecx, substs))) }) } } }); } } trait write_tag_and_id { fn tag(&mut self, tag_id: c::astencode_tag, f: |&mut Self|); fn id(&mut self, id: ast::NodeId); } impl<'a> write_tag_and_id for Encoder<'a> { fn tag(&mut self, tag_id: c::astencode_tag, f: |&mut Encoder<'a>|) { self.start_tag(tag_id as uint); f(self); self.end_tag(); } fn id(&mut self, id: ast::NodeId) { self.wr_tagged_u64(c::tag_table_id as uint, id as u64); } } struct SideTableEncodingIdVisitor<'a,'b> { ecx_ptr: *const libc::c_void, new_ebml_w: &'a mut Encoder<'b>, } impl<'a,'b> ast_util::IdVisitingOperation for SideTableEncodingIdVisitor<'a,'b> { fn visit_id(&self, id: ast::NodeId) { // Note: this will cause a copy of ebml_w, which is bad as // it is mutable. But I believe it's harmless since we generate // balanced EBML. // // FIXME(pcwalton): Don't copy this way. let mut new_ebml_w = unsafe { self.new_ebml_w.unsafe_clone() }; // See above let ecx: &e::EncodeContext = unsafe { mem::transmute(self.ecx_ptr) }; encode_side_tables_for_id(ecx, &mut new_ebml_w, id) } } fn encode_side_tables_for_ii(ecx: &e::EncodeContext, ebml_w: &mut Encoder, ii: &ast::InlinedItem) { ebml_w.start_tag(c::tag_table as uint); let mut new_ebml_w = unsafe { ebml_w.unsafe_clone() }; // Because the ast visitor uses @IdVisitingOperation, I can't pass in // ecx directly, but /I/ know that it'll be fine since the lifetime is // tied to the CrateContext that lives throughout this entire section. ast_util::visit_ids_for_inlined_item(ii, &SideTableEncodingIdVisitor { ecx_ptr: unsafe { mem::transmute(ecx) }, new_ebml_w: &mut new_ebml_w, }); ebml_w.end_tag(); } fn encode_side_tables_for_id(ecx: &e::EncodeContext, ebml_w: &mut Encoder, id: ast::NodeId) { let tcx = ecx.tcx; debug!("Encoding side tables for id {}", id); for def in tcx.def_map.borrow().find(&id).iter() { ebml_w.tag(c::tag_table_def, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| (*def).encode(ebml_w).unwrap()); }) } for &ty in tcx.node_types.borrow().find(&(id as uint)).iter() { ebml_w.tag(c::tag_table_node_type, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { ebml_w.emit_ty(ecx, *ty); }) }) } for &item_substs in tcx.item_substs.borrow().find(&id).iter() { ebml_w.tag(c::tag_table_item_subst, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { ebml_w.emit_substs(ecx, &item_substs.substs); }) }) } for &fv in tcx.freevars.borrow().find(&id).iter() { ebml_w.tag(c::tag_table_freevars, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { ebml_w.emit_from_vec(fv.as_slice(), |ebml_w, fv_entry| { Ok(encode_freevar_entry(ebml_w, fv_entry)) }); }) }) } let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id }; for &pty in tcx.tcache.borrow().find(&lid).iter() { ebml_w.tag(c::tag_table_tcache, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { ebml_w.emit_polytype(ecx, pty.clone()); }) }) } for &type_param_def in tcx.ty_param_defs.borrow().find(&id).iter() { ebml_w.tag(c::tag_table_param_defs, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { ebml_w.emit_type_param_def(ecx, type_param_def) }) }) } let method_call = MethodCall::expr(id); for &method in tcx.method_map.borrow().find(&method_call).iter() { ebml_w.tag(c::tag_table_method_map, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { encode_method_callee(ecx, ebml_w, method_call.adjustment, method) }) }) } for &dr in tcx.vtable_map.borrow().find(&method_call).iter() { ebml_w.tag(c::tag_table_vtable_map, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { encode_vtable_res_with_key(ecx, ebml_w, method_call.adjustment, dr); }) }) } for &adj in tcx.adjustments.borrow().find(&id).iter() { match *adj { ty::AutoDerefRef(adj) => { for autoderef in range(0, adj.autoderefs) { let method_call = MethodCall::autoderef(id, autoderef); for &method in tcx.method_map.borrow().find(&method_call).iter() { ebml_w.tag(c::tag_table_method_map, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { encode_method_callee(ecx, ebml_w, method_call.adjustment, method) }) }) } for &dr in tcx.vtable_map.borrow().find(&method_call).iter() { ebml_w.tag(c::tag_table_vtable_map, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { encode_vtable_res_with_key(ecx, ebml_w, method_call.adjustment, dr); }) }) } } } ty::AutoObject(..) => { let method_call = MethodCall::autoobject(id); for &method in tcx.method_map.borrow().find(&method_call).iter() { ebml_w.tag(c::tag_table_method_map, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { encode_method_callee(ecx, ebml_w, method_call.adjustment, method) }) }) } for &dr in tcx.vtable_map.borrow().find(&method_call).iter() { ebml_w.tag(c::tag_table_vtable_map, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { encode_vtable_res_with_key(ecx, ebml_w, method_call.adjustment, dr); }) }) } } _ => {} } ebml_w.tag(c::tag_table_adjustments, |ebml_w| { ebml_w.id(id); ebml_w.tag(c::tag_table_val, |ebml_w| { ebml_w.emit_auto_adjustment(ecx, adj); }) }) } } trait doc_decoder_helpers { fn as_int(&self) -> int; fn opt_child(&self, tag: c::astencode_tag) -> Option<Self>; } impl<'a> doc_decoder_helpers for ebml::Doc<'a> { fn as_int(&self) -> int { reader::doc_as_u64(*self) as int } fn opt_child(&self, tag: c::astencode_tag) -> Option<ebml::Doc<'a>> { reader::maybe_get_doc(*self, tag as uint) } } trait ebml_decoder_decoder_helpers { fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t; fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t>; fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext) -> ty::TypeParameterDef; fn read_polytype(&mut self, xcx: &ExtendedDecodeContext) -> ty::Polytype; fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> subst::Substs; fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment; fn convert_def_id(&mut self, xcx: &ExtendedDecodeContext, source: DefIdSource, did: ast::DefId) -> ast::DefId; // Versions of the type reading functions that don't need the full // ExtendedDecodeContext. fn read_ty_noxcx(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> ty::t; fn read_tys_noxcx(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> Vec<ty::t>; fn read_substs_noxcx(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> subst::Substs; } impl<'a> ebml_decoder_decoder_helpers for reader::Decoder<'a> { fn read_ty_noxcx(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> ty::t { self.read_opaque(|_, doc| { Ok(tydecode::parse_ty_data( doc.data, cdata.cnum, doc.start, tcx, |_, id| decoder::translate_def_id(cdata, id))) }).unwrap() } fn read_tys_noxcx(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> Vec<ty::t> { self.read_to_vec(|this| Ok(this.read_ty_noxcx(tcx, cdata)) ) .unwrap() .move_iter() .collect() } fn read_substs_noxcx(&mut self, tcx: &ty::ctxt, cdata: &cstore::crate_metadata) -> subst::Substs { self.read_opaque(|_, doc| { Ok(tydecode::parse_substs_data( doc.data, cdata.cnum, doc.start, tcx, |_, id| decoder::translate_def_id(cdata, id))) }).unwrap() } fn read_ty(&mut self, xcx: &ExtendedDecodeContext) -> ty::t { // Note: regions types embed local node ids. In principle, we // should translate these node ids into the new decode // context. However, we do not bother, because region types // are not used during trans. return self.read_opaque(|this, doc| { debug!("read_ty({})", type_string(doc)); let ty = tydecode::parse_ty_data( doc.data, xcx.dcx.cdata.cnum, doc.start, xcx.dcx.tcx, |s, a| this.convert_def_id(xcx, s, a)); Ok(ty) }).unwrap(); fn type_string(doc: ebml::Doc) -> String { let mut str = String::new(); for i in range(doc.start, doc.end) { str.push_char(doc.data[i] as char); } str } } fn read_tys(&mut self, xcx: &ExtendedDecodeContext) -> Vec<ty::t> { self.read_to_vec(|this| Ok(this.read_ty(xcx))).unwrap().move_iter().collect() } fn read_type_param_def(&mut self, xcx: &ExtendedDecodeContext) -> ty::TypeParameterDef { self.read_opaque(|this, doc| { Ok(tydecode::parse_type_param_def_data( doc.data, doc.start, xcx.dcx.cdata.cnum, xcx.dcx.tcx, |s, a| this.convert_def_id(xcx, s, a))) }).unwrap() } fn read_polytype(&mut self, xcx: &ExtendedDecodeContext) -> ty::Polytype { self.read_struct("Polytype", 2, |this| { Ok(ty::Polytype { generics: this.read_struct_field("generics", 0, |this| { this.read_struct("Generics", 2, |this| { Ok(ty::Generics { types: this.read_struct_field("types", 0, |this| { Ok(this.read_vec_per_param_space( |this| this.read_type_param_def(xcx))) }).unwrap(), regions: this.read_struct_field("regions", 1, |this| { Ok(this.read_vec_per_param_space( |this| Decodable::decode(this).unwrap())) }).unwrap() }) }) }).unwrap(), ty: this.read_struct_field("ty", 1, |this| { Ok(this.read_ty(xcx)) }).unwrap() }) }).unwrap() } fn read_substs(&mut self, xcx: &ExtendedDecodeContext) -> subst::Substs { self.read_opaque(|this, doc| { Ok(tydecode::parse_substs_data(doc.data, xcx.dcx.cdata.cnum, doc.start, xcx.dcx.tcx, |s, a| this.convert_def_id(xcx, s, a))) }).unwrap() } fn read_auto_adjustment(&mut self, xcx: &ExtendedDecodeContext) -> ty::AutoAdjustment { self.read_enum("AutoAdjustment", |this| { let variants = ["AutoAddEnv", "AutoDerefRef", "AutoObject"]; this.read_enum_variant(variants, |this, i| { Ok(match i { 0 => { let store: ty::TraitStore = this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap(); ty:: AutoAddEnv(store.tr(xcx)) } 1 => { let auto_deref_ref: ty::AutoDerefRef = this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap(); ty::AutoDerefRef(auto_deref_ref.tr(xcx)) } 2 => { let store: ty::TraitStore = this.read_enum_variant_arg(0, |this| Decodable::decode(this)).unwrap(); let b: ty::BuiltinBounds = this.read_enum_variant_arg(1, |this| Decodable::decode(this)).unwrap(); let def_id: ast::DefId = this.read_enum_variant_arg(2, |this| Decodable::decode(this)).unwrap(); let substs = this.read_enum_variant_arg(3, |this| Ok(this.read_substs(xcx))) .unwrap(); ty::AutoObject(store.tr(xcx), b, def_id.tr(xcx), substs) } _ => fail!("bad enum variant for ty::AutoAdjustment") }) }) }).unwrap() } fn convert_def_id(&mut self, xcx: &ExtendedDecodeContext, source: tydecode::DefIdSource, did: ast::DefId) -> ast::DefId { /*! * Converts a def-id that appears in a type. The correct * translation will depend on what kind of def-id this is. * This is a subtle point: type definitions are not * inlined into the current crate, so if the def-id names * a nominal type or type alias, then it should be * translated to refer to the source crate. * * However, *type parameters* are cloned along with the function * they are attached to. So we should translate those def-ids * to refer to the new, cloned copy of the type parameter. * We only see references to free type parameters in the body of * an inlined function. In such cases, we need the def-id to * be a local id so that the TypeContents code is able to lookup * the relevant info in the ty_param_defs table. * * *Region parameters*, unfortunately, are another kettle of fish. * In such cases, def_id's can appear in types to distinguish * shadowed bound regions and so forth. It doesn't actually * matter so much what we do to these, since regions are erased * at trans time, but it's good to keep them consistent just in * case. We translate them with `tr_def_id()` which will map * the crate numbers back to the original source crate. * * It'd be really nice to refactor the type repr to not include * def-ids so that all these distinctions were unnecessary. */ let r = match source { NominalType | TypeWithId | RegionParameter => xcx.tr_def_id(did), TypeParameter => xcx.tr_intern_def_id(did) }; debug!("convert_def_id(source={:?}, did={:?})={:?}", source, did, r); return r; } } fn decode_side_tables(xcx: &ExtendedDecodeContext, ast_doc: ebml::Doc) { let dcx = xcx.dcx; let tbl_doc = ast_doc.get(c::tag_table as uint); reader::docs(tbl_doc, |tag, entry_doc| { let id0 = entry_doc.get(c::tag_table_id as uint).as_int(); let id = xcx.tr_id(id0 as ast::NodeId); debug!(">> Side table document with tag 0x{:x} \ found for id {} (orig {})", tag, id, id0); match c::astencode_tag::from_uint(tag) { None => { xcx.dcx.tcx.sess.bug( format!("unknown tag found in side tables: {:x}", tag).as_slice()); } Some(value) => { let val_doc = entry_doc.get(c::tag_table_val as uint); let mut val_dsr = reader::Decoder::new(val_doc); let val_dsr = &mut val_dsr; match value { c::tag_table_def => { let def = decode_def(xcx, val_doc); dcx.tcx.def_map.borrow_mut().insert(id, def); } c::tag_table_node_type => { let ty = val_dsr.read_ty(xcx); debug!("inserting ty for node {:?}: {}", id, ty_to_str(dcx.tcx, ty)); dcx.tcx.node_types.borrow_mut().insert(id as uint, ty); } c::tag_table_item_subst => { let item_substs = ty::ItemSubsts { substs: val_dsr.read_substs(xcx) }; dcx.tcx.item_substs.borrow_mut().insert( id, item_substs); } c::tag_table_freevars => { let fv_info = val_dsr.read_to_vec(|val_dsr| { Ok(val_dsr.read_freevar_entry(xcx)) }).unwrap().move_iter().collect(); dcx.tcx.freevars.borrow_mut().insert(id, fv_info); } c::tag_table_tcache => { let pty = val_dsr.read_polytype(xcx); let lid = ast::DefId { krate: ast::LOCAL_CRATE, node: id }; dcx.tcx.tcache.borrow_mut().insert(lid, pty); } c::tag_table_param_defs => { let bounds = val_dsr.read_type_param_def(xcx); dcx.tcx.ty_param_defs.borrow_mut().insert(id, bounds); } c::tag_table_method_map => { let (adjustment, method) = val_dsr.read_method_callee(xcx); let method_call = MethodCall { expr_id: id, adjustment: adjustment }; dcx.tcx.method_map.borrow_mut().insert(method_call, method); } c::tag_table_vtable_map => { let (adjustment, vtable_res) = val_dsr.read_vtable_res_with_key(xcx.dcx.tcx, xcx.dcx.cdata); let vtable_key = MethodCall { expr_id: id, adjustment: adjustment }; dcx.tcx.vtable_map.borrow_mut().insert(vtable_key, vtable_res); } c::tag_table_adjustments => { let adj: ty::AutoAdjustment = val_dsr.read_auto_adjustment(xcx); dcx.tcx.adjustments.borrow_mut().insert(id, adj); } _ => { xcx.dcx.tcx.sess.bug( format!("unknown tag found in side tables: {:x}", tag).as_slice()); } } } } debug!(">< Side table doc loaded"); true }); } // ______________________________________________________________________ // Testing of astencode_gen #[cfg(test)] fn encode_item_ast(ebml_w: &mut Encoder, item: Gc<ast::Item>) { ebml_w.start_tag(c::tag_tree as uint); (*item).encode(ebml_w); ebml_w.end_tag(); } #[cfg(test)] fn decode_item_ast(par_doc: ebml::Doc) -> Gc<ast::Item> { let chi_doc = par_doc.get(c::tag_tree as uint); let mut d = reader::Decoder::new(chi_doc); box(GC) Decodable::decode(&mut d).unwrap() } #[cfg(test)] trait fake_ext_ctxt { fn cfg(&self) -> ast::CrateConfig; fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess; fn call_site(&self) -> Span; fn ident_of(&self, st: &str) -> ast::Ident; } #[cfg(test)] impl fake_ext_ctxt for parse::ParseSess { fn cfg(&self) -> ast::CrateConfig { Vec::new() } fn parse_sess<'a>(&'a self) -> &'a parse::ParseSess { self } fn call_site(&self) -> Span { codemap::Span { lo: codemap::BytePos(0), hi: codemap::BytePos(0), expn_info: None } } fn ident_of(&self, st: &str) -> ast::Ident { token::str_to_ident(st) } } #[cfg(test)] fn mk_ctxt() -> parse::ParseSess { parse::new_parse_sess() } #[cfg(test)] fn roundtrip(in_item: Option<Gc<ast::Item>>) { use std::io::MemWriter; let in_item = in_item.unwrap(); let mut wr = MemWriter::new(); { let mut ebml_w = writer::Encoder::new(&mut wr); encode_item_ast(&mut ebml_w, in_item); } let ebml_doc = ebml::Doc::new(wr.get_ref()); let out_item = decode_item_ast(ebml_doc); assert!(in_item == out_item); } #[test] fn test_basic() { let cx = mk_ctxt(); roundtrip(quote_item!(cx, fn foo() {} )); } #[test] fn test_smalltalk() { let cx = mk_ctxt(); roundtrip(quote_item!(cx, fn foo() -> int { 3 + 4 } // first smalltalk program ever executed. )); } #[test] fn test_more() { let cx = mk_ctxt(); roundtrip(quote_item!(cx, fn foo(x: uint, y: uint) -> uint { let z = x + y; return z; } )); } #[test] fn test_simplification() { let cx = mk_ctxt(); let item = quote_item!(&cx, fn new_int_alist<B>() -> alist<int, B> { fn eq_int(a: int, b: int) -> bool { a == b } return alist {eq_fn: eq_int, data: Vec::new()}; } ).unwrap(); let item_in = e::IIItemRef(item); let item_out = simplify_ast(item_in); let item_exp = ast::IIItem(quote_item!(cx, fn new_int_alist<B>() -> alist<int, B> { return alist {eq_fn: eq_int, data: Vec::new()}; } ).unwrap()); match (item_out, item_exp) { (ast::IIItem(item_out), ast::IIItem(item_exp)) => { assert!(pprust::item_to_str(item_out) == pprust::item_to_str(item_exp)); } _ => fail!() } }
{'content_hash': '5b6e5b51e3a45dfc5494ee99066ce8e6', 'timestamp': '', 'source': 'github', 'line_count': 1568, 'max_line_length': 100, 'avg_line_length': 37.11798469387755, 'alnum_prop': 0.4861084861084861, 'repo_name': 'pfalabella/rust', 'id': '19e7b9329b1ff218a9f25627766706e19732b98a', 'size': '58201', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/librustc/middle/astencode.rs', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=iso-8859-1"> <title>FLAC: Member List</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.4.2 --> <div class="qindex"><a class="qindex" href="index.html">Main&nbsp;Page</a> | <a class="qindex" href="modules.html">Modules</a> | <a class="qindex" href="hierarchy.html">Class&nbsp;Hierarchy</a> | <a class="qindex" href="classes.html">Alphabetical&nbsp;List</a> | <a class="qindex" href="annotated.html">Class&nbsp;List</a> | <a class="qindex" href="dirs.html">Directories</a> | <a class="qindex" href="files.html">File&nbsp;List</a> | <a class="qindex" href="functions.html">Class&nbsp;Members</a> | <a class="qindex" href="globals.html">File&nbsp;Members</a></div> <h1>FLAC::Metadata::SimpleIterator::Status Member List</h1>This is the complete list of members for <a class="el" href="classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status.html">FLAC::Metadata::SimpleIterator::Status</a>, including all inherited members.<p><table> <tr bgcolor="#f0f0f0"><td><b>as_cstring</b>() const (defined in <a class="el" href="classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status.html">FLAC::Metadata::SimpleIterator::Status</a>)</td><td><a class="el" href="classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status.html">FLAC::Metadata::SimpleIterator::Status</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>operator::FLAC__Metadata_SimpleIteratorStatus</b>() const (defined in <a class="el" href="classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status.html">FLAC::Metadata::SimpleIterator::Status</a>)</td><td><a class="el" href="classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status.html">FLAC::Metadata::SimpleIterator::Status</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>Status</b>(::FLAC__Metadata_SimpleIteratorStatus status) (defined in <a class="el" href="classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status.html">FLAC::Metadata::SimpleIterator::Status</a>)</td><td><a class="el" href="classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status.html">FLAC::Metadata::SimpleIterator::Status</a></td><td><code> [inline]</code></td></tr> <tr bgcolor="#f0f0f0"><td><b>status_</b> (defined in <a class="el" href="classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status.html">FLAC::Metadata::SimpleIterator::Status</a>)</td><td><a class="el" href="classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status.html">FLAC::Metadata::SimpleIterator::Status</a></td><td><code> [protected]</code></td></tr> </table> <hr size="1"> <div class="copyright"> <!-- @@@ oh so hacky --> <table> <tr> <td align="left"> Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson </td> <td width="1%" align="right"> <a href="http://sourceforge.net"><img src="http://sflogo.sourceforge.net/sflogo.php?group_id=13478&amp;type=1" width="88" height="31" border="0" alt="SourceForge.net Logo" /></a> </td> </tr> </table> </div> <!-- Copyright (c) 2000,2001,2002,2003,2004,2005,2006,2007 Josh Coalson --> <!-- Permission is granted to copy, distribute and/or modify this document --> <!-- under the terms of the GNU Free Documentation License, Version 1.1 --> <!-- or any later version published by the Free Software Foundation; --> <!-- with no invariant sections. --> <!-- A copy of the license can be found at http://www.gnu.org/copyleft/fdl.html --> </body> </html>
{'content_hash': '195986697543c0c20657cbe4f95ac97a', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 565, 'avg_line_length': 99.48571428571428, 'alnum_prop': 0.699310740953475, 'repo_name': 'kyleconroy/golds', 'id': '8aee35f6a2f19118891d5a11c7207072b2481a52', 'size': '3482', 'binary': False, 'copies': '111', 'ref': 'refs/heads/master', 'path': 'vendor/sdl2_mixer/external/flac-1.2.1/doc/html/api/classFLAC_1_1Metadata_1_1SimpleIterator_1_1Status-members.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Go', 'bytes': '131477'}]}
<!DOCTYPE HTML> <!-- AUTO GENERATED - DO NOT MODIFY --> <html> <head> <title>jQuery (2.x) Test Suite</title> <base href="../../" /> <!--[if IE]> <script type="text/javascript"> // Fix for IE ignoring relative base tags. (function() { var baseTag = document.getElementsByTagName( 'base')[0]; var loc = window.location.toString(); var location = loc.substring(0, loc.lastIndexOf( '/') + 1); baseTag.href = location + '../../'; })(); </script> <![endif]--> <link rel="stylesheet" type="text/css" href="bower_components/qunit/qunit/qunit.css" /> <script type="text/javascript" src="../../bower_components/html5shiv/dist/html5shiv.js"></script> </head> <body> <h1 id="qunit-header">jQuery (2.x) Test Suite</h1> <h2 id="qunit-banner"></h2> <div id="qunit-testrunner-toolbar"></div> <h2 id="qunit-userAgent"></h2> <ol id="qunit-tests"></ol> <div id="qunit-test-area"></div> <div id="qunit-fixture"></div> <script type="text/javascript" src="bower_components/qunit/qunit/qunit.js"></script> <script type="text/javascript"> QUnit.config.autostart = false; </script> <script type="text/javascript" src="bower_components/jquery/dist/jquery.js"></script> <script type="text/javascript" src="dist/can.jquery.js"></script> <script type="text/javascript" src="dist/can.list.promise.js"></script> <script type="text/javascript" src="dist/can.ejs.js"></script> <script type="text/javascript" src="dist/can.stache.js"></script> <script type="text/javascript" src="dist/can.route.pushstate.js"></script> <script type="text/javascript" src="dist/can.model.queue.js"></script> <script type="text/javascript" src="dist/can.construct.super.js"></script> <script type="text/javascript" src="dist/can.construct.proxy.js"></script> <script type="text/javascript" src="dist/can.map.lazy.js"></script> <script type="text/javascript" src="dist/can.map.delegate.js"></script> <script type="text/javascript" src="dist/can.map.setter.js"></script> <script type="text/javascript" src="dist/can.map.attributes.js"></script> <script type="text/javascript" src="dist/can.map.validations.js"></script> <script type="text/javascript" src="dist/can.map.backup.js"></script> <script type="text/javascript" src="dist/can.map.list.js"></script> <script type="text/javascript" src="dist/can.map.define.js"></script> <script type="text/javascript" src="dist/can.list.sort.js"></script> <script type="text/javascript" src="dist/can.control.plugin.js"></script> <script type="text/javascript" src="dist/can.view.modifiers.js"></script> <script type="text/javascript" src="dist/can.object.js"></script> <script type="text/javascript" src="dist/can.fixture.js"></script> <script type="text/javascript" src="dist/can.autorender.js"></script> <script type="text/javascript" src="test/pluginified/latest.js"></script> <script type="text/javascript"> window.require = undefined; QUnit.start(); </script> </body> </html>
{'content_hash': 'ee5053e7d2422b968f28f6b027657cad', 'timestamp': '', 'source': 'github', 'line_count': 73, 'max_line_length': 105, 'avg_line_length': 47.61643835616438, 'alnum_prop': 0.5865937859608745, 'repo_name': 'ackl/canjs', 'id': '251400c5bdb115c7742357cc82d9dc2d3fe23a91', 'size': '3476', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'test/dist/jquery-2.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '20766'}, {'name': 'HTML', 'bytes': '340836'}, {'name': 'JavaScript', 'bytes': '3071315'}, {'name': 'Ruby', 'bytes': '886'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v0.4.10 - v0.4.12: v8::internal::InternalConstants&lt; ptr_size &gt; Struct Template Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v0.4.10 - v0.4.12 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="hierarchy.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><b>internal</b></li><li class="navelem"><a class="el" href="structv8_1_1internal_1_1_internal_constants.html">InternalConstants</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::internal::InternalConstants&lt; ptr_size &gt; Struct Template Reference</div> </div> </div><!--header--> <div class="contents"> <hr/>The documentation for this struct was generated from the following file:<ul> <li>deps/v8/include/<a class="el" href="v8_8h_source.html">v8.h</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Tue Aug 11 2015 23:46:58 for V8 API Reference Guide for node.js v0.4.10 - v0.4.12 by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{'content_hash': 'e4db61f9c00b50080fe213493dff2fe6', 'timestamp': '', 'source': 'github', 'line_count': 106, 'max_line_length': 232, 'avg_line_length': 43.764150943396224, 'alnum_prop': 0.6477689157145936, 'repo_name': 'v8-dox/v8-dox.github.io', 'id': '55ddfd0160220eb4cc8bc24cd213e5117cc88e3b', 'size': '4639', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '9f9a4cb/html/structv8_1_1internal_1_1_internal_constants.html', 'mode': '33188', 'license': 'mit', 'language': []}
/******************************************************************************* * _____ _ _____ _____ ___ * / ___| | | / ___/ __ \ / _ \ * \ `--. ___ __ _| | __ _\ `--.| / \// /_\ \ * `--. \/ __/ _` | |/ _` |`--. \ | | _ | * /\__/ / (_| (_| | | (_| /\__/ / \__/\| | | | * \____/ \___\__,_|_|\__,_\____/ \____/\_| |_/ * * Static Code Analyser for Scala. * (c) 2014, LARA/EPFL, Typesafe * * Author: Jean Andre GAUTHIER * Supervisors: Dr. Viktor KUNCAK, Iulian DRAGOS ******************************************************************************/ package lara.epfl.scalasca.rules import lara.epfl.scalasca.core._ import scala.tools.nsc._ import scala.actors.Actor class DefaultRule[T <: Global](val global: T, sourcePath: String, inputResults: List[RuleResult] = List()) extends Rule { import global._ type RR = NoResult override val ruleName = "GEN_DEFAULT" def apply(syntaxTree: Tree): NoResult = { // val constProp = (new BlockConstantPropagation[global.type](global, inputResults)).apply(syntaxTree) // val cfg = (new IntraProceduralControlFlowGraphGenerator[global.type](global, inputResults)).apply(syntaxTree) // val intermediateResults: List[RuleResult] = constProp :: List(cfg) val intermediateResults: List[RuleResult] = List() // val divByZero = (new DivisionByZero[global.type](global, intermediateResults)).apply(syntaxTree) // val emptyFinallys = (new EmptyFinally[global.type](global, intermediateResults)).apply(syntaxTree) // val doubleTripleEquals = (new DoubleTripleEquals[global.type, Actor](global, intermediateResults)).apply(syntaxTree) val unfreedResources = (new UnfreedResourcesControlFlowAnalysis[global.type](global, TermName("open"), TermName("close"), intermediateResults)).apply(syntaxTree) // val codeRemoval = new UnusedCodeRemoval[global.type](global, intermediateResults) // val uselessAssignment = new UselessAssignment[global.type](global, intermediateResults) // val finalResults = ASTRule.apply(global)(syntaxTree, List(divByZero, emptyFinallys, doubleTripleEquals)) // val freeRessources = (new FreeResourceControlFlowAnalysis[global.type](global, q"scala.io.Source.fromFile", q"close")).apply(syntaxTree, computedResults) // (new ShowWarnings[global.type](global, sourcePath, finalResults)).apply(syntaxTree) NoResult() } }
{'content_hash': 'c65af37b88ffdc9a5a45de784a05b814', 'timestamp': '', 'source': 'github', 'line_count': 48, 'max_line_length': 163, 'avg_line_length': 48.958333333333336, 'alnum_prop': 0.6229787234042553, 'repo_name': 'jean-andre-gauthier/scalasca', 'id': '1f6f073dea4d95431111cc4b4d6696e67b730975', 'size': '2350', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/scala/lara/epfl/scalasca/rules/DefaultRule.scala', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Scala', 'bytes': '129972'}, {'name': 'Shell', 'bytes': '571'}, {'name': 'TeX', 'bytes': '106112'}]}
#include "mbedtls_stub.h" mbedtls_stub_def mbedtls_stub; //From ssl.h int mbedtls_ssl_handshake_step( mbedtls_ssl_context *ssl ) { if( mbedtls_stub.useCounter ){ if( mbedtls_stub.retArray[mbedtls_stub.counter] == HANDSHAKE_FINISHED_VALUE || mbedtls_stub.retArray[mbedtls_stub.counter] == HANDSHAKE_FINISHED_VALUE_RETURN_ZERO){ ssl->state = MBEDTLS_SSL_HANDSHAKE_OVER; if(mbedtls_stub.retArray[mbedtls_stub.counter] == HANDSHAKE_FINISHED_VALUE_RETURN_ZERO) return 0; } return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } int mbedtls_ssl_close_notify( mbedtls_ssl_context *a ) { if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } void mbedtls_ssl_init( mbedtls_ssl_context *a ){ } void mbedtls_ssl_conf_min_version( mbedtls_ssl_config *conf, int major, int minor ){ } void mbedtls_ssl_conf_max_version( mbedtls_ssl_config *conf, int major, int minor ){ } void mbedtls_ssl_config_init( mbedtls_ssl_config *a ){ } void mbedtls_ssl_conf_handshake_timeout( mbedtls_ssl_config *a, uint32_t b, uint32_t c) { } void mbedtls_ssl_free( mbedtls_ssl_context *a ){ } int mbedtls_ssl_conf_own_cert( mbedtls_ssl_config *a, mbedtls_x509_crt *b, mbedtls_pk_context *c ){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } void mbedtls_ssl_conf_authmode( mbedtls_ssl_config *a, int c ){ } void mbedtls_ssl_conf_ca_chain( mbedtls_ssl_config *a, mbedtls_x509_crt *b, mbedtls_x509_crl *c ){ } int mbedtls_ssl_conf_psk( mbedtls_ssl_config *a, const unsigned char *b, size_t c, const unsigned char *d, size_t e ){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } int mbedtls_ssl_config_defaults( mbedtls_ssl_config *a, int b, int c, int d){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } void mbedtls_ssl_conf_rng( mbedtls_ssl_config *a, int (*f_rng)(void *, unsigned char *, size_t), void *b ){ } void mbedtls_ssl_conf_ciphersuites( mbedtls_ssl_config *a, const int *b) { } int mbedtls_ssl_setup( mbedtls_ssl_context *a, const mbedtls_ssl_config *b ){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } void mbedtls_ssl_set_bio( mbedtls_ssl_context *ssl, void *p_bio, int (*f_send)(void *, const unsigned char *, size_t), int (*f_recv)(void *, unsigned char *, size_t), int (*f_recv_timeout)(void *, unsigned char *, size_t, uint32_t) ){ if( p_bio != NULL ){ if( f_send ) f_send( p_bio, NULL, 0 ); if( f_recv ) f_recv( p_bio, NULL, 0 ); if( f_recv_timeout ) f_recv_timeout( p_bio, NULL, 0, 0 ); } } void mbedtls_ssl_set_timer_cb( mbedtls_ssl_context *a, void *ctx, void (*f_set_timer)(void *, uint32_t int_ms, uint32_t fin_ms), int (*f_get_timer)(void *) ){ f_set_timer(ctx, 1, 2); f_get_timer(ctx); if(mbedtls_stub.invalidate_timer){ f_set_timer(ctx, 0, 0); } f_get_timer(ctx); } int mbedtls_ssl_handshake( mbedtls_ssl_context *ssl ){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } uint32_t mbedtls_ssl_get_verify_result( const mbedtls_ssl_context *a ){ return mbedtls_stub.uint32_value; } int mbedtls_ssl_read( mbedtls_ssl_context *a, unsigned char *b, size_t c){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } int mbedtls_ssl_write( mbedtls_ssl_context *a, const unsigned char *b, size_t c ){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } //From crt_drbg.h int mbedtls_ctr_drbg_seed( mbedtls_ctr_drbg_context *a, int (*f_entropy)(void *, unsigned char *, size_t), void *b, const unsigned char *c, size_t d ){ return mbedtls_stub.crt_expected_int; } void mbedtls_ctr_drbg_init( mbedtls_ctr_drbg_context *a ){ } void mbedtls_ctr_drbg_free( mbedtls_ctr_drbg_context *a ){ } int mbedtls_ctr_drbg_random_with_add( void *a, unsigned char *b, size_t c, const unsigned char *d, size_t e ){ return mbedtls_stub.crt_expected_int; } int mbedtls_ctr_drbg_random( void *p_rng, unsigned char *output, size_t output_len ){ return mbedtls_stub.crt_expected_int; } //From x509_crt.h void mbedtls_x509_crt_init( mbedtls_x509_crt *a ){ } void mbedtls_x509_crt_free( mbedtls_x509_crt *a ){ } int mbedtls_x509_crt_parse( mbedtls_x509_crt *a, const unsigned char *b, size_t c ){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } //From entropy.h void mbedtls_entropy_init( mbedtls_entropy_context *a ){ } void mbedtls_entropy_free( mbedtls_entropy_context *ctx ){ } int mbedtls_entropy_func( void *a, unsigned char *b, size_t c ){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } int mbedtls_entropy_add_source( mbedtls_entropy_context *a, mbedtls_entropy_f_source_ptr f_source, void *b, size_t c, int d ){ unsigned char buf[2]; size_t len; f_source(NULL, buf, 1, &len); if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } //From pk.h int mbedtls_pk_parse_key( mbedtls_pk_context *a, const unsigned char *b, size_t c, const unsigned char *d, size_t e ){ if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } void mbedtls_pk_init( mbedtls_pk_context *ctx ) { } void mbedtls_pk_free( mbedtls_pk_context *ctx ) { } void mbedtls_ssl_config_free( mbedtls_ssl_config *a) { } int mbedtls_ssl_set_hs_ecjpake_password( mbedtls_ssl_context *ssl, const unsigned char *pw, size_t pw_len ) { if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; } void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf, mbedtls_ssl_cookie_write_t *f_cookie_write, mbedtls_ssl_cookie_check_t *f_cookie_check, void *p_cookie ) { if( mbedtls_stub.cookie_obj && f_cookie_check && mbedtls_stub.cookie_len > 0 ){ f_cookie_check(mbedtls_stub.cookie_obj, &mbedtls_stub.cookie_value, mbedtls_stub.cookie_len, NULL, 0); } if( mbedtls_stub.cookie_obj && f_cookie_write && mbedtls_stub.cookie_len > 0 ){ unsigned char out[16]; unsigned char *ptr = &out; f_cookie_write(mbedtls_stub.cookie_obj, &ptr, ptr+mbedtls_stub.cookie_len, NULL, 0); } } void mbedtls_ssl_conf_export_keys_cb( mbedtls_ssl_config *conf, mbedtls_ssl_export_keys_t *f_export_keys, void *p_export_keys ) { if( f_export_keys && p_export_keys){ unsigned char value[40]; memset(&value, 1, 40); f_export_keys(p_export_keys, &value, "", 0, 0,0); //failure case f_export_keys(p_export_keys, &value, "", 0, 20,0); //success case } } int mbedtls_ssl_session_reset( mbedtls_ssl_context *ssl ) { if( mbedtls_stub.useCounter ){ return mbedtls_stub.retArray[mbedtls_stub.counter++]; } return mbedtls_stub.expected_int; }
{'content_hash': 'ae520ad69cb8c57e0c93e448a5f171a4', 'timestamp': '', 'source': 'github', 'line_count': 308, 'max_line_length': 110, 'avg_line_length': 27.82792207792208, 'alnum_prop': 0.5989966164974916, 'repo_name': 'Archcady/mbed-os', 'id': '8ee286f8408b34fe7baafd1605c7b69078094dcd', 'size': '9230', 'binary': False, 'copies': '19', 'ref': 'refs/heads/master', 'path': 'features/nanostack/FEATURE_NANOSTACK/coap-service/test/coap-service/unittest/stub/mbedtls_stub.c', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '6762118'}, {'name': 'Batchfile', 'bytes': '22'}, {'name': 'C', 'bytes': '309779349'}, {'name': 'C++', 'bytes': '9669540'}, {'name': 'CMake', 'bytes': '5285'}, {'name': 'HTML', 'bytes': '2063156'}, {'name': 'Makefile', 'bytes': '122828'}, {'name': 'Objective-C', 'bytes': '66073'}, {'name': 'Perl', 'bytes': '2589'}, {'name': 'Python', 'bytes': '53026'}, {'name': 'Shell', 'bytes': '70904'}, {'name': 'XSLT', 'bytes': '5596'}]}
package org.apache.flink.optimizer.operators; import org.apache.flink.api.common.Plan; import org.apache.flink.api.common.functions.JoinFunction; import org.apache.flink.api.java.DataSet; import org.apache.flink.api.java.ExecutionEnvironment; import org.apache.flink.api.java.io.DiscardingOutputFormat; import org.apache.flink.api.java.tuple.Tuple3; import org.apache.flink.api.java.utils.DataSetUtils; import org.apache.flink.optimizer.plan.*; import org.apache.flink.optimizer.util.CompilerTestBase; import org.apache.flink.runtime.operators.shipping.ShipStrategyType; import org.junit.Test; import static org.junit.Assert.assertEquals; public class JoinWithDistributionTest extends CompilerTestBase { @Test public void JoinWithSameDistributionTest() throws Exception { ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<Tuple3<Integer, Integer, Integer>> set1 = env.readCsvFile(IN_FILE).types(Integer.class, Integer.class, Integer.class); DataSet<Tuple3<Integer, Integer, Integer>> set2 = env.readCsvFile(IN_FILE).types(Integer.class, Integer.class, Integer.class); TestDistribution dist1 = new TestDistribution(3); TestDistribution dist2 = new TestDistribution(3); DataSet<Tuple3<Integer, Integer, Integer>> coGrouped = DataSetUtils.partitionByRange(set1, dist1, 0) .join(DataSetUtils.partitionByRange(set2, dist2, 0)) .where(0) .equalTo(0) .with(new JoinFunc()); coGrouped.output(new DiscardingOutputFormat<Tuple3<Integer, Integer, Integer>>()); Plan plan = env.createProgramPlan(); OptimizedPlan oPlan = compileWithStats(plan); SinkPlanNode sink = oPlan.getDataSinks().iterator().next(); DualInputPlanNode join = (DualInputPlanNode) sink.getInput().getSource(); Channel input1 = join.getInput1(); Channel input2 = join.getInput2(); assertEquals(ShipStrategyType.FORWARD, input1.getShipStrategy()); assertEquals(ShipStrategyType.FORWARD, input2.getShipStrategy()); } @Test public void JoinWithDifferentDistributionTest() throws Exception { ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment(); DataSet<Tuple3<Integer, Integer, Integer>> set1 = env.readCsvFile(IN_FILE).types(Integer.class, Integer.class, Integer.class); DataSet<Tuple3<Integer, Integer, Integer>> set2 = env.readCsvFile(IN_FILE).types(Integer.class, Integer.class, Integer.class); TestDistribution dist1 = new TestDistribution(3); TestDistribution dist2 = new TestDistribution(4); DataSet<Tuple3<Integer, Integer, Integer>> coGrouped = DataSetUtils.partitionByRange(set1, dist1, 0) .join(DataSetUtils.partitionByRange(set2, dist2, 0)) .where(0) .equalTo(0) .with(new JoinFunc()); coGrouped.output(new DiscardingOutputFormat<Tuple3<Integer, Integer, Integer>>()); Plan plan = env.createProgramPlan(); OptimizedPlan oPlan = compileWithStats(plan); SinkPlanNode sink = oPlan.getDataSinks().iterator().next(); DualInputPlanNode join = (DualInputPlanNode) sink.getInput().getSource(); Channel input1 = join.getInput1(); Channel input2 = join.getInput2(); assertEquals(ShipStrategyType.PARTITION_HASH, input1.getShipStrategy()); assertEquals(ShipStrategyType.PARTITION_HASH, input2.getShipStrategy()); } public static class JoinFunc implements JoinFunction< Tuple3<Integer, Integer, Integer>, Tuple3<Integer, Integer, Integer>, Tuple3<Integer, Integer, Integer>> { @Override public Tuple3<Integer, Integer, Integer> join( Tuple3<Integer, Integer, Integer> first, Tuple3<Integer, Integer, Integer> second) throws Exception { return null; } } }
{'content_hash': '3811d7a5fe346bb4d52ee06ca23d3c3f', 'timestamp': '', 'source': 'github', 'line_count': 95, 'max_line_length': 98, 'avg_line_length': 44.0, 'alnum_prop': 0.6660287081339713, 'repo_name': 'clarkyzl/flink', 'id': '6fba6f7d52b3bbac953ef3821789cba833845d2b', 'size': '4985', 'binary': False, 'copies': '17', 'ref': 'refs/heads/master', 'path': 'flink-optimizer/src/test/java/org/apache/flink/optimizer/operators/JoinWithDistributionTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '4792'}, {'name': 'CSS', 'bytes': '18100'}, {'name': 'CoffeeScript', 'bytes': '89007'}, {'name': 'HTML', 'bytes': '86524'}, {'name': 'Java', 'bytes': '31467756'}, {'name': 'JavaScript', 'bytes': '8267'}, {'name': 'Python', 'bytes': '166860'}, {'name': 'Scala', 'bytes': '5921090'}, {'name': 'Shell', 'bytes': '92059'}]}
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>AWSIoTTopicRuleListItem Class Reference</title> <link rel="stylesheet" href="../css/style.css"> <meta name="viewport" content="initial-scale=1, maximum-scale=1.4"> <meta name="generator" content="appledoc 2.2.1 (build 1333)"> </head> <body class="appledoc"> <header> <div class="container" class="hide-in-xcode"> <h1 id="library-title"> <a href="../index.html">AWS Mobile SDK for iOS v2.4.1 </a> </h1> <p id="developer-home"> <a href="../index.html">Amazon Web Services, Inc.</a> </p> </div> </header> <aside> <div class="container"> <nav> <ul id="header-buttons" role="toolbar"> <li><a href="../index.html">Index</a></li> <li><a href="../hierarchy.html">Hierarchy</a></li> <li id="on-this-page" role="navigation"> <label> On This Page <div class="chevron"> <div class="chevy chevron-left"></div> <div class="chevy chevron-right"></div> </div> <select id="jump-to"> <option value="top">Jump To&#133;</option> <option value="overview">Overview</option> <option value="tasks">Tasks</option> <optgroup label="Properties"> <option value="//api/name/createdAt">createdAt</option> <option value="//api/name/ruleDisabled">ruleDisabled</option> <option value="//api/name/ruleName">ruleName</option> <option value="//api/name/topicPattern">topicPattern</option> </optgroup> </select> </label> </li> </ul> </nav> </div> </aside> <article> <div id="overview_contents" class="container"> <div id="content"> <main role="main"> <h1 class="title">AWSIoTTopicRuleListItem Class Reference</h1> <div class="section section-specification"><table cellspacing="0"><tbody> <tr> <th>Inherits from</th> <td>AWSModel : AWSMTLModel</td> </tr><tr> <th>Declared in</th> <td>AWSIoTModel.h<br />AWSIoTModel.m</td> </tr> </tbody></table></div> <div class="section section-overview"> <a title="Overview" name="overview"></a> <h2 class="subtitle subtitle-overview">Overview</h2> <p>Describes a rule.</p> </div> <div class="section section-tasks"> <a title="Tasks" name="tasks"></a> <div class="task-list"> <div class="section-method"> <a name="//api/name/createdAt" title="createdAt"></a> <h3 class="method-title"><code><a href="#//api/name/createdAt">&nbsp;&nbsp;createdAt</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>The date and time the rule was created.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) NSDate *createdAt</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">AWSIoTModel.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/ruleDisabled" title="ruleDisabled"></a> <h3 class="method-title"><code><a href="#//api/name/ruleDisabled">&nbsp;&nbsp;ruleDisabled</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>Specifies whether the rule is disabled.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) NSNumber *ruleDisabled</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">AWSIoTModel.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/ruleName" title="ruleName"></a> <h3 class="method-title"><code><a href="#//api/name/ruleName">&nbsp;&nbsp;ruleName</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>The name of the rule.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) NSString *ruleName</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">AWSIoTModel.h</code></p> </div> </div> </div> </div><div class="section-method"> <a name="//api/name/topicPattern" title="topicPattern"></a> <h3 class="method-title"><code><a href="#//api/name/topicPattern">&nbsp;&nbsp;topicPattern</a></code> </h3> <div class="method-info"> <div class="pointy-thing"></div> <div class="method-info-container"> <div class="method-subsection brief-description"> <p>The pattern for the topic names that apply.</p> </div> <div class="method-subsection method-declaration"><code>@property (nonatomic, strong) NSString *topicPattern</code></div> <div class="method-subsection declared-in-section"> <h4 class="method-subtitle">Declared In</h4> <p><code class="declared-in-ref">AWSIoTModel.h</code></p> </div> </div> </div> </div> </div> </div> </main> <footer> <div class="footer-copyright"> <p class="copyright">Copyright &copy; 2016 Amazon Web Services, Inc. All rights reserved. Updated: 2016-04-28</p> <p class="generator">Generated by <a href="http://appledoc.gentlebytes.com">appledoc 2.2.1 (build 1333)</a>.</p> </div> </footer> </div> </div> </article> <script src="../js/script.js"></script> </body> </html>
{'content_hash': '14052685e729adee3ef0372580b6b5e6', 'timestamp': '', 'source': 'github', 'line_count': 315, 'max_line_length': 124, 'avg_line_length': 19.377777777777776, 'alnum_prop': 0.5925622542595019, 'repo_name': 'davidbutz/ChristmasFamDuels', 'id': '44922c35c875fb1340eaeb3c9a6021a19924da8f', 'size': '6104', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'iOS/frameworks/aws-ios-sdk-2.4.1/documentation/html/Classes/AWSIoTTopicRuleListItem.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '211'}, {'name': 'CSS', 'bytes': '77'}, {'name': 'HTML', 'bytes': '330'}, {'name': 'JavaScript', 'bytes': '212297'}, {'name': 'Objective-C', 'bytes': '3465743'}, {'name': 'Ruby', 'bytes': '461'}, {'name': 'Shell', 'bytes': '2569'}, {'name': 'Swift', 'bytes': '325330'}]}
export interface CollapseClasses { /** Styles applied to the root element. */ root: string; /** State class applied to the root element if `orientation="horizontal"`. */ horizontal: string; /** Styles applied to the root element when the transition has entered. */ entered: string; /** Styles applied to the root element when the transition has exited and `collapsedSize` = 0px. */ hidden: string; /** Styles applied to the outer wrapper element. */ wrapper: string; /** Styles applied to the inner wrapper element. */ wrapperInner: string; } export declare type CollapseClassKey = keyof CollapseClasses; export declare function getCollapseUtilityClass(slot: string): string; declare const collapseClasses: CollapseClasses; export default collapseClasses;
{'content_hash': '8726a7bea5df2bbfb61c81ee89c1d757', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 103, 'avg_line_length': 45.666666666666664, 'alnum_prop': 0.7104622871046229, 'repo_name': 'cdnjs/cdnjs', 'id': 'bfec1795e84232f77df0541c7e1dc33878337fcc', 'size': '822', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'ajax/libs/material-ui/5.0.0-beta.5/Collapse/collapseClasses.d.ts', 'mode': '33188', 'license': 'mit', 'language': []}
package org.hawkular.apm.examples.vertx.opentracing.common; import java.util.Iterator; import java.util.Map; import io.opentracing.propagation.TextMap; /** * @author gbrown */ public final class HttpHeadersInjectAdapter implements TextMap { private final Map<String, Object> map; public HttpHeadersInjectAdapter(final Map<String, Object> map) { this.map = map; } @Override public Iterator<Map.Entry<String, String>> iterator() { throw new UnsupportedOperationException("TextMapInjectAdapter should only be used with Tracer.inject()"); } @Override public void put(String key, String value) { this.map.put(key, value); } }
{'content_hash': '25060a231d0900a000066b17a94119df', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 113, 'avg_line_length': 24.642857142857142, 'alnum_prop': 0.7057971014492753, 'repo_name': 'objectiser/hawkular-btm', 'id': '6d2d9495597e4e910d76189e47b9cf4eb52d209c', 'size': '1372', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'examples/vertx-opentracing/common/src/main/java/org/hawkular/apm/examples/vertx/opentracing/common/HttpHeadersInjectAdapter.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '51395'}, {'name': 'HTML', 'bytes': '61691'}, {'name': 'Java', 'bytes': '1825554'}, {'name': 'JavaScript', 'bytes': '10771'}, {'name': 'Shell', 'bytes': '4792'}, {'name': 'TypeScript', 'bytes': '46378'}, {'name': 'XSLT', 'bytes': '13773'}]}
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <View android:layout_width="250dp" android:layout_height="60dp" android:background="@drawable/dk_bg_loading"/> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center"> <ProgressBar android:id="@+id/dk_loadingImageView" android:layout_width="32dp" android:layout_height="32dp" android:indeterminate="false" android:indeterminateDrawable="@drawable/dk_loading_progress"/> <TextView android:layout_marginLeft="8dp" android:id="@+id/dk_tv_loading_msg" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:textSize="14sp" android:textColor="@color/dk_gamesdk_white"/> </LinearLayout> </FrameLayout>
{'content_hash': '14c644607df74d07cb4aac807db58bb8', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 74, 'avg_line_length': 34.77142857142857, 'alnum_prop': 0.6335250616269515, 'repo_name': 'bianfeng-shenbin/plugin', 'id': 'aafcf1647a0724ffa9d10decde691beec5e9d2f3', 'size': '1217', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'plugins/Baidupay/proj.android/DependProject/res/layout/dk_custom_progress.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '14052'}, {'name': 'C++', 'bytes': '380594'}, {'name': 'CSS', 'bytes': '26162'}, {'name': 'HTML', 'bytes': '3128'}, {'name': 'Java', 'bytes': '787938'}, {'name': 'Makefile', 'bytes': '1990'}, {'name': 'Objective-C', 'bytes': '1712265'}, {'name': 'Objective-C++', 'bytes': '115875'}, {'name': 'Python', 'bytes': '26592'}, {'name': 'Shell', 'bytes': '23666'}]}
// External Requirements var React = require('react'); var MortarJS = require('../../../../../app-container').MortarJS; // Bricks var Br = MortarJS.require('components', 'Row', 'Column', 'Form', 'Table', 'Modal'); // Stores var FormStore = MortarJS.Stores.FormStore; // Mixins var ResourceComponentMixin = MortarJS.Mixins.ResourceComponentMixin; /** * Summable Rows * * @type {*|Function} */ var SummableRows = React.createClass({ mixins: [ResourceComponentMixin], getInitialState: function() { return { params : {}, formIsValid : true }; }, pageConfig: function() { return { stores: [ { store: FormStore } ] }; }, componentDidMount: function() { this._componentDidMount(); }, componentWillUnmount: function() { this._componentWillUnmount(); }, render: function() { var tableOptions = { summableRows: ['hands'] }; return ( <div id="page-wrapper"> <div id="page-content"> <Br.Row> <Br.Column grid="lg" size="12"> <Br.Table data={this.props.workingResource} dataKeys={this.props.tableKeys} title={'Table'} options={tableOptions} /> </Br.Column> </Br.Row> </div> </div> ); } }); module.exports = SummableRows;
{'content_hash': '1b7261a75fc3dac9ea02c51215785484', 'timestamp': '', 'source': 'github', 'line_count': 69, 'max_line_length': 103, 'avg_line_length': 19.08695652173913, 'alnum_prop': 0.5793470007593015, 'repo_name': 'MortarJS/Mortar-JS', 'id': '9c8b5c8e7c65cee003687b441f3566b43a134405', 'size': '1317', 'binary': False, 'copies': '2', 'ref': 'refs/heads/dev', 'path': 'examples/playground/src/pages/components/visualization/Table/components/SummableRows.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '79401'}, {'name': 'JavaScript', 'bytes': '201115'}]}
.class public Landroid/graphics/LinearGradient; .super Landroid/graphics/Shader; .source "LinearGradient.java" # static fields .field private static final TYPE_COLORS_AND_POSITIONS:I = 0x1 .field private static final TYPE_COLOR_START_AND_COLOR_END:I = 0x2 # instance fields .field private mColor0:I .field private mColor1:I .field private mColors:[I .field private mPositions:[F .field private mTileMode:Landroid/graphics/Shader$TileMode; .field private mType:I .field private mX0:F .field private mX1:F .field private mY0:F .field private mY1:F # direct methods .method public constructor <init>(FFFFIILandroid/graphics/Shader$TileMode;)V .locals 10 .param p1, "x0" # F .param p2, "y0" # F .param p3, "x1" # F .param p4, "y1" # F .param p5, "color0" # I .param p6, "color1" # I .param p7, "tile" # Landroid/graphics/Shader$TileMode; .prologue .line 83 invoke-direct {p0}, Landroid/graphics/Shader;-><init>()V .line 84 const/4 v1, 0x2 iput v1, p0, Landroid/graphics/LinearGradient;->mType:I .line 85 iput p1, p0, Landroid/graphics/LinearGradient;->mX0:F .line 86 iput p2, p0, Landroid/graphics/LinearGradient;->mY0:F .line 87 iput p3, p0, Landroid/graphics/LinearGradient;->mX1:F .line 88 iput p4, p0, Landroid/graphics/LinearGradient;->mY1:F .line 89 iput p5, p0, Landroid/graphics/LinearGradient;->mColor0:I .line 90 move/from16 v0, p6 iput v0, p0, Landroid/graphics/LinearGradient;->mColor1:I .line 91 move-object/from16 v0, p7 iput-object v0, p0, Landroid/graphics/LinearGradient;->mTileMode:Landroid/graphics/Shader$TileMode; .line 92 move-object/from16 v0, p7 iget v8, v0, Landroid/graphics/Shader$TileMode;->nativeInt:I move-object v1, p0 move v2, p1 move v3, p2 move v4, p3 move v5, p4 move v6, p5 move/from16 v7, p6 invoke-direct/range {v1 .. v8}, Landroid/graphics/LinearGradient;->nativeCreate2(FFFFIII)I move-result v1 iput v1, p0, Landroid/graphics/LinearGradient;->native_instance:I .line 93 iget v2, p0, Landroid/graphics/LinearGradient;->native_instance:I move-object/from16 v0, p7 iget v9, v0, Landroid/graphics/Shader$TileMode;->nativeInt:I move-object v1, p0 move v3, p1 move v4, p2 move v5, p3 move v6, p4 move v7, p5 move/from16 v8, p6 invoke-direct/range {v1 .. v9}, Landroid/graphics/LinearGradient;->nativePostCreate2(IFFFFIII)I move-result v1 iput v1, p0, Landroid/graphics/LinearGradient;->native_shader:I .line 95 return-void .end method .method public constructor <init>(FFFF[I[FLandroid/graphics/Shader$TileMode;)V .locals 10 .param p1, "x0" # F .param p2, "y0" # F .param p3, "x1" # F .param p4, "y1" # F .param p5, "colors" # [I .param p6, "positions" # [F .param p7, "tile" # Landroid/graphics/Shader$TileMode; .prologue .line 53 invoke-direct {p0}, Landroid/graphics/Shader;-><init>()V .line 54 array-length v1, p5 const/4 v2, 0x2 if-ge v1, v2, :cond_0 .line 55 new-instance v1, Ljava/lang/IllegalArgumentException; const-string/jumbo v2, "needs >= 2 number of colors" invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V throw v1 .line 57 :cond_0 if-eqz p6, :cond_1 array-length v1, p5 move-object/from16 v0, p6 array-length v2, v0 if-eq v1, v2, :cond_1 .line 58 new-instance v1, Ljava/lang/IllegalArgumentException; const-string v2, "color and position arrays must be of equal length" invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V throw v1 .line 60 :cond_1 const/4 v1, 0x1 iput v1, p0, Landroid/graphics/LinearGradient;->mType:I .line 61 iput p1, p0, Landroid/graphics/LinearGradient;->mX0:F .line 62 iput p2, p0, Landroid/graphics/LinearGradient;->mY0:F .line 63 iput p3, p0, Landroid/graphics/LinearGradient;->mX1:F .line 64 iput p4, p0, Landroid/graphics/LinearGradient;->mY1:F .line 65 iput-object p5, p0, Landroid/graphics/LinearGradient;->mColors:[I .line 66 move-object/from16 v0, p6 iput-object v0, p0, Landroid/graphics/LinearGradient;->mPositions:[F .line 67 move-object/from16 v0, p7 iput-object v0, p0, Landroid/graphics/LinearGradient;->mTileMode:Landroid/graphics/Shader$TileMode; .line 68 move-object/from16 v0, p7 iget v8, v0, Landroid/graphics/Shader$TileMode;->nativeInt:I move-object v1, p0 move v2, p1 move v3, p2 move v4, p3 move v5, p4 move-object v6, p5 move-object/from16 v7, p6 invoke-direct/range {v1 .. v8}, Landroid/graphics/LinearGradient;->nativeCreate1(FFFF[I[FI)I move-result v1 iput v1, p0, Landroid/graphics/LinearGradient;->native_instance:I .line 69 iget v2, p0, Landroid/graphics/LinearGradient;->native_instance:I move-object/from16 v0, p7 iget v9, v0, Landroid/graphics/Shader$TileMode;->nativeInt:I move-object v1, p0 move v3, p1 move v4, p2 move v5, p3 move v6, p4 move-object v7, p5 move-object/from16 v8, p6 invoke-direct/range {v1 .. v9}, Landroid/graphics/LinearGradient;->nativePostCreate1(IFFFF[I[FI)I move-result v1 iput v1, p0, Landroid/graphics/LinearGradient;->native_shader:I .line 71 return-void .end method .method private native nativeCreate1(FFFF[I[FI)I .end method .method private native nativeCreate2(FFFFIII)I .end method .method private native nativePostCreate1(IFFFF[I[FI)I .end method .method private native nativePostCreate2(IFFFFIII)I .end method # virtual methods .method protected copy()Landroid/graphics/Shader; .locals 8 .prologue .line 103 iget v1, p0, Landroid/graphics/LinearGradient;->mType:I packed-switch v1, :pswitch_data_0 .line 112 new-instance v1, Ljava/lang/IllegalArgumentException; const-string v2, "LinearGradient should be created with either colors and positions or start color and end color" invoke-direct {v1, v2}, Ljava/lang/IllegalArgumentException;-><init>(Ljava/lang/String;)V throw v1 .line 105 :pswitch_0 new-instance v0, Landroid/graphics/LinearGradient; iget v1, p0, Landroid/graphics/LinearGradient;->mX0:F iget v2, p0, Landroid/graphics/LinearGradient;->mY0:F iget v3, p0, Landroid/graphics/LinearGradient;->mX1:F iget v4, p0, Landroid/graphics/LinearGradient;->mY1:F iget-object v5, p0, Landroid/graphics/LinearGradient;->mColors:[I invoke-virtual {v5}, [I->clone()Ljava/lang/Object; move-result-object v5 check-cast v5, [I iget-object v6, p0, Landroid/graphics/LinearGradient;->mPositions:[F if-eqz v6, :cond_0 iget-object v6, p0, Landroid/graphics/LinearGradient;->mPositions:[F invoke-virtual {v6}, [F->clone()Ljava/lang/Object; move-result-object v6 check-cast v6, [F :goto_0 iget-object v7, p0, Landroid/graphics/LinearGradient;->mTileMode:Landroid/graphics/Shader$TileMode; invoke-direct/range {v0 .. v7}, Landroid/graphics/LinearGradient;-><init>(FFFF[I[FLandroid/graphics/Shader$TileMode;)V .line 115 .local v0, "copy":Landroid/graphics/LinearGradient; :goto_1 invoke-virtual {p0, v0}, Landroid/graphics/LinearGradient;->copyLocalMatrix(Landroid/graphics/Shader;)V .line 116 return-object v0 .line 105 .end local v0 # "copy":Landroid/graphics/LinearGradient; :cond_0 const/4 v6, 0x0 goto :goto_0 .line 109 :pswitch_1 new-instance v0, Landroid/graphics/LinearGradient; iget v1, p0, Landroid/graphics/LinearGradient;->mX0:F iget v2, p0, Landroid/graphics/LinearGradient;->mY0:F iget v3, p0, Landroid/graphics/LinearGradient;->mX1:F iget v4, p0, Landroid/graphics/LinearGradient;->mY1:F iget v5, p0, Landroid/graphics/LinearGradient;->mColor0:I iget v6, p0, Landroid/graphics/LinearGradient;->mColor1:I iget-object v7, p0, Landroid/graphics/LinearGradient;->mTileMode:Landroid/graphics/Shader$TileMode; invoke-direct/range {v0 .. v7}, Landroid/graphics/LinearGradient;-><init>(FFFFIILandroid/graphics/Shader$TileMode;)V .line 110 .restart local v0 # "copy":Landroid/graphics/LinearGradient; goto :goto_1 .line 103 :pswitch_data_0 .packed-switch 0x1 :pswitch_0 :pswitch_1 .end packed-switch .end method
{'content_hash': 'a7208409616e75cde808b2e509d4f995', 'timestamp': '', 'source': 'github', 'line_count': 387, 'max_line_length': 122, 'avg_line_length': 22.30749354005168, 'alnum_prop': 0.6768214988995714, 'repo_name': 'GaHoKwan/tos_device_meizu_mx4', 'id': '1cc869ddc0e6801d77542f465fcafbb780bedaa6', 'size': '8633', 'binary': False, 'copies': '2', 'ref': 'refs/heads/TPS-YUNOS', 'path': 'patch/smali/pack/framework.jar/smali/android/graphics/LinearGradient.smali', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2407'}, {'name': 'Groff', 'bytes': '8687'}, {'name': 'Makefile', 'bytes': '31774'}, {'name': 'Shell', 'bytes': '6226'}, {'name': 'Smali', 'bytes': '350951922'}]}
namespace Microsoft.WindowsAzure.Management.ServiceManagement.Test.FunctionalTests.PowershellCore { public class CmdletParam { private readonly string cmdletParamName; private readonly object cmdletParamValue; public string name { get { return cmdletParamName; } } public object value { get { return cmdletParamValue; } } public CmdletParam(string name, object value) { cmdletParamName = name; cmdletParamValue = value; } public CmdletParam(string name) { cmdletParamName = name; //cmdletParamValue = value; } } }
{'content_hash': '8e8f22106f41598435df823150d45279', 'timestamp': '', 'source': 'github', 'line_count': 37, 'max_line_length': 97, 'avg_line_length': 22.43243243243243, 'alnum_prop': 0.4963855421686747, 'repo_name': 'bryanhunter/azure-sdk-tools', 'id': '6eb811299ebf72fe913fecb93c71004bf6d9c99b', 'size': '1598', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'WindowsAzurePowershell/src/Management.ServiceManagement.Test/FunctionalTests/PowershellCore/CmdletParam.cs', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
package org.apache.pulsar.broker.authentication; import java.net.InetSocketAddress; import java.net.SocketAddress; import javax.servlet.http.HttpServletRequest; public class AuthenticationDataHttp implements AuthenticationDataSource { protected final HttpServletRequest request; protected final SocketAddress remoteAddress; protected String subscription; public AuthenticationDataHttp(HttpServletRequest request) { if (request == null) { throw new IllegalArgumentException(); } this.request = request; this.remoteAddress = InetSocketAddress.createUnresolved(request.getRemoteAddr(), request.getRemotePort()); } /* * HTTP */ @Override public boolean hasDataFromHttp() { return true; } @Override public String getHttpAuthType() { return request.getAuthType(); } @Override public String getHttpHeader(String name) { return request.getHeader(name); } /* * Peer */ @Override public boolean hasDataFromPeer() { return true; } @Override public SocketAddress getPeerAddress() { return remoteAddress; } /* * Subscription */ @Override public boolean hasSubscription() { return this.subscription != null; } @Override public void setSubscription(String subscription) { this.subscription = subscription; } @Override public String getSubscription() { return subscription; } }
{'content_hash': 'eec0ef2f4dce9ea41e75b6294d460293', 'timestamp': '', 'source': 'github', 'line_count': 74, 'max_line_length': 114, 'avg_line_length': 20.87837837837838, 'alnum_prop': 0.654368932038835, 'repo_name': 'yahoo/pulsar', 'id': 'f48dbc263e0e64ee3b795983e9d845ac10def549', 'size': '2353', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'pulsar-broker-common/src/main/java/org/apache/pulsar/broker/authentication/AuthenticationDataHttp.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'C', 'bytes': '77960'}, {'name': 'C++', 'bytes': '736937'}, {'name': 'CMake', 'bytes': '9092'}, {'name': 'HTML', 'bytes': '29382'}, {'name': 'Java', 'bytes': '5371040'}, {'name': 'Protocol Buffer', 'bytes': '15090'}, {'name': 'Python', 'bytes': '91802'}, {'name': 'Shell', 'bytes': '47717'}]}
// snippet-start:[cwEvents.JavaScript.cwe.putRuleV3] // Import required AWS SDK clients and commands for Node.js import { PutRuleCommand } from "@aws-sdk/client-cloudwatch-events"; import { cweClient } from "./libs/cloudWatchEventsClient.js"; // Set the parameters export const params = { Name: "DEMO_EVENT", RoleArn: "IAM_ROLE_ARN", //IAM_ROLE_ARN ScheduleExpression: "rate(5 minutes)", State: "ENABLED", }; export const run = async () => { try { const data = await cweClient.send(new PutRuleCommand(params)); console.log("Success, scheduled rule created; Rule ARN:", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; // Uncomment this line to run execution within this file. // run(); // snippet-end:[cwEvents.JavaScript.cwe.putRuleV3] // For unit tests only. // module.exports ={run, params};
{'content_hash': '30050c1b7a406d25b4498bb53a2cad88', 'timestamp': '', 'source': 'github', 'line_count': 29, 'max_line_length': 68, 'avg_line_length': 29.896551724137932, 'alnum_prop': 0.6885813148788927, 'repo_name': 'awsdocs/aws-doc-sdk-examples', 'id': 'e3e8d28cc82f8be318dfcee5129bd809524ebdad', 'size': '1477', 'binary': False, 'copies': '1', 'ref': 'refs/heads/main', 'path': 'javascriptv3/example_code/cloudwatch-events/src/putRule.js', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ABAP', 'bytes': '476653'}, {'name': 'Batchfile', 'bytes': '900'}, {'name': 'C', 'bytes': '3852'}, {'name': 'C#', 'bytes': '2051923'}, {'name': 'C++', 'bytes': '943634'}, {'name': 'CMake', 'bytes': '82068'}, {'name': 'CSS', 'bytes': '33378'}, {'name': 'Dockerfile', 'bytes': '2243'}, {'name': 'Go', 'bytes': '1764292'}, {'name': 'HTML', 'bytes': '319090'}, {'name': 'Java', 'bytes': '4966853'}, {'name': 'JavaScript', 'bytes': '1655476'}, {'name': 'Jupyter Notebook', 'bytes': '9749'}, {'name': 'Kotlin', 'bytes': '1099902'}, {'name': 'Makefile', 'bytes': '4922'}, {'name': 'PHP', 'bytes': '1220594'}, {'name': 'Python', 'bytes': '2507509'}, {'name': 'Ruby', 'bytes': '500331'}, {'name': 'Rust', 'bytes': '558811'}, {'name': 'Shell', 'bytes': '63776'}, {'name': 'Swift', 'bytes': '267325'}, {'name': 'TypeScript', 'bytes': '119632'}]}
/*! * Generated using the Bootstrap Customizer (http://getbootstrap.com/customize/?id=0af8709aa7116a215c20) * Config saved to config.json and https://gist.github.com/0af8709aa7116a215c20 */ .btn-default, .btn-primary, .btn-success, .btn-info, .btn-warning, .btn-danger { text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075); } .btn-default:active, .btn-primary:active, .btn-success:active, .btn-info:active, .btn-warning:active, .btn-danger:active, .btn-default.active, .btn-primary.active, .btn-success.active, .btn-info.active, .btn-warning.active, .btn-danger.active { -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn:active, .btn.active { background-image: none; } .btn-default { background-image: -webkit-linear-gradient(top, #ffffff 0%, #e0e0e0 100%); background-image: -o-linear-gradient(top, #ffffff 0%, #e0e0e0 100%); background-image: linear-gradient(to bottom, #ffffff 0%, #e0e0e0 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #dbdbdb; text-shadow: 0 1px 0 #fff; border-color: #ccc; } .btn-default:hover, .btn-default:focus { background-color: #e0e0e0; background-position: 0 -15px; } .btn-default:active, .btn-default.active { background-color: #e0e0e0; border-color: #dbdbdb; } .btn-default:disabled, .btn-default[disabled] { background-color: #e0e0e0; background-image: none; } .btn-primary { background-image: -webkit-linear-gradient(top, #428bca 0%, #2d6ca2 100%); background-image: -o-linear-gradient(top, #428bca 0%, #2d6ca2 100%); background-image: linear-gradient(to bottom, #428bca 0%, #2d6ca2 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff2d6ca2', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #2b669a; } .btn-primary:hover, .btn-primary:focus { background-color: #2d6ca2; background-position: 0 -15px; } .btn-primary:active, .btn-primary.active { background-color: #2d6ca2; border-color: #2b669a; } .btn-primary:disabled, .btn-primary[disabled] { background-color: #2d6ca2; background-image: none; } .btn-success { background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%); background-image: -o-linear-gradient(top, #5cb85c 0%, #419641 100%); background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #3e8f3e; } .btn-success:hover, .btn-success:focus { background-color: #419641; background-position: 0 -15px; } .btn-success:active, .btn-success.active { background-color: #419641; border-color: #3e8f3e; } .btn-success:disabled, .btn-success[disabled] { background-color: #419641; background-image: none; } .btn-info { background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%); background-image: -o-linear-gradient(top, #5bc0de 0%, #2aabd2 100%); background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #28a4c9; } .btn-info:hover, .btn-info:focus { background-color: #2aabd2; background-position: 0 -15px; } .btn-info:active, .btn-info.active { background-color: #2aabd2; border-color: #28a4c9; } .btn-info:disabled, .btn-info[disabled] { background-color: #2aabd2; background-image: none; } .btn-warning { background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%); background-image: -o-linear-gradient(top, #f0ad4e 0%, #eb9316 100%); background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #e38d13; } .btn-warning:hover, .btn-warning:focus { background-color: #eb9316; background-position: 0 -15px; } .btn-warning:active, .btn-warning.active { background-color: #eb9316; border-color: #e38d13; } .btn-warning:disabled, .btn-warning[disabled] { background-color: #eb9316; background-image: none; } .btn-danger { background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%); background-image: -o-linear-gradient(top, #d9534f 0%, #c12e2a 100%); background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #b92c28; } .btn-danger:hover, .btn-danger:focus { background-color: #c12e2a; background-position: 0 -15px; } .btn-danger:active, .btn-danger.active { background-color: #c12e2a; border-color: #b92c28; } .btn-danger:disabled, .btn-danger[disabled] { background-color: #c12e2a; background-image: none; } .thumbnail, .img-thumbnail { -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); background-color: #e8e8e8; } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { background-image: -webkit-linear-gradient(top, #428bca 0%, #357ebd 100%); background-image: -o-linear-gradient(top, #428bca 0%, #357ebd 100%); background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0); background-color: #357ebd; } .navbar-default { background-image: -webkit-linear-gradient(top, #ffffff 0%, #f8f8f8 100%); background-image: -o-linear-gradient(top, #ffffff 0%, #f8f8f8 100%); background-image: linear-gradient(to bottom, #ffffff 0%, #f8f8f8 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border-radius: 4px; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075); } .navbar-default .navbar-nav > .active > a { background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f3f3f3 100%); background-image: -o-linear-gradient(top, #ebebeb 0%, #f3f3f3 100%); background-image: linear-gradient(to bottom, #ebebeb 0%, #f3f3f3 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff3f3f3', GradientType=0); -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075); box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075); } .navbar-brand, .navbar-nav > li > a { text-shadow: 0 1px 0 rgba(255, 255, 255, 0.25); } .navbar-inverse { background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222222 100%); background-image: -o-linear-gradient(top, #3c3c3c 0%, #222222 100%); background-image: linear-gradient(to bottom, #3c3c3c 0%, #222222 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .navbar-inverse .navbar-nav > .active > a { background-image: -webkit-linear-gradient(top, #222222 0%, #282828 100%); background-image: -o-linear-gradient(top, #222222 0%, #282828 100%); background-image: linear-gradient(to bottom, #222222 0%, #282828 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff222222', endColorstr='#ff282828', GradientType=0); -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25); box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25); } .navbar-inverse .navbar-brand, .navbar-inverse .navbar-nav > li > a { text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .navbar-static-top, .navbar-fixed-top, .navbar-fixed-bottom { border-radius: 0; } .alert { text-shadow: 0 1px 0 rgba(255, 255, 255, 0.2); -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05); } .alert-success { background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%); background-image: -o-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%); background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0); border-color: #b2dba1; } .alert-info { background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%); background-image: -o-linear-gradient(top, #d9edf7 0%, #b9def0 100%); background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0); border-color: #9acfea; } .alert-warning { background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%); background-image: -o-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%); background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0); border-color: #f5e79e; } .alert-danger { background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%); background-image: -o-linear-gradient(top, #f2dede 0%, #e7c3c3 100%); background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0); border-color: #dca7a7; } .progress { background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%); background-image: -o-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%); background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0); } .progress-bar { background-image: -webkit-linear-gradient(top, #428bca 0%, #3071a9 100%); background-image: -o-linear-gradient(top, #428bca 0%, #3071a9 100%); background-image: linear-gradient(to bottom, #428bca 0%, #3071a9 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3071a9', GradientType=0); } .progress-bar-success { background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%); background-image: -o-linear-gradient(top, #5cb85c 0%, #449d44 100%); background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0); } .progress-bar-info { background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%); background-image: -o-linear-gradient(top, #5bc0de 0%, #31b0d5 100%); background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0); } .progress-bar-warning { background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%); background-image: -o-linear-gradient(top, #f0ad4e 0%, #ec971f 100%); background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0); } .progress-bar-danger { background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%); background-image: -o-linear-gradient(top, #d9534f 0%, #c9302c 100%); background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0); } .progress-bar-striped { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .list-group { border-radius: 4px; -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); } .list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus { text-shadow: 0 -1px 0 #3071a9; background-image: -webkit-linear-gradient(top, #428bca 0%, #3278b3 100%); background-image: -o-linear-gradient(top, #428bca 0%, #3278b3 100%); background-image: linear-gradient(to bottom, #428bca 0%, #3278b3 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff3278b3', GradientType=0); border-color: #3278b3; } .panel { -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .panel-default > .panel-heading { background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); } .panel-primary > .panel-heading { background-image: -webkit-linear-gradient(top, #428bca 0%, #357ebd 100%); background-image: -o-linear-gradient(top, #428bca 0%, #357ebd 100%); background-image: linear-gradient(to bottom, #428bca 0%, #357ebd 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff428bca', endColorstr='#ff357ebd', GradientType=0); } .panel-success > .panel-heading { background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%); background-image: -o-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%); background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0); } .panel-info > .panel-heading { background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%); background-image: -o-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%); background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0); } .panel-warning > .panel-heading { background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%); background-image: -o-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%); background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0); } .panel-danger > .panel-heading { background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%); background-image: -o-linear-gradient(top, #f2dede 0%, #ebcccc 100%); background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0); } .well { background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%); background-image: -o-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%); background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0); border-color: #dcdcdc; -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1); box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1); }
{'content_hash': '56fcfe6d58754a7c071201c128a29f71', 'timestamp': '', 'source': 'github', 'line_count': 411, 'max_line_length': 208, 'avg_line_length': 43.89537712895377, 'alnum_prop': 0.7180865805664874, 'repo_name': 'iottly/iottly-console', 'id': '9842f2f37defd4ee2510e95890b981e32ad40155', 'size': '18209', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'iottly_console/iottly_project/app/styles/bootstrap-theme.css', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '78755'}, {'name': 'HTML', 'bytes': '79456'}, {'name': 'JavaScript', 'bytes': '147794'}, {'name': 'Shell', 'bytes': '531'}]}
package mesosphere.marathon package core.externalvolume.impl.providers import com.wix.accord.{ Failure, Result, Success } import mesosphere.UnitTest import mesosphere.marathon.api.v2.Validation import mesosphere.marathon.api.v2.Validation.ConstraintViolation import mesosphere.marathon.core.externalvolume.ExternalVolumes import mesosphere.marathon.state._ import mesosphere.marathon.test.GroupCreation import play.api.libs.json.{ JsString, Json } import scala.collection.immutable.Seq class DVDIProviderRootGroupValidationTest extends UnitTest with GroupCreation { "DVDIProviderRootGroupValidation" should { "two volumes with different names should not result in an error" in { val f = new Fixture Given("a root group with two apps and conflicting volumes") val app1 = f.appWithDVDIVolume(appId = PathId("/nested/foo1"), volumeName = "vol1") val app2 = f.appWithDVDIVolume(appId = PathId("/nested/foo2"), volumeName = "vol2") val rootGroup = createRootGroup( groups = Set( createGroup( id = PathId("/nested"), apps = Map( app1.id -> app1, app2.id -> app2 ), validate = false ) ), validate = false ) f.checkResult( rootGroup, expectedViolations = Set.empty ) } "two volumes with same name result in an error" in { val f = new Fixture Given("a root group with two apps and conflicting volumes") val app1 = f.appWithDVDIVolume(appId = PathId("/nested/app1"), volumeName = "vol") val app2 = f.appWithDVDIVolume(appId = PathId("/nested/app2"), volumeName = "vol") val rootGroup = createRootGroup( groups = Set( createGroup( id = PathId("/nested"), apps = Map( app1.id -> app1, app2.id -> app2 ), validate = false ) ), validate = false ) f.checkResult( rootGroup, expectedViolations = Set( ConstraintViolation( constraint = "Volume name 'vol' in /nested/app1 conflicts with volume(s) of same name in app(s): /nested/app2", path = "/groups(0)/apps(0)/externalVolumes(0)" ), ConstraintViolation( constraint = "Volume name 'vol' in /nested/app2 conflicts with volume(s) of same name in app(s): /nested/app1", path = "/groups(0)/apps(1)/externalVolumes(0)" ) ) ) } class Fixture { def appWithDVDIVolume(appId: PathId, volumeName: String, provider: String = DVDIProvider.name): AppDefinition = { AppDefinition( id = appId, cmd = Some("sleep 123"), upgradeStrategy = UpgradeStrategy.forResidentTasks, container = Some( Container.Mesos( volumes = Seq( VolumeWithMount( volume = ExternalVolume( name = None, external = ExternalVolumeInfo( name = volumeName, provider = provider, options = Map( DVDIProvider.driverOption -> "rexray"))), mount = VolumeMount( volumeName = None, mountPath = "ignoreme", readOnly = false)))))) } def jsonResult(result: Result): String = { Json.prettyPrint( result match { case Success => JsString("Success") case f: Failure => Json.toJson(f)(Validation.failureWrites) } ) } def checkResult(rootGroup: RootGroup, expectedViolations: Set[ConstraintViolation]): Unit = { val expectFailure = expectedViolations.nonEmpty When("validating the root group") val result = DVDIProviderValidations.rootGroup(rootGroup) Then(s"we should ${if (expectFailure) "" else "NOT "}get an error") withClue(jsonResult(result)) { result.isFailure should be(expectFailure) } And("ExternalVolumes validation agrees") val externalVolumesResult = ExternalVolumes.validRootGroup()(rootGroup) withClue(jsonResult(externalVolumesResult)) { externalVolumesResult.isFailure should be(expectFailure) } And("global validation agrees") val globalResult: Result = RootGroup.rootGroupValidator(Set("external_volumes"))(rootGroup) withClue(jsonResult(globalResult)) { globalResult.isFailure should be(expectFailure) } val ruleViolations = globalResult match { case Success => Seq.empty[ConstraintViolation] case f: Failure => Validation.allViolations(f) } And("the rule violations are the expected ones") withClue(jsonResult(globalResult)) { ruleViolations.toSet should equal(expectedViolations) } } } } }
{'content_hash': '06c11b6a6ea53b0df8ae471a0ab8d4d6', 'timestamp': '', 'source': 'github', 'line_count': 138, 'max_line_length': 123, 'avg_line_length': 35.95652173913044, 'alnum_prop': 0.601975010076582, 'repo_name': 'meln1k/marathon', 'id': 'dbd29e91c5f4498d68e3cffc3f5c56bf7574445c', 'size': '4962', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'src/test/scala/mesosphere/marathon/core/externalvolume/impl/providers/DVDIProviderRootGroupValidationTest.scala', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Clojure', 'bytes': '59270'}, {'name': 'Groovy', 'bytes': '14255'}, {'name': 'HTML', 'bytes': '502'}, {'name': 'Java', 'bytes': '778'}, {'name': 'Makefile', 'bytes': '4005'}, {'name': 'Python', 'bytes': '169779'}, {'name': 'Ruby', 'bytes': '772'}, {'name': 'Scala', 'bytes': '4280011'}, {'name': 'Shell', 'bytes': '41549'}]}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.9.1"/> <title>V8 API Reference Guide for node.js v5.0.0: Member List</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { init_search(); }); </script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">V8 API Reference Guide for node.js v5.0.0 </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.9.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="examples.html"><span>Examples</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="namespacev8.html">v8</a></li><li class="navelem"><a class="el" href="classv8_1_1PersistentHandleVisitor.html">PersistentHandleVisitor</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">v8::PersistentHandleVisitor Member List</div> </div> </div><!--header--> <div class="contents"> <p>This is the complete list of members for <a class="el" href="classv8_1_1PersistentHandleVisitor.html">v8::PersistentHandleVisitor</a>, including all inherited members.</p> <table class="directory"> <tr bgcolor="#f0f0f0" class="even"><td class="entry"><b>VisitPersistentHandle</b>(Persistent&lt; Value &gt; *value, uint16_t class_id) (defined in <a class="el" href="classv8_1_1PersistentHandleVisitor.html">v8::PersistentHandleVisitor</a>)</td><td class="entry"><a class="el" href="classv8_1_1PersistentHandleVisitor.html">v8::PersistentHandleVisitor</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> <tr bgcolor="#f0f0f0"><td class="entry"><b>~PersistentHandleVisitor</b>() (defined in <a class="el" href="classv8_1_1PersistentHandleVisitor.html">v8::PersistentHandleVisitor</a>)</td><td class="entry"><a class="el" href="classv8_1_1PersistentHandleVisitor.html">v8::PersistentHandleVisitor</a></td><td class="entry"><span class="mlabel">inline</span><span class="mlabel">virtual</span></td></tr> </table></div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.9.1 </small></address> </body> </html>
{'content_hash': 'cd7a825408980868f0bf5abd4253b3d7', 'timestamp': '', 'source': 'github', 'line_count': 108, 'max_line_length': 459, 'avg_line_length': 49.03703703703704, 'alnum_prop': 0.661820241691843, 'repo_name': 'v8-dox/v8-dox.github.io', 'id': 'a8bc1da8311969a764ffb26bf87fefc734528893', 'size': '5296', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '0a43697/html/classv8_1_1PersistentHandleVisitor-members.html', 'mode': '33188', 'license': 'mit', 'language': []}
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Performance Tuning</title> <link rel="stylesheet" href="gettingStarted.css" type="text/css" /> <meta name="generator" content="DocBook XSL Stylesheets V1.73.2" /> <link rel="start" href="index.html" title="Getting Started with Berkeley DB Transaction Processing" /> <link rel="up" href="introduction.html" title="Chapter 1. Introduction" /> <link rel="prev" href="recovery-intro.html" title="Recoverability" /> <link rel="next" href="enabletxn.html" title="Chapter 2. Enabling Transactions" /> </head> <body> <div xmlns="" class="navheader"> <div class="libver"> <p>Library Version 11.2.5.3</p> </div> <table width="100%" summary="Navigation header"> <tr> <th colspan="3" align="center">Performance Tuning</th> </tr> <tr> <td width="20%" align="left"><a accesskey="p" href="recovery-intro.html">Prev</a> </td> <th width="60%" align="center">Chapter 1. Introduction</th> <td width="20%" align="right"> <a accesskey="n" href="enabletxn.html">Next</a></td> </tr> </table> <hr /> </div> <div class="sect1" lang="en" xml:lang="en"> <div class="titlepage"> <div> <div> <h2 class="title" style="clear: both"><a id="perftune-intro"></a>Performance Tuning</h2> </div> </div> </div> <p> From a performance perspective, the use of transactions is not free. Depending on how you configure them, transaction commits usually require your application to perform disk I/O that a non-transactional application does not perform. Also, for multi-threaded <span>and multi-process</span> applications, the use of transactions can result in increased lock contention due to extra locking requirements driven by transactional isolation guarantees. </p> <p> There is therefore a performance tuning component to transactional applications that is not applicable for non-transactional applications (although some tuning considerations do exist whether or not your application uses transactions). Where appropriate, these tuning considerations are introduced in the following chapters. <span> However, for a more complete description of them, see the <a class="ulink" href="http://download.oracle.com/docs/cd/E17076_02/html/programmer_reference/transapp_tune.html" target="_top"> Transaction tuning </a> and <a class="ulink" href="http://download.oracle.com/docs/cd/E17076_02/html/programmer_reference/transapp_throughput.html" target="_top"> Transaction throughput </a> sections of the <em class="citetitle">Berkeley DB Programmer's Reference Guide</em>. </span> </p> </div> <div class="navfooter"> <hr /> <table width="100%" summary="Navigation footer"> <tr> <td width="40%" align="left"><a accesskey="p" href="recovery-intro.html">Prev</a> </td> <td width="20%" align="center"> <a accesskey="u" href="introduction.html">Up</a> </td> <td width="40%" align="right"> <a accesskey="n" href="enabletxn.html">Next</a></td> </tr> <tr> <td width="40%" align="left" valign="top">Recoverability </td> <td width="20%" align="center"> <a accesskey="h" href="index.html">Home</a> </td> <td width="40%" align="right" valign="top"> Chapter 2. Enabling Transactions</td> </tr> </table> </div> </body> </html>
{'content_hash': '3ccefe2d589eb85cdaf6e49c6e080a8b', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 146, 'avg_line_length': 45.5, 'alnum_prop': 0.5948717948717949, 'repo_name': 'iadix/iadixcoin', 'id': '7a8c2e67261e1d89a0cfb561879e4544c9e9c84e', 'size': '4109', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'db-5.3.28.NC/docs/gsg_txn/JAVA/perftune-intro.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '21896'}, {'name': 'Assembly', 'bytes': '52315'}, {'name': 'Awk', 'bytes': '14973'}, {'name': 'Batchfile', 'bytes': '192'}, {'name': 'C', 'bytes': '20479063'}, {'name': 'C#', 'bytes': '2168773'}, {'name': 'C++', 'bytes': '3655123'}, {'name': 'CSS', 'bytes': '75032'}, {'name': 'DTrace', 'bytes': '22240'}, {'name': 'Erlang', 'bytes': '22675'}, {'name': 'Groff', 'bytes': '19516'}, {'name': 'HTML', 'bytes': '58797564'}, {'name': 'Java', 'bytes': '5962444'}, {'name': 'JavaScript', 'bytes': '80758'}, {'name': 'M4', 'bytes': '22796'}, {'name': 'Makefile', 'bytes': '126124'}, {'name': 'NSIS', 'bytes': '18836'}, {'name': 'Objective-C', 'bytes': '858'}, {'name': 'Objective-C++', 'bytes': '3517'}, {'name': 'OpenEdge ABL', 'bytes': '71055'}, {'name': 'PHP', 'bytes': '1306'}, {'name': 'Perl', 'bytes': '566089'}, {'name': 'Python', 'bytes': '54355'}, {'name': 'QMake', 'bytes': '13707'}, {'name': 'R', 'bytes': '4009'}, {'name': 'Shell', 'bytes': '1271754'}, {'name': 'Tcl', 'bytes': '3377538'}, {'name': 'XS', 'bytes': '200617'}, {'name': 'Yacc', 'bytes': '49248'}]}
/// Copyright (c) 2012 Ecma International. All rights reserved. /** * @path ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-39.js * @description Object.defineProperty - 'Attributes' is a Date object that uses Object's [[Get]] method to access the 'enumerable' property (8.10.5 step 3.a) */ function testcase() { var obj = {}; var accessed = false; var dateObj = new Date(); dateObj.enumerable = true; Object.defineProperty(obj, "property", dateObj); for (var prop in obj) { if (prop === "property") { accessed = true; } } return accessed; } runTestCase(testcase);
{'content_hash': '2014cd6505f7771b1ca786f09c5e2338', 'timestamp': '', 'source': 'github', 'line_count': 24, 'max_line_length': 157, 'avg_line_length': 27.958333333333332, 'alnum_prop': 0.5707898658718331, 'repo_name': 'fvaneijk/jint', 'id': '03b7fb84343e0e83379bcc0429ae8be703aa5cbd', 'size': '671', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'Jint.Tests.Ecma/TestCases/ch15/15.2/15.2.3/15.2.3.6/15.2.3.6-3-39.js', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Batchfile', 'bytes': '70'}, {'name': 'C#', 'bytes': '3898518'}, {'name': 'JavaScript', 'bytes': '11429348'}]}
Release 2.0.170327 --------------------------------------------------------------------- New features -------- - Allow the mini depth chart to be hidden by the user - Refactor the MyMarkets component, 'show star only' and revamped search - Display up to 20 rows of the orderbook by default instead of 10 - Add Trade and Borrow links to the default assets in AccountOverview Bug fixes -------- - Fix an issue with blocktrades deposit addresses being set incorrectly - Change positioning of some tooltips - Fix password score checker freezing on very long passwords - Hide 'something for nothing order history items - Update bitsharesjs to fix proposals array undefined error - Fix 'Cannot use 'in' operator to search for 'translate'' error in api dropdown - Fix order rounding when modifying the 'Total' after clicking an order from the orderbook - Improve first-time brainkey lookup to check at least 10 positions - Log pub keys when creating a new account - Fix some Account permissions css issues and add some loggin - Also check if generated active key matches owner key and vice versa - Fix account create with faucet not rejecting errors properly - Fix password strength meter turning red for long passwords - Fix gateway actions in progress return --------------------------------------------------------------------- Release 2.0.170327 --------------------------------------------------------------------- New features -------- - Add password based login using account+role+password as private key seed - Add a Migration option to add password based keys to an existing account - Add password strength checker to password input - Update account creation using password login method - Use AccountImage in header instead of User icon - Add language selection dropdown with flag symbols to Header - Add a 'Quick buy' modal for blocktrades bridge deposit requests - Add blocktrades bridge deposits to the Exchange Buy/Sell box - Make OPEN.X trade links default to X_USD pair - Add CSP policies for improved security - Allow users to disable auto-lock by setting timeout to 0 - Include OPEN.DASH as one of the default assets available for deposits - Restore the small depth chart - Move the 'borrow X' buttons to the Buy/Sell boxes Bug fixes -------- - Add a wallet creation link to WalletUnlockModal - Fix some missing translation - Ensure all href links have window.opener clobbered - Remove TCNY deposits - Add vesting_balance_withdraw to ProposedOperation.jsx - Fix the calling of calcMarketStats in onSubscribeMarket - Improve how low volume markets are determined, add OPEN.DASH - Fix some pricechart resizing issues, put all controls on the same line - Tweak the dropdown css - Improve the price calculation of getMarketStats - Add missing translation of deposit withdraw title - Refactor Create account layout, add some text - Fix some minor header and Chat issues - Add missing translation key for supposed scammer accounts - Fix some possible issues in BlocktradesMethods and WithdrawModalBlocktrades - Wrap localStorage 'get' in try/catch to catch parsing errors, fixes Deposit/Withdraw issues for some accounts - Adjust the xAxis range for depth charts with no bids but asks - Fix blocktrades dropdown colors - Make the openledger fiat registration open in a separate browser - Fix some minor issues in Header and WithdrawModal - Fix transfer asset selection dropdown not showing more than 9 assets - Adjust the positioning of the cog header dropdown - Remove the borders in the electron header navigation buttons - Use default cursor to indicate account is not clickable with 1 account - Fix error when clicking on Header account with only 1 account present --------------------------------------------------------------------- Release 2.0.170314 --------------------------------------------------------------------- New features -------- - Make the account dropdown a direct link when only one account is present - Add a 'choose automatically' option for API server selection. - Add tooltips for bitassets, open.x and trade.x assets - Add 'to' account to deposit/withdraw summary, and show full asset name - Add several markets to dashboard list, filter out low volume markets - Implement some design ideas from @etherdesign - Refactor Transfer page, add new asset dropdown - Refactor AccountLeftPanel using etherdesign's designs - Increase max. KAPITAL withdraw limit to 100k - Improve the determination of low volume markets - Refactor DepositWithdraw layout according to design by @etherdesign - Add a dropdown to AccountSelector, use it in Transfer to show your accounts in From field - Change Tabs styling to use segmented button class - Modify the switch colors to make it very clear what's the checked state - Update the header account link behaviour to always switch the active account, add notification - Make the header balance value depend on the active account - Put Explore, Help and Settings behind a dropdown using the cog icon - Move the price chart controls below the chart itself - Fetch 3x as much data for price charts Bug fixes -------- - Make event listeners passive, ensure removal - Add theme as query param to BitKapital iframe urls - Improve MarketCard shouldComponentUpdate logic - Improve the borders and display of market cards in the Dashboard - Fix top markets list disappearing due to low volume check - Rename 'pay' to 'send to - Sort call orders by id for consistent sort in CollateralPosition - Move the date in the operation list to a third column - Always set the 'from' account in Transfer.jsx - Fix account registration without referral id - Fix KAPITAL:OPEN.BTC price display in dashboard - Fix BuySell input style after Transfer refactor - Improve the Identicon question mark color - Include accounts with partial authority in list of my accounts - Only render mobileMenu on small screens - Filter Blocktrades backed coins by active wallets - Fix Exchange balance check - Fix BuySell balance asset construction - Fix withdrawal modal input check for amounts < 0 - Fix fee subtraction in BuySell - Fix removal of ws api nodes in WebSocketAddModal - Persist backedCoins in localStorage - Persist map of low volume markets --------------------------------------------------------------------- Release 2.0.170303 --------------------------------------------------------------------- New features -------- - API node hopping: fallback to next API server if current API is down - API latency checks: all known API servers are regularly polled for latency, the ranking is used for fallback attempts - Notifications for confirmed transactions instead of second OK button - Big Russian language update - Delay Chat component appearance, default user name is now the first account in the user's wallet - Add empty input warning to WithdrawModalBlocktrades - Persist BlockTradesGateway deposit/withdraw setting Bug fixes -------- - Remove redirect from / to /dashboard - Store referral account in localStorage, fixes account creation referrals - Fix brainkey sequence sync issues with account creation failure, add reset/decrement methods, resolve process_transaction properly on trx inclusion - Trigger account ref lookup immediately on AccountStore loadDbData, fixes slow Dashboard load - Fix for MyOrders incorrect amounts - Fix Exchange insufficient funds message - Fix order cancellations not updating properly - Filter out OPEN.X coins that are currently unavailable from preset list - Modify app init Chain to better handle sync error redirects - Add missing getFee method for SimpleDepositWithdraw --------------------------------------------------------------------- Release 2.0.170224 --------------------------------------------------------------------- New features -------- - New modal for quick deposit/withdraw of OPEN.X assets on account overview page - A set of default assets are available for deposits on the account overview page - New summary of open orders on account overview page - Set precision for bitCNY and bitUSD to 5 in orderbook display - Flip CNY:OPEN.BTC market in dashboard - Add bitSilver asset icon - Add Chinese intro text by bitcrab - Add grid lines and y axis labels to the depth chart Bug fixes -------- - Fix Popover links so they work within the router context - Update react-router to v3.0.2 - Refactor blockTrades withdrawal address caching - Scroll orderbook to top when changing markets - Don't set feed price in MarketStore for markets without call orders - Fix setting of highestBid in MarketStore - Update bitsharesjs, fixes vesting balances not loading properly - Fix persistence of indicator settings - Fix PriceChart resize on switching to/from left orderbook - Update Dashboard markets, add loading indication until accounts are ready - Fix Operation display of asset_global_settle operation --------------------------------------------------------------------- Release 2.0.170215 --------------------------------------------------------------------- New features - New intro text has been added to the Dashboard for new users - Several settings and wallet related parameters have been made dependent on the chain id, and will thus switch accordingly if you connect to the testnet for example. - Windows light client installer will now remove personal data properly if checked Bug fixes -------- - Fix Russian language selection - Fix proxy selection - Fix committee/witness pages - A bug when importing old BTS 1 balances has been fixed - App init flow has been improved - Fix asset creation precision slider - Fix HelpContent links - Only trigger MarketCard img onerror update once - [Blocktrades] Fix issue with 'calculating crashes' in Blocktrades Bridge - [Blocktrades] Disable 'withdraw now' and 'convert now' buttons if no funds - [Blocktrades] Move amount from output withdraw section to withdraw dialog in Blocktrades Bridge - [Blocktrades] Fix displaying MKR coin - [Blocktrades] Add ability to move balance to 'Amount selector' in withdraw dialog on mouse click --------------------------------------------------------------------- Release 2.0.170201 --------------------------------------------------------------------- New features - Charting revamp: new charts using [react-stockchart](https://github.com/rrag/react-stockcharts) - Russian language translation thanks to @rusteemitblog and @testzcrypto - Add brainkey restoration to create-account, improve brainkey restoration - All open orders, collateral and debt are now included when estimating total account value on the account screen - A 'Borrow' action added to the account assets table - A 'Reset settings' button added to the Settings page - Dates have been added to the Chat (requires implementation by other clients like Openledger also) - Hide 'OPEN.' prefix from Openledger assets - The dashboard market cards have been modified to be more clear - Hempsweet UIA symbol added ahead of their launch Bug fixes -------- - Many tweaks and fixes to colors, positioning and more - Make sure transfer asset stays synced - Fix bug in CER input during asset creation - Move 'show hidden accounts' inside DashboardList, improve the layout --------------------------------------------------------------------- Release 2.0.170123 --------------------------------------------------------------------- Bug fixes -------- - Use relative paths for fetching assets, fixed wallet creation issues - Fix some links in the light wallets - Fix market flipping for UIAs - Fix several bugs related to hash-history react router config - Change Graphene to BitShares - Replace graphenejs-lib with bitsharesjs - Fix npm errors - Fix line breaks for memos with very long words - Make sure asset actions render properly in AccountOverview - Ensure proxy accounts get resolved properly in Voting --------------------------------------------------------------------- Release 2.0.170118 --------------------------------------------------------------------- New features -------- - Helpul tooltips have been added in multiple locations, such as login/unlock, margin mechanics ++ - Proposed transaction summaries added to transaction history lists - Always display settings cog in header Bug fixes -------- - Fix display of asset page for bit assets with no valid feeds - Remove maximum_short_squeeze_ratio requirement for minimum collateral - Base Call Order forSale/toReceive calculation on debt instead of collateral - Fix TimeAgo tooltip positioning - Hide 'show hidden assets' button when no assets are hidden - Update Chinese translations - Set depth chart xaxis properly when no asks are present - Fix price being set when clicking on orderbook order - Add a tooltip explaning that buy amounts are minimum to receive - Filter call orders on feed update --------------------------------------------------------------------- Release 2.0.170116-rc1 --------------------------------------------------------------------- New features -------- - Major refactor of market handling: improved order matching and market data processing - Upgrade to Webpack 2, add ES6 code splitting and dynamic route loading - [Blocktrades] Add internal conversion - Major package upgrades: react, react-router, alt, file-saver ++ - Use Roboto font everywhere by default - Add Equivalent values to Worker table, improve layout - Add a warning for disabled markets and disable buy/sell - Only redirect to account creation on direct navigation to "/" - Update default markets and add some asset symbols Bug fixes -------- - [Blocktrades] Fix 'Calculating Internal Server Error' - [Blocktrades] Fix displaying 'Deposit limit' for 'Internal conversion' - [Blocktrades] Fix copy/paste for memo - Fix dropdown font colors - Fix missing connection translation key - Improve multi-sig signing handling, exclude owner keys if not needed - Hide tooltips on navigation - Fix Account active state in Header - Change 'No price available' to 'Unknown', and add a tooltip - Fix account creation and dictionary loading - Fix orderbook show more button - Fix some invalid JSON --------------------------------------------------------------------- Release 2.0.161031 --------------------------------------------------------------------- New features -------- - Add Blockpay to default markets and update markets list - Add btsabs and Transwiser API servers - Allow the Chat box to be hidden from a docked state - Vesting balance amounts are now updated correctly, and a Try claim all button has been added - Chinese translation updates - MetaExchange has been removed from the deposit withdraw providers Bug fixes -------- - Add BitShares bloom filter for BTS 1 account imports - Fix a GenesisFilter bug and update ImportKeys flow slightly - Fix input of uppercase characters in AccountPermissions - Fix Highcharts build issues - Remove unused refcode inputs --------------------------------------------------------------------- Release 2.0.160829 --------------------------------------------------------------------- New features -------- - Hash checksums for all binaries - Add copy address/memo buttons to deposit, improve mobile layout - Improve transfer layout, add exchange scam account warnings - Add option to move BuySell below Orderbook - Add brainkey option to Settings Restore page - Add API selection to SyncError page, improve the error message Bug fixes -------- - Fix price display in MarketCards - Add proposed operation id to summary - Add deposit/withdraw to mobile menu - Fix hiding of disabled chat window - Fix WalletCreate submit with invalid inputs, close #860 - Fix BackupBrainkey navigation - Hide input spinner in Firefox - Use newest version of node-libs-browser, fixes backups in Firefox close - Fix HelpContent 'en' locale fallback --------------------------------------------------------------------- Release 2.0.160813 --------------------------------------------------------------------- New features -------- - Refactor account creation - Disable chart indicators by default - BlockTrades deposit/withdraw improvements - Update Featured assets, add ICOO/PeerPlays - Change depth chart tooltip to table layout - Restore the Account link to the Header - Disable Chat by default, make it easier to enable/disable - Add current price to Dashboard MarketCards Bug fixes -------- - Rearrange Exchange components and improve responsive behaviour - Adjust DepthChart min/max range - Prevent infinite loop on bad system clock, add warning - Filter out duplicate welcome messages from chat history - Fix Orderbook click calculation - Fix buy side order book click total calculation - Fix for 1.0 balance claims --------------------------------------------------------------------- Release 2.0.160702 --------------------------------------------------------------------- Bug fixes -------- - Display 'New wallet' button for users with only one wallet - Fix light wallet local file loading, use data-urls for some pngs - Remove back call on wallet deletion - Update electron version - Center-align the advanced features button - Fix backup restore submit button - Fix api error redirection - Fix Backup restore accept button close #858 - Fix initError loading issues and layout --------------------------------------------------------------------- Release 2.0.160629 --------------------------------------------------------------------- New features -------- - Api code moved to new graphenejs-ws library - Crypto and blockchain state code moved to graphenejs-lib library - Add OPEN.MKR deposit/withdrawal - Limit chat messages to 140 characters - Refactor MyMarkets selection to tabbed layout - Remove MetaEx deposits, add warning and link - Add OpenLedger deposit/withdrawal support for Omni & related coins (USDT, EURT) - Updated header layout, new dropdown menu - Add lightning bolt to indicate lifetime members - Refactor Deposit/Withdraw tabs to a dropdown selection - Modify OpenOrders layout, use x icon for Cancel order - Big refactor of the Settings page to more friendly layout - Hide advanced features by default Bug fixes -------- - Update several packages to newer versions - Remove brainkey dictionary from app.js and load async instead - Refactor language selection to fetch language files async on demand - Improve build routine, reduce filesize - Fix cancel button font color in WebSocketAddModal - Fix buttons with invisible text - Improve Exchange fee asset selection - Disable chat in Safari - Use 8 decimal prices for assets like BTC in markets list - Make sure a valid price history bucket size is selected on load - Improve visibility of Buy/Sell fee selector - Improve initial load of AccountStore, should fix #827 - Update default markets - Remove 'Ignore' button in AccountLeftPanel - Lowercase account names in DashboardList, change filter style and text --------------------------------------------------------------------- Release 2.0.160524 --------------------------------------------------------------------- New features -------- - Improvements to account creation and wallet creation pages - Improvements to wallet management - Update several 3rd party libraries - Add Lisk symbol and OPEN.LISK to dashboard, homogenize icon sizes Bug fixes -------- - Fix tooltip bug causing the screen to scroll to the top - Add some padding to Dashboard sides - Allow Transfer page recent history to take full height - Change purple link/button color to blue - Fix unrestrained icon height issues in the dashboard - Scroll the Chat to the bottom if the footer visibility changes - Chinese translation updates - Fix Chatbox not scrolling to bottom on new messages - Fix a bug that made the cli_wallet unable to decode GUI memos - Fix the BlockTrades gateway, which was not validating withdrawal addresses correctly --------------------------------------------------------------------- Release 2.0.160514 --------------------------------------------------------------------- New features -------- - Simple p2p chat history - More improvements to the deposit/withdraw screens - Make trollbox dockable on right side - Use separate support addresses for OpenLedger and BlockTrades deposits - Add OPEN.ETH:OPEN.DAO market to featured markets Bug fixes -------- - Fix Settings page issue with chat disable - Fix settings page causing the GUI to freeze (#842) - Improvements to trollbox server to ensure uptime - Fix chatbox select box height (thanks to nmywn) - Turkish translation updates - Add some filtering to BlockTrades coins to prevent errors - Separate price and volume slightly in PriceChart, adjust colors - Improve depth chart zoom level - Improve Footer hide behaviour - Fix trollbox mem leak and connection counter, improve error handling #844 - Update packages: react to 15.0.2, react-highcharts, fix breaking changes - Fix an AccountSelector bug causing name resets while typing --------------------------------------------------------------------- Release 2.0.160504 --------------------------------------------------------------------- New features -------- - Trollbox has been added (with tipping!) - Revamped deposit/withdraw for Blocktrades/Openledger - Add and show more 'Featured Markets' - Transaction filtering in recent transactions lists Bug fixes -------- - Chinese and Turkish translation updates - Increase grid-container max-width to 70rem - Change CCEDK in deposit/withdraw to Openledger - Format MarketCard volumes, add some spacing - Improve volume formatting - Show more decimals for BTC equivalent balance values - Show market name in AccountOverview asset popover market link - Fix AccountPermissions width issue --------------------------------------------------------------------- Release 2.0.160428 --------------------------------------------------------------------- New features -------- - Enable OPEN.DGD deposits and withdrawals - Add 'Featured Markets' to Home page, change page layout - Add timestamp to backup names - Enable the account selector on the Deposit/Withdraw page - Restore Deposit/Withdraw to AccountLeftPanel, add 'Advanced' subheader - Always show header account selector - Account selector icon is now clickable and takes you to the account - Always show 'Home' button in header Bug fixes -------- - Fix Safari load issues - Chinese translation updates - Fix InitError dropdown not displaying correct entry - Chinese translation updates - Fix TotalBalance tooltip when borrowing small amounts - Replace n/a with 'No price available' - Fix Asset popover title color, adjust some text - Tweak some light-theme font colors --------------------------------------------------------------------- Release 2.0.160420 --------------------------------------------------------------------- New features -------- - Allow fees for order cancellation and shorting to be paid in assets other than BTS - Enable OPEN.STEEM deposits and withdrawals Bug fixes -------- - Turkish translation updates - Improve localStorage wrapper methods - Blocktrades display fix Notes -------- Two new developers had commits accepted into this release: destenson and rulatir, and nmywn also continues to make useful contributions. Their efforts are much appreciated! --------------------------------------------------------------------- Release 2.0.160413 --------------------------------------------------------------------- New features -------- - Rename Trade to Exchange - Change order of header entries - Move Deposit/Withdraw to header - Add support for bitassets with backing asset other than CORE in the exchange Bug fixes -------- - Fix some deposit page bugs and update the layouts - Some external lib updates - Hide empty parentheses in RecentTransactions header - Increase depth chart range - Update the Blocktrades bridge code to use the correct wallet symbols for MKR on the BitShares blockchain - Fix ProposedOperation text for asset_create operation - Chinese, Turkish and English translation updates - Market trade date format fix + light theme hovering fixes and cosmetics - Added OPEN.STEEM deposit option to CCEDK tab - Only use 'bit' prefix for SmartCoins issued by the committee-account --------------------------------------------------------------------- Release 2.0.160406 --------------------------------------------------------------------- New features -------- - Display required approvals as percent for multi-sig with threshold higher than 10 - Add asset description to AssetName tooltip - Add 'bit' prefix to bit assets, remove *, use smaller prefix for OPEN, TRADE and METAEX assets Bug fixes -------- - Sorting public keys by their converted address (per witness_node logic). #795 - Bug in BuySell fee asset selection - Show account names as links in account permissions list #790 - Fix account selector issue - Add warning about precision on asset creation #756 - Fix tooltips not appearing over modals - Allow account upgrade, voting, permission changes and withdrawals to be paid in assets other than BTS if necessary #786 --------------------------------------------------------------------- Release 2.0.160330 --------------------------------------------------------------------- NEW FEATURES: - Proposed transactions - Add a 'Reset settings' button to Settings and InitError page - Split workers table into proposed and active workers - Remove negative votes - Add set of known proxies, add lists of active witnesses and cm's to voting pages - Add name replace for asset symbols in fee selection dropdown - Improve worker approve/reject logic and add status coloring - Add explanation of vesting balances - Add memo support to asset issue modal and display memos in Operation/Transaction BUG FIXES: - Language settings not persisting in light client - Fix some bugs and typos in AccountStore authority check - In serializer for transactions, sort addresses and public keys in descending order - Handle nested authorities for hierarchical multi-sig - Set new accounts voting proxy to 'proxy-to-self' account #700 - Improve RecentTransactions sorting function #793 - Add Settings link to mobile menu #759 - Make sure negative votes are removed when updating votes #798 - Fix vesting balance styling #722 - Fix init loader white background - Fix orderbook onClick not syncing after order has filled #768 - Translate csv and tooltip and move closer to title #780 --------------------------------------------------------------------- Release 2.0.160314 --------------------------------------------------------------------- NEW FEATURES: - Updated with serializer types from stealth branch (adds better sorting in transactions) - Improve DepthChart construction and plotting - Increase websocket timeout to 5s BUG FIXES: - Refactor and fix error in onAmountChange function that prevents withdraw modal to pop up - Enforce https for faucet address when on https domain - Fix buy/sell collapse behaviour #779 - Show disabled buy/sell and my orders for users with no account #774 - Redirect to proper websocket url if user entered invalid URL #770 --------------------------------------------------------------------- Release 2.0.160309 --------------------------------------------------------------------- NEW FEATURES: - Switch to using unique ethereum addresses for OpenLedger inputs - Hide Footer in Exchange view - Add preferred market pairing field to asset description - Сoloring of price column headers in Orderbook - Add + - buttons to the pricechart to change the height of the exchange charts - Filter out 0 and Inf price values from pricechart data - Put volume and price in the same chart - Add zoom buttons for PriceChart, filter out bucket sizes below 5 minute BUG FIXES: - Prices with precision larger than asset precision causes incorrect final price #757 - Fix exchange box header background colors - TransitionWrapper not reenabling after reset - Fix Transfer fee asset selection for users with only one non-core asset --------------------------------------------------------------------- Release 2.0.160302 --------------------------------------------------------------------- NEW FEATURES: - Various exchange layout improvements - Add rgba fill colors for depth charts - Use full precision for Orderbook and MarketHistory asset amounts BUG FIXES: - Check for price equal to infinity when parsing fill history - Fix membership button text being invisible #752 - Fix asset creation CER precision issues #753 - Fix disappearing faucet address in Settings #751 - Fix AccountMembership spelling errors, also remove reference to annual membership #749 - Fix AccountMembership margin issues and add referral link for lifetime members --------------------------------------------------------------------- Release 2.0.160225 --------------------------------------------------------------------- NEW FEATURES: - Add theming support and theme switch in Settings #576 - Add scrolling to RecentTransactions - Add base groups to MyMarkets: BTS, BTC, USD or CNY + others BUG FIXES: - Fix BlockTrades select background color - Ensure vertical orderbook layout is correct on mount - Fix Fee schedule decimals issue - Allow user to delete last number in Transfer amount entry - Fix some styling issues after move to themes - Fix matching of orders when clicking on order in orderbook #586 - Sum for_sale values when adding orders at same price --------------------------------------------------------------------- Release 2.0.160217 --------------------------------------------------------------------- NEW FEATURES: - Big trade page make over BUG FIXES: - Exchange buy fee selection - Remove link to BTS:BTS market in asset popover, fix asset description #709 - Disable annual membership upgrade #730 - Fix My Orders not updating when flipping the market - Fix Orderbook totals calculation - Fix current price indicator not repositioning after window resize - Fix fee subtraction when clicking on current balance - Fix margin call mechanics, add dynamic update support for settle orders and feed price changes, improve market data fetching logic - Fix number parsing for call orders and homogenize presentation with asks/bids/calls - Fix vertical orderbook positioning and scrolling - Link to /overview from Dashboard, change Orders to Open orders, #707 and #736 - Fix transfer fee mismatch #738 - Fix a bug in BlockTradesGatewayDepositRequest and change BridgeDepositRequest input types to 'number' #733 - Fix Blocktrades input and select colors #733 --------------------------------------------------------------------- Release 2.0.160208 --------------------------------------------------------------------- NEW FEATURES: - Fee asset selection when trading on the exchange - Allow funding of fee pool by accounts other than the issuer - Enable fee claim operation - OpenLedger gateway support for OPEN.ETH BUG FIXES: - Add a react key to gateway assets to prevent rendering the wrong data when swtiching tabs in the deposit/withdraw screen - Include all orders when show all is active fix #727 - Hide Issue Asset button for MPAs --------------------------------------------------------------------- Release 2.0.160203 --------------------------------------------------------------------- NEW FEATURES: - Support address authorities in account permissions #660 - Ability to permanently ignore/unignore own accounts #697 - Support SmartCoins/UIAs/Prediction Market in Assets Explorer - Support SmartCoins and Prediction Market Assets on Assets Creation page - Added show all button to orderbook - Better prediction markets support: one-click shorting, enforce market direction, set depth BUG FIXES: - Fix OpenLedger/ccedk's gateway mistakely labeled as a bridge #696 - Fix pubkey lookup method #660 - Fix Exchange scrolling issues - Fix Orderbook scroll bars appearing when not necessary - Fix some fee schedule bugs --------------------------------------------------------------------- Release 2.0.160127 --------------------------------------------------------------------- NEW FEATURES: - Bridge support for OPEN.BKS - Better price precision on markets with low precision assets #692 - Improved operations display, added more op translation - Simplify Exchange price handling, limit values to Satoshi amounts - Ability to hide/show assets in the Overview balance list #687 - Some performance optimizations BUG FIXES: - Disappearing fee field in Transfer #678 - TimeAgo not updating, and update react-intl version - Fix edge case in PriceChart update logic #669 - Per market price display direction #415 - Update all memos when the wallet is unlocked #661 --------------------------------------------------------------------- Release 2.0.160121 --------------------------------------------------------------------- NEW FEATURES: - USD, EUR, CNY fiat deposit/withdrawals via OpenLedger - Added OPEN.EMC and OPEN.EGD to OpenLedger bridge - Blocktrades support for TRADE.DASH/PPC/DOGE - Table View for Workers #632 - Hide Workers with negative approval #632 - UTF-8 memo support #624 - Support for 'asset_reserve' operation - Show lifetime membership fees - Improved Fee Explorer: Cleanup, nicer tables, better translations - Allow users to browse the Exchange even without having an account BUG FIXES: - My History / History alignment #568 - 'Missing Active Authority' permissions issue #676 - Show correct selected connection in Settings - Allow shorting of prediction market assets, fix #667 - Refactor AccountVoting worker view to table layout, fix #632 - Fix 'span' as child of 'tr' error - Subtract fees for filled orders, show fees paid, fix #658 --------------------------------------------------------------------- Release 2.0.160106 --------------------------------------------------------------------- NEW FEATURES: - Add tooltips explaining why Buy/Sell buttons are disabled fix #628 - Add vesting balances page showing all vesting balance objects fix #640 - Enforce secure websocket connections when using https host fix #638 - Add tooltip showing full memo #636 - Add text and unlock button for transfers with memos when wallet is locked #636 - Wallet auto lock #265 BUG FIXES: - Incorrect asset listed in "net worth" tooltip #633 - Persistence of language selection #634 - Settings screen "Preferred unit of account", wrong asset is selected #626 - Inconsistent toggle placement between Table View and Card View #613 - MetaExchange withdraw/deposit page, persist tab state - Excel issue with transactions history csv format --------------------------------------------------------------------- Release 2.0.151223 --------------------------------------------------------------------- NEW FEATURES: - Membership page: show vested cashback balance and add Claim button next to it #500 - Ability to download account history as CSV file #611 - UX improvements to asset update and create BUG FIXES: - Many URLs in the GUI are not clickable #546 - Update Voting help text #589 - Add asset formatting to fee pool balance and issuer income #618 - Limit core exchange rate asset amounts by asset precision #617 - Fix 'cannot dispatch in the middle of dispatch' error #614 - Restrict min width of markets section #615 - Add vesting balance information and claim button #500 - Add CER (core exchange rate) to asset creation #543 --------------------------------------------------------------------- Release 2.0.151216 --------------------------------------------------------------------- NEW FEATURES: - Dashboard makeover #590 - Total Value in header #584 - Show Date in All History #580 - Switch the default chart interval to 1 day #601 - Show one more decimal for prices in Exchange - Show popup with additional info when user clicks on currency symbol BUG FIXES: - Failed to broadcast the transaction (now <= trx.expiration) #583 - Consolidated Open Orders screen bug #585 - Get rid of the horizontal scroll-bar in Recent Activity #470 - Unnecessary scroll-bars on the Create Asset confirmation screen #547 - Decimal Bug in Matching in 8-digit Assets #586 - In Lite wallet all website links result in broken pages #581 --------------------------------------------------------------------- Release 2.0.151202 --------------------------------------------------------------------- NEW FEATURES: - Option to pay fees in BTS if possible #356 - Block explorer page that shows the current fee schedule #357 - Improved my history panel on Exchange page #527 - Exchange layout improvements: add borders, refactor statusbar, no-data text, panel headers #538 - Support for Fee Pool funding and Asset fee claims #495 - Exchange layout: add borders, refactor statusbar, no-data text, panel - Ability to send all, subtract fees if paid in same asset #454 - Cease IE support and warn IE users that they need to switch to Edge, Chrome or Firefox #474 BUG FIXES: - Active account name is missing on the top toolbar of the market page #545 - Don't show "This wallet has already been imported" if there are duplicate keys #565 - Populate empty pricedata with latest price if outside of bucket window #550 - Turkish ui buttons don't respond #539 - Changing indicators on market without history makes whole web wallet unresponsive #569 --------------------------------------------------------------------- Release 2.0.151125 --------------------------------------------------------------------- NEW FEATURES: - Added "Back" and "Forward" buttons #453 - Show stake percentages at all times in wallet #522 - Display total assets of all account in chosen currency #512 - Request settlement of bit asset #493 - Show BTS balance in Accounts search results table #482 - Exchange > highlight active market state on bottom right #499 - Deposit/Withdraw page split into tabs (addresses #521) BUG FIXES: - Fix market issue: clicking on account balance vs Lowest Ask #469 - Transfer Dialog does not fall back to BTS fee when there is no core exchange rate or funded fee pool #329 - "Borrow Asset" window resets on new block on some accounts #505 - Clicking on lowest or highest buy/sell price does not result in an eligible market order #515 - Add the collateral ratio number of each asset to the overview page #397 - App crashes on the market page - argument is not an object id #520 - OS X Light Wallet Bug #525 - Market %change and volume do not match #528 - The [FAV MARKETS] / [ALL MARKETS] tabs don't work when accessed for the very first time. #519 - Cannot find some markets #526 - Account drop-down options are inconsistent with selected third-party account #523 - Market page shows loading indicator if user doesn't have any account - it should suggest to create account instead #507 --------------------------------------------------------------------- Release 2.0.151119 --------------------------------------------------------------------- NEW FEATURES: - Warn users placing below the price market orders (e.g. 20% off market price) #445 - Feedback while adjusting collateral slider #451 - Account orders history on Exchange - Markets overview page redisign, improved market search functionality - Add 24h change and volume to markets list - Improved favorite/unvoriete markets functionality - Added support for deposits/withdrawals on blocktrades.us in bridge mode - Added filtering and current supply to Assets overview - Added TRADE.MUSE, METAFEES and OBITS to default favorite markets BUG FIXES: - Fixed several spelling and typos issues - Issue building with the latest node.js on Windows #481 - "Promise not defined" build issue #488 - Orderbook and market history colors are missing for some numbers #490 - "Borrow Asset" window resets on new block on some accounts #505 - Animation on create account page - helps to safe space - Fix asset creation fee estimation
{'content_hash': '04b35a6eb0f84b523e0d6f29be5f0fd8', 'timestamp': '', 'source': 'github', 'line_count': 918, 'max_line_length': 172, 'avg_line_length': 43.1078431372549, 'alnum_prop': 0.6837490207970081, 'repo_name': 'oceanliao/chnbts', 'id': 'daaa7b9c18133d250ae07561133f526342b02b83', 'size': '39644', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CHANGELOG.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '84240'}, {'name': 'CoffeeScript', 'bytes': '2702'}, {'name': 'HTML', 'bytes': '5921'}, {'name': 'JavaScript', 'bytes': '2087427'}, {'name': 'NSIS', 'bytes': '3769'}, {'name': 'Python', 'bytes': '1188'}]}
<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="numberformat08.xsl"?> <doc> </doc>
{'content_hash': '7bc23385558ea6f27d71d70fa9a2114e', 'timestamp': '', 'source': 'github', 'line_count': 4, 'max_line_length': 60, 'avg_line_length': 24.5, 'alnum_prop': 0.6428571428571429, 'repo_name': 'gsnedders/presto-testo', 'id': '97789445df8dc17d3a40ae8f81ac457bba11fe45', 'size': '98', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'core/standards/xslt/numberformat/numberformat08.xml', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'ASP', 'bytes': '2312'}, {'name': 'ActionScript', 'bytes': '23470'}, {'name': 'AutoHotkey', 'bytes': '8832'}, {'name': 'Batchfile', 'bytes': '5001'}, {'name': 'C', 'bytes': '116512'}, {'name': 'C++', 'bytes': '219486'}, {'name': 'CSS', 'bytes': '207914'}, {'name': 'Erlang', 'bytes': '18523'}, {'name': 'Groff', 'bytes': '674'}, {'name': 'HTML', 'bytes': '103359143'}, {'name': 'Haxe', 'bytes': '3874'}, {'name': 'Java', 'bytes': '125658'}, {'name': 'JavaScript', 'bytes': '22516843'}, {'name': 'Makefile', 'bytes': '13409'}, {'name': 'PHP', 'bytes': '531453'}, {'name': 'Perl', 'bytes': '321672'}, {'name': 'Python', 'bytes': '948191'}, {'name': 'Ruby', 'bytes': '1006850'}, {'name': 'Shell', 'bytes': '12140'}, {'name': 'Smarty', 'bytes': '1860'}, {'name': 'XSLT', 'bytes': '2567445'}]}
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="#FFCCCCCC" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Fragment1" android:textColor="#FF000000"/> </LinearLayout>
{'content_hash': '0d491da07539adf958e26e719c85ec7e', 'timestamp': '', 'source': 'github', 'line_count': 14, 'max_line_length': 72, 'avg_line_length': 32.642857142857146, 'alnum_prop': 0.6849015317286652, 'repo_name': 'ksoichiro/android-snippets', 'id': 'db40bd42784a7dec9156b5dbed07953c32a424ee', 'size': '457', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'app/src/main/res/layout/fragment_tab1.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Groovy', 'bytes': '3836'}, {'name': 'Java', 'bytes': '181388'}, {'name': 'Shell', 'bytes': '969'}]}
package com.jetbrains.python.fixtures; import com.intellij.lexer.Lexer; import com.intellij.testFramework.PlatformLiteFixture; import com.jetbrains.python.PythonDialectsTokenSetContributor; import com.jetbrains.python.PythonDialectsTokenSetProvider; import com.jetbrains.python.PythonTokenSetContributor; /** * @author yole */ public abstract class PyLexerTestCase extends PlatformLiteFixture { @Override protected void setUp() throws Exception { super.setUp(); initApplication(); registerExtensionPoint(PythonDialectsTokenSetContributor.EP_NAME, PythonDialectsTokenSetContributor.class); registerExtension(PythonDialectsTokenSetContributor.EP_NAME, new PythonTokenSetContributor()); PythonDialectsTokenSetProvider.reset(); } public static void doLexerTest(String text, Lexer lexer, String... expectedTokens) { doLexerTest(text, lexer, false, expectedTokens); } public static void doLexerTest(String text, Lexer lexer, boolean checkTokenText, String... expectedTokens) { lexer.start(text); int idx = 0; int tokenPos = 0; while (lexer.getTokenType() != null) { if (idx >= expectedTokens.length) { final StringBuilder remainingTokens = new StringBuilder(); while (lexer.getTokenType() != null) { if (remainingTokens.length() != 0) { remainingTokens.append(", "); } remainingTokens.append("\"").append(checkTokenText ? lexer.getTokenText() : lexer.getTokenType().toString()).append("\""); lexer.advance(); } fail("Too many tokens. Following tokens: " + remainingTokens.toString()); } assertEquals("Token offset mismatch at position " + idx, tokenPos, lexer.getTokenStart()); String tokenName = checkTokenText ? lexer.getTokenText() : lexer.getTokenType().toString(); assertEquals("Token mismatch at position " + idx, expectedTokens[idx], tokenName); idx++; tokenPos = lexer.getTokenEnd(); lexer.advance(); } if (idx < expectedTokens.length) fail("Not enough tokens"); } }
{'content_hash': '078abb1aeca1ad220e855795a1a8f743', 'timestamp': '', 'source': 'github', 'line_count': 56, 'max_line_length': 132, 'avg_line_length': 38.75, 'alnum_prop': 0.6751152073732719, 'repo_name': 'leafclick/intellij-community', 'id': 'b5a51d317357b60eb1c1b52b74141f1798db7482', 'size': '2770', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'python/testSrc/com/jetbrains/python/fixtures/PyLexerTestCase.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Score extends CI_Controller { public function __construct() { parent::__construct(); $this->load->library('session'); $this->load->helper(array('form', 'url')); $this->load->model('score_model'); } public function index() { $this->load->view('header'); $this->load->view('score'); $this->load->view('footer'); } public function view() { $data = array( 'category' => $this->input->post('category'), 'name' => $this->input->post('name'), 'number' => $this->input->post('number') ); $data = $this->security->xss_clean($data); $data['item'] = $this->score_model->get_items($data); $data['scores'] = $this->score_model->get_scores($data); $data['total'] = $this->score_model->get_total($data); $this->load->view('header'); $this->load->view('score_detail', $data); $this->load->view('footer'); } }
{'content_hash': 'ed7bd6eedf5aa3d78f73731c2090d7b1', 'timestamp': '', 'source': 'github', 'line_count': 35, 'max_line_length': 64, 'avg_line_length': 30.62857142857143, 'alnum_prop': 0.5223880597014925, 'repo_name': 'huaiping/aladdin', 'id': 'ceb94810119693370678d4f272ae4bf7279d796e', 'size': '1072', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'application/controllers/Score.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '21967'}, {'name': 'HTML', 'bytes': '5633'}, {'name': 'JavaScript', 'bytes': '136848'}, {'name': 'PHP', 'bytes': '2256780'}, {'name': 'TSQL', 'bytes': '9771'}]}
<!-- THIS IS AUTO-GENERATED CONTENT. DO NOT MANUALLY EDIT. --> This image is part of the [balena.io][balena] base image series for IoT devices. The image is optimized for use with [balena.io][balena] and [balenaOS][balena-os], but can be used in any Docker environment running on the appropriate architecture. ![balenalogo](https://avatars2.githubusercontent.com/u/6157842?s=200&v=4). Some notable features in `balenalib` base images: - Helpful package installer script called `install_packages` that abstracts away the specifics of the underlying package managers. It will install the named packages with smallest number of dependencies (ignore optional dependencies), clean up the package manager medata and retry if package install fails. - Working with dynamically plugged devices: each `balenalib` base image has a default `ENTRYPOINT` which is defined as `ENTRYPOINT ["/usr/bin/entry.sh"]`, it checks if the `UDEV` flag is set to true or not (by adding `ENV UDEV=1`) and if true, it will start `udevd` daemon and the relevant device nodes in the container /dev will appear. For more details, please check the [features overview](https://www.balena.io/docs/reference/base-images/base-images/#features-overview) in our documentation. # [Image Variants][variants] The `balenalib` images come in many flavors, each designed for a specific use case. ## `:<version>` or `:<version>-run` This is the defacto image. The `run` variant is designed to be a slim and minimal variant with only runtime essentials packaged into it. ## `:<version>-build` The build variant is a heavier image that includes many of the tools required for building from source. This reduces the number of packages that you will need to manually install in your Dockerfile, thus reducing the overall size of all images on your system. [variants]: https://www.balena.io/docs/reference/base-images/base-images/#run-vs-build?ref=dockerhub # How to use this image with Balena This [guide][getting-started] can help you get started with using this base image with balena, there are also some cool [example projects][example-projects] that will give you an idea what can be done with balena. # What is Python? Python is an interpreted, interactive, object-oriented, open-source programming language. It incorporates modules, exceptions, dynamic typing, very high level dynamic data types, and classes. Python combines remarkable power with very clear syntax. It has interfaces to many system calls and libraries, as well as to various window systems, and is extensible in C or C++. It is also usable as an extension language for applications that need a programmable interface. Finally, Python is portable: it runs on many Unix variants, on the Mac, and on Windows 2000 and later. > [wikipedia.org/wiki/Python_(programming_language)](https://en.wikipedia.org/wiki/Python_%28programming_language%29) ![logo](https://raw.githubusercontent.com/docker-library/docs/01c12653951b2fe592c1f93a13b4e289ada0e3a1/python/logo.png). # Supported versions and respective `Dockerfile` links : [&#x60;3.9.1 (latest)&#x60;, &#x60;3.8.6&#x60;, &#x60;2.7.18&#x60;, &#x60;3.7.9&#x60;, &#x60;3.6.12&#x60;, &#x60;3.5.10&#x60;](https://github.com/balena-io-library/base-images/tree/master/balena-base-images/python/artik5/fedora/) For more information about this image and its history, please see the [relevant manifest file (`artik5-fedora-python`)](https://github.com/balena-io-library/official-images/blob/master/library/artik5-fedora-python) in the [`balena-io-library/official-images` GitHub repo](https://github.com/balena-io-library/official-images). # How to use this image ## Create a `Dockerfile` in your Python app project ```dockerfile FROM balenalib/artik5-fedora-python:latest WORKDIR /usr/src/app COPY requirements.txt ./ RUN pip install --no-cache-dir -r requirements.txt COPY . . CMD [ "python", "./your-daemon-or-script.py" ] ``` You can then build and run the Docker image: ```console $ docker build -t my-python-app . $ docker run -it --rm --name my-running-app my-python-app ``` ## Run a single Python script For many simple, single file projects, you may find it inconvenient to write a complete `Dockerfile`. In such cases, you can run a Python script by using the Python Docker image directly: ```console $ docker run -it --rm --name my-running-script -v "$PWD":/usr/src/myapp -w /usr/src/myapp balenalib/artik5-fedora-python:latest python your-daemon-or-script.py ``` [example-projects]: https://www.balena.io/docs/learn/getting-started/artik5/python/#example-projects?ref=dockerhub [getting-started]: https://www.balena.io/docs/learn/getting-started/artik5/python/?ref=dockerhub # User Feedback ## Issues If you have any problems with or questions about this image, please contact us through a [GitHub issue](https://github.com/balena-io-library/base-images/issues). ## Contributing You are invited to contribute new features, fixes, or updates, large or small; we are always thrilled to receive pull requests, and do our best to process them as fast as we can. Before you start to code, we recommend discussing your plans through a [GitHub issue](https://github.com/balena-io-library/base-images/issues), especially for more ambitious contributions. This gives other contributors a chance to point you in the right direction, give you feedback on your design, and help you find out if someone else is working on the same thing. ## Documentation Documentation for this image is stored in the [base images documentation][docs]. Check it out for list of all of our base images including many specialised ones for e.g. node, python, go, smaller images, etc. You can also find more details about new features in `balenalib` base images in this [blog post][migration-docs] [docs]: https://www.balena.io/docs/reference/base-images/base-images/#balena-base-images?ref=dockerhub [variants]: https://www.balena.io/docs/reference/base-images/base-images/#run-vs-build?ref=dockerhub [migration-docs]: https://www.balena.io/blog/new-year-new-balena-base-images/?ref=dockerhub [balena]: https://balena.io/?ref=dockerhub [balena-os]: https://www.balena.io/os/?ref=dockerhub
{'content_hash': '927f2df27dd4365251aefde43931811c', 'timestamp': '', 'source': 'github', 'line_count': 104, 'max_line_length': 570, 'avg_line_length': 59.33653846153846, 'alnum_prop': 0.7681088964511424, 'repo_name': 'nghiant2710/base-images', 'id': '70b5afa3137eba14ed86260510e6c463c27a9785', 'size': '6171', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'balena-base-images/docs/dockerhub/artik5-fedora-python-full-description.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Dockerfile', 'bytes': '144558581'}, {'name': 'JavaScript', 'bytes': '16316'}, {'name': 'Shell', 'bytes': '368690'}]}
package routes import ( "log" "net/http" "github.com/gorilla/websocket" "github.com/jijeshmohan/mtgrid/middleware" "github.com/jijeshmohan/mtgrid/models" "github.com/martini-contrib/binding" "github.com/martini-contrib/render" ) func ListDevices(r render.Render, data middleware.Data, req *http.Request) { devices, err := models.GetAllDevices() if err != nil { log.Println("error ", err) handleError(500, r) return } data["devices"] = devices data["host"] = req.Host r.HTML(200, "devices/index", data) } func NewDevice(r render.Render, data middleware.Data) { r.HTML(200, "devices/new", data) } func CreateDevice(r render.Render, err binding.Errors, device models.Device, data middleware.Data, req *http.Request) { if err.Len() > 0 { data["errors"] = err r.HTML(http.StatusBadRequest, "devices/new", data) return } if e := models.AddDevice(&device); e != nil { data["errors"] = updateError(err, e) r.HTML(http.StatusBadRequest, "devices/new", data) return } websocketClient(req.Host, device) r.Redirect("/devices") } func updateError(err binding.Errors, e error) binding.Errors { newError := binding.Error{ FieldNames: []string{"message"}, Classification: "Database", Message: e.Error(), } if err != nil { return binding.Errors{newError} } else { return append(err, newError) } } func websocketClient(host string, device models.Device) { dlr := &websocket.Dialer{} con, _, err := dlr.Dial("ws://"+host+"/sock", http.Header{}) if err != nil { log.Println(err) } d := struct { Status string Device models.Device }{ "CREATED", device, } err = con.WriteJSON(d) if err != nil { log.Println("ERROR: ", err) } con.Close() }
{'content_hash': '154077e5ad802e3c38a6e5c929c6e2ec', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 119, 'avg_line_length': 22.513157894736842, 'alnum_prop': 0.673874926943308, 'repo_name': 'jijeshmohan/mtgrid', 'id': 'aebe7ea48c470e07903f92d9e497dcb0f3ada01b', 'size': '1711', 'binary': False, 'copies': '1', 'ref': 'refs/heads/spa', 'path': 'routes/devices.go', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '1411'}, {'name': 'Go', 'bytes': '14467'}, {'name': 'JavaScript', 'bytes': '14024'}]}
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Cosmos.Assembler { public class LiteralAssemblerCode: Instruction { public LiteralAssemblerCode(string code) { Code = code; } public string Code { get; set; } public override void WriteText(Assembler aAssembler, System.IO.TextWriter aOutput) { aOutput.Write(Code); } } }
{'content_hash': 'a2a6760dccd879a33669f375abe5ca1e', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 90, 'avg_line_length': 19.615384615384617, 'alnum_prop': 0.5666666666666667, 'repo_name': 'kant2002/Cosmos-1', 'id': 'a717b272fcb37a90b374babf304c5384e8e4f9d4', 'size': '512', 'binary': False, 'copies': '7', 'ref': 'refs/heads/master', 'path': 'source/Cosmos.Assembler/LiteralAssemblerCode.cs', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Assembly', 'bytes': '124257'}, {'name': 'AutoIt', 'bytes': '814'}, {'name': 'Batchfile', 'bytes': '4037'}, {'name': 'C', 'bytes': '17776'}, {'name': 'C#', 'bytes': '17597675'}, {'name': 'F#', 'bytes': '1583'}, {'name': 'HTML', 'bytes': '137991'}, {'name': 'Inno Setup', 'bytes': '30869'}, {'name': 'Python', 'bytes': '4886'}, {'name': 'Visual Basic', 'bytes': '3336'}, {'name': 'XS', 'bytes': '104548'}]}
import os from pathlib import Path import subprocess from .git import git class InvalidArrowSource(Exception): pass class ArrowSources: """ ArrowSources is a companion class representing a directory containing Apache Arrow's sources. """ # Note that WORKSPACE is a reserved git revision name by this module to # reference the current git workspace. In other words, this indicates to # ArrowSources.at_revision that no cloning/checkout is required. WORKSPACE = "WORKSPACE" def __init__(self, path): """ Initialize an ArrowSources The caller must ensure that path is valid arrow source directory (can be checked with ArrowSources.valid) Parameters ---------- path : src """ path = Path(path) # validate by checking a specific path in the arrow source tree if not (path / 'cpp' / 'CMakeLists.txt').exists(): raise InvalidArrowSource( "No Arrow C++ sources found in {}.".format(path) ) self.path = path @property def archery(self): """ Returns the archery directory of an Arrow sources. """ return self.dev / "archery" @property def cpp(self): """ Returns the cpp directory of an Arrow sources. """ return self.path / "cpp" @property def dev(self): """ Returns the dev directory of an Arrow sources. """ return self.path / "dev" @property def java(self): """ Returns the java directory of an Arrow sources. """ return self.path / "java" @property def python(self): """ Returns the python directory of an Arrow sources. """ return self.path / "python" @property def pyarrow(self): """ Returns the python/pyarrow directory of an Arrow sources. """ return self.python / "pyarrow" @property def r(self): """ Returns the r directory of an Arrow sources. """ return self.path / "r" @property def git_backed(self): """ Indicate if the sources are backed by git. """ return (self.path / ".git").exists() @property def git_dirty(self): """ Indicate if the sources is a dirty git directory. """ return self.git_backed and git.dirty(git_dir=self.path) def archive(self, path, dereference=False, compressor=None, revision=None): """ Saves a git archive at path. """ if not self.git_backed: raise ValueError("{} is not backed by git".format(self)) rev = revision if revision else "HEAD" archive = git.archive("--prefix=apache-arrow/", rev, git_dir=self.path) # TODO(fsaintjacques): fix dereference for if compressor: archive = compressor(archive) with open(path, "wb") as archive_fd: archive_fd.write(archive) def at_revision(self, revision, clone_dir): """ Return a copy of the current sources for a specified git revision. This method may return the current object if no checkout is required. The caller is responsible to remove the cloned repository directory. The user can use the special WORKSPACE token to mean the current git workspace (no checkout performed). The second value of the returned tuple indicates if a clone was performed. Parameters ---------- revision : str Revision to checkout sources at. clone_dir : str Path to checkout the local clone. """ if not self.git_backed: raise ValueError("{} is not backed by git".format(self)) if revision == ArrowSources.WORKSPACE: return self, False # A local clone is required to leave the current sources intact such # that builds depending on said sources are not invalidated (or worse # slightly affected when re-invoking the generator). # "--local" only works when dest dir is on same volume of source dir. # "--shared" works even if dest dir is on different volume. git.clone("--shared", self.path, clone_dir) # Revision can reference "origin/" (or any remotes) that are not found # in the local clone. Thus, revisions are dereferenced in the source # repository. original_revision = git.rev_parse(revision) git.checkout(original_revision, git_dir=clone_dir) return ArrowSources(clone_dir), True @staticmethod def find(path=None): """ Infer Arrow sources directory from various method. The following guesses are done in order until a valid match is found: 1. Checks the given optional parameter. 2. Checks if the environment variable `ARROW_SRC` is defined and use this. 3. Checks if the current working directory (cwd) is an Arrow source directory. 4. Checks if this file (cli.py) is still in the original source repository. If so, returns the relative path to the source directory. """ # Explicit via environment env = os.environ.get("ARROW_SRC") # Implicit via cwd cwd = Path.cwd() # Implicit via current file try: this = Path(__file__).parents[4] except IndexError: this = None # Implicit via git repository (if archery is installed system wide) try: repo = git.repository_root(git_dir=cwd) except subprocess.CalledProcessError: # We're not inside a git repository. repo = None paths = list(filter(None, [path, env, cwd, this, repo])) for p in paths: try: return ArrowSources(p) except InvalidArrowSource: pass searched_paths = "\n".join([" - {}".format(p) for p in paths]) raise InvalidArrowSource( "Unable to locate Arrow's source directory. " "Searched paths are:\n{}".format(searched_paths) ) def __repr__(self): return self.path
{'content_hash': '9808c2fd3ba82310c9480e9a416d1c17', 'timestamp': '', 'source': 'github', 'line_count': 194, 'max_line_length': 79, 'avg_line_length': 31.9020618556701, 'alnum_prop': 0.6015511391177897, 'repo_name': 'cpcloud/arrow', 'id': '1080cb75d67f52b26b5fd9dccb4d16c8fd5acd09', 'size': '6975', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'dev/archery/archery/utils/source.py', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '486660'}, {'name': 'Awk', 'bytes': '3709'}, {'name': 'Batchfile', 'bytes': '29705'}, {'name': 'C', 'bytes': '1078695'}, {'name': 'C#', 'bytes': '911504'}, {'name': 'C++', 'bytes': '18880401'}, {'name': 'CMake', 'bytes': '588081'}, {'name': 'Cython', 'bytes': '1156054'}, {'name': 'Dockerfile', 'bytes': '108671'}, {'name': 'Emacs Lisp', 'bytes': '1916'}, {'name': 'FreeMarker', 'bytes': '2312'}, {'name': 'Go', 'bytes': '1794213'}, {'name': 'HTML', 'bytes': '3430'}, {'name': 'Java', 'bytes': '5134538'}, {'name': 'JavaScript', 'bytes': '110059'}, {'name': 'Jinja', 'bytes': '9101'}, {'name': 'Julia', 'bytes': '241544'}, {'name': 'Lua', 'bytes': '8771'}, {'name': 'MATLAB', 'bytes': '36260'}, {'name': 'Makefile', 'bytes': '19262'}, {'name': 'Meson', 'bytes': '55180'}, {'name': 'Objective-C++', 'bytes': '12128'}, {'name': 'PLpgSQL', 'bytes': '56995'}, {'name': 'Perl', 'bytes': '3803'}, {'name': 'Python', 'bytes': '2417779'}, {'name': 'R', 'bytes': '864022'}, {'name': 'Ruby', 'bytes': '1366715'}, {'name': 'Shell', 'bytes': '312029'}, {'name': 'Thrift', 'bytes': '142245'}, {'name': 'TypeScript', 'bytes': '1183174'}]}
<div style="padding: 7px"> <div style="width: 450px;padding-bottom: 5px;"> <div style="width: 135px; display:inline-block;"> <strong>Current branch:</strong> </div> <div style="display:inline-block;" id="GitMergeBranchInfo"></div> </div> <div style="padding-bottom: 5px;"> <div style="width:135px;display:inline-block;"> <strong> <label for="GitMergeBranchSelect">Choose merge branch:</label> </strong> </div> <div style="width:345px;display:inline-block;"> <select id="GitMergeBranchSelect" style="width: 100%" data-dojo-type="dijit/form/Select"></select> </div> </div> <div> <div style="width:135px;display:inline-block;"> <strong> <label for="GitMergeMsgInput">Message:</label> </strong> </div> <div style="width:345px;display:inline-block;"> <input type="text" id="GitMergeMsgInput" data-dojo-type="dijit/form/TextBox" data-dojo-props="placeHolder: 'Enter merge message'" style="width: 100%"/> </div> </div> <fieldset style="padding: 5px; border: 1px solid gray"> <legend> <strong>Options</strong> </legend> <div> <div style="width:160px;display:inline-block;"> <input id="GitMergeNoCommitCheckbox" data-dojo-type="dijit/form/CheckBox"/> <label for="GitMergeNoCommitCheckbox">No commit</label> </div> <div style="width:180px;display:inline-block;"> <input id="GitMergeSquashCheckbox" data-dojo-type="dijit/form/CheckBox"/> <label for="GitMergeSquashCheckbox">Squash commit</label> </div> <div style="display:inline-block;"> <input id="GitMergeNoFFCheckbox" data-dojo-type="dijit/form/CheckBox"/> <label for="GitMergeNoFFCheckbox">No Fast Forward</label> </div> </div> </fieldset> </div>
{'content_hash': '6c4a9244280a094ad486c85aaecb53d2', 'timestamp': '', 'source': 'github', 'line_count': 47, 'max_line_length': 159, 'avg_line_length': 39.59574468085106, 'alnum_prop': 0.6243954862976894, 'repo_name': 'gseok/webida-client', 'id': 'd942848285505dbd1912ba9c095d4833e0a41839', 'size': '1861', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'common/src/webida/plugins/git/layer/merge.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '2275105'}, {'name': 'HTML', 'bytes': '516508'}, {'name': 'Java', 'bytes': '138'}, {'name': 'JavaScript', 'bytes': '8010584'}, {'name': 'Python', 'bytes': '1807'}, {'name': 'Ruby', 'bytes': '867'}, {'name': 'Shell', 'bytes': '4042'}]}
<?xml version="1.0" encoding="UTF-8"?> <metadataProfile xmlns="http://www.nkp.cz/pspValidator/2.2.1/metadataProfile" name="MODS volume of multivolume monographic (AACR2)" validatorVersion="2.2.1" dmf="monograph_1.3.2" > <info> <text>DMF Monografie 1.3.2 očekává MODS verze 3.6. Dále se zde upřesňují očekávaná metadata pro svazek vícesvazkové monografie pro záznamy zpracované podle katalogizačních pravidel AACR2. </text> <url>http://www.loc.gov/standards/mods/</url> <url description="XSD pro MODS 3.6">http://www.loc.gov/standards/mods/v3/mods-3-6.xsd</url> <url description="popis MODS 3.6">http://www.loc.gov/standards/mods/mods-outline-3-6.html</url> </info> <namespaces> <namespace prefix="mods">http://www.loc.gov/mods/v3</namespace> </namespaces> <dictionaries> <dictionary name="marcRelatorCodes" description="kódy rolí podle MARC21" url="http://www.loc.gov/marc/relators/relaterm.html"/> <dictionary name="iso6392languageCodes" description="kódy jazyků podle ISO 639-2" url="http://www.loc.gov/standards/iso639-2/php/code_list.php"/> <dictionary name="siglaInstitutionCodes" description="sigly knihoven"/> </dictionaries> <rootElement name="mods:mods"> <expectedAttributes> <attribute name="ID"> <expectedContent> <regexp>MODS_VOLUME_[0-9]{4}</regexp>> </expectedContent> </attribute> </expectedAttributes> <expectedElements> <element name="mods:titleInfo"> <expectedAttributes> <attribute name="type" mandatory="false"> <expectedContent> <oneOf> <value>alternative</value> <value>translated</value> <value>uniform</value> </oneOf> </expectedContent> </attribute> </expectedAttributes> <expectedElements> <element name="mods:title"> <expectedContent/> </element> <element name="mods:subTitle" mandatory="false"> <expectedContent/> </element> <element name="mods:partNumber" mandatory="false"> <expectedContent/> </element> <element name="mods:partName" mandatory="false"> <expectedContent/> </element> </expectedElements> </element> <element name="mods:name" specification="not(mods:etal)" mandatory="false"> <expectedAttributes> <attribute name="type" mandatory="false"> <expectedContent> <oneOf> <value>personal</value> <value>corporate</value> <value>conference</value> <value>family</value> </oneOf> </expectedContent> </attribute> <attribute name="usage" mandatory="false"> <expectedContent> <value>primary</value> </expectedContent> </attribute> </expectedAttributes> <expectedElements> <element name="mods:namePart" specification="@type='date'" mandatory="false"> <expectedAttributes> <attribute name="type"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:namePart" specification="@type='family'" mandatory="false"> <expectedAttributes> <attribute name="type"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:namePart" specification="@type='given'" mandatory="false"> <expectedAttributes> <attribute name="type"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:namePart" specification="@type='termsOfAddress'" mandatory="false"> <expectedAttributes> <attribute name="type"/> </expectedAttributes> <expectedContent/> </element> <!--namePart s celym jmenem--> <element name="mods:namePart" specification="not(@type)" mandatory="false"> <expectedContent/> </element> <element name="mods:nameIdentifier" mandatory="false"> <expectedContent/> </element> <element name="mods:role" mandatory="false"> <expectedElements> <element name="mods:roleTerm"> <expectedAttributes> <attribute name="type"> <expectedContent> <value>code</value> </expectedContent> </attribute> <attribute name="authority"> <recommendedContent> <value>marcrelator</value> </recommendedContent> </attribute> </expectedAttributes> <recommendedContent> <fromDictionary name="marcRelatorCodes"/> </recommendedContent> </element> </expectedElements> </element> </expectedElements> <extraRules> <!-- Musí existovat alespoň jeden element namePart--> <existsAtLeastOnce xpath="mods:namePart"/> </extraRules> </element> <element name="mods:name" specification="mods:etal" mandatory="false"> <expectedElements> <element name="mods:etal"> <expectedContent/> </element> </expectedElements> </element> <element name="mods:typeOfResource" mandatory="false"> <expectedContent> <value>text</value> </expectedContent> </element> <element name="mods:genre" specification="text()='volume'"/> <element name="mods:originInfo"> <expectedElements> <element name="mods:place" mandatory="false"> <expectedElements> <element name="mods:placeTerm" mandatory="false"> <expectedAttributes> <attribute name="type"> <expectedContent> <oneOf> <value>code</value> <value>text</value> </oneOf> </expectedContent> </attribute> <attribute name="authority" mandatory="false"> <expectedContent> <value>marccountry</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> </expectedElements> </element> <element name="mods:publisher" mandatory="false"> <expectedContent/> </element> <element name="mods:dateIssued"> <expectedAttributes> <attribute name="encoding" mandatory="false"/> <attribute name="point" mandatory="false"> <!--tohle je povinne, coz nedava uplne smysl, resp. problem s praxi--> </attribute> <attribute name="qualifier" mandatory="false"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:dateCreated" mandatory="false"> <expectedContent/> </element> <element name="mods:edition" mandatory="false"> <expectedContent/> </element> <element name="mods:issuance"> <expectedContent> <oneOf> <value>monographic</value> <value>multipart monograph</value> <value>single unit</value> </oneOf> </expectedContent> </element> </expectedElements> </element> <element name="mods:language"> <expectedAttributes> <attribute name="objectPart" mandatory="false"> <expectedContent> <oneOf> <value>summary</value> <value>table of contents</value> <value>accompanying material</value> <value>translation</value> </oneOf> </expectedContent> </attribute> </expectedAttributes> <expectedElements> <element name="mods:languageTerm"> <expectedAttributes> <attribute name="type"> <expectedContent> <value>code</value> </expectedContent> </attribute> <attribute name="authority"> <expectedContent> <value>iso639-2b</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <fromDictionary name="iso6392languageCodes"/> </expectedContent> </element> </expectedElements> <extraRules> <!-- V rámci elementu mods:language musí existovat nejvýše jeden element mods:languageTerm s atributy type='code' a authority='iso639-2b' --> <existsAtMostOnce xpath="mods:languageTerm[@type='code' and @authority='iso639-2b']/text()" description="Pokud je potřeba zaznamenat více jazyků, musí být každý ve vlastním elementu mods:language" /> </extraRules> </element> <element name="mods:physicalDescription"> <expectedElements> <element name="mods:form"> <expectedAttributes> <!--neni jasne, jestli tohle ma byt povinne - je tam M/MA--> <attribute name="authority" mandatory="false"> <expectedContent> <oneOf> <value>marcform</value> <value>marccategory</value> <value>marcsmd</value> <value>gmd</value> </oneOf> </expectedContent> </attribute> <attribute name="type" mandatory="false"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:extent" mandatory="false"> <expectedContent/> </element> <element name="mods:note" mandatory="false"> <expectedContent/> </element> </expectedElements> </element> <element name="mods:abstract" mandatory="false"> <expectedContent/> </element> <element name="mods:note" mandatory="false"> <expectedContent/> </element> <element name="mods:subject" mandatory="false"> <expectedAttributes> <attribute name="authority" mandatory="false"> <recommendedContent> <oneOf> <value>czenas</value> <value>eczenas</value> <value>Konspekt</value> <value>czmesh</value> <value>mednas</value> <value>msvkth</value> <value>agrovoc</value> </oneOf> </recommendedContent> </attribute> </expectedAttributes> <expectedElements> <element name="mods:topic" mandatory="false"> <!--V DMF je "použít kontrolovaný slovník, napříkld ... " - tj. kontrolovaný slovník NENÍ vyžadován DMF--> <expectedContent/> </element> <element name="mods:geographic" mandatory="false"> <!--V DMF je "použít kontrolovaný slovník, napříkld ... " - tj. kontrolovaný slovník NENÍ vyžadován DMF--> <expectedContent/> </element> <element name="mods:temporal" mandatory="false"> <!--V DMF je "použít kontrolovaný slovník, napříkld ... " - tj. kontrolovaný slovník NENÍ vyžadován DMF--> <expectedContent/> </element> <element name="mods:name" mandatory="false"> <!--V DMF je "použít kontrolovaný slovník, napříkld ... " - tj. kontrolovaný slovník NENÍ vyžadován DMF--> <expectedContent/> </element> </expectedElements> </element> <element name="mods:classification" specification="not(@edition)" mandatory="false"> <!--Mezinarodni desetinne trideni--> <expectedAttributes> <!--NOTE: DMF neuvadi, jestli je authority povinny atribut, nechavam nepovinny. Povolena hodnota Konspekt, aby prošel i element bez atributu edition--> <attribute name="authority"> <recommendedContent> <oneOf> <value>udc</value> <value>Konspekt</value> </oneOf> </recommendedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:classification" specification="boolean(@edition)" mandatory="false"> <!--Konspekt--> <expectedAttributes> <!--NOTE: DMF neuvadi, jestli je authority povinny atribut, necham, ze je nepovinny--> <attribute name="authority"> <recommendedContent> <oneOf> <value>udc</value> <value>Konspekt</value> </oneOf> </recommendedContent> </attribute> <attribute name="edition"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:relatedItem" mandatory="false" ignoreUnexpectedChildElements="true"> <expectedAttributes> <!--NOTE: DMF neuvadi, jestli je type povinny atribut, necham, ze je nepovinny--> <attribute name="type" mandatory="false"/> <attribute name="otherType" mandatory="false"/> <attribute name="otherTypeURI" mandatory="false"/> <!--chyba v DMF, viz https://github.com/NLCR/Standard_NDK/issues/80--> <attribute name="otherTypeAuth" mandatory="false"/> <attribute name="otherTypeAuthURI" mandatory="false"/> </expectedAttributes> </element> <!-- identifier--> <element name="mods:identifier" specification="@type='uuid'"> <expectedAttributes> <attribute name="type"/> <attribute name="invalid" mandatory="false"> <expectedContent> <value>yes</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:identifier" specification="@type='urnnbn'"> <expectedAttributes> <attribute name="type"/> <attribute name="invalid" mandatory="false"> <expectedContent> <value>yes</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <regexp>(?i)urn:nbn:cz:[a-z0-9]{2,6}-[a-z0-9]{6}</regexp> </expectedContent> </element> <element name="mods:identifier" specification="@type='ccnb'" mandatory="false"> <expectedAttributes> <attribute name="type"/> <attribute name="invalid" mandatory="false"> <expectedContent> <value>yes</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:identifier" specification="@type='isbn'" mandatory="false"> <expectedAttributes> <attribute name="type"/> <attribute name="invalid" mandatory="false"> <expectedContent> <value>yes</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:identifier" specification="@type='ismn'" mandatory="false"> <expectedAttributes> <attribute name="type"/> <attribute name="invalid" mandatory="false"> <expectedContent> <value>yes</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:identifier" specification="@type!='uuid' and @type!='urnnbn' and @type!='ccnb' and @type!='isbn' and @type!='ismn'" mandatory="false"> <expectedAttributes> <attribute name="type" mandatory="false"/> <attribute name="invalid" mandatory="false"> <expectedContent> <value>yes</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:location" mandatory="false"> <expectedElements> <element name="mods:url" mandatory="false"> <expectedAttributes> <attribute name="note" mandatory="false"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:physicalLocation" repeatable="false"> <expectedAttributes> <attribute name="authority" mandatory="false"> <expectedContent> <value>siglaADR</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <fromDictionary name="siglaInstitutionCodes"/> </expectedContent> </element> <element name="mods:shelfLocator"> <expectedContent/> </element> </expectedElements> </element> <element name="mods:part" mandatory="false"> <expectedAttributes> <attribute name="type" mandatory="false"> <expectedContent> <value>volume</value> </expectedContent> </attribute> </expectedAttributes> <expectedElements> <element name="mods:detail" mandatory="false"> <expectedElements> <element name="mods:caption" mandatory="false"> <expectedContent/> </element> </expectedElements> </element> </expectedElements> </element> <element name="mods:recordInfo"> <expectedElements> <element name="mods:descriptionStandard" mandatory="false"> <recommendedContent> <value>aacr</value> </recommendedContent> </element> <element name="mods:recordContentSource" mandatory="false"> <expectedAttributes> <attribute name="authority" mandatory="false"> <expectedContent> <value>marcorg</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:recordCreationDate"> <expectedAttributes> <attribute name="encoding"> <expectedContent> <value>iso8601</value> </expectedContent> </attribute> </expectedAttributes> <expectedContent> <!--TODO: mozna regulernim vyrazem, resp. skupinou, protoze ten zapis muze byt dost ruzny - uz jenom oddelovace, viz. treba http://www.pelagodesign.com/blog/2009/05/20/iso-8601-date-validation-that-doesnt-suck/ --> </expectedContent> </element> <element name="mods:recordChangeDate" mandatory="false"> <expectedAttributes> <attribute name="encoding" mandatory="false"> <!--DMF jej vůbec neuvádí, což je "chyba ve specifikaci".--> <!--Proto je zde atribut nepovinný a hodnota jen doporučená, ne nutná.--> <recommendedContent> <value>iso8601</value> </recommendedContent> </attribute> </expectedAttributes> <expectedContent/> </element> <element name="mods:recordIdentifier" mandatory="false"> <expectedAttributes> <attribute name="source" mandatory="false"/> </expectedAttributes> <expectedContent/> </element> <element name="mods:recordOrigin" mandatory="false"> <recommendedContent> <oneOf> <value>machine generated</value> <value>human prepared</value> </oneOf> </recommendedContent> </element> <element name="mods:languageOfCataloging" mandatory="false"> <expectedElements> <element name="mods:languageTerm" mandatory="false"> <expectedAttributes> <attribute name="authority" mandatory="false"> <expectedContent> <!--nicmene DMF nevyzaduje, aby hodnota byla podle iso639-2b--> <value>iso639-2b</value> </expectedContent> </attribute> </expectedAttributes> </element> </expectedElements> </element> </expectedElements> </element> </expectedElements> </rootElement> </metadataProfile>
{'content_hash': 'eff6c13e2b3a55ab80d46918ae76c03e', 'timestamp': '', 'source': 'github', 'line_count': 612, 'max_line_length': 171, 'avg_line_length': 45.161764705882355, 'alnum_prop': 0.4190093708165997, 'repo_name': 'NLCR/komplexni-validator', 'id': '2ece823a705401986afc2419561e3cdb68ab4884', 'size': '27726', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sharedModule/src/main/resources/nkp/pspValidator/shared/validatorConfig/fDMF/monograph_1.3.2/biblioProfiles/mods/volume_multivolume_aacr2.xml', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '5811'}, {'name': 'Java', 'bytes': '990304'}, {'name': 'XSLT', 'bytes': '17921'}]}
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('react-dom')) : typeof define === 'function' && define.amd ? define(['react-dom'], factory) : (global.ReactDOMUnstableNativeDependencies = factory(global.ReactDOM)); }(this, (function (reactDom) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule reactProdInvariant * */ /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var validateFormat = function validateFormat(format) {}; { validateFormat = function validateFormat(format) { if (format === undefined) { throw new Error('invariant requires an error message argument'); } }; } function invariant(condition, format, a, b, c, d, e, f) { validateFormat(format); if (!condition) { var error; if (format === undefined) { error = new Error('Minified exception occurred; use the non-minified dev environment ' + 'for the full error message and additional helpful warnings.'); } else { var args = [a, b, c, d, e, f]; var argIndex = 0; error = new Error(format.replace(/%s/g, function () { return args[argIndex++]; })); error.name = 'Invariant Violation'; } error.framesToPop = 1; // we don't care about invariant's own frame throw error; } } var invariant_1 = invariant; var ReactErrorUtils = { // Used by Fiber to simulate a try-catch. _caughtError: null, _hasCaughtError: false, // Used by event system to capture/rethrow the first error. _rethrowError: null, _hasRethrowError: false, injection: { injectErrorUtils: function (injectedErrorUtils) { !(typeof injectedErrorUtils.invokeGuardedCallback === 'function') ? invariant_1(false, 'Injected invokeGuardedCallback() must be a function.') : void 0; invokeGuardedCallback = injectedErrorUtils.invokeGuardedCallback; } }, /** * Call a function while guarding against errors that happens within it. * Returns an error if it throws, otherwise null. * * In production, this is implemented using a try-catch. The reason we don't * use a try-catch directly is so that we can swap out a different * implementation in DEV mode. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ invokeGuardedCallback: function (name, func, context, a, b, c, d, e, f) { invokeGuardedCallback.apply(ReactErrorUtils, arguments); }, /** * Same as invokeGuardedCallback, but instead of returning an error, it stores * it in a global so it can be rethrown by `rethrowCaughtError` later. * TODO: See if _caughtError and _rethrowError can be unified. * * @param {String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} context The context to use when calling the function * @param {...*} args Arguments for function */ invokeGuardedCallbackAndCatchFirstError: function (name, func, context, a, b, c, d, e, f) { ReactErrorUtils.invokeGuardedCallback.apply(this, arguments); if (ReactErrorUtils.hasCaughtError()) { var error = ReactErrorUtils.clearCaughtError(); if (!ReactErrorUtils._hasRethrowError) { ReactErrorUtils._hasRethrowError = true; ReactErrorUtils._rethrowError = error; } } }, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { return rethrowCaughtError.apply(ReactErrorUtils, arguments); }, hasCaughtError: function () { return ReactErrorUtils._hasCaughtError; }, clearCaughtError: function () { if (ReactErrorUtils._hasCaughtError) { var error = ReactErrorUtils._caughtError; ReactErrorUtils._caughtError = null; ReactErrorUtils._hasCaughtError = false; return error; } else { invariant_1(false, 'clearCaughtError was called but no error was captured. This error is likely caused by a bug in React. Please file an issue.'); } } }; var invokeGuardedCallback = function (name, func, context, a, b, c, d, e, f) { ReactErrorUtils._hasCaughtError = false; ReactErrorUtils._caughtError = null; var funcArgs = Array.prototype.slice.call(arguments, 3); try { func.apply(context, funcArgs); } catch (error) { ReactErrorUtils._caughtError = error; ReactErrorUtils._hasCaughtError = true; } }; { // In DEV mode, we swap out invokeGuardedCallback for a special version // that plays more nicely with the browser's DevTools. The idea is to preserve // "Pause on exceptions" behavior. Because React wraps all user-provided // functions in invokeGuardedCallback, and the production version of // invokeGuardedCallback uses a try-catch, all user exceptions are treated // like caught exceptions, and the DevTools won't pause unless the developer // takes the extra step of enabling pause on caught exceptions. This is // untintuitive, though, because even though React has caught the error, from // the developer's perspective, the error is uncaught. // // To preserve the expected "Pause on exceptions" behavior, we don't use a // try-catch in DEV. Instead, we synchronously dispatch a fake event to a fake // DOM node, and call the user-provided callback from inside an event handler // for that fake event. If the callback throws, the error is "captured" using // a global event handler. But because the error happens in a different // event loop context, it does not interrupt the normal program flow. // Effectively, this gives us try-catch behavior without actually using // try-catch. Neat! // Check that the browser supports the APIs we need to implement our special // DEV version of invokeGuardedCallback if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); var invokeGuardedCallbackDev = function (name, func, context, a, b, c, d, e, f) { // Keeps track of whether the user-provided callback threw an error. We // set this to true at the beginning, then set it to false right after // calling the function. If the function errors, `didError` will never be // set to false. This strategy works even if the browser is flaky and // fails to call our global error handler, because it doesn't rely on // the error event at all. var didError = true; // Create an event handler for our fake event. We will synchronously // dispatch our fake event using `dispatchEvent`. Inside the handler, we // call the user-provided callback. var funcArgs = Array.prototype.slice.call(arguments, 3); function callCallback() { // We immediately remove the callback from event listeners so that // nested `invokeGuardedCallback` calls do not clash. Otherwise, a // nested call would trigger the fake event handlers of any call higher // in the stack. fakeNode.removeEventListener(evtType, callCallback, false); func.apply(context, funcArgs); didError = false; } // Create a global error event handler. We use this to capture the value // that was thrown. It's possible that this error handler will fire more // than once; for example, if non-React code also calls `dispatchEvent` // and a handler for that event throws. We should be resilient to most of // those cases. Even if our error event handler fires more than once, the // last error event is always used. If the callback actually does error, // we know that the last error event is the correct one, because it's not // possible for anything else to have happened in between our callback // erroring and the code that follows the `dispatchEvent` call below. If // the callback doesn't error, but the error event was fired, we know to // ignore it because `didError` will be false, as described above. var error = void 0; // Use this to track whether the error event is ever called. var didSetError = false; var isCrossOriginError = false; function onError(event) { error = event.error; didSetError = true; if (error === null && event.colno === 0 && event.lineno === 0) { isCrossOriginError = true; } } // Create a fake event type. var evtType = 'react-' + (name ? name : 'invokeguardedcallback'); // Attach our event handlers window.addEventListener('error', onError); fakeNode.addEventListener(evtType, callCallback, false); // Synchronously dispatch our fake event. If the user-provided function // errors, it will trigger our global error handler. var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); if (didError) { if (!didSetError) { // The callback errored, but the error event never fired. error = new Error('An error was thrown inside one of your components, but React ' + "doesn't know what it was. This is likely due to browser " + 'flakiness. React does its best to preserve the "Pause on ' + 'exceptions" behavior of the DevTools, which requires some ' + "DEV-mode only tricks. It's possible that these don't work in " + 'your browser. Try triggering the error in production mode, ' + 'or switching to a modern browser. If you suspect that this is ' + 'actually an issue with React, please file an issue.'); } else if (isCrossOriginError) { error = new Error("A cross-origin error was thrown. React doesn't have access to " + 'the actual error object in development. ' + 'See https://fb.me/react-crossorigin-error for more information.'); } ReactErrorUtils._hasCaughtError = true; ReactErrorUtils._caughtError = error; } else { ReactErrorUtils._hasCaughtError = false; ReactErrorUtils._caughtError = null; } // Remove our event listeners window.removeEventListener('error', onError); }; invokeGuardedCallback = invokeGuardedCallbackDev; } } var rethrowCaughtError = function () { if (ReactErrorUtils._hasRethrowError) { var error = ReactErrorUtils._rethrowError; ReactErrorUtils._rethrowError = null; ReactErrorUtils._hasRethrowError = false; throw error; } }; var ReactErrorUtils_1 = ReactErrorUtils; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ var emptyFunction = function emptyFunction() {}; emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; var emptyFunction_1 = emptyFunction; /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning$1 = emptyFunction_1; { var printWarning = function printWarning(format) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} }; warning$1 = function warning(condition, format) { if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { args[_key2 - 2] = arguments[_key2]; } printWarning.apply(undefined, [format].concat(args)); } }; } var warning_1 = warning$1; { var warning = warning_1; } /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; { warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.'); } } }; function isEndish(topLevelType) { return topLevelType === 'topMouseUp' || topLevelType === 'topTouchEnd' || topLevelType === 'topTouchCancel'; } function isMoveish(topLevelType) { return topLevelType === 'topMouseMove' || topLevelType === 'topTouchMove'; } function isStartish(topLevelType) { return topLevelType === 'topMouseDown' || topLevelType === 'topTouchStart'; } var validateEventDispatches; { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.'); }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); ReactErrorUtils_1.invokeGuardedCallbackAndCatchFirstError(type, listener, undefined, event); event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? invariant_1(false, 'executeDirectDispatch(...): Invalid `event`.') : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getFiberCurrentPropsFromNode: function (node) { return ComponentTree.getFiberCurrentPropsFromNode(node); }, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, injection: injection }; var EventPluginUtils_1 = EventPluginUtils; /** * Injectable ordering of event plugins. */ var eventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!eventPluginOrder) { // Wait until an `eventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var pluginModule = namesToPlugins[pluginName]; var pluginIndex = eventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? invariant_1(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in the plugin ordering, `%s`.', pluginName) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !pluginModule.extractEvents ? invariant_1(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` method, but `%s` does not.', pluginName) : void 0; EventPluginRegistry.plugins[pluginIndex] = pluginModule; var publishedEvents = pluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], pluginModule, eventName) ? invariant_1(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, pluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? invariant_1(false, 'EventPluginHub: More than one plugin attempted to publish the same event name, `%s`.', eventName) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, pluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, pluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, pluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? invariant_1(false, 'EventPluginHub: More than one plugin attempted to publish the same registration name, `%s`.', registrationName) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = pluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = pluginModule.eventTypes[eventName].dependencies; { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === 'onDoubleClick') { EventPluginRegistry.possibleRegistrationNames.ondblclick = registrationName; } } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in true. * @type {Object} */ possibleRegistrationNames: {}, // Trust the developer to only use possibleRegistrationNames in true /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (injectedEventPluginOrder) { !!eventPluginOrder ? invariant_1(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than once. You are likely trying to load more than one copy of React.') : void 0; // Clone the ordering so it cannot be dynamically mutated. eventPluginOrder = Array.prototype.slice.call(injectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var pluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== pluginModule) { !!namesToPlugins[pluginName] ? invariant_1(false, 'EventPluginRegistry: Cannot inject two different event plugins using the same name, `%s`.', pluginName) : void 0; namesToPlugins[pluginName] = pluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } } }; var EventPluginRegistry_1 = EventPluginRegistry; /** * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? invariant_1(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { if (Array.isArray(next)) { current.push.apply(current, next); return current; } current.push(next); return current; } if (Array.isArray(next)) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } var accumulateInto_1 = accumulateInto; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated * */ /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). * @param {function} cb Callback invoked with each element or a collection. * @param {?} [scope] Scope used as `this` in a callback. */ function forEachAccumulated(arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } } var forEachAccumulated_1 = forEachAccumulated; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils_1.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; function isInteractive(tag) { return tag === 'button' || tag === 'input' || tag === 'select' || tag === 'textarea'; } function shouldPreventMouseEvent(name, type, props) { switch (name) { case 'onClick': case 'onClickCapture': case 'onDoubleClick': case 'onDoubleClickCapture': case 'onMouseDown': case 'onMouseDownCapture': case 'onMouseMove': case 'onMouseMoveCapture': case 'onMouseUp': case 'onMouseUpCapture': return !!(props.disabled && isInteractive(type)); default: return false; } } /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry_1.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry_1.injectEventPluginsByName }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { var listener; // TODO: shouldPreventMouseEvent is DOM-specific and definitely should not // live here; needs to be moved to a better place soon if (typeof inst.tag === 'number') { var stateNode = inst.stateNode; if (!stateNode) { // Work in progress (ex: onload events in incremental mode). return null; } var props = EventPluginUtils_1.getFiberCurrentPropsFromNode(stateNode); if (!props) { // Work in progress. return null; } listener = props[registrationName]; if (shouldPreventMouseEvent(registrationName, inst.type, props)) { return null; } } else { var currentElement = inst._currentElement; if (typeof currentElement === 'string' || typeof currentElement === 'number') { // Text node, let it bubble through. return null; } if (!inst._rootNodeID) { // If the instance is already unmounted, we have no listeners. return null; } var _props = currentElement.props; listener = _props[registrationName]; if (shouldPreventMouseEvent(registrationName, currentElement.type, _props)) { return null; } } !(!listener || typeof listener === 'function') ? invariant_1(false, 'Expected `%s` listener to be a function, instead got a value of `%s` type.', registrationName, typeof listener) : void 0; return listener; }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry_1.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto_1(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto_1(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated_1(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? invariant_1(false, 'processEventQueue(): Additional events were enqueued while processing an event queue. Support for this has not yet been implemented.') : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils_1.rethrowCaughtError(); } }; var EventPluginHub_1 = EventPluginHub; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactTypeOfWork * */ var ReactTypeOfWork = { IndeterminateComponent: 0, // Before we know whether it is functional or class FunctionalComponent: 1, ClassComponent: 2, HostRoot: 3, // Root of a host tree. Could be nested inside another node. HostPortal: 4, // A subtree. Could be an entry point to a different renderer. HostComponent: 5, HostText: 6, CoroutineComponent: 7, CoroutineHandlerPhase: 8, YieldComponent: 9, Fragment: 10 }; var HostComponent = ReactTypeOfWork.HostComponent; function getParent(inst) { if (inst._hostParent !== undefined) { return inst._hostParent; } if (typeof inst.tag === 'number') { do { inst = inst['return']; // TODO: If this is a HostRoot we might want to bail out. // That is depending on if we want nested subtrees (layers) to bubble // events to their parent. We could also go through parentNode on the // host node but that wouldn't work for React Native and doesn't let us // do the portal feature. } while (inst && inst.tag !== HostComponent); if (inst) { return inst; } } return null; } /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { var depthA = 0; for (var tempA = instA; tempA; tempA = getParent(tempA)) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = getParent(tempB)) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = getParent(instA); depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = getParent(instB); depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB || instA === instB.alternate) { return instA; } instA = getParent(instA); instB = getParent(instB); } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { while (instB) { if (instA === instB || instA === instB.alternate) { return true; } instB = getParent(instB); } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { return getParent(inst); } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = getParent(inst); } var i; for (i = path.length; i-- > 0;) { fn(path[i], 'captured', arg); } for (i = 0; i < path.length; i++) { fn(path[i], 'bubbled', arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = getParent(from); } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = getParent(to); } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], 'bubbled', argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], 'captured', argTo); } } var ReactTreeTraversal = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; var getListener = EventPluginHub_1.getListener; { var warning$2 = warning_1; } /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, phase, event) { { warning$2(inst, 'Dispatching inst must not be null'); } var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { ReactTreeTraversal.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? ReactTreeTraversal.getParentInstance(targetInst) : null; ReactTreeTraversal.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (inst && event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto_1(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto_1(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated_1(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { ReactTreeTraversal.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated_1(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing even a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; var EventPropagators_1 = EventPropagators; /* object-assign (c) Sindre Sorhus @license MIT */ /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } var index = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var EVENT_POOL_SIZE = 10; { var warning$3 = warning_1; } var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction_1.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction_1.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction_1.thatReturnsFalse; } this.isPropagationStopped = emptyFunction_1.thatReturnsFalse; return this; } index(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else if (typeof event.returnValue !== 'unknown') { event.returnValue = false; } this.isDefaultPrevented = emptyFunction_1.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else if (typeof event.cancelBubble !== 'unknown') { // The ChangeEventPlugin registers a "propertychange" event for // IE. This event does not support bubbling or cancelling, and // any references to cancelBubble throw "Member not found". A // typeof check of "unknown" circumvents this issue (and is also // IE specific). event.cancelBubble = true; } this.isPropagationStopped = emptyFunction_1.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction_1.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction_1.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } { Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', emptyFunction_1)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', emptyFunction_1)); } } }); SyntheticEvent.Interface = EventInterface; /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); index(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = index({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; addEventPoolingTo(Class); }; /** Proxying after everything set on SyntheticEvent * to resolve Proxy issue on some WebKit browsers * in which some Event properties are set to undefined (GH#10010) */ { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { warning$3(didWarnForAddedNewProperty || target.isPersistent(), "This synthetic event is reused for performance reasons. If you're " + "seeing this, you're adding a new property in the synthetic event object. " + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.'); didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } addEventPoolingTo(SyntheticEvent); var SyntheticEvent_1 = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {String} propName * @param {?object} getVal * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; warning$3(warningCondition, "This synthetic event is reused for performance reasons. If you're seeing this, " + "you're %s `%s` on a released/nullified synthetic event. %s. " + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result); } } function getPooledEvent(dispatchConfig, targetInst, nativeEvent, nativeInst) { var EventConstructor = this; if (EventConstructor.eventPool.length) { var instance = EventConstructor.eventPool.pop(); EventConstructor.call(instance, dispatchConfig, targetInst, nativeEvent, nativeInst); return instance; } return new EventConstructor(dispatchConfig, targetInst, nativeEvent, nativeInst); } function releasePooledEvent(event) { var EventConstructor = this; !(event instanceof EventConstructor) ? invariant_1(false, 'Trying to release an event instance into a pool of a different type.') : void 0; event.destructor(); if (EventConstructor.eventPool.length < EVENT_POOL_SIZE) { EventConstructor.eventPool.push(event); } } function addEventPoolingTo(EventConstructor) { EventConstructor.eventPool = []; EventConstructor.getPooled = getPooledEvent; EventConstructor.release = releasePooledEvent; } /** * `touchHistory` isn't actually on the native event, but putting it in the * interface will ensure that it is cleaned up when pooled/destroyed. The * `ResponderEventPlugin` will populate it appropriately. */ var ResponderEventInterface = { touchHistory: function (nativeEvent) { return null; // Actually doesn't even look at the native event. } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native event. * @extends {SyntheticEvent} */ function ResponderSyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent_1.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent_1.augmentClass(ResponderSyntheticEvent, ResponderEventInterface); var ResponderSyntheticEvent_1 = ResponderSyntheticEvent; var isEndish$2 = EventPluginUtils_1.isEndish; var isMoveish$2 = EventPluginUtils_1.isMoveish; var isStartish$2 = EventPluginUtils_1.isStartish; { var warning$4 = warning_1; } /** * Tracks the position and time of each active touch by `touch.identifier`. We * should typically only see IDs in the range of 1-20 because IDs get recycled * when touches end and start again. */ var MAX_TOUCH_BANK = 20; var touchBank = []; var touchHistory = { touchBank: touchBank, numberActiveTouches: 0, // If there is only one active touch, we remember its location. This prevents // us having to loop through all of the touches all the time in the most // common case. indexOfSingleActiveTouch: -1, mostRecentTimeStamp: 0 }; function timestampForTouch(touch) { // The legacy internal implementation provides "timeStamp", which has been // renamed to "timestamp". Let both work for now while we iron it out // TODO (evv): rename timeStamp to timestamp in internal code return touch.timeStamp || touch.timestamp; } /** * TODO: Instead of making gestures recompute filtered velocity, we could * include a built in velocity computation that can be reused globally. */ function createTouchRecord(touch) { return { touchActive: true, startPageX: touch.pageX, startPageY: touch.pageY, startTimeStamp: timestampForTouch(touch), currentPageX: touch.pageX, currentPageY: touch.pageY, currentTimeStamp: timestampForTouch(touch), previousPageX: touch.pageX, previousPageY: touch.pageY, previousTimeStamp: timestampForTouch(touch) }; } function resetTouchRecord(touchRecord, touch) { touchRecord.touchActive = true; touchRecord.startPageX = touch.pageX; touchRecord.startPageY = touch.pageY; touchRecord.startTimeStamp = timestampForTouch(touch); touchRecord.currentPageX = touch.pageX; touchRecord.currentPageY = touch.pageY; touchRecord.currentTimeStamp = timestampForTouch(touch); touchRecord.previousPageX = touch.pageX; touchRecord.previousPageY = touch.pageY; touchRecord.previousTimeStamp = timestampForTouch(touch); } function getTouchIdentifier(_ref) { var identifier = _ref.identifier; !(identifier != null) ? invariant_1(false, 'Touch object is missing identifier.') : void 0; { warning$4(identifier <= MAX_TOUCH_BANK, 'Touch identifier %s is greater than maximum supported %s which causes ' + 'performance issues backfilling array locations for all of the indices.', identifier, MAX_TOUCH_BANK); } return identifier; } function recordTouchStart(touch) { var identifier = getTouchIdentifier(touch); var touchRecord = touchBank[identifier]; if (touchRecord) { resetTouchRecord(touchRecord, touch); } else { touchBank[identifier] = createTouchRecord(touch); } touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } function recordTouchMove(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; if (touchRecord) { touchRecord.touchActive = true; touchRecord.previousPageX = touchRecord.currentPageX; touchRecord.previousPageY = touchRecord.currentPageY; touchRecord.previousTimeStamp = touchRecord.currentTimeStamp; touchRecord.currentPageX = touch.pageX; touchRecord.currentPageY = touch.pageY; touchRecord.currentTimeStamp = timestampForTouch(touch); touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } else { console.error('Cannot record touch move without a touch start.\n' + 'Touch Move: %s\n', 'Touch Bank: %s', printTouch(touch), printTouchBank()); } } function recordTouchEnd(touch) { var touchRecord = touchBank[getTouchIdentifier(touch)]; if (touchRecord) { touchRecord.touchActive = false; touchRecord.previousPageX = touchRecord.currentPageX; touchRecord.previousPageY = touchRecord.currentPageY; touchRecord.previousTimeStamp = touchRecord.currentTimeStamp; touchRecord.currentPageX = touch.pageX; touchRecord.currentPageY = touch.pageY; touchRecord.currentTimeStamp = timestampForTouch(touch); touchHistory.mostRecentTimeStamp = timestampForTouch(touch); } else { console.error('Cannot record touch end without a touch start.\n' + 'Touch End: %s\n', 'Touch Bank: %s', printTouch(touch), printTouchBank()); } } function printTouch(touch) { return JSON.stringify({ identifier: touch.identifier, pageX: touch.pageX, pageY: touch.pageY, timestamp: timestampForTouch(touch) }); } function printTouchBank() { var printed = JSON.stringify(touchBank.slice(0, MAX_TOUCH_BANK)); if (touchBank.length > MAX_TOUCH_BANK) { printed += ' (original size: ' + touchBank.length + ')'; } return printed; } var ResponderTouchHistoryStore = { recordTouchTrack: function (topLevelType, nativeEvent) { if (isMoveish$2(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchMove); } else if (isStartish$2(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchStart); touchHistory.numberActiveTouches = nativeEvent.touches.length; if (touchHistory.numberActiveTouches === 1) { touchHistory.indexOfSingleActiveTouch = nativeEvent.touches[0].identifier; } } else if (isEndish$2(topLevelType)) { nativeEvent.changedTouches.forEach(recordTouchEnd); touchHistory.numberActiveTouches = nativeEvent.touches.length; if (touchHistory.numberActiveTouches === 1) { for (var i = 0; i < touchBank.length; i++) { var touchTrackToCheck = touchBank[i]; if (touchTrackToCheck != null && touchTrackToCheck.touchActive) { touchHistory.indexOfSingleActiveTouch = i; break; } } { var activeRecord = touchBank[touchHistory.indexOfSingleActiveTouch]; warning$4(activeRecord != null && activeRecord.touchActive, 'Cannot find single active touch.'); } } } }, touchHistory: touchHistory }; var ResponderTouchHistoryStore_1 = ResponderTouchHistoryStore; /** * Accumulates items that must not be null or undefined. * * This is used to conserve memory by avoiding array allocations. * * @return {*|array<*>} An accumulation of items. */ function accumulate(current, next) { !(next != null) ? invariant_1(false, 'accumulate(...): Accumulated items must be not be null or undefined.') : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). if (Array.isArray(current)) { return current.concat(next); } if (Array.isArray(next)) { return [current].concat(next); } return [current, next]; } var accumulate_1 = accumulate; var isStartish$1 = EventPluginUtils_1.isStartish; var isMoveish$1 = EventPluginUtils_1.isMoveish; var isEndish$1 = EventPluginUtils_1.isEndish; var executeDirectDispatch$1 = EventPluginUtils_1.executeDirectDispatch; var hasDispatches$1 = EventPluginUtils_1.hasDispatches; var executeDispatchesInOrderStopAtTrue$1 = EventPluginUtils_1.executeDispatchesInOrderStopAtTrue; /** * Instance of element that should respond to touch/move types of interactions, * as indicated explicitly by relevant callbacks. */ var responderInst = null; /** * Count of current touches. A textInput should become responder iff the * selection changes while there is a touch on the screen. */ var trackedTouchCount = 0; /** * Last reported number of active touches. */ var previousActiveTouches = 0; var changeResponder = function (nextResponderInst, blockHostResponder) { var oldResponderInst = responderInst; responderInst = nextResponderInst; if (ResponderEventPlugin.GlobalResponderHandler !== null) { ResponderEventPlugin.GlobalResponderHandler.onChange(oldResponderInst, nextResponderInst, blockHostResponder); } }; var eventTypes = { /** * On a `touchStart`/`mouseDown`, is it desired that this element become the * responder? */ startShouldSetResponder: { phasedRegistrationNames: { bubbled: 'onStartShouldSetResponder', captured: 'onStartShouldSetResponderCapture' } }, /** * On a `scroll`, is it desired that this element become the responder? This * is usually not needed, but should be used to retroactively infer that a * `touchStart` had occurred during momentum scroll. During a momentum scroll, * a touch start will be immediately followed by a scroll event if the view is * currently scrolling. * * TODO: This shouldn't bubble. */ scrollShouldSetResponder: { phasedRegistrationNames: { bubbled: 'onScrollShouldSetResponder', captured: 'onScrollShouldSetResponderCapture' } }, /** * On text selection change, should this element become the responder? This * is needed for text inputs or other views with native selection, so the * JS view can claim the responder. * * TODO: This shouldn't bubble. */ selectionChangeShouldSetResponder: { phasedRegistrationNames: { bubbled: 'onSelectionChangeShouldSetResponder', captured: 'onSelectionChangeShouldSetResponderCapture' } }, /** * On a `touchMove`/`mouseMove`, is it desired that this element become the * responder? */ moveShouldSetResponder: { phasedRegistrationNames: { bubbled: 'onMoveShouldSetResponder', captured: 'onMoveShouldSetResponderCapture' } }, /** * Direct responder events dispatched directly to responder. Do not bubble. */ responderStart: { registrationName: 'onResponderStart' }, responderMove: { registrationName: 'onResponderMove' }, responderEnd: { registrationName: 'onResponderEnd' }, responderRelease: { registrationName: 'onResponderRelease' }, responderTerminationRequest: { registrationName: 'onResponderTerminationRequest' }, responderGrant: { registrationName: 'onResponderGrant' }, responderReject: { registrationName: 'onResponderReject' }, responderTerminate: { registrationName: 'onResponderTerminate' } }; /** * * Responder System: * ---------------- * * - A global, solitary "interaction lock" on a view. * - If a node becomes the responder, it should convey visual feedback * immediately to indicate so, either by highlighting or moving accordingly. * - To be the responder means, that touches are exclusively important to that * responder view, and no other view. * - While touches are still occurring, the responder lock can be transferred to * a new view, but only to increasingly "higher" views (meaning ancestors of * the current responder). * * Responder being granted: * ------------------------ * * - Touch starts, moves, and scrolls can cause an ID to become the responder. * - We capture/bubble `startShouldSetResponder`/`moveShouldSetResponder` to * the "appropriate place". * - If nothing is currently the responder, the "appropriate place" is the * initiating event's `targetID`. * - If something *is* already the responder, the "appropriate place" is the * first common ancestor of the event target and the current `responderInst`. * - Some negotiation happens: See the timing diagram below. * - Scrolled views automatically become responder. The reasoning is that a * platform scroll view that isn't built on top of the responder system has * began scrolling, and the active responder must now be notified that the * interaction is no longer locked to it - the system has taken over. * * - Responder being released: * As soon as no more touches that *started* inside of descendants of the * *current* responderInst, an `onResponderRelease` event is dispatched to the * current responder, and the responder lock is released. * * TODO: * - on "end", a callback hook for `onResponderEndShouldRemainResponder` that * determines if the responder lock should remain. * - If a view shouldn't "remain" the responder, any active touches should by * default be considered "dead" and do not influence future negotiations or * bubble paths. It should be as if those touches do not exist. * -- For multitouch: Usually a translate-z will choose to "remain" responder * after one out of many touches ended. For translate-y, usually the view * doesn't wish to "remain" responder after one of many touches end. * - Consider building this on top of a `stopPropagation` model similar to * `W3C` events. * - Ensure that `onResponderTerminate` is called on touch cancels, whether or * not `onResponderTerminationRequest` returns `true` or `false`. * */ /* Negotiation Performed +-----------------------+ / \ Process low level events to + Current Responder + wantsResponderID determine who to perform negot-| (if any exists at all) | iation/transition | Otherwise just pass through| -------------------------------+----------------------------+------------------+ Bubble to find first ID | | to return true:wantsResponderID| | | | +-------------+ | | | onTouchStart| | | +------+------+ none | | | return| | +-----------v-------------+true| +------------------------+ | |onStartShouldSetResponder|----->|onResponderStart (cur) |<-----------+ +-----------+-------------+ | +------------------------+ | | | | | +--------+-------+ | returned true for| false:REJECT +-------->|onResponderReject | wantsResponderID | | | +----------------+ | (now attempt | +------------------+-----+ | | handoff) | | onResponder | | +------------------->| TerminationRequest| | | +------------------+-----+ | | | | +----------------+ | true:GRANT +-------->|onResponderGrant| | | +--------+-------+ | +------------------------+ | | | | onResponderTerminate |<-----------+ | +------------------+-----+ | | | | +----------------+ | +-------->|onResponderStart| | | +----------------+ Bubble to find first ID | | to return true:wantsResponderID| | | | +-------------+ | | | onTouchMove | | | +------+------+ none | | | return| | +-----------v-------------+true| +------------------------+ | |onMoveShouldSetResponder |----->|onResponderMove (cur) |<-----------+ +-----------+-------------+ | +------------------------+ | | | | | +--------+-------+ | returned true for| false:REJECT +-------->|onResponderRejec| | wantsResponderID | | | +----------------+ | (now attempt | +------------------+-----+ | | handoff) | | onResponder | | +------------------->| TerminationRequest| | | +------------------+-----+ | | | | +----------------+ | true:GRANT +-------->|onResponderGrant| | | +--------+-------+ | +------------------------+ | | | | onResponderTerminate |<-----------+ | +------------------+-----+ | | | | +----------------+ | +-------->|onResponderMove | | | +----------------+ | | | | Some active touch started| | inside current responder | +------------------------+ | +------------------------->| onResponderEnd | | | | +------------------------+ | +---+---------+ | | | onTouchEnd | | | +---+---------+ | | | | +------------------------+ | +------------------------->| onResponderEnd | | No active touches started| +-----------+------------+ | inside current responder | | | | v | | +------------------------+ | | | onResponderRelease | | | +------------------------+ | | | + + */ /** * A note about event ordering in the `EventPluginHub`. * * Suppose plugins are injected in the following order: * * `[R, S, C]` * * To help illustrate the example, assume `S` is `SimpleEventPlugin` (for * `onClick` etc) and `R` is `ResponderEventPlugin`. * * "Deferred-Dispatched Events": * * - The current event plugin system will traverse the list of injected plugins, * in order, and extract events by collecting the plugin's return value of * `extractEvents()`. * - These events that are returned from `extractEvents` are "deferred * dispatched events". * - When returned from `extractEvents`, deferred-dispatched events contain an * "accumulation" of deferred dispatches. * - These deferred dispatches are accumulated/collected before they are * returned, but processed at a later time by the `EventPluginHub` (hence the * name deferred). * * In the process of returning their deferred-dispatched events, event plugins * themselves can dispatch events on-demand without returning them from * `extractEvents`. Plugins might want to do this, so that they can use event * dispatching as a tool that helps them decide which events should be extracted * in the first place. * * "On-Demand-Dispatched Events": * * - On-demand-dispatched events are not returned from `extractEvents`. * - On-demand-dispatched events are dispatched during the process of returning * the deferred-dispatched events. * - They should not have side effects. * - They should be avoided, and/or eventually be replaced with another * abstraction that allows event plugins to perform multiple "rounds" of event * extraction. * * Therefore, the sequence of event dispatches becomes: * * - `R`s on-demand events (if any) (dispatched by `R` on-demand) * - `S`s on-demand events (if any) (dispatched by `S` on-demand) * - `C`s on-demand events (if any) (dispatched by `C` on-demand) * - `R`s extracted events (if any) (dispatched by `EventPluginHub`) * - `S`s extracted events (if any) (dispatched by `EventPluginHub`) * - `C`s extracted events (if any) (dispatched by `EventPluginHub`) * * In the case of `ResponderEventPlugin`: If the `startShouldSetResponder` * on-demand dispatch returns `true` (and some other details are satisfied) the * `onResponderGrant` deferred dispatched event is returned from * `extractEvents`. The sequence of dispatch executions in this case * will appear as follows: * * - `startShouldSetResponder` (`ResponderEventPlugin` dispatches on-demand) * - `touchStartCapture` (`EventPluginHub` dispatches as usual) * - `touchStart` (`EventPluginHub` dispatches as usual) * - `responderGrant/Reject` (`EventPluginHub` dispatches as usual) */ function setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var shouldSetEventType = isStartish$1(topLevelType) ? eventTypes.startShouldSetResponder : isMoveish$1(topLevelType) ? eventTypes.moveShouldSetResponder : topLevelType === 'topSelectionChange' ? eventTypes.selectionChangeShouldSetResponder : eventTypes.scrollShouldSetResponder; // TODO: stop one short of the current responder. var bubbleShouldSetFrom = !responderInst ? targetInst : ReactTreeTraversal.getLowestCommonAncestor(responderInst, targetInst); // When capturing/bubbling the "shouldSet" event, we want to skip the target // (deepest ID) if it happens to be the current responder. The reasoning: // It's strange to get an `onMoveShouldSetResponder` when you're *already* // the responder. var skipOverBubbleShouldSetFrom = bubbleShouldSetFrom === responderInst; var shouldSetEvent = ResponderSyntheticEvent_1.getPooled(shouldSetEventType, bubbleShouldSetFrom, nativeEvent, nativeEventTarget); shouldSetEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory; if (skipOverBubbleShouldSetFrom) { EventPropagators_1.accumulateTwoPhaseDispatchesSkipTarget(shouldSetEvent); } else { EventPropagators_1.accumulateTwoPhaseDispatches(shouldSetEvent); } var wantsResponderInst = executeDispatchesInOrderStopAtTrue$1(shouldSetEvent); if (!shouldSetEvent.isPersistent()) { shouldSetEvent.constructor.release(shouldSetEvent); } if (!wantsResponderInst || wantsResponderInst === responderInst) { return null; } var extracted; var grantEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderGrant, wantsResponderInst, nativeEvent, nativeEventTarget); grantEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory; EventPropagators_1.accumulateDirectDispatches(grantEvent); var blockHostResponder = executeDirectDispatch$1(grantEvent) === true; if (responderInst) { var terminationRequestEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminationRequest, responderInst, nativeEvent, nativeEventTarget); terminationRequestEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory; EventPropagators_1.accumulateDirectDispatches(terminationRequestEvent); var shouldSwitch = !hasDispatches$1(terminationRequestEvent) || executeDirectDispatch$1(terminationRequestEvent); if (!terminationRequestEvent.isPersistent()) { terminationRequestEvent.constructor.release(terminationRequestEvent); } if (shouldSwitch) { var terminateEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderTerminate, responderInst, nativeEvent, nativeEventTarget); terminateEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory; EventPropagators_1.accumulateDirectDispatches(terminateEvent); extracted = accumulate_1(extracted, [grantEvent, terminateEvent]); changeResponder(wantsResponderInst, blockHostResponder); } else { var rejectEvent = ResponderSyntheticEvent_1.getPooled(eventTypes.responderReject, wantsResponderInst, nativeEvent, nativeEventTarget); rejectEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory; EventPropagators_1.accumulateDirectDispatches(rejectEvent); extracted = accumulate_1(extracted, rejectEvent); } } else { extracted = accumulate_1(extracted, grantEvent); changeResponder(wantsResponderInst, blockHostResponder); } return extracted; } /** * A transfer is a negotiation between a currently set responder and the next * element to claim responder status. Any start event could trigger a transfer * of responderInst. Any move event could trigger a transfer. * * @param {string} topLevelType Record from `BrowserEventConstants`. * @return {boolean} True if a transfer of responder could possibly occur. */ function canTriggerTransfer(topLevelType, topLevelInst, nativeEvent) { return topLevelInst && ( // responderIgnoreScroll: We are trying to migrate away from specifically // tracking native scroll events here and responderIgnoreScroll indicates we // will send topTouchCancel to handle canceling touch events instead topLevelType === 'topScroll' && !nativeEvent.responderIgnoreScroll || trackedTouchCount > 0 && topLevelType === 'topSelectionChange' || isStartish$1(topLevelType) || isMoveish$1(topLevelType)); } /** * Returns whether or not this touch end event makes it such that there are no * longer any touches that started inside of the current `responderInst`. * * @param {NativeEvent} nativeEvent Native touch end event. * @return {boolean} Whether or not this touch end event ends the responder. */ function noResponderTouches(nativeEvent) { var touches = nativeEvent.touches; if (!touches || touches.length === 0) { return true; } for (var i = 0; i < touches.length; i++) { var activeTouch = touches[i]; var target = activeTouch.target; if (target !== null && target !== undefined && target !== 0) { // Is the original touch location inside of the current responder? var targetInst = EventPluginUtils_1.getInstanceFromNode(target); if (ReactTreeTraversal.isAncestor(responderInst, targetInst)) { return false; } } } return true; } var ResponderEventPlugin = { /* For unit testing only */ _getResponder: function () { return responderInst; }, eventTypes: eventTypes, /** * We must be resilient to `targetInst` being `null` on `touchMove` or * `touchEnd`. On certain platforms, this means that a native scroll has * assumed control and the original touch targets are destroyed. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (isStartish$1(topLevelType)) { trackedTouchCount += 1; } else if (isEndish$1(topLevelType)) { if (trackedTouchCount >= 0) { trackedTouchCount -= 1; } else { console.error('Ended a touch event which was not counted in `trackedTouchCount`.'); return null; } } ResponderTouchHistoryStore_1.recordTouchTrack(topLevelType, nativeEvent); var extracted = canTriggerTransfer(topLevelType, targetInst, nativeEvent) ? setResponderAndExtractTransfer(topLevelType, targetInst, nativeEvent, nativeEventTarget) : null; // Responder may or may not have transferred on a new touch start/move. // Regardless, whoever is the responder after any potential transfer, we // direct all touch start/move/ends to them in the form of // `onResponderMove/Start/End`. These will be called for *every* additional // finger that move/start/end, dispatched directly to whoever is the // current responder at that moment, until the responder is "released". // // These multiple individual change touch events are are always bookended // by `onResponderGrant`, and one of // (`onResponderRelease/onResponderTerminate`). var isResponderTouchStart = responderInst && isStartish$1(topLevelType); var isResponderTouchMove = responderInst && isMoveish$1(topLevelType); var isResponderTouchEnd = responderInst && isEndish$1(topLevelType); var incrementalTouch = isResponderTouchStart ? eventTypes.responderStart : isResponderTouchMove ? eventTypes.responderMove : isResponderTouchEnd ? eventTypes.responderEnd : null; if (incrementalTouch) { var gesture = ResponderSyntheticEvent_1.getPooled(incrementalTouch, responderInst, nativeEvent, nativeEventTarget); gesture.touchHistory = ResponderTouchHistoryStore_1.touchHistory; EventPropagators_1.accumulateDirectDispatches(gesture); extracted = accumulate_1(extracted, gesture); } var isResponderTerminate = responderInst && topLevelType === 'topTouchCancel'; var isResponderRelease = responderInst && !isResponderTerminate && isEndish$1(topLevelType) && noResponderTouches(nativeEvent); var finalTouch = isResponderTerminate ? eventTypes.responderTerminate : isResponderRelease ? eventTypes.responderRelease : null; if (finalTouch) { var finalEvent = ResponderSyntheticEvent_1.getPooled(finalTouch, responderInst, nativeEvent, nativeEventTarget); finalEvent.touchHistory = ResponderTouchHistoryStore_1.touchHistory; EventPropagators_1.accumulateDirectDispatches(finalEvent); extracted = accumulate_1(extracted, finalEvent); changeResponder(null); } var numberActiveTouches = ResponderTouchHistoryStore_1.touchHistory.numberActiveTouches; if (ResponderEventPlugin.GlobalInteractionHandler && numberActiveTouches !== previousActiveTouches) { ResponderEventPlugin.GlobalInteractionHandler.onChange(numberActiveTouches); } previousActiveTouches = numberActiveTouches; return extracted; }, GlobalResponderHandler: null, GlobalInteractionHandler: null, injection: { /** * @param {{onChange: (ReactID, ReactID) => void} GlobalResponderHandler * Object that handles any change in responder. Use this to inject * integration with an existing touch handling system etc. */ injectGlobalResponderHandler: function (GlobalResponderHandler) { ResponderEventPlugin.GlobalResponderHandler = GlobalResponderHandler; }, /** * @param {{onChange: (numberActiveTouches) => void} GlobalInteractionHandler * Object that handles any change in the number of active touches. */ injectGlobalInteractionHandler: function (GlobalInteractionHandler) { ResponderEventPlugin.GlobalInteractionHandler = GlobalInteractionHandler; } } }; var ResponderEventPlugin_1 = ResponderEventPlugin; /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMUnstableNativeDependenciesEntry */ var ReactDOMUnstableNativeDependencies = { injectComponentTree: EventPluginUtils_1.injection.injectComponentTree, ResponderEventPlugin: ResponderEventPlugin_1, ResponderTouchHistoryStore: ResponderTouchHistoryStore_1 }; // Inject react-dom's ComponentTree into this module. var ReactDOMComponentTree = reactDom.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactDOMComponentTree; ReactDOMUnstableNativeDependencies.injectComponentTree(ReactDOMComponentTree); var ReactDOMUnstableNativeDependenciesEntry = ReactDOMUnstableNativeDependencies; return ReactDOMUnstableNativeDependenciesEntry; })));
{'content_hash': '425a80924c75805407911acdab55e219', 'timestamp': '', 'source': 'github', 'line_count': 2385, 'max_line_length': 532, 'avg_line_length': 36.7916142557652, 'alnum_prop': 0.6816451657017824, 'repo_name': 'extend1994/cdnjs', 'id': '415b1201031aadbe615287a02ce8026cf672bec5', 'size': '88140', 'binary': False, 'copies': '18', 'ref': 'refs/heads/master', 'path': 'ajax/libs/react-dom/16.0.0-rc.3/umd/react-dom-unstable-native-dependencies.development.js', 'mode': '33188', 'license': 'mit', 'language': []}
var Proto = require("./Proto"); var Observation = require("./Observation"); var Notification = require("./Notification"); var Observable = Proto.clone().newSlots({ type: "ideal.Observable", observations: [], observedSlots: [] }).setSlots({ init: function() { this.setObservations([]); //this.initObservedSlots(); }, initObservedSlots: function() { var self = this; this.observedSlots().forEach(function(slotName){ self.initObservedSlot(slotName); }); }, initObservedSlot: function(slotName) { var self = this; var v = self.perform(slotName); this.perform("set" + slotName.capitalized(), Object.perform(v, "clone")); this.mySlotChanged(slotName, v, v); }, observedSlots: function() { if (!this.ownsSlot("_observedSlots")) { this.setObservedSlots(this._observedSlots.copy()); } return this._observedSlots; }, mySlotChanged: function(slotName, oldValue, newValue) { Proto.mySlotChanged.apply(this, arguments); if (this.observedSlots().contains(slotName)) { this.sendNotification("slotChanged", Proto.clone().newSlots({ slotName: slotName, oldValue: oldValue, newValue: newValue })); var prefix = "child"; Object.perform(oldValue, "removeObserverWithPrefix", this, prefix); var observation = Object.perform(newValue, "addObserver", this); Object.perform(observation, "newSlot", "parentSlotName", slotName); Object.perform(observation, "setPrefix", prefix); } }, childSlotChanged: function(msg) { var slotName = msg.observation().parentSlotName(); var value = this.perform(slotName); this.mySlotChanged(slotName, value, value); }, addObserver: function(observer) //returns an observation not self { var observation = Observation.clone().setObserved(this).setObserver(observer).setPrefix(this.type().split(".").last().uncapitalized()); this.observations().append(observation); return observation; }, removeObserver: function(observer) { this.setObservations(this.observations().filter(function(observation){ return observation.observer() != observer; })); return this; }, removeObserverWithPrefix: function(observer, prefix) { this.setObservations(this.observations().filter(function(observation){ return((observation.observer() != observer) || (observation.prefix() != prefix)); })); return this; }, removeAllObservers: function() { this.observations().empty(); return this; }, newNotification: function(name) { return Notification.clone().setName(name).setSender(this); }, sendNotification: function(name, data) { this.newNotification(name).setData(data || null).send(); return this; }, on: function(notificationName, callback) { this.addObserver(Proto.clone().setSlot(notificationName, function(msg){ msg.sender().removeObserver(this); callback(msg); })).setPrefix(null); return this; }, cancel: function() { this.removeAllObservers(); return this; } }); module.exports = Observable;
{'content_hash': '4cd1249e5f8c0c41d1040af1af8effd7', 'timestamp': '', 'source': 'github', 'line_count': 128, 'max_line_length': 137, 'avg_line_length': 23.25, 'alnum_prop': 0.7002688172043011, 'repo_name': 'richcollins/ideal', 'id': 'a18b3484fb5281df36868c90034e4a826d09686b', 'size': '2976', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'lib/Observable.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '39566'}]}
#ifndef GRPC_CORE_LIB_IOMGR_ENDPOINT_H #define GRPC_CORE_LIB_IOMGR_ENDPOINT_H #include <grpc/support/port_platform.h> #include <grpc/slice.h> #include <grpc/slice_buffer.h> #include <grpc/support/time.h> #include "src/core/lib/iomgr/pollset.h" #include "src/core/lib/iomgr/pollset_set.h" #include "src/core/lib/iomgr/resource_quota.h" /* An endpoint caps a streaming channel between two communicating processes. Examples may be: a tcp socket, <stdin+stdout>, or some shared memory. */ typedef struct grpc_endpoint grpc_endpoint; typedef struct grpc_endpoint_vtable grpc_endpoint_vtable; class Timestamps; struct grpc_endpoint_vtable { void (*read)(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb); void (*write)(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb, void* arg); void (*add_to_pollset)(grpc_endpoint* ep, grpc_pollset* pollset); void (*add_to_pollset_set)(grpc_endpoint* ep, grpc_pollset_set* pollset); void (*delete_from_pollset_set)(grpc_endpoint* ep, grpc_pollset_set* pollset); void (*shutdown)(grpc_endpoint* ep, grpc_error* why); void (*destroy)(grpc_endpoint* ep); grpc_resource_user* (*get_resource_user)(grpc_endpoint* ep); char* (*get_peer)(grpc_endpoint* ep); int (*get_fd)(grpc_endpoint* ep); bool (*can_track_err)(grpc_endpoint* ep); }; /* When data is available on the connection, calls the callback with slices. Callback success indicates that the endpoint can accept more reads, failure indicates the endpoint is closed. Valid slices may be placed into \a slices even when the callback is invoked with error != GRPC_ERROR_NONE. */ void grpc_endpoint_read(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb); char* grpc_endpoint_get_peer(grpc_endpoint* ep); /* Get the file descriptor used by \a ep. Return -1 if \a ep is not using an fd. */ int grpc_endpoint_get_fd(grpc_endpoint* ep); /* Write slices out to the socket. If the connection is ready for more data after the end of the call, it returns GRPC_ENDPOINT_DONE. Otherwise it returns GRPC_ENDPOINT_PENDING and calls cb when the connection is ready for more data. \a slices may be mutated at will by the endpoint until cb is called. No guarantee is made to the content of slices after a write EXCEPT that it is a valid slice buffer. \a arg is platform specific. It is currently only used by TCP on linux platforms as an argument that would be forwarded to the timestamps callback. */ void grpc_endpoint_write(grpc_endpoint* ep, grpc_slice_buffer* slices, grpc_closure* cb, void* arg); /* Causes any pending and future read/write callbacks to run immediately with success==0 */ void grpc_endpoint_shutdown(grpc_endpoint* ep, grpc_error* why); void grpc_endpoint_destroy(grpc_endpoint* ep); /* Add an endpoint to a pollset or pollset_set, so that when the pollset is polled, events from this endpoint are considered */ void grpc_endpoint_add_to_pollset(grpc_endpoint* ep, grpc_pollset* pollset); void grpc_endpoint_add_to_pollset_set(grpc_endpoint* ep, grpc_pollset_set* pollset_set); /* Delete an endpoint from a pollset_set */ void grpc_endpoint_delete_from_pollset_set(grpc_endpoint* ep, grpc_pollset_set* pollset_set); grpc_resource_user* grpc_endpoint_get_resource_user(grpc_endpoint* endpoint); bool grpc_endpoint_can_track_err(grpc_endpoint* ep); struct grpc_endpoint { const grpc_endpoint_vtable* vtable; }; #endif /* GRPC_CORE_LIB_IOMGR_ENDPOINT_H */
{'content_hash': 'b49f2b06919b48366d453f111778ade3', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 80, 'avg_line_length': 40.70786516853933, 'alnum_prop': 0.7099089152635937, 'repo_name': 'carl-mastrangelo/grpc', 'id': '79c8ece263a94c9a49e3b75e8946d99e1d3e3a4b', 'size': '4225', 'binary': False, 'copies': '9', 'ref': 'refs/heads/master', 'path': 'src/core/lib/iomgr/endpoint.h', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '32274'}, {'name': 'C', 'bytes': '1677470'}, {'name': 'C#', 'bytes': '1905512'}, {'name': 'C++', 'bytes': '30667850'}, {'name': 'CMake', 'bytes': '624762'}, {'name': 'CSS', 'bytes': '1519'}, {'name': 'DTrace', 'bytes': '147'}, {'name': 'Dockerfile', 'bytes': '153845'}, {'name': 'Go', 'bytes': '34791'}, {'name': 'HTML', 'bytes': '14'}, {'name': 'Java', 'bytes': '6907'}, {'name': 'JavaScript', 'bytes': '53044'}, {'name': 'M4', 'bytes': '46911'}, {'name': 'Makefile', 'bytes': '1151674'}, {'name': 'Objective-C', 'bytes': '441626'}, {'name': 'Objective-C++', 'bytes': '37623'}, {'name': 'PHP', 'bytes': '471571'}, {'name': 'Python', 'bytes': '2754606'}, {'name': 'Ruby', 'bytes': '993806'}, {'name': 'Shell', 'bytes': '429791'}, {'name': 'Swift', 'bytes': '3516'}, {'name': 'XSLT', 'bytes': '9673'}]}
Switching Service ]]-- local Delta = ... IPlib = Delta.lib.Address local function wrap(side) if peripheral.isPresent(side) then if peripheral.getType(side) == "modem" then if peripheral.call(side,"isWireless") == false then print("Accepted ", side) return Delta.modem(side) end end end return nil end local function Switch() local MainSide local MainIP local private_network_ID local modems = { top = wrap("top"), bottom = wrap("bottom"), front = wrap("front"), back = wrap("back"), right = wrap("right"), left = wrap("left"), } for i,v in pairs(modems) do istrue = v.connect() if istrue then print("Is true ", i) MainSide = i MainIP = v.IP end v.open(65535) v.open(65534) v.open(64511) end for i,v in pairs(modems) do v.setIP(MainIP) end print(MainIP) local ips = { } local macs = { } local side, protocol, req_id, message, s_side, d_ip, s_ip while true do event = {coroutine.yield("modem_message")} if event[1] == "modem_message" then side, protocol, req_id, message = event[2], event[3], event[4], event[5] if protocol == 65535 then if not (side == MainSide) then modems[MainSide].transmit(65535, req_id, message) print("Protocol 65535...") macs[message] = side end elseif protocol == 65534 then if side == MainSide then s_side = macs[message[1]] if s_side then modems[s_side].transmit(65534, req_id, message) macs[message[1]] = nil ips[message[2]] = side print("Protocol 65534...") end end elseif protocol == 64511 then d_ip, s_ip = message[1], message[2] ips[s_ip] = side message[6] = message[6] - 1 --[[Private Network Stuff]]-- private_network_ID = nil private_network_ID = IPlib.isReserved(d_ip, true) if private_network_ID then if private_network_ID == 9 then s_side = ips[sip] if s_side then modems[s_side].transmit(64511, 0x0, message) print("Protocol 64511...") else for i,v in pairs(modems) do if i ~= side then v.transmit(64511, 0x0, message) end end print("Protocol 64511...") --wow end end else modems[MainSide].transmit(64511, 0x0, message) print("Protocol 64511...") --wow print("Main side") end end end end end return Switch
{'content_hash': '38fb4cba3bd8004234686735933594c3', 'timestamp': '', 'source': 'github', 'line_count': 113, 'max_line_length': 75, 'avg_line_length': 20.964601769911503, 'alnum_prop': 0.6086956521739131, 'repo_name': 'ccTCP/Delta', 'id': '61c4a7332fc539055c5aded865814d617be5eb71', 'size': '2374', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Devices/Switch/Switch.lua', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Lua', 'bytes': '602977'}]}
package hudson.tasks; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.Descriptor; import hudson.model.FreeStyleBuild; import hudson.model.FreeStyleProject; import hudson.model.Result; import hudson.model.Run; import hudson.model.queue.QueueTaskFuture; import hudson.tasks.ArtifactArchiverTest.CreateArtifact; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.FailureBuilder; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.TestBuilder; /** * Verifies that the last successful and stable builds of a job will be kept if requested. */ public class LogRotatorTest { @Rule public JenkinsRule j = new JenkinsRule(); @Test public void successVsFailure() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.setLogRotator(new LogRotator(-1, 2, -1, -1)); j.buildAndAssertSuccess(project); // #1 project.getBuildersList().replaceBy(Collections.singleton(new FailureBuilder())); j.buildAndAssertStatus(Result.FAILURE, project); // #2 j.buildAndAssertStatus(Result.FAILURE, project); // #3 assertEquals(1, numberOf(project.getLastSuccessfulBuild())); project.getBuildersList().replaceBy(Collections.emptySet()); j.buildAndAssertSuccess(project); // #4 assertEquals(4, numberOf(project.getLastSuccessfulBuild())); assertNull(project.getBuildByNumber(1)); assertNull(project.getBuildByNumber(2)); assertEquals(3, numberOf(project.getLastFailedBuild())); } @Test @Issue("JENKINS-2417") public void stableVsUnstable() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.setLogRotator(new LogRotator(-1, 2, -1, -1)); j.buildAndAssertSuccess(project); // #1 project.getPublishersList().replaceBy(Collections.singleton(new TestsFail())); j.buildAndAssertStatus(Result.UNSTABLE, project); // #2 j.buildAndAssertStatus(Result.UNSTABLE, project); // #3 assertEquals(1, numberOf(project.getLastStableBuild())); project.getPublishersList().replaceBy(Collections.emptySet()); j.buildAndAssertSuccess(project); // #4 assertNull(project.getBuildByNumber(1)); assertNull(project.getBuildByNumber(2)); } @Test @Issue("JENKINS-834") public void artifactDelete() throws Exception { FreeStyleProject project = j.createFreeStyleProject(); project.setLogRotator(new LogRotator(-1, 6, -1, 2)); project.getPublishersList().replaceBy(Collections.singleton(new ArtifactArchiver("f", "", true, false))); j.buildAndAssertStatus(Result.FAILURE, project); // #1 assertFalse(project.getBuildByNumber(1).getHasArtifacts()); project.getBuildersList().replaceBy(Collections.singleton(new CreateArtifact())); j.buildAndAssertSuccess(project); // #2 assertTrue(project.getBuildByNumber(2).getHasArtifacts()); project.getBuildersList().replaceBy(Arrays.asList(new CreateArtifact(), new FailureBuilder())); j.buildAndAssertStatus(Result.FAILURE, project); // #3 assertTrue(project.getBuildByNumber(2).getHasArtifacts()); assertTrue(project.getBuildByNumber(3).getHasArtifacts()); j.buildAndAssertStatus(Result.FAILURE, project); // #4 assertTrue(project.getBuildByNumber(2).getHasArtifacts()); assertTrue(project.getBuildByNumber(3).getHasArtifacts()); assertTrue(project.getBuildByNumber(4).getHasArtifacts()); j.buildAndAssertStatus(Result.FAILURE, project); // #5 assertTrue(project.getBuildByNumber(2).getHasArtifacts()); assertFalse("no better than #4", project.getBuildByNumber(3).getHasArtifacts()); assertTrue(project.getBuildByNumber(4).getHasArtifacts()); assertTrue(project.getBuildByNumber(5).getHasArtifacts()); project.getBuildersList().replaceBy(Collections.singleton(new CreateArtifact())); j.buildAndAssertSuccess(project); // #6 assertFalse("#2 is still lastSuccessful until #6 is complete", project.getBuildByNumber(2).getHasArtifacts()); assertFalse(project.getBuildByNumber(3).getHasArtifacts()); assertFalse(project.getBuildByNumber(4).getHasArtifacts()); assertTrue(project.getBuildByNumber(5).getHasArtifacts()); assertTrue(project.getBuildByNumber(6).getHasArtifacts()); j.buildAndAssertSuccess(project); // #7 assertNull(project.getBuildByNumber(1)); assertNotNull(project.getBuildByNumber(2)); assertFalse("lastSuccessful was #6 for ArtifactArchiver", project.getBuildByNumber(2).getHasArtifacts()); assertFalse(project.getBuildByNumber(3).getHasArtifacts()); assertFalse(project.getBuildByNumber(4).getHasArtifacts()); assertFalse(project.getBuildByNumber(5).getHasArtifacts()); assertTrue(project.getBuildByNumber(6).getHasArtifacts()); assertTrue(project.getBuildByNumber(7).getHasArtifacts()); j.buildAndAssertSuccess(project); // #8 assertNull(project.getBuildByNumber(2)); assertNotNull(project.getBuildByNumber(3)); assertFalse(project.getBuildByNumber(3).getHasArtifacts()); assertFalse(project.getBuildByNumber(4).getHasArtifacts()); assertFalse(project.getBuildByNumber(5).getHasArtifacts()); assertFalse(project.getBuildByNumber(6).getHasArtifacts()); assertTrue(project.getBuildByNumber(7).getHasArtifacts()); assertTrue(project.getBuildByNumber(8).getHasArtifacts()); } @Test @Issue("JENKINS-27836") public void artifactsRetainedWhileBuilding() throws Exception { j.getInstance().setNumExecutors(3); FreeStyleProject p = j.createFreeStyleProject(); p.setBuildDiscarder(new LogRotator(-1, 3, -1, 1)); StallBuilder sync = new StallBuilder(); p.getBuildersList().replaceBy(Arrays.asList(new CreateArtifact(), sync)); p.setConcurrentBuild(true); QueueTaskFuture<FreeStyleBuild> futureRun1 = p.scheduleBuild2(0); FreeStyleBuild run1 = futureRun1.waitForStart(); sync.waitFor(run1.getNumber(), 1, TimeUnit.SECONDS); QueueTaskFuture<FreeStyleBuild> futureRun2 = p.scheduleBuild2(0); FreeStyleBuild run2 = futureRun2.waitForStart(); sync.waitFor(run2.getNumber(), 1, TimeUnit.SECONDS); QueueTaskFuture<FreeStyleBuild> futureRun3 = p.scheduleBuild2(0); FreeStyleBuild run3 = futureRun3.waitForStart(); sync.waitFor(run3.getNumber(), 1, TimeUnit.SECONDS); assertThat("we haven't released run1's guard", run1.isBuilding(), is(true)); assertThat("we haven't released run2's guard", run2.isBuilding(), is(true)); assertThat("we haven't released run3's guard", run3.isBuilding(), is(true)); assertThat("we have artifacts in run1", run1.getHasArtifacts(), is(true)); assertThat("we have artifacts in run2", run2.getHasArtifacts(), is(true)); assertThat("we have artifacts in run3", run3.getHasArtifacts(), is(true)); sync.release(run1.getNumber()); futureRun1.get(); assertThat("we have released run1's guard", run1.isBuilding(), is(false)); assertThat("we haven't released run2's guard", run2.isBuilding(), is(true)); assertThat("we haven't released run3's guard", run3.isBuilding(), is(true)); assertThat("run1 is last stable build", p.getLastStableBuild(), is(run1)); assertThat("run1 is last successful build", p.getLastSuccessfulBuild(), is(run1)); assertThat("we have artifacts in run1", run1.getHasArtifacts(), is(true)); assertThat("CRITICAL ASSERTION: we have artifacts in run2", run2.getHasArtifacts(), is(true)); assertThat("we have artifacts in run3", run3.getHasArtifacts(), is(true)); sync.release(run2.getNumber()); futureRun2.get(); assertThat("we have released run2's guard", run2.isBuilding(), is(false)); assertThat("we haven't released run3's guard", run3.isBuilding(), is(true)); assertThat("we have no artifacts in run1", run1.getHasArtifacts(), is(false)); assertThat("run2 is last stable build", p.getLastStableBuild(), is(run2)); assertThat("run2 is last successful build", p.getLastSuccessfulBuild(), is(run2)); assertThat("we have artifacts in run2", run2.getHasArtifacts(), is(true)); assertThat("we have artifacts in run3", run3.getHasArtifacts(), is(true)); sync.release(run3.getNumber()); futureRun3.get(); assertThat("we have released run3's guard", run3.isBuilding(), is(false)); assertThat("we have no artifacts in run1", run1.getHasArtifacts(), is(false)); assertThat("we have no artifacts in run2", run2.getHasArtifacts(), is(false)); assertThat("run3 is last stable build", p.getLastStableBuild(), is(run3)); assertThat("run3 is last successful build", p.getLastSuccessfulBuild(), is(run3)); assertThat("we have artifacts in run3", run3.getHasArtifacts(), is(true)); } private static int numberOf(Run<?, ?> run) { return run != null ? run.getNumber() : -1; } static class TestsFail extends Publisher { @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) { build.setResult(Result.UNSTABLE); return true; } @Override public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } @Override public Descriptor<Publisher> getDescriptor() { return new Descriptor<Publisher>(TestsFail.class) {}; } } public static class StallBuilder extends TestBuilder { private int syncBuildNumber; private final Object syncLock = new Object(); private int waitBuildNumber; private final Object waitLock = new Object(); private final ArtifactArchiver archiver = new ArtifactArchiver("f"); @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException { archiver.perform(build, launcher, listener); Logger.getAnonymousLogger().log(Level.INFO, "Building #{0}", build.getNumber()); synchronized (waitLock) { if (waitBuildNumber < build.getNumber()) { waitBuildNumber = build.getNumber(); waitLock.notifyAll(); } } Logger.getAnonymousLogger().log(Level.INFO, "Waiting #{0}", build.getNumber()); synchronized (syncLock) { while (build.getNumber() > syncBuildNumber) { try { syncLock.wait(10); } catch (InterruptedException e) { e.printStackTrace(listener.fatalError("Interrupted: %s", e.getMessage())); return false; } } } Logger.getAnonymousLogger().log(Level.INFO, "Done #{0}", build.getNumber()); return true; } public void release(int upToBuildNumber) { synchronized (syncLock) { if (syncBuildNumber < upToBuildNumber) { Logger.getAnonymousLogger().log(Level.INFO, "Signal #{0}", upToBuildNumber); syncBuildNumber = upToBuildNumber; syncLock.notifyAll(); } } } public void waitFor(int buildNumber, long timeout, TimeUnit units) throws TimeoutException, InterruptedException { long giveUp = System.nanoTime() + units.toNanos(timeout); synchronized (waitLock) { while (waitBuildNumber < buildNumber) { long remaining = giveUp - System.nanoTime(); if (remaining < 0) { throw new TimeoutException(); } waitLock.wait(remaining / 1000000L, (int) (remaining % 1000000L)); } } } @Override public BuildStepMonitor getRequiredMonitorService() { return BuildStepMonitor.NONE; } } }
{'content_hash': 'fbad1941f6274f0e8fe5ddefb27240a8', 'timestamp': '', 'source': 'github', 'line_count': 272, 'max_line_length': 118, 'avg_line_length': 48.0110294117647, 'alnum_prop': 0.666207213416035, 'repo_name': 'v1v/jenkins', 'id': 'da5da0f15211ebfd64c6b0082de67acf266325cb', 'size': '14232', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'test/src/test/java/hudson/tasks/LogRotatorTest.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Batchfile', 'bytes': '1023'}, {'name': 'C', 'bytes': '2091'}, {'name': 'CSS', 'bytes': '231481'}, {'name': 'GAP', 'bytes': '6933'}, {'name': 'Groovy', 'bytes': '80098'}, {'name': 'HTML', 'bytes': '975503'}, {'name': 'Handlebars', 'bytes': '15034'}, {'name': 'Java', 'bytes': '11492804'}, {'name': 'JavaScript', 'bytes': '419239'}, {'name': 'Less', 'bytes': '167006'}, {'name': 'Perl', 'bytes': '15321'}, {'name': 'Ruby', 'bytes': '17290'}, {'name': 'Shell', 'bytes': '4286'}]}
***This repos has been moved back to Inridea so that it can live with Grape - https://github.com/intridea/grape-entity*** # Grape::Entity [![Build Status](https://travis-ci.org/agileanimal/grape-entity.png?branch=master)](https://travis-ci.org/agileanimal/grape-entity) ## Introduction This gem adds Entity support to API frameworks, such as [Grape](https://github.com/intridea/grape). Grape's Entity is an API focussed facade that sits on top of an object model. ## What's New We are currently working on a set of "shoulda-style matchers" (sorry, RSpec only right now -- although they've been done in a way that can support test-unit in the future). [Grape Entity Matchers](https://github.com/agileanimal/grape-entity-matchers). This is still a work in progress but worth checking out. ## Reusable Responses with Entities Entities are a reusable means for converting Ruby objects to API responses. Entities can be used to conditionally include fields, nest other entities, and build ever larger responses, using inheritance. ### Defining Entities Entities inherit from Grape::Entity, and define a simple DSL. Exposures can use runtime options to determine which fields should be visible, these options are available to `:if`, `:unless`, and `:proc`. The option keys `:version` and `:collection` will always be defined. The `:version` key is defined as `api.version`. The `:collection` key is boolean, and defined as `true` if the object presented is an array. * `expose SYMBOLS` * define a list of fields which will always be exposed * `expose SYMBOLS, HASH` * HASH keys include `:if`, `:unless`, `:proc`, `:as`, `:using`, `:format_with`, `:documentation` * `:if` and `:unless` accept hashes (passed during runtime) or procs (arguments are object and options) * `expose SYMBOL, { :format_with => :formatter }` * expose a value, formatting it first * `:format_with` can only be applied to one exposure at a time * `expose SYMBOL, { :as => "alias" }` * Expose a value, changing its hash key from SYMBOL to alias * `:as` can only be applied to one exposure at a time * `expose SYMBOL BLOCK` * block arguments are object and options * expose the value returned by the block * block can only be applied to one exposure at a time ```ruby module API module Entities class Status < Grape::Entity expose :user_name expose :text, :documentation => { :type => "string", :desc => "Status update text." } expose :ip, :if => { :type => :full } expose :user_type, user_id, :if => lambda{ |status, options| status.user.public? } expose :digest { |status, options| Digest::MD5.hexdigest(satus.txt) } expose :replies, :using => API::Status, :as => :replies end end end module API module Entities class StatusDetailed < API::Entities::Status expose :internal_id end end end ``` #### Using the Exposure DSL Grape ships with a DSL to easily define entities within the context of an existing class: ```ruby class Status include Grape::Entity::DSL entity :text, :user_id do expose :detailed, if: :conditional end end ``` The above will automatically create a `Status::Entity` class and define properties on it according to the same rules as above. If you only want to define simple exposures you don't have to supply a block and can instead simply supply a list of comma-separated symbols. ### Using Entities Once an entity is defined, it can be used within endpoints, by calling `present`. The `present` method accepts two arguments, the object to be presented and the options associated with it. The options hash must always include `:with`, which defines the entity to expose. If the entity includes documentation it can be included in an endpoint's description. ```ruby module API class Statuses < Grape::API version 'v1' desc 'Statuses index', { :object_fields => API::Entities::Status.documentation } get '/statuses' do statuses = Status.all type = current_user.admin? ? :full : :default present statuses, with: API::Entities::Status, :type => type end end end ``` ### Entity Organization In addition to separately organizing entities, it may be useful to put them as namespaced classes underneath the model they represent. ```ruby class Status def entity Status.new(self) end class Entity < Grape::Entity expose :text, :user_id end end ``` If you organize your entities this way, Grape will automatically detect the `Entity` class and use it to present your models. In this example, if you added `present User.new` to your endpoint, Grape would automatically detect that there is a `Status::Entity` class and use that as the representative entity. This can still be overridden by using the `:with` option or an explicit `represents` call. ### Caveats Entities with duplicate exposure names and conditions will silently overwrite one another. In the following example, when `object.check` equals "foo", only `field_a` will be exposed. However, when `object.check` equals "bar" both `field_b` and `foo` will be exposed. ```ruby module API module Entities class Status < Grape::Entity expose :field_a, :foo, :if => lambda { |object, options| object.check == "foo" } expose :field_b, :foo, :if => lambda { |object, options| object.check == "bar" } end end end ``` This can be problematic, when you have mixed collections. Using `respond_to?` is safer. ```ruby module API module Entities class Status < Grape::Entity expose :field_a, :if => lambda { |object, options| object.check == "foo" } expose :field_b, :if => lambda { |object, options| object.check == "bar" } expose :foo, :if => lambda { |object, options| object.respond_to?(:foo) } end end end ``` ## Installation Add this line to your application's Gemfile: gem 'grape-entity' And then execute: $ bundle Or install it yourself as: $ gem install grape-entity ## Contributing 1. Fork it 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create new Pull Request ## License MIT License. See LICENSE for details. ## Copyright Copyright (c) 2010-2012 Michael Bleigh, and Intridea, Inc.
{'content_hash': '25ddde2a693e4e6e781ba4b2d9bdb5cf', 'timestamp': '', 'source': 'github', 'line_count': 199, 'max_line_length': 177, 'avg_line_length': 31.974874371859297, 'alnum_prop': 0.7073707370737073, 'repo_name': 'agileanimal/grape-entity', 'id': '73e7bec09b059fcdf870a8bfb6f8a907dc69c254', 'size': '6363', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.markdown', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '39106'}]}
SYNONYM #### According to The Catalogue of Life, 3rd January 2011 #### Published in null #### Original name null ### Remarks null
{'content_hash': 'b3ce326780e34da9f5dbb65b29afcbcb', 'timestamp': '', 'source': 'github', 'line_count': 13, 'max_line_length': 39, 'avg_line_length': 10.23076923076923, 'alnum_prop': 0.6917293233082706, 'repo_name': 'mdoering/backbone', 'id': 'e077e800cd1c8d11fe91a3226dae91468b0f502c', 'size': '183', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'life/Plantae/Magnoliophyta/Magnoliopsida/Fabales/Fabaceae/Tachigali/Tachigali paniculata/ Syn. Tachigali carinata/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
package org.apache.camel.component.mongodb3.springboot; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Generated; import org.apache.camel.CamelContext; import org.apache.camel.component.mongodb3.MongoDbComponent; import org.apache.camel.spi.ComponentCustomizer; import org.apache.camel.spi.HasId; import org.apache.camel.spring.boot.CamelAutoConfiguration; import org.apache.camel.spring.boot.ComponentConfigurationProperties; import org.apache.camel.spring.boot.util.CamelPropertiesHelper; import org.apache.camel.spring.boot.util.ConditionalOnCamelContextAndAutoConfigurationBeans; import org.apache.camel.spring.boot.util.GroupCondition; import org.apache.camel.spring.boot.util.HierarchicalPropertiesEvaluator; import org.apache.camel.util.IntrospectionSupport; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Lazy; /** * Generated by camel-package-maven-plugin - do not edit this file! */ @Generated("org.apache.camel.maven.packaging.SpringBootAutoConfigurationMojo") @Configuration @Conditional({ConditionalOnCamelContextAndAutoConfigurationBeans.class, MongoDbComponentAutoConfiguration.GroupConditions.class}) @AutoConfigureAfter(CamelAutoConfiguration.class) @EnableConfigurationProperties({ComponentConfigurationProperties.class, MongoDbComponentConfiguration.class}) public class MongoDbComponentAutoConfiguration { private static final Logger LOGGER = LoggerFactory .getLogger(MongoDbComponentAutoConfiguration.class); @Autowired private ApplicationContext applicationContext; @Autowired private CamelContext camelContext; @Autowired private MongoDbComponentConfiguration configuration; @Autowired(required = false) private List<ComponentCustomizer<MongoDbComponent>> customizers; static class GroupConditions extends GroupCondition { public GroupConditions() { super("camel.component", "camel.component.mongodb3"); } } @Lazy @Bean(name = "mongodb3-component") @ConditionalOnMissingBean(MongoDbComponent.class) public MongoDbComponent configureMongoDbComponent() throws Exception { MongoDbComponent component = new MongoDbComponent(); component.setCamelContext(camelContext); Map<String, Object> parameters = new HashMap<>(); IntrospectionSupport.getProperties(configuration, parameters, null, false); for (Map.Entry<String, Object> entry : parameters.entrySet()) { Object value = entry.getValue(); Class<?> paramClass = value.getClass(); if (paramClass.getName().endsWith("NestedConfiguration")) { Class nestedClass = null; try { nestedClass = (Class) paramClass.getDeclaredField( "CAMEL_NESTED_CLASS").get(null); HashMap<String, Object> nestedParameters = new HashMap<>(); IntrospectionSupport.getProperties(value, nestedParameters, null, false); Object nestedProperty = nestedClass.newInstance(); CamelPropertiesHelper.setCamelProperties(camelContext, nestedProperty, nestedParameters, false); entry.setValue(nestedProperty); } catch (NoSuchFieldException e) { } } } CamelPropertiesHelper.setCamelProperties(camelContext, component, parameters, false); if (ObjectHelper.isNotEmpty(customizers)) { for (ComponentCustomizer<MongoDbComponent> customizer : customizers) { boolean useCustomizer = (customizer instanceof HasId) ? HierarchicalPropertiesEvaluator.evaluate( applicationContext.getEnvironment(), "camel.component.customizer", "camel.component.mongodb3.customizer", ((HasId) customizer).getId()) : HierarchicalPropertiesEvaluator.evaluate( applicationContext.getEnvironment(), "camel.component.customizer", "camel.component.mongodb3.customizer"); if (useCustomizer) { LOGGER.debug("Configure component {}, with customizer {}", component, customizer); customizer.customize(component); } } } return component; } }
{'content_hash': '9fe1791e2980ac0a82b5c15ea1bf67ac', 'timestamp': '', 'source': 'github', 'line_count': 113, 'max_line_length': 92, 'avg_line_length': 47.26548672566372, 'alnum_prop': 0.6869500093615428, 'repo_name': 'rmarting/camel', 'id': 'd19e759cefe14b4d9aa0af707ad5799e313dd5ef', 'size': '6144', 'binary': False, 'copies': '15', 'ref': 'refs/heads/master', 'path': 'platforms/spring-boot/components-starter/camel-mongodb3-starter/src/main/java/org/apache/camel/component/mongodb3/springboot/MongoDbComponentAutoConfiguration.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Apex', 'bytes': '6519'}, {'name': 'Batchfile', 'bytes': '1518'}, {'name': 'CSS', 'bytes': '30373'}, {'name': 'Elm', 'bytes': '10852'}, {'name': 'FreeMarker', 'bytes': '11410'}, {'name': 'Groovy', 'bytes': '53380'}, {'name': 'HTML', 'bytes': '183702'}, {'name': 'Java', 'bytes': '63735850'}, {'name': 'JavaScript', 'bytes': '90230'}, {'name': 'Makefile', 'bytes': '513'}, {'name': 'Python', 'bytes': '36'}, {'name': 'Ruby', 'bytes': '4802'}, {'name': 'Scala', 'bytes': '323662'}, {'name': 'Shell', 'bytes': '17092'}, {'name': 'Tcl', 'bytes': '4974'}, {'name': 'XQuery', 'bytes': '546'}, {'name': 'XSLT', 'bytes': '284638'}]}
import os import functools ROOT_PATH = os.path.dirname(os.path.realpath(__file__)) make_path = functools.partial(os.path.join, ROOT_PATH) class T: def __init__(self, tmp): self.template_name = tmp def __call__(self, func): thiz = self def __wrap__(self, *args, **kwargs): ret = func(self, *args, **kwargs) self.render(thiz.template_name, **ret or {}) return __wrap__
{'content_hash': '1debb9879c9c6259ece6c7440ef0c94e', 'timestamp': '', 'source': 'github', 'line_count': 18, 'max_line_length': 56, 'avg_line_length': 24.22222222222222, 'alnum_prop': 0.5711009174311926, 'repo_name': 'senghoo/operator', 'id': '1d0cbdb31c6a48c4937050b97e481c5fd273e894', 'size': '436', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'utils.py', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '1558'}, {'name': 'HTML', 'bytes': '3432'}, {'name': 'JavaScript', 'bytes': '484'}, {'name': 'Python', 'bytes': '5883'}]}
title: Spy School - Secret Service written_by: Stuart Gibbs available: 'October 10th, 2017' isbn: '9781481477826' binding: Hardcover link_to_buy_page: image_path: 'https://images.booksense.com/images/826/477/9781481477826.jpg' link: ---
{'content_hash': '7af86ac148f79bd0fbab74cd571c3c75', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 75, 'avg_line_length': 21.727272727272727, 'alnum_prop': 0.7573221757322176, 'repo_name': 'Frontmatter/brooklinebooksmith', 'id': 'cc5334a7877903767161bf1ed6b008f1f969ed84', 'size': '243', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': '_books/spy-school---secret-service.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '191471'}, {'name': 'HTML', 'bytes': '58328'}, {'name': 'JavaScript', 'bytes': '4750'}, {'name': 'Ruby', 'bytes': '3911'}, {'name': 'Shell', 'bytes': '189'}]}
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; using System.Threading.Tasks; namespace Altairis.SerialRfid.Client { [Serializable] public class RfidException : Exception { public string DataReceived { get; private set; } public RfidException() : base("Error communicating with reader") { } public RfidException(string message) : base(message) { } public RfidException(string message, string dataReceived) : base(message) { this.DataReceived = dataReceived; } public RfidException(string message, Exception innerException) : base(message, innerException) { } protected RfidException(SerializationInfo info, StreamingContext context) : base(info, context) { this.DataReceived = info.GetString(nameof(this.DataReceived)); } [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); info.AddValue(nameof(this.DataReceived), this.DataReceived); base.GetObjectData(info, context); } } }
{'content_hash': '97bdc9714100bb435ff485cfbe4402c8', 'timestamp': '', 'source': 'github', 'line_count': 39, 'max_line_length': 105, 'avg_line_length': 34.51282051282051, 'alnum_prop': 0.6924219910846954, 'repo_name': 'ridercz/SerialRFID', 'id': '91722fef3e2d399512fae30ba96ec593f42f8504', 'size': '1348', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Software/Altairis.SerialRfid.Client/RfidException.cs', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'C#', 'bytes': '12387'}, {'name': 'C++', 'bytes': '2044'}]}
<?php namespace app\models; use Yii; /** * This is the model class for table "beneficiario_des". * * @property integer $cod * @property string $cedrif * @property string $razon * @property string $direccion * @property string $telefono * * @property DesincorporacionesBm[] $desincorporacionesBms */ class BeneficiarioDes extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'beneficiario_des'; } /** * @inheritdoc */ public function rules() { return [ [['razon','cedrif'], 'required'], [['cedrif', 'telefono'], 'string', 'max' => 20], [['razon'], 'string', 'max' => 100], [['direccion'], 'string', 'max' => 400], [['cedrif'], 'unique'] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'cod' => 'Cod', 'cedrif' => 'Cedula o Rif', 'razon' => 'Razon Social', 'direccion' => 'Dirección', 'telefono' => 'Telefono de Contacto', ]; } /** * @return \yii\db\ActiveQuery */ public function getDesincorporacionesBms() { return $this->hasMany(DesincorporacionesBm::className(), ['codben' => 'cod']); } }
{'content_hash': '85c925a4c5c192168f38dbd1c6f3363b', 'timestamp': '', 'source': 'github', 'line_count': 63, 'max_line_length': 86, 'avg_line_length': 21.349206349206348, 'alnum_prop': 0.516728624535316, 'repo_name': 'hernangutier/bm', 'id': 'e8eae2991a8f3923a3ba6f1c93ee405f84cf0f63', 'size': '1346', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'models/BeneficiarioDes.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Batchfile', 'bytes': '1030'}, {'name': 'HTML', 'bytes': '3595'}, {'name': 'JavaScript', 'bytes': '583185'}, {'name': 'PHP', 'bytes': '821650'}]}
/** * This is just a simple "decode sound, play it through SDL" example. * The much more complex, fancy, and robust code is playsound.c. * * Please see the file LICENSE.txt in the source's root directory. * * This file written by Ryan C. Gordon. ([email protected]) */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "SDL.h" #include "SDL_sound.h" /* global decoding state. */ typedef struct { Sound_Sample *sample; SDL_AudioSpec devformat; Uint8 *decoded_ptr; Uint32 decoded_bytes; } PlaysoundAudioCallbackData; /* * This variable is flipped to non-zero when the audio callback has * finished playing the whole file. */ static volatile int global_done_flag = 0; /* * The audio callback. SDL calls this frequently to feed the audio device. * We decode the audio file being played in here in small chunks and feed * the device as necessary. Other solutions may want to predecode more * (or all) of the file, since this needs to run fast and frequently, * but since we're only sitting here and waiting for the file to play, * the only real requirement is that we can decode a given audio file * faster than realtime, which isn't really a problem with any modern format * on even pretty old hardware at this point. */ static void audio_callback(void *userdata, Uint8 *stream, int len) { PlaysoundAudioCallbackData *data = (PlaysoundAudioCallbackData *) userdata; Sound_Sample *sample = data->sample; int bw = 0; /* bytes written to stream this time through the callback */ while (bw < len) { int cpysize; /* bytes to copy on this iteration of the loop. */ if (data->decoded_bytes == 0) /* need more data! */ { /* if there wasn't previously an error or EOF, read more. */ if ( ((sample->flags & SOUND_SAMPLEFLAG_ERROR) == 0) && ((sample->flags & SOUND_SAMPLEFLAG_EOF) == 0) ) { data->decoded_bytes = Sound_Decode(sample); data->decoded_ptr = sample->buffer; } /* if */ if (data->decoded_bytes == 0) { /* ...there isn't any more data to read! */ memset(stream + bw, '\0', len - bw); /* write silence. */ global_done_flag = 1; return; /* we're done playback, one way or another. */ } /* if */ } /* if */ /* we have data decoded and ready to write to the device... */ cpysize = len - bw; /* len - bw == amount device still wants. */ if (cpysize > data->decoded_bytes) cpysize = data->decoded_bytes; /* clamp to what we have left. */ /* if it's 0, next iteration will decode more or decide we're done. */ if (cpysize > 0) { /* write this iteration's data to the device. */ memcpy(stream + bw, (Uint8 *) data->decoded_ptr, cpysize); /* update state for next iteration or callback */ bw += cpysize; data->decoded_ptr += cpysize; data->decoded_bytes -= cpysize; } /* if */ } /* while */ } /* audio_callback */ static void playOneSoundFile(const char *fname) { PlaysoundAudioCallbackData data; memset(&data, '\0', sizeof (PlaysoundAudioCallbackData)); data.sample = Sound_NewSampleFromFile(fname, NULL, 65536); if (data.sample == NULL) { fprintf(stderr, "Couldn't load '%s': %s.\n", fname, Sound_GetError()); return; } /* if */ /* * Open device in format of the the sound to be played. * We open and close the device for each sound file, so that SDL * handles the data conversion to hardware format; this is the * easy way out, but isn't practical for most apps. Usually you'll * want to pick one format for all the data or one format for the * audio device and convert the data when needed. This is a more * complex issue than I can describe in a source code comment, though. */ data.devformat.freq = data.sample->actual.rate; data.devformat.format = data.sample->actual.format; data.devformat.channels = data.sample->actual.channels; data.devformat.samples = 4096; /* I just picked a largish number here. */ data.devformat.callback = audio_callback; data.devformat.userdata = &data; if (SDL_OpenAudio(&data.devformat, NULL) < 0) { fprintf(stderr, "Couldn't open audio device: %s.\n", SDL_GetError()); Sound_FreeSample(data.sample); return; } /* if */ printf("Now playing [%s]...\n", fname); SDL_PauseAudio(0); /* SDL audio device is "paused" right after opening. */ global_done_flag = 0; /* the audio callback will flip this flag. */ while (!global_done_flag) SDL_Delay(10); /* just wait for the audio callback to finish. */ /* at this point, we've played the entire audio file. */ SDL_PauseAudio(1); /* so stop the device. */ /* * Sleep two buffers' worth of audio before closing, in order * to allow the playback to finish. This isn't always enough; * perhaps SDL needs a way to explicitly wait for device drain? * Most apps don't have this issue, since they aren't explicitly * closing the device as soon as a sound file is done playback. * As an alternative for this app, you could also change the callback * to write silence for a call or two before flipping global_done_flag. */ SDL_Delay(2 * 1000 * data.devformat.samples / data.devformat.freq); /* if there was an error, tell the user. */ if (data.sample->flags & SOUND_SAMPLEFLAG_ERROR) fprintf(stderr, "Error decoding file: %s\n", Sound_GetError()); Sound_FreeSample(data.sample); /* clean up SDL_Sound resources... */ SDL_CloseAudio(); /* will reopen with next file's format. */ } /* playOneSoundFile */ int main(int argc, char **argv) { int i; if (!Sound_Init()) /* this calls SDL_Init(SDL_INIT_AUDIO) ... */ { fprintf(stderr, "Sound_Init() failed: %s.\n", Sound_GetError()); SDL_Quit(); return(42); } /* if */ for (i = 1; i < argc; i++) /* each arg is an audio file to play. */ playOneSoundFile(argv[i]); /* Shutdown the libraries... */ Sound_Quit(); SDL_Quit(); return(0); } /* main */ /* end of playsound-simple.c ... */
{'content_hash': '00ce4a9ac0783df149b43c3c293c4a48', 'timestamp': '', 'source': 'github', 'line_count': 180, 'max_line_length': 79, 'avg_line_length': 35.605555555555554, 'alnum_prop': 0.6142924013106569, 'repo_name': 'MaddTheSane/executor', 'id': 'b68de219650ca047b4326b3db9fad2857b1d56a4', 'size': '7248', 'binary': False, 'copies': '5', 'ref': 'refs/heads/CppPort', 'path': 'external/SDL_sound/playsound/playsound_simple.c', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '78587'}, {'name': 'Awk', 'bytes': '5579'}, {'name': 'C', 'bytes': '1598474'}, {'name': 'C++', 'bytes': '4606280'}, {'name': 'GDB', 'bytes': '36'}, {'name': 'Inno Setup', 'bytes': '25291'}, {'name': 'M4', 'bytes': '5802'}, {'name': 'Makefile', 'bytes': '62397'}, {'name': 'Mathematica', 'bytes': '9405'}, {'name': 'NewLisp', 'bytes': '35906'}, {'name': 'Objective-C', 'bytes': '25209'}, {'name': 'Objective-C++', 'bytes': '101300'}, {'name': 'Perl', 'bytes': '33397'}, {'name': 'Perl 6', 'bytes': '2970'}, {'name': 'Roff', 'bytes': '19007'}, {'name': 'Shell', 'bytes': '65013'}, {'name': 'Yacc', 'bytes': '27639'}]}
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/joke_activity_container" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".JokeActivity"/> <!-- <fragment android:id="@+id/fragment_joke_to_tell" android:name="com.example.jose.step2library.TellAJokeFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout="@layout/fragment_tell_a_joke"/> </FrameLayout>-->
{'content_hash': 'f479022e0fea798e2d6ac46564936969', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 74, 'avg_line_length': 36.68421052631579, 'alnum_prop': 0.6499282639885222, 'repo_name': 'Jamargle/GradleJokesProject', 'id': '4d8f3cad25b46cb38a0d07cc978190887913dad6', 'size': '697', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'step2library/src/main/res/layout/activity_joke.xml', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'HTML', 'bytes': '5670'}, {'name': 'Java', 'bytes': '22340'}]}
<!DOCTYPE html><html><head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=Edge"> <meta name="description"> <meta name="keywords" content="static content generator,static site generator,static site,HTML,web development,.NET,C#,Razor,Markdown,YAML"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="shortcut icon" href="/OpenTl.Schema/assets/img/favicon.ico" type="image/x-icon"> <link rel="icon" href="/OpenTl.Schema/assets/img/favicon.ico" type="image/x-icon"> <title>OpenTl.Schema - API - RequestGetMessages.Id Property</title> <link href="/OpenTl.Schema/assets/css/mermaid.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/highlight.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/bootstrap/bootstrap.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/adminlte/AdminLTE.css" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/theme/theme.css" rel="stylesheet"> <link href="//fonts.googleapis.com/css?family=Roboto+Mono:400,700|Roboto:400,400i,700,700i" rel="stylesheet"> <link href="/OpenTl.Schema/assets/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="/OpenTl.Schema/assets/css/override.css" rel="stylesheet"> <script src="/OpenTl.Schema/assets/js/jquery-2.2.3.min.js"></script> <script src="/OpenTl.Schema/assets/js/bootstrap.min.js"></script> <script src="/OpenTl.Schema/assets/js/app.min.js"></script> <script src="/OpenTl.Schema/assets/js/highlight.pack.js"></script> <script src="/OpenTl.Schema/assets/js/jquery.slimscroll.min.js"></script> <script src="/OpenTl.Schema/assets/js/jquery.sticky-kit.min.js"></script> <script src="/OpenTl.Schema/assets/js/mermaid.min.js"></script> <!--[if lt IE 9]> <script src="/OpenTl.Schema/assets/js/html5shiv.min.js"></script> <script src="/OpenTl.Schema/assets/js/respond.min.js"></script> <![endif]--> </head> <body class="hold-transition wyam layout-boxed "> <div class="top-banner"></div> <div class="wrapper with-container"> <!-- Header --> <header class="main-header"> <a href="/OpenTl.Schema/" class="logo"> <span>OpenTl.Schema</span> </a> <nav class="navbar navbar-static-top" role="navigation"> <!-- Sidebar toggle button--> <a href="#" class="sidebar-toggle visible-xs-block" data-toggle="offcanvas" role="button"> <span class="sr-only">Toggle side menu</span> <i class="fa fa-chevron-circle-right"></i> </a> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse"> <span class="sr-only">Toggle side menu</span> <i class="fa fa-chevron-circle-down"></i> </button> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse pull-left" id="navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="/OpenTl.Schema/about.html">About This Project</a></li> <li class="active"><a href="/OpenTl.Schema/api">API</a></li> </ul> </div> <!-- /.navbar-collapse --> <!-- Navbar Right Menu --> </nav> </header> <!-- Left side column. contains the logo and sidebar --> <aside class="main-sidebar "> <section class="infobar" data-spy="affix" data-offset-top="60" data-offset-bottom="200"> <div id="infobar-headings"><h6>On This Page</h6><p><a href="#Syntax">Syntax</a></p> <p><a href="#Attributes">Attributes</a></p> <p><a href="#Value">Value</a></p> <hr class="infobar-hidden"> </div> </section> <section class="sidebar"> <script src="/OpenTl.Schema/assets/js/lunr.min.js"></script> <script src="/OpenTl.Schema/assets/js/searchIndex.js"></script> <div class="sidebar-form"> <div class="input-group"> <input type="text" name="search" id="search" class="form-control" placeholder="Search Types..."> <span class="input-group-btn"> <button class="btn btn-flat"><i class="fa fa-search"></i></button> </span> </div> </div> <div id="search-results"> </div> <script> function runSearch(query){ $("#search-results").empty(); if( query.length < 2 ){ return; } var results = searchModule.search("*" + query + "*"); var listHtml = "<ul class='sidebar-menu'>"; listHtml += "<li class='header'>Type Results</li>"; if(results.length == 0 ){ listHtml += "<li>No results found</li>"; } else { for(var i = 0; i < results.length; ++i){ var res = results[i]; listHtml += "<li><a href='" + res.url + "'>" + htmlEscape(res.title) + "</a></li>"; } } listHtml += "</ul>"; $("#search-results").append(listHtml); } $(document).ready(function(){ $("#search").on('input propertychange paste', function() { runSearch($("#search").val()); }); }); function htmlEscape(html) { return document.createElement('div') .appendChild(document.createTextNode(html)) .parentNode .innerHTML; } </script> <hr> <ul class="sidebar-menu"> <li class="header">Namespace</li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages">OpenTl<wbr>.Schema<wbr>.Messages</a></li> <li class="header">Type</li> <li><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages/RequestGetMessages">RequestGetMessages</a></li> <li role="separator" class="divider"></li> <li class="header">Property Members</li> <li class="selected"><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages/RequestGetMessages/A32FCEE8.html">Id</a></li> </ul> </section> </aside> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <section class="content-header"> <h3><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages/RequestGetMessages">RequestGetMessages</a>.</h3> <h1>Id <small>Property</small></h1> </section> <section class="content"> <div class="panel panel-default"> <div class="panel-body"> <dl class="dl-horizontal"> <dt>Namespace</dt> <dd><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages">OpenTl<wbr>.Schema<wbr>.Messages</a></dd> <dt>Containing Type</dt> <dd><a href="/OpenTl.Schema/api/OpenTl.Schema.Messages/RequestGetMessages">RequestGetMessages</a></dd> </dl> </div> </div> <h1 id="Syntax">Syntax</h1> <pre><code>[SerializationOrder(0)] public TVector&lt;IInputMessage&gt; Id { get; set; }</code></pre> <h1 id="Attributes">Attributes</h1> <div class="box"> <div class="box-body no-padding table-responsive"> <table class="table table-striped table-hover two-cols"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody><tr> <td>Serialization<wbr>Order<wbr>Attribute</td> <td></td> </tr> </tbody></table> </div> </div> <h1 id="Value">Value</h1> <div class="box"> <div class="box-body no-padding table-responsive"> <table class="table table-striped table-hover two-cols"> <thead> <tr> <th>Type</th> <th>Description</th> </tr> </thead> <tbody><tr> <td><a href="/OpenTl.Schema/api/OpenTl.Schema/TVector_1">TVector</a><wbr>&lt;<a href="/OpenTl.Schema/api/OpenTl.Schema/IInputMessage">IInputMessage</a>&gt;<wbr></td> <td></td> </tr> </tbody></table> </div> </div> </section> </div> <!-- Footer --> <footer class="main-footer"> </footer> </div> <div class="wrapper bottom-wrapper"> <footer class="bottom-footer"> Generated by <a href="https://wyam.io">Wyam</a> </footer> </div> <a href="javascript:" id="return-to-top"><i class="fa fa-chevron-up"></i></a> <script> // Close the sidebar if we select an anchor link $(".main-sidebar a[href^='#']:not('.expand')").click(function(){ $(document.body).removeClass('sidebar-open'); }); $(document).load(function() { mermaid.initialize( { flowchart: { htmlLabels: false, useMaxWidth:false } }); mermaid.init(undefined, ".mermaid") $('svg').addClass('img-responsive'); $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }); hljs.initHighlightingOnLoad(); // Back to top $(window).scroll(function() { if ($(this).scrollTop() >= 200) { // If page is scrolled more than 50px $('#return-to-top').fadeIn(1000); // Fade in the arrow } else { $('#return-to-top').fadeOut(1000); // Else fade out the arrow } }); $('#return-to-top').click(function() { // When arrow is clicked $('body,html').animate({ scrollTop : 0 // Scroll to top of body }, 500); }); </script> </body></html>
{'content_hash': '8456f70ee453ce93d4555cef24fca315', 'timestamp': '', 'source': 'github', 'line_count': 277, 'max_line_length': 170, 'avg_line_length': 39.17689530685921, 'alnum_prop': 0.5035016586804276, 'repo_name': 'OpenTl/OpenTl.Schema', 'id': '577d9ca52356ff03420aa6560bce369d73789ab3', 'size': '10854', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/api/OpenTl.Schema.Messages/RequestGetMessages/A32FCEE8.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '810786'}, {'name': 'F#', 'bytes': '19501'}, {'name': 'PowerShell', 'bytes': '1288'}]}
import {ILayerConfiguration, Layer} from './Layer'; import {Unit} from './Unit'; import {Util} from './Util'; /** * The neural network class that manages Layers of Neurons * @since 0.0.1 */ export class NeuralNetwork { /** * The layer of neurons that accepts input and passes it to the subsequent layers * @since 0.0.1 */ private inputLayer: Layer; /** * The layer of neurons that produces an output based on the input from the previous layers * @since 0.0.1 */ private outputLayer: Layer; /** * Units representing the data sent to the Input Layer in the neural network * @since 0.0.1 */ private inputUnits: Unit[]; /** * Units representing the output produced by the Output Layer of the neural network * @since 0.0.1 */ private outputUnits: Unit[]; /** * NeuralNetwork constructor. Takes the amount of expected input and output values as arguments. * @since 0.1.1 Added missing `this.outputLayer` assignment * @since 0.1.0 Output layer is now the last layer in the `layers` arrays * @since 0.0.9 Fixed bug where `outputLayer` would be pushed into `allLayers` even if it is undefined * @since 0.0.8 Now uses LinearNeuron since Neuron is now abstract, all layers but input are now optional * @since 0.0.7 Added `inputLayerConfig` * @since 0.0.6 Changed `number` to `ILayerConfiguration` in types of `outputLayer` and `hiddenLayers` * @since 0.0.4 Fixed a bug where the output layer would not get linked correctly * @since 0.0.3 Fixed a bug where layers were not interconnected * @since 0.0.1 */ public constructor(inputCount: number, layers: ILayerConfiguration[] = []) { let inputUnits: Unit[] = []; for (let i = 0; i < inputCount; i++) { inputUnits[i] = new Unit(); } this.inputLayer = Layer.fromInput(inputUnits); let lastLayer = this.inputLayer; for (let i = 0; i < layers.length; i++) { let memoryLayer = lastLayer; lastLayer = Layer.fromLayer(layers[i], lastLayer); memoryLayer.setNextLayer(lastLayer); } this.outputLayer = lastLayer; this.inputUnits = inputUnits; this.outputUnits = this.outputLayer.getOutputUnits(); } /** * Trains the network using some input data and the expected output data, adjusting the variable inputs in the * neurons by the step size supplied. The `outputOperation` function is applied to the output before comparing * it to the expected output. * @since 0.0.5 Now uses the sigma function to calculate the pull * @since 0.0.1 */ public trainWith(inputData: number[], outputData: number[], stepSize: number, outputOperation?: (output: number) => number) { for (let i = 0; i < inputData.length; i++) { if (this.inputUnits[i]) { this.inputUnits[i].value = inputData[i]; } } this.inputLayer.forward(); for (let i = 0; i < outputData.length; i++) { let output = this.outputUnits[i].value; let expectedOutput = outputData[i]; if (outputOperation) { output = outputOperation(output); } let pull = 0; let difference = Math.abs(expectedOutput - output); if (output < expectedOutput) { pull = 1 + Util.sigma(difference); } else if (output > expectedOutput) { pull = -1 - Util.sigma(difference); } this.outputUnits[i].gradient = pull; } this.outputLayer.backward(stepSize); } /** * Uses the network on some input data to retrieve the output, The `outputOperation` function is applied * to the output before returning it. * @since 0.0.2 Now simply returns the output instead of testing it * @since 0.0.1 */ public runWith(inputData: number[], outputOperation?: (output: number) => number): number[] { for (let i = 0; i < inputData.length; i++) { if (this.inputUnits[i]) { this.inputUnits[i].value = inputData[i]; } } this.inputLayer.forward(); let outputArray: number[] = []; for (let i = 0; i < this.outputUnits.length; i++) { let output = this.outputUnits[i].value; if (outputOperation) { output = outputOperation(output); } outputArray[i] = output; } return outputArray; } }
{'content_hash': '5df097a5333c23f373407036aed7173f', 'timestamp': '', 'source': 'github', 'line_count': 123, 'max_line_length': 114, 'avg_line_length': 38.17886178861789, 'alnum_prop': 0.5856047700170358, 'repo_name': 'TimboKZ/js-digit-recognition', 'id': '136873d0ef64b9e4df7c0f3bf96fbbff52572347', 'size': '4946', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/NeuralNetwork.ts', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'JavaScript', 'bytes': '57769'}, {'name': 'TypeScript', 'bytes': '56751'}]}
namespace base { class Value; } namespace chromecast { // Class that encapsulates the construction and parsing of dump entries // in the log file. class DumpInfo { public: // Validate the input as a valid JSON representation of DumpInfo, then // populate the relevant fields. explicit DumpInfo(const base::Value* entry); // Attempt to construct a DumpInfo object that has the following info: // // -crashed_process_dump: the full path of the dump written // -crashed_process_logfile: the full path of the logfile written // -crashed_process_attachments: the full path of the attachments // -dump_time: the time of the dump written // -params: a structure containing other useful crash information DumpInfo(const std::string& crashed_process_dump, const std::string& crashed_process_logfile, const base::Time& dump_time, const MinidumpParams& params, const std::vector<std::string>* attachments = nullptr); DumpInfo(const DumpInfo&) = delete; DumpInfo& operator=(const DumpInfo&) = delete; ~DumpInfo(); const std::string& crashed_process_dump() const { return crashed_process_dump_; } const std::string& logfile() const { return logfile_; } const base::Time& dump_time() const { return dump_time_; } const std::vector<std::string>& attachments() const { return attachments_; } // Return a deep copy of the entry's JSON representation. // The format is: // { // "name": <name>, // "dump_time": <dump_time (kDumpTimeFormat)>, // "dump": <dump>, // "uptime": <uptime>, // "logfile": <logfile>, // "attachments": [<attachment_name>], // "suffix": <suffix>, // "prev_app_name": <prev_app_name>, // "cur_app_name": <current_app_name>, // "last_app_name": <last_app_name>, // "release_version": <release_version>, // "build_number": <build_number> // "reason": <reason> // } std::unique_ptr<base::Value> GetAsValue() const; const MinidumpParams& params() const { return params_; } bool valid() const { return valid_; } private: // Checks if parsed JSON in |value| is valid, if so populates the object's // fields from |value|. bool ParseEntry(const base::Value* value); bool SetDumpTimeFromString(const std::string& timestr); std::string crashed_process_dump_; std::string logfile_; std::vector<std::string> attachments_; base::Time dump_time_; MinidumpParams params_; bool valid_; }; } // namespace chromecast #endif // CHROMECAST_CRASH_LINUX_DUMP_INFO_H_
{'content_hash': '19a49f0e45d4554739fea4ab28241dd4', 'timestamp': '', 'source': 'github', 'line_count': 77, 'max_line_length': 78, 'avg_line_length': 32.935064935064936, 'alnum_prop': 0.6656151419558359, 'repo_name': 'ric2b/Vivaldi-browser', 'id': '076c13244a0e70037177c05f2a860c681b108a2e', 'size': '2927', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'chromium/chromecast/crash/linux/dump_info.h', 'mode': '33188', 'license': 'bsd-3-clause', 'language': []}
package com.pippin; public class UserInfo { private Address address; private PhoneNumber phoneNumber; public UserInfo() { } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public PhoneNumber getPhoneNumber() { return phoneNumber; } public void phoneNumber(PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; } }
{'content_hash': '098a2ee9af0e56d3133259d1613f4bf5', 'timestamp': '', 'source': 'github', 'line_count': 28, 'max_line_length': 51, 'avg_line_length': 15.857142857142858, 'alnum_prop': 0.6846846846846847, 'repo_name': 'dburgess560/kloudbook', 'id': '8db702fb8d089f612c4467f684316c2aa0a3f1d0', 'size': '444', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Database/src/com/pippin/UserInfo.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
#if 0 #include <string.h> #include "FAT.h" using namespace std; namespace fat { //-------------------------File--------------------------------------------- File::File(FS* fs, u32 cluster,size_t size, Directory* parent) :_parent(parent), _fs(fs),_cluster(cluster),_size(size){ _clusterSize = _fs->_fmbr.SectorPerCluster; } size_t File::getSize() const{ if(!_size) const_cast<File*>(this)->_size = 512* _clusterSize * _fs ->nbRemainingCluster(_cluster); return _size; } void File::writeaddr (u64 addr,const void * data, size_t size){ assert (size <= 512);// will take care of larger write later u32 clusterOffset = addr / (512*_clusterSize); u32 offset = addr - clusterOffset *512 * _clusterSize; u32 LBA = _fs->clusterToLBA(_cluster,clusterOffset); _fs->_part->writeaddr(LBA*512 + offset,data,size); } void File::readaddr (u64 addr, void * data, size_t size) const { assert (size <= 512);// will take care of larger read later u32 clusterOffset = addr / (512*_clusterSize); u32 offset = addr - clusterOffset *512 * _clusterSize; u32 LBA = _fs->clusterToLBA(_cluster,clusterOffset); _fs->_part->readaddr(LBA*512 + offset,data,size); } void File::writelba (u32 LBA , const void* data, u32 nbsector){ assert (nbsector == 1);// will take care of larger write later u32 clusterOffset = LBA / _clusterSize; u32 offset = LBA - clusterOffset * _clusterSize; u32 LBAo = _fs->clusterToLBA(_cluster,clusterOffset); _fs->_part->writelba(LBAo+ offset,data,nbsector); } void File::readlba (u32 LBA, void * data, u32 nbsector)const { assert (nbsector == 1);// will take care of larger read later u32 clusterOffset = LBA / _clusterSize; u32 offset = LBA - clusterOffset * _clusterSize; u32 LBAo = _fs->clusterToLBA(_cluster,clusterOffset); //printf("file reading at %u \n",LBAo + offset); _fs->_part->readlba(LBAo+ offset,data,nbsector); } //void File::setName(const std::string& name){} ::Directory* File::getParent(){ return _parent; } //-------------------------------Directory---------------------------------- std::string LongFileName::getName(){ char buffer[14]= {}; for(int i = 0; i < 5 ; ++i){ buffer[i] = char(first5[i]); } for(int i = 0 ; i < 6 ; ++i){ buffer[i+5] = char(second6[i]); } for(int i = 0 ; i < 2 ; ++i){ buffer[i+11] = char(third2[i]); } return buffer; } std::string DirectoryEntry::getName(){ string ext(shortName+8,3); string beg(shortName,8); while(!ext.empty() && ext.back() == ' ') ext.pop_back(); while(!beg.empty() && beg.back() == ' ') beg.pop_back(); if(!ext.empty()) { beg += "."; beg += ext; } return beg; } std::string Directory::fusion(const std::map<u8,LongFileName>& longName){ std::string res; for(auto p : longName){ res += p.second.getName(); } return res; } Directory::Directory(FS* fs, u32 cluster, size_t size,Directory* parent) :fat::File(fs,cluster,size,parent),_loaded(false){} void Directory::load(){ if(_loaded) return; _loaded = true; static LongFileName buffer[16]; std::map<u8,LongFileName> longName; for(size_t i = 0 ; i < getLBASize() ; ++i){ readlba(i,buffer,1); for(int j = 0 ; j < 16 ; ++j){ /*printf("treating area :"); u8 * buf = reinterpret_cast<u8*> (&buffer[j]); for(int k = 0 ;k < 32 ; ++k){ printf("%2x",buf[k]); }printf("\n");*/ if (buffer[j].order == 0xE5) continue; //deleted or invalid entry. if (buffer[j].order == 0x00) return; //end of directory. if (buffer[j].attribute == 0x0F){ //printf("found long name : %s\n",buffer[j].getName().c_str()); //WAIT(100000000); longName [buffer[j].order] = buffer[j]; //printf("Registeredlong name"); //WAIT(100000000); } else { DirectoryEntry* entry = reinterpret_cast<DirectoryEntry*>(&buffer[j]); if(entry->directory){ if (entry->getCluster() == 0) { entry->setCluster(_fs->_fmbr.RootCluster); } string name = fusion(longName); if(name == "")name = entry->getName(); //printf("Found directory %s\n",name.c_str()); //WAIT(100000000); _content[name] = new Directory(_fs,entry->getCluster(),entry->size,this); //printf("Registered directory %s",name.c_str()); //WAIT(300000000); longName.clear(); //printf("Cleared map"); //WAIT(300000000); } else if(entry->volume_id){ longName.clear(); } else { //regular file string name = fusion(longName); if(name == "")name = entry->getName(); //printf("Found file %s\n",name.c_str()); //WAIT(100000000); _content[name] = new File(_fs,entry->getCluster(),entry->size,this); longName.clear(); } } } } } //std::vector<std::string> Directory::getFilesName (){ //load(); //std::vector<std::string> res; //for(auto p : _content){ //res.push_back(p.first); //} //return res; //} File * Directory::operator[](const std::string& name){ load(); auto it = _content.find(name); if(it == _content.end()) return nullptr; else return it->second; } //-----------------------------FileSystem----------------------------------- FS::FS (Partition* part) : FileSystem(part){ //assert(_fmbr.BytesPerSector == 512); // TODO generic sector size. //u32 clusterOffset = LBA / _clusterSize; _part->readaddr(0,&_fmbr,sizeof(_fmbr)); char name [12] = {}; memcpy(name,_fmbr.Label,11); /*printf("Opening FAT32 filesystem : %s; with FAT Size of %u\n",name,_fmbr.FATSize); printf("with %d reserved sectors and %d sectors per cluster\n", _fmbr.nbofReservedSectors, _fmbr.SectorPerCluster); printf("FAT at sector %d\n",_fmbr.nbofReservedSectors); printf("Root Directory at sector %u\n",clusterToLBA(_fmbr.RootCluster,0));*/ } u32 FS::getFATEntry(u32 cluster)const{ u32 res; _part->readaddr(_fmbr.nbofReservedSectors *512 + cluster *4,&res,4); return res; } u32 FS::clusterToLBA(u32 cluster,u32 offset)const{ cluster &= 0x0FFFFFFF; assert (cluster != 0x0FFFFFF7); if (cluster > 0x0FFFFFF7) return -1; if(offset == 0){ return _fmbr.nbofReservedSectors + _fmbr.nbofFAT*_fmbr.FATSize + (cluster-2)*_fmbr.SectorPerCluster; } else { return clusterToLBA(getFATEntry(cluster),offset-1); } } u32 FS::nbRemainingCluster(u32 cluster)const{ int res =0; cluster &= 0x0FFFFFFF; while(cluster < 0x0FFFFFF7){ ++res; cluster = getFATEntry(cluster); } assert (cluster != 0x0FFFFFF7); return res; } ::Directory* FS::getRoot(){ return new Directory (this,_fmbr.RootCluster,0,nullptr); } Directory* FS::getRootFat(){ return new Directory (this,_fmbr.RootCluster,0,nullptr); } }; #endif
{'content_hash': '86faf081721daf8595d71da856e80e59', 'timestamp': '', 'source': 'github', 'line_count': 226, 'max_line_length': 92, 'avg_line_length': 36.5929203539823, 'alnum_prop': 0.49274486094316805, 'repo_name': 'TWal/ENS_sysres', 'id': '506f6714b6a728bd1abe9770cf1d9d9569983876', 'size': '8270', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/HDD/FAT.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '6187'}, {'name': 'C', 'bytes': '57933'}, {'name': 'C++', 'bytes': '425519'}, {'name': 'Lex', 'bytes': '919'}, {'name': 'Makefile', 'bytes': '14525'}, {'name': 'Objective-C', 'bytes': '2216'}, {'name': 'Python', 'bytes': '419'}, {'name': 'Shell', 'bytes': '1481'}, {'name': 'TeX', 'bytes': '30126'}, {'name': 'Yacc', 'bytes': '2858'}]}
package com.google.cloud.dataflow.sdk.transforms.windowing; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import com.google.cloud.dataflow.sdk.util.TriggerTester; import com.google.cloud.dataflow.sdk.util.TriggerTester.SimpleTriggerTester; import org.joda.time.Duration; import org.joda.time.Instant; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; /** * Tests for {@link Repeatedly}. */ @RunWith(JUnit4.class) public class RepeatedlyTest { @Mock private Trigger<IntervalWindow> mockTrigger; private SimpleTriggerTester<IntervalWindow> tester; private static Trigger<IntervalWindow>.TriggerContext anyTriggerContext() { return Mockito.<Trigger<IntervalWindow>.TriggerContext>any(); } public void setUp(WindowFn<Object, IntervalWindow> windowFn) throws Exception { MockitoAnnotations.initMocks(this); tester = TriggerTester.forTrigger(Repeatedly.forever(mockTrigger), windowFn); } /** * Tests that onElement correctly passes the data on to the subtrigger. */ @Test public void testOnElement() throws Exception { setUp(FixedWindows.of(Duration.millis(10))); tester.injectElements(37); verify(mockTrigger).onElement(Mockito.<Trigger<IntervalWindow>.OnElementContext>any()); } /** * Tests that the repeatedly is ready to fire whenever the subtrigger is ready. */ @Test public void testShouldFire() throws Exception { setUp(FixedWindows.of(Duration.millis(10))); when(mockTrigger.shouldFire(anyTriggerContext())).thenReturn(true); assertTrue(tester.shouldFire(new IntervalWindow(new Instant(0), new Instant(10)))); when(mockTrigger.shouldFire(Mockito.<Trigger<IntervalWindow>.TriggerContext>any())) .thenReturn(false); assertFalse(tester.shouldFire(new IntervalWindow(new Instant(0), new Instant(10)))); } /** * Tests that the watermark that guarantees firing is that of the subtrigger. */ @Test public void testFireDeadline() throws Exception { setUp(FixedWindows.of(Duration.millis(10))); IntervalWindow window = new IntervalWindow(new Instant(0), new Instant(10)); Instant arbitraryInstant = new Instant(34957849); when(mockTrigger.getWatermarkThatGuaranteesFiring(Mockito.<IntervalWindow>any())) .thenReturn(arbitraryInstant); assertThat( Repeatedly.forever(mockTrigger).getWatermarkThatGuaranteesFiring(window), equalTo(arbitraryInstant)); } @Test public void testContinuation() throws Exception { Trigger<IntervalWindow> trigger = AfterProcessingTime.pastFirstElementInPane(); Trigger<IntervalWindow> repeatedly = Repeatedly.forever(trigger); assertEquals( Repeatedly.forever(trigger.getContinuationTrigger()), repeatedly.getContinuationTrigger()); assertEquals( Repeatedly.forever(trigger.getContinuationTrigger().getContinuationTrigger()), repeatedly.getContinuationTrigger().getContinuationTrigger()); } @Test public void testShouldFireAfterMerge() throws Exception { tester = TriggerTester.forTrigger( Repeatedly.forever(AfterPane.<IntervalWindow>elementCountAtLeast(2)), Sessions.withGapDuration(Duration.millis(10))); tester.injectElements(1); IntervalWindow firstWindow = new IntervalWindow(new Instant(1), new Instant(11)); assertFalse(tester.shouldFire(firstWindow)); tester.injectElements(5); IntervalWindow secondWindow = new IntervalWindow(new Instant(5), new Instant(15)); assertFalse(tester.shouldFire(secondWindow)); // Merge them, if the merged window were on the second trigger, it would be ready tester.mergeWindows(); IntervalWindow mergedWindow = new IntervalWindow(new Instant(1), new Instant(15)); assertTrue(tester.shouldFire(mergedWindow)); } }
{'content_hash': '4e7da1ff68097f9185dca43f0f5793d9', 'timestamp': '', 'source': 'github', 'line_count': 114, 'max_line_length': 99, 'avg_line_length': 36.3421052631579, 'alnum_prop': 0.7579048998310403, 'repo_name': 'shakamunyi/beam', 'id': 'f445b52565ed5821db7a94fe15dbb13812bdfbe2', 'size': '4737', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'sdk/src/test/java/com/google/cloud/dataflow/sdk/transforms/windowing/RepeatedlyTest.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Go', 'bytes': '146134'}, {'name': 'Groovy', 'bytes': '3274'}, {'name': 'Java', 'bytes': '34540397'}, {'name': 'Protocol Buffer', 'bytes': '137365'}, {'name': 'Python', 'bytes': '4248665'}, {'name': 'Shell', 'bytes': '53893'}]}
<!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"> <title>Section 8.5.3: Analytic center of a set of linear inequalities</title> <link rel="canonical" href="http://cvxr.com/cvx/examples/cvxbook/Ch08_geometric_probs/html/analytic_center.html"> <link rel="stylesheet" href="../../../examples.css" type="text/css"> </head> <body> <div id="header"> <h1>Section 8.5.3: Analytic center of a set of linear inequalities</h1> Jump to:&nbsp;&nbsp;&nbsp;&nbsp; <a href="#source">Source code</a>&nbsp;&nbsp;&nbsp;&nbsp; <a href="#output">Text output</a> &nbsp;&nbsp;&nbsp;&nbsp; Plots &nbsp;&nbsp;&nbsp;&nbsp;<a href="../../../index.html">Library index</a> </div> <div id="content"> <a id="source"></a> <pre class="codeinput"> <span class="comment">% Boyd &amp; Vandenberghe "Convex Optimization"</span> <span class="comment">% Jo&Atilde;&laquo;lle Skaf - 04/29/08</span> <span class="comment">%</span> <span class="comment">% The analytic center of a set of linear inequalities and equalities:</span> <span class="comment">% a_i^Tx &lt;= b_i i=1,...,m,</span> <span class="comment">% Fx = g,</span> <span class="comment">% is the solution of the unconstrained minimization problem</span> <span class="comment">% minimize -sum_{i=1}^m log(b_i-a_i^Tx).</span> <span class="comment">% Input data</span> randn(<span class="string">'state'</span>, 0); rand(<span class="string">'state'</span>, 0); n = 10; m = 50; p = 5; tmp = randn(n,1); A = randn(m,n); b = A*tmp + 10*rand(m,1); F = randn(p,n); g = F*tmp; <span class="comment">% Analytic center</span> cvx_begin variable <span class="string">x(n)</span> minimize <span class="string">-sum(log(b-A*x))</span> F*x == g cvx_end disp([<span class="string">'The analytic center of the set of linear inequalities and '</span> <span class="keyword">...</span> <span class="string">'equalities is: '</span>]); disp(x); </pre> <a id="output"></a> <pre class="codeoutput"> Successive approximation method to be employed. SDPT3 will be called several times to refine the solution. Original size: 160 variables, 105 equality constraints 50 exponentials add 400 variables, 250 equality constraints ----------------------------------------------------------------- Cones | Errors | Mov/Act | Centering Exp cone Poly cone | Status --------+---------------------------------+--------- 50/ 50 | 2.435e+00 3.573e-01 0.000e+00 | Solved 50/ 50 | 1.982e-01 3.069e-03 0.000e+00 | Solved 49/ 49 | 2.535e-02 4.842e-05 0.000e+00 | Solved 11/ 46 | 1.342e-03 1.284e-07 0.000e+00 | Solved 0/ 6 | 1.582e-04 1.762e-09 0.000e+00 | Solved ----------------------------------------------------------------- Status: Solved Optimal value (cvx_optval): -64.8504 The analytic center of the set of linear inequalities and equalities is: -0.3618 -1.5333 0.1387 0.2491 -1.1163 1.3142 1.2303 -0.0511 0.4031 0.1248 </pre> </div> </body> </html>
{'content_hash': '0c71f3fbcb3e1c98ac69b18dbd1d592d', 'timestamp': '', 'source': 'github', 'line_count': 89, 'max_line_length': 127, 'avg_line_length': 33.640449438202246, 'alnum_prop': 0.6065464261857048, 'repo_name': 'pchrapka/brain-modelling', 'id': '21441ccf74c3419ee2c471ca8129f219bd70ed35', 'size': '2994', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'external/cvx/examples/cvxbook/Ch08_geometric_probs/html/analytic_center.html', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'Jupyter Notebook', 'bytes': '2265630'}, {'name': 'M', 'bytes': '2270'}, {'name': 'MATLAB', 'bytes': '1750479'}, {'name': 'Makefile', 'bytes': '305'}, {'name': 'Objective-C', 'bytes': '1122'}, {'name': 'Shell', 'bytes': '45091'}]}
<?php namespace LoadFooModule; use Zend\ModuleManager\ModuleManager; class Module { public function init(ModuleManager $moduleManager) { $moduleManager->loadModule('LoadBarModule'); } public function getConfig() { return array( 'bar' => 'foo', 'foo' => 'foo', ); } }
{'content_hash': '7aa212c2c7293138e081a7c12f24516a', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 54, 'avg_line_length': 15.636363636363637, 'alnum_prop': 0.5668604651162791, 'repo_name': 'stefanotorresi/zf2', 'id': 'c6387c693126717b78d3f39984e54599d8bd52f5', 'size': '646', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'tests/ZendTest/ModuleManager/TestAsset/LoadFooModule/Module.php', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'Groff', 'bytes': '310'}, {'name': 'HTML', 'bytes': '42752'}, {'name': 'PHP', 'bytes': '18959523'}, {'name': 'Shell', 'bytes': '1602'}]}
package com.intellij.ide.navigationToolbar; import com.intellij.ide.ui.UISettings; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.DumbAware; import com.intellij.openapi.project.Project; import com.intellij.util.ui.UIUtil; import java.awt.*; /** * @author Konstantin Bulenkov */ public class ShowNavBarAction extends AnAction implements DumbAware, PopupAction { @Override public void actionPerformed(AnActionEvent e){ final DataContext context = e.getDataContext(); final Project project = CommonDataKeys.PROJECT.getData(context); if (project != null) { UISettings uiSettings = UISettings.getInstance(); if (uiSettings.SHOW_NAVIGATION_BAR && !uiSettings.PRESENTATION_MODE){ new SelectInNavBarTarget(project).select(null, false); } else { final Component component = PlatformDataKeys.CONTEXT_COMPONENT.getData(context); if (!isInsideNavBar(component)) { final Editor editor = CommonDataKeys.EDITOR.getData(context); final NavBarPanel toolbarPanel = new NavBarPanel(project, false); toolbarPanel.showHint(editor, context); } } } } private static boolean isInsideNavBar(Component c) { return c == null || c instanceof NavBarPanel || UIUtil.getParentOfType(NavBarListWrapper.class, c) != null; } @Override public void update(final AnActionEvent e){ final boolean enabled = e.getData(CommonDataKeys.PROJECT) != null; e.getPresentation().setEnabled(enabled); } }
{'content_hash': 'c49f960622f72e93db9977d561c54730', 'timestamp': '', 'source': 'github', 'line_count': 49, 'max_line_length': 88, 'avg_line_length': 32.53061224489796, 'alnum_prop': 0.7151819322459222, 'repo_name': 'robovm/robovm-studio', 'id': '3e8c35cc26920b32ec8491096e2bd270a37d9b10', 'size': '2194', 'binary': False, 'copies': '52', 'ref': 'refs/heads/master', 'path': 'platform/lang-impl/src/com/intellij/ide/navigationToolbar/ShowNavBarAction.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AMPL', 'bytes': '20665'}, {'name': 'AspectJ', 'bytes': '182'}, {'name': 'Batchfile', 'bytes': '75274'}, {'name': 'C', 'bytes': '214180'}, {'name': 'C#', 'bytes': '1538'}, {'name': 'C++', 'bytes': '190028'}, {'name': 'CSS', 'bytes': '111474'}, {'name': 'CoffeeScript', 'bytes': '1759'}, {'name': 'Cucumber', 'bytes': '14382'}, {'name': 'Erlang', 'bytes': '10'}, {'name': 'FLUX', 'bytes': '57'}, {'name': 'Groff', 'bytes': '35232'}, {'name': 'Groovy', 'bytes': '2184274'}, {'name': 'HTML', 'bytes': '1726803'}, {'name': 'J', 'bytes': '5050'}, {'name': 'Java', 'bytes': '147025461'}, {'name': 'JavaScript', 'bytes': '125871'}, {'name': 'Jupyter Notebook', 'bytes': '92629'}, {'name': 'Kotlin', 'bytes': '451807'}, {'name': 'Lex', 'bytes': '166177'}, {'name': 'Makefile', 'bytes': '2352'}, {'name': 'NSIS', 'bytes': '130850'}, {'name': 'Objective-C', 'bytes': '28634'}, {'name': 'Perl6', 'bytes': '26'}, {'name': 'Protocol Buffer', 'bytes': '6570'}, {'name': 'Python', 'bytes': '21458826'}, {'name': 'Ruby', 'bytes': '1213'}, {'name': 'Scala', 'bytes': '11698'}, {'name': 'Shell', 'bytes': '73228'}, {'name': 'Smalltalk', 'bytes': '64'}, {'name': 'TeX', 'bytes': '60798'}, {'name': 'TypeScript', 'bytes': '6152'}, {'name': 'XSLT', 'bytes': '113040'}]}
@implementation UIViewController(LifeCycle) + (UIView *)spawn { return [[[self alloc] init] autorelease]; } + (UIViewController *)viewController { return [[[self alloc] init] autorelease]; } @end #endif // #if (TARGET_OS_IPHONE || TARGET_IPHONE_SIMULATOR)
{'content_hash': '4d051497df112b076efe9c63c4862a7d', 'timestamp': '', 'source': 'github', 'line_count': 15, 'max_line_length': 59, 'avg_line_length': 17.466666666666665, 'alnum_prop': 0.7061068702290076, 'repo_name': 'zztiswb116/BeeFramework', 'id': '00ed157982e11d23d364f4219d6522ae4b4d8c4d', 'size': '1700', 'binary': False, 'copies': '34', 'ref': 'refs/heads/master', 'path': 'framework/mvc/view/container/extension/UIViewController+LifeCycle.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '1356269'}, {'name': 'C++', 'bytes': '122306'}, {'name': 'Groff', 'bytes': '3123'}, {'name': 'M', 'bytes': '228686'}, {'name': 'Objective-C', 'bytes': '3419448'}, {'name': 'Objective-C++', 'bytes': '410195'}]}
package com.flipkart.poseidon.core; import java.util.HashMap; import java.util.Map; /** * Request level context where a request implies a single invocation of Lego. Implemented as a thread local which is * used to hold things like requestId, or other request level information to accessed by various elements in the call * stack. */ public class RequestContext { private static final ThreadLocal<Map<String, Object>> context = new ThreadLocal<Map<String, Object>>() { @Override protected Map<String, Object> initialValue() { return new HashMap<>(); } }; private static final ThreadLocal<Boolean> isImmutable = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; /** * initialize an empty request context, it will cleanup previous value of the threadlocal if used in a threadpool */ public static void initialize() { if (isImmutable.get()) { throw new UnsupportedOperationException(); } context.remove(); isImmutable.set(false); } /** * initialize a new request context with the given context, it will cleanup previous value of * the threadlocal if it is being used in a threadpool * * @param ctxt Context map */ public static void initialize(Map<String, Object> ctxt) { if (isImmutable.get()) { throw new UnsupportedOperationException(); } context.remove(); context.get().putAll(ctxt); isImmutable.set(true); } /** * Set's the value for a given key in the request context, this value will be accessible from the context * using the get method. * * @param key Key to set * @param value Value to set */ public static void set(String key, Object value) { if (isImmutable.get()) { throw new UnsupportedOperationException(); } context.get().put(key, value); } /** * Get's the value for a given key from the request context. * * @param key Key to get * @return {@link Object} - Value for given key */ public static <T> T get(String key) { return (T) context.get().get(key); } /** * Get's a snapshot of the request context as a a Map * * @return context map */ public static Map<String, Object> getContextMap() { return new HashMap<>(context.get()); } /** * Shuts down the request context by cleaning up the threadlocal. */ public static void shutDown() { context.remove(); isImmutable.remove(); } }
{'content_hash': 'd2f1716f7c3d92057cf4c642d99cc8ea', 'timestamp': '', 'source': 'github', 'line_count': 100, 'max_line_length': 117, 'avg_line_length': 26.99, 'alnum_prop': 0.6102260096331975, 'repo_name': 'flipkart-incubator/Poseidon', 'id': '5248e98732f768d891ecbd034a9c1e405374289f', 'size': '3305', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/src/main/java/com/flipkart/poseidon/core/RequestContext.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '682398'}]}
from __future__ import print_function # force // operator to be integer division in Python 2 from __future__ import division import argparse import json import os import subprocess import sys TOOLS_PATH = os.path.dirname(os.path.realpath(__file__)) BASE_PATH = os.path.join(TOOLS_PATH, '..') FLAG_CLEAN = '--clean' FLAG_DEBUG = '--debug' FLAG_HEAPLIMIT = '--mem-heap' JERRY_BUILDER = os.path.join(BASE_PATH, 'tools', 'build.py') JERRY_BIN = os.path.join(BASE_PATH, 'build', 'bin', 'jerry') TEST_DIR = os.path.join(BASE_PATH, 'tests') def get_args(): """ Parse input arguments. """ desc = 'Finds the smallest possible JerryHeap size without failing to run the given js file' parser = argparse.ArgumentParser(description=desc) parser.add_argument('testfile') parser.add_argument('--heapsize', type=int, default=512, help='set the limit of the first heapsize (default: %(default)d)') parser.add_argument('--buildtype', choices=['release', 'debug'], default='release', help='select build type (default: %(default)s)') script_args = parser.parse_args() return script_args def check_files(opts): files = [JERRY_BUILDER, opts.testfile] for _file in files: if not os.path.isfile(_file): sys.exit("File not found: %s" % _file) def build_bin(heapsize, opts): """ Run tools/build.py script """ command = [ JERRY_BUILDER, FLAG_CLEAN, FLAG_HEAPLIMIT, str(heapsize) ] if opts.buildtype == 'debug': command.append(FLAG_DEBUG) print('Building JerryScript with: %s' % (' '.join(command))) subprocess.check_output(command) def run_test(opts): """ Run the testfile to get the exitcode. """ try: testfile = os.path.abspath(opts.testfile) run_cmd = [JERRY_BIN, testfile] # check output will raise an error if the exit code is not 0 subprocess.check_output(run_cmd, cwd=TEST_DIR) except subprocess.CalledProcessError as err: return err.returncode return 0 def heap_limit(opts): """ Find the minimal size of jerryheap to pass """ goodheap = opts.heapsize lowheap = 0 hiheap = opts.heapsize while lowheap < hiheap: build_bin(hiheap, opts) assert os.path.isfile(JERRY_BIN), 'Jerry binary file does not exists' exitcode = run_test(opts) if exitcode != 0: lowheap = hiheap hiheap = (lowheap + goodheap) // 2 else: goodheap = hiheap hiheap = (lowheap + hiheap) // 2 return { 'testfile': opts.testfile, 'heaplimit to pass': goodheap } def main(options): check_files(options) result = heap_limit(options) print(json.dumps(result, indent=4)) if __name__ == "__main__": main(get_args())
{'content_hash': '943ab67ae7a81018fbfc6c3677f414b5', 'timestamp': '', 'source': 'github', 'line_count': 104, 'max_line_length': 96, 'avg_line_length': 27.46153846153846, 'alnum_prop': 0.6207983193277311, 'repo_name': 'yichoi/jerryscript', 'id': '35ab42d8db58934e984bd7012c60f501406e4ef5', 'size': '3495', 'binary': False, 'copies': '11', 'ref': 'refs/heads/master', 'path': 'tools/heaplimit_measure.py', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'Assembly', 'bytes': '6519'}, {'name': 'Batchfile', 'bytes': '1898'}, {'name': 'C', 'bytes': '3320703'}, {'name': 'C++', 'bytes': '252504'}, {'name': 'CMake', 'bytes': '50175'}, {'name': 'JavaScript', 'bytes': '1674779'}, {'name': 'Makefile', 'bytes': '17988'}, {'name': 'Python', 'bytes': '154989'}, {'name': 'Shell', 'bytes': '55868'}, {'name': 'Tcl', 'bytes': '45226'}]}
(function () { /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return function cachedFn (str) { var key = isPrimitive(str) ? str : JSON.stringify(str); var hit = cache[key]; return hit || (cache[key] = fn(str)) } } /** * Hyphenate a camelCase string. */ var hyphenate = cached(function (str) { return str.replace(/([A-Z])/g, function (m) { return '-' + m.toLowerCase(); }) }); /** * Simple Object.assign polyfill */ var merge = Object.assign || function (to) { var arguments$1 = arguments; var hasOwn = Object.prototype.hasOwnProperty; for (var i = 1; i < arguments.length; i++) { var from = Object(arguments$1[i]); for (var key in from) { if (hasOwn.call(from, key)) { to[key] = from[key]; } } } return to }; /** * Check if value is primitive */ function isPrimitive (value) { return typeof value === 'string' || typeof value === 'number' } /** * Perform no operation. */ function noop () {} /** * Check if value is function */ function isFn (obj) { return typeof obj === 'function' } var config = merge( { el: '#app', repo: '', maxLevel: 6, subMaxLevel: 0, loadSidebar: null, loadNavbar: null, homepage: 'README.md', coverpage: '', basePath: '', auto2top: false, name: '', themeColor: '', nameLink: window.location.pathname, autoHeader: false, executeScript: null, noEmoji: false, ga: '', ext: '.md', mergeNavbar: false, formatUpdated: '', externalLinkTarget: '_blank', routerMode: 'hash', noCompileLinks: [] }, window.$docsify ); var script = document.currentScript || [].slice .call(document.getElementsByTagName('script')) .filter(function (n) { return /docsify\./.test(n.src); })[0]; if (script) { for (var prop in config) { var val = script.getAttribute('data-' + hyphenate(prop)); if (isPrimitive(val)) { config[prop] = val === '' ? true : val; } } if (config.loadSidebar === true) { config.loadSidebar = '_sidebar' + config.ext; } if (config.loadNavbar === true) { config.loadNavbar = '_navbar' + config.ext; } if (config.coverpage === true) { config.coverpage = '_coverpage' + config.ext; } if (config.repo === true) { config.repo = ''; } if (config.name === true) { config.name = ''; } } window.$docsify = config; function initLifecycle (vm) { var hooks = [ 'init', 'mounted', 'beforeEach', 'afterEach', 'doneEach', 'ready' ]; vm._hooks = {}; vm._lifecycle = {}; hooks.forEach(function (hook) { var arr = (vm._hooks[hook] = []); vm._lifecycle[hook] = function (fn) { return arr.push(fn); }; }); } function callHook (vm, hook, data, next) { if ( next === void 0 ) next = noop; var queue = vm._hooks[hook]; var step = function (index) { var hook = queue[index]; if (index >= queue.length) { next(data); } else { if (typeof hook === 'function') { if (hook.length === 2) { hook(data, function (result) { data = result; step(index + 1); }); } else { var result = hook(data); data = result !== undefined ? result : data; step(index + 1); } } else { step(index + 1); } } }; step(0); } var inBrowser = !false; var isMobile = inBrowser && document.body.clientWidth <= 600; /** * @see https://github.com/MoOx/pjax/blob/master/lib/is-supported.js */ var supportsPushState = inBrowser && (function () { // Borrowed wholesale from https://github.com/defunkt/jquery-pjax return ( window.history && window.history.pushState && window.history.replaceState && // pushState isn’t reliable on iOS until 5. !navigator.userAgent.match( /((iPod|iPhone|iPad).+\bOS\s+[1-4]\D|WebApps\/.+CFNetwork)/ ) ) })(); var cacheNode = {}; /** * Get Node * @param {String|Element} el * @param {Boolean} noCache * @return {Element} */ function getNode (el, noCache) { if ( noCache === void 0 ) noCache = false; if (typeof el === 'string') { if (typeof window.Vue !== 'undefined') { return find(el) } el = noCache ? find(el) : cacheNode[el] || (cacheNode[el] = find(el)); } return el } var $ = inBrowser && document; var body = inBrowser && $.body; var head = inBrowser && $.head; /** * Find element * @example * find('nav') => document.querySelector('nav') * find(nav, 'a') => nav.querySelector('a') */ function find (el, node) { return node ? el.querySelector(node) : $.querySelector(el) } /** * Find all elements * @example * findAll('a') => [].slice.call(document.querySelectorAll('a')) * findAll(nav, 'a') => [].slice.call(nav.querySelectorAll('a')) */ function findAll (el, node) { return [].slice.call( node ? el.querySelectorAll(node) : $.querySelectorAll(el) ) } function create (node, tpl) { node = $.createElement(node); if (tpl) { node.innerHTML = tpl; } return node } function appendTo (target, el) { return target.appendChild(el) } function before (target, el) { return target.insertBefore(el, target.children[0]) } function on (el, type, handler) { isFn(type) ? window.addEventListener(el, type) : el.addEventListener(type, handler); } function off (el, type, handler) { isFn(type) ? window.removeEventListener(el, type) : el.removeEventListener(type, handler); } /** * Toggle class * * @example * toggleClass(el, 'active') => el.classList.toggle('active') * toggleClass(el, 'add', 'active') => el.classList.add('active') */ function toggleClass (el, type, val) { el && el.classList[val ? type : 'toggle'](val || type); } function style (content) { appendTo(head, create('style', content)); } var dom = Object.freeze({ getNode: getNode, $: $, body: body, head: head, find: find, findAll: findAll, create: create, appendTo: appendTo, before: before, on: on, off: off, toggleClass: toggleClass, style: style }); /** * Render github corner * @param {Object} data * @return {String} */ function corner (data) { if (!data) { return '' } if (!/\/\//.test(data)) { data = 'https://github.com/' + data; } data = data.replace(/^git\+/, ''); return ( "<a href=\"" + data + "\" class=\"github-corner\" aria-label=\"View source on Github\">" + '<svg viewBox="0 0 250 250" aria-hidden="true">' + '<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>' + '<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>' + '<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path>' + '</svg>' + '</a>' ) } /** * Render main content */ function main (config) { var aside = '<button class="sidebar-toggle">' + '<div class="sidebar-toggle-button">' + '<span></span><span></span><span></span>' + '</div>' + '</button>' + '<aside class="sidebar">' + (config.name ? ("<h1><a class=\"app-name-link\" data-nosearch>" + (config.name) + "</a></h1>") : '') + '<div class="sidebar-nav"><!--sidebar--></div>' + '</aside>'; return ( (isMobile ? (aside + "<main>") : ("<main>" + aside)) + '<section class="content">' + '<article class="markdown-section" id="main"><!--main--></article>' + '</section>' + '</main>' ) } /** * Cover Page */ function cover () { var SL = ', 100%, 85%'; var bgc = 'linear-gradient(to left bottom, ' + "hsl(" + (Math.floor(Math.random() * 255) + SL) + ") 0%," + "hsl(" + (Math.floor(Math.random() * 255) + SL) + ") 100%)"; return ( "<section class=\"cover show\" style=\"background: " + bgc + "\">" + '<div class="cover-main"><!--cover--></div>' + '<div class="mask"></div>' + '</section>' ) } /** * Render tree * @param {Array} tree * @param {String} tpl * @return {String} */ function tree (toc, tpl) { if ( tpl === void 0 ) tpl = ''; if (!toc || !toc.length) { return '' } toc.forEach(function (node) { tpl += "<li><a class=\"section-link\" href=\"" + (node.slug) + "\">" + (node.title) + "</a></li>"; if (node.children) { tpl += "<li><ul class=\"children\">" + (tree(node.children)) + "</li></ul>"; } }); return tpl } function helper (className, content) { return ("<p class=\"" + className + "\">" + (content.slice(5).trim()) + "</p>") } function theme (color) { return ("<style>:root{--theme-color: " + color + ";}</style>") } var barEl; var timeId; /** * Init progress component */ function init () { var div = create('div'); div.classList.add('progress'); appendTo(body, div); barEl = div; } /** * Render progress bar */ function progressbar (ref) { var loaded = ref.loaded; var total = ref.total; var step = ref.step; var num; !barEl && init(); if (step) { num = parseInt(barEl.style.width || 0, 10) + step; num = num > 80 ? 80 : num; } else { num = Math.floor(loaded / total * 100); } barEl.style.opacity = 1; barEl.style.width = num >= 95 ? '100%' : num + '%'; if (num >= 95) { clearTimeout(timeId); timeId = setTimeout(function (_) { barEl.style.opacity = 0; barEl.style.width = '0%'; }, 200); } } var cache = {}; /** * Simple ajax get * @param {string} url * @param {boolean} [hasBar=false] has progress bar * @return { then(resolve, reject), abort } */ function get (url, hasBar, headers) { if ( hasBar === void 0 ) hasBar = false; if ( headers === void 0 ) headers = {}; var xhr = new XMLHttpRequest(); var on = function () { xhr.addEventListener.apply(xhr, arguments); }; var cached$$1 = cache[url]; if (cached$$1) { return { then: function (cb) { return cb(cached$$1.content, cached$$1.opt); }, abort: noop } } xhr.open('GET', url); for (var i in headers) { xhr.setRequestHeader(i, headers[i]); } xhr.send(); return { then: function (success, error) { if ( error === void 0 ) error = noop; if (hasBar) { var id = setInterval( function (_) { return progressbar({ step: Math.floor(Math.random() * 5 + 1) }); }, 500 ); on('progress', progressbar); on('loadend', function (evt) { progressbar(evt); clearInterval(id); }); } on('error', error); on('load', function (ref) { var target = ref.target; if (target.status >= 400) { error(target); } else { var result = (cache[url] = { content: target.response, opt: { updatedAt: xhr.getResponseHeader('last-modified') } }); success(result.content, result.opt); } }); }, abort: function (_) { return xhr.readyState !== 4 && xhr.abort(); } } } function replaceVar (block, color) { block.innerHTML = block.innerHTML.replace( /var\(\s*--theme-color.*?\)/g, color ); } function cssVars (color) { // Variable support if (window.CSS && window.CSS.supports && window.CSS.supports('(--v:red)')) { return } var styleBlocks = findAll('style:not(.inserted),link');[].forEach.call(styleBlocks, function (block) { if (block.nodeName === 'STYLE') { replaceVar(block, color); } else if (block.nodeName === 'LINK') { var href = block.getAttribute('href'); if (!/\.css$/.test(href)) { return } get(href).then(function (res) { var style$$1 = create('style', res); head.appendChild(style$$1); replaceVar(style$$1, color); }); } }); } var RGX = /([^{]*?)\w(?=\})/g; var dict = { YYYY: 'getFullYear', YY: 'getYear', MM: function (d) { return d.getMonth() + 1; }, DD: 'getDate', HH: 'getHours', mm: 'getMinutes', ss: 'getSeconds' }; function tinydate (str) { var parts=[], offset=0; str.replace(RGX, function (key, _, idx) { // save preceding string parts.push(str.substring(offset, idx - 1)); offset = idx += key.length + 1; // save function parts.push(function(d){ return ('00' + (typeof dict[key]==='string' ? d[dict[key]]() : dict[key](d))).slice(-key.length); }); }); if (offset !== str.length) { parts.push(str.substring(offset)); } return function (arg) { var out='', i=0, d=arg||new Date(); for (; i<parts.length; i++) { out += (typeof parts[i]==='string') ? parts[i] : parts[i](d); } return out; }; } var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var marked = createCommonjsModule(function (module, exports) { /** * marked - a markdown parser * Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed) * https://github.com/chjj/marked */ (function() { var block = { newline: /^\n+/, code: /^( {4}[^\n]+\n*)+/, fences: noop, hr: /^( *[-*_]){3,} *(?:\n+|$)/, heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/, nptable: noop, lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/, blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/, list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/, html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/, def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/, table: noop, paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/, text: /^[^\n]+/ }; block.bullet = /(?:[*+-]|\d+\.)/; block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/; block.item = replace(block.item, 'gm') (/bull/g, block.bullet) (); block.list = replace(block.list) (/bull/g, block.bullet) ('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))') ('def', '\\n+(?=' + block.def.source + ')') (); block.blockquote = replace(block.blockquote) ('def', block.def) (); block._tag = '(?!(?:' + 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code' + '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo' + '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b'; block.html = replace(block.html) ('comment', /<!--[\s\S]*?-->/) ('closed', /<(tag)[\s\S]+?<\/\1>/) ('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/) (/tag/g, block._tag) (); block.paragraph = replace(block.paragraph) ('hr', block.hr) ('heading', block.heading) ('lheading', block.lheading) ('blockquote', block.blockquote) ('tag', '<' + block._tag) ('def', block.def) (); /** * Normal Block Grammar */ block.normal = merge({}, block); /** * GFM Block Grammar */ block.gfm = merge({}, block.normal, { fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]*?)\s*\1 *(?:\n+|$)/, paragraph: /^/, heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/ }); block.gfm.paragraph = replace(block.paragraph) ('(?!', '(?!' + block.gfm.fences.source.replace('\\1', '\\2') + '|' + block.list.source.replace('\\1', '\\3') + '|') (); /** * GFM + Tables Block Grammar */ block.tables = merge({}, block.gfm, { nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/, table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/ }); /** * Block Lexer */ function Lexer(options) { this.tokens = []; this.tokens.links = {}; this.options = options || marked.defaults; this.rules = block.normal; if (this.options.gfm) { if (this.options.tables) { this.rules = block.tables; } else { this.rules = block.gfm; } } } /** * Expose Block Rules */ Lexer.rules = block; /** * Static Lex Method */ Lexer.lex = function(src, options) { var lexer = new Lexer(options); return lexer.lex(src); }; /** * Preprocessing */ Lexer.prototype.lex = function(src) { src = src .replace(/\r\n|\r/g, '\n') .replace(/\t/g, ' ') .replace(/\u00a0/g, ' ') .replace(/\u2424/g, '\n'); return this.token(src, true); }; /** * Lexing */ Lexer.prototype.token = function(src, top, bq) { var this$1 = this; var src = src.replace(/^ +$/gm, '') , next , loose , cap , bull , b , item , space , i , l; while (src) { // newline if (cap = this$1.rules.newline.exec(src)) { src = src.substring(cap[0].length); if (cap[0].length > 1) { this$1.tokens.push({ type: 'space' }); } } // code if (cap = this$1.rules.code.exec(src)) { src = src.substring(cap[0].length); cap = cap[0].replace(/^ {4}/gm, ''); this$1.tokens.push({ type: 'code', text: !this$1.options.pedantic ? cap.replace(/\n+$/, '') : cap }); continue; } // fences (gfm) if (cap = this$1.rules.fences.exec(src)) { src = src.substring(cap[0].length); this$1.tokens.push({ type: 'code', lang: cap[2], text: cap[3] || '' }); continue; } // heading if (cap = this$1.rules.heading.exec(src)) { src = src.substring(cap[0].length); this$1.tokens.push({ type: 'heading', depth: cap[1].length, text: cap[2] }); continue; } // table no leading pipe (gfm) if (top && (cap = this$1.rules.nptable.exec(src))) { src = src.substring(cap[0].length); item = { type: 'table', header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3].replace(/\n$/, '').split('\n') }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i].split(/ *\| */); } this$1.tokens.push(item); continue; } // lheading if (cap = this$1.rules.lheading.exec(src)) { src = src.substring(cap[0].length); this$1.tokens.push({ type: 'heading', depth: cap[2] === '=' ? 1 : 2, text: cap[1] }); continue; } // hr if (cap = this$1.rules.hr.exec(src)) { src = src.substring(cap[0].length); this$1.tokens.push({ type: 'hr' }); continue; } // blockquote if (cap = this$1.rules.blockquote.exec(src)) { src = src.substring(cap[0].length); this$1.tokens.push({ type: 'blockquote_start' }); cap = cap[0].replace(/^ *> ?/gm, ''); // Pass `top` to keep the current // "toplevel" state. This is exactly // how markdown.pl works. this$1.token(cap, top, true); this$1.tokens.push({ type: 'blockquote_end' }); continue; } // list if (cap = this$1.rules.list.exec(src)) { src = src.substring(cap[0].length); bull = cap[2]; this$1.tokens.push({ type: 'list_start', ordered: bull.length > 1 }); // Get each top-level item. cap = cap[0].match(this$1.rules.item); next = false; l = cap.length; i = 0; for (; i < l; i++) { item = cap[i]; // Remove the list item's bullet // so it is seen as the next token. space = item.length; item = item.replace(/^ *([*+-]|\d+\.) +/, ''); // Outdent whatever the // list item contains. Hacky. if (~item.indexOf('\n ')) { space -= item.length; item = !this$1.options.pedantic ? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '') : item.replace(/^ {1,4}/gm, ''); } // Determine whether the next list item belongs here. // Backpedal if it does not belong in this list. if (this$1.options.smartLists && i !== l - 1) { b = block.bullet.exec(cap[i + 1])[0]; if (bull !== b && !(bull.length > 1 && b.length > 1)) { src = cap.slice(i + 1).join('\n') + src; i = l - 1; } } // Determine whether item is loose or not. // Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/ // for discount behavior. loose = next || /\n\n(?!\s*$)/.test(item); if (i !== l - 1) { next = item.charAt(item.length - 1) === '\n'; if (!loose) { loose = next; } } this$1.tokens.push({ type: loose ? 'loose_item_start' : 'list_item_start' }); // Recurse. this$1.token(item, false, bq); this$1.tokens.push({ type: 'list_item_end' }); } this$1.tokens.push({ type: 'list_end' }); continue; } // html if (cap = this$1.rules.html.exec(src)) { src = src.substring(cap[0].length); this$1.tokens.push({ type: this$1.options.sanitize ? 'paragraph' : 'html', pre: !this$1.options.sanitizer && (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'), text: cap[0] }); continue; } // def if ((!bq && top) && (cap = this$1.rules.def.exec(src))) { src = src.substring(cap[0].length); this$1.tokens.links[cap[1].toLowerCase()] = { href: cap[2], title: cap[3] }; continue; } // table (gfm) if (top && (cap = this$1.rules.table.exec(src))) { src = src.substring(cap[0].length); item = { type: 'table', header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */), align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */), cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n') }; for (i = 0; i < item.align.length; i++) { if (/^ *-+: *$/.test(item.align[i])) { item.align[i] = 'right'; } else if (/^ *:-+: *$/.test(item.align[i])) { item.align[i] = 'center'; } else if (/^ *:-+ *$/.test(item.align[i])) { item.align[i] = 'left'; } else { item.align[i] = null; } } for (i = 0; i < item.cells.length; i++) { item.cells[i] = item.cells[i] .replace(/^ *\| *| *\| *$/g, '') .split(/ *\| */); } this$1.tokens.push(item); continue; } // top-level paragraph if (top && (cap = this$1.rules.paragraph.exec(src))) { src = src.substring(cap[0].length); this$1.tokens.push({ type: 'paragraph', text: cap[1].charAt(cap[1].length - 1) === '\n' ? cap[1].slice(0, -1) : cap[1] }); continue; } // text if (cap = this$1.rules.text.exec(src)) { // Top-level should never reach here. src = src.substring(cap[0].length); this$1.tokens.push({ type: 'text', text: cap[0] }); continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return this.tokens; }; /** * Inline-Level Grammar */ var inline = { escape: /^\\([\\`*{}\[\]()#+\-.!_>])/, autolink: /^<([^ <>]+(@|:\/)[^ <>]+)>/, url: noop, tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^<'">])*?>/, link: /^!?\[(inside)\]\(href\)/, reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/, nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/, strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/, em: /^\b_((?:[^_]|__)+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/, code: /^(`+)([\s\S]*?[^`])\1(?!`)/, br: /^ {2,}\n(?!\s*$)/, del: noop, text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/ }; inline._inside = /(?:\[[^\]]*\]|\\[\[\]]|[^\[\]]|\](?=[^\[]*\]))*/; inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/; inline.link = replace(inline.link) ('inside', inline._inside) ('href', inline._href) (); inline.reflink = replace(inline.reflink) ('inside', inline._inside) (); /** * Normal Inline Grammar */ inline.normal = merge({}, inline); /** * Pedantic Inline Grammar */ inline.pedantic = merge({}, inline.normal, { strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/, em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/ }); /** * GFM Inline Grammar */ inline.gfm = merge({}, inline.normal, { escape: replace(inline.escape)('])', '~|])')(), url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/, del: /^~~(?=\S)([\s\S]*?\S)~~/, text: replace(inline.text) (']|', '~]|') ('|', '|https?://|') () }); /** * GFM + Line Breaks Inline Grammar */ inline.breaks = merge({}, inline.gfm, { br: replace(inline.br)('{2,}', '*')(), text: replace(inline.gfm.text)('{2,}', '*')() }); /** * Inline Lexer & Compiler */ function InlineLexer(links, options) { this.options = options || marked.defaults; this.links = links; this.rules = inline.normal; this.renderer = this.options.renderer || new Renderer; this.renderer.options = this.options; if (!this.links) { throw new Error('Tokens array requires a `links` property.'); } if (this.options.gfm) { if (this.options.breaks) { this.rules = inline.breaks; } else { this.rules = inline.gfm; } } else if (this.options.pedantic) { this.rules = inline.pedantic; } } /** * Expose Inline Rules */ InlineLexer.rules = inline; /** * Static Lexing/Compiling Method */ InlineLexer.output = function(src, links, options) { var inline = new InlineLexer(links, options); return inline.output(src); }; /** * Lexing/Compiling */ InlineLexer.prototype.output = function(src) { var this$1 = this; var out = '' , link , text , href , cap; while (src) { // escape if (cap = this$1.rules.escape.exec(src)) { src = src.substring(cap[0].length); out += cap[1]; continue; } // autolink if (cap = this$1.rules.autolink.exec(src)) { src = src.substring(cap[0].length); if (cap[2] === '@') { text = escape( cap[1].charAt(6) === ':' ? this$1.mangle(cap[1].substring(7)) : this$1.mangle(cap[1]) ); href = this$1.mangle('mailto:') + text; } else { text = escape(cap[1]); href = text; } out += this$1.renderer.link(href, null, text); continue; } // url (gfm) if (!this$1.inLink && (cap = this$1.rules.url.exec(src))) { src = src.substring(cap[0].length); text = escape(cap[1]); href = text; out += this$1.renderer.link(href, null, text); continue; } // tag if (cap = this$1.rules.tag.exec(src)) { if (!this$1.inLink && /^<a /i.test(cap[0])) { this$1.inLink = true; } else if (this$1.inLink && /^<\/a>/i.test(cap[0])) { this$1.inLink = false; } src = src.substring(cap[0].length); out += this$1.options.sanitize ? this$1.options.sanitizer ? this$1.options.sanitizer(cap[0]) : escape(cap[0]) : cap[0]; continue; } // link if (cap = this$1.rules.link.exec(src)) { src = src.substring(cap[0].length); this$1.inLink = true; out += this$1.outputLink(cap, { href: cap[2], title: cap[3] }); this$1.inLink = false; continue; } // reflink, nolink if ((cap = this$1.rules.reflink.exec(src)) || (cap = this$1.rules.nolink.exec(src))) { src = src.substring(cap[0].length); link = (cap[2] || cap[1]).replace(/\s+/g, ' '); link = this$1.links[link.toLowerCase()]; if (!link || !link.href) { out += cap[0].charAt(0); src = cap[0].substring(1) + src; continue; } this$1.inLink = true; out += this$1.outputLink(cap, link); this$1.inLink = false; continue; } // strong if (cap = this$1.rules.strong.exec(src)) { src = src.substring(cap[0].length); out += this$1.renderer.strong(this$1.output(cap[2] || cap[1])); continue; } // em if (cap = this$1.rules.em.exec(src)) { src = src.substring(cap[0].length); out += this$1.renderer.em(this$1.output(cap[2] || cap[1])); continue; } // code if (cap = this$1.rules.code.exec(src)) { src = src.substring(cap[0].length); out += this$1.renderer.codespan(escape(cap[2].trim(), true)); continue; } // br if (cap = this$1.rules.br.exec(src)) { src = src.substring(cap[0].length); out += this$1.renderer.br(); continue; } // del (gfm) if (cap = this$1.rules.del.exec(src)) { src = src.substring(cap[0].length); out += this$1.renderer.del(this$1.output(cap[1])); continue; } // text if (cap = this$1.rules.text.exec(src)) { src = src.substring(cap[0].length); out += this$1.renderer.text(escape(this$1.smartypants(cap[0]))); continue; } if (src) { throw new Error('Infinite loop on byte: ' + src.charCodeAt(0)); } } return out; }; /** * Compile Link */ InlineLexer.prototype.outputLink = function(cap, link) { var href = escape(link.href) , title = link.title ? escape(link.title) : null; return cap[0].charAt(0) !== '!' ? this.renderer.link(href, title, this.output(cap[1])) : this.renderer.image(href, title, escape(cap[1])); }; /** * Smartypants Transformations */ InlineLexer.prototype.smartypants = function(text) { if (!this.options.smartypants) { return text; } return text // em-dashes .replace(/---/g, '\u2014') // en-dashes .replace(/--/g, '\u2013') // opening singles .replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018') // closing singles & apostrophes .replace(/'/g, '\u2019') // opening doubles .replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c') // closing doubles .replace(/"/g, '\u201d') // ellipses .replace(/\.{3}/g, '\u2026'); }; /** * Mangle Links */ InlineLexer.prototype.mangle = function(text) { if (!this.options.mangle) { return text; } var out = '' , l = text.length , i = 0 , ch; for (; i < l; i++) { ch = text.charCodeAt(i); if (Math.random() > 0.5) { ch = 'x' + ch.toString(16); } out += '&#' + ch + ';'; } return out; }; /** * Renderer */ function Renderer(options) { this.options = options || {}; } Renderer.prototype.code = function(code, lang, escaped) { if (this.options.highlight) { var out = this.options.highlight(code, lang); if (out != null && out !== code) { escaped = true; code = out; } } if (!lang) { return '<pre><code>' + (escaped ? code : escape(code, true)) + '\n</code></pre>'; } return '<pre><code class="' + this.options.langPrefix + escape(lang, true) + '">' + (escaped ? code : escape(code, true)) + '\n</code></pre>\n'; }; Renderer.prototype.blockquote = function(quote) { return '<blockquote>\n' + quote + '</blockquote>\n'; }; Renderer.prototype.html = function(html) { return html; }; Renderer.prototype.heading = function(text, level, raw) { return '<h' + level + ' id="' + this.options.headerPrefix + raw.toLowerCase().replace(/[^\w]+/g, '-') + '">' + text + '</h' + level + '>\n'; }; Renderer.prototype.hr = function() { return this.options.xhtml ? '<hr/>\n' : '<hr>\n'; }; Renderer.prototype.list = function(body, ordered) { var type = ordered ? 'ol' : 'ul'; return '<' + type + '>\n' + body + '</' + type + '>\n'; }; Renderer.prototype.listitem = function(text) { return '<li>' + text + '</li>\n'; }; Renderer.prototype.paragraph = function(text) { return '<p>' + text + '</p>\n'; }; Renderer.prototype.table = function(header, body) { return '<table>\n' + '<thead>\n' + header + '</thead>\n' + '<tbody>\n' + body + '</tbody>\n' + '</table>\n'; }; Renderer.prototype.tablerow = function(content) { return '<tr>\n' + content + '</tr>\n'; }; Renderer.prototype.tablecell = function(content, flags) { var type = flags.header ? 'th' : 'td'; var tag = flags.align ? '<' + type + ' style="text-align:' + flags.align + '">' : '<' + type + '>'; return tag + content + '</' + type + '>\n'; }; // span level renderer Renderer.prototype.strong = function(text) { return '<strong>' + text + '</strong>'; }; Renderer.prototype.em = function(text) { return '<em>' + text + '</em>'; }; Renderer.prototype.codespan = function(text) { return '<code>' + text + '</code>'; }; Renderer.prototype.br = function() { return this.options.xhtml ? '<br/>' : '<br>'; }; Renderer.prototype.del = function(text) { return '<del>' + text + '</del>'; }; Renderer.prototype.link = function(href, title, text) { if (this.options.sanitize) { try { var prot = decodeURIComponent(unescape(href)) .replace(/[^\w:]/g, '') .toLowerCase(); } catch (e) { return text; } if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0 || prot.indexOf('data:') === 0) { return text; } } if (this.options.baseUrl && !originIndependentUrl.test(href)) { href = resolveUrl(this.options.baseUrl, href); } var out = '<a href="' + href + '"'; if (title) { out += ' title="' + title + '"'; } out += '>' + text + '</a>'; return out; }; Renderer.prototype.image = function(href, title, text) { if (this.options.baseUrl && !originIndependentUrl.test(href)) { href = resolveUrl(this.options.baseUrl, href); } var out = '<img src="' + href + '" alt="' + text + '"'; if (title) { out += ' title="' + title + '"'; } out += this.options.xhtml ? '/>' : '>'; return out; }; Renderer.prototype.text = function(text) { return text; }; /** * Parsing & Compiling */ function Parser(options) { this.tokens = []; this.token = null; this.options = options || marked.defaults; this.options.renderer = this.options.renderer || new Renderer; this.renderer = this.options.renderer; this.renderer.options = this.options; } /** * Static Parse Method */ Parser.parse = function(src, options, renderer) { var parser = new Parser(options, renderer); return parser.parse(src); }; /** * Parse Loop */ Parser.prototype.parse = function(src) { var this$1 = this; this.inline = new InlineLexer(src.links, this.options, this.renderer); this.tokens = src.reverse(); var out = ''; while (this.next()) { out += this$1.tok(); } return out; }; /** * Next Token */ Parser.prototype.next = function() { return this.token = this.tokens.pop(); }; /** * Preview Next Token */ Parser.prototype.peek = function() { return this.tokens[this.tokens.length - 1] || 0; }; /** * Parse Text Tokens */ Parser.prototype.parseText = function() { var this$1 = this; var body = this.token.text; while (this.peek().type === 'text') { body += '\n' + this$1.next().text; } return this.inline.output(body); }; /** * Parse Current Token */ Parser.prototype.tok = function() { var this$1 = this; switch (this.token.type) { case 'space': { return ''; } case 'hr': { return this.renderer.hr(); } case 'heading': { return this.renderer.heading( this.inline.output(this.token.text), this.token.depth, this.token.text); } case 'code': { return this.renderer.code(this.token.text, this.token.lang, this.token.escaped); } case 'table': { var header = '' , body = '' , i , row , cell , flags , j; // header cell = ''; for (i = 0; i < this.token.header.length; i++) { flags = { header: true, align: this$1.token.align[i] }; cell += this$1.renderer.tablecell( this$1.inline.output(this$1.token.header[i]), { header: true, align: this$1.token.align[i] } ); } header += this.renderer.tablerow(cell); for (i = 0; i < this.token.cells.length; i++) { row = this$1.token.cells[i]; cell = ''; for (j = 0; j < row.length; j++) { cell += this$1.renderer.tablecell( this$1.inline.output(row[j]), { header: false, align: this$1.token.align[j] } ); } body += this$1.renderer.tablerow(cell); } return this.renderer.table(header, body); } case 'blockquote_start': { var body = ''; while (this.next().type !== 'blockquote_end') { body += this$1.tok(); } return this.renderer.blockquote(body); } case 'list_start': { var body = '' , ordered = this.token.ordered; while (this.next().type !== 'list_end') { body += this$1.tok(); } return this.renderer.list(body, ordered); } case 'list_item_start': { var body = ''; while (this.next().type !== 'list_item_end') { body += this$1.token.type === 'text' ? this$1.parseText() : this$1.tok(); } return this.renderer.listitem(body); } case 'loose_item_start': { var body = ''; while (this.next().type !== 'list_item_end') { body += this$1.tok(); } return this.renderer.listitem(body); } case 'html': { var html = !this.token.pre && !this.options.pedantic ? this.inline.output(this.token.text) : this.token.text; return this.renderer.html(html); } case 'paragraph': { return this.renderer.paragraph(this.inline.output(this.token.text)); } case 'text': { return this.renderer.paragraph(this.parseText()); } } }; /** * Helpers */ function escape(html, encode) { return html .replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } function unescape(html) { // explicitly match decimal, hex, and named HTML entities return html.replace(/&(#(?:\d+)|(?:#x[0-9A-Fa-f]+)|(?:\w+));?/ig, function(_, n) { n = n.toLowerCase(); if (n === 'colon') { return ':'; } if (n.charAt(0) === '#') { return n.charAt(1) === 'x' ? String.fromCharCode(parseInt(n.substring(2), 16)) : String.fromCharCode(+n.substring(1)); } return ''; }); } function replace(regex, opt) { regex = regex.source; opt = opt || ''; return function self(name, val) { if (!name) { return new RegExp(regex, opt); } val = val.source || val; val = val.replace(/(^|[^\[])\^/g, '$1'); regex = regex.replace(name, val); return self; }; } function resolveUrl(base, href) { if (!baseUrls[' ' + base]) { // we can ignore everything in base after the last slash of its path component, // but we might need to add _that_ // https://tools.ietf.org/html/rfc3986#section-3 if (/^[^:]+:\/*[^/]*$/.test(base)) { baseUrls[' ' + base] = base + '/'; } else { baseUrls[' ' + base] = base.replace(/[^/]*$/, ''); } } base = baseUrls[' ' + base]; if (href.slice(0, 2) === '//') { return base.replace(/:[\s\S]*/, ':') + href; } else if (href.charAt(0) === '/') { return base.replace(/(:\/*[^/]*)[\s\S]*/, '$1') + href; } else { return base + href; } } var baseUrls = {}; var originIndependentUrl = /^$|^[a-z][a-z0-9+.-]*:|^[?#]/i; function noop() {} noop.exec = noop; function merge(obj) { var arguments$1 = arguments; var i = 1 , target , key; for (; i < arguments.length; i++) { target = arguments$1[i]; for (key in target) { if (Object.prototype.hasOwnProperty.call(target, key)) { obj[key] = target[key]; } } } return obj; } /** * Marked */ function marked(src, opt, callback) { if (callback || typeof opt === 'function') { if (!callback) { callback = opt; opt = null; } opt = merge({}, marked.defaults, opt || {}); var highlight = opt.highlight , tokens , pending , i = 0; try { tokens = Lexer.lex(src, opt); } catch (e) { return callback(e); } pending = tokens.length; var done = function(err) { if (err) { opt.highlight = highlight; return callback(err); } var out; try { out = Parser.parse(tokens, opt); } catch (e) { err = e; } opt.highlight = highlight; return err ? callback(err) : callback(null, out); }; if (!highlight || highlight.length < 3) { return done(); } delete opt.highlight; if (!pending) { return done(); } for (; i < tokens.length; i++) { (function(token) { if (token.type !== 'code') { return --pending || done(); } return highlight(token.text, token.lang, function(err, code) { if (err) { return done(err); } if (code == null || code === token.text) { return --pending || done(); } token.text = code; token.escaped = true; --pending || done(); }); })(tokens[i]); } return; } try { if (opt) { opt = merge({}, marked.defaults, opt); } return Parser.parse(Lexer.lex(src, opt), opt); } catch (e) { e.message += '\nPlease report this to https://github.com/chjj/marked.'; if ((opt || marked.defaults).silent) { return '<p>An error occurred:</p><pre>' + escape(e.message + '', true) + '</pre>'; } throw e; } } /** * Options */ marked.options = marked.setOptions = function(opt) { merge(marked.defaults, opt); return marked; }; marked.defaults = { gfm: true, tables: true, breaks: false, pedantic: false, sanitize: false, sanitizer: null, mangle: true, smartLists: false, silent: false, highlight: null, langPrefix: 'lang-', smartypants: false, headerPrefix: '', renderer: new Renderer, xhtml: false, baseUrl: null }; /** * Expose */ marked.Parser = Parser; marked.parser = Parser.parse; marked.Renderer = Renderer; marked.Lexer = Lexer; marked.lexer = Lexer.lex; marked.InlineLexer = InlineLexer; marked.inlineLexer = InlineLexer.output; marked.parse = marked; { module.exports = marked; } }).call(function() { return this || (typeof window !== 'undefined' ? window : commonjsGlobal); }()); }); var prism = createCommonjsModule(function (module) { /* ********************************************** Begin prism-core.js ********************************************** */ var _self = (typeof window !== 'undefined') ? window // if in browser : ( (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) ? self // if in worker : {} // if in node js ); /** * Prism: Lightweight, robust, elegant syntax highlighting * MIT license http://www.opensource.org/licenses/mit-license.php/ * @author Lea Verou http://lea.verou.me */ var Prism = (function(){ // Private helper vars var lang = /\blang(?:uage)?-(\w+)\b/i; var uniqueId = 0; var _ = _self.Prism = { manual: _self.Prism && _self.Prism.manual, disableWorkerMessageHandler: _self.Prism && _self.Prism.disableWorkerMessageHandler, util: { encode: function (tokens) { if (tokens instanceof Token) { return new Token(tokens.type, _.util.encode(tokens.content), tokens.alias); } else if (_.util.type(tokens) === 'Array') { return tokens.map(_.util.encode); } else { return tokens.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\u00a0/g, ' '); } }, type: function (o) { return Object.prototype.toString.call(o).match(/\[object (\w+)\]/)[1]; }, objId: function (obj) { if (!obj['__id']) { Object.defineProperty(obj, '__id', { value: ++uniqueId }); } return obj['__id']; }, // Deep clone a language definition (e.g. to extend it) clone: function (o) { var type = _.util.type(o); switch (type) { case 'Object': var clone = {}; for (var key in o) { if (o.hasOwnProperty(key)) { clone[key] = _.util.clone(o[key]); } } return clone; case 'Array': return o.map(function(v) { return _.util.clone(v); }); } return o; } }, languages: { extend: function (id, redef) { var lang = _.util.clone(_.languages[id]); for (var key in redef) { lang[key] = redef[key]; } return lang; }, /** * Insert a token before another token in a language literal * As this needs to recreate the object (we cannot actually insert before keys in object literals), * we cannot just provide an object, we need anobject and a key. * @param inside The key (or language id) of the parent * @param before The key to insert before. If not provided, the function appends instead. * @param insert Object with the key/value pairs to insert * @param root The object that contains `inside`. If equal to Prism.languages, it can be omitted. */ insertBefore: function (inside, before, insert, root) { root = root || _.languages; var grammar = root[inside]; if (arguments.length == 2) { insert = arguments[1]; for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { grammar[newToken] = insert[newToken]; } } return grammar; } var ret = {}; for (var token in grammar) { if (grammar.hasOwnProperty(token)) { if (token == before) { for (var newToken in insert) { if (insert.hasOwnProperty(newToken)) { ret[newToken] = insert[newToken]; } } } ret[token] = grammar[token]; } } // Update references in other language definitions _.languages.DFS(_.languages, function(key, value) { if (value === root[inside] && key != inside) { this[key] = ret; } }); return root[inside] = ret; }, // Traverse a language definition with Depth First Search DFS: function(o, callback, type, visited) { visited = visited || {}; for (var i in o) { if (o.hasOwnProperty(i)) { callback.call(o, i, o[i], type || i); if (_.util.type(o[i]) === 'Object' && !visited[_.util.objId(o[i])]) { visited[_.util.objId(o[i])] = true; _.languages.DFS(o[i], callback, null, visited); } else if (_.util.type(o[i]) === 'Array' && !visited[_.util.objId(o[i])]) { visited[_.util.objId(o[i])] = true; _.languages.DFS(o[i], callback, i, visited); } } } } }, plugins: {}, highlightAll: function(async, callback) { _.highlightAllUnder(document, async, callback); }, highlightAllUnder: function(container, async, callback) { var env = { callback: callback, selector: 'code[class*="language-"], [class*="language-"] code, code[class*="lang-"], [class*="lang-"] code' }; _.hooks.run("before-highlightall", env); var elements = env.elements || container.querySelectorAll(env.selector); for (var i=0, element; element = elements[i++];) { _.highlightElement(element, async === true, env.callback); } }, highlightElement: function(element, async, callback) { // Find language var language, grammar, parent = element; while (parent && !lang.test(parent.className)) { parent = parent.parentNode; } if (parent) { language = (parent.className.match(lang) || [,''])[1].toLowerCase(); grammar = _.languages[language]; } // Set language on the element, if not present element.className = element.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; if (element.parentNode) { // Set language on the parent, for styling parent = element.parentNode; if (/pre/i.test(parent.nodeName)) { parent.className = parent.className.replace(lang, '').replace(/\s+/g, ' ') + ' language-' + language; } } var code = element.textContent; var env = { element: element, language: language, grammar: grammar, code: code }; _.hooks.run('before-sanity-check', env); if (!env.code || !env.grammar) { if (env.code) { _.hooks.run('before-highlight', env); env.element.textContent = env.code; _.hooks.run('after-highlight', env); } _.hooks.run('complete', env); return; } _.hooks.run('before-highlight', env); if (async && _self.Worker) { var worker = new Worker(_.filename); worker.onmessage = function(evt) { env.highlightedCode = evt.data; _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; callback && callback.call(env.element); _.hooks.run('after-highlight', env); _.hooks.run('complete', env); }; worker.postMessage(JSON.stringify({ language: env.language, code: env.code, immediateClose: true })); } else { env.highlightedCode = _.highlight(env.code, env.grammar, env.language); _.hooks.run('before-insert', env); env.element.innerHTML = env.highlightedCode; callback && callback.call(element); _.hooks.run('after-highlight', env); _.hooks.run('complete', env); } }, highlight: function (text, grammar, language) { var tokens = _.tokenize(text, grammar); return Token.stringify(_.util.encode(tokens), language); }, matchGrammar: function (text, strarr, grammar, index, startPos, oneshot, target) { var Token = _.Token; for (var token in grammar) { if(!grammar.hasOwnProperty(token) || !grammar[token]) { continue; } if (token == target) { return; } var patterns = grammar[token]; patterns = (_.util.type(patterns) === "Array") ? patterns : [patterns]; for (var j = 0; j < patterns.length; ++j) { var pattern = patterns[j], inside = pattern.inside, lookbehind = !!pattern.lookbehind, greedy = !!pattern.greedy, lookbehindLength = 0, alias = pattern.alias; if (greedy && !pattern.pattern.global) { // Without the global flag, lastIndex won't work var flags = pattern.pattern.toString().match(/[imuy]*$/)[0]; pattern.pattern = RegExp(pattern.pattern.source, flags + "g"); } pattern = pattern.pattern || pattern; // Don’t cache length as it changes during the loop for (var i = index, pos = startPos; i < strarr.length; pos += strarr[i].length, ++i) { var str = strarr[i]; if (strarr.length > text.length) { // Something went terribly wrong, ABORT, ABORT! return; } if (str instanceof Token) { continue; } pattern.lastIndex = 0; var match = pattern.exec(str), delNum = 1; // Greedy patterns can override/remove up to two previously matched tokens if (!match && greedy && i != strarr.length - 1) { pattern.lastIndex = pos; match = pattern.exec(text); if (!match) { break; } var from = match.index + (lookbehind ? match[1].length : 0), to = match.index + match[0].length, k = i, p = pos; for (var len = strarr.length; k < len && (p < to || (!strarr[k].type && !strarr[k - 1].greedy)); ++k) { p += strarr[k].length; // Move the index i to the element in strarr that is closest to from if (from >= p) { ++i; pos = p; } } /* * If strarr[i] is a Token, then the match starts inside another Token, which is invalid * If strarr[k - 1] is greedy we are in conflict with another greedy pattern */ if (strarr[i] instanceof Token || strarr[k - 1].greedy) { continue; } // Number of tokens to delete and replace with the new match delNum = k - i; str = text.slice(pos, p); match.index -= pos; } if (!match) { if (oneshot) { break; } continue; } if(lookbehind) { lookbehindLength = match[1].length; } var from = match.index + lookbehindLength, match = match[0].slice(lookbehindLength), to = from + match.length, before = str.slice(0, from), after = str.slice(to); var args = [i, delNum]; if (before) { ++i; pos += before.length; args.push(before); } var wrapped = new Token(token, inside? _.tokenize(match, inside) : match, alias, match, greedy); args.push(wrapped); if (after) { args.push(after); } Array.prototype.splice.apply(strarr, args); if (delNum != 1) { _.matchGrammar(text, strarr, grammar, i, pos, true, token); } if (oneshot) { break; } } } } }, tokenize: function(text, grammar, language) { var strarr = [text]; var rest = grammar.rest; if (rest) { for (var token in rest) { grammar[token] = rest[token]; } delete grammar.rest; } _.matchGrammar(text, strarr, grammar, 0, 0, false); return strarr; }, hooks: { all: {}, add: function (name, callback) { var hooks = _.hooks.all; hooks[name] = hooks[name] || []; hooks[name].push(callback); }, run: function (name, env) { var callbacks = _.hooks.all[name]; if (!callbacks || !callbacks.length) { return; } for (var i=0, callback; callback = callbacks[i++];) { callback(env); } } } }; var Token = _.Token = function(type, content, alias, matchedStr, greedy) { this.type = type; this.content = content; this.alias = alias; // Copy of the full string this token was created from this.length = (matchedStr || "").length|0; this.greedy = !!greedy; }; Token.stringify = function(o, language, parent) { if (typeof o == 'string') { return o; } if (_.util.type(o) === 'Array') { return o.map(function(element) { return Token.stringify(element, language, o); }).join(''); } var env = { type: o.type, content: Token.stringify(o.content, language, parent), tag: 'span', classes: ['token', o.type], attributes: {}, language: language, parent: parent }; if (o.alias) { var aliases = _.util.type(o.alias) === 'Array' ? o.alias : [o.alias]; Array.prototype.push.apply(env.classes, aliases); } _.hooks.run('wrap', env); var attributes = Object.keys(env.attributes).map(function(name) { return name + '="' + (env.attributes[name] || '').replace(/"/g, '&quot;') + '"'; }).join(' '); return '<' + env.tag + ' class="' + env.classes.join(' ') + '"' + (attributes ? ' ' + attributes : '') + '>' + env.content + '</' + env.tag + '>'; }; if (!_self.document) { if (!_self.addEventListener) { // in Node.js return _self.Prism; } if (!_.disableWorkerMessageHandler) { // In worker _self.addEventListener('message', function (evt) { var message = JSON.parse(evt.data), lang = message.language, code = message.code, immediateClose = message.immediateClose; _self.postMessage(_.highlight(code, _.languages[lang], lang)); if (immediateClose) { _self.close(); } }, false); } return _self.Prism; } //Get current script and highlight var script = document.currentScript || [].slice.call(document.getElementsByTagName("script")).pop(); if (script) { _.filename = script.src; if (!_.manual && !script.hasAttribute('data-manual')) { if(document.readyState !== "loading") { if (window.requestAnimationFrame) { window.requestAnimationFrame(_.highlightAll); } else { window.setTimeout(_.highlightAll, 16); } } else { document.addEventListener('DOMContentLoaded', _.highlightAll); } } } return _self.Prism; })(); if ('object' !== 'undefined' && module.exports) { module.exports = Prism; } // hack for components to work correctly in node.js if (typeof commonjsGlobal !== 'undefined') { commonjsGlobal.Prism = Prism; } /* ********************************************** Begin prism-markup.js ********************************************** */ Prism.languages.markup = { 'comment': /<!--[\s\S]*?-->/, 'prolog': /<\?[\s\S]+?\?>/, 'doctype': /<!DOCTYPE[\s\S]+?>/i, 'cdata': /<!\[CDATA\[[\s\S]*?]]>/i, 'tag': { pattern: /<\/?(?!\d)[^\s>\/=$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+))?)*\s*\/?>/i, inside: { 'tag': { pattern: /^<\/?[^\s>\/]+/i, inside: { 'punctuation': /^<\/?/, 'namespace': /^[^\s>\/:]+:/ } }, 'attr-value': { pattern: /=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+)/i, inside: { 'punctuation': [ /^=/, { pattern: /(^|[^\\])["']/, lookbehind: true } ] } }, 'punctuation': /\/?>/, 'attr-name': { pattern: /[^\s>\/]+/, inside: { 'namespace': /^[^\s>\/:]+:/ } } } }, 'entity': /&#?[\da-z]{1,8};/i }; Prism.languages.markup['tag'].inside['attr-value'].inside['entity'] = Prism.languages.markup['entity']; // Plugin to make entity title show the real entity, idea by Roman Komarov Prism.hooks.add('wrap', function(env) { if (env.type === 'entity') { env.attributes['title'] = env.content.replace(/&amp;/, '&'); } }); Prism.languages.xml = Prism.languages.markup; Prism.languages.html = Prism.languages.markup; Prism.languages.mathml = Prism.languages.markup; Prism.languages.svg = Prism.languages.markup; /* ********************************************** Begin prism-css.js ********************************************** */ Prism.languages.css = { 'comment': /\/\*[\s\S]*?\*\//, 'atrule': { pattern: /@[\w-]+?.*?(?:;|(?=\s*\{))/i, inside: { 'rule': /@[\w-]+/ // See rest below } }, 'url': /url\((?:(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1|.*?)\)/i, 'selector': /[^{}\s][^{};]*?(?=\s*\{)/, 'string': { pattern: /("|')(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, greedy: true }, 'property': /[-_a-z\xA0-\uFFFF][-\w\xA0-\uFFFF]*(?=\s*:)/i, 'important': /\B!important\b/i, 'function': /[-a-z0-9]+(?=\()/i, 'punctuation': /[(){};:]/ }; Prism.languages.css['atrule'].inside.rest = Prism.util.clone(Prism.languages.css); if (Prism.languages.markup) { Prism.languages.insertBefore('markup', 'tag', { 'style': { pattern: /(<style[\s\S]*?>)[\s\S]*?(?=<\/style>)/i, lookbehind: true, inside: Prism.languages.css, alias: 'language-css', greedy: true } }); Prism.languages.insertBefore('inside', 'attr-value', { 'style-attr': { pattern: /\s*style=("|')(?:\\[\s\S]|(?!\1)[^\\])*\1/i, inside: { 'attr-name': { pattern: /^\s*style/i, inside: Prism.languages.markup.tag.inside }, 'punctuation': /^\s*=\s*['"]|['"]\s*$/, 'attr-value': { pattern: /.+/i, inside: Prism.languages.css } }, alias: 'language-css' } }, Prism.languages.markup.tag); } /* ********************************************** Begin prism-clike.js ********************************************** */ Prism.languages.clike = { 'comment': [ { pattern: /(^|[^\\])\/\*[\s\S]*?(?:\*\/|$)/, lookbehind: true }, { pattern: /(^|[^\\:])\/\/.*/, lookbehind: true } ], 'string': { pattern: /(["'])(?:\\(?:\r\n|[\s\S])|(?!\1)[^\\\r\n])*\1/, greedy: true }, 'class-name': { pattern: /((?:\b(?:class|interface|extends|implements|trait|instanceof|new)\s+)|(?:catch\s+\())[\w.\\]+/i, lookbehind: true, inside: { punctuation: /[.\\]/ } }, 'keyword': /\b(?:if|else|while|do|for|return|in|instanceof|function|new|try|throw|catch|finally|null|break|continue)\b/, 'boolean': /\b(?:true|false)\b/, 'function': /[a-z0-9_]+(?=\()/i, 'number': /\b-?(?:0x[\da-f]+|\d*\.?\d+(?:e[+-]?\d+)?)\b/i, 'operator': /--?|\+\+?|!=?=?|<=?|>=?|==?=?|&&?|\|\|?|\?|\*|\/|~|\^|%/, 'punctuation': /[{}[\];(),.:]/ }; /* ********************************************** Begin prism-javascript.js ********************************************** */ Prism.languages.javascript = Prism.languages.extend('clike', { 'keyword': /\b(?:as|async|await|break|case|catch|class|const|continue|debugger|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|instanceof|interface|let|new|null|of|package|private|protected|public|return|set|static|super|switch|this|throw|try|typeof|var|void|while|with|yield)\b/, 'number': /\b-?(?:0[xX][\dA-Fa-f]+|0[bB][01]+|0[oO][0-7]+|\d*\.?\d+(?:[Ee][+-]?\d+)?|NaN|Infinity)\b/, // Allow for all non-ASCII characters (See http://stackoverflow.com/a/2008444) 'function': /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*\()/i, 'operator': /-[-=]?|\+[+=]?|!=?=?|<<?=?|>>?>?=?|=(?:==?|>)?|&[&=]?|\|[|=]?|\*\*?=?|\/=?|~|\^=?|%=?|\?|\.{3}/ }); Prism.languages.insertBefore('javascript', 'keyword', { 'regex': { pattern: /(^|[^/])\/(?!\/)(\[[^\]\r\n]+]|\\.|[^/\\\[\r\n])+\/[gimyu]{0,5}(?=\s*($|[\r\n,.;})]))/, lookbehind: true, greedy: true }, // This must be declared before keyword because we use "function" inside the look-forward 'function-variable': { pattern: /[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*(?=\s*=\s*(?:function\b|(?:\([^()]*\)|[_$a-z\xA0-\uFFFF][$\w\xA0-\uFFFF]*)\s*=>))/i, alias: 'function' } }); Prism.languages.insertBefore('javascript', 'string', { 'template-string': { pattern: /`(?:\\[\s\S]|[^\\`])*`/, greedy: true, inside: { 'interpolation': { pattern: /\$\{[^}]+\}/, inside: { 'interpolation-punctuation': { pattern: /^\$\{|\}$/, alias: 'punctuation' }, rest: Prism.languages.javascript } }, 'string': /[\s\S]+/ } } }); if (Prism.languages.markup) { Prism.languages.insertBefore('markup', 'tag', { 'script': { pattern: /(<script[\s\S]*?>)[\s\S]*?(?=<\/script>)/i, lookbehind: true, inside: Prism.languages.javascript, alias: 'language-javascript', greedy: true } }); } Prism.languages.js = Prism.languages.javascript; /* ********************************************** Begin prism-file-highlight.js ********************************************** */ (function () { if (typeof self === 'undefined' || !self.Prism || !self.document || !document.querySelector) { return; } self.Prism.fileHighlight = function() { var Extensions = { 'js': 'javascript', 'py': 'python', 'rb': 'ruby', 'ps1': 'powershell', 'psm1': 'powershell', 'sh': 'bash', 'bat': 'batch', 'h': 'c', 'tex': 'latex' }; Array.prototype.slice.call(document.querySelectorAll('pre[data-src]')).forEach(function (pre) { var src = pre.getAttribute('data-src'); var language, parent = pre; var lang = /\blang(?:uage)?-(?!\*)(\w+)\b/i; while (parent && !lang.test(parent.className)) { parent = parent.parentNode; } if (parent) { language = (pre.className.match(lang) || [, ''])[1]; } if (!language) { var extension = (src.match(/\.(\w+)$/) || [, ''])[1]; language = Extensions[extension] || extension; } var code = document.createElement('code'); code.className = 'language-' + language; pre.textContent = ''; code.textContent = 'Loading…'; pre.appendChild(code); var xhr = new XMLHttpRequest(); xhr.open('GET', src, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status < 400 && xhr.responseText) { code.textContent = xhr.responseText; Prism.highlightElement(code); } else if (xhr.status >= 400) { code.textContent = '✖ Error ' + xhr.status + ' while fetching file: ' + xhr.statusText; } else { code.textContent = '✖ Error: File does not exist or is empty'; } } }; xhr.send(null); }); }; document.addEventListener('DOMContentLoaded', self.Prism.fileHighlight); })(); }); /** * gen toc tree * @link https://github.com/killercup/grock/blob/5280ae63e16c5739e9233d9009bc235ed7d79a50/styles/solarized/assets/js/behavior.coffee#L54-L81 * @param {Array} toc * @param {Number} maxLevel * @return {Array} */ function genTree (toc, maxLevel) { var headlines = []; var last = {}; toc.forEach(function (headline) { var level = headline.level || 1; var len = level - 1; if (level > maxLevel) { return } if (last[len]) { last[len].children = (last[len].children || []).concat(headline); } else { headlines.push(headline); } last[level] = headline; }); return headlines } var cache$1 = {}; var re = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,.\/:;<=>?@\[\]^`{|}~]/g; function lower (string) { return string.toLowerCase() } function slugify (str) { if (typeof str !== 'string') { return '' } var slug = str .trim() .replace(/[A-Z]+/g, lower) .replace(/<[^>\d]+>/g, '') .replace(re, '') .replace(/\s/g, '-') .replace(/-+/g, '-') .replace(/^(\d)/, '_$1'); var count = cache$1[slug]; count = cache$1.hasOwnProperty(slug) ? count + 1 : 0; cache$1[slug] = count; if (count) { slug = slug + '-' + count; } return slug } slugify.clear = function () { cache$1 = {}; }; function replace (m, $1) { return '<img class="emoji" src="https://assets-cdn.github.com/images/icons/emoji/' + $1 + '.png" alt="' + $1 + '" />' } function emojify (text) { return text .replace(/<(pre|template|code)[^>]*?>[\s\S]+?<\/(pre|template|code)>/g, function (m) { return m.replace(/:/g, '__colon__'); }) .replace(/:(\w+?):/ig, (inBrowser && window.emojify) || replace) .replace(/__colon__/g, ':') } var decode = decodeURIComponent; var encode = encodeURIComponent; function parseQuery (query) { var res = {}; query = query.trim().replace(/^(\?|#|&)/, ''); if (!query) { return res } // Simple parse query.split('&').forEach(function (param) { var parts = param.replace(/\+/g, ' ').split('='); res[parts[0]] = parts[1] && decode(parts[1]); }); return res } function stringifyQuery (obj, ignores) { if ( ignores === void 0 ) ignores = []; var qs = []; for (var key in obj) { if (ignores.indexOf(key) > -1) { continue } qs.push( obj[key] ? ((encode(key)) + "=" + (encode(obj[key]))).toLowerCase() : encode(key) ); } return qs.length ? ("?" + (qs.join('&'))) : '' } function getPath () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return cleanPath(args.join('/')) } var isAbsolutePath = cached(function (path) { return /(:|(\/{2}))/g.test(path) }); var getParentPath = cached(function (path) { return /\/$/g.test(path) ? path : (path = path.match(/(\S*\/)[^\/]+$/)) ? path[1] : '' }); var cleanPath = cached(function (path) { return path.replace(/^\/+/, '/').replace(/([^:])\/{2,}/g, '$1/') }); var replaceSlug = cached(function (path) { return path.replace('#', '?id=') }); var cachedLinks = {}; function getAndRemoveConfig (str) { if ( str === void 0 ) str = ''; var config = {}; if (str) { str = str .replace(/:([\w-]+)=?([\w-]+)?/g, function (m, key, value) { config[key] = (value && value.replace(/&quot;/g, '')) || true; return '' }) .trim(); } return { str: str, config: config } } var compileMedia = { markdown: function markdown (url) { return { url: url } }, iframe: function iframe (url, title) { return { code: ("<iframe src=\"" + url + "\" " + (title || 'width=100% height=400') + "></iframe>") } }, video: function video (url, title) { return { code: ("<video src=\"" + url + "\" " + (title || 'controls') + ">Not Support</video>") } }, audio: function audio (url, title) { return { code: ("<audio src=\"" + url + "\" " + (title || 'controls') + ">Not Support</audio>") } }, code: function code (url, title) { var lang = url.match(/\.(\w+)$/); lang = title || (lang && lang[1]); if (lang === 'md') { lang = 'markdown'; } return { url: url, lang: lang } } }; var Compiler = function Compiler (config, router) { this.config = config; this.router = router; this.cacheTree = {}; this.toc = []; this.linkTarget = config.externalLinkTarget || '_blank'; this.contentBase = router.getBasePath(); var renderer = this._initRenderer(); var compile; var mdConf = config.markdown || {}; if (isFn(mdConf)) { compile = mdConf(marked, renderer); } else { marked.setOptions( merge(mdConf, { renderer: merge(renderer, mdConf.renderer) }) ); compile = marked; } this._marked = compile; this.compile = cached(function (text) { var html = ''; if (!text) { return text } if (isPrimitive(text)) { html = compile(text); } else { html = compile.parser(text); } html = config.noEmoji ? html : emojify(html); slugify.clear(); return html }); }; Compiler.prototype.compileEmbed = function compileEmbed (href, title) { var ref = getAndRemoveConfig(title); var str = ref.str; var config = ref.config; var embed; title = str; if (config.include) { if (!isAbsolutePath(href)) { href = getPath(this.contentBase, href); } var media; if (config.type && (media = compileMedia[config.type])) { embed = media.call(this, href, title); embed.type = config.type; } else { var type = 'code'; if (/\.(md|markdown)/.test(href)) { type = 'markdown'; } else if (/\.html?/.test(href)) { type = 'iframe'; } else if (/\.(mp4|ogg)/.test(href)) { type = 'video'; } else if (/\.mp3/.test(href)) { type = 'audio'; } embed = compileMedia[type].call(this, href, title); embed.type = type; } return embed } }; Compiler.prototype._matchNotCompileLink = function _matchNotCompileLink (link) { var links = this.config.noCompileLinks || []; for (var i = 0; i < links.length; i++) { var n = links[i]; var re = cachedLinks[n] || (cachedLinks[n] = new RegExp(("^" + n + "$"))); if (re.test(link)) { return link } } }; Compiler.prototype._initRenderer = function _initRenderer () { var renderer = new marked.Renderer(); var ref = this; var linkTarget = ref.linkTarget; var router = ref.router; var contentBase = ref.contentBase; var _self = this; var origin = {}; /** * render anchor tag * @link https://github.com/chjj/marked#overriding-renderer-methods */ origin.heading = renderer.heading = function (text, level) { var nextToc = { level: level, title: text }; if (/{docsify-ignore}/g.test(text)) { text = text.replace('{docsify-ignore}', ''); nextToc.title = text; nextToc.ignoreSubHeading = true; } if (/{docsify-ignore-all}/g.test(text)) { text = text.replace('{docsify-ignore-all}', ''); nextToc.title = text; nextToc.ignoreAllSubs = true; } var slug = slugify(text); var url = router.toURL(router.getCurrentPath(), { id: slug }); nextToc.slug = url; _self.toc.push(nextToc); return ("<h" + level + " id=\"" + slug + "\"><a href=\"" + url + "\" data-id=\"" + slug + "\" class=\"anchor\"><span>" + text + "</span></a></h" + level + ">") }; // highlight code origin.code = renderer.code = function (code, lang) { if ( lang === void 0 ) lang = ''; code = code.replace(/@DOCSIFY_QM@/g, '`'); var hl = prism.highlight( code, prism.languages[lang] || prism.languages.markup ); return ("<pre v-pre data-lang=\"" + lang + "\"><code class=\"lang-" + lang + "\">" + hl + "</code></pre>") }; origin.link = renderer.link = function (href, title, text) { if ( title === void 0 ) title = ''; var attrs = ''; var ref = getAndRemoveConfig(title); var str = ref.str; var config = ref.config; title = str; if ( !/:|(\/{2})/.test(href) && !_self._matchNotCompileLink(href) && !config.ignore ) { if (href === _self.config.homepage) { href = 'README'; } href = router.toURL(href, null, router.getCurrentPath()); } else { attrs += " target=\"" + linkTarget + "\""; } if (config.target) { attrs += ' target=' + config.target; } if (config.disabled) { attrs += ' disabled'; href = 'javascript:void(0)'; } if (title) { attrs += " title=\"" + title + "\""; } return ("<a href=\"" + href + "\"" + attrs + ">" + text + "</a>") }; origin.paragraph = renderer.paragraph = function (text) { if (/^!&gt;/.test(text)) { return helper('tip', text) } else if (/^\?&gt;/.test(text)) { return helper('warn', text) } return ("<p>" + text + "</p>") }; origin.image = renderer.image = function (href, title, text) { var url = href; var attrs = ''; var ref = getAndRemoveConfig(title); var str = ref.str; var config = ref.config; title = str; if (config['no-zoom']) { attrs += ' data-no-zoom'; } if (title) { attrs += " title=\"" + title + "\""; } if (!isAbsolutePath(href)) { url = getPath(contentBase, href); } return ("<img src=\"" + url + "\"data-origin=\"" + href + "\" alt=\"" + text + "\"" + attrs + ">") }; var CHECKED_RE = /^\[([ x])\] +/; origin.listitem = renderer.listitem = function (text) { var checked = CHECKED_RE.exec(text); if (checked) { text = text.replace( CHECKED_RE, ("<input type=\"checkbox\" " + (checked[1] === 'x' ? 'checked' : '') + " />") ); } return ("<li" + (checked ? " class=\"task-list-item\"" : '') + ">" + text + "</li>\n") }; renderer.origin = origin; return renderer }; /** * Compile sidebar */ Compiler.prototype.sidebar = function sidebar (text, level) { var currentPath = this.router.getCurrentPath(); var html = ''; if (text) { html = this.compile(text); html = html && html.match(/<ul[^>]*>([\s\S]+)<\/ul>/g)[0]; } else { var tree$$1 = this.cacheTree[currentPath] || genTree(this.toc, level); html = tree(tree$$1, '<ul>'); this.cacheTree[currentPath] = tree$$1; } return html }; /** * Compile sub sidebar */ Compiler.prototype.subSidebar = function subSidebar (level) { if (!level) { this.toc = []; return } var currentPath = this.router.getCurrentPath(); var ref = this; var cacheTree = ref.cacheTree; var toc = ref.toc; toc[0] && toc[0].ignoreAllSubs && toc.splice(0); toc[0] && toc[0].level === 1 && toc.shift(); for (var i = 0; i < toc.length; i++) { toc[i].ignoreSubHeading && toc.splice(i, 1) && i--; } var tree$$1 = cacheTree[currentPath] || genTree(toc, level); cacheTree[currentPath] = tree$$1; this.toc = []; return tree(tree$$1, '<ul class="app-sub-sidebar">') }; Compiler.prototype.article = function article (text) { return this.compile(text) }; /** * Compile cover page */ Compiler.prototype.cover = function cover$$1 (text) { var cacheToc = this.toc.slice(); var html = this.compile(text); this.toc = cacheToc.slice(); return html }; var title = $.title; /** * Toggle button */ function btn (el, router) { var toggle = function (_) { return body.classList.toggle('close'); }; el = getNode(el); on(el, 'click', function (e) { e.stopPropagation(); toggle(); }); isMobile && on( body, 'click', function (_) { return body.classList.contains('close') && toggle(); } ); } function collapse (el, router) { el = getNode(el); on(el, 'click', function (ref) { var target = ref.target; if ( target.nodeName === 'A' && target.nextSibling && target.nextSibling.classList.contains('app-sub-sidebar') ) { toggleClass(target.parentNode, 'collapse'); } }); } function sticky () { var cover = getNode('section.cover'); if (!cover) { return } var coverHeight = cover.getBoundingClientRect().height; if (window.pageYOffset >= coverHeight || cover.classList.contains('hidden')) { toggleClass(body, 'add', 'sticky'); } else { toggleClass(body, 'remove', 'sticky'); } } /** * Get and active link * @param {object} router * @param {string|element} el * @param {Boolean} isParent acitve parent * @param {Boolean} autoTitle auto set title * @return {element} */ function getAndActive (router, el, isParent, autoTitle) { el = getNode(el); var links = findAll(el, 'a'); var hash = decodeURI(router.toURL(router.getCurrentPath())); var target; links.sort(function (a, b) { return b.href.length - a.href.length; }).forEach(function (a) { var href = a.getAttribute('href'); var node = isParent ? a.parentNode : a; if (hash.indexOf(href) === 0 && !target) { target = a; toggleClass(node, 'add', 'active'); } else { toggleClass(node, 'remove', 'active'); } }); if (autoTitle) { $.title = target ? ((target.innerText) + " - " + title) : title; } return target } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) { descriptor.writable = true; } Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) { defineProperties(Constructor.prototype, protoProps); } if (staticProps) { defineProperties(Constructor, staticProps); } return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Tweezer = function () { function Tweezer() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Tweezer); this.duration = opts.duration || 1000; this.ease = opts.easing || this._defaultEase; this.start = opts.start; this.end = opts.end; this.frame = null; this.next = null; this.isRunning = false; this.events = {}; this.direction = this.start < this.end ? 'up' : 'down'; } _createClass(Tweezer, [{ key: 'begin', value: function begin() { if (!this.isRunning && this.next !== this.end) { this.frame = window.requestAnimationFrame(this._tick.bind(this)); } return this; } }, { key: 'stop', value: function stop() { window.cancelAnimationFrame(this.frame); this.isRunning = false; this.frame = null; this.timeStart = null; this.next = null; return this; } }, { key: 'on', value: function on(name, handler) { this.events[name] = this.events[name] || []; this.events[name].push(handler); return this; } }, { key: 'emit', value: function emit(name, val) { var _this = this; var e = this.events[name]; e && e.forEach(function (handler) { return handler.call(_this, val); }); } }, { key: '_tick', value: function _tick(currentTime) { this.isRunning = true; var lastTick = this.next || this.start; if (!this.timeStart) { this.timeStart = currentTime; } this.timeElapsed = currentTime - this.timeStart; this.next = Math.round(this.ease(this.timeElapsed, this.start, this.end - this.start, this.duration)); if (this._shouldTick(lastTick)) { this.emit('tick', this.next); this.frame = window.requestAnimationFrame(this._tick.bind(this)); } else { this.emit('tick', this.end); this.emit('done', null); } } }, { key: '_shouldTick', value: function _shouldTick(lastTick) { return { up: this.next < this.end && lastTick <= this.next, down: this.next > this.end && lastTick >= this.next }[this.direction]; } }, { key: '_defaultEase', value: function _defaultEase(t, b, c, d) { if ((t /= d / 2) < 1) { return c / 2 * t * t + b; } return -c / 2 * (--t * (t - 2) - 1) + b; } }]); return Tweezer; }(); var nav = {}; var hoverOver = false; var scroller = null; var enableScrollEvent = true; var coverHeight = 0; function scrollTo (el) { if (scroller) { scroller.stop(); } enableScrollEvent = false; scroller = new Tweezer({ start: window.pageYOffset, end: el.getBoundingClientRect().top + window.pageYOffset, duration: 500 }) .on('tick', function (v) { return window.scrollTo(0, v); }) .on('done', function () { enableScrollEvent = true; scroller = null; }) .begin(); } function highlight (path) { if (!enableScrollEvent) { return } var sidebar = getNode('.sidebar'); var anchors = findAll('.anchor'); var wrap = find(sidebar, '.sidebar-nav'); var active = find(sidebar, 'li.active'); var doc = document.documentElement; var top = ((doc && doc.scrollTop) || document.body.scrollTop) - coverHeight; var last; for (var i = 0, len = anchors.length; i < len; i += 1) { var node = anchors[i]; if (node.offsetTop > top) { if (!last) { last = node; } break } else { last = node; } } if (!last) { return } var li = nav[getNavKey(path, last.getAttribute('data-id'))]; if (!li || li === active) { return } active && active.classList.remove('active'); li.classList.add('active'); active = li; // scroll into view // https://github.com/vuejs/vuejs.org/blob/master/themes/vue/source/js/common.js#L282-L297 if (!hoverOver && body.classList.contains('sticky')) { var height = sidebar.clientHeight; var curOffset = 0; var cur = active.offsetTop + active.clientHeight + 40; var isInView = active.offsetTop >= wrap.scrollTop && cur <= wrap.scrollTop + height; var notThan = cur - curOffset < height; var top$1 = isInView ? wrap.scrollTop : notThan ? curOffset : cur - height; sidebar.scrollTop = top$1; } } function getNavKey (path, id) { return (path + "?id=" + id) } function scrollActiveSidebar (router) { var cover = find('.cover.show'); coverHeight = cover ? cover.offsetHeight : 0; var sidebar = getNode('.sidebar'); var lis = findAll(sidebar, 'li'); for (var i = 0, len = lis.length; i < len; i += 1) { var li = lis[i]; var a = li.querySelector('a'); if (!a) { continue } var href = a.getAttribute('href'); if (href !== '/') { var ref = router.parse(href); var id = ref.query.id; var path$1 = ref.path; if (id) { href = getNavKey(path$1, id); } } if (href) { nav[decodeURIComponent(href)] = li; } } if (isMobile) { return } var path = router.getCurrentPath(); off('scroll', function () { return highlight(path); }); on('scroll', function () { return highlight(path); }); on(sidebar, 'mouseover', function () { hoverOver = true; }); on(sidebar, 'mouseleave', function () { hoverOver = false; }); } function scrollIntoView (path, id) { if (!id) { return } var section = find('#' + id); section && scrollTo(section); var li = nav[getNavKey(path, id)]; var sidebar = getNode('.sidebar'); var active = find(sidebar, 'li.active'); active && active.classList.remove('active'); li && li.classList.add('active'); } var scrollEl = $.scrollingElement || $.documentElement; function scroll2Top (offset) { if ( offset === void 0 ) offset = 0; scrollEl.scrollTop = offset === true ? 0 : Number(offset); } var cached$1 = {}; function walkFetchEmbed (ref, cb) { var step = ref.step; if ( step === void 0 ) step = 0; var embedTokens = ref.embedTokens; var compile = ref.compile; var fetch = ref.fetch; var token = embedTokens[step]; if (!token) { return cb({}) } var next = function (text) { var embedToken; if (text) { if (token.embed.type === 'markdown') { embedToken = compile.lexer(text); } else if (token.embed.type === 'code') { embedToken = compile.lexer( '```' + token.embed.lang + '\n' + text.replace(/`/g, '@DOCSIFY_QM@') + '\n```\n' ); } } cb({ token: token, embedToken: embedToken }); walkFetchEmbed({ step: ++step, compile: compile, embedTokens: embedTokens, fetch: fetch }, cb); }; { get(token.embed.url).then(next); } } function prerenderEmbed (ref, done) { var compiler = ref.compiler; var raw = ref.raw; if ( raw === void 0 ) raw = ''; var fetch = ref.fetch; var hit; if ((hit = cached$1[raw])) { return done(hit) } var compile = compiler._marked; var tokens = compile.lexer(raw); var embedTokens = []; var linkRE = compile.InlineLexer.rules.link; var links = tokens.links; tokens.forEach(function (token, index) { if (token.type === 'paragraph') { token.text = token.text.replace( new RegExp(linkRE.source, 'g'), function (src, filename, href, title) { var embed = compiler.compileEmbed(href, title); if (embed) { if (embed.type === 'markdown' || embed.type === 'code') { embedTokens.push({ index: index, embed: embed }); } return embed.code } return src } ); } }); var moveIndex = 0; walkFetchEmbed({ compile: compile, embedTokens: embedTokens, fetch: fetch }, function (ref) { var embedToken = ref.embedToken; var token = ref.token; if (token) { var index = token.index + moveIndex; merge(links, embedToken.links); tokens = tokens .slice(0, index) .concat(embedToken, tokens.slice(index + 1)); moveIndex += embedToken.length - 1; } else { cached$1[raw] = tokens.concat(); tokens.links = cached$1[raw].links = links; done(tokens); } }); } function executeScript () { var script = findAll('.markdown-section>script') .filter(function (s) { return !/template/.test(s.type); })[0]; if (!script) { return false } var code = script.innerText.trim(); if (!code) { return false } setTimeout(function (_) { window.__EXECUTE_RESULT__ = new Function(code)(); }, 0); } function formatUpdated (html, updated, fn) { updated = typeof fn === 'function' ? fn(updated) : typeof fn === 'string' ? tinydate(fn)(new Date(updated)) : updated; return html.replace(/{docsify-updated}/g, updated) } function renderMain (html) { if (!html) { // TODO: Custom 404 page html = 'not found'; } this._renderTo('.markdown-section', html); // Render sidebar with the TOC !this.config.loadSidebar && this._renderSidebar(); // execute script if ( this.config.executeScript !== false && typeof window.Vue !== 'undefined' && !executeScript() ) { setTimeout(function (_) { var vueVM = window.__EXECUTE_RESULT__; vueVM && vueVM.$destroy && vueVM.$destroy(); window.__EXECUTE_RESULT__ = new window.Vue().$mount('#main'); }, 0); } else { this.config.executeScript && executeScript(); } } function renderNameLink (vm) { var el = getNode('.app-name-link'); var nameLink = vm.config.nameLink; var path = vm.route.path; if (!el) { return } if (isPrimitive(vm.config.nameLink)) { el.setAttribute('href', nameLink); } else if (typeof nameLink === 'object') { var match = Object.keys(nameLink).filter(function (key) { return path.indexOf(key) > -1; })[0]; el.setAttribute('href', nameLink[match]); } } function renderMixin (proto) { proto._renderTo = function (el, content, replace) { var node = getNode(el); if (node) { node[replace ? 'outerHTML' : 'innerHTML'] = content; } }; proto._renderSidebar = function (text) { var ref = this.config; var maxLevel = ref.maxLevel; var subMaxLevel = ref.subMaxLevel; var loadSidebar = ref.loadSidebar; this._renderTo('.sidebar-nav', this.compiler.sidebar(text, maxLevel)); var activeEl = getAndActive(this.router, '.sidebar-nav', true, true); if (loadSidebar && activeEl) { activeEl.parentNode.innerHTML += this.compiler.subSidebar(subMaxLevel) || ''; } else { // reset toc this.compiler.subSidebar(); } // bind event this._bindEventOnRendered(activeEl); }; proto._bindEventOnRendered = function (activeEl) { var ref = this.config; var autoHeader = ref.autoHeader; var auto2top = ref.auto2top; scrollActiveSidebar(this.router); if (autoHeader && activeEl) { var main$$1 = getNode('#main'); var firstNode = main$$1.children[0]; if (firstNode && firstNode.tagName !== 'H1') { var h1 = create('h1'); h1.innerText = activeEl.innerText; before(main$$1, h1); } } auto2top && scroll2Top(auto2top); }; proto._renderNav = function (text) { text && this._renderTo('nav', this.compiler.compile(text)); getAndActive(this.router, 'nav'); }; proto._renderMain = function (text, opt, next) { var this$1 = this; if ( opt === void 0 ) opt = {}; if (!text) { return renderMain.call(this, text) } callHook(this, 'beforeEach', text, function (result) { var html; var callback = function () { if (opt.updatedAt) { html = formatUpdated(html, opt.updatedAt, this$1.config.formatUpdated); } callHook(this$1, 'afterEach', html, function (text) { return renderMain.call(this$1, text); }); }; if (this$1.isHTML) { html = this$1.result; callback(); next(); } else { prerenderEmbed( { compiler: this$1.compiler, raw: text }, function (tokens) { html = this$1.compiler.compile(tokens); callback(); next(); } ); } }); }; proto._renderCover = function (text, coverOnly) { var el = getNode('.cover'); toggleClass(getNode('main'), coverOnly ? 'add' : 'remove', 'hidden'); if (!text) { toggleClass(el, 'remove', 'show'); return } toggleClass(el, 'add', 'show'); var html = this.coverIsHTML ? text : this.compiler.cover(text); var m = html .trim() .match('<p><img.*?data-origin="(.*?)"[^a]+alt="(.*?)">([^<]*?)</p>$'); if (m) { if (m[2] === 'color') { el.style.background = m[1] + (m[3] || ''); } else { var path = m[1]; toggleClass(el, 'add', 'has-mask'); if (!isAbsolutePath(m[1])) { path = getPath(this.router.getBasePath(), m[1]); } el.style.backgroundImage = "url(" + path + ")"; el.style.backgroundSize = 'cover'; el.style.backgroundPosition = 'center center'; } html = html.replace(m[0], ''); } this._renderTo('.cover-main', html); sticky(); }; proto._updateRender = function () { // render name link renderNameLink(this); }; } function initRender (vm) { var config = vm.config; // Init markdown compiler vm.compiler = new Compiler(config, vm.router); if (inBrowser) { window['__current_docsify_compiler__'] = vm.compiler; } var id = config.el || '#app'; var navEl = find('nav') || create('nav'); var el = find(id); var html = ''; var navAppendToTarget = body; if (el) { if (config.repo) { html += corner(config.repo); } if (config.coverpage) { html += cover(); } html += main(config); // Render main app vm._renderTo(el, html, true); } else { vm.rendered = true; } if (config.mergeNavbar && isMobile) { navAppendToTarget = find('.sidebar'); } else { navEl.classList.add('app-nav'); if (!config.repo) { navEl.classList.add('no-badge'); } } // Add nav before(navAppendToTarget, navEl); if (config.themeColor) { $.head.appendChild( create('div', theme(config.themeColor)).firstElementChild ); // Polyfll cssVars(config.themeColor); } vm._updateRender(); toggleClass(body, 'ready'); } var cached$2 = {}; function getAlias (path, alias, last) { var match = Object.keys(alias).filter(function (key) { var re = cached$2[key] || (cached$2[key] = new RegExp(("^" + key + "$"))); return re.test(path) && path !== last })[0]; return match ? getAlias(path.replace(cached$2[match], alias[match]), alias, path) : path } function getFileName (path, ext) { return new RegExp(("\\.(" + (ext.replace(/^\./, '')) + "|html)$"), 'g').test(path) ? path : /\/$/g.test(path) ? (path + "README" + ext) : ("" + path + ext) } var History = function History (config) { this.config = config; }; History.prototype.getBasePath = function getBasePath () { return this.config.basePath }; History.prototype.getFile = function getFile (path, isRelative) { if ( path === void 0 ) path = this.getCurrentPath(); var ref = this; var config = ref.config; var base = this.getBasePath(); var ext = typeof config.ext !== 'string' ? '.md' : config.ext; path = config.alias ? getAlias(path, config.alias) : path; path = getFileName(path, ext); path = path === ("/README" + ext) ? config.homepage || path : path; path = isAbsolutePath(path) ? path : getPath(base, path); if (isRelative) { path = path.replace(new RegExp(("^" + base)), ''); } return path }; History.prototype.onchange = function onchange (cb) { if ( cb === void 0 ) cb = noop; cb(); }; History.prototype.getCurrentPath = function getCurrentPath () {}; History.prototype.normalize = function normalize () {}; History.prototype.parse = function parse () {}; History.prototype.toURL = function toURL (path, params, currentRoute) { var local = currentRoute && path[0] === '#'; var route = this.parse(replaceSlug(path)); route.query = merge({}, route.query, params); path = route.path + stringifyQuery(route.query); path = path.replace(/\.md(\?)|\.md$/, '$1'); if (local) { var idIndex = currentRoute.indexOf('?'); path = (idIndex > 0 ? currentRoute.substr(0, idIndex) : currentRoute) + path; } return cleanPath('/' + path) }; function replaceHash (path) { var i = location.href.indexOf('#'); location.replace(location.href.slice(0, i >= 0 ? i : 0) + '#' + path); } var HashHistory = (function (History$$1) { function HashHistory (config) { History$$1.call(this, config); this.mode = 'hash'; } if ( History$$1 ) HashHistory.__proto__ = History$$1; HashHistory.prototype = Object.create( History$$1 && History$$1.prototype ); HashHistory.prototype.constructor = HashHistory; HashHistory.prototype.getBasePath = function getBasePath () { var path = window.location.pathname || ''; var base = this.config.basePath; return /^(\/|https?:)/g.test(base) ? base : cleanPath(path + '/' + base) }; HashHistory.prototype.getCurrentPath = function getCurrentPath () { // We can't use location.hash here because it's not // consistent across browsers - Firefox will pre-decode it! var href = location.href; var index = href.indexOf('#'); return index === -1 ? '' : href.slice(index + 1) }; HashHistory.prototype.onchange = function onchange (cb) { if ( cb === void 0 ) cb = noop; on('hashchange', cb); }; HashHistory.prototype.normalize = function normalize () { var path = this.getCurrentPath(); path = replaceSlug(path); if (path.charAt(0) === '/') { return replaceHash(path) } replaceHash('/' + path); }; /** * Parse the url * @param {string} [path=location.herf] * @return {object} { path, query } */ HashHistory.prototype.parse = function parse (path) { if ( path === void 0 ) path = location.href; var query = ''; var hashIndex = path.indexOf('#'); if (hashIndex >= 0) { path = path.slice(hashIndex + 1); } var queryIndex = path.indexOf('?'); if (queryIndex >= 0) { query = path.slice(queryIndex + 1); path = path.slice(0, queryIndex); } return { path: path, file: this.getFile(path, true), query: parseQuery(query) } }; HashHistory.prototype.toURL = function toURL (path, params, currentRoute) { return '#' + History$$1.prototype.toURL.call(this, path, params, currentRoute) }; return HashHistory; }(History)); var HTML5History = (function (History$$1) { function HTML5History (config) { History$$1.call(this, config); this.mode = 'history'; } if ( History$$1 ) HTML5History.__proto__ = History$$1; HTML5History.prototype = Object.create( History$$1 && History$$1.prototype ); HTML5History.prototype.constructor = HTML5History; HTML5History.prototype.getCurrentPath = function getCurrentPath () { var base = this.getBasePath(); var path = window.location.pathname; if (base && path.indexOf(base) === 0) { path = path.slice(base.length); } return (path || '/') + window.location.search + window.location.hash }; HTML5History.prototype.onchange = function onchange (cb) { if ( cb === void 0 ) cb = noop; on('click', function (e) { var el = e.target.tagName === 'A' ? e.target : e.target.parentNode; if (el.tagName === 'A' && !/_blank/.test(el.target)) { e.preventDefault(); var url = el.href; window.history.pushState({ key: url }, '', url); cb(); } }); on('popstate', cb); }; /** * Parse the url * @param {string} [path=location.href] * @return {object} { path, query } */ HTML5History.prototype.parse = function parse (path) { if ( path === void 0 ) path = location.href; var query = ''; var queryIndex = path.indexOf('?'); if (queryIndex >= 0) { query = path.slice(queryIndex + 1); path = path.slice(0, queryIndex); } var base = getPath(location.origin); var baseIndex = path.indexOf(base); if (baseIndex > -1) { path = path.slice(baseIndex + base.length); } return { path: path, file: this.getFile(path), query: parseQuery(query) } }; return HTML5History; }(History)); function routerMixin (proto) { proto.route = {}; } var lastRoute = {}; function updateRender (vm) { vm.router.normalize(); vm.route = vm.router.parse(); body.setAttribute('data-page', vm.route.file); } function initRouter (vm) { var config = vm.config; var mode = config.routerMode || 'hash'; var router; if (mode === 'history' && supportsPushState) { router = new HTML5History(config); } else { router = new HashHistory(config); } vm.router = router; updateRender(vm); lastRoute = vm.route; router.onchange(function (_) { updateRender(vm); vm._updateRender(); if (lastRoute.path === vm.route.path) { vm.$resetEvents(); return } vm.$fetch(); lastRoute = vm.route; }); } function eventMixin (proto) { proto.$resetEvents = function () { scrollIntoView(this.route.path, this.route.query.id); getAndActive(this.router, 'nav'); }; } function initEvent (vm) { // Bind toggle button btn('button.sidebar-toggle', vm.router); collapse('.sidebar', vm.router); // Bind sticky effect if (vm.config.coverpage) { !isMobile && on('scroll', sticky); } else { body.classList.add('sticky'); } } function loadNested (path, qs, file, next, vm, first) { path = first ? path : path.replace(/\/$/, ''); path = getParentPath(path); if (!path) { return } get( vm.router.getFile(path + file) + qs, false, vm.config.requestHeaders ).then(next, function (_) { return loadNested(path, qs, file, next, vm); }); } function fetchMixin (proto) { var last; proto._fetch = function (cb) { var this$1 = this; if ( cb === void 0 ) cb = noop; var ref = this.route; var path = ref.path; var query = ref.query; var qs = stringifyQuery(query, ['id']); var ref$1 = this.config; var loadNavbar = ref$1.loadNavbar; var loadSidebar = ref$1.loadSidebar; var requestHeaders = ref$1.requestHeaders; // Abort last request last && last.abort && last.abort(); last = get(this.router.getFile(path) + qs, true, requestHeaders); // Current page is html this.isHTML = /\.html$/g.test(path); var loadSideAndNav = function () { if (!loadSidebar) { return cb() } var fn = function (result) { this$1._renderSidebar(result); cb(); }; // Load sidebar loadNested(path, qs, loadSidebar, fn, this$1, true); }; // Load main content last.then( function (text, opt) { this$1._renderMain(text, opt, loadSideAndNav); }, function (_) { this$1._renderMain(null, {}, loadSideAndNav); } ); // Load nav loadNavbar && loadNested( path, qs, loadNavbar, function (text) { return this$1._renderNav(text); }, this, true ); }; proto._fetchCover = function () { var this$1 = this; var ref = this.config; var coverpage = ref.coverpage; var requestHeaders = ref.requestHeaders; var query = this.route.query; var root = getParentPath(this.route.path); if (coverpage) { var path = null; var routePath = this.route.path; if (typeof coverpage === 'string') { if (routePath === '/') { path = coverpage; } } else if (Array.isArray(coverpage)) { path = coverpage.indexOf(routePath) > -1 && '_coverpage'; } else { var cover = coverpage[routePath]; path = cover === true ? '_coverpage' : cover; } var coverOnly = !!path && this.config.onlyCover; if (path) { path = this.router.getFile(root + path); this.coverIsHTML = /\.html$/g.test(path); get(path + stringifyQuery(query, ['id']), false, requestHeaders).then( function (text) { return this$1._renderCover(text, coverOnly); } ); } else { this._renderCover(null, coverOnly); } return coverOnly } }; proto.$fetch = function (cb) { var this$1 = this; if ( cb === void 0 ) cb = noop; var done = function () { callHook(this$1, 'doneEach'); cb(); }; var onlyCover = this._fetchCover(); if (onlyCover) { done(); } else { this._fetch(function (result) { this$1.$resetEvents(); done(); }); } }; } function initFetch (vm) { var ref = vm.config; var loadSidebar = ref.loadSidebar; // server-client renderer if (vm.rendered) { var activeEl = getAndActive(vm.router, '.sidebar-nav', true, true); if (loadSidebar && activeEl) { activeEl.parentNode.innerHTML += window.__SUB_SIDEBAR__; } vm._bindEventOnRendered(activeEl); vm.$resetEvents(); callHook(vm, 'doneEach'); callHook(vm, 'ready'); } else { vm.$fetch(function (_) { return callHook(vm, 'ready'); }); } } function initMixin (proto) { proto._init = function () { var vm = this; vm.config = config || {}; initLifecycle(vm); // Init hooks initPlugin(vm); // Install plugins callHook(vm, 'init'); initRouter(vm); // Add router initRender(vm); // Render base DOM initEvent(vm); // Bind events initFetch(vm); // Fetch data callHook(vm, 'mounted'); }; } function initPlugin (vm) { [].concat(vm.config.plugins).forEach(function (fn) { return isFn(fn) && fn(vm._lifecycle, vm); }); } var util = Object.freeze({ cached: cached, hyphenate: hyphenate, merge: merge, isPrimitive: isPrimitive, noop: noop, isFn: isFn, inBrowser: inBrowser, isMobile: isMobile, supportsPushState: supportsPushState, parseQuery: parseQuery, stringifyQuery: stringifyQuery, getPath: getPath, isAbsolutePath: isAbsolutePath, getParentPath: getParentPath, cleanPath: cleanPath, replaceSlug: replaceSlug }); function initGlobalAPI () { window.Docsify = { util: util, dom: dom, get: get, slugify: slugify }; window.DocsifyCompiler = Compiler; window.marked = marked; window.Prism = prism; } /** * Fork https://github.com/bendrucker/document-ready/blob/master/index.js */ function ready (callback) { var state = document.readyState; if (state === 'complete' || state === 'interactive') { return setTimeout(callback, 0) } document.addEventListener('DOMContentLoaded', callback); } function Docsify () { this._init(); } var proto = Docsify.prototype; initMixin(proto); routerMixin(proto); renderMixin(proto); fetchMixin(proto); eventMixin(proto); /** * Global API */ initGlobalAPI(); /** * Version */ Docsify.version = '4.6.2'; /** * Run Docsify */ ready(function (_) { return new Docsify(); }); }());
{'content_hash': 'aa9f744945386d74a8519b7db2e284ec', 'timestamp': '', 'source': 'github', 'line_count': 4389, 'max_line_length': 595, 'avg_line_length': 24.051948051948052, 'alnum_prop': 0.5499412678564662, 'repo_name': 'ahocevar/cdnjs', 'id': 'bcfefb1f6130897ec31c20d7df65e202175bf123', 'size': '105574', 'binary': False, 'copies': '10', 'ref': 'refs/heads/master', 'path': 'ajax/libs/docsify/4.6.2/docsify.js', 'mode': '33188', 'license': 'mit', 'language': []}
package org.wso2.andes.store.cassandra; import me.prettyprint.cassandra.model.ConfigurableConsistencyLevel; import me.prettyprint.cassandra.model.thrift.ThriftCounterColumnQuery; import me.prettyprint.cassandra.serializers.ByteBufferSerializer; import me.prettyprint.cassandra.serializers.BytesArraySerializer; import me.prettyprint.cassandra.serializers.IntegerSerializer; import me.prettyprint.cassandra.serializers.LongSerializer; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.cassandra.service.ThriftCfDef; import me.prettyprint.cassandra.service.ThriftKsDef; import me.prettyprint.hector.api.Cluster; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.beans.ColumnSlice; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HCounterColumn; import me.prettyprint.hector.api.beans.OrderedRows; import me.prettyprint.hector.api.beans.Row; import me.prettyprint.hector.api.beans.Rows; import me.prettyprint.hector.api.ddl.ColumnFamilyDefinition; import me.prettyprint.hector.api.ddl.ColumnType; import me.prettyprint.hector.api.ddl.ComparatorType; import me.prettyprint.hector.api.ddl.KeyspaceDefinition; import me.prettyprint.hector.api.exceptions.HUnavailableException; import me.prettyprint.hector.api.exceptions.HectorException; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.ColumnQuery; import me.prettyprint.hector.api.query.CounterQuery; import me.prettyprint.hector.api.query.MultigetSliceQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.RangeSlicesQuery; import me.prettyprint.hector.api.query.SliceQuery; import org.apache.commons.lang.StringUtils; import org.wso2.andes.kernel.AndesException; import org.wso2.andes.kernel.AndesMessageMetadata; import org.wso2.andes.kernel.AndesMessagePart; import org.wso2.andes.kernel.MessageExpirationWorker; import org.wso2.andes.store.AndesStoreUnavailableException; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; /** * Class <code>HectorDataAccessHelper</code> Encapsulate the Cassandra DataAccessLogic used in * org.wso2.andes.store.cassandra.HectorBasedAndesContextStoreImpl and org.wso2.andes * .store.cassandra.hector.HectorBasedMessageStoreImpl */ public class HectorDataAccessHelper { /** The error message emitted hector client library when it loose connectivity to all known cassandra hosts */ private static final String HECTOR_CONNECTION_ERROR_MESSAGE = "All host pools marked down. Retry burden pushed out to client"; public static final int STANDARD_PAGE_SIZE = 1000; /** * Serializes used for Cassandra data operations */ private static StringSerializer stringSerializer = StringSerializer.get(); private static LongSerializer longSerializer = LongSerializer.get(); private static BytesArraySerializer bytesArraySerializer = BytesArraySerializer.get(); private static IntegerSerializer integerSerializer = IntegerSerializer.get(); private static ByteBufferSerializer byteBufferSerializer = ByteBufferSerializer.get(); /** * The number of records read in "listAllStringRows" method. */ private final static int MAX_NUMBER_OF_ROWS_TO_READ = 1000; /** * Create a keySpace in a given cluster * * @param cluster Cluster where Keyspace should be created * @param keySpaceName name of the Cassandra KeySpace * @return Keyspace */ public static Keyspace createKeySpace(Cluster cluster, String keySpaceName, int replicationFactor, String strategyClass, ConfigurableConsistencyLevel policy) { //Define the keySpaceName ThriftKsDef thriftKsDef = new ThriftKsDef(keySpaceName); thriftKsDef.setReplicationFactor(replicationFactor); if (strategyClass == null || strategyClass.isEmpty()) { strategyClass = ThriftKsDef.DEF_STRATEGY_CLASS; } thriftKsDef.setStrategyClass(strategyClass); KeyspaceDefinition definition = cluster.describeKeyspace(keySpaceName); if (definition == null) { //Adding keySpaceName to the cluster cluster.addKeyspace(thriftKsDef, true); } Keyspace keyspace = HFactory.createKeyspace(keySpaceName, cluster); // Setting consistency policy keyspace.setConsistencyLevelPolicy(policy); return keyspace; } /** * Create a Column family in a Given Cluster instance * * @param name ColumnFamily Name * @param keySpace KeySpace name * @param cluster Cluster instance * @param comparatorType Comparator * @param gcGraceSeconds gc_grace_second option in cassandra * @throws CassandraDataAccessException In case of an Error accessing database or data error */ public static void createColumnFamily(String name, String keySpace, Cluster cluster, String comparatorType, int gcGraceSeconds) throws AndesStoreUnavailableException, CassandraDataAccessException { try { KeyspaceDefinition keyspaceDefinition = cluster.describeKeyspace(keySpace); if (keyspaceDefinition == null) { throw new IllegalStateException("Can't create Column family, keyspace " + keySpace + " does not exist"); } ColumnFamilyDefinition columnFamilyDefinition = new ThriftCfDef( keySpace, name, ComparatorType.getByClassName(comparatorType)); columnFamilyDefinition.setGcGraceSeconds(gcGraceSeconds); List<ColumnFamilyDefinition> cfDefinitionList = keyspaceDefinition.getCfDefs(); HashSet<String> columnFamilyNames = new HashSet<String>(); for (ColumnFamilyDefinition definition : cfDefinitionList) { columnFamilyNames.add(definition.getName()); } if (!columnFamilyNames.contains(name)) { cluster.addColumnFamily(columnFamilyDefinition, true); } } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("Unable to create the column family " + name + " consistency level was not met", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Unable to create keyspace " + name + "cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while creating:" + name, e); } } } /** * Create a Column family for cassandra counters in a given Cluster instance * * @param name ColumnFamily Name * @param cluster Cluster instance * @throws CassandraDataAccessException In case of an Error accessing database or data error */ public static void createCounterColumnFamily(String name, String keySpace, Cluster cluster, int gcGraceSeconds) throws CassandraDataAccessException, AndesStoreUnavailableException { try { KeyspaceDefinition ksDef = cluster.describeKeyspace(keySpace); if (ksDef == null) { throw new IllegalStateException("Can't create Column family, keyspace " + keySpace + " does not exist"); } ColumnFamilyDefinition cfDef = HFactory.createColumnFamilyDefinition(keySpace, name, ComparatorType.COUNTERTYPE); cfDef.setGcGraceSeconds(gcGraceSeconds); cfDef.setComparatorType(ComparatorType.UTF8TYPE); cfDef.setDefaultValidationClass(ComparatorType.COUNTERTYPE.getClassName()); cfDef.setColumnType(ColumnType.STANDARD); List<ColumnFamilyDefinition> cfDefsList = ksDef.getCfDefs(); HashSet<String> cfNames = new HashSet<String>(); for (ColumnFamilyDefinition columnFamilyDefinition : cfDefsList) { cfNames.add(columnFamilyDefinition.getName()); } if (!cfNames.contains(name)) { cluster.addColumnFamily(cfDef, true); } } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("Unable to create the column family " + name + " consistency level was not met", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Unable to create keyspace " + name + "cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while creating:" + name, e); } } } /** * Method to initialize the MESSAGES_FOR_EXPIRY_COLUMN_FAMILY Column Family in cql style * * @param name * @param keySpace * @param cluster * @throws CassandraDataAccessException */ public static void createMessageExpiryColumnFamily(String name, String keySpace, Cluster cluster, String comparatorType, int gcGraceSeconds) throws CassandraDataAccessException, AndesStoreUnavailableException { try { KeyspaceDefinition ksDef = cluster.describeKeyspace(keySpace); if (ksDef == null) { throw new IllegalStateException("Can't create Column family, keyspace " + keySpace + " does not exist"); } ColumnFamilyDefinition cfDef = new ThriftCfDef(keySpace, /* "Queue" */name, ComparatorType.getByClassName(comparatorType)); cfDef.setGcGraceSeconds(gcGraceSeconds); List<ColumnFamilyDefinition> cfDefsList = ksDef.getCfDefs(); HashSet<String> cfNames = new HashSet<String>(); for (ColumnFamilyDefinition columnFamilyDefinition : cfDefsList) { cfNames.add(columnFamilyDefinition.getName()); } if (!cfNames.contains(name)) { cluster.addColumnFamily(cfDef, true); } } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("Unable to create the column family " + name + " consistency level was not met", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Unable to create keyspace " + name + "cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while creating:" + name, e); } } } /** * Insert a raw-column for counting a property (row is property, column is item) * * @param cfName column family name * @param counterRowName name of row * @param queueColumn name of column * @param keyspace key space name * @throws CassandraDataAccessException */ public static void insertCounterColumn(String cfName, String counterRowName, String queueColumn, Keyspace keyspace) throws AndesStoreUnavailableException, CassandraDataAccessException { try { Mutator<String> mutator = HFactory.createMutator(keyspace, StringSerializer.get()); // inserting counter column mutator.insertCounter(counterRowName, cfName, HFactory.createCounterColumn (queueColumn, 0L, StringSerializer.get())); mutator.execute(); CounterQuery<String, String> counter = new ThriftCounterColumnQuery<String, String>( keyspace, stringSerializer, stringSerializer); counter.setColumnFamily(cfName).setKey(counterRowName).setName(queueColumn); } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Unable to insert data since " + "cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while inserting data to:" + cfName, e); } } } /** * Remove allocated raw-column space for counter * * @param cfName column family name * @param counterRowName name of row * @param queueColumn name of column * @param keyspace key space name * @throws CassandraDataAccessException */ public static void removeCounterColumn(String cfName, String counterRowName, String queueColumn, Keyspace keyspace) throws AndesStoreUnavailableException, CassandraDataAccessException { try { Mutator<String> mutator = HFactory.createMutator(keyspace, StringSerializer.get()); mutator.deleteCounter(counterRowName, cfName, queueColumn, stringSerializer); mutator.execute(); CounterQuery<String, String> counter = new ThriftCounterColumnQuery<String, String>( keyspace, stringSerializer, stringSerializer); counter.setColumnFamily(cfName).setKey(counterRowName).setName(queueColumn); } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Unable to access data as " + "cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while accessing:" + cfName, e); } } } /** * Increment counter by given value * * @param rawID raw name * @param columnFamily column family name * @param columnName name of column * @param keyspace keyspace * @param incrementBy value to increase by * @throws CassandraDataAccessException */ public static void incrementCounter(String columnName, String columnFamily, String rawID, Keyspace keyspace, long incrementBy) throws AndesStoreUnavailableException, CassandraDataAccessException { try { Mutator<String> mutator = HFactory.createMutator(keyspace, StringSerializer.get()); mutator.incrementCounter(rawID, columnFamily, columnName, incrementBy); mutator.execute(); } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while accessing " + columnFamily + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while accessing:" + columnFamily, e); } } } /** * Decrement counter by a given value * * @param rawID raw name * @param columnFamily column family name * @param columnName name of column * @param keyspace keyspace * @throws CassandraDataAccessException */ public static void decrementCounter(String columnName, String columnFamily, String rawID, Keyspace keyspace, long decrementBy) throws AndesStoreUnavailableException, CassandraDataAccessException { try { Mutator<String> mutator = HFactory.createMutator(keyspace, StringSerializer.get()); mutator.decrementCounter(rawID, columnFamily, columnName, decrementBy); mutator.execute(); } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException he) { if (he.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while accessing " + columnFamily + " since cassandra connection is down", he); } else { throw new CassandraDataAccessException("Error while accessing:" + columnFamily, he); } } } /** * Get the value of a counter * * @param keyspace name of key space * @param columnFamily column family name * @param key key value (property) * @param cloumnName column name (item) * @return long count value * @throws CassandraDataAccessException */ public static long getCountValue(Keyspace keyspace, String columnFamily, String cloumnName, String key) throws AndesStoreUnavailableException, CassandraDataAccessException { try { long count = 0; CounterQuery<String, String> query = HFactory.createCounterColumnQuery(keyspace, stringSerializer, stringSerializer); query.setColumnFamily(columnFamily).setKey(key).setName(cloumnName); HCounterColumn<String> counter = query.execute().get(); if (counter != null) { count = counter.getValue(); } return count; } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while accessing " + columnFamily + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while accessing:" + columnFamily, e); } } } /** * Get the meta data stored for a given message ID * * @param columnFamilyName name of the column family * @param keyspace Cassandra Keyspace * @param messageId ID of the message * @return the metadata stored in Cassandra as a byte array * @throws CassandraDataAccessException */ public static byte[] getMessageMetaDataOfMessage(String columnFamilyName, Keyspace keyspace, long messageId) throws AndesStoreUnavailableException, CassandraDataAccessException { byte[] value = null; if (keyspace == null) { throw new IllegalArgumentException("Can't access Data , no keyspace provided "); } if (columnFamilyName == null) { throw new IllegalArgumentException("Can't access data with queueType = " + columnFamilyName); } try { RangeSlicesQuery<String, Long, byte[]> sliceQuery = HFactory.createRangeSlicesQuery(keyspace, stringSerializer, longSerializer, bytesArraySerializer); sliceQuery.setRange(null, null, false, Integer.MAX_VALUE); sliceQuery.setKeys(null, null); sliceQuery.setColumnNames(messageId); sliceQuery.setColumnFamily(columnFamilyName); QueryResult<OrderedRows<String, Long, byte[]>> result = sliceQuery.execute(); if (result == null || result.get().getList().size() == 0) { value = null; } else { Row<String, Long, byte[]> rowSlice = result.get().peekLast(); ColumnSlice<Long, byte[]> columnSlice = rowSlice.getColumnSlice(); for (Object column : columnSlice.getColumns()) { if (column instanceof HColumn) { value = ((HColumn<Long, byte[]>) column).getValue(); } } } return value; } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while getting data from " + columnFamilyName + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while getting data from " + columnFamilyName, e); } } } /** * Get set of <ColumnName,ColumnValue> list in a column family with a offset and a maximum cont * (row-STRING,column-LONG,Value-ByteArray). Used to get messages * form cassandra * * @param rowName name of row (queue name) * @param columnFamilyName ColumnFamilyName * @param keyspace Cassandra KeySpace * @param lastProcessedId Last processed Message id to use as a offset * @param count max message count limit * @throws CassandraDataAccessException */ public static List<AndesMessageMetadata> getMessagesFromQueue(String rowName, String columnFamilyName, Keyspace keyspace, long firstID, long lastProcessedId, int count, boolean parse ) throws AndesStoreUnavailableException, CassandraDataAccessException { if (keyspace == null) { throw new IllegalArgumentException("Can't access Data , no keyspace provided "); } if (columnFamilyName == null || rowName == null) { throw new IllegalArgumentException("Can't access data with queueType = " + columnFamilyName + " and queueName=" + rowName); } try { SliceQuery<String, Long, byte[]> sliceQuery = HFactory.createSliceQuery(keyspace, stringSerializer, longSerializer, bytesArraySerializer); sliceQuery.setKey(rowName); sliceQuery.setRange(firstID, lastProcessedId, false, count); sliceQuery.setColumnFamily(columnFamilyName); QueryResult<ColumnSlice<Long, byte[]>> result = sliceQuery.execute(); ColumnSlice<Long, byte[]> columnSlice = result.get(); List<AndesMessageMetadata> metadataList = new ArrayList<AndesMessageMetadata>(); for (Object column : columnSlice.getColumns()) { if (column instanceof HColumn) { AndesMessageMetadata metadata = new AndesMessageMetadata(((HColumn<Long, byte[]>) column).getName(), ((HColumn<Long, byte[]>) column).getValue(), parse); if (!MessageExpirationWorker.isExpired(metadata.getExpirationTime())) { metadataList.add(metadata); } } } return metadataList; } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while getting data from " + columnFamilyName + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while getting data from " + columnFamilyName, e); } } } /** * Get all columns in a given row of a cassandra column family * * @param rowName row Name we are querying for * @param columnFamilyName column family name * @param keyspace Cassandra Keyspace * @param count number of columns the column slice should contain * @return */ public static ColumnSlice<String, String> getStringTypeColumnsInARow(String rowName, String columnFamilyName, Keyspace keyspace, int count) throws AndesStoreUnavailableException, CassandraDataAccessException { if (keyspace == null) { throw new IllegalArgumentException("Can't access Data , no keyspace provided"); } if (StringUtils.isBlank(columnFamilyName) || StringUtils.isBlank(rowName)) { throw new IllegalArgumentException("Can't access data with queueType = " + columnFamilyName + " and rowName=" + rowName); } try { SliceQuery<String,String,String> sliceQuery = HFactory.createSliceQuery(keyspace, stringSerializer, stringSerializer, stringSerializer); sliceQuery.setKey(rowName); sliceQuery.setColumnFamily(columnFamilyName); sliceQuery.setRange("", "", false, count); QueryResult<ColumnSlice<String, String>> result = sliceQuery.execute(); ColumnSlice<String, String> columnSlice = result.get(); return columnSlice; } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while getting data from " + columnFamilyName + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while getting data from : " + columnFamilyName, e); } } } /** * Method used to retrieve <long> list of a column keys from a given row. (in our case, message ID) * @param keyspace keyspace reference * @param columnFamilyName name of the column family * @param rowKey row key of which the column keys are required * @param count number of column keys to fetch * @param lastProcessedID last processed column key ID, so that this request can continue from that point. * @return List<Long> * @throws CassandraDataAccessException */ public static List<Long> getNumericColumnKeysOfRow(Keyspace keyspace, String columnFamilyName, String rowKey, int count, Long lastProcessedID) throws AndesStoreUnavailableException, CassandraDataAccessException { if (keyspace == null) { throw new IllegalArgumentException("Can't access Data , no keyspace provided"); } if (StringUtils.isBlank(columnFamilyName) || StringUtils.isBlank(rowKey)) { throw new IllegalArgumentException("Can't access data with queueType = " + columnFamilyName + " and row key =" + rowKey); } List<Long> messageIDs = new ArrayList<Long>(); try { SliceQuery<String, Long, byte[]> sliceQuery = HFactory.createSliceQuery(keyspace, stringSerializer, longSerializer, bytesArraySerializer); sliceQuery.setKey(rowKey); sliceQuery.setRange(lastProcessedID, null, false, count); sliceQuery.setColumnFamily(columnFamilyName); QueryResult<ColumnSlice<Long, byte[]>> result = sliceQuery.execute(); ColumnSlice<Long, byte[]> columnSlice = result.get(); for (Object column : columnSlice.getColumns()) { if (column instanceof HColumn) { messageIDs.add(((HColumn<Long, byte[]>) column).getName()); } } return messageIDs; } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new CassandraDataAccessException("Error while getting data from " + columnFamilyName + " since cassandra connection is down", e); } else { throw new AndesStoreUnavailableException("Error while getting data from " + columnFamilyName, e); } } } /** * Add message to a queue * * @param columnFamily column family name * @param queue name of queue (row name) * @param key message ID of the message (column name) * @param message message content * @param mutator mutator to execute the query * @param execute whether to execute the query * @throws CassandraDataAccessException */ public static void addMessageToQueue(String columnFamily, String queue, int key, byte[] message, Mutator<String> mutator, boolean execute) throws AndesStoreUnavailableException, CassandraDataAccessException { if (mutator == null) { throw new IllegalArgumentException("Can't add Data , no mutator provided"); } if (StringUtils.isBlank(columnFamily) || StringUtils.isBlank(queue) || message == null) { throw new IllegalArgumentException("Can't add data with queueType = " + columnFamily + " and queue=" + queue + " offset = " + key + " message = " + message); } try { mutator.addInsertion(queue.trim(), columnFamily, HFactory.createColumn(key, message, integerSerializer, BytesArraySerializer.get())); if (execute) { mutator.execute(); } } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while adding message to Queue " + queue + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while adding message to Queue", e); } } } /** * Add message to a queue * * @param columnFamily column family name * @param queue name of queue (row name) * @param messageId message ID of the message (column name) * @param message message content * @param mutator mutator to execute the query * @param execute whether to execute the query * @throws CassandraDataAccessException */ public static void addMessageToQueue(String columnFamily, String queue, long messageId, byte[] message, Mutator<String> mutator, boolean execute) throws AndesStoreUnavailableException, CassandraDataAccessException { if (mutator == null) { throw new IllegalArgumentException("Can't add Data , no mutator provided "); } if (columnFamily == null || queue == null || message == null) { throw new IllegalArgumentException("Can't add data with queueType = " + columnFamily + " and queue=" + queue + " message id = " + messageId + " " + "message = " + message); } try { mutator.addInsertion(queue.trim(), columnFamily, HFactory.createColumn(messageId, message, LongSerializer.get(), BytesArraySerializer.get())); if (execute) { mutator.execute(); } } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while adding message to Queue " + queue + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while adding message to Queue", e); } } } /** * Add a <String,String> Mapping to a Given Row in cassandra column family. * Mappings are used as search indexes * * @param columnFamily columnFamilyName * @param row row name * @param cKey key name for the adding column * @param cValue value for the adding column * @param keyspace Cassandra KeySpace * @throws CassandraDataAccessException In case of database access error or data error */ public static void addMappingToRaw(String columnFamily, String row, String cKey, String cValue, Keyspace keyspace) throws AndesStoreUnavailableException, CassandraDataAccessException { if (keyspace == null) { throw new IllegalArgumentException("Can't add Data , no KeySpace provided "); } if (columnFamily == null || row == null || cKey == null) { throw new IllegalArgumentException("Can't add data with queueType = " + columnFamily + " and rowName=" + row + " key = " + cKey); } try { Mutator<String> mutator = HFactory.createMutator(keyspace, stringSerializer); mutator.addInsertion(row, columnFamily, HFactory.createColumn(cKey, cValue.trim(), stringSerializer, stringSerializer)); mutator.execute(); } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while adding a mapping to row " + row + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while adding a mapping to row ", e); } } } /** * Delete a given string column in a raw in a column family * * @param columnFamily column family name * @param row row name * @param key key name * @param keyspace cassandra keySpace * @throws CassandraDataAccessException In case of database access error or data error */ public static void deleteStringColumnFromRaw(String columnFamily, String row, String key, Keyspace keyspace) throws AndesStoreUnavailableException, CassandraDataAccessException { if (keyspace == null) { throw new IllegalArgumentException("Can't delete Data , no keyspace provided "); } if (columnFamily == null || row == null || key == null) { throw new CassandraDataAccessException("Can't delete data in queueType = " + columnFamily + " and rowName=" + row + " key = " + key); } try { Mutator<String> mutator = HFactory.createMutator(keyspace, stringSerializer); mutator.addDeletion(row, columnFamily, key, stringSerializer); mutator.execute(); } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while deleting " + key + " from " + columnFamily + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while deleting " + key + " from " + columnFamily); } } } /** * Delete a given long column in a raw in a column family. * * @param columnFamily name of column family * @param row name of row * @param key column key * @param mutator mutator * @param execute whether to execute the mutator * @throws CassandraDataAccessException */ public static void deleteLongColumnFromRaw(String columnFamily, String row, long key, Mutator<String> mutator, boolean execute) throws AndesStoreUnavailableException, CassandraDataAccessException { if (mutator == null) { throw new IllegalArgumentException("Can't delete Data , no mutator provided "); } if (columnFamily == null || row == null) { throw new IllegalArgumentException("Can't delete data in queueType = " + columnFamily + " and rowName=" + row + " key = " + key); } try { mutator.addDeletion(row, columnFamily, key, longSerializer); if (execute) { mutator.execute(); } } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while deleting " + key + " from " + row + " since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while deleting " + key + " from " + row); } } } /** * Delete a list of integer rows from a column family * * @param columnFamily name of column family * @param rows list of rows to be removed * @param mutator mutator * @throws CassandraDataAccessException */ public static void deleteIntegerRowListFromColumnFamily(String columnFamily, List<String> rows, Mutator<String> mutator, boolean execute) throws AndesStoreUnavailableException, CassandraDataAccessException { if (mutator == null) { throw new IllegalArgumentException("Can't delete Data , no mutator provided "); } if (columnFamily == null || rows == null) { throw new IllegalArgumentException("Can't delete data in queueType = " + columnFamily + " and rowName=" + rows); } try { mutator.addDeletion(rows, columnFamily); if (execute) { mutator.execute(); } } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while deleting data since " + "cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while deleting data", e); } } } /** * List all string rows * * @param columnFamilyName name of the column family * @param keyspace Cassandra Keyspace * @return Map of Rows */ public static Map<String, List<String>> listAllStringRows(String columnFamilyName, Keyspace keyspace) throws AndesException , CassandraDataAccessException { try{ Map<String, List<String>> results = new HashMap<String, List<String>>(); RangeSlicesQuery<String, String, String> rangeSlicesQuery = HFactory .createRangeSlicesQuery(keyspace, stringSerializer, stringSerializer, stringSerializer); rangeSlicesQuery.setColumnFamily(columnFamilyName); rangeSlicesQuery.setRange("", "", false, MAX_NUMBER_OF_ROWS_TO_READ); QueryResult<OrderedRows<String, String, String>> result = rangeSlicesQuery .execute(); for (Row<String, String, String> row : result.get().getList()) { List<String> list = new ArrayList<String>(); String rowkey = new String(row.getKey().getBytes()); for (HColumn<String, String> hc : row.getColumnSlice().getColumns()) { list.add(hc.getValue()); } results.put(rowkey, list); } return results; } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while deleting data since " + "cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while deleting data", e); } } } /** * Read message content as a batch in cassandra * * @param columnFamily name of column family * @param keyspace name of key space * @param messageId list of message IDs * @return List of content List<AndesMessagePart> * @throws CassandraDataAccessException */ public static Map<Long, List<AndesMessagePart>> getMessageContentBatch( String columnFamily, Keyspace keyspace, List<Long> messageId) throws AndesStoreUnavailableException, CassandraDataAccessException { //Holds the messages that will be sent back to the API for delivery Map<Long, List<AndesMessagePart>> messageContentBatch = new HashMap<Long, List<AndesMessagePart>>(); try { //Specify the range of offsets in a message Integer startOffSet = 0; Integer maxOffset = Integer.MAX_VALUE; //TODO remove this once the mid is taken out from hector //TODO need to verify the reason for appending mid for the hector case List<String> sanitizedMessageID = new ArrayList<String>(); //Need to prefix the message id since in the DB the message comes sanitized for (int msgIDs = 0; msgIDs < messageId.size(); msgIDs++) { sanitizedMessageID.add(HectorBasedMessageStoreImpl.MESSAGE_CONTENT_CASSANDRA_ROW_NAME_PREFIX + messageId.get(msgIDs)); } //Create the query to get the list of messages for the specified list of ids //SELECT * FROM MB_KEYSPACE.MB_CONTENT WHERE "QpidKeySpace"."MessageContent" Collection<String> messageIDs = sanitizedMessageID; MultigetSliceQuery<String, Integer, ByteBuffer> getMessageListQuery = HFactory .createMultigetSliceQuery(keyspace, stringSerializer, integerSerializer, byteBufferSerializer); getMessageListQuery.setColumnFamily(columnFamily); getMessageListQuery.setRange(startOffSet, maxOffset, false, maxOffset); getMessageListQuery.setKeys(messageIDs); //The data structure holds message represented as ids in each row, messageID ---> offsets (1..*) // Each chunk will be defined as an offset, which which will be the column // i.e messageID offset 0 offset 1 //First for the given list of ids all the messages will be fetched from the database //Will return each row represented through the list of provided message ids QueryResult<Rows<String, Integer, ByteBuffer>> results = getMessageListQuery.execute(); //Will go through the list of rows for (Row<String, Integer, ByteBuffer> messageIDRows : results.get()) { //Each column will represent an offset that will hold the message chunk List<HColumn<Integer, ByteBuffer>> columnSliced = messageIDRows.getColumnSlice().getColumns(); //This will be the id of the message Long columnKey = Long.valueOf(messageIDRows.getKey(). substring(HectorBasedMessageStoreImpl.MESSAGE_CONTENT_CASSANDRA_ROW_NAME_PREFIX.length())); //Will iterate through each slice, each slice will represent an offset for (HColumn<Integer, ByteBuffer> column : columnSliced) { if (column != null) { int offset = column.getName(); byte[] content = bytesArraySerializer.fromByteBuffer(column .getValue()); List<AndesMessagePart> andesMessagePart = messageContentBatch.get(columnKey); if (null == andesMessagePart) { andesMessagePart = new ArrayList<AndesMessagePart>(); messageContentBatch.put(columnKey, andesMessagePart); } AndesMessagePart msgPart = new AndesMessagePart(); msgPart.setMessageID(columnKey); msgPart.setDataLength(content.length); msgPart.setOffSet(offset); msgPart.setData(content); andesMessagePart.add(msgPart); } else { throw new RuntimeException("Unexpected Error , content already deleted for " + "message id :" + messageId); } } } } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); } catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while getting message content " + "since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while getting message content", e); } } return messageContentBatch; } /** * Read message content from Cassandra * * @param rowKey row name * @param columnFamily name of the column family * @param keyspace Cassandra Keyspace * @param messageId ID of the message * @param offsetValue the offset of the message part * @return AndesMessagePart * @throws CassandraDataAccessException */ public static AndesMessagePart getMessageContent(String rowKey, String columnFamily, Keyspace keyspace, long messageId, int offsetValue) throws AndesStoreUnavailableException, CassandraDataAccessException { AndesMessagePart messagePart = new AndesMessagePart(); try { ColumnQuery<String, Integer, ByteBuffer> columnQuery = HFactory.createColumnQuery(keyspace, stringSerializer, integerSerializer, byteBufferSerializer); columnQuery.setColumnFamily(columnFamily); columnQuery.setKey(rowKey.trim()); columnQuery.setName(offsetValue); QueryResult<HColumn<Integer, ByteBuffer>> result = columnQuery.execute(); HColumn<Integer, ByteBuffer> column = result.get(); if (column != null) { int offset = column.getName(); byte[] content = bytesArraySerializer.fromByteBuffer(column .getValue()); messagePart.setData(content); messagePart.setMessageID(messageId); messagePart.setDataLength(content.length); messagePart.setOffSet(offset); } else { throw new RuntimeException("Unexpected Error , content already deleted for " + "message id :" + messageId); } } catch (HUnavailableException unavailEx) { throw new AndesStoreUnavailableException("unable to meet required consitancy level for the operation", unavailEx); }catch (HectorException e) { if (e.getMessage().contains(HECTOR_CONNECTION_ERROR_MESSAGE)) { throw new AndesStoreUnavailableException("Error while getting message content " + "since cassandra connection is down", e); } else { throw new CassandraDataAccessException("Error while getting message content", e); } } return messagePart; } }
{'content_hash': 'c5f043a68c025055cb25d390fb600c70', 'timestamp': '', 'source': 'github', 'line_count': 1121, 'max_line_length': 127, 'avg_line_length': 48.471900089206066, 'alnum_prop': 0.5757770947972837, 'repo_name': 'chanakaudaya/andes', 'id': 'eac1c7377f7791cfac774942780ae7850b461de2', 'size': '55015', 'binary': False, 'copies': '3', 'ref': 'refs/heads/master', 'path': 'modules/andes-core/broker/src/main/java/org/wso2/andes/store/cassandra/HectorDataAccessHelper.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '22770'}, {'name': 'HTML', 'bytes': '15583'}, {'name': 'Java', 'bytes': '11875284'}, {'name': 'Perl', 'bytes': '30872'}, {'name': 'Python', 'bytes': '82273'}, {'name': 'Shell', 'bytes': '117030'}, {'name': 'Smarty', 'bytes': '17916'}, {'name': 'Thrift', 'bytes': '2029'}, {'name': 'XSLT', 'bytes': '59112'}]}
using namespace Upp; struct MyAppData { String text; Color color; }; struct MyApp : TopWindow { Point pos; MyAppData data; Point dragpos; virtual void CancelMode(); virtual void Paint(Draw& w); virtual void DragAndDrop(Point p, PasteClip& clip); virtual void DragLeave(); virtual void LeftDrag(Point p, dword keyflags); MyApp(); }; void MyApp::CancelMode() { dragpos = Null; Refresh(); } void MyApp::DragAndDrop(Point p, PasteClip& clip) { if(clip.Accept("MyAppData")) { String bin = clip; if(bin.GetLength() > sizeof(Color)) { // prudent check pos = p; memcpy(&data.color, ~bin, sizeof(Color)); data.text = bin.Mid(sizeof(Color)); } Refresh(); } if(AcceptText(clip)) { pos = p; data.text = GetString(clip); } dragpos = clip.IsAccepted() ? p : Null; Refresh(); } void MyApp::DragLeave() { dragpos = Null; Refresh(); } void MyApp::LeftDrag(Point p, dword keyflags) { String bin; bin.Cat((byte *)&data.color, sizeof(data.color)); bin.Cat(data.text); VectorMap<String, ClipData> d; d.Add("MyAppData", bin); Append(d, data.text); Size sz(128, 64); ImageDraw iw(sz); iw.DrawRect(sz, Black()); iw.Alpha().DrawRect(sz, Black()); iw.Alpha().DrawText(0, 0, data.text, Courier(14), White()); DoDragAndDrop(d, iw); } void MyApp::Paint(Draw& w) { w.DrawRect(GetSize(), SColorPaper()); w.DrawText(pos.x, pos.y, data.text, StdFont(), data.color); if(!IsNull(dragpos)) w.DrawRect(RectC(dragpos.x - 1, dragpos.y - 1, 3, 3), LtBlue); } MyApp::MyApp() { data.text = FormatIntRoman(Random(2000)); data.color = Color(Random() & 127, Random() & 127, Random() & 127); pos = Point(10, 10); SetRect(0, 0, 500, 100); dragpos = Null; } GUI_APP_MAIN { MyApp().Run(); }
{'content_hash': '8f04e3c1a2f8050ce4f0d2567c7de34b', 'timestamp': '', 'source': 'github', 'line_count': 90, 'max_line_length': 68, 'avg_line_length': 20.22222222222222, 'alnum_prop': 0.6153846153846154, 'repo_name': 'dreamsxin/ultimatepp', 'id': '58e0590ebebcad025375cf105b8f354d60441e26', 'size': '1850', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'reference/DragAndDrop1/main.cpp', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'Assembly', 'bytes': '8477'}, {'name': 'C', 'bytes': '47921993'}, {'name': 'C++', 'bytes': '28354499'}, {'name': 'CSS', 'bytes': '659'}, {'name': 'JavaScript', 'bytes': '7006'}, {'name': 'Objective-C', 'bytes': '178854'}, {'name': 'Perl', 'bytes': '65041'}, {'name': 'Python', 'bytes': '38142'}, {'name': 'Shell', 'bytes': '91097'}, {'name': 'Smalltalk', 'bytes': '101'}, {'name': 'Turing', 'bytes': '661569'}]}
@interface TodoObject : RLMObject @end
{'content_hash': '9afaf11bb1897324c91c4a84955113fe', 'timestamp': '', 'source': 'github', 'line_count': 3, 'max_line_length': 33, 'avg_line_length': 13.333333333333334, 'alnum_prop': 0.775, 'repo_name': 'friendtree16/TodoList', 'id': '4bed53c27b0db0235f50e042573676f133a34dba', 'size': '200', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'TodoList/Model/DB/TodoObject.h', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Objective-C', 'bytes': '5880'}, {'name': 'Ruby', 'bytes': '452'}]}
package de.wolfi.minopoly.events; import de.wolfi.minopoly.components.Player; import de.wolfi.minopoly.components.fields.Field; public class FieldEvent extends MinopolyEvent{ private Field field; public FieldEvent(Player player, Field field) { super(player); this.field = field; } public Field getField() { return field; } }
{'content_hash': 'a592e63d741d3993de0ba1bd98dca75e', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 49, 'avg_line_length': 18.05263157894737, 'alnum_prop': 0.7521865889212828, 'repo_name': 'WOLFI3654/Minopoly', 'id': '07eb764452755a29d0e635fffd6d9380bf28cd95', 'size': '343', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/main/java/de/wolfi/minopoly/events/FieldEvent.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '148752'}]}
<!DOCTYPE html> <html lang="en"> <head> <!-- Charisma v1.0.0 Copyright 2012 Muhammad Usman Licensed under the Apache License v2.0 http://www.apache.org/licenses/LICENSE-2.0 http://usman.it http://twitter.com/halalit_usman --> <meta charset="utf-8"> <title>Free HTML5 Bootstrap Admin Template</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Charisma, a fully featured, responsive, HTML5, Bootstrap admin template."> <meta name="author" content="Muhammad Usman"> <!-- The styles --> <link id="bs-css" href="/resources/css/bootstrap-cerulean.css" rel="stylesheet"> <style type="text/css"> body { padding-bottom: 40px; } .sidebar-nav { padding: 9px 0; } </style> <link href="/resources/css/bootstrap-responsive.css" rel="stylesheet"> <link href="/resources/css/charisma-app.css" rel="stylesheet"> <link href="/resources/css/jquery-ui-1.8.21.custom.css" rel="stylesheet"> <link href='/resources/css/fullcalendar.css' rel='stylesheet'> <link href='/resources/css/fullcalendar.print.css' rel='stylesheet' media='print'> <link href='/resources/css/chosen.css' rel='stylesheet'> <link href='/resources/css/uniform.default.css' rel='stylesheet'> <link href='/resources/css/colorbox.css' rel='stylesheet'> <link href='/resources/css/jquery.cleditor.css' rel='stylesheet'> <link href='/resources/css/jquery.noty.css' rel='stylesheet'> <link href='/resources/css/noty_theme_default.css' rel='stylesheet'> <link href='/resources/css/elfinder.min.css' rel='stylesheet'> <link href='/resources/css/elfinder.theme.css' rel='stylesheet'> <link href='/resources/css/jquery.iphone.toggle.css' rel='stylesheet'> <link href='/resources/css/opa-icons.css' rel='stylesheet'> <link href='/resources/css/uploadify.css' rel='stylesheet'> <!-- The HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <!-- The fav icon --> <link rel="shortcut icon" href="/resources/img/favicon.ico"> </head> <body> <!-- topbar starts --> <div class="navbar"> <div class="navbar-inner"> <div class="container-fluid"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".top-nav.nav-collapse,.sidebar-nav.nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="index.html"> <img alt="Charisma Logo" src="/resources/img/logo20.png" /> <span>Charisma</span></a> <!-- theme selector starts --> <div class="btn-group pull-right theme-container" > <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"> <i class="icon-tint"></i><span class="hidden-phone"> Change Theme / Skin</span> <span class="caret"></span> </a> <ul class="dropdown-menu" id="themes"> <li><a data-value="classic" href="#"><i class="icon-blank"></i> Classic</a></li> <li><a data-value="cerulean" href="#"><i class="icon-blank"></i> Cerulean</a></li> <li><a data-value="cyborg" href="#"><i class="icon-blank"></i> Cyborg</a></li> <li><a data-value="redy" href="#"><i class="icon-blank"></i> Redy</a></li> <li><a data-value="journal" href="#"><i class="icon-blank"></i> Journal</a></li> <li><a data-value="simplex" href="#"><i class="icon-blank"></i> Simplex</a></li> <li><a data-value="slate" href="#"><i class="icon-blank"></i> Slate</a></li> <li><a data-value="spacelab" href="#"><i class="icon-blank"></i> Spacelab</a></li> <li><a data-value="united" href="#"><i class="icon-blank"></i> United</a></li> </ul> </div> <!-- theme selector ends --> <!-- user dropdown starts --> <div class="btn-group pull-right" > <a class="btn dropdown-toggle" data-toggle="dropdown" href="#"> <i class="icon-user"></i><span class="hidden-phone"> admin</span> <span class="caret"></span> </a> <ul class="dropdown-menu"> <li><a href="#">Profile</a></li> <li class="divider"></li> <li><a href="login.html">Logout</a></li> </ul> </div> <!-- user dropdown ends --> <div class="top-nav nav-collapse"> <ul class="nav"> <li><a href="#">Visit Site</a></li> <li> <form class="navbar-search pull-left"> <input placeholder="Search" class="search-query span2" name="query" type="text"> </form> </li> </ul> </div><!--/.nav-collapse --> </div> </div> </div> <!-- topbar ends --> <div class="container-fluid"> <div class="row-fluid"> <!-- left menu starts --> <div class="span2 main-menu-span"> <div class="well nav-collapse sidebar-nav"> <ul class="nav nav-tabs nav-stacked main-menu"> <li class="nav-header hidden-tablet">Main</li> <li><a class="ajax-link" href="index.html"><i class="icon-home"></i><span class="hidden-tablet"> Dashboard</span></a></li> <li><a class="ajax-link" href="ui.html"><i class="icon-eye-open"></i><span class="hidden-tablet"> UI Features</span></a></li> <li><a class="ajax-link" href="form.html"><i class="icon-edit"></i><span class="hidden-tablet"> Forms</span></a></li> <li><a class="ajax-link" href="chart.html"><i class="icon-list-alt"></i><span class="hidden-tablet"> Charts</span></a></li> <li><a class="ajax-link" href="typography.html"><i class="icon-font"></i><span class="hidden-tablet"> Typography</span></a></li> <li><a class="ajax-link" href="gallery.html"><i class="icon-picture"></i><span class="hidden-tablet"> Gallery</span></a></li> <li class="nav-header hidden-tablet">Sample Section</li> <li><a class="ajax-link" href="table.html"><i class="icon-align-justify"></i><span class="hidden-tablet"> Tables</span></a></li> <li><a class="ajax-link" href="calendar.html"><i class="icon-calendar"></i><span class="hidden-tablet"> Calendar</span></a></li> <li><a class="ajax-link" href="grid.html"><i class="icon-th"></i><span class="hidden-tablet"> Grid</span></a></li> <li><a class="ajax-link" href="file-manager.html"><i class="icon-folder-open"></i><span class="hidden-tablet"> File Manager</span></a></li> <li><a href="tour.html"><i class="icon-globe"></i><span class="hidden-tablet"> Tour</span></a></li> <li><a class="ajax-link" href="icon.html"><i class="icon-star"></i><span class="hidden-tablet"> Icons</span></a></li> <li><a href="error.html"><i class="icon-ban-circle"></i><span class="hidden-tablet"> Error Page</span></a></li> <li><a href="login.html"><i class="icon-lock"></i><span class="hidden-tablet"> Login Page</span></a></li> </ul> <label id="for-is-ajax" class="hidden-tablet" for="is-ajax"><input id="is-ajax" type="checkbox"> Ajax on menu</label> </div><!--/.well --> </div><!--/span--> <!-- left menu ends --> <noscript> <div class="alert alert-block span10"> <h4 class="alert-heading">Warning!</h4> <p>You need to have <a href="http://en.wikipedia.org/wiki/JavaScript" target="_blank">JavaScript</a> enabled to use this site.</p> </div> </noscript> <div id="content" class="span10"> <!-- content starts --> <div> <ul class="breadcrumb"> <li> <a href="#">Home</a> <span class="divider">/</span> </li> <li> <a href="#">UI Features</a> </li> </ul> </div> <div class="row-fluid sortable"> <div class="box span12"> <div class="box-header well" data-original-title> <h2><i class="icon-plus"></i> Extended Elements</h2> <div class="box-icon"> <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a> <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a> <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a> </div> </div> <div class="box-content"> <table class="table table-bordered table-striped"> <tr> <td><h3>Multiple File Upload</h3></td> <td> <input data-no-uniform="true" type="file" name="file_upload" id="file_upload" /> </td> <td></td> </tr> <tr> <td><h3>Star Rating</h3></td> <td> <div class="raty"></div> </td> <td><code>&lt;div class="raty"&gt;&lt;/div&gt;</code></td> </tr> <tr> <td><h3>Toggle Switch</h3></td> <td> <input data-no-uniform="true" checked type="checkbox" class="iphone-toggle"> </td> <td><code>&lt;input data-no-uniform="true" type="checkbox" class="iphone-toggle"&gt;</code></td> </tr> <tr> <td><h3>Auto Growing Textarea</h3></td> <td> <textarea class="autogrow">Press enter here, it will grow automatically.</textarea> </td> <td><code>&lt;textarea class="autogrow"&gt;&lt;/textarea&gt;</code></td> </tr> <tr> <td><h3>Popover</h3></td> <td> <a href="#" class="btn btn-danger" data-rel="popover" data-content="And here's some amazing content. It's very engaging. right?" title="A Title">Hover for popover</a> </td> <td><code>&lt;a href="#" class="btn btn-danger" data-rel="popover" data-content="And here's some amazing content. It's very engaging. right?" title="A Title"&gt;hover for popover&lt;/a&gt;</code></td> </tr> <tr> <td><h3>Slider</h3></td> <td> <div class="slider"></div> </td> <td><code>&lt;div class="slider"&gt;&lt;/div&gt;</code></td> </tr> <tr> <td><h3>Dialog</h3></td> <td> <a href="#" class="btn btn-info btn-setting">Click for dialog</a> </td> <td></td> </tr> <tr> <td><h3>Tooltip</h3></td> <td> <a href="#" title="Tooltip, you can change the position." data-rel="tooltip" class="btn btn-warning">Hover for tooltip</a> </td> <td><code>&lt;a href="#" title="Tooltip, you can change the position." data-rel="tooltip" class="btn btn-warning"&gt;Hover for tooltip&lt;/a&gt;</code></td> </tr> </table> </div> </div><!--/span--> </div><!--/row--> <div class="row-fluid sortable"> <div class="box span6"> <div class="box-header well" data-original-title> <h2><i class="icon-tasks"></i> Progress Bars</h2> <div class="box-icon"> <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a> <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a> <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a> </div> </div> <div class="box-content"> <h3>Basic</h3> <div class="progress"> <div class="bar" style="width: 70%;"></div> </div> <h3>Striped</h3> <div class="progress progress-striped"> <div class="bar" style="width: 30%;"></div> </div> <h3>Animated</h3> <div class="progress progress-striped progress-success active"> <div class="bar" style="width: 50%;"></div> </div> <h3>Additional Colors</h3> <div class="progress progress-info progress-striped" style="margin-bottom: 9px;"> <div class="bar" style="width: 20%"></div> </div> <div class="progress progress-success" style="margin-bottom: 9px;"> <div class="bar" style="width: 40%"></div> </div> <div class="progress progress-warning progress-striped active" style="margin-bottom: 9px;"> <div class="bar" style="width: 60%"></div> </div> <div class="progress progress-danger progress-striped" style="margin-bottom: 9px;"> <div class="bar" style="width: 80%"></div> </div> </div> </div><!--/span--> <div class="box span6"> <div class="box-header well"> <h2><i class="icon-eye-open"></i> Labels and Annotations</h2> <div class="box-icon"> <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a> <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a> <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a> </div> </div> <div class="box-content"> <table class="table table-bordered table-striped"> <thead> <tr> <th>Labels</th> <th>Markup</th> </tr> </thead> <tbody> <tr> <td> <span class="label">Default</span> </td> <td> <code>&lt;span class="label"&gt;Default&lt;/span&gt;</code> </td> </tr> <tr> <td> <span class="label label-success">Success</span> </td> <td> <code>&lt;span class="label label-success"&gt;Success&lt;/span&gt;</code> </td> </tr> <tr> <td> <span class="label label-warning">Warning</span> </td> <td> <code>&lt;span class="label label-warning"&gt;Warning&lt;/span&gt;</code> </td> </tr> <tr> <td> <span class="label label-important">Important</span> </td> <td> <code>&lt;span class="label label-important"&gt;Important&lt;/span&gt;</code> </td> </tr> <tr> <td> <span class="label label-info">Info</span> </td> <td> <code>&lt;span class="label label-info"&gt;Info&lt;/span&gt;</code> </td> </tr> <tr> <td> <span class="label label-inverse">Inverse</span> </td> <td> <code>&lt;span class="label label-inverse"&gt;Inverse&lt;/span&gt;</code> </td> </tr> </tbody> </table> </div> </div><!--/span--> </div><!--/row--> <div class="row-fluid sortable"> <div class="box span5"> <div class="box-header well"> <h2><i class="icon-bullhorn"></i> Alerts</h2> <div class="box-icon"> <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a> <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a> <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a> </div> </div> <div class="box-content alerts"> <div class="alert alert-error"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Oh snap!</strong> Change a few things up and try submitting again. </div> <div class="alert alert-success"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Well done!</strong> You successfully read this important alert message. </div> <div class="alert alert-info"> <button type="button" class="close" data-dismiss="alert">×</button> <strong>Heads up!</strong> This alert needs your attention, but it's not super important. </div> <div class="alert alert-block "> <button type="button" class="close" data-dismiss="alert">×</button> <h4 class="alert-heading">Warning!</h4> <p>Best check yo self, you're not looking too good. Nulla vitae elit libero, a pharetra augue. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.</p> </div> </div> </div><!--/span--> <div class="box span7"> <div class="box-header well" data-original-title> <h2><i class="icon-bell"></i> Notifications</h2> <div class="box-icon"> <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a> <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a> <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a> </div> </div> <div class="box-content"> <div class="alert alert-info"> Click buttons below to see Pop Notifications. </div> <p class="center"> <button class="btn btn-primary noty" data-noty-options='{"text":"This is a success notification","layout":"topLeft","type":"success"}'><i class="icon-bell icon-white"></i> Top Left</button> <button class="btn btn-primary noty" data-noty-options='{"text":"This is an alert notification with fade effect","layout":"topCenter","type":"alert","animateOpen": {"opacity": "show"}}'><i class="icon-bell icon-white"></i> Top Center (fade)</button> <button class="btn btn-primary noty" data-noty-options='{"text":"This is an error notification","layout":"topRight","type":"error"}'><i class="icon-bell icon-white"></i> Top Right</button> <button class="btn btn-primary noty" data-noty-options='{"text":"This is a success information","layout":"top","type":"information"}'><i class="icon-bell icon-white"></i> Top Full Width</button> </p> <p class="center"> <button class="btn btn-primary noty" data-noty-options='{"text":"This is an alert notification with fade effect","layout":"center","type":"alert","animateOpen": {"opacity": "show"}}'><i class="icon-bell icon-white"></i> Center (fade)</button> <button class="btn btn-primary noty" data-noty-options='{"text":"This is an error notification","layout":"center","type":"error"}'><i class="icon-bell icon-white"></i> Center</button> </p> <p class="center"> <button class="btn btn-primary noty" data-noty-options='{"text":"This is an error notification","layout":"bottomLeft","type":"error"}'><i class="icon-bell icon-white"></i> Bottom Left</button> <button class="btn btn-primary noty" data-noty-options='{"text":"This is an alert notification with fade effect","layout":"bottomRight","type":"alert","animateOpen": {"opacity": "show"}}'><i class="icon-bell icon-white"></i> Bottom Right (fade)</button> </p> <p class="center"> <button class="btn btn-primary noty" data-noty-options='{"text":"This is an alert","layout":"bottom","type":"alert","closeButton":"true"}'><i class="icon-bell icon-white"></i> Bottom Full Width with Close Button</button> </p> </div> </div><!--/span--> <div class="box span7"> <div class="box-header well" data-original-title> <h2><i class="icon-refresh"></i> Ajax Loaders</h2> <div class="box-icon"> <a href="#" class="btn btn-setting btn-round"><i class="icon-cog"></i></a> <a href="#" class="btn btn-minimize btn-round"><i class="icon-chevron-up"></i></a> <a href="#" class="btn btn-close btn-round"><i class="icon-remove"></i></a> </div> </div> <div class="box-content"> <ul class="ajax-loaders"> <li><img src="/resources/img/ajax-loaders/ajax-loader-1.gif" title="img/ajax-loaders/ajax-loader-1.gif" ></li> <li><img src="/resources/img/ajax-loaders/ajax-loader-2.gif" title="img/ajax-loaders/ajax-loader-2.gif" ></li> <li><img src="/resources/img/ajax-loaders/ajax-loader-3.gif" title="img/ajax-loaders/ajax-loader-3.gif" ></li> <li><img src="/resources/img/ajax-loaders/ajax-loader-4.gif" title="img/ajax-loaders/ajax-loader-4.gif" ></li> <li><img src="/resources/img/ajax-loaders/ajax-loader-5.gif" title="img/ajax-loaders/ajax-loader-5.gif" ></li> <li><img src="/resources/img/ajax-loaders/ajax-loader-6.gif" title="img/ajax-loaders/ajax-loader-6.gif" ></li> <li><img src="/resources/img/ajax-loaders/ajax-loader-7.gif" title="img/ajax-loaders/ajax-loader-7.gif" ></li> <li><img src="/resources/img/ajax-loaders/ajax-loader-8.gif" title="img/ajax-loaders/ajax-loader-8.gif" ></li> </ul> <span class="clearfix">From / More <a href="http://ajaxload.info/" target="_blank">http://ajaxload.info/</a></span> </div> </div><!--/span--> </div><!--/row--> <!-- content ends --> </div><!--/#content.span10--> </div><!--/fluid-row--> <hr> <div class="modal hide fade" id="myModal"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">×</button> <h3>Settings</h3> </div> <div class="modal-body"> <p>Here settings can be configured...</p> </div> <div class="modal-footer"> <a href="#" class="btn" data-dismiss="modal">Close</a> <a href="#" class="btn btn-primary">Save changes</a> </div> </div> <footer> <p class="pull-left">&copy; <a href="http://usman.it" target="_blank">Muhammad Usman</a> 2012</p> <p class="pull-right">Powered by: <a href="http://usman.it/free-responsive-admin-template">Charisma</a></p> </footer> </div><!--/.fluid-container--> <!-- external javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <!-- jQuery --> <script src="/resources/js/jquery-1.7.2.min.js"></script> <!-- jQuery UI --> <script src="/resources/js/jquery-ui-1.8.17.custom.min.js"></script> <!-- transition / effect library --> <script src="/resources/js/bootstrap-transition.js"></script> <!-- alert enhancer library --> <script src="/resources/js/bootstrap-alert.js"></script> <!-- modal / dialog library --> <script src="/resources/js/bootstrap-modal.js"></script> <!-- custom dropdown library --> <script src="/resources/js/bootstrap-dropdown.js"></script> <!-- scrolspy library --> <script src="/resources/js/bootstrap-scrollspy.js"></script> <!-- library for creating tabs --> <script src="/resources/js/bootstrap-tab.js"></script> <!-- library for advanced tooltip --> <script src="/resources/js/bootstrap-tooltip.js"></script> <!-- popover effect library --> <script src="/resources/js/bootstrap-popover.js"></script> <!-- button enhancer library --> <script src="/resources/js/bootstrap-button.js"></script> <!-- accordion library (optional, not used in demo) --> <script src="/resources/js/bootstrap-collapse.js"></script> <!-- carousel slideshow library (optional, not used in demo) --> <script src="/resources/js/bootstrap-carousel.js"></script> <!-- autocomplete library --> <script src="/resources/js/bootstrap-typeahead.js"></script> <!-- tour library --> <script src="/resources/js/bootstrap-tour.js"></script> <!-- library for cookie management --> <script src="/resources/js/jquery.cookie.js"></script> <!-- calander plugin --> <script src='/resources/js/fullcalendar.min.js'></script> <!-- data table plugin --> <script src='/resources/js/jquery.dataTables.min.js'></script> <!-- chart libraries start --> <script src="/resources/js/excanvas.js"></script> <script src="/resources/js/jquery.flot.min.js"></script> <script src="/resources/js/jquery.flot.pie.min.js"></script> <script src="/resources/js/jquery.flot.stack.js"></script> <script src="/resources/js/jquery.flot.resize.min.js"></script> <!-- chart libraries end --> <!-- select or dropdown enhancer --> <script src="/resources/js/jquery.chosen.min.js"></script> <!-- checkbox, radio, and file input styler --> <script src="/resources/js/jquery.uniform.min.js"></script> <!-- plugin for gallery image view --> <script src="/resources/js/jquery.colorbox.min.js"></script> <!-- rich text editor library --> <script src="/resources/js/jquery.cleditor.min.js"></script> <!-- notification plugin --> <script src="/resources/js/jquery.noty.js"></script> <!-- file manager library --> <script src="/resources/js/jquery.elfinder.min.js"></script> <!-- star rating plugin --> <script src="/resources/js/jquery.raty.min.js"></script> <!-- for iOS style toggle switch --> <script src="/resources/js/jquery.iphone.toggle.js"></script> <!-- autogrowing textarea plugin --> <script src="/resources/js/jquery.autogrow-textarea.js"></script> <!-- multiple file upload plugin --> <script src="/resources/js/jquery.uploadify-3.1.min.js"></script> <!-- history.js for cross-browser state change on ajax --> <script src="/resources/js/jquery.history.js"></script> <!-- application script for Charisma demo --> <script src="/resources/js/charisma.js"></script> </body> </html>
{'content_hash': '70afa64001bef55b2f15cb5711911b09', 'timestamp': '', 'source': 'github', 'line_count': 548, 'max_line_length': 260, 'avg_line_length': 44.1514598540146, 'alnum_prop': 0.5958255837983054, 'repo_name': 'tesla-cm/gravitation', 'id': '61fc5c71cf04a72828b21750a0c5dd8a0866c243', 'size': '24200', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'gravitation-views/src/html/ui.html', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '566126'}, {'name': 'HTML', 'bytes': '1202678'}, {'name': 'Java', 'bytes': '20983'}, {'name': 'JavaScript', 'bytes': '584366'}, {'name': 'PHP', 'bytes': '344076'}, {'name': 'Python', 'bytes': '14647'}, {'name': 'Scala', 'bytes': '25139'}]}
//==- UninitializedValues.cpp - Find Uninitialized Values -------*- C++ --*-==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements uninitialized values analysis for source-level CFGs. // //===----------------------------------------------------------------------===// #include "clang/AST/ASTContext.h" #include "clang/AST/Attr.h" #include "clang/AST/Decl.h" #include "clang/Analysis/Analyses/PostOrderCFGView.h" #include "clang/Analysis/Analyses/UninitializedValues.h" #include "clang/Analysis/AnalysisContext.h" #include "clang/Analysis/CFG.h" #include "clang/Analysis/DomainSpecific/ObjCNoReturn.h" #include "clang/Analysis/Visitors/CFGRecStmtDeclVisitor.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/PackedVector.h" #include "llvm/ADT/SmallBitVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/SaveAndRestore.h" #include <utility> using namespace clang; #define DEBUG_LOGGING 0 static bool isTrackedVar(const VarDecl *vd, const DeclContext *dc) { if (vd->isLocalVarDecl() && !vd->hasGlobalStorage() && !vd->isExceptionVariable() && vd->getDeclContext() == dc) { QualType ty = vd->getType(); return ty->isScalarType() || ty->isVectorType(); } return false; } //------------------------------------------------------------------------====// // DeclToIndex: a mapping from Decls we track to value indices. //====------------------------------------------------------------------------// namespace { class DeclToIndex { llvm::DenseMap<const VarDecl *, unsigned> map; public: DeclToIndex() {} /// Compute the actual mapping from declarations to bits. void computeMap(const DeclContext &dc); /// Return the number of declarations in the map. unsigned size() const { return map.size(); } /// Returns the bit vector index for a given declaration. Optional<unsigned> getValueIndex(const VarDecl *d) const; }; } void DeclToIndex::computeMap(const DeclContext &dc) { unsigned count = 0; DeclContext::specific_decl_iterator<VarDecl> I(dc.decls_begin()), E(dc.decls_end()); for ( ; I != E; ++I) { const VarDecl *vd = *I; if (isTrackedVar(vd, &dc)) map[vd] = count++; } } Optional<unsigned> DeclToIndex::getValueIndex(const VarDecl *d) const { llvm::DenseMap<const VarDecl *, unsigned>::const_iterator I = map.find(d); if (I == map.end()) return None; return I->second; } //------------------------------------------------------------------------====// // CFGBlockValues: dataflow values for CFG blocks. //====------------------------------------------------------------------------// // These values are defined in such a way that a merge can be done using // a bitwise OR. enum Value { Unknown = 0x0, /* 00 */ Initialized = 0x1, /* 01 */ Uninitialized = 0x2, /* 10 */ MayUninitialized = 0x3 /* 11 */ }; static bool isUninitialized(const Value v) { return v >= Uninitialized; } static bool isAlwaysUninit(const Value v) { return v == Uninitialized; } namespace { typedef llvm::PackedVector<Value, 2, llvm::SmallBitVector> ValueVector; class CFGBlockValues { const CFG &cfg; SmallVector<ValueVector, 8> vals; ValueVector scratch; DeclToIndex declToIndex; public: CFGBlockValues(const CFG &cfg); unsigned getNumEntries() const { return declToIndex.size(); } void computeSetOfDeclarations(const DeclContext &dc); ValueVector &getValueVector(const CFGBlock *block) { return vals[block->getBlockID()]; } void setAllScratchValues(Value V); void mergeIntoScratch(ValueVector const &source, bool isFirst); bool updateValueVectorWithScratch(const CFGBlock *block); bool hasNoDeclarations() const { return declToIndex.size() == 0; } void resetScratch(); ValueVector::reference operator[](const VarDecl *vd); Value getValue(const CFGBlock *block, const CFGBlock *dstBlock, const VarDecl *vd) { const Optional<unsigned> &idx = declToIndex.getValueIndex(vd); assert(idx.hasValue()); return getValueVector(block)[idx.getValue()]; } }; } // end anonymous namespace CFGBlockValues::CFGBlockValues(const CFG &c) : cfg(c), vals(0) {} void CFGBlockValues::computeSetOfDeclarations(const DeclContext &dc) { declToIndex.computeMap(dc); unsigned decls = declToIndex.size(); scratch.resize(decls); unsigned n = cfg.getNumBlockIDs(); if (!n) return; vals.resize(n); for (unsigned i = 0; i < n; ++i) vals[i].resize(decls); } #if DEBUG_LOGGING static void printVector(const CFGBlock *block, ValueVector &bv, unsigned num) { llvm::errs() << block->getBlockID() << " :"; for (unsigned i = 0; i < bv.size(); ++i) { llvm::errs() << ' ' << bv[i]; } llvm::errs() << " : " << num << '\n'; } #endif void CFGBlockValues::setAllScratchValues(Value V) { for (unsigned I = 0, E = scratch.size(); I != E; ++I) scratch[I] = V; } void CFGBlockValues::mergeIntoScratch(ValueVector const &source, bool isFirst) { if (isFirst) scratch = source; else scratch |= source; } bool CFGBlockValues::updateValueVectorWithScratch(const CFGBlock *block) { ValueVector &dst = getValueVector(block); bool changed = (dst != scratch); if (changed) dst = scratch; #if DEBUG_LOGGING printVector(block, scratch, 0); #endif return changed; } void CFGBlockValues::resetScratch() { scratch.reset(); } ValueVector::reference CFGBlockValues::operator[](const VarDecl *vd) { const Optional<unsigned> &idx = declToIndex.getValueIndex(vd); assert(idx.hasValue()); return scratch[idx.getValue()]; } //------------------------------------------------------------------------====// // Worklist: worklist for dataflow analysis. //====------------------------------------------------------------------------// namespace { class DataflowWorklist { PostOrderCFGView::iterator PO_I, PO_E; SmallVector<const CFGBlock *, 20> worklist; llvm::BitVector enqueuedBlocks; public: DataflowWorklist(const CFG &cfg, PostOrderCFGView &view) : PO_I(view.begin()), PO_E(view.end()), enqueuedBlocks(cfg.getNumBlockIDs(), true) { // Treat the first block as already analyzed. if (PO_I != PO_E) { assert(*PO_I == &cfg.getEntry()); enqueuedBlocks[(*PO_I)->getBlockID()] = false; ++PO_I; } } void enqueueSuccessors(const CFGBlock *block); const CFGBlock *dequeue(); }; } void DataflowWorklist::enqueueSuccessors(const clang::CFGBlock *block) { for (CFGBlock::const_succ_iterator I = block->succ_begin(), E = block->succ_end(); I != E; ++I) { const CFGBlock *Successor = *I; if (!Successor || enqueuedBlocks[Successor->getBlockID()]) continue; worklist.push_back(Successor); enqueuedBlocks[Successor->getBlockID()] = true; } } const CFGBlock *DataflowWorklist::dequeue() { const CFGBlock *B = 0; // First dequeue from the worklist. This can represent // updates along backedges that we want propagated as quickly as possible. if (!worklist.empty()) { B = worklist.back(); worklist.pop_back(); } // Next dequeue from the initial reverse post order. This is the // theoretical ideal in the presence of no back edges. else if (PO_I != PO_E) { B = *PO_I; ++PO_I; } else { return 0; } assert(enqueuedBlocks[B->getBlockID()] == true); enqueuedBlocks[B->getBlockID()] = false; return B; } //------------------------------------------------------------------------====// // Classification of DeclRefExprs as use or initialization. //====------------------------------------------------------------------------// namespace { class FindVarResult { const VarDecl *vd; const DeclRefExpr *dr; public: FindVarResult(const VarDecl *vd, const DeclRefExpr *dr) : vd(vd), dr(dr) {} const DeclRefExpr *getDeclRefExpr() const { return dr; } const VarDecl *getDecl() const { return vd; } }; static const Expr *stripCasts(ASTContext &C, const Expr *Ex) { while (Ex) { Ex = Ex->IgnoreParenNoopCasts(C); if (const CastExpr *CE = dyn_cast<CastExpr>(Ex)) { if (CE->getCastKind() == CK_LValueBitCast) { Ex = CE->getSubExpr(); continue; } } break; } return Ex; } /// If E is an expression comprising a reference to a single variable, find that /// variable. static FindVarResult findVar(const Expr *E, const DeclContext *DC) { if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(stripCasts(DC->getParentASTContext(), E))) if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) if (isTrackedVar(VD, DC)) return FindVarResult(VD, DRE); return FindVarResult(0, 0); } /// \brief Classify each DeclRefExpr as an initialization or a use. Any /// DeclRefExpr which isn't explicitly classified will be assumed to have /// escaped the analysis and will be treated as an initialization. class ClassifyRefs : public StmtVisitor<ClassifyRefs> { public: enum Class { Init, Use, SelfInit, Ignore }; private: const DeclContext *DC; llvm::DenseMap<const DeclRefExpr*, Class> Classification; bool isTrackedVar(const VarDecl *VD) const { return ::isTrackedVar(VD, DC); } void classify(const Expr *E, Class C); public: ClassifyRefs(AnalysisDeclContext &AC) : DC(cast<DeclContext>(AC.getDecl())) {} void VisitDeclStmt(DeclStmt *DS); void VisitUnaryOperator(UnaryOperator *UO); void VisitBinaryOperator(BinaryOperator *BO); void VisitCallExpr(CallExpr *CE); void VisitCastExpr(CastExpr *CE); void operator()(Stmt *S) { Visit(S); } Class get(const DeclRefExpr *DRE) const { llvm::DenseMap<const DeclRefExpr*, Class>::const_iterator I = Classification.find(DRE); if (I != Classification.end()) return I->second; const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()); if (!VD || !isTrackedVar(VD)) return Ignore; return Init; } }; } static const DeclRefExpr *getSelfInitExpr(VarDecl *VD) { if (Expr *Init = VD->getInit()) { const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(stripCasts(VD->getASTContext(), Init)); if (DRE && DRE->getDecl() == VD) return DRE; } return 0; } void ClassifyRefs::classify(const Expr *E, Class C) { // The result of a ?: could also be an lvalue. E = E->IgnoreParens(); if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) { const Expr *TrueExpr = CO->getTrueExpr(); if (!isa<OpaqueValueExpr>(TrueExpr)) classify(TrueExpr, C); classify(CO->getFalseExpr(), C); return; } FindVarResult Var = findVar(E, DC); if (const DeclRefExpr *DRE = Var.getDeclRefExpr()) Classification[DRE] = std::max(Classification[DRE], C); } void ClassifyRefs::VisitDeclStmt(DeclStmt *DS) { for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); DI != DE; ++DI) { VarDecl *VD = dyn_cast<VarDecl>(*DI); if (VD && isTrackedVar(VD)) if (const DeclRefExpr *DRE = getSelfInitExpr(VD)) Classification[DRE] = SelfInit; } } void ClassifyRefs::VisitBinaryOperator(BinaryOperator *BO) { // Ignore the evaluation of a DeclRefExpr on the LHS of an assignment. If this // is not a compound-assignment, we will treat it as initializing the variable // when TransferFunctions visits it. A compound-assignment does not affect // whether a variable is uninitialized, and there's no point counting it as a // use. if (BO->isCompoundAssignmentOp()) classify(BO->getLHS(), Use); else if (BO->getOpcode() == BO_Assign) classify(BO->getLHS(), Ignore); } void ClassifyRefs::VisitUnaryOperator(UnaryOperator *UO) { // Increment and decrement are uses despite there being no lvalue-to-rvalue // conversion. if (UO->isIncrementDecrementOp()) classify(UO->getSubExpr(), Use); } void ClassifyRefs::VisitCallExpr(CallExpr *CE) { // If a value is passed by const reference to a function, we should not assume // that it is initialized by the call, and we conservatively do not assume // that it is used. for (CallExpr::arg_iterator I = CE->arg_begin(), E = CE->arg_end(); I != E; ++I) if ((*I)->getType().isConstQualified() && (*I)->isGLValue()) classify(*I, Ignore); } void ClassifyRefs::VisitCastExpr(CastExpr *CE) { if (CE->getCastKind() == CK_LValueToRValue) classify(CE->getSubExpr(), Use); else if (CStyleCastExpr *CSE = dyn_cast<CStyleCastExpr>(CE)) { if (CSE->getType()->isVoidType()) { // Squelch any detected load of an uninitialized value if // we cast it to void. // e.g. (void) x; classify(CSE->getSubExpr(), Ignore); } } } //------------------------------------------------------------------------====// // Transfer function for uninitialized values analysis. //====------------------------------------------------------------------------// namespace { class TransferFunctions : public StmtVisitor<TransferFunctions> { CFGBlockValues &vals; const CFG &cfg; const CFGBlock *block; AnalysisDeclContext &ac; const ClassifyRefs &classification; ObjCNoReturn objCNoRet; UninitVariablesHandler &handler; public: TransferFunctions(CFGBlockValues &vals, const CFG &cfg, const CFGBlock *block, AnalysisDeclContext &ac, const ClassifyRefs &classification, UninitVariablesHandler &handler) : vals(vals), cfg(cfg), block(block), ac(ac), classification(classification), objCNoRet(ac.getASTContext()), handler(handler) {} void reportUse(const Expr *ex, const VarDecl *vd); void VisitBinaryOperator(BinaryOperator *bo); void VisitBlockExpr(BlockExpr *be); void VisitCallExpr(CallExpr *ce); void VisitDeclRefExpr(DeclRefExpr *dr); void VisitDeclStmt(DeclStmt *ds); void VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS); void VisitObjCMessageExpr(ObjCMessageExpr *ME); bool isTrackedVar(const VarDecl *vd) { return ::isTrackedVar(vd, cast<DeclContext>(ac.getDecl())); } FindVarResult findVar(const Expr *ex) { return ::findVar(ex, cast<DeclContext>(ac.getDecl())); } UninitUse getUninitUse(const Expr *ex, const VarDecl *vd, Value v) { UninitUse Use(ex, isAlwaysUninit(v)); assert(isUninitialized(v)); if (Use.getKind() == UninitUse::Always) return Use; // If an edge which leads unconditionally to this use did not initialize // the variable, we can say something stronger than 'may be uninitialized': // we can say 'either it's used uninitialized or you have dead code'. // // We track the number of successors of a node which have been visited, and // visit a node once we have visited all of its successors. Only edges where // the variable might still be uninitialized are followed. Since a variable // can't transfer from being initialized to being uninitialized, this will // trace out the subgraph which inevitably leads to the use and does not // initialize the variable. We do not want to skip past loops, since their // non-termination might be correlated with the initialization condition. // // For example: // // void f(bool a, bool b) { // block1: int n; // if (a) { // block2: if (b) // block3: n = 1; // block4: } else if (b) { // block5: while (!a) { // block6: do_work(&a); // n = 2; // } // } // block7: if (a) // block8: g(); // block9: return n; // } // // Starting from the maybe-uninitialized use in block 9: // * Block 7 is not visited because we have only visited one of its two // successors. // * Block 8 is visited because we've visited its only successor. // From block 8: // * Block 7 is visited because we've now visited both of its successors. // From block 7: // * Blocks 1, 2, 4, 5, and 6 are not visited because we didn't visit all // of their successors (we didn't visit 4, 3, 5, 6, and 5, respectively). // * Block 3 is not visited because it initializes 'n'. // Now the algorithm terminates, having visited blocks 7 and 8, and having // found the frontier is blocks 2, 4, and 5. // // 'n' is definitely uninitialized for two edges into block 7 (from blocks 2 // and 4), so we report that any time either of those edges is taken (in // each case when 'b == false'), 'n' is used uninitialized. SmallVector<const CFGBlock*, 32> Queue; SmallVector<unsigned, 32> SuccsVisited(cfg.getNumBlockIDs(), 0); Queue.push_back(block); // Specify that we've already visited all successors of the starting block. // This has the dual purpose of ensuring we never add it to the queue, and // of marking it as not being a candidate element of the frontier. SuccsVisited[block->getBlockID()] = block->succ_size(); while (!Queue.empty()) { const CFGBlock *B = Queue.back(); Queue.pop_back(); for (CFGBlock::const_pred_iterator I = B->pred_begin(), E = B->pred_end(); I != E; ++I) { const CFGBlock *Pred = *I; if (vals.getValue(Pred, B, vd) == Initialized) // This block initializes the variable. continue; unsigned &SV = SuccsVisited[Pred->getBlockID()]; if (!SV) { // When visiting the first successor of a block, mark all NULL // successors as having been visited. for (CFGBlock::const_succ_iterator SI = Pred->succ_begin(), SE = Pred->succ_end(); SI != SE; ++SI) if (!*SI) ++SV; } if (++SV == Pred->succ_size()) // All paths from this block lead to the use and don't initialize the // variable. Queue.push_back(Pred); } } // Scan the frontier, looking for blocks where the variable was // uninitialized. for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) { const CFGBlock *Block = *BI; unsigned BlockID = Block->getBlockID(); const Stmt *Term = Block->getTerminator(); if (SuccsVisited[BlockID] && SuccsVisited[BlockID] < Block->succ_size() && Term) { // This block inevitably leads to the use. If we have an edge from here // to a post-dominator block, and the variable is uninitialized on that // edge, we have found a bug. for (CFGBlock::const_succ_iterator I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) { const CFGBlock *Succ = *I; if (Succ && SuccsVisited[Succ->getBlockID()] >= Succ->succ_size() && vals.getValue(Block, Succ, vd) == Uninitialized) { // Switch cases are a special case: report the label to the caller // as the 'terminator', not the switch statement itself. Suppress // situations where no label matched: we can't be sure that's // possible. if (isa<SwitchStmt>(Term)) { const Stmt *Label = Succ->getLabel(); if (!Label || !isa<SwitchCase>(Label)) // Might not be possible. continue; UninitUse::Branch Branch; Branch.Terminator = Label; Branch.Output = 0; // Ignored. Use.addUninitBranch(Branch); } else { UninitUse::Branch Branch; Branch.Terminator = Term; Branch.Output = I - Block->succ_begin(); Use.addUninitBranch(Branch); } } } } } return Use; } }; } void TransferFunctions::reportUse(const Expr *ex, const VarDecl *vd) { Value v = vals[vd]; if (isUninitialized(v)) handler.handleUseOfUninitVariable(vd, getUninitUse(ex, vd, v)); } void TransferFunctions::VisitObjCForCollectionStmt(ObjCForCollectionStmt *FS) { // This represents an initialization of the 'element' value. if (DeclStmt *DS = dyn_cast<DeclStmt>(FS->getElement())) { const VarDecl *VD = cast<VarDecl>(DS->getSingleDecl()); if (isTrackedVar(VD)) vals[VD] = Initialized; } } void TransferFunctions::VisitBlockExpr(BlockExpr *be) { const BlockDecl *bd = be->getBlockDecl(); for (BlockDecl::capture_const_iterator i = bd->capture_begin(), e = bd->capture_end() ; i != e; ++i) { const VarDecl *vd = i->getVariable(); if (!isTrackedVar(vd)) continue; if (i->isByRef()) { vals[vd] = Initialized; continue; } reportUse(be, vd); } } void TransferFunctions::VisitCallExpr(CallExpr *ce) { if (Decl *Callee = ce->getCalleeDecl()) { if (Callee->hasAttr<ReturnsTwiceAttr>()) { // After a call to a function like setjmp or vfork, any variable which is // initialized anywhere within this function may now be initialized. For // now, just assume such a call initializes all variables. FIXME: Only // mark variables as initialized if they have an initializer which is // reachable from here. vals.setAllScratchValues(Initialized); } else if (Callee->hasAttr<AnalyzerNoReturnAttr>()) { // Functions labeled like "analyzer_noreturn" are often used to denote // "panic" functions that in special debug situations can still return, // but for the most part should not be treated as returning. This is a // useful annotation borrowed from the static analyzer that is useful for // suppressing branch-specific false positives when we call one of these // functions but keep pretending the path continues (when in reality the // user doesn't care). vals.setAllScratchValues(Unknown); } } } void TransferFunctions::VisitDeclRefExpr(DeclRefExpr *dr) { switch (classification.get(dr)) { case ClassifyRefs::Ignore: break; case ClassifyRefs::Use: reportUse(dr, cast<VarDecl>(dr->getDecl())); break; case ClassifyRefs::Init: vals[cast<VarDecl>(dr->getDecl())] = Initialized; break; case ClassifyRefs::SelfInit: handler.handleSelfInit(cast<VarDecl>(dr->getDecl())); break; } } void TransferFunctions::VisitBinaryOperator(BinaryOperator *BO) { if (BO->getOpcode() == BO_Assign) { FindVarResult Var = findVar(BO->getLHS()); if (const VarDecl *VD = Var.getDecl()) vals[VD] = Initialized; } } void TransferFunctions::VisitDeclStmt(DeclStmt *DS) { for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end(); DI != DE; ++DI) { VarDecl *VD = dyn_cast<VarDecl>(*DI); if (VD && isTrackedVar(VD)) { if (getSelfInitExpr(VD)) { // If the initializer consists solely of a reference to itself, we // explicitly mark the variable as uninitialized. This allows code // like the following: // // int x = x; // // to deliberately leave a variable uninitialized. Different analysis // clients can detect this pattern and adjust their reporting // appropriately, but we need to continue to analyze subsequent uses // of the variable. vals[VD] = Uninitialized; } else if (VD->getInit()) { // Treat the new variable as initialized. vals[VD] = Initialized; } else { // No initializer: the variable is now uninitialized. This matters // for cases like: // while (...) { // int n; // use(n); // n = 0; // } // FIXME: Mark the variable as uninitialized whenever its scope is // left, since its scope could be re-entered by a jump over the // declaration. vals[VD] = Uninitialized; } } } } void TransferFunctions::VisitObjCMessageExpr(ObjCMessageExpr *ME) { // If the Objective-C message expression is an implicit no-return that // is not modeled in the CFG, set the tracked dataflow values to Unknown. if (objCNoRet.isImplicitNoReturn(ME)) { vals.setAllScratchValues(Unknown); } } //------------------------------------------------------------------------====// // High-level "driver" logic for uninitialized values analysis. //====------------------------------------------------------------------------// static bool runOnBlock(const CFGBlock *block, const CFG &cfg, AnalysisDeclContext &ac, CFGBlockValues &vals, const ClassifyRefs &classification, llvm::BitVector &wasAnalyzed, UninitVariablesHandler &handler) { wasAnalyzed[block->getBlockID()] = true; vals.resetScratch(); // Merge in values of predecessor blocks. bool isFirst = true; for (CFGBlock::const_pred_iterator I = block->pred_begin(), E = block->pred_end(); I != E; ++I) { const CFGBlock *pred = *I; if (wasAnalyzed[pred->getBlockID()]) { vals.mergeIntoScratch(vals.getValueVector(pred), isFirst); isFirst = false; } } // Apply the transfer function. TransferFunctions tf(vals, cfg, block, ac, classification, handler); for (CFGBlock::const_iterator I = block->begin(), E = block->end(); I != E; ++I) { if (Optional<CFGStmt> cs = I->getAs<CFGStmt>()) tf.Visit(const_cast<Stmt*>(cs->getStmt())); } return vals.updateValueVectorWithScratch(block); } /// PruneBlocksHandler is a special UninitVariablesHandler that is used /// to detect when a CFGBlock has any *potential* use of an uninitialized /// variable. It is mainly used to prune out work during the final /// reporting pass. namespace { struct PruneBlocksHandler : public UninitVariablesHandler { PruneBlocksHandler(unsigned numBlocks) : hadUse(numBlocks, false), hadAnyUse(false), currentBlock(0) {} virtual ~PruneBlocksHandler() {} /// Records if a CFGBlock had a potential use of an uninitialized variable. llvm::BitVector hadUse; /// Records if any CFGBlock had a potential use of an uninitialized variable. bool hadAnyUse; /// The current block to scribble use information. unsigned currentBlock; virtual void handleUseOfUninitVariable(const VarDecl *vd, const UninitUse &use) { hadUse[currentBlock] = true; hadAnyUse = true; } /// Called when the uninitialized variable analysis detects the /// idiom 'int x = x'. All other uses of 'x' within the initializer /// are handled by handleUseOfUninitVariable. virtual void handleSelfInit(const VarDecl *vd) { hadUse[currentBlock] = true; hadAnyUse = true; } }; } void clang::runUninitializedVariablesAnalysis( const DeclContext &dc, const CFG &cfg, AnalysisDeclContext &ac, UninitVariablesHandler &handler, UninitVariablesAnalysisStats &stats) { CFGBlockValues vals(cfg); vals.computeSetOfDeclarations(dc); if (vals.hasNoDeclarations()) return; stats.NumVariablesAnalyzed = vals.getNumEntries(); // Precompute which expressions are uses and which are initializations. ClassifyRefs classification(ac); cfg.VisitBlockStmts(classification); // Mark all variables uninitialized at the entry. const CFGBlock &entry = cfg.getEntry(); ValueVector &vec = vals.getValueVector(&entry); const unsigned n = vals.getNumEntries(); for (unsigned j = 0; j < n ; ++j) { vec[j] = Uninitialized; } // Proceed with the workist. DataflowWorklist worklist(cfg, *ac.getAnalysis<PostOrderCFGView>()); llvm::BitVector previouslyVisited(cfg.getNumBlockIDs()); worklist.enqueueSuccessors(&cfg.getEntry()); llvm::BitVector wasAnalyzed(cfg.getNumBlockIDs(), false); wasAnalyzed[cfg.getEntry().getBlockID()] = true; PruneBlocksHandler PBH(cfg.getNumBlockIDs()); while (const CFGBlock *block = worklist.dequeue()) { PBH.currentBlock = block->getBlockID(); // Did the block change? bool changed = runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, PBH); ++stats.NumBlockVisits; if (changed || !previouslyVisited[block->getBlockID()]) worklist.enqueueSuccessors(block); previouslyVisited[block->getBlockID()] = true; } if (!PBH.hadAnyUse) return; // Run through the blocks one more time, and report uninitialized variables. for (CFG::const_iterator BI = cfg.begin(), BE = cfg.end(); BI != BE; ++BI) { const CFGBlock *block = *BI; if (PBH.hadUse[block->getBlockID()]) { runOnBlock(block, cfg, ac, vals, classification, wasAnalyzed, handler); ++stats.NumBlockVisits; } } } UninitVariablesHandler::~UninitVariablesHandler() {}
{'content_hash': 'd2130c3b1f2c920509f7a527e03cc5f8', 'timestamp': '', 'source': 'github', 'line_count': 850, 'max_line_length': 80, 'avg_line_length': 34.06941176470588, 'alnum_prop': 0.6234676611761456, 'repo_name': 'dplbsd/soc2013', 'id': '730aa6ba212c79d9bbf892a072b04b5510ee9dbd', 'size': '28959', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'head/contrib/llvm/tools/clang/lib/Analysis/UninitializedValues.cpp', 'mode': '33188', 'license': 'bsd-2-clause', 'language': [{'name': 'AGS Script', 'bytes': '62471'}, {'name': 'Assembly', 'bytes': '4478661'}, {'name': 'Awk', 'bytes': '278525'}, {'name': 'Batchfile', 'bytes': '20417'}, {'name': 'C', 'bytes': '383420305'}, {'name': 'C++', 'bytes': '72796771'}, {'name': 'CSS', 'bytes': '109748'}, {'name': 'ChucK', 'bytes': '39'}, {'name': 'D', 'bytes': '3784'}, {'name': 'DIGITAL Command Language', 'bytes': '10640'}, {'name': 'DTrace', 'bytes': '2311027'}, {'name': 'Emacs Lisp', 'bytes': '65902'}, {'name': 'EmberScript', 'bytes': '286'}, {'name': 'Forth', 'bytes': '184405'}, {'name': 'GAP', 'bytes': '72156'}, {'name': 'Groff', 'bytes': '32248806'}, {'name': 'HTML', 'bytes': '6749816'}, {'name': 'IGOR Pro', 'bytes': '6301'}, {'name': 'Java', 'bytes': '112547'}, {'name': 'KRL', 'bytes': '4950'}, {'name': 'Lex', 'bytes': '398817'}, {'name': 'Limbo', 'bytes': '3583'}, {'name': 'Logos', 'bytes': '187900'}, {'name': 'Makefile', 'bytes': '3551839'}, {'name': 'Mathematica', 'bytes': '9556'}, {'name': 'Max', 'bytes': '4178'}, {'name': 'Module Management System', 'bytes': '817'}, {'name': 'NSIS', 'bytes': '3383'}, {'name': 'Objective-C', 'bytes': '836351'}, {'name': 'PHP', 'bytes': '6649'}, {'name': 'Perl', 'bytes': '5530761'}, {'name': 'Perl6', 'bytes': '41802'}, {'name': 'PostScript', 'bytes': '140088'}, {'name': 'Prolog', 'bytes': '29514'}, {'name': 'Protocol Buffer', 'bytes': '61933'}, {'name': 'Python', 'bytes': '299247'}, {'name': 'R', 'bytes': '764'}, {'name': 'Rebol', 'bytes': '738'}, {'name': 'Ruby', 'bytes': '45958'}, {'name': 'Scilab', 'bytes': '197'}, {'name': 'Shell', 'bytes': '10501540'}, {'name': 'SourcePawn', 'bytes': '463194'}, {'name': 'SuperCollider', 'bytes': '80208'}, {'name': 'Tcl', 'bytes': '80913'}, {'name': 'TeX', 'bytes': '719821'}, {'name': 'VimL', 'bytes': '22201'}, {'name': 'XS', 'bytes': '25451'}, {'name': 'XSLT', 'bytes': '31488'}, {'name': 'Yacc', 'bytes': '1857830'}]}
<?php namespace TweedeGolf\SwiftmailerLoggerBundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\HttpKernel\Bundle\Bundle; use TweedeGolf\SwiftmailerLoggerBundle\DependencyInjection\RegisterSendListenerCompilerPass; /** * Class TweedeGolfSwiftmailerLoggerBundle * @package TweedeGolf\SwiftmailerLoggerBundle */ class TweedeGolfSwiftmailerLoggerBundle extends Bundle { public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new RegisterSendListenerCompilerPass()); } }
{'content_hash': 'e03bc5b86d0df94710c5d6bb5f9ef199', 'timestamp': '', 'source': 'github', 'line_count': 20, 'max_line_length': 92, 'avg_line_length': 29.6, 'alnum_prop': 0.8091216216216216, 'repo_name': 'tweedegolf/swiftmailer-logger-bundle', 'id': '98627b12184152ed39d31409a7f2317886f155c8', 'size': '592', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/TweedeGolf/SwiftmailerLoggerBundle/TweedeGolfSwiftmailerLoggerBundle.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'PHP', 'bytes': '21792'}]}
from __future__ import print_function import os import shutil import string from importlib import import_module from os.path import join, dirname, abspath, exists, splitext import scrapy from scrapy.command import ScrapyCommand from scrapy.utils.template import render_templatefile, string_camelcase from scrapy.exceptions import UsageError def sanitize_module_name(module_name): """Sanitize the given module name, by replacing dashes and points with underscores and prefixing it with a letter if it doesn't start with one """ module_name = module_name.replace('-', '_').replace('.', '_') if module_name[0] not in string.ascii_letters: module_name = "a" + module_name return module_name class Command(ScrapyCommand): requires_project = True default_settings = {'LOG_ENABLED': False} def syntax(self): return "[options] <name> <domain>" def short_desc(self): return "Generate new spider using pre-defined templates" def add_options(self, parser): ScrapyCommand.add_options(self, parser) parser.add_option("-l", "--list", dest="list", action="store_true", help="List available templates") parser.add_option("-e", "--edit", dest="edit", action="store_true", help="Edit spider after creating it") parser.add_option("-d", "--dump", dest="dump", metavar="TEMPLATE", help="Dump template to standard output") parser.add_option("-t", "--template", dest="template", default="basic", help="Uses a custom template.") parser.add_option("--force", dest="force", action="store_true", help="If the spider already exists, overwrite it with the template") def run(self, args, opts): if opts.list: self._list_templates() return if opts.dump: template_file = self._find_template(opts.dump) if template_file: print(open(template_file, 'r').read()) return if len(args) != 2: raise UsageError() name, domain = args[0:2] module = sanitize_module_name(name) if self.settings.get('BOT_NAME') == module: print("Cannot create a spider with the same name as your project") return try: crawler = self.crawler_process.create_crawler() spider = crawler.spiders.create(name) except KeyError: pass else: # if spider already exists and not --force then halt if not opts.force: print("Spider %r already exists in module:" % name) print(" %s" % spider.__module__) return template_file = self._find_template(opts.template) if template_file: self._genspider(module, name, domain, opts.template, template_file) if opts.edit: self.exitcode = os.system('scrapy edit "%s"' % name) def _genspider(self, module, name, domain, template_name, template_file): """Generate the spider module, based on the given template""" tvars = { 'project_name': self.settings.get('BOT_NAME'), 'ProjectName': string_camelcase(self.settings.get('BOT_NAME')), 'module': module, 'name': name, 'domain': domain, 'classname': '%sSpider' % ''.join([s.capitalize() \ for s in module.split('_')]) } spiders_module = import_module(self.settings['NEWSPIDER_MODULE']) spiders_dir = abspath(dirname(spiders_module.__file__)) spider_file = "%s.py" % join(spiders_dir, module) shutil.copyfile(template_file, spider_file) render_templatefile(spider_file, **tvars) print("Created spider %r using template %r in module:" % (name, \ template_name)) print(" %s.%s" % (spiders_module.__name__, module)) def _find_template(self, template): template_file = join(self.templates_dir, '%s.tmpl' % template) if exists(template_file): return template_file print("Unable to find template: %s\n" % template) print('Use "scrapy genspider --list" to see all available templates.') def _list_templates(self): print("Available templates:") for filename in sorted(os.listdir(self.templates_dir)): if filename.endswith('.tmpl'): print(" %s" % splitext(filename)[0]) @property def templates_dir(self): _templates_base_dir = self.settings['TEMPLATES_DIR'] or \ join(scrapy.__path__[0], 'templates') return join(_templates_base_dir, 'spiders')
{'content_hash': 'a55f41adb09edffc3031bfbe93bf0554', 'timestamp': '', 'source': 'github', 'line_count': 121, 'max_line_length': 80, 'avg_line_length': 38.925619834710744, 'alnum_prop': 0.5983014861995753, 'repo_name': 'jake1036/spider', 'id': '3e2e24b21d5b850db4a5145bd74646224a564376', 'size': '4710', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'scrapy/commands/genspider.py', 'mode': '33188', 'license': 'bsd-3-clause', 'language': [{'name': 'CSS', 'bytes': '9681'}, {'name': 'Makefile', 'bytes': '2225'}, {'name': 'Python', 'bytes': '1230388'}, {'name': 'Shell', 'bytes': '2059'}]}
To work with the application you should set the following environment variables: * YANDEX_CLIENT_ID - id of Yandex application with read access to your disk. * YANDEX_DISK_FOLDER - path to a folder with images on your Yandex disk. * MONGO_DB_URL - URL for connection to a Mongo database. * MONGO_DB_COLLECTION - name of collection in the Mongo database.
{'content_hash': '348bf180f200277e3f2b4144ce2b07ec', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 80, 'avg_line_length': 59.0, 'alnum_prop': 0.7768361581920904, 'repo_name': 'yakimovim/tagged-gallery', 'id': '7ac534a793df60624fb3ee1c5d1d9f052362368b', 'size': '354', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'README.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '5648'}, {'name': 'HTML', 'bytes': '2008'}, {'name': 'JavaScript', 'bytes': '42373'}, {'name': 'Procfile', 'bytes': '24'}]}
require "sinatra/base" module Sinatra module WWWAuthenticateHelper def www_authenticate_error(error = nil, reason: nil, description: nil) details = [] details << "error=\"#{error}\"" if error details << "error_reason=\"#{reason}\"" if reason details << "error_description=\"#{description}\"" if description headers['WWW-Authenticate'] = ["Bearer", details.join(", ")].join(" ") halt 401 end end helpers WWWAuthenticateHelper end
{'content_hash': 'cc7d7cf51912077870cfa89bdc5e6a16', 'timestamp': '', 'source': 'github', 'line_count': 19, 'max_line_length': 76, 'avg_line_length': 25.473684210526315, 'alnum_prop': 0.6384297520661157, 'repo_name': 'blinkboxbooks/auth-server', 'id': 'a886fab8dc847bb520dabcb899d8ac1eca08a440', 'size': '484', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'lib/sinatra/www_authenticate_helper.rb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Ruby', 'bytes': '129278'}]}
package org.schema.api.model.thing.creativeWork.webPageElement; import org.schema.api.model.thing.creativeWork.webPageElement.WebPageElement; import org.schema.api.model.thing.Thing; import org.schema.api.model.thing.Person; import org.schema.api.model.thing.intangible.rating.AggregateRating; import org.schema.api.model.thing.creativeWork.mediaObject.MediaObject; import org.schema.api.model.thing.intangible.audience.Audience; import org.schema.api.model.thing.creativeWork.mediaObject.AudioObject; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.Person; import org.schema.api.model.thing.creativeWork.comment.Comment; import org.schema.api.model.thing.place.Place; import java.util.Date; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.organization.Organization; import java.util.Date; import java.util.Date; import java.util.Date; import org.schema.api.model.thing.Person; import org.schema.api.model.thing.intangible.AlignmentObject; import org.schema.api.model.thing.creativeWork.mediaObject.MediaObject; import org.schema.api.model.thing.creativeWork.CreativeWork; import java.util.Date; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.creativeWork.CreativeWork; import org.schema.api.model.thing.intangible.structuredValue.InteractionCounter; import org.schema.api.model.thing.creativeWork.CreativeWork; import org.schema.api.model.thing.place.Place; import org.schema.api.model.thing.Thing; import org.schema.api.model.thing.Thing; import org.schema.api.model.thing.intangible.offer.Offer; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.event.publicationEvent.PublicationEvent; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.event.Event; import org.schema.api.model.thing.event.publicationEvent.PublicationEvent; import org.schema.api.model.thing.creativeWork.Review; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.place.Place; import org.schema.api.model.thing.organization.Organization; import java.util.Date; import org.schema.api.model.thing.intangible.quantity.Duration; import org.schema.api.model.thing.creativeWork.CreativeWork; import org.schema.api.model.thing.organization.Organization; import org.schema.api.model.thing.creativeWork.mediaObject.VideoObject; import org.schema.api.model.thing.creativeWork.CreativeWork; import org.schema.api.model.thing.creativeWork.CreativeWork; public class WPSideBar extends WebPageElement { private Thing about; private String accessMode; private String accessModeSufficient; private String accessibilityAPI; private String accessibilityControl; private String accessibilityFeature; private String accessibilityHazard; private String accessibilitySummary; private Person accountablePerson; private AggregateRating aggregateRating; private String alternativeHeadline; private MediaObject associatedMedia; private Audience audience;//Notes - Allowed types- [Audience, serviceAudience] private AudioObject audio; private Organization author;//Notes - Allowed types- [Organization, Person] private String award; private Person character; private String citation;//Notes - Allowed types- [CreativeWork, Text] private Comment comment; private Integer commentCount; private Place contentLocation; private String contentRating; private Date contentReferenceTime; private Organization contributor;//Notes - Allowed types- [Organization, Person] private Organization copyrightHolder;//Notes - Allowed types- [Organization, Person] private Number copyrightYear; private Organization creator;//Notes - Allowed types- [Organization, Person] private Date dateCreated;//Notes - Allowed types- [Date, DateTime] private Date dateModified;//Notes - Allowed types- [Date, DateTime] private Date datePublished; private String discussionUrl; private Person editor; private AlignmentObject educationalAlignment; private String educationalUse; private MediaObject encoding; private CreativeWork exampleOfWork;//Notes - Allowed types- [CreativeWork, workExample] private Date expires; private String fileFormat;//Notes - Allowed types- [Text, URL] private Organization funder;//Notes - Allowed types- [Organization, Person] private String genre;//Notes - Allowed types- [Text, URL] private CreativeWork hasPart;//Notes - Allowed types- [CreativeWork, isPartOf] private String headline; private String inLanguage;//Notes - Allowed types- [Language, Text] private InteractionCounter interactionStatistic; private String interactivityType; private Boolean isAccessibleForFree;//Notes - Allowed types- [Boolean, free] private String isBasedOn;//Notes - Allowed types- [CreativeWork, Product, URL] private Boolean isFamilyFriendly; private CreativeWork isPartOf;//Notes - Allowed types- [CreativeWork, hasPart] private String keywords; private String learningResourceType; private String license;//Notes - Allowed types- [CreativeWork, URL] private Place locationCreated; private Thing mainEntity;//Notes - Allowed types- [Thing, mainEntityOfPage] private String material;//Notes - Allowed types- [Product, Text, URL] private Thing mentions; private Offer offers; private String position;//Notes - Allowed types- [Integer, Text] private Organization producer;//Notes - Allowed types- [Organization, Person] private Organization provider;//Notes - Allowed types- [Organization, Person, carrier] private PublicationEvent publication; private Organization publisher;//Notes - Allowed types- [Organization, Person] private Organization publisherImprint; private String publishingPrinciples;//Notes - Allowed types- [CreativeWork, URL] private Event recordedAt;//Notes - Allowed types- [Event, recordedIn] private PublicationEvent releasedEvent; private Review review;//Notes - Allowed types- [Review, reviews] private String schemaVersion;//Notes - Allowed types- [Text, URL] private Organization sourceOrganization; private Place spatialCoverage; private Organization sponsor;//Notes - Allowed types- [Organization, Person] private Date temporalCoverage;//Notes - Allowed types- [DateTime, Text, URL] private String text; private String thumbnailUrl; private Duration timeRequired; private CreativeWork translationOfWork;//Notes - Allowed types- [CreativeWork, workTranslation] private Organization translator;//Notes - Allowed types- [Organization, Person] private String typicalAgeRange; private Number version;//Notes - Allowed types- [Number, Text] private VideoObject video; private CreativeWork workExample;//Notes - Allowed types- [CreativeWork, exampleOfWork] private CreativeWork workTranslation;//Notes - Allowed types- [CreativeWork, translationOfWork] public Thing getAbout() { return about; } public void setAbout(Thing about) { this.about = about; } public String getAccessMode() { return accessMode; } public void setAccessMode(String accessMode) { this.accessMode = accessMode; } public String getAccessModeSufficient() { return accessModeSufficient; } public void setAccessModeSufficient(String accessModeSufficient) { this.accessModeSufficient = accessModeSufficient; } public String getAccessibilityAPI() { return accessibilityAPI; } public void setAccessibilityAPI(String accessibilityAPI) { this.accessibilityAPI = accessibilityAPI; } public String getAccessibilityControl() { return accessibilityControl; } public void setAccessibilityControl(String accessibilityControl) { this.accessibilityControl = accessibilityControl; } public String getAccessibilityFeature() { return accessibilityFeature; } public void setAccessibilityFeature(String accessibilityFeature) { this.accessibilityFeature = accessibilityFeature; } public String getAccessibilityHazard() { return accessibilityHazard; } public void setAccessibilityHazard(String accessibilityHazard) { this.accessibilityHazard = accessibilityHazard; } public String getAccessibilitySummary() { return accessibilitySummary; } public void setAccessibilitySummary(String accessibilitySummary) { this.accessibilitySummary = accessibilitySummary; } public Person getAccountablePerson() { return accountablePerson; } public void setAccountablePerson(Person accountablePerson) { this.accountablePerson = accountablePerson; } public AggregateRating getAggregateRating() { return aggregateRating; } public void setAggregateRating(AggregateRating aggregateRating) { this.aggregateRating = aggregateRating; } public String getAlternativeHeadline() { return alternativeHeadline; } public void setAlternativeHeadline(String alternativeHeadline) { this.alternativeHeadline = alternativeHeadline; } public MediaObject getAssociatedMedia() { return associatedMedia; } public void setAssociatedMedia(MediaObject associatedMedia) { this.associatedMedia = associatedMedia; } public Audience getAudience() { return audience; } public void setAudience(Audience audience) { this.audience = audience; } public AudioObject getAudio() { return audio; } public void setAudio(AudioObject audio) { this.audio = audio; } public Organization getAuthor() { return author; } public void setAuthor(Organization author) { this.author = author; } public String getAward() { return award; } public void setAward(String award) { this.award = award; } public Person getCharacter() { return character; } public void setCharacter(Person character) { this.character = character; } public String getCitation() { return citation; } public void setCitation(String citation) { this.citation = citation; } public Comment getComment() { return comment; } public void setComment(Comment comment) { this.comment = comment; } public Integer getCommentCount() { return commentCount; } public void setCommentCount(Integer commentCount) { this.commentCount = commentCount; } public Place getContentLocation() { return contentLocation; } public void setContentLocation(Place contentLocation) { this.contentLocation = contentLocation; } public String getContentRating() { return contentRating; } public void setContentRating(String contentRating) { this.contentRating = contentRating; } public Date getContentReferenceTime() { return contentReferenceTime; } public void setContentReferenceTime(Date contentReferenceTime) { this.contentReferenceTime = contentReferenceTime; } public Organization getContributor() { return contributor; } public void setContributor(Organization contributor) { this.contributor = contributor; } public Organization getCopyrightHolder() { return copyrightHolder; } public void setCopyrightHolder(Organization copyrightHolder) { this.copyrightHolder = copyrightHolder; } public Number getCopyrightYear() { return copyrightYear; } public void setCopyrightYear(Number copyrightYear) { this.copyrightYear = copyrightYear; } public Organization getCreator() { return creator; } public void setCreator(Organization creator) { this.creator = creator; } public Date getDateCreated() { return dateCreated; } public void setDateCreated(Date dateCreated) { this.dateCreated = dateCreated; } public Date getDateModified() { return dateModified; } public void setDateModified(Date dateModified) { this.dateModified = dateModified; } public Date getDatePublished() { return datePublished; } public void setDatePublished(Date datePublished) { this.datePublished = datePublished; } public String getDiscussionUrl() { return discussionUrl; } public void setDiscussionUrl(String discussionUrl) { this.discussionUrl = discussionUrl; } public Person getEditor() { return editor; } public void setEditor(Person editor) { this.editor = editor; } public AlignmentObject getEducationalAlignment() { return educationalAlignment; } public void setEducationalAlignment(AlignmentObject educationalAlignment) { this.educationalAlignment = educationalAlignment; } public String getEducationalUse() { return educationalUse; } public void setEducationalUse(String educationalUse) { this.educationalUse = educationalUse; } public MediaObject getEncoding() { return encoding; } public void setEncoding(MediaObject encoding) { this.encoding = encoding; } public CreativeWork getExampleOfWork() { return exampleOfWork; } public void setExampleOfWork(CreativeWork exampleOfWork) { this.exampleOfWork = exampleOfWork; } public Date getExpires() { return expires; } public void setExpires(Date expires) { this.expires = expires; } public String getFileFormat() { return fileFormat; } public void setFileFormat(String fileFormat) { this.fileFormat = fileFormat; } public Organization getFunder() { return funder; } public void setFunder(Organization funder) { this.funder = funder; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } public CreativeWork getHasPart() { return hasPart; } public void setHasPart(CreativeWork hasPart) { this.hasPart = hasPart; } public String getHeadline() { return headline; } public void setHeadline(String headline) { this.headline = headline; } public String getInLanguage() { return inLanguage; } public void setInLanguage(String inLanguage) { this.inLanguage = inLanguage; } public InteractionCounter getInteractionStatistic() { return interactionStatistic; } public void setInteractionStatistic(InteractionCounter interactionStatistic) { this.interactionStatistic = interactionStatistic; } public String getInteractivityType() { return interactivityType; } public void setInteractivityType(String interactivityType) { this.interactivityType = interactivityType; } public Boolean getIsAccessibleForFree() { return isAccessibleForFree; } public void setIsAccessibleForFree(Boolean isAccessibleForFree) { this.isAccessibleForFree = isAccessibleForFree; } public String getIsBasedOn() { return isBasedOn; } public void setIsBasedOn(String isBasedOn) { this.isBasedOn = isBasedOn; } public Boolean getIsFamilyFriendly() { return isFamilyFriendly; } public void setIsFamilyFriendly(Boolean isFamilyFriendly) { this.isFamilyFriendly = isFamilyFriendly; } public CreativeWork getIsPartOf() { return isPartOf; } public void setIsPartOf(CreativeWork isPartOf) { this.isPartOf = isPartOf; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getLearningResourceType() { return learningResourceType; } public void setLearningResourceType(String learningResourceType) { this.learningResourceType = learningResourceType; } public String getLicense() { return license; } public void setLicense(String license) { this.license = license; } public Place getLocationCreated() { return locationCreated; } public void setLocationCreated(Place locationCreated) { this.locationCreated = locationCreated; } public Thing getMainEntity() { return mainEntity; } public void setMainEntity(Thing mainEntity) { this.mainEntity = mainEntity; } public String getMaterial() { return material; } public void setMaterial(String material) { this.material = material; } public Thing getMentions() { return mentions; } public void setMentions(Thing mentions) { this.mentions = mentions; } public Offer getOffers() { return offers; } public void setOffers(Offer offers) { this.offers = offers; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Organization getProducer() { return producer; } public void setProducer(Organization producer) { this.producer = producer; } public Organization getProvider() { return provider; } public void setProvider(Organization provider) { this.provider = provider; } public PublicationEvent getPublication() { return publication; } public void setPublication(PublicationEvent publication) { this.publication = publication; } public Organization getPublisher() { return publisher; } public void setPublisher(Organization publisher) { this.publisher = publisher; } public Organization getPublisherImprint() { return publisherImprint; } public void setPublisherImprint(Organization publisherImprint) { this.publisherImprint = publisherImprint; } public String getPublishingPrinciples() { return publishingPrinciples; } public void setPublishingPrinciples(String publishingPrinciples) { this.publishingPrinciples = publishingPrinciples; } public Event getRecordedAt() { return recordedAt; } public void setRecordedAt(Event recordedAt) { this.recordedAt = recordedAt; } public PublicationEvent getReleasedEvent() { return releasedEvent; } public void setReleasedEvent(PublicationEvent releasedEvent) { this.releasedEvent = releasedEvent; } public Review getReview() { return review; } public void setReview(Review review) { this.review = review; } public String getSchemaVersion() { return schemaVersion; } public void setSchemaVersion(String schemaVersion) { this.schemaVersion = schemaVersion; } public Organization getSourceOrganization() { return sourceOrganization; } public void setSourceOrganization(Organization sourceOrganization) { this.sourceOrganization = sourceOrganization; } public Place getSpatialCoverage() { return spatialCoverage; } public void setSpatialCoverage(Place spatialCoverage) { this.spatialCoverage = spatialCoverage; } public Organization getSponsor() { return sponsor; } public void setSponsor(Organization sponsor) { this.sponsor = sponsor; } public Date getTemporalCoverage() { return temporalCoverage; } public void setTemporalCoverage(Date temporalCoverage) { this.temporalCoverage = temporalCoverage; } public String getText() { return text; } public void setText(String text) { this.text = text; } public String getThumbnailUrl() { return thumbnailUrl; } public void setThumbnailUrl(String thumbnailUrl) { this.thumbnailUrl = thumbnailUrl; } public Duration getTimeRequired() { return timeRequired; } public void setTimeRequired(Duration timeRequired) { this.timeRequired = timeRequired; } public CreativeWork getTranslationOfWork() { return translationOfWork; } public void setTranslationOfWork(CreativeWork translationOfWork) { this.translationOfWork = translationOfWork; } public Organization getTranslator() { return translator; } public void setTranslator(Organization translator) { this.translator = translator; } public String getTypicalAgeRange() { return typicalAgeRange; } public void setTypicalAgeRange(String typicalAgeRange) { this.typicalAgeRange = typicalAgeRange; } public Number getVersion() { return version; } public void setVersion(Number version) { this.version = version; } public VideoObject getVideo() { return video; } public void setVideo(VideoObject video) { this.video = video; } public CreativeWork getWorkExample() { return workExample; } public void setWorkExample(CreativeWork workExample) { this.workExample = workExample; } public CreativeWork getWorkTranslation() { return workTranslation; } public void setWorkTranslation(CreativeWork workTranslation) { this.workTranslation = workTranslation; } }
{'content_hash': '4a4cf216c3e4a79b5d679cf2c3591a52', 'timestamp': '', 'source': 'github', 'line_count': 957, 'max_line_length': 96, 'avg_line_length': 20.986415882967606, 'alnum_prop': 0.772903804023103, 'repo_name': 'omindra/schema_org_java_api', 'id': '270216a40c9b3e94557fa05f6de61d011096ac3e', 'size': '20084', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'core/main/java/org/schema/api/model/thing/creativeWork/webPageElement/WPSideBar.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Java', 'bytes': '2797669'}]}
package org.conscrypt; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.CertPath; import java.security.cert.CertPathValidator; import java.security.cert.CertPathValidatorException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateParsingException; import java.security.cert.CertificateFactory; import java.security.cert.PKIXCertPathChecker; import java.security.cert.PKIXParameters; import java.security.cert.TrustAnchor; import java.security.cert.X509Certificate; import java.util.Arrays; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.net.ssl.X509TrustManager; import libcore.io.EventLogger; /** * * TrustManager implementation. The implementation is based on CertPathValidator * PKIX and CertificateFactory X509 implementations. This implementations should * be provided by some certification provider. * * @see javax.net.ssl.X509TrustManager */ public final class TrustManagerImpl implements X509TrustManager { /** * The AndroidCAStore if non-null, null otherwise. */ private final KeyStore rootKeyStore; /** * The CertPinManager, which validates the chain against a host-to-pin mapping */ private CertPinManager pinManager; /** * The backing store for the AndroidCAStore if non-null. This will * be null when the rootKeyStore is null, implying we are not * using the AndroidCAStore. */ private final TrustedCertificateStore trustedCertificateStore; private final CertPathValidator validator; /** * An index of TrustAnchor instances that we've seen. Unlike the * TrustedCertificateStore, this may contain intermediate CAs. */ private final TrustedCertificateIndex trustedCertificateIndex; /** * This is lazily initialized in the AndroidCAStore case since it * forces us to bring all the CAs into memory. In the * non-AndroidCAStore, we initialize this as part of the * constructor. */ private final X509Certificate[] acceptedIssuers; private final Exception err; private final CertificateFactory factory; /** * Creates X509TrustManager based on a keystore * * @param ks */ public TrustManagerImpl(KeyStore keyStore) { this(keyStore, null); } /** * For testing only */ public TrustManagerImpl(KeyStore keyStore, CertPinManager manager) { CertPathValidator validatorLocal = null; CertificateFactory factoryLocal = null; KeyStore rootKeyStoreLocal = null; TrustedCertificateStore trustedCertificateStoreLocal = null; TrustedCertificateIndex trustedCertificateIndexLocal = null; X509Certificate[] acceptedIssuersLocal = null; Exception errLocal = null; try { validatorLocal = CertPathValidator.getInstance("PKIX"); factoryLocal = CertificateFactory.getInstance("X509"); // if we have an AndroidCAStore, we will lazily load CAs if ("AndroidCAStore".equals(keyStore.getType())) { rootKeyStoreLocal = keyStore; trustedCertificateStoreLocal = new TrustedCertificateStore(); acceptedIssuersLocal = null; trustedCertificateIndexLocal = new TrustedCertificateIndex(); } else { rootKeyStoreLocal = null; trustedCertificateStoreLocal = null; acceptedIssuersLocal = acceptedIssuers(keyStore); trustedCertificateIndexLocal = new TrustedCertificateIndex(trustAnchors(acceptedIssuersLocal)); } } catch (Exception e) { errLocal = e; } if (manager != null) { this.pinManager = manager; } else { try { pinManager = new CertPinManager(trustedCertificateStoreLocal); } catch (PinManagerException e) { throw new SecurityException("Could not initialize CertPinManager", e); } } this.rootKeyStore = rootKeyStoreLocal; this.trustedCertificateStore = trustedCertificateStoreLocal; this.validator = validatorLocal; this.factory = factoryLocal; this.trustedCertificateIndex = trustedCertificateIndexLocal; this.acceptedIssuers = acceptedIssuersLocal; this.err = errLocal; } private static X509Certificate[] acceptedIssuers(KeyStore ks) { try { // Note that unlike the PKIXParameters code to create a Set of // TrustAnchors from a KeyStore, this version takes from both // TrustedCertificateEntry and PrivateKeyEntry, not just // TrustedCertificateEntry, which is why TrustManagerImpl // cannot just use an PKIXParameters(KeyStore) // constructor. // TODO remove duplicates if same cert is found in both a // PrivateKeyEntry and TrustedCertificateEntry List<X509Certificate> trusted = new ArrayList<X509Certificate>(); for (Enumeration<String> en = ks.aliases(); en.hasMoreElements();) { final String alias = en.nextElement(); final X509Certificate cert = (X509Certificate) ks.getCertificate(alias); if (cert != null) { trusted.add(cert); } } return trusted.toArray(new X509Certificate[trusted.size()]); } catch (KeyStoreException e) { return new X509Certificate[0]; } } private static Set<TrustAnchor> trustAnchors(X509Certificate[] certs) { Set<TrustAnchor> trustAnchors = new HashSet<TrustAnchor>(certs.length); for (X509Certificate cert : certs) { trustAnchors.add(new TrustAnchor(cert, null)); } return trustAnchors; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { checkTrusted(chain, authType, null, true); } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { checkTrusted(chain, authType, null, false); } /** * Validates whether a server is trusted. If hostname is given and non-null it also checks if * chain is pinned appropriately for that host. If null, it does not check for pinned certs. * The return value is a list of the certificates used for making the trust decision. */ public List<X509Certificate> checkServerTrusted(X509Certificate[] chain, String authType, String host) throws CertificateException { return checkTrusted(chain, authType, host, false); } public void handleTrustStorageUpdate() { if (acceptedIssuers == null) { trustedCertificateIndex.reset(); } else { trustedCertificateIndex.reset(trustAnchors(acceptedIssuers)); } } private List<X509Certificate> checkTrusted(X509Certificate[] chain, String authType, String host, boolean clientAuth) throws CertificateException { if (chain == null || chain.length == 0 || authType == null || authType.length() == 0) { throw new IllegalArgumentException("null or zero-length parameter"); } if (err != null) { throw new CertificateException(err); } // get the cleaned up chain and trust anchor Set<TrustAnchor> trustAnchor = new HashSet<TrustAnchor>(); // there can only be one! X509Certificate[] newChain = cleanupCertChainAndFindTrustAnchors(chain, trustAnchor); // add the first trust anchor to the chain, which may be an intermediate List<X509Certificate> wholeChain = new ArrayList<X509Certificate>(); wholeChain.addAll(Arrays.asList(newChain)); // trustAnchor is actually just a single element for (TrustAnchor trust : trustAnchor) { wholeChain.add(trust.getTrustedCert()); } // add all the cached certificates from the cert index, avoiding loops // this gives us a full chain from leaf to root, which we use for cert pinning and pass // back out to callers when we return. X509Certificate last = wholeChain.get(wholeChain.size() - 1); while (true) { TrustAnchor cachedTrust = trustedCertificateIndex.findByIssuerAndSignature(last); // the cachedTrust can be null if there isn't anything in the index or if a user has // trusted a non-self-signed cert. if (cachedTrust == null) { break; } // at this point we have a cached trust anchor, but don't know if its one we got from // the server. Extract the cert, compare it to the last element in the chain, and add it // if we haven't seen it before. X509Certificate next = cachedTrust.getTrustedCert(); if (next != last) { wholeChain.add(next); last = next; } else { // if next == last then we found a self-signed cert and the chain is done break; } } // build the cert path from the array of certs sans trust anchors CertPath certPath = factory.generateCertPath(Arrays.asList(newChain)); if (host != null) { boolean chainIsNotPinned = true; try { chainIsNotPinned = pinManager.chainIsNotPinned(host, wholeChain); } catch (PinManagerException e) { throw new CertificateException(e); } if (chainIsNotPinned) { throw new CertificateException(new CertPathValidatorException( "Certificate path is not properly pinned.", null, certPath, -1)); } } if (newChain.length == 0) { // chain was entirely trusted, skip the validator return wholeChain; } if (trustAnchor.isEmpty()) { throw new CertificateException(new CertPathValidatorException( "Trust anchor for certification path not found.", null, certPath, -1)); } // There's no point in checking trust anchors here, and it will throw off the MD5 check, // so we just hand it the chain without anchors ChainStrengthAnalyzer.check(newChain); try { PKIXParameters params = new PKIXParameters(trustAnchor); params.setRevocationEnabled(false); params.addCertPathChecker(new ExtendedKeyUsagePKIXCertPathChecker(clientAuth, newChain[0])); validator.validate(certPath, params); // Add intermediate CAs to the index to tolerate sites // that assume that the browser will have cached these. // The server certificate is skipped by skipping the // zeroth element of new chain and note that the root CA // will have been removed in // cleanupCertChainAndFindTrustAnchors. http://b/3404902 for (int i = 1; i < newChain.length; i++) { trustedCertificateIndex.index(newChain[i]); } } catch (InvalidAlgorithmParameterException e) { throw new CertificateException(e); } catch (CertPathValidatorException e) { throw new CertificateException(e); } return wholeChain; } /** * Clean up the certificate chain, returning a cleaned up chain, * which may be a new array instance if elements were removed. * Theoretically, we shouldn't have to do this, but various web * servers in practice are mis-configured to have out-of-order * certificates, expired self-issued root certificate, or CAs with * unsupported signature algorithms such as * md2WithRSAEncryption. This also handles removing old certs * after bridge CA certs. */ private X509Certificate[] cleanupCertChainAndFindTrustAnchors(X509Certificate[] chain, Set<TrustAnchor> trustAnchors) { X509Certificate[] original = chain; // 1. Clean the received certificates chain. int currIndex; // Start with the first certificate in the chain, assuming it // is the leaf certificate (server or client cert). for (currIndex = 0; currIndex < chain.length; currIndex++) { // Walk the chain to find a "subject" matching // the "issuer" of the current certificate. In a properly // ordered chain this should be the next cert and be fast. // If not, we reorder things to be as the validator will // expect. boolean foundNext = false; for (int nextIndex = currIndex + 1; nextIndex < chain.length; nextIndex++) { if (chain[currIndex].getIssuerDN().equals(chain[nextIndex].getSubjectDN())) { foundNext = true; // Exchange certificates so that 0 through currIndex + 1 are in proper order if (nextIndex != currIndex + 1) { // don't mutuate original chain, which may be directly from an SSLSession if (chain == original) { chain = original.clone(); } X509Certificate tempCertificate = chain[nextIndex]; chain[nextIndex] = chain[currIndex + 1]; chain[currIndex + 1] = tempCertificate; } break; } } // If we can't find the next in the chain, just give up // and use what we found so far. This drops unrelated // certificates that have nothing to do with the cert // chain. if (!foundNext) { break; } } // 2. Find the trust anchor in the chain, if any int anchorIndex; for (anchorIndex = 0; anchorIndex <= currIndex; anchorIndex++) { // If the current cert is a TrustAnchor, we can ignore the rest of the chain. // This avoids including "bridge" CA certs that added for legacy compatibility. TrustAnchor trustAnchor = findTrustAnchorBySubjectAndPublicKey(chain[anchorIndex]); if (trustAnchor != null) { trustAnchors.add(trustAnchor); break; } } // 3. If the chain is now shorter, copy to an appropriately sized array. int chainLength = anchorIndex; X509Certificate[] newChain = ((chainLength == chain.length) ? chain : Arrays.copyOf(chain, chainLength)); // 4. If we didn't find a trust anchor earlier, look for one now if (trustAnchors.isEmpty()) { TrustAnchor trustAnchor = findTrustAnchorByIssuerAndSignature(newChain[anchorIndex-1]); if (trustAnchor != null) { trustAnchors.add(trustAnchor); } } return newChain; } /** * If an EKU extension is present in the end-entity certificate, * it MUST contain an appropriate key usage. For servers, this * includes anyExtendedKeyUsage, serverAuth, or the historical * Server Gated Cryptography options of nsSGC or msSGC. For * clients, this includes anyExtendedKeyUsage and clientAuth. */ private static class ExtendedKeyUsagePKIXCertPathChecker extends PKIXCertPathChecker { private static final String EKU_OID = "2.5.29.37"; private static final String EKU_anyExtendedKeyUsage = "2.5.29.37.0"; private static final String EKU_clientAuth = "1.3.6.1.5.5.7.3.2"; private static final String EKU_serverAuth = "1.3.6.1.5.5.7.3.1"; private static final String EKU_nsSGC = "2.16.840.1.113730.4.1"; private static final String EKU_msSGC = "1.3.6.1.4.1.311.10.3.3"; private static final Set<String> SUPPORTED_EXTENSIONS = Collections.unmodifiableSet(new HashSet<String>(Arrays.asList(EKU_OID))); private final boolean clientAuth; private final X509Certificate leaf; private ExtendedKeyUsagePKIXCertPathChecker(boolean clientAuth, X509Certificate leaf) { this.clientAuth = clientAuth; this.leaf = leaf; } @Override public void init(boolean forward) throws CertPathValidatorException { } @Override public boolean isForwardCheckingSupported() { return true; } @Override public Set<String> getSupportedExtensions() { return SUPPORTED_EXTENSIONS; } @Override public void check(Certificate c, Collection<String> unresolvedCritExts) throws CertPathValidatorException { // We only want to validate the EKU on the leaf certificate. if (c != leaf) { return; } List<String> ekuOids; try { ekuOids = leaf.getExtendedKeyUsage(); } catch (CertificateParsingException e) { // A malformed EKU is bad news, consider it fatal. throw new CertPathValidatorException(e); } // We are here to check EKU, but there is none. if (ekuOids == null) { return; } boolean goodExtendedKeyUsage = false; for (String ekuOid : ekuOids) { // anyExtendedKeyUsage for clients and servers if (ekuOid.equals(EKU_anyExtendedKeyUsage)) { goodExtendedKeyUsage = true; break; } // clients if (clientAuth) { if (ekuOid.equals(EKU_clientAuth)) { goodExtendedKeyUsage = true; break; } continue; } // servers if (ekuOid.equals(EKU_serverAuth)) { goodExtendedKeyUsage = true; break; } if (ekuOid.equals(EKU_nsSGC)) { goodExtendedKeyUsage = true; break; } if (ekuOid.equals(EKU_msSGC)) { goodExtendedKeyUsage = true; break; } } if (goodExtendedKeyUsage) { // Mark extendedKeyUsage as resolved if present. unresolvedCritExts.remove(EKU_OID); } else { throw new CertPathValidatorException("End-entity certificate does not have a valid " + "extendedKeyUsage."); } } } private TrustAnchor findTrustAnchorByIssuerAndSignature(X509Certificate lastCert) { TrustAnchor trustAnchor = trustedCertificateIndex.findByIssuerAndSignature(lastCert); if (trustAnchor != null) { return trustAnchor; } if (trustedCertificateStore == null) { return null; } // we have a KeyStore and the issuer of the last cert in // the chain seems to be missing from the // TrustedCertificateIndex, check the KeyStore for a hit X509Certificate issuer = trustedCertificateStore.findIssuer(lastCert); if (issuer != null) { return trustedCertificateIndex.index(issuer); } return null; } /** * Check the trustedCertificateIndex for the cert to see if it is * already trusted and failing that check the KeyStore if it is * available. */ private TrustAnchor findTrustAnchorBySubjectAndPublicKey(X509Certificate cert) { TrustAnchor trustAnchor = trustedCertificateIndex.findBySubjectAndPublicKey(cert); if (trustAnchor != null) { return trustAnchor; } if (trustedCertificateStore == null) { // not trusted and no TrustedCertificateStore to check return null; } // probe KeyStore for a cert. AndroidCAStore stores its // contents hashed by cert subject on the filesystem to make // this faster than scanning all key store entries. if (trustedCertificateStore.isTrustAnchor(cert)) { // add new TrustAnchor to params index to avoid // checking filesystem next time around. return trustedCertificateIndex.index(cert); } return null; } @Override public X509Certificate[] getAcceptedIssuers() { return (acceptedIssuers != null) ? acceptedIssuers.clone() : acceptedIssuers(rootKeyStore); } }
{'content_hash': '1eb28161d667098f59829b0b9a15953d', 'timestamp': '', 'source': 'github', 'line_count': 521, 'max_line_length': 100, 'avg_line_length': 41.12284069097889, 'alnum_prop': 0.6078879813302217, 'repo_name': 'indashnet/InDashNet.Open.UN2000', 'id': 'ef366d2baa64a10b8d9b133daad1e75638bb179a', 'size': '22237', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'android/libcore/crypto/src/main/java/org/conscrypt/TrustManagerImpl.java', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
@org.spongepowered.api.util.annotation.NonnullByDefault package org.spongepowered.common.event.tracking.phase;
{'content_hash': '1282ac506d8a06f4e3aeaf02676f3be7', 'timestamp': '', 'source': 'github', 'line_count': 2, 'max_line_length': 110, 'avg_line_length': 56.0, 'alnum_prop': 0.8571428571428571, 'repo_name': 'Grinch/SpongeCommon', 'id': '67e8a091c1485e02e12dcd8b16f1048995c07fc6', 'size': '1359', 'binary': False, 'copies': '5', 'ref': 'refs/heads/bleeding', 'path': 'src/main/java/org/spongepowered/common/event/tracking/phase/package-info.java', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Java', 'bytes': '11036834'}, {'name': 'Shell', 'bytes': '1072'}]}
package mx.fiscoflex.contabilidad.respaldo; public class ImexEmpresa { }
{'content_hash': 'ffd324b3c3cf3b39b188426f96f7806b', 'timestamp': '', 'source': 'github', 'line_count': 5, 'max_line_length': 43, 'avg_line_length': 15.0, 'alnum_prop': 0.8, 'repo_name': 'fiscoflex/erp', 'id': '3daabe33e5cc7b44719c203879f7c07395d8cc3e', 'size': '75', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'fiscoflex-rest/src/main/java/mx/fiscoflex/contabilidad/respaldo/ImexEmpresa.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'CSS', 'bytes': '501998'}, {'name': 'HTML', 'bytes': '1698308'}, {'name': 'Java', 'bytes': '197843'}, {'name': 'JavaScript', 'bytes': '2866114'}, {'name': 'PHP', 'bytes': '1684'}]}
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>windows::basic_object_handle::operator=</title> <link rel="stylesheet" href="../../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../../boost_asio.html" title="Boost.Asio"> <link rel="up" href="../windows__basic_object_handle.html" title="windows::basic_object_handle"> <link rel="prev" href="native_type.html" title="windows::basic_object_handle::native_type"> <link rel="next" href="service.html" title="windows::basic_object_handle::service"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../boost.png"></td> <td align="center"><a href="../../../../../index.html">Home</a></td> <td align="center"><a href="../../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="native_type.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../windows__basic_object_handle.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="service.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="section"> <div class="titlepage"><div><div><h4 class="title"> <a name="boost_asio.reference.windows__basic_object_handle.operator_eq_"></a><a class="link" href="operator_eq_.html" title="windows::basic_object_handle::operator=">windows::basic_object_handle::operator=</a> </h4></div></div></div> <p> <a class="indexterm" name="idp106274640"></a> Move-assign a <a class="link" href="../windows__basic_object_handle.html" title="windows::basic_object_handle"><code class="computeroutput"><span class="identifier">windows</span><span class="special">::</span><span class="identifier">basic_object_handle</span></code></a> from another. </p> <pre class="programlisting"><span class="identifier">basic_object_handle</span> <span class="special">&amp;</span> <span class="keyword">operator</span><span class="special">=(</span> <span class="identifier">basic_object_handle</span> <span class="special">&amp;&amp;</span> <span class="identifier">other</span><span class="special">);</span> </pre> <p> This assignment operator moves an object handle from one object to another. </p> <h6> <a name="boost_asio.reference.windows__basic_object_handle.operator_eq_.h0"></a> <span><a name="boost_asio.reference.windows__basic_object_handle.operator_eq_.parameters"></a></span><a class="link" href="operator_eq_.html#boost_asio.reference.windows__basic_object_handle.operator_eq_.parameters">Parameters</a> </h6> <div class="variablelist"> <p class="title"><b></b></p> <dl> <dt><span class="term">other</span></dt> <dd><p> The other <a class="link" href="../windows__basic_object_handle.html" title="windows::basic_object_handle"><code class="computeroutput"><span class="identifier">windows</span><span class="special">::</span><span class="identifier">basic_object_handle</span></code></a> object from which the move will occur. </p></dd> </dl> </div> <h6> <a name="boost_asio.reference.windows__basic_object_handle.operator_eq_.h1"></a> <span><a name="boost_asio.reference.windows__basic_object_handle.operator_eq_.remarks"></a></span><a class="link" href="operator_eq_.html#boost_asio.reference.windows__basic_object_handle.operator_eq_.remarks">Remarks</a> </h6> <p> Following the move, the moved-from object is in the same state as if constructed using the <code class="computeroutput"><span class="identifier">basic_object_handle</span><span class="special">(</span><span class="identifier">io_service</span><span class="special">&amp;)</span> <span class="identifier">constructor</span></code>. </p> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2015 Christopher M. Kohlhoff<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="native_type.html"><img src="../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../windows__basic_object_handle.html"><img src="../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../../boost_asio.html"><img src="../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="service.html"><img src="../../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
{'content_hash': 'a3fa85726ba4d93a634971607e393583', 'timestamp': '', 'source': 'github', 'line_count': 76, 'max_line_length': 444, 'avg_line_length': 71.10526315789474, 'alnum_prop': 0.6502590673575129, 'repo_name': 'calvinfarias/IC2015-2', 'id': 'd14305b164b7180ec594bcbe1e03c2692150d427', 'size': '5404', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'BOOST/boost_1_61_0/libs/asio/doc/html/boost_asio/reference/windows__basic_object_handle/operator_eq_.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'Assembly', 'bytes': '223360'}, {'name': 'Batchfile', 'bytes': '32233'}, {'name': 'C', 'bytes': '2977162'}, {'name': 'C#', 'bytes': '40804'}, {'name': 'C++', 'bytes': '184445796'}, {'name': 'CMake', 'bytes': '119765'}, {'name': 'CSS', 'bytes': '427923'}, {'name': 'Cuda', 'bytes': '111870'}, {'name': 'DIGITAL Command Language', 'bytes': '6246'}, {'name': 'FORTRAN', 'bytes': '5291'}, {'name': 'Groff', 'bytes': '5189'}, {'name': 'HTML', 'bytes': '234946752'}, {'name': 'IDL', 'bytes': '14'}, {'name': 'JavaScript', 'bytes': '682223'}, {'name': 'Lex', 'bytes': '1231'}, {'name': 'M4', 'bytes': '29689'}, {'name': 'Makefile', 'bytes': '1083443'}, {'name': 'Max', 'bytes': '36857'}, {'name': 'Objective-C', 'bytes': '11406'}, {'name': 'Objective-C++', 'bytes': '630'}, {'name': 'PHP', 'bytes': '59030'}, {'name': 'Perl', 'bytes': '39008'}, {'name': 'Perl6', 'bytes': '2053'}, {'name': 'Python', 'bytes': '1759984'}, {'name': 'QML', 'bytes': '593'}, {'name': 'QMake', 'bytes': '16692'}, {'name': 'Rebol', 'bytes': '354'}, {'name': 'Ruby', 'bytes': '5532'}, {'name': 'Shell', 'bytes': '355247'}, {'name': 'Tcl', 'bytes': '1172'}, {'name': 'TeX', 'bytes': '126042'}, {'name': 'XSLT', 'bytes': '552736'}, {'name': 'Yacc', 'bytes': '19623'}]}
package org.drools.model.view; import org.drools.model.Condition; import org.drools.model.Variable; public class ExistentialExprViewItem<T> extends AbstractExprViewItem<T> { private final Condition.Type type; private final ViewItem expression; public ExistentialExprViewItem(Condition.Type type, ViewItem expression) { super(expression.getFirstVariable()); this.type = type; this.expression = expression; } public ViewItem getExpression() { return expression; } @Override public Variable<?>[] getVariables() { return expression.getVariables(); } @Override public Condition.Type getType() { return type; } }
{'content_hash': 'f841ed12e721b155a5a5fe9e64a851ab', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 78, 'avg_line_length': 22.25, 'alnum_prop': 0.6797752808988764, 'repo_name': 'romartin/drools', 'id': '7adac259c8f3a560565227d14f6f3730d035fcd4', 'size': '1305', 'binary': False, 'copies': '16', 'ref': 'refs/heads/master', 'path': 'drools-model/drools-canonical-model/src/main/java/org/drools/model/view/ExistentialExprViewItem.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '15988'}, {'name': 'Batchfile', 'bytes': '2554'}, {'name': 'CSS', 'bytes': '1412'}, {'name': 'GAP', 'bytes': '197299'}, {'name': 'HTML', 'bytes': '6271'}, {'name': 'Java', 'bytes': '34370393'}, {'name': 'Python', 'bytes': '4555'}, {'name': 'Ruby', 'bytes': '491'}, {'name': 'Shell', 'bytes': '1120'}, {'name': 'XSLT', 'bytes': '24302'}]}
using System.Diagnostics.Contracts; using System; namespace System.Reflection { public class ParameterInfo { public MemberInfo Member { get; } public object DefaultValue { get; } public ParameterAttributes Attributes { get; } public Type ParameterType { get; } public string Name { get; } public bool IsLcid { get; } public bool IsOut { get; } public bool IsOptional { get; } public bool IsRetval { get; } public int Position { get; } public bool IsIn { get; } public bool IsDefined (Type! attributeType, bool inherit) { CodeContract.Requires(attributeType != null); return default(bool); } public Object[] GetCustomAttributes (Type! attributeType, bool inherit) { CodeContract.Requires(attributeType != null); return default(Object[]); } return default(Object[]); } public Object[] GetCustomAttributes (bool inherit) { } }
{'content_hash': '3e826d2826ab6d6e0cf2552ea3777e14', 'timestamp': '', 'source': 'github', 'line_count': 79, 'max_line_length': 81, 'avg_line_length': 16.810126582278482, 'alnum_prop': 0.46762048192771083, 'repo_name': 'huoxudong125/CodeContracts', 'id': '280b4afbcdc48a1c204dc713fe1ad099b699812f', 'size': '2479', 'binary': False, 'copies': '12', 'ref': 'refs/heads/master', 'path': 'Microsoft.Research/Contracts/MsCorlib/Original/System.Reflection.ParameterInfo.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ASP', 'bytes': '2883'}, {'name': 'Batchfile', 'bytes': '26723'}, {'name': 'C', 'bytes': '232630'}, {'name': 'C#', 'bytes': '53501571'}, {'name': 'C++', 'bytes': '504486'}, {'name': 'F#', 'bytes': '418'}, {'name': 'HTML', 'bytes': '2819'}, {'name': 'JavaScript', 'bytes': '1544'}, {'name': 'Makefile', 'bytes': '8484'}, {'name': 'Perl', 'bytes': '8834'}, {'name': 'PostScript', 'bytes': '1364'}, {'name': 'PowerShell', 'bytes': '3542'}, {'name': 'Python', 'bytes': '1906'}, {'name': 'TeX', 'bytes': '61151'}, {'name': 'Visual Basic', 'bytes': '245561'}, {'name': 'XSLT', 'bytes': '102883'}]}
'********************************************************* ' ' Copyright (c) Microsoft. All rights reserved. ' '********************************************************* Imports Windows.UI.Xaml Imports Windows.UI.Xaml.Controls Imports Windows.UI.Xaml.Navigation Imports SDKTemplate Imports System Namespace Global.AssociationLaunching ''' <summary> ''' An empty page that can be used on its own or navigated to within a Frame. ''' </summary> Public NotInheritable Partial Class ReceiveUri Inherits Page Dim rootPage As MainPage = MainPage.Current Public Sub New() Me.InitializeComponent() End Sub ''' <summary> ''' Invoked when this page is about to be displayed in a Frame. ''' </summary> ''' <param name="e">Event data that describes how this page was reached. The Parameter ''' property is typically used to configure the page.</param> Protected Overrides Sub OnNavigatedTo(e As NavigationEventArgs) If Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons") Then Me.WindowsScenarioDescription.Visibility = Visibility.Collapsed Else Me.PhoneScenarioDescription.Visibility = Visibility.Collapsed End If If rootPage.ProtocolEvent IsNot Nothing Then rootPage.NotifyUser("Protocol activation received. The received URI is " & rootPage.ProtocolEvent.Uri.AbsoluteUri & ".", NotifyType.StatusMessage) End If End Sub End Class End Namespace
{'content_hash': '8c4828013d81dfe42a41fb5af7292813', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 162, 'avg_line_length': 37.51162790697674, 'alnum_prop': 0.6255424674519529, 'repo_name': 'Keyvandabar/Windows-universal-samples', 'id': '65bce3ade7bf1deb5786995f44d5b16164e2826b', 'size': '1613', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Samples/AssociationLaunching/vb/Scenario4_ReceiveUri.xaml.vb', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2690'}, {'name': 'C#', 'bytes': '10546'}, {'name': 'C++', 'bytes': '202691'}, {'name': 'CSS', 'bytes': '486076'}, {'name': 'HTML', 'bytes': '3945'}, {'name': 'JavaScript', 'bytes': '4204267'}, {'name': 'Visual Basic', 'bytes': '8199'}]}
<?php namespace Mrimann\CoMo\Tests\Unit\Domain\Model; /* * * This script belongs to the TYPO3 Flow package "Mrimann.CoMo". * * * * */ /** * Testcase for Commit */ class CommitTest extends \TYPO3\Flow\Tests\UnitTestCase { /** * @var \Mrimann\CoMo\Domain\Model\Commit */ var $fixture; public function setUp() { $this->fixture = new \Mrimann\CoMo\Domain\Model\Commit(); } public function tearDown() { unset($this->fixture); } /** * @test */ public function setRepositorySetsRepository() { $repository = new \Mrimann\CoMo\Domain\Model\Repository(); $this->fixture->setRepository($repository); $this->assertSame( $this->fixture->getRepository(), $repository ); } /** * @test */ public function setHashSetsHash() { $this->fixture->setHash('foo'); $this->assertEquals( $this->fixture->getHash(), 'foo' ); } /** * @test */ public function setAuthorNameSetsAuthorName() { $this->fixture->setAuthorName('Max Muster'); $this->assertEquals( $this->fixture->getAuthorName(), 'Max Muster' ); } /** * @test */ public function setAuthorEmailSetsAuthorEmail() { $this->fixture->setAuthorEmail('[email protected]'); $this->assertEquals( $this->fixture->getAuthorEmail(), '[email protected]' ); } /** * @test */ public function setCommitterNameSetsCommitterName() { $this->fixture->setCommitterName('Max Muster'); $this->assertEquals( $this->fixture->getCommitterName(), 'Max Muster' ); } /** * @test */ public function setCommitterEmailSetsCommitterEmail() { $this->fixture->setCommitterEmail('[email protected]'); $this->assertEquals( $this->fixture->getCommitterEmail(), '[email protected]' ); } /** * @test */ public function setCommitLineSetsCommitLine() { $this->fixture->setCommitLine('[TEST] Blubb'); $this->assertEquals( '[TEST] Blubb', $this->fixture->getCommitLine() ); } /** * @test */ public function setCommitLineSetsCommitClassToUnknown() { $this->fixture->setCommitLine('Foobar changed'); $this->assertEquals( \Mrimann\CoMo\Domain\Model\Commit::CLASS_UNKNOWN, $this->fixture->getCommitClass() ); } /** * @test */ public function setCommitLineSetsCommitClassToTask() { $this->fixture->setCommitLine('[TASK] Foobar changed'); $this->assertEquals( \Mrimann\CoMo\Domain\Model\Commit::CLASS_TASK, $this->fixture->getCommitClass() ); } /** * @test */ public function setCommitLineSetsCommitClassEvenIfStrangelyWritten() { $this->fixture->setCommitLine('[bugFIX] Foobar fixed'); $this->assertEquals( \Mrimann\CoMo\Domain\Model\Commit::CLASS_BUGFIX, $this->fixture->getCommitClass() ); } /** * @test */ public function getMonthIdentifierReturnsProperValue() { $date = new \DateTime('2013-03-01'); $this->fixture->setDate($date); $this->assertEquals( $this->fixture->getMonthIdentifier(), '2013-03' ); } } ?>
{'content_hash': '759ce4da878833494320c68f89ed0787', 'timestamp': '', 'source': 'github', 'line_count': 151, 'max_line_length': 76, 'avg_line_length': 20.814569536423843, 'alnum_prop': 0.6076996500159084, 'repo_name': 'mrimann/CoMo', 'id': '45d3d06d8c98d8002bf8c890f0c95bed5a39cc18', 'size': '3143', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Tests/Unit/Domain/Model/CommitTest.php', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '4533'}, {'name': 'JavaScript', 'bytes': '440'}, {'name': 'PHP', 'bytes': '71945'}]}
layout: page title: About permalink: /about/ --- DevF aims to replace universities. With hands-on projects and inclusive environment we provide the best platform for learning with on-site programs. You can find more info about DevF [here](http://devf.mx/)
{'content_hash': 'e0cb16c14173693598740440195d7cff', 'timestamp': '', 'source': 'github', 'line_count': 9, 'max_line_length': 149, 'avg_line_length': 28.88888888888889, 'alnum_prop': 0.7653846153846153, 'repo_name': 'devfmx/blog', 'id': '1ed923f1341686c144fa47ea9f4f7ff473a560e8', 'size': '264', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'about.md', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'CSS', 'bytes': '153908'}]}
<?php class Google_Service_DatabaseMigrationService_Expr extends Google_Model { public $description; public $expression; public $location; public $title; public function setDescription($description) { $this->description = $description; } public function getDescription() { return $this->description; } public function setExpression($expression) { $this->expression = $expression; } public function getExpression() { return $this->expression; } public function setLocation($location) { $this->location = $location; } public function getLocation() { return $this->location; } public function setTitle($title) { $this->title = $title; } public function getTitle() { return $this->title; } }
{'content_hash': '5f50198971340e5fa45a5bd77b7141d8', 'timestamp': '', 'source': 'github', 'line_count': 43, 'max_line_length': 71, 'avg_line_length': 18.11627906976744, 'alnum_prop': 0.668806161745828, 'repo_name': 'bshaffer/google-api-php-client-services', 'id': '544c28432a34594fbafe91f94e455d073269f5df', 'size': '1369', 'binary': False, 'copies': '2', 'ref': 'refs/heads/master', 'path': 'src/Google/Service/DatabaseMigrationService/Expr.php', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'PHP', 'bytes': '9540154'}]}
define( "dojox/calendar/nls/id/buttons", { previousButton: "◄", nextButton: "►", todayButton: "Hari Ini", dayButton: "Hari", weekButton: "Minggu", fourDaysButton: "4 Hari", monthButton: "Bulan" } );
{'content_hash': 'e00bbf2dbe39ac486081713b8b7ad808', 'timestamp': '', 'source': 'github', 'line_count': 11, 'max_line_length': 42, 'avg_line_length': 18.818181818181817, 'alnum_prop': 0.6618357487922706, 'repo_name': 'dawenx/p3_web', 'id': 'ae639c8aeeebca60d172fb67c89371bf76c6b7bd', 'size': '211', 'binary': False, 'copies': '29', 'ref': 'refs/heads/master', 'path': 'public/js/release/dojox/calendar/nls/id/buttons.js', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'ActionScript', 'bytes': '17567'}, {'name': 'AngelScript', 'bytes': '4817'}, {'name': 'Batchfile', 'bytes': '1371'}, {'name': 'CSS', 'bytes': '6296498'}, {'name': 'CoffeeScript', 'bytes': '30579'}, {'name': 'HTML', 'bytes': '3374423'}, {'name': 'JavaScript', 'bytes': '35808164'}, {'name': 'Makefile', 'bytes': '848'}, {'name': 'Mako', 'bytes': '405'}, {'name': 'PHP', 'bytes': '38090'}, {'name': 'Shell', 'bytes': '2996'}, {'name': 'XSLT', 'bytes': '47383'}]}
package org.apache.hadoop.mapred; import java.net.InetSocketAddress; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapred.TaskLog.LogName; import org.apache.hadoop.mapreduce.ID; import org.apache.hadoop.mapreduce.MRJobConfig; import org.apache.hadoop.mapreduce.v2.util.MRApps; import org.apache.hadoop.yarn.api.ApplicationConstants; import org.apache.hadoop.yarn.api.ApplicationConstants.Environment; import org.apache.hadoop.yarn.conf.YarnConfiguration; @SuppressWarnings("deprecation") public class MapReduceChildJVM { private static String getTaskLogFile(LogName filter) { return ApplicationConstants.LOG_DIR_EXPANSION_VAR + Path.SEPARATOR + filter.toString(); } private static String getChildEnv(JobConf jobConf, boolean isMap) { if (isMap) { return jobConf.get(JobConf.MAPRED_MAP_TASK_ENV, jobConf.get(JobConf.MAPRED_TASK_ENV)); } return jobConf.get(JobConf.MAPRED_REDUCE_TASK_ENV, jobConf.get(JobConf.MAPRED_TASK_ENV)); } private static String getChildLogLevel(JobConf conf, boolean isMap) { if (isMap) { return conf.get( MRJobConfig.MAP_LOG_LEVEL, JobConf.DEFAULT_LOG_LEVEL.toString() ); } else { return conf.get( MRJobConfig.REDUCE_LOG_LEVEL, JobConf.DEFAULT_LOG_LEVEL.toString() ); } } public static void setVMEnv(Map<String, String> environment, Task task) { JobConf conf = task.conf; // Add the env variables passed by the user String mapredChildEnv = getChildEnv(conf, task.isMapTask()); MRApps.setEnvFromInputString(environment, mapredChildEnv, conf); // Set logging level in the environment. // This is so that, if the child forks another "bin/hadoop" (common in // streaming) it will have the correct loglevel. environment.put( "HADOOP_ROOT_LOGGER", getChildLogLevel(conf, task.isMapTask()) + ",console"); // TODO: The following is useful for instance in streaming tasks. Should be // set in ApplicationMaster's env by the RM. String hadoopClientOpts = System.getenv("HADOOP_CLIENT_OPTS"); if (hadoopClientOpts == null) { hadoopClientOpts = ""; } else { hadoopClientOpts = hadoopClientOpts + " "; } environment.put("HADOOP_CLIENT_OPTS", hadoopClientOpts); // setEnvFromInputString above will add env variable values from // mapredChildEnv to existing variables. We want to overwrite // HADOOP_ROOT_LOGGER and HADOOP_CLIENT_OPTS if the user set it explicitly. Map<String, String> tmpEnv = new HashMap<String, String>(); MRApps.setEnvFromInputString(tmpEnv, mapredChildEnv, conf); String[] keys = { "HADOOP_ROOT_LOGGER", "HADOOP_CLIENT_OPTS" }; for (String key : keys) { if (tmpEnv.containsKey(key)) { environment.put(key, tmpEnv.get(key)); } } // Add stdout/stderr env environment.put( MRJobConfig.STDOUT_LOGFILE_ENV, getTaskLogFile(TaskLog.LogName.STDOUT) ); environment.put( MRJobConfig.STDERR_LOGFILE_ENV, getTaskLogFile(TaskLog.LogName.STDERR) ); } private static String getChildJavaOpts(JobConf jobConf, boolean isMapTask) { String userClasspath = ""; String adminClasspath = ""; if (isMapTask) { userClasspath = jobConf.get( JobConf.MAPRED_MAP_TASK_JAVA_OPTS, jobConf.get( JobConf.MAPRED_TASK_JAVA_OPTS, JobConf.DEFAULT_MAPRED_TASK_JAVA_OPTS) ); adminClasspath = jobConf.get( MRJobConfig.MAPRED_MAP_ADMIN_JAVA_OPTS, MRJobConfig.DEFAULT_MAPRED_ADMIN_JAVA_OPTS); } else { userClasspath = jobConf.get( JobConf.MAPRED_REDUCE_TASK_JAVA_OPTS, jobConf.get( JobConf.MAPRED_TASK_JAVA_OPTS, JobConf.DEFAULT_MAPRED_TASK_JAVA_OPTS) ); adminClasspath = jobConf.get( MRJobConfig.MAPRED_REDUCE_ADMIN_JAVA_OPTS, MRJobConfig.DEFAULT_MAPRED_ADMIN_JAVA_OPTS); } // Add admin classpath first so it can be overridden by user. return adminClasspath + " " + userClasspath; } private static void setupLog4jProperties(Task task, Vector<String> vargs, long logSize, Configuration conf) { String logLevel = getChildLogLevel(task.conf, task.isMapTask()); int numBackups = task.conf.getInt(MRJobConfig.TASK_LOG_BACKUPS, MRJobConfig.DEFAULT_TASK_LOG_BACKUPS); MRApps.addLog4jSystemProperties(logLevel, logSize, numBackups, vargs, conf); } public static List<String> getVMCommand( InetSocketAddress taskAttemptListenerAddr, Task task, JVMId jvmID) { TaskAttemptID attemptID = task.getTaskID(); JobConf conf = task.conf; Vector<String> vargs = new Vector<String>(8); vargs.add(MRApps.crossPlatformifyMREnv(task.conf, Environment.JAVA_HOME) + "/bin/java"); // Add child (task) java-vm options. // // The following symbols if present in mapred.{map|reduce}.child.java.opts // value are replaced: // + @taskid@ is interpolated with value of TaskID. // Other occurrences of @ will not be altered. // // Example with multiple arguments and substitutions, showing // jvm GC logging, and start of a passwordless JVM JMX agent so can // connect with jconsole and the likes to watch child memory, threads // and get thread dumps. // // <property> // <name>mapred.map.child.java.opts</name> // <value>-Xmx 512M -verbose:gc -Xloggc:/tmp/@[email protected] \ // -Dcom.sun.management.jmxremote.authenticate=false \ // -Dcom.sun.management.jmxremote.ssl=false \ // </value> // </property> // // <property> // <name>mapred.reduce.child.java.opts</name> // <value>-Xmx 1024M -verbose:gc -Xloggc:/tmp/@[email protected] \ // -Dcom.sun.management.jmxremote.authenticate=false \ // -Dcom.sun.management.jmxremote.ssl=false \ // </value> // </property> // String javaOpts = getChildJavaOpts(conf, task.isMapTask()); javaOpts = javaOpts.replace("@taskid@", attemptID.toString()); String [] javaOptsSplit = javaOpts.split(" "); for (int i = 0; i < javaOptsSplit.length; i++) { vargs.add(javaOptsSplit[i]); } Path childTmpDir = new Path(MRApps.crossPlatformifyMREnv(conf, Environment.PWD), YarnConfiguration.DEFAULT_CONTAINER_TEMP_DIR); vargs.add("-Djava.io.tmpdir=" + childTmpDir); // Setup the log4j prop long logSize = TaskLog.getTaskLogLength(conf); setupLog4jProperties(task, vargs, logSize, conf); if (conf.getProfileEnabled()) { if (conf.getProfileTaskRange(task.isMapTask() ).isIncluded(task.getPartition())) { final String profileParams = conf.get(task.isMapTask() ? MRJobConfig.TASK_MAP_PROFILE_PARAMS : MRJobConfig.TASK_REDUCE_PROFILE_PARAMS, conf.getProfileParams()); vargs.add(String.format(profileParams, getTaskLogFile(TaskLog.LogName.PROFILE))); } } // Add main class and its arguments vargs.add(YarnChild.class.getName()); // main of Child // pass TaskAttemptListener's address vargs.add(taskAttemptListenerAddr.getAddress().getHostAddress()); vargs.add(Integer.toString(taskAttemptListenerAddr.getPort())); vargs.add(attemptID.toString()); // pass task identifier // Finally add the jvmID vargs.add(String.valueOf(jvmID.getId())); vargs.add("1>" + getTaskLogFile(TaskLog.LogName.STDOUT)); vargs.add("2>" + getTaskLogFile(TaskLog.LogName.STDERR)); // Final commmand StringBuilder mergedCommand = new StringBuilder(); for (CharSequence str : vargs) { mergedCommand.append(str).append(" "); } Vector<String> vargsFinal = new Vector<String>(1); vargsFinal.add(mergedCommand.toString()); return vargsFinal; } }
{'content_hash': '3d2e03c64f68a5ac25cd8622bbb1ba48', 'timestamp': '', 'source': 'github', 'line_count': 230, 'max_line_length': 84, 'avg_line_length': 35.969565217391306, 'alnum_prop': 0.6557476127160643, 'repo_name': 'DislabNJU/Hadoop', 'id': 'c790c57648336d42be824064fb1285a9d2d90b63', 'size': '9063', 'binary': False, 'copies': '13', 'ref': 'refs/heads/master', 'path': 'hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapred/MapReduceChildJVM.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'AspectJ', 'bytes': '31146'}, {'name': 'Batchfile', 'bytes': '62129'}, {'name': 'C', 'bytes': '1360000'}, {'name': 'C++', 'bytes': '95352'}, {'name': 'CMake', 'bytes': '38954'}, {'name': 'CSS', 'bytes': '44021'}, {'name': 'Java', 'bytes': '47649954'}, {'name': 'JavaScript', 'bytes': '22681'}, {'name': 'Perl', 'bytes': '18992'}, {'name': 'Python', 'bytes': '11309'}, {'name': 'Shell', 'bytes': '182021'}, {'name': 'TLA', 'bytes': '14993'}, {'name': 'TeX', 'bytes': '19322'}, {'name': 'XSLT', 'bytes': '34239'}]}
function myRegStats = regressOnResiduals(depVar, designMatrix_1, designMatrix_2) % Performs a regression on residuals after performing a regression % % regressOnResiduals(depVar, designMatrix_1, designMatrix_2) % % input: % depVar -> dependent variable % % designMatrix_1 -> first regression to obtain residuals % % designMatrix_2 -> second regresion to obtain desired estimates % % output: % myRegstats, structure that contains these fields: % regression statistics output from regstats % coefficients confidence intervals % CPD % SRC % SRC confidence intervals % % See also regAnal % % But see: Freckleton 2002 J Anim Eco. On the misuse of residuals in % ecology: regression of residuals vs. multiple regression % % rbm 1.15 % Obtain residuals residuals = regstats(depVar(:),designMatrix_1,eye(size(designMatrix_1,2)),'r'); % regress on residuals myRegStats = regAnal(residuals.r, designMatrix_2);
{'content_hash': 'a241433a31fe46056e08fd53742c5688', 'timestamp': '', 'source': 'github', 'line_count': 32, 'max_line_length': 80, 'avg_line_length': 30.96875, 'alnum_prop': 0.7013118062563067, 'repo_name': 'rb476/Picasso', 'id': '7611393bab110e284ebca7a580bc10234c050abe', 'size': '991', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Statistics/regressOnResiduals.m', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'M', 'bytes': '671'}, {'name': 'MATLAB', 'bytes': '1949066'}]}
package org.apache.airavata.xbaya.ui.graph.amazon; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.geom.GeneralPath; import java.util.List; import org.apache.airavata.workflow.model.graph.Port; import org.apache.airavata.workflow.model.graph.amazon.TerminateInstanceNode; import org.apache.airavata.xbaya.graph.controller.NodeController; import org.apache.airavata.xbaya.ui.graph.NodeGUI; import org.apache.airavata.xbaya.ui.graph.PortGUI; import org.apache.airavata.xbaya.ui.utils.DrawUtils; public class TerminateInstanceNodeGUI extends NodeGUI { private TerminateInstanceNode node; private Polygon polygon; private GeneralPath generalPath; /** * Constructs a InstanceNodeGUI. * * @param node */ public TerminateInstanceNodeGUI(TerminateInstanceNode node) { super(node); this.node = node; this.polygon = new Polygon(); generalPath = new GeneralPath(); } /** * @see org.apache.airavata.xbaya.ui.graph.system.ConfigurableNodeGUI#calculatePositions(java.awt.Graphics) */ @Override protected void calculatePositions(Graphics g) { super.calculatePositions(g); calculatePositions(); setPortPositions(); } /** * @see org.apache.airavata.xbaya.ui.graph.NodeGUI#getBounds() */ @Override protected Rectangle getBounds() { return this.polygon.getBounds(); } /** * @see org.apache.airavata.xbaya.ui.graph.NodeGUI#isIn(java.awt.Point) */ @Override protected boolean isIn(Point point) { return this.polygon.contains(point); } /** * @see org.apache.airavata.xbaya.ui.graph.system.ConfigurableNodeGUI#paint(java.awt.Graphics2D) */ @Override protected void paint(Graphics2D g) { Point position = getPosition(); // Draws the body. if (this.dragged) { g.setColor(DRAGGED_BODY_COLOR); } else { g.setColor(this.bodyColor); } drawBody(g, generalPath, g.getColor()); // Draws the head. Polygon head = createHeader(position); drawHeader(g, DrawUtils.getRoundedShape(head), node.getName(), headColor); // Edge drawEdge(g, generalPath, EDGE_COLOR); // Paint all ports drawPorts(g, node); } private Polygon createHeader(Point position) { Polygon head = new Polygon(); head.addPoint(position.x, position.y); head.addPoint(position.x, position.y + this.headHeight); head.addPoint(position.x + this.dimension.width, position.y + this.headHeight); head.addPoint(position.x + this.dimension.width, position.y + this.headHeight / 2); return head; } /** * Sets up the position of ports */ @Override protected void setPortPositions() { // inputs List<? extends Port> inputPorts = this.node.getInputPorts(); for (int i = 0; i < inputPorts.size(); i++) { Port port = inputPorts.get(i); Point offset = new Point(PortGUI.DATA_PORT_SIZE / 2, this.headHeight + PORT_INITIAL_GAP + PORT_GAP * i); NodeController.getGUI(port).setOffset(offset); } // outputs List<? extends Port> outputPorts = this.node.getOutputPorts(); for (int i = 0; i < outputPorts.size(); i++) { Port port = outputPorts.get(i); // Use getBounds() instead of this.dimension because subclass might // overwrite getBounds() to have different shape. Point offset = new Point(this.getBounds().width - PortGUI.DATA_PORT_SIZE / 2, this.headHeight + PORT_INITIAL_GAP + PORT_GAP * i); NodeController.getGUI(port).setOffset(offset); } // control in port Port controlInPort = this.node.getControlInPort(); NodeController.getGUI(controlInPort).setOffset(new Point(0, 0)); } private void calculatePositions() { // Avoid instantiating a new polygon each time. this.polygon.reset(); Point position = getPosition(); this.polygon.addPoint(position.x, position.y); this.polygon.addPoint(position.x, position.y + this.dimension.height + this.headHeight / 2); this.polygon.addPoint(position.x + this.dimension.width, position.y + this.dimension.height + this.headHeight / 2); this.polygon.addPoint(position.x + this.dimension.width, position.y + this.headHeight / 2); DrawUtils.setupRoundedGeneralPath(polygon, generalPath); } }
{'content_hash': '1ca498858328c2d33b1a82c08524789b', 'timestamp': '', 'source': 'github', 'line_count': 141, 'max_line_length': 117, 'avg_line_length': 33.06382978723404, 'alnum_prop': 0.6458601458601458, 'repo_name': 'dogless/airavata', 'id': '74128da6513679d6c80bc9bdb1c3a4cb2253783a', 'size': '5475', 'binary': False, 'copies': '6', 'ref': 'refs/heads/master', 'path': 'modules/xbaya-gui/src/main/java/org/apache/airavata/xbaya/ui/graph/amazon/TerminateInstanceNodeGUI.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '6134'}, {'name': 'C', 'bytes': '55273'}, {'name': 'C++', 'bytes': '4933303'}, {'name': 'Java', 'bytes': '17045500'}, {'name': 'PHP', 'bytes': '2078481'}, {'name': 'Python', 'bytes': '182750'}, {'name': 'Shell', 'bytes': '68647'}, {'name': 'Thrift', 'bytes': '168157'}, {'name': 'XSLT', 'bytes': '51124'}]}
@implementation CPData //@synthesize objectContext = _objectContext; @synthesize appArray = _appArray; //@synthesize storeCoordinator = _storeCoordinator; //@synthesize store = _store; // //@synthesize managedObjectContext; //@synthesize persistentStoreCoordinator; //@synthesize persistentStore; -(id) init { self = [super init]; _appArray = [[NSMutableArray alloc] init]; // _objectContext = [[NSManagedObjectContext alloc] init]; // // _storeCoordinator = [[NSPersistentStoreCoordinator alloc] init]; // _store = [[NSPersistentStore alloc] initWithPersistentStoreCoordinator:_storeCoordinator configurationName:@"CPModel" URL:nil options:nil]; // // if (_storeCoordinator != nil) { // _objectContext = [[NSManagedObjectContext alloc] init]; // [_objectContext setPersistentStoreCoordinator:_storeCoordinator]; // [_objectContext setUndoManager:nil]; // } NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:self.persistentStorePath]) { // NSError *error = nil; // BOOL oldStoreRemovalSuccess = [[NSFileManager defaultManager] removeItemAtPath:self.persistentStorePath error:&error]; // NSAssert3(oldStoreRemovalSuccess, @"Unhandled error adding persistent store in %s at line %d: %@", __FUNCTION__, __LINE__, [error localizedDescription]); NSString *defaultStorePath = [[NSBundle mainBundle] pathForResource:@"CPModel" ofType:@"momd"]; if (defaultStorePath) { [fileManager copyItemAtPath:defaultStorePath toPath:self.persistentStorePath error:NULL]; } DLog(@"init - %@ - %d",defaultStorePath,[[NSFileManager defaultManager] fileExistsAtPath:defaultStorePath]); DLog(@"init - %d",[[NSFileManager defaultManager] fileExistsAtPath:self.persistentStorePath]); } if (!self.managedObjectContext) { // should trigger managedObjectContext generation. } if (!self.persistentStoreCoordinator) { // should trigger persistentStoreCoordinator generation. } return self; } - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { NSLog(@"persistentStoreCoordinator"); if (persistentStoreCoordinator == nil) { NSString *tmpStr = [NSString stringWithFormat:@"%@",[NSURL fileURLWithPath:self.persistentStorePath]]; tmpStr = [tmpStr substringWithRange:NSMakeRange(0,[tmpStr length] - 2)]; NSURL *storeUrl = [NSURL URLWithString:tmpStr]; DLog(@"self.persistentStorePath - %@ - %d",storeUrl,[[NSFileManager defaultManager] fileExistsAtPath:self.persistentStorePath]); persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[NSManagedObjectModel mergedModelFromBundles:nil]]; NSError *error = nil; NSPersistentStore *persistentStore = [persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]; if (error) { DLog(@"store error - %@",error); } NSAssert3(persistentStore != nil, @"Unhandled error adding persistent store in %s at line %d: %@", __FUNCTION__, __LINE__, [error localizedDescription]); persistentStore = nil; //hide the warning; } return persistentStoreCoordinator; } - (NSManagedObjectContext *)managedObjectContext { if (managedObjectContext == nil) { managedObjectContext = [[NSManagedObjectContext alloc] init]; [managedObjectContext setPersistentStoreCoordinator:self.persistentStoreCoordinator]; } return managedObjectContext; } - (NSString *)persistentStorePath { if (persistentStorePath == nil) { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths lastObject]; persistentStorePath = [documentsDirectory stringByAppendingPathComponent:@"CPModel.momd"]; DLog(@"persistentStorePath - %@ - %d",persistentStorePath,[[NSFileManager defaultManager] fileExistsAtPath:self.persistentStorePath]); } return persistentStorePath; } -(NSString *) getAppUUID { AppData *appdata = nil; int16_t recordNum = 1; NSError *error = nil; NSString *uuidStr = nil; // Check If We Have A Record NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"AppData" inManagedObjectContext:self.managedObjectContext]; [request setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"recordid" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; NSMutableArray *mutableFetchResults = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; appArray = mutableFetchResults; if ([appArray count] == 0) { // Create The UUID CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault); uuidStr = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuid); appdata = (AppData *)[NSEntityDescription insertNewObjectForEntityForName:@"AppData" inManagedObjectContext:self.managedObjectContext]; [appdata setRecordid:recordNum]; [appdata setUuid:uuidStr]; if (![self.managedObjectContext save:&error]) { // Handle the error. DLog(@"Save Error"); } else { DLog(@"Saved"); } } else { uuidStr = [[appArray objectAtIndex:0] valueForKey:@"uuid"]; } return uuidStr; } -(Issue *) getIssue : (NSString *) issueUUID { Issue *data = nil; NSError *error = nil; //Issue *issue = (Issue *)[NSEntityDescription insertNewObjectForEntityForName:@"Issue" inManagedObjectContext:self.managedObjectContext]; NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Issue" inManagedObjectContext:self.managedObjectContext]; [request setEntity:entity]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"uuid" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [request setSortDescriptors:sortDescriptors]; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"uuid = %@",issueUUID]; [request setPredicate:predicate]; NSMutableArray *issueList = [[self.managedObjectContext executeFetchRequest:request error:&error] mutableCopy]; if ([issueList count] == 0) { data = (Issue *)[NSEntityDescription insertNewObjectForEntityForName:@"Issue" inManagedObjectContext:self.managedObjectContext]; [data setUuid:issueUUID]; } else { data = [issueList objectAtIndex:0]; } return data; } @end
{'content_hash': '4dc35e6979412af20632906f63b83339', 'timestamp': '', 'source': 'github', 'line_count': 190, 'max_line_length': 175, 'avg_line_length': 34.50526315789474, 'alnum_prop': 0.75045759609518, 'repo_name': 'buzzcloudau/ConstructCloud', 'id': '7a48e150ab56e6a6f1ce264d47ece5e1865d1730', 'size': '6857', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'Classes/CPData.m', 'mode': '33261', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '200215'}, {'name': 'C++', 'bytes': '13749'}, {'name': 'Matlab', 'bytes': '1653'}, {'name': 'Objective-C', 'bytes': '984205'}, {'name': 'Python', 'bytes': '647'}, {'name': 'Ruby', 'bytes': '5588'}]}
package org.apache.spark.sql.execution.metric import java.text.NumberFormat import java.util.Locale import org.apache.spark.SparkContext import org.apache.spark.scheduler.AccumulableInfo import org.apache.spark.sql.execution.ui.SparkListenerDriverAccumUpdates import org.apache.spark.util.{AccumulatorContext, AccumulatorV2, Utils} /** * A metric used in a SQL query plan. This is implemented as an [[AccumulatorV2]]. Updates on * the executor side are automatically propagated and shown in the SQL UI through metrics. Updates * on the driver side must be explicitly posted using [[SQLMetrics.postDriverMetricUpdates()]]. */ class SQLMetric(val metricType: String, initValue: Long = 0L) extends AccumulatorV2[Long, Long] { // This is a workaround for SPARK-11013. // We may use -1 as initial value of the accumulator, if the accumulator is valid, we will // update it at the end of task and the value will be at least 0. Then we can filter out the -1 // values before calculate max, min, etc. private[this] var _value = initValue private var _zeroValue = initValue override def copy(): SQLMetric = { val newAcc = new SQLMetric(metricType, _value) newAcc._zeroValue = initValue newAcc } override def reset(): Unit = _value = _zeroValue override def merge(other: AccumulatorV2[Long, Long]): Unit = other match { case o: SQLMetric => _value += o.value case _ => throw new UnsupportedOperationException( s"Cannot merge ${this.getClass.getName} with ${other.getClass.getName}") } override def isZero(): Boolean = _value == _zeroValue override def add(v: Long): Unit = _value += v // We can set a double value to `SQLMetric` which stores only long value, if it is // average metrics. def set(v: Double): Unit = SQLMetrics.setDoubleForAverageMetrics(this, v) def set(v: Long): Unit = _value = v def +=(v: Long): Unit = _value += v override def value: Long = _value // Provide special identifier as metadata so we can tell that this is a `SQLMetric` later override def toInfo(update: Option[Any], value: Option[Any]): AccumulableInfo = { new AccumulableInfo( id, name, update, value, true, true, Some(AccumulatorContext.SQL_ACCUM_IDENTIFIER)) } } object SQLMetrics { private val SUM_METRIC = "sum" private val SIZE_METRIC = "size" private val TIMING_METRIC = "timing" private val AVERAGE_METRIC = "average" private val baseForAvgMetric: Int = 10 /** * Converts a double value to long value by multiplying a base integer, so we can store it in * `SQLMetrics`. It only works for average metrics. When showing the metrics on UI, we restore * it back to a double value up to the decimal places bound by the base integer. */ private[sql] def setDoubleForAverageMetrics(metric: SQLMetric, v: Double): Unit = { assert(metric.metricType == AVERAGE_METRIC, s"Can't set a double to a metric of metrics type: ${metric.metricType}") metric.set((v * baseForAvgMetric).toLong) } def createMetric(sc: SparkContext, name: String): SQLMetric = { val acc = new SQLMetric(SUM_METRIC) acc.register(sc, name = Some(name), countFailedValues = false) acc } /** * Create a metric to report the size information (including total, min, med, max) like data size, * spill size, etc. */ def createSizeMetric(sc: SparkContext, name: String): SQLMetric = { // The final result of this metric in physical operator UI may looks like: // data size total (min, med, max): // 100GB (100MB, 1GB, 10GB) val acc = new SQLMetric(SIZE_METRIC, -1) acc.register(sc, name = Some(s"$name total (min, med, max)"), countFailedValues = false) acc } def createTimingMetric(sc: SparkContext, name: String): SQLMetric = { // The final result of this metric in physical operator UI may looks like: // duration(min, med, max): // 5s (800ms, 1s, 2s) val acc = new SQLMetric(TIMING_METRIC, -1) acc.register(sc, name = Some(s"$name total (min, med, max)"), countFailedValues = false) acc } /** * Create a metric to report the average information (including min, med, max) like * avg hash probe. As average metrics are double values, this kind of metrics should be * only set with `SQLMetric.set` method instead of other methods like `SQLMetric.add`. * The initial values (zeros) of this metrics will be excluded after. */ def createAverageMetric(sc: SparkContext, name: String): SQLMetric = { // The final result of this metric in physical operator UI may looks like: // probe avg (min, med, max): // (1.2, 2.2, 6.3) val acc = new SQLMetric(AVERAGE_METRIC) acc.register(sc, name = Some(s"$name (min, med, max)"), countFailedValues = false) acc } /** * A function that defines how we aggregate the final accumulator results among all tasks, * and represent it in string for a SQL physical operator. */ def stringValue(metricsType: String, values: Seq[Long]): String = { if (metricsType == SUM_METRIC) { val numberFormat = NumberFormat.getIntegerInstance(Locale.US) numberFormat.format(values.sum) } else if (metricsType == AVERAGE_METRIC) { val numberFormat = NumberFormat.getNumberInstance(Locale.US) val validValues = values.filter(_ > 0) val Seq(min, med, max) = { val metric = if (validValues.isEmpty) { Seq.fill(3)(0L) } else { val sorted = validValues.sorted Seq(sorted(0), sorted(validValues.length / 2), sorted(validValues.length - 1)) } metric.map(v => numberFormat.format(v.toDouble / baseForAvgMetric)) } s"\n($min, $med, $max)" } else { val strFormat: Long => String = if (metricsType == SIZE_METRIC) { Utils.bytesToString } else if (metricsType == TIMING_METRIC) { Utils.msDurationToString } else { throw new IllegalStateException("unexpected metrics type: " + metricsType) } val validValues = values.filter(_ >= 0) val Seq(sum, min, med, max) = { val metric = if (validValues.isEmpty) { Seq.fill(4)(0L) } else { val sorted = validValues.sorted Seq(sorted.sum, sorted(0), sorted(validValues.length / 2), sorted(validValues.length - 1)) } metric.map(strFormat) } s"\n$sum ($min, $med, $max)" } } /** * Updates metrics based on the driver side value. This is useful for certain metrics that * are only updated on the driver, e.g. subquery execution time, or number of files. */ def postDriverMetricUpdates( sc: SparkContext, executionId: String, metrics: Seq[SQLMetric]): Unit = { // There are some cases we don't care about the metrics and call `SparkPlan.doExecute` // directly without setting an execution id. We should be tolerant to it. if (executionId != null) { sc.listenerBus.post( SparkListenerDriverAccumUpdates(executionId.toLong, metrics.map(m => m.id -> m.value))) } } }
{'content_hash': '1b98c89fd85914411bd4f43b4c493ec1', 'timestamp': '', 'source': 'github', 'line_count': 182, 'max_line_length': 100, 'avg_line_length': 38.63186813186813, 'alnum_prop': 0.675579576162708, 'repo_name': 'VigneshMohan1/spark-branch-2.3', 'id': 'b4653c1b564f361fea05896875790e01507388dd', 'size': '7816', 'binary': False, 'copies': '8', 'ref': 'refs/heads/master', 'path': 'sql/core/src/main/scala/org/apache/spark/sql/execution/metric/SQLMetrics.scala', 'mode': '33261', 'license': 'apache-2.0', 'language': [{'name': 'ANTLR', 'bytes': '33141'}, {'name': 'Batchfile', 'bytes': '57399'}, {'name': 'C', 'bytes': '1493'}, {'name': 'CSS', 'bytes': '49141'}, {'name': 'HTML', 'bytes': '70317'}, {'name': 'Java', 'bytes': '3907367'}, {'name': 'JavaScript', 'bytes': '282426'}, {'name': 'Makefile', 'bytes': '7774'}, {'name': 'PLpgSQL', 'bytes': '17576'}, {'name': 'PowerShell', 'bytes': '3751'}, {'name': 'Python', 'bytes': '2247029'}, {'name': 'R', 'bytes': '1064003'}, {'name': 'Roff', 'bytes': '57264'}, {'name': 'SQLPL', 'bytes': '12466'}, {'name': 'Scala', 'bytes': '23016780'}, {'name': 'Shell', 'bytes': '203542'}, {'name': 'Thrift', 'bytes': '33605'}]}
brew tap homebrew/science brew install git brew install cmake brew install boost brew install libccd
{'content_hash': '7e59822aa8e835ad47ec2a92380f2957', 'timestamp': '', 'source': 'github', 'line_count': 6, 'max_line_length': 25, 'avg_line_length': 17.0, 'alnum_prop': 0.8333333333333334, 'repo_name': 'uschwes/fcl', 'id': '1b1a6107076f87c7ad271f65fee59056c1d55ccd', 'size': '102', 'binary': False, 'copies': '4', 'ref': 'refs/heads/master', 'path': 'ci/install_osx.sh', 'mode': '33261', 'license': 'bsd-3-clause', 'language': [{'name': 'C', 'bytes': '7945'}, {'name': 'C++', 'bytes': '2168935'}, {'name': 'CMake', 'bytes': '12704'}, {'name': 'Shell', 'bytes': '691'}]}
package org.develnext.jphp.ext.libgdx.classes.graphics; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Sprite; import org.develnext.jphp.ext.libgdx.LibGDXExtension; import php.runtime.annotation.Reflection; import php.runtime.env.Environment; import php.runtime.lang.BaseWrapper; import php.runtime.reflection.ClassEntity; import static php.runtime.annotation.Reflection.Name; import static php.runtime.annotation.Reflection.Signature; import static php.runtime.annotation.Reflection.WrapInterface; @Name(LibGDXExtension.NAMESPACE + "graphics\\Sprite") @WrapInterface(value = Sprite.class, skipConflicts = true) public class WrapSprite extends BaseWrapper<Sprite> { public WrapSprite(Environment env, Sprite wrappedObject) { super(env, wrappedObject); } public WrapSprite(Environment env, ClassEntity clazz) { super(env, clazz); } @Signature public void __construct() { __wrappedObject = new Sprite(); } @Signature public void __construct(Texture texture) { __wrappedObject = new Sprite(texture); } @Signature public void __construct(Texture texture, int width, int height) { __wrappedObject = new Sprite(texture, width, height); } @Signature public void __construct(Texture texture, int width, int height, int x, int y) { __wrappedObject = new Sprite(texture, x, y, width, height); } }
{'content_hash': '9234a3f40d41f65bd1339b8e124f0be9', 'timestamp': '', 'source': 'github', 'line_count': 46, 'max_line_length': 83, 'avg_line_length': 31.304347826086957, 'alnum_prop': 0.7236111111111111, 'repo_name': 'livingvirus/jphp', 'id': '5fb76128e6c1cf2ec6b2bac662c05af9544dc02e', 'size': '1440', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'jphp-gdx-ext/src/main/java/org/develnext/jphp/ext/libgdx/classes/graphics/WrapSprite.java', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Batchfile', 'bytes': '112'}, {'name': 'C++', 'bytes': '510'}, {'name': 'Groovy', 'bytes': '14969'}, {'name': 'HTML', 'bytes': '4169'}, {'name': 'Java', 'bytes': '3522396'}, {'name': 'PHP', 'bytes': '1129715'}, {'name': 'Shell', 'bytes': '441'}, {'name': 'SourcePawn', 'bytes': '90'}]}
<!--* freshness: { owner: 'hzeller' reviewed: '2020-10-04' } *--> At the heart of language-tooling libraries and applications lie various structural representations of text, and the functions that operate on them. This directory contains _language-agnostic_ data structures like: * Tokens: annotated substrings of a body of text, often what a lexer produces. * Token streams: iterable representations of lexer output, including filtered views thereof. * Syntax trees: represent how parsers understand and organize code hierarchically. ## Key Concepts `absl::string_view`s do not just represent text, but they represent **position** within a larger body of text, by virtue of comparing their `begin` and `end` bounds. This concept is leveraged heavily to avoid unnecessary string copying. A base `string_view` that represents a body of text and serve as the basis for interchanging between substring-views and byte-offsets relative to the start of the base.
{'content_hash': '78b8db29cefef40150645b48fdd333ca', 'timestamp': '', 'source': 'github', 'line_count': 22, 'max_line_length': 80, 'avg_line_length': 44.68181818181818, 'alnum_prop': 0.768056968463886, 'repo_name': 'chipsalliance/verible', 'id': 'fa6df1777f5704017bbc694fce0ab3bc64e5fe6f', 'size': '1027', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'common/text/README.md', 'mode': '33188', 'license': 'apache-2.0', 'language': [{'name': 'Awk', 'bytes': '3459'}, {'name': 'C++', 'bytes': '6853412'}, {'name': 'Dockerfile', 'bytes': '567'}, {'name': 'JavaScript', 'bytes': '1512'}, {'name': 'Lex', 'bytes': '58612'}, {'name': 'Makefile', 'bytes': '166'}, {'name': 'Nix', 'bytes': '558'}, {'name': 'Python', 'bytes': '44099'}, {'name': 'Shell', 'bytes': '169683'}, {'name': 'Starlark', 'bytes': '257597'}, {'name': 'TypeScript', 'bytes': '1711'}, {'name': 'Yacc', 'bytes': '282973'}]}
<!DOCTYPE html> <!--[if IE]><![endif]--> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title>Class FileUploadParameter </title> <meta name="viewport" content="width=device-width"> <meta name="title" content="Class FileUploadParameter "> <meta name="generator" content="docfx 2.33.1.0"> <link rel="shortcut icon" href="../favicon.ico"> <link rel="stylesheet" href="../styles/docfx.vendor.css"> <link rel="stylesheet" href="../styles/docfx.css"> <link rel="stylesheet" href="../styles/main.css"> <meta property="docfx:navrel" content="../toc.html"> <meta property="docfx:tocrel" content="toc.html"> </head> <body data-spy="scroll" data-target="#affix"> <div id="wrapper"> <header> <nav id="autocollapse" class="navbar navbar-inverse ng-scope" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../index.html"> <img id="logo" class="svg" src="../logo.svg" alt=""> </a> </div> <div class="collapse navbar-collapse" id="navbar"> <form class="navbar-form navbar-right" role="search" id="search"> <div class="form-group"> <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off"> </div> </form> </div> </div> </nav> <div class="subnav navbar navbar-default"> <div class="container hide-when-search" id="breadcrumb"> <ul class="breadcrumb"> <li></li> </ul> </div> </div> </header> <div role="main" class="container body-content hide-when-search"> <div class="sidenav hide-when-search"> <a class="btn toc-toggle collapse" data-toggle="collapse" href="#sidetoggle" aria-expanded="false" aria-controls="sidetoggle">Show / Hide Table of Contents</a> <div class="sidetoggle collapse" id="sidetoggle"> <div id="sidetoc"></div> </div> </div> <div class="article row grid-right"> <div class="col-md-10"> <article class="content wrap" id="_content" data-uid="Auth0.Core.Http.FileUploadParameter"> <h1 id="Auth0_Core_Http_FileUploadParameter" data-uid="Auth0.Core.Http.FileUploadParameter" class="text-break">Class FileUploadParameter </h1> <div class="markdown level0 summary"></div> <div class="markdown level0 conceptual"></div> <div class="inheritance"> <h5>Inheritance</h5> <div class="level0"><span class="xref">System.Object</span></div> <div class="level1"><span class="xref">FileUploadParameter</span></div> </div> <div class="inheritedMembers"> <h5>Inherited Members</h5> <div> <span class="xref">System.Object.ToString()</span> </div> <div> <span class="xref">System.Object.Equals(System.Object)</span> </div> <div> <span class="xref">System.Object.Equals(System.Object, System.Object)</span> </div> <div> <span class="xref">System.Object.ReferenceEquals(System.Object, System.Object)</span> </div> <div> <span class="xref">System.Object.GetHashCode()</span> </div> <div> <span class="xref">System.Object.GetType()</span> </div> <div> <span class="xref">System.Object.MemberwiseClone()</span> </div> </div> <h6><strong>Namespace</strong>: <a class="xref" href="Auth0.Core.Http.html">Auth0.Core.Http</a></h6> <h6><strong>Assembly</strong>: cs.temp.dll.dll</h6> <h5 id="Auth0_Core_Http_FileUploadParameter_syntax">Syntax</h5> <div class="codewrapper"> <pre><code class="lang-csharp hljs">public class FileUploadParameter</code></pre> </div> </article> </div> <div class="hidden-sm col-md-2" role="complementary"> <div class="sideaffix"> <div class="contribution"> <ul class="nav"> </ul> </div> <nav class="bs-docs-sidebar hidden-print hidden-xs hidden-sm affix" id="affix"> <!-- <p><a class="back-to-top" href="#top">Back to top</a><p> --> </nav> </div> </div> </div> </div> <footer> <div class="grad-bottom"></div> <div class="footer"> <div class="container"> <span class="pull-right"> <a href="#top">Back to top</a> </span> <span>Generated by <strong>DocFX</strong></span> </div> </div> </footer> </div> <script type="text/javascript" src="../styles/docfx.vendor.js"></script> <script type="text/javascript" src="../styles/docfx.js"></script> <script type="text/javascript" src="../styles/main.js"></script> </body> </html>
{'content_hash': 'c2e4c2848340896dab4ca24bed0c6bd4', 'timestamp': '', 'source': 'github', 'line_count': 148, 'max_line_length': 169, 'avg_line_length': 36.42567567567568, 'alnum_prop': 0.5577814876646262, 'repo_name': 'jerriep/auth0.net', 'id': '984b484313fe09d6895271c2ce1257ef599c01c2', 'size': '5393', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'docs/api/Auth0.Core.Http.FileUploadParameter.html', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '496948'}, {'name': 'HTML', 'bytes': '82866'}, {'name': 'PowerShell', 'bytes': '7434'}, {'name': 'Shell', 'bytes': '2936'}]}
.class public Landroid/media/ThumbnailUtils; .super Ljava/lang/Object; .source "ThumbnailUtils.java" # annotations .annotation system Ldalvik/annotation/MemberClasses; value = { Landroid/media/ThumbnailUtils$1;, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap; } .end annotation # static fields .field private static final MAX_NUM_PIXELS_MICRO_THUMBNAIL:I = 0x4000 .field private static final MAX_NUM_PIXELS_THUMBNAIL:I = 0x30000 .field private static final OPTIONS_NONE:I = 0x0 .field public static final OPTIONS_RECYCLE_INPUT:I = 0x2 .field private static final OPTIONS_SCALE_UP:I = 0x1 .field private static final TAG:Ljava/lang/String; = "ThumbnailUtils" .field public static final TARGET_SIZE_MICRO_THUMBNAIL:I = 0x60 .field public static final TARGET_SIZE_MINI_THUMBNAIL:I = 0x140 .field private static final UNCONSTRAINED:I = -0x1 # direct methods .method public constructor <init>()V .locals 0 .prologue .line 46 invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V .line 466 return-void .end method .method private static closeSilently(Landroid/os/ParcelFileDescriptor;)V .locals 1 .parameter "c" .prologue .line 342 if-nez p0, :cond_0 .line 348 :goto_0 return-void .line 344 :cond_0 :try_start_0 invoke-virtual {p0}, Landroid/os/ParcelFileDescriptor;->close()V :try_end_0 .catch Ljava/lang/Throwable; {:try_start_0 .. :try_end_0} :catch_0 goto :goto_0 .line 345 :catch_0 move-exception v0 goto :goto_0 .end method .method private static computeInitialSampleSize(Landroid/graphics/BitmapFactory$Options;II)I .locals 12 .parameter "options" .parameter "minSideLength" .parameter "maxNumOfPixels" .prologue const/4 v6, 0x1 const/4 v11, -0x1 .line 276 iget v7, p0, Landroid/graphics/BitmapFactory$Options;->outWidth:I int-to-double v4, v7 .line 277 .local v4, w:D iget v7, p0, Landroid/graphics/BitmapFactory$Options;->outHeight:I int-to-double v0, v7 .line 279 .local v0, h:D if-ne p2, v11, :cond_1 move v2, v6 .line 281 .local v2, lowerBound:I :goto_0 if-ne p1, v11, :cond_2 const/16 v3, 0x80 .line 285 .local v3, upperBound:I :goto_1 if-ge v3, v2, :cond_3 .line 296 .end local v2 #lowerBound:I :cond_0 :goto_2 return v2 .line 279 .end local v3 #upperBound:I :cond_1 mul-double v7, v4, v0 int-to-double v9, p2 div-double/2addr v7, v9 invoke-static {v7, v8}, Ljava/lang/Math;->sqrt(D)D move-result-wide v7 invoke-static {v7, v8}, Ljava/lang/Math;->ceil(D)D move-result-wide v7 double-to-int v2, v7 goto :goto_0 .line 281 .restart local v2 #lowerBound:I :cond_2 int-to-double v7, p1 div-double v7, v4, v7 invoke-static {v7, v8}, Ljava/lang/Math;->floor(D)D move-result-wide v7 int-to-double v9, p1 div-double v9, v0, v9 invoke-static {v9, v10}, Ljava/lang/Math;->floor(D)D move-result-wide v9 invoke-static {v7, v8, v9, v10}, Ljava/lang/Math;->min(DD)D move-result-wide v7 double-to-int v3, v7 goto :goto_1 .line 290 .restart local v3 #upperBound:I :cond_3 if-ne p2, v11, :cond_4 if-ne p1, v11, :cond_4 move v2, v6 .line 292 goto :goto_2 .line 293 :cond_4 if-eq p1, v11, :cond_0 move v2, v3 .line 296 goto :goto_2 .end method .method private static computeSampleSize(Landroid/graphics/BitmapFactory$Options;II)I .locals 3 .parameter "options" .parameter "minSideLength" .parameter "maxNumOfPixels" .prologue .line 258 invoke-static {p0, p1, p2}, Landroid/media/ThumbnailUtils;->computeInitialSampleSize(Landroid/graphics/BitmapFactory$Options;II)I move-result v0 .line 262 .local v0, initialSize:I const/16 v2, 0x8 if-gt v0, v2, :cond_0 .line 263 const/4 v1, 0x1 .line 264 .local v1, roundedSize:I :goto_0 if-ge v1, v0, :cond_1 .line 265 shl-int/lit8 v1, v1, 0x1 goto :goto_0 .line 268 .end local v1 #roundedSize:I :cond_0 add-int/lit8 v2, v0, 0x7 div-int/lit8 v2, v2, 0x8 mul-int/lit8 v1, v2, 0x8 .line 271 .restart local v1 #roundedSize:I :cond_1 return v1 .end method .method public static createImageThumbnail(Ljava/lang/String;I)Landroid/graphics/Bitmap; .locals 16 .parameter "filePath" .parameter "kind" .prologue .line 91 const/4 v13, 0x1 move/from16 v0, p1 if-ne v0, v13, :cond_3 const/4 v12, 0x1 .line 92 .local v12, wantMini:Z :goto_0 if-eqz v12, :cond_4 const/16 v11, 0x140 .line 95 .local v11, targetSize:I :goto_1 if-eqz v12, :cond_5 const/high16 v5, 0x3 .line 98 .local v5, maxPixels:I :goto_2 new-instance v8, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap; const/4 v13, 0x0 invoke-direct {v8, v13}, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap;-><init>(Landroid/media/ThumbnailUtils$1;)V .line 99 .local v8, sizedThumbnailBitmap:Landroid/media/ThumbnailUtils$SizedThumbnailBitmap; const/4 v1, 0x0 .line 100 .local v1, bitmap:Landroid/graphics/Bitmap; invoke-static/range {p0 .. p0}, Landroid/media/MediaFile;->getFileType(Ljava/lang/String;)Landroid/media/MediaFile$MediaFileType; move-result-object v4 .line 101 .local v4, fileType:Landroid/media/MediaFile$MediaFileType; if-eqz v4, :cond_0 iget v13, v4, Landroid/media/MediaFile$MediaFileType;->fileType:I const/16 v14, 0x1f if-ne v13, v14, :cond_0 .line 102 move-object/from16 v0, p0 invoke-static {v0, v11, v5, v8}, Landroid/media/ThumbnailUtils;->createThumbnailFromEXIF(Ljava/lang/String;IILandroid/media/ThumbnailUtils$SizedThumbnailBitmap;)V .line 103 iget-object v1, v8, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap;->mBitmap:Landroid/graphics/Bitmap; .line 106 :cond_0 if-nez v1, :cond_7 .line 107 const/4 v9, 0x0 .line 109 .local v9, stream:Ljava/io/FileInputStream; :try_start_0 new-instance v10, Ljava/io/FileInputStream; move-object/from16 v0, p0 invoke-direct {v10, v0}, Ljava/io/FileInputStream;-><init>(Ljava/lang/String;)V :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_2 .catch Ljava/lang/OutOfMemoryError; {:try_start_0 .. :try_end_0} :catch_4 .line 110 .end local v9 #stream:Ljava/io/FileInputStream; .local v10, stream:Ljava/io/FileInputStream; :try_start_1 invoke-virtual {v10}, Ljava/io/FileInputStream;->getFD()Ljava/io/FileDescriptor; move-result-object v3 .line 111 .local v3, fd:Ljava/io/FileDescriptor; new-instance v7, Landroid/graphics/BitmapFactory$Options; invoke-direct {v7}, Landroid/graphics/BitmapFactory$Options;-><init>()V .line 112 .local v7, options:Landroid/graphics/BitmapFactory$Options; const/4 v13, 0x1 iput v13, v7, Landroid/graphics/BitmapFactory$Options;->inSampleSize:I .line 113 const/4 v13, 0x1 iput-boolean v13, v7, Landroid/graphics/BitmapFactory$Options;->inJustDecodeBounds:Z .line 114 const/4 v13, 0x0 invoke-static {v3, v13, v7}, Landroid/graphics/BitmapFactory;->decodeFileDescriptor(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap; .line 115 iget-boolean v13, v7, Landroid/graphics/BitmapFactory$Options;->mCancel:Z if-nez v13, :cond_1 iget v13, v7, Landroid/graphics/BitmapFactory$Options;->outWidth:I const/4 v14, -0x1 if-eq v13, v14, :cond_1 iget v13, v7, Landroid/graphics/BitmapFactory$Options;->outHeight:I :try_end_1 .catchall {:try_start_1 .. :try_end_1} :catchall_1 .catch Ljava/io/IOException; {:try_start_1 .. :try_end_1} :catch_8 .catch Ljava/lang/OutOfMemoryError; {:try_start_1 .. :try_end_1} :catch_7 const/4 v14, -0x1 if-ne v13, v14, :cond_6 .line 117 :cond_1 const/4 v13, 0x0 .line 132 if-eqz v10, :cond_2 .line 133 :try_start_2 invoke-virtual {v10}, Ljava/io/FileInputStream;->close()V :try_end_2 .catch Ljava/io/IOException; {:try_start_2 .. :try_end_2} :catch_0 .line 148 .end local v3 #fd:Ljava/io/FileDescriptor; .end local v7 #options:Landroid/graphics/BitmapFactory$Options; .end local v10 #stream:Ljava/io/FileInputStream; :cond_2 :goto_3 return-object v13 .line 91 .end local v1 #bitmap:Landroid/graphics/Bitmap; .end local v4 #fileType:Landroid/media/MediaFile$MediaFileType; .end local v5 #maxPixels:I .end local v8 #sizedThumbnailBitmap:Landroid/media/ThumbnailUtils$SizedThumbnailBitmap; .end local v11 #targetSize:I .end local v12 #wantMini:Z :cond_3 const/4 v12, 0x0 goto :goto_0 .line 92 .restart local v12 #wantMini:Z :cond_4 const/16 v11, 0x60 goto :goto_1 .line 95 .restart local v11 #targetSize:I :cond_5 const/16 v5, 0x4000 goto :goto_2 .line 135 .restart local v1 #bitmap:Landroid/graphics/Bitmap; .restart local v3 #fd:Ljava/io/FileDescriptor; .restart local v4 #fileType:Landroid/media/MediaFile$MediaFileType; .restart local v5 #maxPixels:I .restart local v7 #options:Landroid/graphics/BitmapFactory$Options; .restart local v8 #sizedThumbnailBitmap:Landroid/media/ThumbnailUtils$SizedThumbnailBitmap; .restart local v10 #stream:Ljava/io/FileInputStream; :catch_0 move-exception v2 .line 136 .local v2, ex:Ljava/io/IOException; const-string v14, "ThumbnailUtils" const-string v15, "" invoke-static {v14, v15, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I goto :goto_3 .line 119 .end local v2 #ex:Ljava/io/IOException; :cond_6 :try_start_3 invoke-static {v7, v11, v5}, Landroid/media/ThumbnailUtils;->computeSampleSize(Landroid/graphics/BitmapFactory$Options;II)I move-result v13 iput v13, v7, Landroid/graphics/BitmapFactory$Options;->inSampleSize:I .line 121 const/4 v13, 0x0 iput-boolean v13, v7, Landroid/graphics/BitmapFactory$Options;->inJustDecodeBounds:Z .line 123 const/4 v13, 0x0 iput-boolean v13, v7, Landroid/graphics/BitmapFactory$Options;->inDither:Z .line 124 sget-object v13, Landroid/graphics/Bitmap$Config;->ARGB_8888:Landroid/graphics/Bitmap$Config; iput-object v13, v7, Landroid/graphics/BitmapFactory$Options;->inPreferredConfig:Landroid/graphics/Bitmap$Config; .line 125 const/4 v13, 0x0 invoke-static {v3, v13, v7}, Landroid/graphics/BitmapFactory;->decodeFileDescriptor(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap; :try_end_3 .catchall {:try_start_3 .. :try_end_3} :catchall_1 .catch Ljava/io/IOException; {:try_start_3 .. :try_end_3} :catch_8 .catch Ljava/lang/OutOfMemoryError; {:try_start_3 .. :try_end_3} :catch_7 move-result-object v1 .line 132 if-eqz v10, :cond_7 .line 133 :try_start_4 invoke-virtual {v10}, Ljava/io/FileInputStream;->close()V :try_end_4 .catch Ljava/io/IOException; {:try_start_4 .. :try_end_4} :catch_1 .line 142 .end local v3 #fd:Ljava/io/FileDescriptor; .end local v7 #options:Landroid/graphics/BitmapFactory$Options; .end local v10 #stream:Ljava/io/FileInputStream; :cond_7 :goto_4 const/4 v13, 0x3 move/from16 v0, p1 if-ne v0, v13, :cond_8 .line 144 const/16 v13, 0x60 const/16 v14, 0x60 const/4 v15, 0x2 invoke-static {v1, v13, v14, v15}, Landroid/media/ThumbnailUtils;->extractThumbnail(Landroid/graphics/Bitmap;III)Landroid/graphics/Bitmap; move-result-object v1 :cond_8 move-object v13, v1 .line 148 goto :goto_3 .line 135 .restart local v3 #fd:Ljava/io/FileDescriptor; .restart local v7 #options:Landroid/graphics/BitmapFactory$Options; .restart local v10 #stream:Ljava/io/FileInputStream; :catch_1 move-exception v2 .line 136 .restart local v2 #ex:Ljava/io/IOException; const-string v13, "ThumbnailUtils" const-string v14, "" invoke-static {v13, v14, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I goto :goto_4 .line 126 .end local v2 #ex:Ljava/io/IOException; .end local v3 #fd:Ljava/io/FileDescriptor; .end local v7 #options:Landroid/graphics/BitmapFactory$Options; .end local v10 #stream:Ljava/io/FileInputStream; .restart local v9 #stream:Ljava/io/FileInputStream; :catch_2 move-exception v2 .line 127 .restart local v2 #ex:Ljava/io/IOException; :goto_5 :try_start_5 const-string v13, "ThumbnailUtils" const-string v14, "" invoke-static {v13, v14, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I :try_end_5 .catchall {:try_start_5 .. :try_end_5} :catchall_0 .line 132 if-eqz v9, :cond_7 .line 133 :try_start_6 invoke-virtual {v9}, Ljava/io/FileInputStream;->close()V :try_end_6 .catch Ljava/io/IOException; {:try_start_6 .. :try_end_6} :catch_3 goto :goto_4 .line 135 :catch_3 move-exception v2 .line 136 const-string v13, "ThumbnailUtils" const-string v14, "" invoke-static {v13, v14, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I goto :goto_4 .line 128 .end local v2 #ex:Ljava/io/IOException; :catch_4 move-exception v6 .line 129 .local v6, oom:Ljava/lang/OutOfMemoryError; :goto_6 :try_start_7 const-string v13, "ThumbnailUtils" new-instance v14, Ljava/lang/StringBuilder; invoke-direct {v14}, Ljava/lang/StringBuilder;-><init>()V const-string v15, "Unable to decode file " invoke-virtual {v14, v15}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v14 move-object/from16 v0, p0 invoke-virtual {v14, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v14 const-string v15, ". OutOfMemoryError." invoke-virtual {v14, v15}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; move-result-object v14 invoke-virtual {v14}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; move-result-object v14 invoke-static {v13, v14, v6}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I :try_end_7 .catchall {:try_start_7 .. :try_end_7} :catchall_0 .line 132 if-eqz v9, :cond_7 .line 133 :try_start_8 invoke-virtual {v9}, Ljava/io/FileInputStream;->close()V :try_end_8 .catch Ljava/io/IOException; {:try_start_8 .. :try_end_8} :catch_5 goto :goto_4 .line 135 :catch_5 move-exception v2 .line 136 .restart local v2 #ex:Ljava/io/IOException; const-string v13, "ThumbnailUtils" const-string v14, "" invoke-static {v13, v14, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I goto :goto_4 .line 131 .end local v2 #ex:Ljava/io/IOException; .end local v6 #oom:Ljava/lang/OutOfMemoryError; :catchall_0 move-exception v13 .line 132 :goto_7 if-eqz v9, :cond_9 .line 133 :try_start_9 invoke-virtual {v9}, Ljava/io/FileInputStream;->close()V :try_end_9 .catch Ljava/io/IOException; {:try_start_9 .. :try_end_9} :catch_6 .line 137 :cond_9 :goto_8 throw v13 .line 135 :catch_6 move-exception v2 .line 136 .restart local v2 #ex:Ljava/io/IOException; const-string v14, "ThumbnailUtils" const-string v15, "" invoke-static {v14, v15, v2}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I goto :goto_8 .line 131 .end local v2 #ex:Ljava/io/IOException; .end local v9 #stream:Ljava/io/FileInputStream; .restart local v10 #stream:Ljava/io/FileInputStream; :catchall_1 move-exception v13 move-object v9, v10 .end local v10 #stream:Ljava/io/FileInputStream; .restart local v9 #stream:Ljava/io/FileInputStream; goto :goto_7 .line 128 .end local v9 #stream:Ljava/io/FileInputStream; .restart local v10 #stream:Ljava/io/FileInputStream; :catch_7 move-exception v6 move-object v9, v10 .end local v10 #stream:Ljava/io/FileInputStream; .restart local v9 #stream:Ljava/io/FileInputStream; goto :goto_6 .line 126 .end local v9 #stream:Ljava/io/FileInputStream; .restart local v10 #stream:Ljava/io/FileInputStream; :catch_8 move-exception v2 move-object v9, v10 .end local v10 #stream:Ljava/io/FileInputStream; .restart local v9 #stream:Ljava/io/FileInputStream; goto :goto_5 .end method .method private static createThumbnailFromEXIF(Ljava/lang/String;IILandroid/media/ThumbnailUtils$SizedThumbnailBitmap;)V .locals 12 .parameter "filePath" .parameter "targetSize" .parameter "maxPixels" .parameter "sizedThumbBitmap" .prologue .line 480 if-nez p0, :cond_1 .line 526 :cond_0 :goto_0 return-void .line 482 :cond_1 const/4 v1, 0x0 .line 483 .local v1, exif:Landroid/media/ExifInterface; const/4 v8, 0x0 .line 485 .local v8, thumbData:[B :try_start_0 new-instance v2, Landroid/media/ExifInterface; invoke-direct {v2, p0}, Landroid/media/ExifInterface;-><init>(Ljava/lang/String;)V :try_end_0 .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_0 .line 486 .end local v1 #exif:Landroid/media/ExifInterface; .local v2, exif:Landroid/media/ExifInterface; :try_start_1 invoke-virtual {v2}, Landroid/media/ExifInterface;->getThumbnail()[B :try_end_1 .catch Ljava/io/IOException; {:try_start_1 .. :try_end_1} :catch_1 move-result-object v8 move-object v1, v2 .line 491 .end local v2 #exif:Landroid/media/ExifInterface; .restart local v1 #exif:Landroid/media/ExifInterface; :goto_1 new-instance v5, Landroid/graphics/BitmapFactory$Options; invoke-direct {v5}, Landroid/graphics/BitmapFactory$Options;-><init>()V .line 492 .local v5, fullOptions:Landroid/graphics/BitmapFactory$Options; new-instance v3, Landroid/graphics/BitmapFactory$Options; invoke-direct {v3}, Landroid/graphics/BitmapFactory$Options;-><init>()V .line 493 .local v3, exifOptions:Landroid/graphics/BitmapFactory$Options; const/4 v4, 0x0 .line 494 .local v4, exifThumbWidth:I const/4 v6, 0x0 .line 497 .local v6, fullThumbWidth:I if-eqz v8, :cond_2 .line 498 const/4 v10, 0x1 iput-boolean v10, v3, Landroid/graphics/BitmapFactory$Options;->inJustDecodeBounds:Z .line 499 const/4 v10, 0x0 array-length v11, v8 invoke-static {v8, v10, v11, v3}, Landroid/graphics/BitmapFactory;->decodeByteArray([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap; .line 500 invoke-static {v3, p1, p2}, Landroid/media/ThumbnailUtils;->computeSampleSize(Landroid/graphics/BitmapFactory$Options;II)I move-result v10 iput v10, v3, Landroid/graphics/BitmapFactory$Options;->inSampleSize:I .line 501 iget v10, v3, Landroid/graphics/BitmapFactory$Options;->outWidth:I iget v11, v3, Landroid/graphics/BitmapFactory$Options;->inSampleSize:I div-int v4, v10, v11 .line 505 :cond_2 const/4 v10, 0x1 iput-boolean v10, v5, Landroid/graphics/BitmapFactory$Options;->inJustDecodeBounds:Z .line 506 invoke-static {p0, v5}, Landroid/graphics/BitmapFactory;->decodeFile(Ljava/lang/String;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap; .line 507 invoke-static {v5, p1, p2}, Landroid/media/ThumbnailUtils;->computeSampleSize(Landroid/graphics/BitmapFactory$Options;II)I move-result v10 iput v10, v5, Landroid/graphics/BitmapFactory$Options;->inSampleSize:I .line 508 iget v10, v5, Landroid/graphics/BitmapFactory$Options;->outWidth:I iget v11, v5, Landroid/graphics/BitmapFactory$Options;->inSampleSize:I div-int v6, v10, v11 .line 511 if-eqz v8, :cond_3 if-lt v4, v6, :cond_3 .line 512 iget v9, v3, Landroid/graphics/BitmapFactory$Options;->outWidth:I .line 513 .local v9, width:I iget v7, v3, Landroid/graphics/BitmapFactory$Options;->outHeight:I .line 514 .local v7, height:I const/4 v10, 0x0 iput-boolean v10, v3, Landroid/graphics/BitmapFactory$Options;->inJustDecodeBounds:Z .line 515 const/4 v10, 0x0 array-length v11, v8 invoke-static {v8, v10, v11, v3}, Landroid/graphics/BitmapFactory;->decodeByteArray([BIILandroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap; move-result-object v10 iput-object v10, p3, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap;->mBitmap:Landroid/graphics/Bitmap; .line 517 iget-object v10, p3, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap;->mBitmap:Landroid/graphics/Bitmap; if-eqz v10, :cond_0 .line 518 iput-object v8, p3, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap;->mThumbnailData:[B .line 519 iput v9, p3, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap;->mThumbnailWidth:I .line 520 iput v7, p3, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap;->mThumbnailHeight:I goto :goto_0 .line 487 .end local v3 #exifOptions:Landroid/graphics/BitmapFactory$Options; .end local v4 #exifThumbWidth:I .end local v5 #fullOptions:Landroid/graphics/BitmapFactory$Options; .end local v6 #fullThumbWidth:I .end local v7 #height:I .end local v9 #width:I :catch_0 move-exception v0 .line 488 .local v0, ex:Ljava/io/IOException; :goto_2 const-string v10, "ThumbnailUtils" invoke-static {v10, v0}, Landroid/util/Log;->w(Ljava/lang/String;Ljava/lang/Throwable;)I goto :goto_1 .line 523 .end local v0 #ex:Ljava/io/IOException; .restart local v3 #exifOptions:Landroid/graphics/BitmapFactory$Options; .restart local v4 #exifThumbWidth:I .restart local v5 #fullOptions:Landroid/graphics/BitmapFactory$Options; .restart local v6 #fullThumbWidth:I :cond_3 const/4 v10, 0x0 iput-boolean v10, v5, Landroid/graphics/BitmapFactory$Options;->inJustDecodeBounds:Z .line 524 invoke-static {p0, v5}, Landroid/graphics/BitmapFactory;->decodeFile(Ljava/lang/String;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap; move-result-object v10 iput-object v10, p3, Landroid/media/ThumbnailUtils$SizedThumbnailBitmap;->mBitmap:Landroid/graphics/Bitmap; goto :goto_0 .line 487 .end local v1 #exif:Landroid/media/ExifInterface; .end local v3 #exifOptions:Landroid/graphics/BitmapFactory$Options; .end local v4 #exifThumbWidth:I .end local v5 #fullOptions:Landroid/graphics/BitmapFactory$Options; .end local v6 #fullThumbWidth:I .restart local v2 #exif:Landroid/media/ExifInterface; :catch_1 move-exception v0 move-object v1, v2 .end local v2 #exif:Landroid/media/ExifInterface; .restart local v1 #exif:Landroid/media/ExifInterface; goto :goto_2 .end method .method public static createVideoThumbnail(Ljava/lang/String;I)Landroid/graphics/Bitmap; .locals 12 .parameter "filePath" .parameter "kind" .prologue const/16 v11, 0x60 const/4 v10, 0x1 .line 159 const/4 v0, 0x0 .line 160 .local v0, bitmap:Landroid/graphics/Bitmap; new-instance v4, Landroid/media/MediaMetadataRetriever; invoke-direct {v4}, Landroid/media/MediaMetadataRetriever;-><init>()V .line 162 .local v4, retriever:Landroid/media/MediaMetadataRetriever; :try_start_0 invoke-virtual {v4, p0}, Landroid/media/MediaMetadataRetriever;->setDataSource(Ljava/lang/String;)V .line 163 const-wide/16 v8, -0x1 invoke-virtual {v4, v8, v9}, Landroid/media/MediaMetadataRetriever;->getFrameAtTime(J)Landroid/graphics/Bitmap; :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 .catch Ljava/lang/IllegalArgumentException; {:try_start_0 .. :try_end_0} :catch_0 .catch Ljava/lang/RuntimeException; {:try_start_0 .. :try_end_0} :catch_2 move-result-object v0 .line 170 :try_start_1 invoke-virtual {v4}, Landroid/media/MediaMetadataRetriever;->release()V :try_end_1 .catch Ljava/lang/RuntimeException; {:try_start_1 .. :try_end_1} :catch_4 .line 176 :goto_0 if-nez v0, :cond_0 const/4 v8, 0x0 .line 195 :goto_1 return-object v8 .line 164 :catch_0 move-exception v8 .line 170 :try_start_2 invoke-virtual {v4}, Landroid/media/MediaMetadataRetriever;->release()V :try_end_2 .catch Ljava/lang/RuntimeException; {:try_start_2 .. :try_end_2} :catch_1 goto :goto_0 .line 171 :catch_1 move-exception v8 goto :goto_0 .line 166 :catch_2 move-exception v8 .line 170 :try_start_3 invoke-virtual {v4}, Landroid/media/MediaMetadataRetriever;->release()V :try_end_3 .catch Ljava/lang/RuntimeException; {:try_start_3 .. :try_end_3} :catch_3 goto :goto_0 .line 171 :catch_3 move-exception v8 goto :goto_0 .line 169 :catchall_0 move-exception v8 .line 170 :try_start_4 invoke-virtual {v4}, Landroid/media/MediaMetadataRetriever;->release()V :try_end_4 .catch Ljava/lang/RuntimeException; {:try_start_4 .. :try_end_4} :catch_5 .line 173 :goto_2 throw v8 .line 178 :cond_0 if-ne p1, v10, :cond_2 .line 180 invoke-virtual {v0}, Landroid/graphics/Bitmap;->getWidth()I move-result v7 .line 181 .local v7, width:I invoke-virtual {v0}, Landroid/graphics/Bitmap;->getHeight()I move-result v2 .line 182 .local v2, height:I invoke-static {v7, v2}, Ljava/lang/Math;->max(II)I move-result v3 .line 183 .local v3, max:I const/16 v8, 0x200 if-le v3, v8, :cond_1 .line 184 const/high16 v8, 0x4400 int-to-float v9, v3 div-float v5, v8, v9 .line 185 .local v5, scale:F int-to-float v8, v7 mul-float/2addr v8, v5 invoke-static {v8}, Ljava/lang/Math;->round(F)I move-result v6 .line 186 .local v6, w:I int-to-float v8, v2 mul-float/2addr v8, v5 invoke-static {v8}, Ljava/lang/Math;->round(F)I move-result v1 .line 187 .local v1, h:I invoke-static {v0, v6, v1, v10}, Landroid/graphics/Bitmap;->createScaledBitmap(Landroid/graphics/Bitmap;IIZ)Landroid/graphics/Bitmap; move-result-object v0 .end local v1 #h:I .end local v2 #height:I .end local v3 #max:I .end local v5 #scale:F .end local v6 #w:I .end local v7 #width:I :cond_1 :goto_3 move-object v8, v0 .line 195 goto :goto_1 .line 189 :cond_2 const/4 v8, 0x3 if-ne p1, v8, :cond_1 .line 190 const/4 v8, 0x2 invoke-static {v0, v11, v11, v8}, Landroid/media/ThumbnailUtils;->extractThumbnail(Landroid/graphics/Bitmap;III)Landroid/graphics/Bitmap; move-result-object v0 goto :goto_3 .line 171 :catch_4 move-exception v8 goto :goto_0 :catch_5 move-exception v9 goto :goto_2 .end method .method public static extractThumbnail(Landroid/graphics/Bitmap;II)Landroid/graphics/Bitmap; .locals 1 .parameter "source" .parameter "width" .parameter "height" .prologue .line 207 const/4 v0, 0x0 invoke-static {p0, p1, p2, v0}, Landroid/media/ThumbnailUtils;->extractThumbnail(Landroid/graphics/Bitmap;III)Landroid/graphics/Bitmap; move-result-object v0 return-object v0 .end method .method public static extractThumbnail(Landroid/graphics/Bitmap;III)Landroid/graphics/Bitmap; .locals 5 .parameter "source" .parameter "width" .parameter "height" .parameter "options" .prologue .line 220 if-nez p0, :cond_0 .line 221 const/4 v2, 0x0 .line 234 :goto_0 return-object v2 .line 225 :cond_0 invoke-virtual {p0}, Landroid/graphics/Bitmap;->getWidth()I move-result v3 invoke-virtual {p0}, Landroid/graphics/Bitmap;->getHeight()I move-result v4 if-ge v3, v4, :cond_1 .line 226 int-to-float v3, p1 invoke-virtual {p0}, Landroid/graphics/Bitmap;->getWidth()I move-result v4 int-to-float v4, v4 div-float v1, v3, v4 .line 230 .local v1, scale:F :goto_1 new-instance v0, Landroid/graphics/Matrix; invoke-direct {v0}, Landroid/graphics/Matrix;-><init>()V .line 231 .local v0, matrix:Landroid/graphics/Matrix; invoke-virtual {v0, v1, v1}, Landroid/graphics/Matrix;->setScale(FF)V .line 232 or-int/lit8 v3, p3, 0x1 invoke-static {v0, p0, p1, p2, v3}, Landroid/media/ThumbnailUtils;->transform(Landroid/graphics/Matrix;Landroid/graphics/Bitmap;III)Landroid/graphics/Bitmap; move-result-object v2 .line 234 .local v2, thumbnail:Landroid/graphics/Bitmap; goto :goto_0 .line 228 .end local v0 #matrix:Landroid/graphics/Matrix; .end local v1 #scale:F .end local v2 #thumbnail:Landroid/graphics/Bitmap; :cond_1 int-to-float v3, p2 invoke-virtual {p0}, Landroid/graphics/Bitmap;->getHeight()I move-result v4 int-to-float v4, v4 div-float v1, v3, v4 .restart local v1 #scale:F goto :goto_1 .end method .method private static makeBitmap(IILandroid/net/Uri;Landroid/content/ContentResolver;Landroid/os/ParcelFileDescriptor;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap; .locals 7 .parameter "minSideLength" .parameter "maxNumOfPixels" .parameter "uri" .parameter "cr" .parameter "pfd" .parameter "options" .prologue const/4 v6, -0x1 const/4 v4, 0x0 .line 311 const/4 v0, 0x0 .line 313 .local v0, b:Landroid/graphics/Bitmap; if-nez p4, :cond_0 :try_start_0 invoke-static {p2, p3}, Landroid/media/ThumbnailUtils;->makeInputStream(Landroid/net/Uri;Landroid/content/ContentResolver;)Landroid/os/ParcelFileDescriptor; :try_end_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 .catch Ljava/lang/OutOfMemoryError; {:try_start_0 .. :try_end_0} :catch_0 move-result-object p4 .line 314 :cond_0 if-nez p4, :cond_1 .line 336 invoke-static {p4}, Landroid/media/ThumbnailUtils;->closeSilently(Landroid/os/ParcelFileDescriptor;)V .line 338 :goto_0 return-object v4 .line 315 :cond_1 if-nez p5, :cond_2 :try_start_1 new-instance v3, Landroid/graphics/BitmapFactory$Options; invoke-direct {v3}, Landroid/graphics/BitmapFactory$Options;-><init>()V .end local p5 .local v3, options:Landroid/graphics/BitmapFactory$Options; move-object p5, v3 .line 317 .end local v3 #options:Landroid/graphics/BitmapFactory$Options; .restart local p5 :cond_2 invoke-virtual {p4}, Landroid/os/ParcelFileDescriptor;->getFileDescriptor()Ljava/io/FileDescriptor; move-result-object v2 .line 318 .local v2, fd:Ljava/io/FileDescriptor; const/4 v5, 0x1 iput v5, p5, Landroid/graphics/BitmapFactory$Options;->inSampleSize:I .line 319 const/4 v5, 0x1 iput-boolean v5, p5, Landroid/graphics/BitmapFactory$Options;->inJustDecodeBounds:Z .line 320 const/4 v5, 0x0 invoke-static {v2, v5, p5}, Landroid/graphics/BitmapFactory;->decodeFileDescriptor(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap; .line 321 iget-boolean v5, p5, Landroid/graphics/BitmapFactory$Options;->mCancel:Z if-nez v5, :cond_3 iget v5, p5, Landroid/graphics/BitmapFactory$Options;->outWidth:I if-eq v5, v6, :cond_3 iget v5, p5, Landroid/graphics/BitmapFactory$Options;->outHeight:I :try_end_1 .catchall {:try_start_1 .. :try_end_1} :catchall_0 .catch Ljava/lang/OutOfMemoryError; {:try_start_1 .. :try_end_1} :catch_0 if-ne v5, v6, :cond_4 .line 336 :cond_3 invoke-static {p4}, Landroid/media/ThumbnailUtils;->closeSilently(Landroid/os/ParcelFileDescriptor;)V goto :goto_0 .line 325 :cond_4 :try_start_2 invoke-static {p5, p0, p1}, Landroid/media/ThumbnailUtils;->computeSampleSize(Landroid/graphics/BitmapFactory$Options;II)I move-result v5 iput v5, p5, Landroid/graphics/BitmapFactory$Options;->inSampleSize:I .line 327 const/4 v5, 0x0 iput-boolean v5, p5, Landroid/graphics/BitmapFactory$Options;->inJustDecodeBounds:Z .line 329 const/4 v5, 0x0 iput-boolean v5, p5, Landroid/graphics/BitmapFactory$Options;->inDither:Z .line 330 sget-object v5, Landroid/graphics/Bitmap$Config;->ARGB_8888:Landroid/graphics/Bitmap$Config; iput-object v5, p5, Landroid/graphics/BitmapFactory$Options;->inPreferredConfig:Landroid/graphics/Bitmap$Config; .line 331 const/4 v5, 0x0 invoke-static {v2, v5, p5}, Landroid/graphics/BitmapFactory;->decodeFileDescriptor(Ljava/io/FileDescriptor;Landroid/graphics/Rect;Landroid/graphics/BitmapFactory$Options;)Landroid/graphics/Bitmap; :try_end_2 .catchall {:try_start_2 .. :try_end_2} :catchall_0 .catch Ljava/lang/OutOfMemoryError; {:try_start_2 .. :try_end_2} :catch_0 move-result-object v0 .line 336 invoke-static {p4}, Landroid/media/ThumbnailUtils;->closeSilently(Landroid/os/ParcelFileDescriptor;)V move-object v4, v0 .line 338 goto :goto_0 .line 332 .end local v2 #fd:Ljava/io/FileDescriptor; :catch_0 move-exception v1 .line 333 .local v1, ex:Ljava/lang/OutOfMemoryError; :try_start_3 const-string v5, "ThumbnailUtils" const-string v6, "Got oom exception " invoke-static {v5, v6, v1}, Landroid/util/Log;->e(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I :try_end_3 .catchall {:try_start_3 .. :try_end_3} :catchall_0 .line 336 invoke-static {p4}, Landroid/media/ThumbnailUtils;->closeSilently(Landroid/os/ParcelFileDescriptor;)V goto :goto_0 .end local v1 #ex:Ljava/lang/OutOfMemoryError; :catchall_0 move-exception v4 invoke-static {p4}, Landroid/media/ThumbnailUtils;->closeSilently(Landroid/os/ParcelFileDescriptor;)V throw v4 .end method .method private static makeInputStream(Landroid/net/Uri;Landroid/content/ContentResolver;)Landroid/os/ParcelFileDescriptor; .locals 2 .parameter "uri" .parameter "cr" .prologue .line 353 :try_start_0 const-string/jumbo v1, "r" invoke-virtual {p1, p0, v1}, Landroid/content/ContentResolver;->openFileDescriptor(Landroid/net/Uri;Ljava/lang/String;)Landroid/os/ParcelFileDescriptor; :try_end_0 .catch Ljava/io/IOException; {:try_start_0 .. :try_end_0} :catch_0 move-result-object v1 .line 355 :goto_0 return-object v1 .line 354 :catch_0 move-exception v0 .line 355 .local v0, ex:Ljava/io/IOException; const/4 v1, 0x0 goto :goto_0 .end method .method private static transform(Landroid/graphics/Matrix;Landroid/graphics/Bitmap;III)Landroid/graphics/Bitmap; .locals 30 .parameter "scaler" .parameter "source" .parameter "targetWidth" .parameter "targetHeight" .parameter "options" .prologue .line 367 and-int/lit8 v3, p4, 0x1 if-eqz v3, :cond_3 const/16 v27, 0x1 .line 368 .local v27, scaleUp:Z :goto_0 and-int/lit8 v3, p4, 0x2 if-eqz v3, :cond_4 const/16 v25, 0x1 .line 370 .local v25, recycle:Z :goto_1 invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->getWidth()I move-result v3 sub-int v16, v3, p2 .line 371 .local v16, deltaX:I invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->getHeight()I move-result v3 sub-int v18, v3, p3 .line 372 .local v18, deltaY:I if-nez v27, :cond_5 if-ltz v16, :cond_0 if-gez v18, :cond_5 .line 379 :cond_0 sget-object v3, Landroid/graphics/Bitmap$Config;->ARGB_8888:Landroid/graphics/Bitmap$Config; move/from16 v0, p2 move/from16 v1, p3 invoke-static {v0, v1, v3}, Landroid/graphics/Bitmap;->createBitmap(IILandroid/graphics/Bitmap$Config;)Landroid/graphics/Bitmap; move-result-object v11 .line 381 .local v11, b2:Landroid/graphics/Bitmap; new-instance v15, Landroid/graphics/Canvas; invoke-direct {v15, v11}, Landroid/graphics/Canvas;-><init>(Landroid/graphics/Bitmap;)V .line 383 .local v15, c:Landroid/graphics/Canvas; const/4 v3, 0x0 div-int/lit8 v4, v16, 0x2 invoke-static {v3, v4}, Ljava/lang/Math;->max(II)I move-result v17 .line 384 .local v17, deltaXHalf:I const/4 v3, 0x0 div-int/lit8 v4, v18, 0x2 invoke-static {v3, v4}, Ljava/lang/Math;->max(II)I move-result v19 .line 385 .local v19, deltaYHalf:I new-instance v28, Landroid/graphics/Rect; invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->getWidth()I move-result v3 move/from16 v0, p2 invoke-static {v0, v3}, Ljava/lang/Math;->min(II)I move-result v3 add-int v3, v3, v17 invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->getHeight()I move-result v4 move/from16 v0, p3 invoke-static {v0, v4}, Ljava/lang/Math;->min(II)I move-result v4 add-int v4, v4, v19 move-object/from16 v0, v28 move/from16 v1, v17 move/from16 v2, v19 invoke-direct {v0, v1, v2, v3, v4}, Landroid/graphics/Rect;-><init>(IIII)V .line 390 .local v28, src:Landroid/graphics/Rect; invoke-virtual/range {v28 .. v28}, Landroid/graphics/Rect;->width()I move-result v3 sub-int v3, p2, v3 div-int/lit8 v21, v3, 0x2 .line 391 .local v21, dstX:I invoke-virtual/range {v28 .. v28}, Landroid/graphics/Rect;->height()I move-result v3 sub-int v3, p3, v3 div-int/lit8 v22, v3, 0x2 .line 392 .local v22, dstY:I new-instance v20, Landroid/graphics/Rect; sub-int v3, p2, v21 sub-int v4, p3, v22 move-object/from16 v0, v20 move/from16 v1, v21 move/from16 v2, v22 invoke-direct {v0, v1, v2, v3, v4}, Landroid/graphics/Rect;-><init>(IIII)V .line 397 .local v20, dst:Landroid/graphics/Rect; const/4 v3, 0x0 move-object/from16 v0, p1 move-object/from16 v1, v28 move-object/from16 v2, v20 invoke-virtual {v15, v0, v1, v2, v3}, Landroid/graphics/Canvas;->drawBitmap(Landroid/graphics/Bitmap;Landroid/graphics/Rect;Landroid/graphics/Rect;Landroid/graphics/Paint;)V .line 398 if-eqz v25, :cond_1 .line 399 invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->recycle()V .line 401 :cond_1 const/4 v3, 0x0 invoke-virtual {v15, v3}, Landroid/graphics/Canvas;->setBitmap(Landroid/graphics/Bitmap;)V .line 455 .end local v15 #c:Landroid/graphics/Canvas; .end local v17 #deltaXHalf:I .end local v19 #deltaYHalf:I .end local v20 #dst:Landroid/graphics/Rect; .end local v21 #dstX:I .end local v22 #dstY:I .end local v28 #src:Landroid/graphics/Rect; :cond_2 :goto_2 return-object v11 .line 367 .end local v11 #b2:Landroid/graphics/Bitmap; .end local v16 #deltaX:I .end local v18 #deltaY:I .end local v25 #recycle:Z .end local v27 #scaleUp:Z :cond_3 const/16 v27, 0x0 goto/16 :goto_0 .line 368 .restart local v27 #scaleUp:Z :cond_4 const/16 v25, 0x0 goto/16 :goto_1 .line 404 .restart local v16 #deltaX:I .restart local v18 #deltaY:I .restart local v25 #recycle:Z :cond_5 invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->getWidth()I move-result v3 int-to-float v14, v3 .line 405 .local v14, bitmapWidthF:F invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->getHeight()I move-result v3 int-to-float v13, v3 .line 407 .local v13, bitmapHeightF:F div-float v12, v14, v13 .line 408 .local v12, bitmapAspect:F move/from16 v0, p2 int-to-float v3, v0 move/from16 v0, p3 int-to-float v4, v0 div-float v29, v3, v4 .line 410 .local v29, viewAspect:F cmpl-float v3, v12, v29 if-lez v3, :cond_a .line 411 move/from16 v0, p3 int-to-float v3, v0 div-float v26, v3, v13 .line 412 .local v26, scale:F const v3, 0x3f666666 cmpg-float v3, v26, v3 if-ltz v3, :cond_6 const/high16 v3, 0x3f80 cmpl-float v3, v26, v3 if-lez v3, :cond_9 .line 413 :cond_6 move-object/from16 v0, p0 move/from16 v1, v26 move/from16 v2, v26 invoke-virtual {v0, v1, v2}, Landroid/graphics/Matrix;->setScale(FF)V .line 427 :goto_3 if-eqz p0, :cond_d .line 429 const/4 v4, 0x0 const/4 v5, 0x0 invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->getWidth()I move-result v6 invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->getHeight()I move-result v7 const/4 v9, 0x1 move-object/from16 v3, p1 move-object/from16 v8, p0 invoke-static/range {v3 .. v9}, Landroid/graphics/Bitmap;->createBitmap(Landroid/graphics/Bitmap;IIIILandroid/graphics/Matrix;Z)Landroid/graphics/Bitmap; move-result-object v10 .line 435 .local v10, b1:Landroid/graphics/Bitmap; :goto_4 if-eqz v25, :cond_7 move-object/from16 v0, p1 if-eq v10, v0, :cond_7 .line 436 invoke-virtual/range {p1 .. p1}, Landroid/graphics/Bitmap;->recycle()V .line 439 :cond_7 const/4 v3, 0x0 invoke-virtual {v10}, Landroid/graphics/Bitmap;->getWidth()I move-result v4 sub-int v4, v4, p2 invoke-static {v3, v4}, Ljava/lang/Math;->max(II)I move-result v23 .line 440 .local v23, dx1:I const/4 v3, 0x0 invoke-virtual {v10}, Landroid/graphics/Bitmap;->getHeight()I move-result v4 sub-int v4, v4, p3 invoke-static {v3, v4}, Ljava/lang/Math;->max(II)I move-result v24 .line 442 .local v24, dy1:I div-int/lit8 v3, v23, 0x2 div-int/lit8 v4, v24, 0x2 move/from16 v0, p2 move/from16 v1, p3 invoke-static {v10, v3, v4, v0, v1}, Landroid/graphics/Bitmap;->createBitmap(Landroid/graphics/Bitmap;IIII)Landroid/graphics/Bitmap; move-result-object v11 .line 449 .restart local v11 #b2:Landroid/graphics/Bitmap; if-eq v11, v10, :cond_2 .line 450 if-nez v25, :cond_8 move-object/from16 v0, p1 if-eq v10, v0, :cond_2 .line 451 :cond_8 invoke-virtual {v10}, Landroid/graphics/Bitmap;->recycle()V goto/16 :goto_2 .line 415 .end local v10 #b1:Landroid/graphics/Bitmap; .end local v11 #b2:Landroid/graphics/Bitmap; .end local v23 #dx1:I .end local v24 #dy1:I :cond_9 const/16 p0, 0x0 goto :goto_3 .line 418 .end local v26 #scale:F :cond_a move/from16 v0, p2 int-to-float v3, v0 div-float v26, v3, v14 .line 419 .restart local v26 #scale:F const v3, 0x3f666666 cmpg-float v3, v26, v3 if-ltz v3, :cond_b const/high16 v3, 0x3f80 cmpl-float v3, v26, v3 if-lez v3, :cond_c .line 420 :cond_b move-object/from16 v0, p0 move/from16 v1, v26 move/from16 v2, v26 invoke-virtual {v0, v1, v2}, Landroid/graphics/Matrix;->setScale(FF)V goto :goto_3 .line 422 :cond_c const/16 p0, 0x0 goto :goto_3 .line 432 :cond_d move-object/from16 v10, p1 .restart local v10 #b1:Landroid/graphics/Bitmap; goto :goto_4 .end method
{'content_hash': '1cc613f7cf948c35cf6d95cb3377befd', 'timestamp': '', 'source': 'github', 'line_count': 1881, 'max_line_length': 201, 'avg_line_length': 24.036150983519406, 'alnum_prop': 0.6524152879766434, 'repo_name': 'baidurom/reference', 'id': '128d2cf1066063998e7d9991fd5f20161ea3a0c7', 'size': '45212', 'binary': False, 'copies': '4', 'ref': 'refs/heads/coron-4.2', 'path': 'aosp/framework.jar.out/smali/android/media/ThumbnailUtils.smali', 'mode': '33188', 'license': 'apache-2.0', 'language': []}
Window::Window(SharedObject<sf::RenderWindow>& sharedWin) : m_sharedWin(sharedWin) { } Window::~Window() { } //########################################################################### void Window::create(const Size& size, const String& title, bool isFullscreen) { m_win.create(sf::VideoMode(size.width, size.height), title.getStr(), isFullscreen ? sf::Style::Fullscreen : sf::Style::Default); } void Window::exit() { m_win.close(); } //-------------------------------------------------------------------------- bool Window::isRunning() const { return m_win.isOpen(); } //########################################################################### void Window::show() { m_win.setActive(true); } void Window::hide() { m_win.setActive(false); } //-------------------------------------------------------------------------- bool Window::isOpen() const { return m_win.hasFocus(); } //########################################################################### bool Window::onUpdate(WindowEvent* outEvent) { sf::Event newEvent; if (m_win.pollEvent(newEvent)) { if (newEvent.type == sf::Event::Closed) this->exit(); if (outEvent != nullptr) { using EventTypes = WindowEvent::Types; EventTypes eventType = EventTypes::Unknown; switch (newEvent.type) { case sf::Event::Closed: eventType = EventTypes::Closed; break; case sf::Event::Resized: eventType = EventTypes::Resized; outEvent->size.width = newEvent.size.width; outEvent->size.height = newEvent.size.height; break; case sf::Event::TextEntered: eventType = EventTypes::TextEntered; outEvent->text.unicode = newEvent.text.unicode; break; } outEvent->setType(eventType); } return true; } return false; } void Window::beginDraw(const Color& backColor) { m_win.clear(sf::Color( backColor.r, backColor.g, backColor.b, backColor.a)); } void Window::endDraw() { m_win.display(); } //########################################################################### auto Window::getSize() const -> Size { auto size = m_win.getSize(); return Size(size.x, size.y); } void Window::setFramerate(int framePerSec) { m_win.setFramerateLimit(framePerSec); } void Window::disableFramerate() { m_win.setFramerateLimit(0); } //########################################################################### void Window::attach() { m_sharedWin.pushObject(&m_win); } void Window::detach() { m_sharedWin.popObject(); }
{'content_hash': '55086d64a8a4d15b082fecf402d4a060', 'timestamp': '', 'source': 'github', 'line_count': 150, 'max_line_length': 77, 'avg_line_length': 16.593333333333334, 'alnum_prop': 0.5198875050220972, 'repo_name': 'NeuroWhAI/CodeAdapter', 'id': '51af180c97d16220a8dd931255b3cca04913f9f4', 'size': '2684', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'CodeAdapterSFML/Window.cpp', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C', 'bytes': '2108'}, {'name': 'C++', 'bytes': '231266'}]}
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace LateNightStupidities.IIImaBackupViewer.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.3.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
{'content_hash': '17c1dd0c386d6408eb1ce919a628a892', 'timestamp': '', 'source': 'github', 'line_count': 26, 'max_line_length': 151, 'avg_line_length': 42.03846153846154, 'alnum_prop': 0.5910338517840805, 'repo_name': 'spkl/3ma-backup-viewer', 'id': '3fdf4624227b6c260963991dea20bf956f2e95ff', 'size': '1095', 'binary': False, 'copies': '1', 'ref': 'refs/heads/master', 'path': 'src/3maBackupViewer/Properties/Settings.Designer.cs', 'mode': '33188', 'license': 'mit', 'language': [{'name': 'C#', 'bytes': '96142'}]}