text
stringlengths
2
99.9k
meta
dict
# -*- coding: utf-8 -*- # 淘宝账号 taobao_username = u"" taobao_password = "" # CSDN账户 csdn_username = "" csdn_password = "" # 七牛授权 qiniu_ak = "" qiniu_sk = "" qiniu_bucket = "csdn-data" qiniu_domain = "http://example.com" # 邮箱账号 mail_username = "" # 邮箱登录密码(可选,mail_send_type=2有效) mail_password = "" # 邮箱独立密码(可选,mail_send_type=2有效) mail_password2 = "" # 邮箱授权码(可选,mail_send_type=1有效) mail_authorization_code = "" # 接收邮件号 master_mail = "" # 本地保存下载文件地址 local_dir = "c://Robot_Download/" # 自带文件下载服务器地址前缀,类似http://xx.com/(可选,mail_send_type=0有效) server_file_url = "http://example.com:8080/" # 下载次数总数 download_total = 20 # 爬虫每次检查待发货订单间隔/秒 check_order_period = 30 # 爬虫每次检查存在退款订单间隔/秒 check_refunding_period = 60 # 页面加载等待最长时间(推荐10秒以上,视网速而定) delay_wait = 15 # 邮件发送方式 0=仅仅发送资源新的下载链接(需自带服务器) 1=发送邮件附件(50M以上问题发送有问题) 2=浏览器方式发送(推荐) mail_send_type = 0 # 是否开启邮件提醒 is_mail_notice = False
{ "pile_set_name": "Github" }
""" 输出乘法口诀表(九九表) Version: 0.1 Author: 骆昊 Date: 2018-03-02 """ for i in range(1, 10): for j in range(1, i + 1): print('%d*%d=%d' % (i, j, i * j), end='\t') print()
{ "pile_set_name": "Github" }
/home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/obj/local/armeabi/objs/ijksoundtouch/source/SoundTouch/RateTransposer.o: \ /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/RateTransposer.cpp \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/assert.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/_cprolog.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/features.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/_stlport_version.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/user_config.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/compat.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/host.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/_system.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/_android.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/_gcc.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/stl_confix.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/_native_headers.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/_epilog.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/_config_compat_post.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stdlib.h \ /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stdio.h \ /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/RateTransposer.h \ /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/AAFilter.h \ /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/STTypes.h \ /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/FIFOSampleBuffer.h \ /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/FIFOSamplePipe.h \ /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/STTypes.h \ /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/FIFOSamplePipe.h \ /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/InterpolateLinear.h \ /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/InterpolateCubic.h \ /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/InterpolateShannon.h /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/assert.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/_cprolog.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/features.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/_stlport_version.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/user_config.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/compat.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/host.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/_system.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/_android.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/_gcc.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/stl_confix.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/config/_native_headers.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/_epilog.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stl/_config_compat_post.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stdlib.h: /home/ksw/develop/android-ndk-r14b/sources/cxx-stl/stlport/stlport/stdio.h: /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/RateTransposer.h: /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/AAFilter.h: /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/STTypes.h: /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/FIFOSampleBuffer.h: /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/FIFOSamplePipe.h: /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/STTypes.h: /home/ksw/develop/ijkplayer-android/ijkmedia/ijksoundtouch/include/FIFOSamplePipe.h: /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/InterpolateLinear.h: /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/InterpolateCubic.h: /home/ksw/develop/ijkplayer-android/android/ijkplayer/ijkplayer-armv5/src/main/jni/ijkmedia/ijksoundtouch/source/SoundTouch/InterpolateShannon.h:
{ "pile_set_name": "Github" }
# executes a predicate on every item of the list (passed by reference) # and returns those items for which the predicate holds function(list_where __list_where_lst predicate) foreach(item ${${__list_where_lst}}) rcall(__matched = "${predicate}"("${item}")) if(__matched) list(APPEND result_list ${item}) endif() endforeach() return_ref(result_list) endfunction() ## fast implemenation function(list_where __list_where_lst __list_where_predicate) function_import("${__list_where_predicate}" as __list_where_predicate REDEFINE) set(__list_where_result_list) foreach(__list_where_item ${${__list_where_lst}}) __list_where_predicate(${__list_where_item}) ans(__matched) if(__matched) list(APPEND __list_where_result_list ${__list_where_item}) endif() endforeach() return_ref(__list_where_result_list) endfunction()
{ "pile_set_name": "Github" }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chain.h> /** * CChain implementation */ void CChain::SetTip(CBlockIndex *pindex) { if (pindex == nullptr) { vChain.clear(); return; } vChain.resize(pindex->nHeight + 1); while (pindex && vChain[pindex->nHeight] != pindex) { vChain[pindex->nHeight] = pindex; pindex = pindex->pprev; } } CBlockLocator CChain::GetLocator(const CBlockIndex *pindex) const { int nStep = 1; std::vector<uint256> vHave; vHave.reserve(32); if (!pindex) pindex = Tip(); while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Stop when we have added the genesis block. if (pindex->nHeight == 0) break; // Exponentially larger steps back, plus the genesis block. int nHeight = std::max(pindex->nHeight - nStep, 0); if (Contains(pindex)) { // Use O(1) CChain index if possible. pindex = (*this)[nHeight]; } else { // Otherwise, use O(log n) skiplist. pindex = pindex->GetAncestor(nHeight); } if (vHave.size() > 10) nStep *= 2; } return CBlockLocator(vHave); } const CBlockIndex *CChain::FindFork(const CBlockIndex *pindex) const { if (pindex == nullptr) { return nullptr; } if (pindex->nHeight > Height()) pindex = pindex->GetAncestor(Height()); while (pindex && !Contains(pindex)) pindex = pindex->pprev; return pindex; } CBlockIndex* CChain::FindEarliestAtLeast(int64_t nTime) const { std::vector<CBlockIndex*>::const_iterator lower = std::lower_bound(vChain.begin(), vChain.end(), nTime, [](CBlockIndex* pBlock, const int64_t& time) -> bool { return pBlock->GetBlockTimeMax() < time; }); return (lower == vChain.end() ? nullptr : *lower); } /** Turn the lowest '1' bit in the binary representation of a number into a '0'. */ int static inline InvertLowestOne(int n) { return n & (n - 1); } /** Compute what height to jump back to with the CBlockIndex::pskip pointer. */ int static inline GetSkipHeight(int height) { if (height < 2) return 0; // Determine which height to jump back to. Any number strictly lower than height is acceptable, // but the following expression seems to perform well in simulations (max 110 steps to go back // up to 2**18 blocks). return (height & 1) ? InvertLowestOne(InvertLowestOne(height - 1)) + 1 : InvertLowestOne(height); } const CBlockIndex* CBlockIndex::GetAncestor(int height) const { if (height > nHeight || height < 0) { return nullptr; } const CBlockIndex* pindexWalk = this; int heightWalk = nHeight; while (heightWalk > height) { int heightSkip = GetSkipHeight(heightWalk); int heightSkipPrev = GetSkipHeight(heightWalk - 1); if (pindexWalk->pskip != nullptr && (heightSkip == height || (heightSkip > height && !(heightSkipPrev < heightSkip - 2 && heightSkipPrev >= height)))) { // Only follow pskip if pprev->pskip isn't better than pskip->pprev. pindexWalk = pindexWalk->pskip; heightWalk = heightSkip; } else { assert(pindexWalk->pprev); pindexWalk = pindexWalk->pprev; heightWalk--; } } return pindexWalk; } CBlockIndex* CBlockIndex::GetAncestor(int height) { return const_cast<CBlockIndex*>(static_cast<const CBlockIndex*>(this)->GetAncestor(height)); } void CBlockIndex::BuildSkip() { if (pprev) pskip = pprev->GetAncestor(GetSkipHeight(nHeight)); } arith_uint256 GetBlockProof(const CBlockIndex& block) { arith_uint256 bnTarget; bool fNegative; bool fOverflow; bnTarget.SetCompact(block.nBits, &fNegative, &fOverflow); if (fNegative || fOverflow || bnTarget == 0) return 0; // We need to compute 2**256 / (bnTarget+1), but we can't represent 2**256 // as it's too large for an arith_uint256. However, as 2**256 is at least as large // as bnTarget+1, it is equal to ((2**256 - bnTarget - 1) / (bnTarget+1)) + 1, // or ~bnTarget / (bnTarget+1) + 1. return (~bnTarget / (bnTarget + 1)) + 1; } int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params& params) { arith_uint256 r; int sign = 1; if (to.nChainWork > from.nChainWork) { r = to.nChainWork - from.nChainWork; } else { r = from.nChainWork - to.nChainWork; sign = -1; } r = r * arith_uint256(params.nPowTargetSpacing) / GetBlockProof(tip); if (r.bits() > 63) { return sign * std::numeric_limits<int64_t>::max(); } return sign * r.GetLow64(); } /** Find the last common ancestor two blocks have. * Both pa and pb must be non-nullptr. */ const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb) { if (pa->nHeight > pb->nHeight) { pa = pa->GetAncestor(pb->nHeight); } else if (pb->nHeight > pa->nHeight) { pb = pb->GetAncestor(pa->nHeight); } while (pa != pb && pa && pb) { pa = pa->pprev; pb = pb->pprev; } // Eventually all chain branches meet at the genesis block. assert(pa == pb); return pa; }
{ "pile_set_name": "Github" }
require 'socket' require_relative '../../services/table-geocoder/lib/table_geocoder_factory' require_relative '../../services/table-geocoder/lib/exceptions' require_relative '../../services/table-geocoder/lib/mail_geocoder' require_relative '../../services/geocoder/lib/geocoder_config' require_relative '../../lib/cartodb/metrics' require_relative 'log' require_relative '../../lib/cartodb/stats/geocoding' require_dependency 'carto/configuration' class Geocoding < Sequel::Model include Carto::Configuration ALLOWED_KINDS = %w(admin0 admin1 namedplace postalcode high-resolution ipaddress) PUBLIC_ATTRIBUTES = [:id, :table_id, :table_name, :state, :kind, :country_code, :region_code, :formatter, :geocoder_type, :geometry_type, :error, :processed_rows, :cache_hits, :processable_rows, :real_rows, :price, :used_credits, :remaining_quota, :country_column, :region_column, :data_import_id, :error_code] # Characters in the following Unicode categories: Letter, Mark, Number and Connector_Punctuation, # plus spaces and single quotes SANITIZED_FORMATTER_REGEXP = /\A[[[:word:]]\s\,\']*\z/ MIN_GEOCODING_TIME_TO_NOTIFY = 3 * 60 #seconds GEOCODING_BLOCK_SIZE = 1000.0 many_to_one :user many_to_one :user_table, :key => :table_id many_to_one :data_import attr_reader :table_geocoder attr_reader :started_at, :finished_at attr_reader :log def self.get_not_aggregated_user_geocoding_calls(db, user_id, date_from, date_to) geocoding_calls_sql = "SELECT date(created_at), sum(processed_rows) as processed_rows, " \ "sum(cache_hits) as cache_hits FROM geocodings WHERE kind = 'high-resolution' " \ "AND user_id = ? AND geocodings.created_at >= ? and geocodings.created_at <= ?" \ "GROUP BY date(created_at) ORDER BY date(created_at) DESC" db.fetch(geocoding_calls_sql, user_id, date_from, date_to + 1.days).all end def public_values Hash[PUBLIC_ATTRIBUTES.map{ |k| [k, (self.send(k) rescue self[k].to_s)] }] end def validate super validates_presence :formatter # INFO: since we want to register geocodings during importing we can't register the table # validates_presence :table_id validates_includes ALLOWED_KINDS, :kind end def before_save super self.updated_at = Time.now # cancel if state == 'cancelled' end def geocoding_logger @@geocoding_logger ||= CartoDB.unformatted_logger(log_file_path('geocodings.log')) end def error additional_info = Carto::GeocoderErrors.additional_info(error_code) if additional_info { title: additional_info.title, description: additional_info.what_about } else { title: 'Geocoding error', description: '' } end end # The table geocoder is meant to be instantiated just once. # Memoize the table geocoder or nil if it couldn't be instantiated def table_geocoder if !defined?(@table_geocoder) begin @table_geocoder = Carto::TableGeocoderFactory.get(user, self, CartoDB::GeocoderConfig.instance.get, table_service, original_formatter: formatter, formatter: sanitize_formatter, remote_id: remote_id, countries: country_code, regions: region_code, geometry_type: geometry_type, kind: kind, max_rows: max_geocodable_rows, country_column: country_column, region_column: region_column, log: log) rescue StandardError => e @table_geocoder = nil raise e end else @table_geocoder end end # INFO: table_geocoder method is very coupled to table model, and we want to use this model during imports, without table yet. # this method allows to inject the dependency to the geocoder # TODO: refactor geocoder instantiation out of this class def force_geocoder geocoder @table_geocoder = geocoder end def cancel log.append_and_store "Cancelling job because of user request" table_geocoder.cancel rescue StandardError => e log.append_and_store "Error trying to cancel a job because of user request: #{e.inspect}" count ||= 1 retry unless (count = count.next) > 5 CartoDB::notify_exception(e, user: user) end # INFO: this method shall always be called from a queue processor def run! @started_at = Time.now log.append_and_store "Running geocoding job on server #{Socket.gethostname} with PID: #{Process.pid}" if self.force_all_rows == true table_geocoder.reset_cartodb_georef_status else table_geocoder.mark_rows_to_geocode end store_geocoder_info(Process.pid) processable_rows = self.class.processable_rows(table_service) if processable_rows == 0 self.update(state: 'finished', real_rows: 0, used_credits: 0, processed_rows: 0, cache_hits: 0) self.report return end rows_geocoded_before = table_service.owner.in_database.select.from(table_service.sequel_qualified_table_name).where(cartodb_georef_status: true).count rescue 0 self.run_geocoding!(processable_rows, rows_geocoded_before) rescue StandardError => e # state == nil probably means it has failed even before run_geocoding begun handle_geocoding_failure(e, rows_geocoded_before || 0) if state == nil log.append_and_store "Unexpected exception: #{e}" log.append_and_store e.backtrace CartoDB.notify_exception(e) raise e ensure log.store # Make sure the log is stored in DB user.db_service.reset_pooled_connections end def run_geocoding!(processable_rows, rows_geocoded_before = 0) log.append_and_store "run_geocoding!()" self.update state: 'started', processable_rows: processable_rows @started_at ||= Time.now # INFO: this is where the real stuff is done table_geocoder.run # Sync state to avoid overwrites for state and log refresh return false if cancelled? self.update(table_geocoder.update_geocoding_status) # TODO better exception handling here raise 'Geocoding failed' if state == 'failed' raise 'Geocoding timed out' if state == 'timeout' handle_geocoding_success(rows_geocoded_before) rescue StandardError => e handle_geocoding_failure(e, rows_geocoded_before) end def report(error = nil) payload = metrics_payload(error) CartoDB::Metrics.new.report(:geocoding, payload) payload.delete_if {|k,v| %w{distinct_id email table_id}.include?(k.to_s)} geocoding_logger.info(payload.to_json) end def self.processable_rows(table_service, force_all_rows=false) dataset = table_service.owner.in_database.select.from(table_service.sequel_qualified_table_name) if !force_all_rows && dataset.columns.include?(:cartodb_georef_status) dataset = dataset.exclude(cartodb_georef_status: true) end dataset.count end # self.processable_rows def calculate_used_credits return 0 unless kind == 'high-resolution' && geocoder_type == 'heremaps' total_rows = processed_rows.to_i + cache_hits.to_i geocoding_quota = user.organization.present? ? user.organization.geocoding_quota.to_i : user.geocoding_quota used_geocoding_calls = user.organization_user? ? user.organization.get_geocoding_calls : user.get_geocoding_calls # ::User#get_geocoding_calls includes this geocoding run, so we discount it remaining_quota = geocoding_quota + total_rows - used_geocoding_calls remaining_quota = (remaining_quota > 0 ? remaining_quota : 0) used_credits = total_rows - remaining_quota (used_credits > 0 ? used_credits : 0) end # calculate_used_credits def price return 0 unless used_credits&.positive? (user.geocoding_block_price * used_credits) / GEOCODING_BLOCK_SIZE end def cost return 0 unless kind == 'high-resolution' processed_rows.to_i * CartoDB::GeocoderConfig.instance.get['cost_per_hit_in_cents'] rescue 0 end def remaining_quota user.remaining_geocoding_quota end # remaining_quota def sanitize_formatter translated_formatter = translate_formatter if translated_formatter =~ SANITIZED_FORMATTER_REGEXP translated_formatter else log_warning(message: 'Incorrect formatter string received', current_user: user, error_detail: formatter) '' end end # {field}, SPAIN => field, ', SPAIN' def translate_formatter translated = formatter.to_s.squish translated.prepend("'") unless /^\{/.match(formatter) translated << "'" unless /\}$/.match(formatter) translated.gsub(/^\{/, '') .gsub(/\}$/, '') .gsub(/\}/, ", '") .gsub(/\{/, "', ") end # translate_formatter def max_geocodable_rows # This is an arbitrary number, previously set to 1M return 50000 if user.soft_geocoding_limit? user.remaining_geocoding_quota end def successful_rows real_rows.to_i end def failed_rows processable_rows.to_i - real_rows.to_i end def metrics_payload(exception = nil) payload = { created_at: created_at, distinct_id: user.username, username: user.username, email: user.email, id: id, table_id: table_id, kind: kind, country_code: country_code, formatter: formatter, geocoder_type: geocoder_type, geometry_type: geometry_type, processed_rows: processed_rows, cache_hits: cache_hits, processable_rows: processable_rows, real_rows: real_rows, successful_rows: successful_rows, failed_rows: failed_rows, price: price, cost: cost, used_credits: used_credits, remaining_quota: remaining_quota, data_import_id: data_import_id, batched: self.batched } if state == 'finished' && exception.nil? payload.merge!( success: true ) elsif exception.present? payload.merge!( success: false, error: exception.message, backtrace: exception.backtrace ) else payload.merge!( success: false, error: error ) end payload.merge!(queue_time: started_at - created_at) if started_at && created_at payload.merge!(processing_time: finished_at - started_at) if started_at && finished_at payload end def log @log ||= instantiate_log end def cancelled? state == 'cancelled' end def timeout? state == 'timeout' end private def table_service @table_service ||= Table.new(user_table: user_table) if user_table.present? end def instantiate_log if self.log_id @log = CartoDB::Log.where(id: log_id).first else @log = CartoDB::Log.new({ type: CartoDB::Log::TYPE_GEOCODING, user_id: user.id }) @log.store self.log_id = @log.id self.save end @log end def handle_geocoding_success(rows_geocoded_before) self.update(cache_hits: table_geocoder.cache.hits) if table_geocoder.respond_to?(:cache) stats_aggregator = CartoDB::Stats::Geocoding.instance stats_aggregator.gauge("requests", "+#{self.processed_rows}") rescue nil stats_aggregator.gauge("cache_hits", "+#{self.cache_hits}") rescue nil @finished_at = Time.now self.batched = table_geocoder.used_batch_request? self.geocoder_type = table_geocoder.name geocoded_rows = total_geocoded_rows(rows_geocoded_before) self.update(state: 'finished', real_rows: geocoded_rows, used_credits: calculate_used_credits) send_report_mail(state, self.table_name, nil, self.processable_rows, geocoded_rows) log.append_and_store "Geocoding finished" # In the import table_service could be nil if !table_service.nil? # To store the bbox in visualizations table_service.update_bounding_box end self.report end def handle_geocoding_failure(raised_exception, rows_geocoded_before) @finished_at = Time.now self.batched = table_geocoder.nil? ? false : table_geocoder.used_batch_request? self.geocoder_type = table_geocoder.nil? ? '' : table_geocoder.name if raised_exception.is_a? Carto::GeocoderErrors::GeocoderBaseError self.error_code = raised_exception.class.additional_info.error_code end self.update(state: 'failed', processed_rows: 0, cache_hits: 0) CartoDB::notify_exception(raised_exception, user: user) geocoded_rows = total_geocoded_rows(rows_geocoded_before) send_report_mail(state, self.table_name, error_code, self.processable_rows, geocoded_rows) log.append_and_store "Unexpected exception: #{raised_exception}" log.append_and_store raised_exception.backtrace self.report(raised_exception) end def total_geocoded_rows(rows_geocoded_before) rows_geocoded_after = table_service.owner.in_database.select.from(table_service.sequel_qualified_table_name).where('cartodb_georef_status is true and the_geom is not null').count rescue 0 rows_geocoded_after - rows_geocoded_before end # Used in the run! method def send_report_mail(state, table_name, error_code=nil, processable_rows, number_geocoded_rows) geocoding_time = @finished_at - @started_at CartoDB::Geocoder::MailNotifier.new(user.id, state, table_name, error_code, processable_rows, number_geocoded_rows, geocoding_time).notify_if_needed end def store_geocoder_info(pid) # we use the object instead of the method because # we don't want to build the object until it has # all the needed data that is created in the run method # of the geocoder object. If not is going to fail because # the object is memoized. self.pid = pid if defined?(@table_geocoder) self.geocoder_type = table_geocoder.name end self.save end end
{ "pile_set_name": "Github" }
//===-- omptargetplugin.h - Target dependent OpenMP Plugin API --*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file defines an interface between target independent OpenMP offload // runtime library libomptarget and target dependent plugin. // //===----------------------------------------------------------------------===// #ifndef _OMPTARGETPLUGIN_H_ #define _OMPTARGETPLUGIN_H_ #include <omptarget.h> #ifdef __cplusplus extern "C" { #endif // Return the number of available devices of the type supported by the // target RTL. int32_t __tgt_rtl_number_of_devices(void); // Return an integer different from zero if the provided device image can be // supported by the runtime. The functionality is similar to comparing the // result of __tgt__rtl__load__binary to NULL. However, this is meant to be a // lightweight query to determine if the RTL is suitable for an image without // having to load the library, which can be expensive. int32_t __tgt_rtl_is_valid_binary(__tgt_device_image *Image); // Return an integer other than zero if the data can be exchaned from SrcDevId // to DstDevId. If it is data exchangable, the device plugin should provide // function to move data from source device to destination device directly. int32_t __tgt_rtl_is_data_exchangable(int32_t SrcDevId, int32_t DstDevId); // Initialize the requires flags for the device. int64_t __tgt_rtl_init_requires(int64_t RequiresFlags); // Initialize the specified device. In case of success return 0; otherwise // return an error code. int32_t __tgt_rtl_init_device(int32_t ID); // Pass an executable image section described by image to the specified // device and prepare an address table of target entities. In case of error, // return NULL. Otherwise, return a pointer to the built address table. // Individual entries in the table may also be NULL, when the corresponding // offload region is not supported on the target device. __tgt_target_table *__tgt_rtl_load_binary(int32_t ID, __tgt_device_image *Image); // Allocate data on the particular target device, of the specified size. // HostPtr is a address of the host data the allocated target data // will be associated with (HostPtr may be NULL if it is not known at // allocation time, like for example it would be for target data that // is allocated by omp_target_alloc() API). Return address of the // allocated data on the target that will be used by libomptarget.so to // initialize the target data mapping structures. These addresses are // used to generate a table of target variables to pass to // __tgt_rtl_run_region(). The __tgt_rtl_data_alloc() returns NULL in // case an error occurred on the target device. void *__tgt_rtl_data_alloc(int32_t ID, int64_t Size, void *HostPtr); // Pass the data content to the target device using the target address. In case // of success, return zero. Otherwise, return an error code. int32_t __tgt_rtl_data_submit(int32_t ID, void *TargetPtr, void *HostPtr, int64_t Size); int32_t __tgt_rtl_data_submit_async(int32_t ID, void *TargetPtr, void *HostPtr, int64_t Size, __tgt_async_info *AsyncInfoPtr); // Retrieve the data content from the target device using its address. In case // of success, return zero. Otherwise, return an error code. int32_t __tgt_rtl_data_retrieve(int32_t ID, void *HostPtr, void *TargetPtr, int64_t Size); // Asynchronous version of __tgt_rtl_data_retrieve int32_t __tgt_rtl_data_retrieve_async(int32_t ID, void *HostPtr, void *TargetPtr, int64_t Size, __tgt_async_info *AsyncInfoPtr); // Copy the data content from one target device to another target device using // its address. This operation does not need to copy data back to host and then // from host to another device. In case of success, return zero. Otherwise, // return an error code. int32_t __tgt_rtl_data_exchange(int32_t SrcID, void *SrcPtr, int32_t DstID, void *DstPtr, int64_t Size); // Asynchronous version of __tgt_rtl_data_exchange int32_t __tgt_rtl_data_exchange_async(int32_t SrcID, void *SrcPtr, int32_t DesID, void *DstPtr, int64_t Size, __tgt_async_info *AsyncInfoPtr); // De-allocate the data referenced by target ptr on the device. In case of // success, return zero. Otherwise, return an error code. int32_t __tgt_rtl_data_delete(int32_t ID, void *TargetPtr); // Transfer control to the offloaded entry Entry on the target device. // Args and Offsets are arrays of NumArgs size of target addresses and // offsets. An offset should be added to the target address before passing it // to the outlined function on device side. If AsyncInfoPtr is nullptr, it is // synchronous; otherwise it is asynchronous. However, AsyncInfoPtr may be // ignored on some platforms, like x86_64. In that case, it is synchronous. In // case of success, return zero. Otherwise, return an error code. int32_t __tgt_rtl_run_target_region(int32_t ID, void *Entry, void **Args, ptrdiff_t *Offsets, int32_t NumArgs); // Asynchronous version of __tgt_rtl_run_target_region int32_t __tgt_rtl_run_target_region_async(int32_t ID, void *Entry, void **Args, ptrdiff_t *Offsets, int32_t NumArgs, __tgt_async_info *AsyncInfoPtr); // Similar to __tgt_rtl_run_target_region, but additionally specify the // number of teams to be created and a number of threads in each team. If // AsyncInfoPtr is nullptr, it is synchronous; otherwise it is asynchronous. // However, AsyncInfoPtr may be ignored on some platforms, like x86_64. In that // case, it is synchronous. int32_t __tgt_rtl_run_target_team_region(int32_t ID, void *Entry, void **Args, ptrdiff_t *Offsets, int32_t NumArgs, int32_t NumTeams, int32_t ThreadLimit, uint64_t loop_tripcount); // Asynchronous version of __tgt_rtl_run_target_team_region int32_t __tgt_rtl_run_target_team_region_async( int32_t ID, void *Entry, void **Args, ptrdiff_t *Offsets, int32_t NumArgs, int32_t NumTeams, int32_t ThreadLimit, uint64_t loop_tripcount, __tgt_async_info *AsyncInfoPtr); // Device synchronization. In case of success, return zero. Otherwise, return an // error code. int32_t __tgt_rtl_synchronize(int32_t ID, __tgt_async_info *AsyncInfoPtr); #ifdef __cplusplus } #endif #endif // _OMPTARGETPLUGIN_H_
{ "pile_set_name": "Github" }
<?php namespace App\Console; use Illuminate\Console\Scheduling\Schedule; use Illuminate\Foundation\Console\Kernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ // ]; /** * Define the application's command schedule. * * @param \Illuminate\Console\Scheduling\Schedule $schedule * @return void */ protected function schedule(Schedule $schedule) { $schedule->command('conserve-target')->hourly(); $schedule->command('backup:clean')->daily()->at('01:00'); $schedule->command('backup:run')->daily()->at('02:00'); } /** * Register the commands for the application. * * @return void */ protected function commands() { $this->load(__DIR__ . '/Commands'); require base_path('routes/console.php'); } }
{ "pile_set_name": "Github" }
/* * Tencent is pleased to support the open source community by making Tinker available. * * Copyright (C) 2016 THL A29 Limited, a Tencent company. All rights reserved. * * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package fastdex.runtime.utils; import android.content.Context; import android.content.pm.ApplicationInfo; import java.io.File; import fastdex.common.ShareConstants; import fastdex.runtime.Constants; public class SharePatchFileUtil { /** * data dir, such as /data/data/com.github.typ0520.fastdex.sample/fastdex * @param context * @return */ public static File getFastdexDirectory(Context context) { ApplicationInfo applicationInfo = context.getApplicationInfo(); if (applicationInfo == null) { // Looks like running on a test Context, so just return without patching. return null; } return new File(applicationInfo.dataDir, Constants.FASTDEX_DIR); } /** * 获取上一次源码发生变化的日期 * @param context * @return */ public static long getLastSourceModified(Context context) { ApplicationInfo applicationInfo = context.getApplicationInfo(); if (applicationInfo == null) { return 0; } return new File(applicationInfo.sourceDir).lastModified(); } /** * data dir, such as /data/data/com.github.typ0520.fastdex.sample/fastdex/patch * @param context * @return */ public static File getPatchDirectory(Context context) { return new File(getFastdexDirectory(context), Constants.PATCH_DIR); } public static File getPatchTempDirectory(Context context) { return new File(getFastdexDirectory(context), Constants.TEMP_DIR); } /** * change the jar file path as the makeDexElements do * * @param path * @param optimizedDirectory * @return */ public static String optimizedPathFor(File path, File optimizedDirectory) { String fileName = path.getName(); if (!fileName.endsWith(ShareConstants.DEX_SUFFIX)) { int lastDot = fileName.lastIndexOf("."); if (lastDot < 0) { fileName += ShareConstants.DEX_SUFFIX; } else { StringBuilder sb = new StringBuilder(lastDot + 4); sb.append(fileName, 0, lastDot); sb.append(ShareConstants.DEX_SUFFIX); fileName = sb.toString(); } } File result = new File(optimizedDirectory, fileName); return result.getPath(); } }
{ "pile_set_name": "Github" }
#!/bin/bash shopt -s expand_aliases alias foo='oneword' foo_word='foo' # # Fails silently to match 'foo': # case "$foo_word" in foo) ;; *) echo bad 1;; esac
{ "pile_set_name": "Github" }
-----BEGIN CERTIFICATE----- MIIB/jCCAaSgAwIBAgIFAN6tvu8wCgYIKoZIzj0EAwIwcjELMAkGA1UEBhMCR0Ix DzANBgNVBAgTBkxvbmRvbjEPMA0GA1UEBxMGTG9uZG9uMQ8wDQYDVQQKEwZHb29n bGUxDDAKBgNVBAsTA0VuZzEiMCAGA1UEAxMZRmFrZUludGVybWVkaWF0ZUF1dGhv cml0eTAeFw0xNjEyMDcxNTEzMzZaFw0yNDAxMjAxNTEzMzZaMFYxCzAJBgNVBAYT AkdCMQ8wDQYDVQQIDAZMb25kb24xDzANBgNVBAoMBkdvb2dsZTEMMAoGA1UECwwD RW5nMRcwFQYDVQQDDA5sZWFmMDIuY3NyLnBlbTBZMBMGByqGSM49AgEGCCqGSM49 AwEHA0IABOs3TlJFnEbVqLjF7Vi5MCmmcIppoCZcni9uuGsjbIThRjqYNoJEpYoX i0GCMvQt4Ahbfgc4UvxHVignm+1gi6yjQzBBMB0GA1UdDgQWBBQ/si9B/BGa042m hYCEhq5+cy5pXTAPBgNVHSMECDAGgAQBAgMEMA8GA1UdDwEB/wQFAwMH+YAwCgYI KoZIzj0EAwIDSAAwRQIgchbW8IQHeu63idQuPXP3KFpSONNSb+sMgQC2zTXHt64C IQD5jcXU1rBmksfHZdlq1pjoNRLdhPzhNDS/L7CixOEToQ== -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleName</key> <string>Font List</string> <key>CFBundleIdentifier</key> <string>com.xamarin.font-list</string> <key>CFBundleShortVersionString</key> <string>1.0</string> <key>CFBundleVersion</key> <string>1.0</string> <key>LSRequiresIPhoneOS</key> <true/> <key>MinimumOSVersion</key> <string>9.0</string> <key>UIDeviceFamily</key> <array> <integer>1</integer> <integer>2</integer> </array> <key>UILaunchStoryboardName</key> <string>LaunchScreen</string> <key>UIMainStoryboardFile</key> <string>Main</string> <key>UIRequiredDeviceCapabilities</key> <array> <string>armv7</string> </array> <key>UISupportedInterfaceOrientations</key> <array> <string>UIInterfaceOrientationPortrait</string> <string>UIInterfaceOrientationLandscapeLeft</string> <string>UIInterfaceOrientationLandscapeRight</string> </array> <key>XSAppIconAssets</key> <string>Assets.xcassets/AppIcon.appiconset</string> </dict> </plist>
{ "pile_set_name": "Github" }
import React from "react" import styled from "@emotion/styled" import { css } from "@emotion/core" import { graphql } from "gatsby" import { SubHeader } from "./utils" const Wrapper = styled(`span`)` font-family: ${p => p.theme.fonts.heading}; font-weight: 400; :before, :after { color: #969584; } :before { content: "{ "; } :after { content: " }"; } ${props => props.block && css` display: block; margin-top: ${props.theme.space[2]}; `}; ` const TypeComponent = ({ children }) => ( <span className="token builtin">{children}</span> ) const Punctuation = ({ children }) => ( <span className="token punctuation">{children}</span> ) const Operator = ({ children }) => ( <span className="token operator">{children}</span> ) const ReactJoin = (arrayOfElements, joiner) => arrayOfElements.reduce((acc, current, index) => { if (index > 0) { acc.push( React.cloneElement(joiner, { key: `joiner ${index}`, }) ) } acc.push(current) return acc }, []) const TypeExpression = ({ type }) => { if (type.type === `NameExpression`) { return <TypeComponent>{type.name}</TypeComponent> } else if (type.type === `NullLiteral`) { return <TypeComponent>null</TypeComponent> } else if (type.type === `UndefinedLiteral`) { return <TypeComponent>undefined</TypeComponent> } else if (type.type === `UnionType`) { return ( <React.Fragment> {ReactJoin( type.elements.map((element, index) => ( <TypeExpression key={`union element ${index}`} type={element} /> )), <Operator> | </Operator> )} </React.Fragment> ) } else if (type.type === `TypeApplication` && type.expression) { if (type.expression.name === `Array`) { return ( <React.Fragment> <TypeExpression type={type.applications[0]} /> <Operator>[]</Operator> </React.Fragment> ) } else { return ( <React.Fragment> <TypeExpression type={type.expression} /> {`<`} <TypeExpression type={type.applications[0]} /> {`>`} </React.Fragment> ) } } return null } const FunctionSignature = ({ definition, block, ignoreParams }) => { const params = definition.params ? definition.params .filter(param => !ignoreParams.includes(param.name)) .map((param, index) => ( <React.Fragment key={param.name}> {index > 0 && <Punctuation>, </Punctuation>} {param.name === `$0` ? `apiCallbackContext` : param.name} {param.type && ( <React.Fragment> <Punctuation>{param.optional && `?`}:</Punctuation> {` `} <TypeExpression type={param.type} /> </React.Fragment> )} </React.Fragment> )) : null return ( <Wrapper block={block}> <Punctuation>{`(`}</Punctuation> {params} <Punctuation>{`)`}</Punctuation> <Operator>=&gt;</Operator> {` `} {definition.returns && definition.returns.length ? ( <TypeExpression type={definition.returns[0].type} /> ) : ( <TypeComponent>undefined</TypeComponent> )} </Wrapper> ) } const isFunctionDef = (definition, recursive = true) => (definition.params && definition.params.length > 0) || (definition.returns && definition.returns.length > 0) || (recursive && definition.type && definition.type.typeDef && isFunctionDef(definition.type.typeDef, false)) const SignatureElement = ({ definition, ignoreParams, fallbackToName = false, block = false, }) => { if (isFunctionDef(definition, false)) { return ( <FunctionSignature definition={definition} block={block} ignoreParams={ignoreParams} /> ) } if (definition.type && definition.type.typeDef) { return ( <SignatureElement definition={definition.type.typeDef} fallbackToName={true} ignoreParams={ignoreParams} block={block} /> ) } if (definition.type) { return ( <Wrapper block={block}> <TypeExpression type={definition.type} /> </Wrapper> ) } if (fallbackToName && definition.name) { return ( <Wrapper block={block}> <TypeComponent>{definition.name}</TypeComponent> </Wrapper> ) } return null } const SignatureBlock = ({ definition, level = 0 }) => ( <React.Fragment> <SubHeader level={level}>Signature</SubHeader> <SignatureElement definition={definition} /> </React.Fragment> ) export { isFunctionDef, SignatureElement, SignatureBlock, TypeComponent, Wrapper as SignatureWrapper, } export const fragment = graphql` fragment DocumentationTypeFragment on DocumentationJs { optional type { name type elements expression applications } } `
{ "pile_set_name": "Github" }
{ "type": "statement", "variant": "list", "statement": [ { "type": "statement", "name": { "type": "identifier", "variant": "table", "name": "bees" }, "variant": "create", "format": "table", "definition": [ { "type": "statement", "variant": "select", "result": [ { "type": "identifier", "variant": "column", "name": "name" }, { "type": "identifier", "variant": "column", "name": "color" }, { "type": "identifier", "variant": "column", "name": "legs" }, { "type": "identifier", "variant": "column", "name": "id" } ], "from": { "type": "identifier", "variant": "table", "name": "old_bees" }, "where": [ { "type": "expression", "format": "binary", "variant": "operation", "operation": "is not", "left": { "type": "identifier", "variant": "column", "name": "name" }, "right": { "type": "literal", "variant": "null", "value": "null" } } ] } ] } ] }
{ "pile_set_name": "Github" }
/* ******************************************************************************* ** O.S : Linux ** FILE NAME : arcmsr_attr.c ** BY : Erich Chen ** Description: attributes exported to sysfs and device host ******************************************************************************* ** Copyright (C) 2002 - 2005, Areca Technology Corporation All rights reserved ** ** Web site: www.areca.com.tw ** E-mail: support@areca.com.tw ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License version 2 as ** published by the Free Software Foundation. ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ******************************************************************************* ** 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. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. ******************************************************************************* ** For history of changes, see Documentation/scsi/ChangeLog.arcmsr ** Firmware Specification, see Documentation/scsi/arcmsr_spec.txt ******************************************************************************* */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/errno.h> #include <linux/delay.h> #include <linux/pci.h> #include <scsi/scsi_cmnd.h> #include <scsi/scsi_device.h> #include <scsi/scsi_host.h> #include <scsi/scsi_transport.h> #include "arcmsr.h" struct device_attribute *arcmsr_host_attrs[]; static ssize_t arcmsr_sysfs_iop_message_read(struct kobject *kobj, struct bin_attribute *bin, char *buf, loff_t off, size_t count) { struct device *dev = container_of(kobj,struct device,kobj); struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; uint8_t *pQbuffer,*ptmpQbuffer; int32_t allxfer_len = 0; if (!capable(CAP_SYS_ADMIN)) return -EACCES; /* do message unit read. */ ptmpQbuffer = (uint8_t *)buf; while ((acb->rqbuf_firstindex != acb->rqbuf_lastindex) && (allxfer_len < 1031)) { pQbuffer = &acb->rqbuffer[acb->rqbuf_firstindex]; memcpy(ptmpQbuffer, pQbuffer, 1); acb->rqbuf_firstindex++; acb->rqbuf_firstindex %= ARCMSR_MAX_QBUFFER; ptmpQbuffer++; allxfer_len++; } if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) { struct QBUFFER __iomem *prbuffer; uint8_t __iomem *iop_data; int32_t iop_len; acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW; prbuffer = arcmsr_get_iop_rqbuffer(acb); iop_data = prbuffer->data; iop_len = readl(&prbuffer->data_len); while (iop_len > 0) { acb->rqbuffer[acb->rqbuf_lastindex] = readb(iop_data); acb->rqbuf_lastindex++; acb->rqbuf_lastindex %= ARCMSR_MAX_QBUFFER; iop_data++; iop_len--; } arcmsr_iop_message_read(acb); } return (allxfer_len); } static ssize_t arcmsr_sysfs_iop_message_write(struct kobject *kobj, struct bin_attribute *bin, char *buf, loff_t off, size_t count) { struct device *dev = container_of(kobj,struct device,kobj); struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; int32_t my_empty_len, user_len, wqbuf_firstindex, wqbuf_lastindex; uint8_t *pQbuffer, *ptmpuserbuffer; if (!capable(CAP_SYS_ADMIN)) return -EACCES; if (count > 1032) return -EINVAL; /* do message unit write. */ ptmpuserbuffer = (uint8_t *)buf; user_len = (int32_t)count; wqbuf_lastindex = acb->wqbuf_lastindex; wqbuf_firstindex = acb->wqbuf_firstindex; if (wqbuf_lastindex != wqbuf_firstindex) { arcmsr_post_ioctldata2iop(acb); return 0; /*need retry*/ } else { my_empty_len = (wqbuf_firstindex-wqbuf_lastindex - 1) &(ARCMSR_MAX_QBUFFER - 1); if (my_empty_len >= user_len) { while (user_len > 0) { pQbuffer = &acb->wqbuffer[acb->wqbuf_lastindex]; memcpy(pQbuffer, ptmpuserbuffer, 1); acb->wqbuf_lastindex++; acb->wqbuf_lastindex %= ARCMSR_MAX_QBUFFER; ptmpuserbuffer++; user_len--; } if (acb->acb_flags & ACB_F_MESSAGE_WQBUFFER_CLEARED) { acb->acb_flags &= ~ACB_F_MESSAGE_WQBUFFER_CLEARED; arcmsr_post_ioctldata2iop(acb); } return count; } else { return 0; /*need retry*/ } } } static ssize_t arcmsr_sysfs_iop_message_clear(struct kobject *kobj, struct bin_attribute *bin, char *buf, loff_t off, size_t count) { struct device *dev = container_of(kobj,struct device,kobj); struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; uint8_t *pQbuffer; if (!capable(CAP_SYS_ADMIN)) return -EACCES; if (acb->acb_flags & ACB_F_IOPDATA_OVERFLOW) { acb->acb_flags &= ~ACB_F_IOPDATA_OVERFLOW; arcmsr_iop_message_read(acb); } acb->acb_flags |= (ACB_F_MESSAGE_WQBUFFER_CLEARED | ACB_F_MESSAGE_RQBUFFER_CLEARED | ACB_F_MESSAGE_WQBUFFER_READED); acb->rqbuf_firstindex = 0; acb->rqbuf_lastindex = 0; acb->wqbuf_firstindex = 0; acb->wqbuf_lastindex = 0; pQbuffer = acb->rqbuffer; memset(pQbuffer, 0, sizeof (struct QBUFFER)); pQbuffer = acb->wqbuffer; memset(pQbuffer, 0, sizeof (struct QBUFFER)); return 1; } static struct bin_attribute arcmsr_sysfs_message_read_attr = { .attr = { .name = "mu_read", .mode = S_IRUSR , }, .size = 1032, .read = arcmsr_sysfs_iop_message_read, }; static struct bin_attribute arcmsr_sysfs_message_write_attr = { .attr = { .name = "mu_write", .mode = S_IWUSR, }, .size = 1032, .write = arcmsr_sysfs_iop_message_write, }; static struct bin_attribute arcmsr_sysfs_message_clear_attr = { .attr = { .name = "mu_clear", .mode = S_IWUSR, }, .size = 1, .write = arcmsr_sysfs_iop_message_clear, }; int arcmsr_alloc_sysfs_attr(struct AdapterControlBlock *acb) { struct Scsi_Host *host = acb->host; int error; error = sysfs_create_bin_file(&host->shost_dev.kobj, &arcmsr_sysfs_message_read_attr); if (error) { printk(KERN_ERR "arcmsr: alloc sysfs mu_read failed\n"); goto error_bin_file_message_read; } error = sysfs_create_bin_file(&host->shost_dev.kobj, &arcmsr_sysfs_message_write_attr); if (error) { printk(KERN_ERR "arcmsr: alloc sysfs mu_write failed\n"); goto error_bin_file_message_write; } error = sysfs_create_bin_file(&host->shost_dev.kobj, &arcmsr_sysfs_message_clear_attr); if (error) { printk(KERN_ERR "arcmsr: alloc sysfs mu_clear failed\n"); goto error_bin_file_message_clear; } return 0; error_bin_file_message_clear: sysfs_remove_bin_file(&host->shost_dev.kobj, &arcmsr_sysfs_message_write_attr); error_bin_file_message_write: sysfs_remove_bin_file(&host->shost_dev.kobj, &arcmsr_sysfs_message_read_attr); error_bin_file_message_read: return error; } void arcmsr_free_sysfs_attr(struct AdapterControlBlock *acb) { struct Scsi_Host *host = acb->host; sysfs_remove_bin_file(&host->shost_dev.kobj, &arcmsr_sysfs_message_clear_attr); sysfs_remove_bin_file(&host->shost_dev.kobj, &arcmsr_sysfs_message_write_attr); sysfs_remove_bin_file(&host->shost_dev.kobj, &arcmsr_sysfs_message_read_attr); } static ssize_t arcmsr_attr_host_driver_version(struct device *dev, struct device_attribute *attr, char *buf) { return snprintf(buf, PAGE_SIZE, "%s\n", ARCMSR_DRIVER_VERSION); } static ssize_t arcmsr_attr_host_driver_posted_cmd(struct device *dev, struct device_attribute *attr, char *buf) { struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; return snprintf(buf, PAGE_SIZE, "%4d\n", atomic_read(&acb->ccboutstandingcount)); } static ssize_t arcmsr_attr_host_driver_reset(struct device *dev, struct device_attribute *attr, char *buf) { struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; return snprintf(buf, PAGE_SIZE, "%4d\n", acb->num_resets); } static ssize_t arcmsr_attr_host_driver_abort(struct device *dev, struct device_attribute *attr, char *buf) { struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; return snprintf(buf, PAGE_SIZE, "%4d\n", acb->num_aborts); } static ssize_t arcmsr_attr_host_fw_model(struct device *dev, struct device_attribute *attr, char *buf) { struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; return snprintf(buf, PAGE_SIZE, "%s\n", acb->firm_model); } static ssize_t arcmsr_attr_host_fw_version(struct device *dev, struct device_attribute *attr, char *buf) { struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; return snprintf(buf, PAGE_SIZE, "%s\n", acb->firm_version); } static ssize_t arcmsr_attr_host_fw_request_len(struct device *dev, struct device_attribute *attr, char *buf) { struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; return snprintf(buf, PAGE_SIZE, "%4d\n", acb->firm_request_len); } static ssize_t arcmsr_attr_host_fw_numbers_queue(struct device *dev, struct device_attribute *attr, char *buf) { struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; return snprintf(buf, PAGE_SIZE, "%4d\n", acb->firm_numbers_queue); } static ssize_t arcmsr_attr_host_fw_sdram_size(struct device *dev, struct device_attribute *attr, char *buf) { struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; return snprintf(buf, PAGE_SIZE, "%4d\n", acb->firm_sdram_size); } static ssize_t arcmsr_attr_host_fw_hd_channels(struct device *dev, struct device_attribute *attr, char *buf) { struct Scsi_Host *host = class_to_shost(dev); struct AdapterControlBlock *acb = (struct AdapterControlBlock *) host->hostdata; return snprintf(buf, PAGE_SIZE, "%4d\n", acb->firm_hd_channels); } static DEVICE_ATTR(host_driver_version, S_IRUGO, arcmsr_attr_host_driver_version, NULL); static DEVICE_ATTR(host_driver_posted_cmd, S_IRUGO, arcmsr_attr_host_driver_posted_cmd, NULL); static DEVICE_ATTR(host_driver_reset, S_IRUGO, arcmsr_attr_host_driver_reset, NULL); static DEVICE_ATTR(host_driver_abort, S_IRUGO, arcmsr_attr_host_driver_abort, NULL); static DEVICE_ATTR(host_fw_model, S_IRUGO, arcmsr_attr_host_fw_model, NULL); static DEVICE_ATTR(host_fw_version, S_IRUGO, arcmsr_attr_host_fw_version, NULL); static DEVICE_ATTR(host_fw_request_len, S_IRUGO, arcmsr_attr_host_fw_request_len, NULL); static DEVICE_ATTR(host_fw_numbers_queue, S_IRUGO, arcmsr_attr_host_fw_numbers_queue, NULL); static DEVICE_ATTR(host_fw_sdram_size, S_IRUGO, arcmsr_attr_host_fw_sdram_size, NULL); static DEVICE_ATTR(host_fw_hd_channels, S_IRUGO, arcmsr_attr_host_fw_hd_channels, NULL); struct device_attribute *arcmsr_host_attrs[] = { &dev_attr_host_driver_version, &dev_attr_host_driver_posted_cmd, &dev_attr_host_driver_reset, &dev_attr_host_driver_abort, &dev_attr_host_fw_model, &dev_attr_host_fw_version, &dev_attr_host_fw_request_len, &dev_attr_host_fw_numbers_queue, &dev_attr_host_fw_sdram_size, &dev_attr_host_fw_hd_channels, NULL, };
{ "pile_set_name": "Github" }
import time class HtmlOutput(object): def __init__(self): self.datas = [] def collect_data(self, data): if data is None: return self.datas.append(data) def output_html(self): file_name = time.strftime("%Y-%m-%d_%H-%M-%S") with open("out_%s.html" % file_name, "w", encoding='utf-8') as f_out: f_out.write("<html>") f_out.write(r'<head>' r'<link rel="stylesheet" ' r'href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" ' r'integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" ' r'crossorigin="anonymous"></head>') f_out.write("<body>") f_out.write(r'<table class="table table-bordered table-hover">') item_css = ['active', 'success', 'warning', 'info'] for data in self.datas: index = self.datas.index(data) % len(item_css) f_out.write(r'<tr class="'+item_css[index]+r'">') f_out.write('<td>%s</td>' % data["url"]) f_out.write('<td>%s</td>' % data["title"]) f_out.write('<td>%s</td>' % data["summary"]) f_out.write("</tr>") f_out.write("</table>") f_out.write("</body>") f_out.write("</html>")
{ "pile_set_name": "Github" }
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-applicationcloudwatchloggingoption-cloudwatchloggingoption.html module Stratosphere.ResourceProperties.KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption where import Stratosphere.ResourceImports -- | Full data type definition for -- KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption. -- See -- 'kinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption' -- for a more convenient constructor. data KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption = KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption { _kinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOptionLogStreamARN :: Val Text } deriving (Show, Eq) instance ToJSON KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption where toJSON KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption{..} = object $ catMaybes [ (Just . ("LogStreamARN",) . toJSON) _kinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOptionLogStreamARN ] -- | Constructor for -- 'KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption' -- containing required fields as arguments. kinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption :: Val Text -- ^ 'kavacwlocwloLogStreamARN' -> KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption kinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption logStreamARNarg = KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption { _kinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOptionLogStreamARN = logStreamARNarg } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-kinesisanalyticsv2-applicationcloudwatchloggingoption-cloudwatchloggingoption.html#cfn-kinesisanalyticsv2-applicationcloudwatchloggingoption-cloudwatchloggingoption-logstreamarn kavacwlocwloLogStreamARN :: Lens' KinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOption (Val Text) kavacwlocwloLogStreamARN = lens _kinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOptionLogStreamARN (\s a -> s { _kinesisAnalyticsV2ApplicationCloudWatchLoggingOptionCloudWatchLoggingOptionLogStreamARN = a })
{ "pile_set_name": "Github" }
// Copyright 2018 Espressif Systems (Shanghai) PTE LTD // All rights reserved. #ifndef _AVS_CONFIG_H_ #define _AVS_CONFIG_H_ #include <conn_mgr_prov.h> /** Callback event for provisioning AVS configuration * * This api can be set as the event_cb in conn_mgr_prov_t while starting provisioning if the application * wants to set the alexa_config_t via the companion app. The cb_user_data in conn_mgr_prov_t must also be * set to an allocated alexa_config_t struct pointer. * */ int alexa_conn_mgr_prov_cb(void *user_data, conn_mgr_cb_event_t event); int avs_config_data_handler(uint32_t session_id, const uint8_t *inbuf, ssize_t inlen, uint8_t **outbuf, ssize_t *outlen, void *priv_data); #endif /* _AVS_CONFIG_H_ */
{ "pile_set_name": "Github" }
{% load datepicker_locale from horizon %} {% datepicker_locale as DATEPICKER_LOCALE %} <script src='{{ STATIC_URL }}lib/jquery-1.10.2.js' type='text/javascript' charset='utf-8'></script> <script src='{{ STATIC_URL }}horizon/js/horizon.js' type='text/javascript' charset='utf-8'></script> <script type='text/javascript' charset='utf-8'> // make translation info available on client horizon.languageCode = '{{ LANGUAGE_CODE }}'; horizon.languageBidi = '{{ LANGUAGE_BIDI }}'; horizon.datepickerLocale = '{{ DATEPICKER_LOCALE }}'; STATIC_URL= '{{ STATIC_URL }}'; /* Load angular modules extensions list before we include angular/horizon.js */ var angularModuleExtension = {{ HORIZON_CONFIG.angular_modules|default:"[]"|safe}}; horizon.conf={ ajax: { queue_limit: {{ HORIZON_CONFIG.ajax_queue_limit|default:"null" }} }, auto_fade_alerts: { delay: {{ HORIZON_CONFIG.auto_fade_alerts.delay|default:"3000" }}, fade_duration: {{ HORIZON_CONFIG.auto_fade_alerts.fade_duration|default:"1500" }}, types: {{ HORIZON_CONFIG.auto_fade_alerts.types|default:"[]"|safe }}, spinner_options: { inline: { lines: 10, length: 5, width: 2, radius: 3, color: '#000', speed: 0.8, trail: 50, zIndex: 100 }, modal: { lines: 10, length: 15, width: 4, radius: 10, color: '#000', speed: 0.8, trail: 50 }, line_chart: { lines: 10, length: 15, width: 4, radius: 11, color: '#000', speed: 0.8, trail: 50 } } } }; </script>
{ "pile_set_name": "Github" }
# Exercism as Part of Ada's Ruby Unit ## Introduction [Exercism.io](https://exercism.io) is a free online community that provides programming exercises that are language-specific and TDD-style to encourage code practice and mentorship. On Exercism.io, we should expect to find resources for the following: - Dozens of TDD-style programming practices for Ruby and other languages - Scaffolding for community and mentorship ## How We Assign and Review Exercism At Ada, from time-to-time, **we will assign specific exercises for you to complete.** As a pattern, these will often be over the weekend, and unrelated to our projects. However, they are specifically curated problems to help increase our practice with Ruby, TDD, and problem-solving. In these cases, the following process will happen: - As homework, you will see a specific exercise on Exercism assigned for completion by a certain day - Assuming that Exercism's CLI tool has been setup, installed, and configured onto your laptop, you will use the Exercism CLI tool to download that exercise to your laptop - You will work on and complete a solution to this exercise. A completed solution will pass all of the provided tests. You are not required to submit your solution via Exercism.io, **you are only required to keep your solution on your own local computer** - After the due date, when we review that exercise, we will spend in-class time to check work. At times, we will present submissions to the class ## Setup Exercism has an up-to-date, thorough, and wonderful guide on how to get started. However, here are some important notes: - We recommend that you sign-in using your GitHub account, but this is not necessary (it's just a lot faster) - **You must sign up using the "Practice Mode"** (we require that you do not use "Mentored Mode") - Exercism will, by default, configure all programming exercises to download to a default directory on your computer. **Read through the Terminal output to find out where Exercism downloads your exercises.** With those notes, get started using Exercism using their [Getting Started Guide](https://exercism.io/getting-started) - Sign up for the Ruby track - Follow their directions for getting started on the "Hello World" problem. You can trust and follow their directions for installing their CLI tool and any dependencies - When working on Hello World, check out the files `GETTING_STARTED.md` and `README.md` that are included in that folder ### How to Run the Tests [Exercism has a guide on how to read and run the tests on the Ruby track here.](https://exercism.io/tracks/ruby/tests) ## Problems We Will Assign at Ada With no promise to order or schedule, Ada roughly has plans to assign the following problems: - Hello World - Leap - Hamming - Word Count - Luhn - RNA Transcription - Roman Numeral Reverter ## Using Exercism beyond Ada's Assignments You are free to do other Exercism problems at any time. You are also free to engage with the Exercism community if you wish.
{ "pile_set_name": "Github" }
.\" $OpenBSD: DH_get0_pqg.3,v 1.5 2018/12/21 21:54:48 schwarze Exp $ .\" selective merge up to: OpenSSL 83cf7abf May 29 13:07:08 2018 +0100 .\" .\" This file was written by Matt Caswell <matt@openssl.org>. .\" Copyright (c) 2016, 2018 The OpenSSL Project. 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. All advertising materials mentioning features or use of this .\" software must display the following acknowledgment: .\" "This product includes software developed by the OpenSSL Project .\" for use in the OpenSSL Toolkit. (http://www.openssl.org/)" .\" .\" 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to .\" endorse or promote products derived from this software without .\" prior written permission. For written permission, please contact .\" openssl-core@openssl.org. .\" .\" 5. Products derived from this software may not be called "OpenSSL" .\" nor may "OpenSSL" appear in their names without prior written .\" permission of the OpenSSL Project. .\" .\" 6. Redistributions of any form whatsoever must retain the following .\" acknowledgment: .\" "This product includes software developed by the OpenSSL Project .\" for use in the OpenSSL Toolkit (http://www.openssl.org/)" .\" .\" THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY .\" EXPRESSED 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 OpenSSL PROJECT OR .\" ITS 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. .\" .Dd $Mdocdate: December 21 2018 $ .Dt DH_GET0_PQG 3 .Os .Sh NAME .Nm DH_get0_pqg , .Nm DH_set0_pqg , .Nm DH_get0_key , .Nm DH_set0_key , .Nm DH_clear_flags , .Nm DH_test_flags , .Nm DH_set_flags , .Nm DH_get0_engine , .Nm DH_set_length .Nd get data from and set data in a DH object .Sh SYNOPSIS .In openssl/dh.h .Ft void .Fo DH_get0_pqg .Fa "const DH *dh" .Fa "const BIGNUM **p" .Fa "const BIGNUM **q" .Fa "const BIGNUM **g" .Fc .Ft int .Fo DH_set0_pqg .Fa "DH *dh" .Fa "BIGNUM *p" .Fa "BIGNUM *q" .Fa "BIGNUM *g" .Fc .Ft void .Fo DH_get0_key .Fa "const DH *dh" .Fa "const BIGNUM **pub_key" .Fa "const BIGNUM **priv_key" .Fc .Ft int .Fo DH_set0_key .Fa "DH *dh" .Fa "BIGNUM *pub_key" .Fa "BIGNUM *priv_key" .Fc .Ft void .Fo DH_clear_flags .Fa "DH *dh" .Fa "int flags" .Fc .Ft int .Fo DH_test_flags .Fa "const DH *dh" .Fa "int flags" .Fc .Ft void .Fo DH_set_flags .Fa "DH *dh" .Fa "int flags" .Fc .Ft ENGINE * .Fo DH_get0_engine .Fa "DH *d" .Fc .Ft int .Fo DH_set_length .Fa "DH *dh" .Fa "long length" .Fc .Sh DESCRIPTION A .Vt DH object contains the parameters .Fa p , .Fa g , and optionally .Fa q . It also contains a public key .Fa pub_key and an optional private key .Fa priv_key . .Pp The .Fa p , .Fa q , and .Fa g parameters can be obtained by calling .Fn DH_get0_pqg . If the parameters have not yet been set, then .Pf * Fa p , .Pf * Fa q , and .Pf * Fa g are set to .Dv NULL . Otherwise, they are set to pointers to the internal representations of the values that should not be freed by the application. Any of the out parameters .Fa p , .Fa q , and .Fa g can be .Dv NULL , in which case no value is returned for that parameter. .Pp The .Fa p , .Fa q , and .Fa g values can be set by calling .Fn DH_set0_pqg . Calling this function transfers the memory management of the values to .Fa dh , and therefore they should not be freed by the caller. The .Fa q argument may be .Dv NULL . .Pp The .Fn DH_get0_key function stores pointers to the internal representations of the public key in .Pf * Fa pub_key and to the private key in .Pf * Fa priv_key . Either may be .Dv NULL if it has not yet been set. If the private key has been set, then the public key must be. Any of the out parameters .Fa pub_key and .Fa priv_key can be .Dv NULL , in which case no value is returned for that parameter. .Pp The public and private key values can be set using .Fn DH_set0_key . Either parameter may be .Dv NULL , which means the corresponding .Vt DH field is left untouched. This function transfers the memory management of the key values to .Fa dh , and therefore they should not be freed by the caller. .Pp Values retrieved with .Fn DH_get0_pqg and .Fn DH_get0_key are owned by the .Vt DH object and may therefore not be passed to .Fn DH_set0_pqg or .Fn DH_set0_key . If needed, duplicate the received values using .Xr BN_dup 3 and pass the duplicates. .Pp .Fn DH_clear_flags clears the specified .Fa flags in .Fa dh . .Fn DH_test_flags tests the .Fa flags in .Fa dh . .Fn DH_set_flags sets the .Fa flags in .Fa dh ; any flags already set remain set. For all three functions, multiple flags can be passed in one call, OR'ed together bitwise. .Pp .Fn DH_set_length sets the optional length attribute of .Fa dh , indicating the length of the secret exponent (private key) in bits. If the length attribute is non-zero, it is used, otherwise it is ignored. .Sh RETURN VALUES .Fn DH_set0_pqg , .Fn DH_set0_key , and .Fn DH_set_length return 1 on success or 0 on failure. .Pp .Fn DH_test_flags return those of the given .Fa flags currently set in .Fa dh or 0 if none of the given .Fa flags are set. .Pp .Fn DH_get0_engine returns a pointer to the .Vt ENGINE used by the .Vt DH object .Fa dh , or .Dv NULL if no engine was set for this object. .Sh SEE ALSO .Xr DH_generate_key 3 , .Xr DH_generate_parameters 3 , .Xr DH_new 3 , .Xr DH_size 3 , .Xr DHparams_print 3 .Sh HISTORY These functions first appeared in OpenSSL 1.1.0 and have been available since .Ox 6.3 .
{ "pile_set_name": "Github" }
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import sorl.thumbnail.fields import newsletter.utils import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Article', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('sortorder', models.PositiveIntegerField(help_text='Sort order determines the order in which articles are concatenated in a post.', verbose_name='sort order', db_index=True)), ('title', models.CharField(max_length=200, verbose_name='title')), ('text', models.TextField(verbose_name='text')), ('url', models.URLField(null=True, verbose_name='link', blank=True)), ('image', sorl.thumbnail.fields.ImageField(upload_to='newsletter/images/%Y/%m/%d', null=True, verbose_name='image', blank=True)), ], options={ 'ordering': ('sortorder',), 'verbose_name': 'article', 'verbose_name_plural': 'articles', }, bases=(models.Model,), ), migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=200, verbose_name='title')), ('slug', models.SlugField(verbose_name='slug')), ('date_create', models.DateTimeField(auto_now_add=True, verbose_name='created')), ('date_modify', models.DateTimeField(auto_now=True, verbose_name='modified')), ], options={ 'verbose_name': 'message', 'verbose_name_plural': 'messages', }, bases=(models.Model,), ), migrations.CreateModel( name='Newsletter', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('title', models.CharField(max_length=200, verbose_name='newsletter title')), ('slug', models.SlugField(unique=True)), ('email', models.EmailField(help_text='Sender e-mail', max_length=75, verbose_name='e-mail')), ('sender', models.CharField(help_text='Sender name', max_length=200, verbose_name='sender')), ('visible', models.BooleanField(default=True, db_index=True, verbose_name='visible')), ('send_html', models.BooleanField(default=True, help_text='Whether or not to send HTML versions of e-mails.', verbose_name='send html')), ('site', models.ManyToManyField(default=newsletter.utils.get_default_sites, to='sites.Site')), ], options={ 'verbose_name': 'newsletter', 'verbose_name_plural': 'newsletters', }, bases=(models.Model,), ), migrations.CreateModel( name='Submission', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('publish_date', models.DateTimeField(default=django.utils.timezone.now, null=True, verbose_name='publication date', db_index=True, blank=True)), ('publish', models.BooleanField(default=True, help_text='Publish in archive.', db_index=True, verbose_name='publish')), ('prepared', models.BooleanField(default=False, verbose_name='prepared', db_index=True, editable=False)), ('sent', models.BooleanField(default=False, verbose_name='sent', db_index=True, editable=False)), ('sending', models.BooleanField(default=False, verbose_name='sending', db_index=True, editable=False)), ('message', models.ForeignKey(verbose_name='message', to='newsletter.Message', on_delete=models.CASCADE)), ('newsletter', models.ForeignKey(editable=False, to='newsletter.Newsletter', verbose_name='newsletter', on_delete=models.CASCADE)), ], options={ 'verbose_name': 'submission', 'verbose_name_plural': 'submissions', }, bases=(models.Model,), ), migrations.CreateModel( name='Subscription', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name_field', models.CharField(db_column='name', max_length=30, blank=True, help_text='optional', null=True, verbose_name='name')), ('email_field', models.EmailField(db_column='email', max_length=75, blank=True, null=True, verbose_name='e-mail', db_index=True)), ('ip', models.IPAddressField(null=True, verbose_name='IP address', blank=True)), ('create_date', models.DateTimeField(default=django.utils.timezone.now, editable=False)), ('activation_code', models.CharField(default=newsletter.utils.make_activation_code, max_length=40, verbose_name='activation code')), ('subscribed', models.BooleanField(default=False, db_index=True, verbose_name='subscribed')), ('subscribe_date', models.DateTimeField(null=True, verbose_name='subscribe date', blank=True)), ('unsubscribed', models.BooleanField(default=False, db_index=True, verbose_name='unsubscribed')), ('unsubscribe_date', models.DateTimeField(null=True, verbose_name='unsubscribe date', blank=True)), ('newsletter', models.ForeignKey(verbose_name='newsletter', to='newsletter.Newsletter', on_delete=models.CASCADE)), ('user', models.ForeignKey(verbose_name='user', blank=True, to=settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)), ], options={ 'verbose_name': 'subscription', 'verbose_name_plural': 'subscriptions', }, bases=(models.Model,), ), migrations.AlterUniqueTogether( name='subscription', unique_together=set([('user', 'email_field', 'newsletter')]), ), migrations.AddField( model_name='submission', name='subscriptions', field=models.ManyToManyField(help_text='If you select none, the system will automatically find the subscribers for you.', to='newsletter.Subscription', db_index=True, verbose_name='recipients', blank=True), preserve_default=True, ), migrations.AddField( model_name='message', name='newsletter', field=models.ForeignKey(verbose_name='newsletter', to='newsletter.Newsletter', on_delete=models.CASCADE), preserve_default=True, ), migrations.AlterUniqueTogether( name='message', unique_together=set([('slug', 'newsletter')]), ), migrations.AddField( model_name='article', name='post', field=models.ForeignKey(related_name='articles', verbose_name='message', to='newsletter.Message', on_delete=models.CASCADE), preserve_default=True, ), ]
{ "pile_set_name": "Github" }
var baseInverter = require('./_baseInverter'); /** * Creates a function like `_.invertBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} toIteratee The function to resolve iteratees. * @returns {Function} Returns the new inverter function. */ function createInverter(setter, toIteratee) { return function(object, iteratee) { return baseInverter(object, setter, toIteratee(iteratee), {}); }; } module.exports = createInverter;
{ "pile_set_name": "Github" }
// Copyright 2012 Neal van Veen. All rights reserved. // Usage of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package gotty // Boolean capabilities var BoolAttr = [...]string{ "auto_left_margin", "bw", "auto_right_margin", "am", "no_esc_ctlc", "xsb", "ceol_standout_glitch", "xhp", "eat_newline_glitch", "xenl", "erase_overstrike", "eo", "generic_type", "gn", "hard_copy", "hc", "has_meta_key", "km", "has_status_line", "hs", "insert_null_glitch", "in", "memory_above", "da", "memory_below", "db", "move_insert_mode", "mir", "move_standout_mode", "msgr", "over_strike", "os", "status_line_esc_ok", "eslok", "dest_tabs_magic_smso", "xt", "tilde_glitch", "hz", "transparent_underline", "ul", "xon_xoff", "nxon", "needs_xon_xoff", "nxon", "prtr_silent", "mc5i", "hard_cursor", "chts", "non_rev_rmcup", "nrrmc", "no_pad_char", "npc", "non_dest_scroll_region", "ndscr", "can_change", "ccc", "back_color_erase", "bce", "hue_lightness_saturation", "hls", "col_addr_glitch", "xhpa", "cr_cancels_micro_mode", "crxm", "has_print_wheel", "daisy", "row_addr_glitch", "xvpa", "semi_auto_right_margin", "sam", "cpi_changes_res", "cpix", "lpi_changes_res", "lpix", "backspaces_with_bs", "", "crt_no_scrolling", "", "no_correctly_working_cr", "", "gnu_has_meta_key", "", "linefeed_is_newline", "", "has_hardware_tabs", "", "return_does_clr_eol", "", } // Numerical capabilities var NumAttr = [...]string{ "columns", "cols", "init_tabs", "it", "lines", "lines", "lines_of_memory", "lm", "magic_cookie_glitch", "xmc", "padding_baud_rate", "pb", "virtual_terminal", "vt", "width_status_line", "wsl", "num_labels", "nlab", "label_height", "lh", "label_width", "lw", "max_attributes", "ma", "maximum_windows", "wnum", "max_colors", "colors", "max_pairs", "pairs", "no_color_video", "ncv", "buffer_capacity", "bufsz", "dot_vert_spacing", "spinv", "dot_horz_spacing", "spinh", "max_micro_address", "maddr", "max_micro_jump", "mjump", "micro_col_size", "mcs", "micro_line_size", "mls", "number_of_pins", "npins", "output_res_char", "orc", "output_res_line", "orl", "output_res_horz_inch", "orhi", "output_res_vert_inch", "orvi", "print_rate", "cps", "wide_char_size", "widcs", "buttons", "btns", "bit_image_entwining", "bitwin", "bit_image_type", "bitype", "magic_cookie_glitch_ul", "", "carriage_return_delay", "", "new_line_delay", "", "backspace_delay", "", "horizontal_tab_delay", "", "number_of_function_keys", "", } // String capabilities var StrAttr = [...]string{ "back_tab", "cbt", "bell", "bel", "carriage_return", "cr", "change_scroll_region", "csr", "clear_all_tabs", "tbc", "clear_screen", "clear", "clr_eol", "el", "clr_eos", "ed", "column_address", "hpa", "command_character", "cmdch", "cursor_address", "cup", "cursor_down", "cud1", "cursor_home", "home", "cursor_invisible", "civis", "cursor_left", "cub1", "cursor_mem_address", "mrcup", "cursor_normal", "cnorm", "cursor_right", "cuf1", "cursor_to_ll", "ll", "cursor_up", "cuu1", "cursor_visible", "cvvis", "delete_character", "dch1", "delete_line", "dl1", "dis_status_line", "dsl", "down_half_line", "hd", "enter_alt_charset_mode", "smacs", "enter_blink_mode", "blink", "enter_bold_mode", "bold", "enter_ca_mode", "smcup", "enter_delete_mode", "smdc", "enter_dim_mode", "dim", "enter_insert_mode", "smir", "enter_secure_mode", "invis", "enter_protected_mode", "prot", "enter_reverse_mode", "rev", "enter_standout_mode", "smso", "enter_underline_mode", "smul", "erase_chars", "ech", "exit_alt_charset_mode", "rmacs", "exit_attribute_mode", "sgr0", "exit_ca_mode", "rmcup", "exit_delete_mode", "rmdc", "exit_insert_mode", "rmir", "exit_standout_mode", "rmso", "exit_underline_mode", "rmul", "flash_screen", "flash", "form_feed", "ff", "from_status_line", "fsl", "init_1string", "is1", "init_2string", "is2", "init_3string", "is3", "init_file", "if", "insert_character", "ich1", "insert_line", "il1", "insert_padding", "ip", "key_backspace", "kbs", "key_catab", "ktbc", "key_clear", "kclr", "key_ctab", "kctab", "key_dc", "kdch1", "key_dl", "kdl1", "key_down", "kcud1", "key_eic", "krmir", "key_eol", "kel", "key_eos", "ked", "key_f0", "kf0", "key_f1", "kf1", "key_f10", "kf10", "key_f2", "kf2", "key_f3", "kf3", "key_f4", "kf4", "key_f5", "kf5", "key_f6", "kf6", "key_f7", "kf7", "key_f8", "kf8", "key_f9", "kf9", "key_home", "khome", "key_ic", "kich1", "key_il", "kil1", "key_left", "kcub1", "key_ll", "kll", "key_npage", "knp", "key_ppage", "kpp", "key_right", "kcuf1", "key_sf", "kind", "key_sr", "kri", "key_stab", "khts", "key_up", "kcuu1", "keypad_local", "rmkx", "keypad_xmit", "smkx", "lab_f0", "lf0", "lab_f1", "lf1", "lab_f10", "lf10", "lab_f2", "lf2", "lab_f3", "lf3", "lab_f4", "lf4", "lab_f5", "lf5", "lab_f6", "lf6", "lab_f7", "lf7", "lab_f8", "lf8", "lab_f9", "lf9", "meta_off", "rmm", "meta_on", "smm", "newline", "_glitch", "pad_char", "npc", "parm_dch", "dch", "parm_delete_line", "dl", "parm_down_cursor", "cud", "parm_ich", "ich", "parm_index", "indn", "parm_insert_line", "il", "parm_left_cursor", "cub", "parm_right_cursor", "cuf", "parm_rindex", "rin", "parm_up_cursor", "cuu", "pkey_key", "pfkey", "pkey_local", "pfloc", "pkey_xmit", "pfx", "print_screen", "mc0", "prtr_off", "mc4", "prtr_on", "mc5", "repeat_char", "rep", "reset_1string", "rs1", "reset_2string", "rs2", "reset_3string", "rs3", "reset_file", "rf", "restore_cursor", "rc", "row_address", "mvpa", "save_cursor", "row_address", "scroll_forward", "ind", "scroll_reverse", "ri", "set_attributes", "sgr", "set_tab", "hts", "set_window", "wind", "tab", "s_magic_smso", "to_status_line", "tsl", "underline_char", "uc", "up_half_line", "hu", "init_prog", "iprog", "key_a1", "ka1", "key_a3", "ka3", "key_b2", "kb2", "key_c1", "kc1", "key_c3", "kc3", "prtr_non", "mc5p", "char_padding", "rmp", "acs_chars", "acsc", "plab_norm", "pln", "key_btab", "kcbt", "enter_xon_mode", "smxon", "exit_xon_mode", "rmxon", "enter_am_mode", "smam", "exit_am_mode", "rmam", "xon_character", "xonc", "xoff_character", "xoffc", "ena_acs", "enacs", "label_on", "smln", "label_off", "rmln", "key_beg", "kbeg", "key_cancel", "kcan", "key_close", "kclo", "key_command", "kcmd", "key_copy", "kcpy", "key_create", "kcrt", "key_end", "kend", "key_enter", "kent", "key_exit", "kext", "key_find", "kfnd", "key_help", "khlp", "key_mark", "kmrk", "key_message", "kmsg", "key_move", "kmov", "key_next", "knxt", "key_open", "kopn", "key_options", "kopt", "key_previous", "kprv", "key_print", "kprt", "key_redo", "krdo", "key_reference", "kref", "key_refresh", "krfr", "key_replace", "krpl", "key_restart", "krst", "key_resume", "kres", "key_save", "ksav", "key_suspend", "kspd", "key_undo", "kund", "key_sbeg", "kBEG", "key_scancel", "kCAN", "key_scommand", "kCMD", "key_scopy", "kCPY", "key_screate", "kCRT", "key_sdc", "kDC", "key_sdl", "kDL", "key_select", "kslt", "key_send", "kEND", "key_seol", "kEOL", "key_sexit", "kEXT", "key_sfind", "kFND", "key_shelp", "kHLP", "key_shome", "kHOM", "key_sic", "kIC", "key_sleft", "kLFT", "key_smessage", "kMSG", "key_smove", "kMOV", "key_snext", "kNXT", "key_soptions", "kOPT", "key_sprevious", "kPRV", "key_sprint", "kPRT", "key_sredo", "kRDO", "key_sreplace", "kRPL", "key_sright", "kRIT", "key_srsume", "kRES", "key_ssave", "kSAV", "key_ssuspend", "kSPD", "key_sundo", "kUND", "req_for_input", "rfi", "key_f11", "kf11", "key_f12", "kf12", "key_f13", "kf13", "key_f14", "kf14", "key_f15", "kf15", "key_f16", "kf16", "key_f17", "kf17", "key_f18", "kf18", "key_f19", "kf19", "key_f20", "kf20", "key_f21", "kf21", "key_f22", "kf22", "key_f23", "kf23", "key_f24", "kf24", "key_f25", "kf25", "key_f26", "kf26", "key_f27", "kf27", "key_f28", "kf28", "key_f29", "kf29", "key_f30", "kf30", "key_f31", "kf31", "key_f32", "kf32", "key_f33", "kf33", "key_f34", "kf34", "key_f35", "kf35", "key_f36", "kf36", "key_f37", "kf37", "key_f38", "kf38", "key_f39", "kf39", "key_f40", "kf40", "key_f41", "kf41", "key_f42", "kf42", "key_f43", "kf43", "key_f44", "kf44", "key_f45", "kf45", "key_f46", "kf46", "key_f47", "kf47", "key_f48", "kf48", "key_f49", "kf49", "key_f50", "kf50", "key_f51", "kf51", "key_f52", "kf52", "key_f53", "kf53", "key_f54", "kf54", "key_f55", "kf55", "key_f56", "kf56", "key_f57", "kf57", "key_f58", "kf58", "key_f59", "kf59", "key_f60", "kf60", "key_f61", "kf61", "key_f62", "kf62", "key_f63", "kf63", "clr_bol", "el1", "clear_margins", "mgc", "set_left_margin", "smgl", "set_right_margin", "smgr", "label_format", "fln", "set_clock", "sclk", "display_clock", "dclk", "remove_clock", "rmclk", "create_window", "cwin", "goto_window", "wingo", "hangup", "hup", "dial_phone", "dial", "quick_dial", "qdial", "tone", "tone", "pulse", "pulse", "flash_hook", "hook", "fixed_pause", "pause", "wait_tone", "wait", "user0", "u0", "user1", "u1", "user2", "u2", "user3", "u3", "user4", "u4", "user5", "u5", "user6", "u6", "user7", "u7", "user8", "u8", "user9", "u9", "orig_pair", "op", "orig_colors", "oc", "initialize_color", "initc", "initialize_pair", "initp", "set_color_pair", "scp", "set_foreground", "setf", "set_background", "setb", "change_char_pitch", "cpi", "change_line_pitch", "lpi", "change_res_horz", "chr", "change_res_vert", "cvr", "define_char", "defc", "enter_doublewide_mode", "swidm", "enter_draft_quality", "sdrfq", "enter_italics_mode", "sitm", "enter_leftward_mode", "slm", "enter_micro_mode", "smicm", "enter_near_letter_quality", "snlq", "enter_normal_quality", "snrmq", "enter_shadow_mode", "sshm", "enter_subscript_mode", "ssubm", "enter_superscript_mode", "ssupm", "enter_upward_mode", "sum", "exit_doublewide_mode", "rwidm", "exit_italics_mode", "ritm", "exit_leftward_mode", "rlm", "exit_micro_mode", "rmicm", "exit_shadow_mode", "rshm", "exit_subscript_mode", "rsubm", "exit_superscript_mode", "rsupm", "exit_upward_mode", "rum", "micro_column_address", "mhpa", "micro_down", "mcud1", "micro_left", "mcub1", "micro_right", "mcuf1", "micro_row_address", "mvpa", "micro_up", "mcuu1", "order_of_pins", "porder", "parm_down_micro", "mcud", "parm_left_micro", "mcub", "parm_right_micro", "mcuf", "parm_up_micro", "mcuu", "select_char_set", "scs", "set_bottom_margin", "smgb", "set_bottom_margin_parm", "smgbp", "set_left_margin_parm", "smglp", "set_right_margin_parm", "smgrp", "set_top_margin", "smgt", "set_top_margin_parm", "smgtp", "start_bit_image", "sbim", "start_char_set_def", "scsd", "stop_bit_image", "rbim", "stop_char_set_def", "rcsd", "subscript_characters", "subcs", "superscript_characters", "supcs", "these_cause_cr", "docr", "zero_motion", "zerom", "char_set_names", "csnm", "key_mouse", "kmous", "mouse_info", "minfo", "req_mouse_pos", "reqmp", "get_mouse", "getm", "set_a_foreground", "setaf", "set_a_background", "setab", "pkey_plab", "pfxl", "device_type", "devt", "code_set_init", "csin", "set0_des_seq", "s0ds", "set1_des_seq", "s1ds", "set2_des_seq", "s2ds", "set3_des_seq", "s3ds", "set_lr_margin", "smglr", "set_tb_margin", "smgtb", "bit_image_repeat", "birep", "bit_image_newline", "binel", "bit_image_carriage_return", "bicr", "color_names", "colornm", "define_bit_image_region", "defbi", "end_bit_image_region", "endbi", "set_color_band", "setcolor", "set_page_length", "slines", "display_pc_char", "dispc", "enter_pc_charset_mode", "smpch", "exit_pc_charset_mode", "rmpch", "enter_scancode_mode", "smsc", "exit_scancode_mode", "rmsc", "pc_term_options", "pctrm", "scancode_escape", "scesc", "alt_scancode_esc", "scesa", "enter_horizontal_hl_mode", "ehhlm", "enter_left_hl_mode", "elhlm", "enter_low_hl_mode", "elohlm", "enter_right_hl_mode", "erhlm", "enter_top_hl_mode", "ethlm", "enter_vertical_hl_mode", "evhlm", "set_a_attributes", "sgr1", "set_pglen_inch", "slength", "termcap_init2", "", "termcap_reset", "", "linefeed_if_not_lf", "", "backspace_if_not_bs", "", "other_non_function_keys", "", "arrow_key_map", "", "acs_ulcorner", "", "acs_llcorner", "", "acs_urcorner", "", "acs_lrcorner", "", "acs_ltee", "", "acs_rtee", "", "acs_btee", "", "acs_ttee", "", "acs_hline", "", "acs_vline", "", "acs_plus", "", "memory_lock", "", "memory_unlock", "", "box_chars_1", "", }
{ "pile_set_name": "Github" }
#!/usr/bin/perl # ******************************************************************** # * Copyright (C) 2016 and later: Unicode, Inc. and others. # * License & terms of use: http://www.unicode.org/copyright.html # ******************************************************************** # ******************************************************************** # * COPYRIGHT: # * Copyright (c) 2002-2013, International Business Machines Corporation and # * others. All Rights Reserved. # ******************************************************************** #use strict; require "../perldriver/Common.pl"; use lib '../perldriver'; use PerfFramework; # This test only works on Windows. if (!$OnWindows) { print "This test only works on Windows.\n"; exit(1); } my $options = { "title"=>"Conversion Performance: ICU".$ICULatestVersion." vs. WindowsXP IMultiLanguage Interface", "headers"=>"WindowsXP(IMultiLanguage2) ICU".$ICULatestVersion, "operationIs"=>"code point", "passes"=>"10", "time"=>"5", #"outputType"=>"HTML", "dataDir"=>"Not Using Data Files", "outputDir"=>"../results" }; # programs # tests will be done for all the programs. Results will be stored and connected my $p = "cd ".$ICULatest."/bin && ".$ICUPathLatest."/convperf/$WindowsPlatform/Release/convperf.exe"; my $tests = { "UTF-8 From Unicode", ["$p,TestWinIML2_UTF8_FromUnicode" , "$p,TestICU_UTF8_FromUnicode" ], "UTF-8 To Unicode", ["$p,TestWinIML2_UTF8_ToUnicode" , "$p,TestICU_UTF8_ToUnicode" ], #### "ISO-8859-1 From Unicode", ["$p,TestWinIML2_Latin1_FromUnicode" , "$p,TestICU_Latin1_FromUnicode" ], "ISO-8859-1 To Unicode", ["$p,TestWinIML2_Latin1_ToUnicode" , "$p,TestICU_Latin1_ToUnicode" ], #### "Shift-JIS From Unicode", ["$p,TestWinIML2_SJIS_FromUnicode" , "$p,TestICU_SJIS_FromUnicode" ], "Shift-JIS To Unicode", ["$p,TestWinIML2_SJIS_ToUnicode" , "$p,TestICU_SJIS_ToUnicode" ], #### "EUC-JP From Unicode", ["$p,TestWinIML2_EUCJP_FromUnicode" , "$p,TestICU_EUCJP_FromUnicode" ], "EUC-JP To Unicode", ["$p,TestWinIML2_EUCJP_ToUnicode" , "$p,TestICU_EUCJP_ToUnicode" ], #### "GB2312 From Unicode", ["$p,TestWinIML2_GB2312_FromUnicode" , "$p,TestICU_GB2312_FromUnicode" ], "GB2312 To Unicode", ["$p,TestWinIML2_GB2312_ToUnicode" , "$p,TestICU_GB2312_ToUnicode" ], #### "ISO2022KR From Unicode", ["$p,TestWinIML2_ISO2022KR_FromUnicode", "$p,TestICU_ISO2022KR_FromUnicode" ], "ISO2022KR To Unicode", ["$p,TestWinIML2_ISO2022KR_ToUnicode" , "$p,TestICU_ISO2022KR_ToUnicode" ], #### "ISO2022JP From Unicode", ["$p,TestWinIML2_ISO2022JP_FromUnicode", "$p,TestICU_ISO2022JP_FromUnicode" ], "ISO2022JP To Unicode", ["$p,TestWinIML2_ISO2022JP_ToUnicode" , "$p,TestICU_ISO2022JP_ToUnicode" ], }; my $dataFiles = ""; runTests($options, $tests, $dataFiles);
{ "pile_set_name": "Github" }
# File src/library/base/R/srcfile.R # Part of the R package, https://www.R-project.org # # Copyright (C) 1995-2017 The R Core Team # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # A copy of the GNU General Public License is available at # https://www.R-project.org/Licenses/ # a srcfile is a file with a timestamp srcfile <- function(filename, encoding = getOption("encoding"), Enc = "unknown") { stopifnot(is.character(filename), length(filename) == 1L) ## This is small, no need to hash. e <- new.env(hash = FALSE, parent = emptyenv()) e$wd <- getwd() e$filename <- filename # If filename is a URL, this will return NA e$timestamp <- file.mtime(filename) if (identical(encoding, "unknown")) encoding <- "native.enc" e$encoding <- encoding e$Enc <- Enc class(e) <- "srcfile" return(e) } print.srcfile <- function(x, ...) { cat(x$filename, "\n") invisible(x) } summary.srcfile <- function(object, ...) { cat(utils:::.normalizePath(object$filename, object$wd), "\n") if (inherits(object$timestamp, "POSIXt")) cat("Timestamp: ", format(object$timestamp, usetz=TRUE), "\n", sep="") cat('Encoding: "', object$encoding, '"', sep="") if (!is.null(object$Enc) && object$Enc != object$encoding && object$Enc != "unknown") cat(', re-encoded to "', object$Enc, '"', sep="") cat("\n") invisible(object) } open.srcfile <- function(con, line, ...) { srcfile <- con oldline <- srcfile$line if (!is.null(oldline) && oldline > line) close(srcfile) conn <- srcfile$conn if (is.null(conn)) { if (!is.null(srcfile$wd)) { olddir <- setwd(srcfile$wd) on.exit(setwd(olddir)) } timestamp <- file.mtime(srcfile$filename) if (!is.null(srcfile$timestamp) && !is.na(srcfile$timestamp) && ( is.na(timestamp) || timestamp != srcfile$timestamp) ) warning(gettextf("Timestamp of %s has changed", sQuote(srcfile$filename)), call. = FALSE, domain = NA) if (is.null(srcfile$encoding)) encoding <- getOption("encoding") else encoding <- srcfile$encoding # Specifying encoding below means that reads will convert to the native encoding srcfile$conn <- conn <- file(srcfile$filename, open="rt", encoding=encoding) srcfile$line <- 1L oldline <- 1L } else if (!isOpen(conn)) { open(conn, open="rt") srcfile$line <- 1 oldline <- 1L } if (oldline < line) { readLines(conn, line - oldline, warn = FALSE) srcfile$line <- line } invisible(conn) } close.srcfile <- function(con, ...) { srcfile <- con conn <- srcfile$conn if (is.null(conn)) return() else { close(conn) rm(list=c("conn", "line"), envir=srcfile) } } # srcfilecopy saves a copy of lines from a file srcfilecopy <- function(filename, lines, timestamp = Sys.time(), isFile = FALSE) { stopifnot(is.character(filename), length(filename) == 1L) e <- new.env(parent=emptyenv()) # Remove embedded newlines if (any(grepl("\n", lines, fixed = TRUE, useBytes = TRUE))) lines <- unlist(strsplit(sub("$", "\n", as.character(lines)), "\n")) e$filename <- filename e$wd <- getwd() e$isFile <- isFile e$lines <- as.character(lines) e$fixedNewlines <- TRUE # we have removed the newlines already e$timestamp <- timestamp e$Enc <- "unknown" class(e) <- c("srcfilecopy", "srcfile") return(e) } open.srcfilecopy <- function(con, line, ...) { srcfile <- con oldline <- srcfile$line if (!is.null(oldline) && oldline > line) close(srcfile) conn <- srcfile$conn if (is.null(conn)) { srcfile$conn <- conn <- textConnection(srcfile$lines, open="r") srcfile$line <- 1L oldline <- 1L } else if (!isOpen(conn)) { open(conn, open="r") srcfile$line <- 1L oldline <- 1L } if (oldline < line) { readLines(conn, line - oldline, warn = FALSE) srcfile$line <- line } invisible(conn) } srcfilealias <- function(filename, srcfile) { stopifnot(is.character(filename), length(filename) == 1L) e <- new.env(parent=emptyenv()) e$filename <- filename e$original <- srcfile class(e) <- c("srcfilealias", "srcfile") return(e) } open.srcfilealias <- function(con, line, ...) open(con$original, line, ...) close.srcfilealias <- function(con, ...) close(con$original, ...) .isOpen <- function(srcfile) { conn <- srcfile$conn return( !is.null(conn) && isOpen(conn) ) } getSrcLines <- function(srcfile, first, last) { if (first > last) return(character()) if (inherits(srcfile, "srcfilealias")) srcfile <- srcfile$original if (inherits(srcfile, "srcfilecopy")) { # Remove embedded newlines if we haven't done this already if (is.null(srcfile$fixedNewlines)) { lines <- srcfile$lines if (any(grepl("\n", lines, fixed = TRUE, useBytes = TRUE))) srcfile$lines <- unlist(strsplit(sub("$", "\n", as.character(lines)), "\n")) srcfile$fixedNewlines <- TRUE } last <- min(last, length(srcfile$lines)) if (first > last) return(character()) else return(srcfile$lines[first:last]) } if (!.isOpen(srcfile)) on.exit(close(srcfile)) conn <- open(srcfile, first) lines <- readLines(conn, n = last - first + 1L, warn = FALSE) # Re-encode from native encoding to specified one if (!is.null(Enc <- srcfile$Enc) && !(Enc %in% c("unknown", "native.enc"))) lines <- iconv(lines, "", Enc) srcfile$line <- first + length(lines) return(lines) } # a srcref gives start and stop positions of text # lloc entries are first_line, first_byte, last_line, last_byte, # first_column, last_column, first_parse, last_parse # all are inclusive srcref <- function(srcfile, lloc) { stopifnot(inherits(srcfile, "srcfile"), length(lloc) %in% c(4L,6L,8L)) if (length(lloc) == 4) lloc <- c(lloc, lloc[c(2,4)]) if (length(lloc) == 6) lloc <- c(lloc, lloc[c(1,3)]) structure(as.integer(lloc), srcfile=srcfile, class="srcref") } as.character.srcref <- function(x, useSource = TRUE, to = x, ...) { srcfile <- attr(x, "srcfile") if (!missing(to)) { if (!identical(srcfile, attr(to, "srcfile"))) stop("'x' and 'to' must refer to same file") x[c(3L, 4L, 6L, 8L)] <- to[c(3L, 4L, 6L, 8L)] } if (!is.null(srcfile) && !inherits(srcfile, "srcfile")) { cat("forcing class on") ## debug print(utils::str(srcfile)) class(srcfile) <- c("srcfilealias", "srcfile") } if (useSource) { if (inherits(srcfile, "srcfilecopy") || inherits(srcfile, "srcfilealias")) lines <- try(getSrcLines(srcfile, x[7L], x[8L]), TRUE) else lines <- try(getSrcLines(srcfile, x[1L], x[3L]), TRUE) } if (!useSource || inherits(lines, "try-error")) lines <- paste0("<srcref: file \"", srcfile$filename, "\" chars ", x[1L], ":", x[5L], " to ", x[3L], ":", x[6L], ">") else if (length(lines)) { enc <- Encoding(lines) Encoding(lines) <- "latin1" # so byte counting works if (length(lines) < x[3L] - x[1L] + 1L) x[4L] <- .Machine$integer.max lines[length(lines)] <- substring(lines[length(lines)], 1L, x[4L]) lines[1L] <- substring(lines[1L], x[2L]) Encoding(lines) <- enc } lines } print.srcref <- function(x, useSource = TRUE, ...) { cat(as.character(x, useSource = useSource), sep="\n") invisible(x) } summary.srcref <- function(object, useSource = FALSE, ...) { cat(as.character(object, useSource = useSource), sep="\n") invisible(object) }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2015-2018 Alibaba Group Holding Limited */ #ifndef _DM_FOTA_H_ #define _DM_FOTA_H_ typedef struct { int is_report_new_config; } dm_fota_ctx_t; int dm_fota_init(void); int dm_fota_deinit(void); int dm_fota_perform_sync(_OU_ char *output, _IN_ int output_len); int dm_fota_status_check(void); int dm_fota_request_image(_IN_ const char *version, _IN_ int buffer_len); #endif
{ "pile_set_name": "Github" }
import { patch } from 'web/runtime/patch' import VNode, { createEmptyVNode } from 'core/vdom/vnode' function prop (name) { return obj => { return obj[name] } } function map (fn, list) { const ret = [] for (let i = 0; i < list.length; i++) { ret[i] = fn(list[i]) } return ret } function spanNum (n) { if (typeof n === 'string') { return new VNode('span', {}, undefined, n) } else { return new VNode('span', { key: n }, undefined, n.toString()) } } function shuffle (array) { let currentIndex = array.length let temporaryValue let randomIndex // while there remain elements to shuffle... while (currentIndex !== 0) { // pick a remaining element... randomIndex = Math.floor(Math.random() * currentIndex) currentIndex -= 1 // and swap it with the current element. temporaryValue = array[currentIndex] array[currentIndex] = array[randomIndex] array[randomIndex] = temporaryValue } return array } const inner = prop('innerHTML') const tag = prop('tagName') describe('vdom patch: children', () => { let vnode0 beforeEach(() => { vnode0 = new VNode('p', { attrs: { id: '1' }}, [createTextVNode('hello world')]) patch(null, vnode0) }) it('should appends elements', () => { const vnode1 = new VNode('p', {}, [1].map(spanNum)) const vnode2 = new VNode('p', {}, [1, 2, 3].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(1) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(3) expect(elm.children[1].innerHTML).toBe('2') expect(elm.children[2].innerHTML).toBe('3') }) it('should prepends elements', () => { const vnode1 = new VNode('p', {}, [4, 5].map(spanNum)) const vnode2 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(2) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['1', '2', '3', '4', '5']) }) it('should add elements in the middle', () => { const vnode1 = new VNode('p', {}, [1, 2, 4, 5].map(spanNum)) const vnode2 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(4) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['1', '2', '3', '4', '5']) }) it('should add elements at begin and end', () => { const vnode1 = new VNode('p', {}, [2, 3, 4].map(spanNum)) const vnode2 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(3) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['1', '2', '3', '4', '5']) }) it('should add children to parent with no children', () => { const vnode1 = new VNode('p', { key: 'p' }) const vnode2 = new VNode('p', { key: 'p' }, [1, 2, 3].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(0) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['1', '2', '3']) }) it('should remove all children from parent', () => { const vnode1 = new VNode('p', { key: 'p' }, [1, 2, 3].map(spanNum)) const vnode2 = new VNode('p', { key: 'p' }) let elm = patch(vnode0, vnode1) expect(map(inner, elm.children)).toEqual(['1', '2', '3']) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(0) }) it('should remove elements from the beginning', () => { const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum)) const vnode2 = new VNode('p', {}, [3, 4, 5].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(5) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['3', '4', '5']) }) it('should removes elements from end', () => { const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum)) const vnode2 = new VNode('p', {}, [1, 2, 3].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(5) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(3) expect(map(inner, elm.children)).toEqual(['1', '2', '3']) }) it('should remove elements from the middle', () => { const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum)) const vnode2 = new VNode('p', {}, [1, 2, 4, 5].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(5) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(4) expect(map(inner, elm.children)).toEqual(['1', '2', '4', '5']) }) it('should moves element forward', () => { const vnode1 = new VNode('p', {}, [1, 2, 3, 4].map(spanNum)) const vnode2 = new VNode('p', {}, [2, 3, 1, 4].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(4) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(4) expect(map(inner, elm.children)).toEqual(['2', '3', '1', '4']) }) it('should move elements to end', () => { const vnode1 = new VNode('p', {}, [1, 2, 3].map(spanNum)) const vnode2 = new VNode('p', {}, [2, 3, 1].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(3) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(3) expect(map(inner, elm.children)).toEqual(['2', '3', '1']) }) it('should move element backwards', () => { const vnode1 = new VNode('p', {}, [1, 2, 3, 4].map(spanNum)) const vnode2 = new VNode('p', {}, [1, 4, 2, 3].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(4) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(4) expect(map(inner, elm.children)).toEqual(['1', '4', '2', '3']) }) it('should swap first and last', () => { const vnode1 = new VNode('p', {}, [1, 2, 3, 4].map(spanNum)) const vnode2 = new VNode('p', {}, [4, 2, 3, 1].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(4) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(4) expect(map(inner, elm.children)).toEqual(['4', '2', '3', '1']) }) it('should move to left and replace', () => { const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5].map(spanNum)) const vnode2 = new VNode('p', {}, [4, 1, 2, 3, 6].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(5) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(5) expect(map(inner, elm.children)).toEqual(['4', '1', '2', '3', '6']) }) it('should move to left and leaves hold', () => { const vnode1 = new VNode('p', {}, [1, 4, 5].map(spanNum)) const vnode2 = new VNode('p', {}, [4, 6].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(3) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['4', '6']) }) it('should handle moved and set to undefined element ending at the end', () => { const vnode1 = new VNode('p', {}, [2, 4, 5].map(spanNum)) const vnode2 = new VNode('p', {}, [4, 5, 3].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(3) elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(3) expect(map(inner, elm.children)).toEqual(['4', '5', '3']) }) it('should move a key in non-keyed nodes with a size up', () => { const vnode1 = new VNode('p', {}, [1, 'a', 'b', 'c'].map(spanNum)) const vnode2 = new VNode('p', {}, ['d', 'a', 'b', 'c', 1, 'e'].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(4) expect(elm.textContent, '1abc') elm = patch(vnode1, vnode2) expect(elm.children.length).toBe(6) expect(elm.textContent, 'dabc1e') }) it('should reverse element', () => { const vnode1 = new VNode('p', {}, [1, 2, 3, 4, 5, 6, 7, 8].map(spanNum)) const vnode2 = new VNode('p', {}, [8, 7, 6, 5, 4, 3, 2, 1].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(8) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['8', '7', '6', '5', '4', '3', '2', '1']) }) it('something', () => { const vnode1 = new VNode('p', {}, [0, 1, 2, 3, 4, 5].map(spanNum)) const vnode2 = new VNode('p', {}, [4, 3, 2, 1, 5, 0].map(spanNum)) let elm = patch(vnode0, vnode1) expect(elm.children.length).toBe(6) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['4', '3', '2', '1', '5', '0']) }) it('should handle random shuffle', () => { let n let i const arr = [] const opacities = [] const elms = 14 const samples = 5 function spanNumWithOpacity (n, o) { return new VNode('span', { key: n, style: { opacity: o }}, undefined, n.toString()) } for (n = 0; n < elms; ++n) { arr[n] = n } for (n = 0; n < samples; ++n) { const vnode1 = new VNode('span', {}, arr.map(n => { return spanNumWithOpacity(n, '1') })) const shufArr = shuffle(arr.slice(0)) let elm = patch(vnode0, vnode1) for (i = 0; i < elms; ++i) { expect(elm.children[i].innerHTML).toBe(i.toString()) opacities[i] = Math.random().toFixed(5).toString() } const vnode2 = new VNode('span', {}, arr.map(n => { return spanNumWithOpacity(shufArr[n], opacities[n]) })) elm = patch(vnode1, vnode2) for (i = 0; i < elms; ++i) { expect(elm.children[i].innerHTML).toBe(shufArr[i].toString()) expect(opacities[i].indexOf(elm.children[i].style.opacity)).toBe(0) } } }) it('should append elements with updating children without keys', () => { const vnode1 = new VNode('div', {}, [ new VNode('span', {}, undefined, 'hello') ]) const vnode2 = new VNode('div', {}, [ new VNode('span', {}, undefined, 'hello'), new VNode('span', {}, undefined, 'world') ]) let elm = patch(vnode0, vnode1) expect(map(inner, elm.children)).toEqual(['hello']) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['hello', 'world']) }) it('should handle unmoved text nodes with updating children without keys', () => { const vnode1 = new VNode('div', {}, [ createTextVNode('text'), new VNode('span', {}, undefined, 'hello') ]) const vnode2 = new VNode('div', {}, [ createTextVNode('text'), new VNode('span', {}, undefined, 'hello') ]) let elm = patch(vnode0, vnode1) expect(elm.childNodes[0].textContent).toBe('text') elm = patch(vnode1, vnode2) expect(elm.childNodes[0].textContent).toBe('text') }) it('should handle changing text children with updating children without keys', () => { const vnode1 = new VNode('div', {}, [ createTextVNode('text'), new VNode('span', {}, undefined, 'hello') ]) const vnode2 = new VNode('div', {}, [ createTextVNode('text2'), new VNode('span', {}, undefined, 'hello') ]) let elm = patch(vnode0, vnode1) expect(elm.childNodes[0].textContent).toBe('text') elm = patch(vnode1, vnode2) expect(elm.childNodes[0].textContent).toBe('text2') }) it('should prepend element with updating children without keys', () => { const vnode1 = new VNode('div', {}, [ new VNode('span', {}, undefined, 'world') ]) const vnode2 = new VNode('div', {}, [ new VNode('span', {}, undefined, 'hello'), new VNode('span', {}, undefined, 'world') ]) let elm = patch(vnode0, vnode1) expect(map(inner, elm.children)).toEqual(['world']) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['hello', 'world']) }) it('should prepend element of different tag type with updating children without keys', () => { const vnode1 = new VNode('div', {}, [ new VNode('span', {}, undefined, 'world') ]) const vnode2 = new VNode('div', {}, [ new VNode('div', {}, undefined, 'hello'), new VNode('span', {}, undefined, 'world') ]) let elm = patch(vnode0, vnode1) expect(map(inner, elm.children)).toEqual(['world']) elm = patch(vnode1, vnode2) expect(map(prop('tagName'), elm.children)).toEqual(['DIV', 'SPAN']) expect(map(inner, elm.children)).toEqual(['hello', 'world']) }) it('should remove elements with updating children without keys', () => { const vnode1 = new VNode('div', {}, [ new VNode('span', {}, undefined, 'one'), new VNode('span', {}, undefined, 'two'), new VNode('span', {}, undefined, 'three') ]) const vnode2 = new VNode('div', {}, [ new VNode('span', {}, undefined, 'one'), new VNode('span', {}, undefined, 'three') ]) let elm = patch(vnode0, vnode1) expect(map(inner, elm.children)).toEqual(['one', 'two', 'three']) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['one', 'three']) }) it('should remove a single text node with updating children without keys', () => { const vnode1 = new VNode('div', {}, undefined, 'one') const vnode2 = new VNode('div', {}) let elm = patch(vnode0, vnode1) expect(elm.textContent).toBe('one') elm = patch(vnode1, vnode2) expect(elm.textContent).toBe('') }) it('should remove a single text node when children are updated', () => { const vnode1 = new VNode('div', {}, undefined, 'one') const vnode2 = new VNode('div', {}, [ new VNode('div', {}, undefined, 'two'), new VNode('span', {}, undefined, 'three') ]) let elm = patch(vnode0, vnode1) expect(elm.textContent).toBe('one') elm = patch(vnode1, vnode2) expect(map(prop('textContent'), elm.childNodes)).toEqual(['two', 'three']) }) it('should remove a text node among other elements', () => { const vnode1 = new VNode('div', {}, [ createTextVNode('one'), new VNode('span', {}, undefined, 'two') ]) const vnode2 = new VNode('div', {}, [ new VNode('div', {}, undefined, 'three') ]) let elm = patch(vnode0, vnode1) expect(map(prop('textContent'), elm.childNodes)).toEqual(['one', 'two']) elm = patch(vnode1, vnode2) expect(elm.childNodes.length).toBe(1) expect(elm.childNodes[0].tagName).toBe('DIV') expect(elm.childNodes[0].textContent).toBe('three') }) it('should reorder elements', () => { const vnode1 = new VNode('div', {}, [ new VNode('span', {}, undefined, 'one'), new VNode('div', {}, undefined, 'two'), new VNode('b', {}, undefined, 'three') ]) const vnode2 = new VNode('div', {}, [ new VNode('b', {}, undefined, 'three'), new VNode('span', {}, undefined, 'two'), new VNode('div', {}, undefined, 'one') ]) let elm = patch(vnode0, vnode1) expect(map(inner, elm.children)).toEqual(['one', 'two', 'three']) elm = patch(vnode1, vnode2) expect(map(inner, elm.children)).toEqual(['three', 'two', 'one']) }) it('should handle children with the same key but with different tag', () => { const vnode1 = new VNode('div', {}, [ new VNode('div', { key: 1 }, undefined, 'one'), new VNode('div', { key: 2 }, undefined, 'two'), new VNode('div', { key: 3 }, undefined, 'three'), new VNode('div', { key: 4 }, undefined, 'four') ]) const vnode2 = new VNode('div', {}, [ new VNode('div', { key: 4 }, undefined, 'four'), new VNode('span', { key: 3 }, undefined, 'three'), new VNode('span', { key: 2 }, undefined, 'two'), new VNode('div', { key: 1 }, undefined, 'one') ]) let elm = patch(vnode0, vnode1) expect(map(tag, elm.children)).toEqual(['DIV', 'DIV', 'DIV', 'DIV']) expect(map(inner, elm.children)).toEqual(['one', 'two', 'three', 'four']) elm = patch(vnode1, vnode2) expect(map(tag, elm.children)).toEqual(['DIV', 'SPAN', 'SPAN', 'DIV']) expect(map(inner, elm.children)).toEqual(['four', 'three', 'two', 'one']) }) it('should handle children with the same tag, same key, but one with data and one without data', () => { const vnode1 = new VNode('div', {}, [ new VNode('div', { class: 'hi' }, undefined, 'one') ]) const vnode2 = new VNode('div', {}, [ new VNode('div', undefined, undefined, 'four') ]) let elm = patch(vnode0, vnode1) const child1 = elm.children[0] expect(child1.className).toBe('hi') elm = patch(vnode1, vnode2) const child2 = elm.children[0] expect(child1).not.toBe(child2) expect(child2.className).toBe('') }) it('should handle static vnodes properly', () => { function makeNode (text) { return new VNode('div', undefined, [ new VNode(undefined, undefined, undefined, text) ]) } const b = makeNode('B') b.isStatic = true b.key = `__static__1` const vnode1 = new VNode('div', {}, [makeNode('A'), b, makeNode('C')]) const vnode2 = new VNode('div', {}, [b]) const vnode3 = new VNode('div', {}, [makeNode('A'), b, makeNode('C')]) let elm = patch(vnode0, vnode1) expect(elm.textContent).toBe('ABC') elm = patch(vnode1, vnode2) expect(elm.textContent).toBe('B') elm = patch(vnode2, vnode3) expect(elm.textContent).toBe('ABC') }) it('should handle static vnodes inside ', () => { function makeNode (text) { return new VNode('div', undefined, [ new VNode(undefined, undefined, undefined, text) ]) } const b = makeNode('B') b.isStatic = true b.key = `__static__1` const vnode1 = new VNode('div', {}, [makeNode('A'), b, makeNode('C')]) const vnode2 = new VNode('div', {}, [b]) const vnode3 = new VNode('div', {}, [makeNode('A'), b, makeNode('C')]) let elm = patch(vnode0, vnode1) expect(elm.textContent).toBe('ABC') elm = patch(vnode1, vnode2) expect(elm.textContent).toBe('B') elm = patch(vnode2, vnode3) expect(elm.textContent).toBe('ABC') }) // #6502 it('should not de-opt when both head and tail are changed', () => { const vnode1 = new VNode('div', {}, [ createEmptyVNode(), new VNode('div'), createEmptyVNode() ]) const vnode2 = new VNode('div', {}, [ new VNode('p'), new VNode('div'), new VNode('p') ]) let root = patch(null, vnode1) const original = root.childNodes[1] root = patch(vnode1, vnode2) const postPatch = root.childNodes[1] expect(postPatch).toBe(original) }) it('should warn with duplicate keys: createChildren', () => { function makeNode (key) { return new VNode('div', { key: key }) } const vnode = new VNode('p', {}, ['b', 'a', 'c', 'b'].map(makeNode)) patch(null, vnode) expect(`Duplicate keys detected: 'b'`).toHaveBeenWarned() }) it('should warn with duplicate keys: updateChildren', () => { function makeNode (key) { return new VNode('div', { key: key }) } const vnode2 = new VNode('p', {}, ['b', 'a', 'c', 'b'].map(makeNode)) const vnode3 = new VNode('p', {}, ['b', 'x', 'd', 'b'].map(makeNode)) patch(vnode0, vnode2) expect(`Duplicate keys detected: 'b'`).toHaveBeenWarned() patch(vnode2, vnode3) expect(`Duplicate keys detected: 'b'`).toHaveBeenWarned() }) it('should warn with duplicate keys: patchVnode with empty oldVnode', () => { function makeNode (key) { return new VNode('li', { key: key }) } const vnode1 = new VNode('div') const vnode2 = new VNode('div', undefined, ['1', '2', '3', '4', '4'].map(makeNode)) patch(vnode1, vnode2) expect(`Duplicate keys detected: '4'`).toHaveBeenWarned() }) })
{ "pile_set_name": "Github" }
// Copyright JS Foundation and other contributors, http://js.foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. var a = 20; var b = a >>> true; assert(b == 10)
{ "pile_set_name": "Github" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ecs/model/UpdateClusterSettingsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::ECS::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; UpdateClusterSettingsResult::UpdateClusterSettingsResult() { } UpdateClusterSettingsResult::UpdateClusterSettingsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } UpdateClusterSettingsResult& UpdateClusterSettingsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("cluster")) { m_cluster = jsonValue.GetObject("cluster"); } return *this; }
{ "pile_set_name": "Github" }
// Copyright 2015 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package rafthttp import ( "errors" "fmt" "io" "io/ioutil" "net/http" "sync" "testing" "time" "github.com/coreos/etcd/etcdserver/stats" "github.com/coreos/etcd/pkg/testutil" "github.com/coreos/etcd/pkg/types" "github.com/coreos/etcd/raft/raftpb" "github.com/coreos/etcd/version" ) // TestPipelineSend tests that pipeline could send data using roundtripper // and increase success count in stats. func TestPipelineSend(t *testing.T) { tr := &roundTripperRecorder{rec: testutil.NewRecorderStream()} picker := mustNewURLPicker(t, []string{"http://localhost:2380"}) tp := &Transport{pipelineRt: tr} p := startTestPipeline(tp, picker) p.msgc <- raftpb.Message{Type: raftpb.MsgApp} tr.rec.Wait(1) p.stop() if p.followerStats.Counts.Success != 1 { t.Errorf("success = %d, want 1", p.followerStats.Counts.Success) } } // TestPipelineKeepSendingWhenPostError tests that pipeline can keep // sending messages if previous messages meet post error. func TestPipelineKeepSendingWhenPostError(t *testing.T) { tr := &respRoundTripper{rec: testutil.NewRecorderStream(), err: fmt.Errorf("roundtrip error")} picker := mustNewURLPicker(t, []string{"http://localhost:2380"}) tp := &Transport{pipelineRt: tr} p := startTestPipeline(tp, picker) defer p.stop() for i := 0; i < 50; i++ { p.msgc <- raftpb.Message{Type: raftpb.MsgApp} } _, err := tr.rec.Wait(50) if err != nil { t.Errorf("unexpected wait error %v", err) } } func TestPipelineExceedMaximumServing(t *testing.T) { rt := newRoundTripperBlocker() picker := mustNewURLPicker(t, []string{"http://localhost:2380"}) tp := &Transport{pipelineRt: rt} p := startTestPipeline(tp, picker) defer p.stop() // keep the sender busy and make the buffer full // nothing can go out as we block the sender for i := 0; i < connPerPipeline+pipelineBufSize; i++ { select { case p.msgc <- raftpb.Message{}: case <-time.After(time.Second): t.Errorf("failed to send out message") } } // try to send a data when we are sure the buffer is full select { case p.msgc <- raftpb.Message{}: t.Errorf("unexpected message sendout") default: } // unblock the senders and force them to send out the data rt.unblock() // It could send new data after previous ones succeed select { case p.msgc <- raftpb.Message{}: case <-time.After(time.Second): t.Errorf("failed to send out message") } } // TestPipelineSendFailed tests that when send func meets the post error, // it increases fail count in stats. func TestPipelineSendFailed(t *testing.T) { picker := mustNewURLPicker(t, []string{"http://localhost:2380"}) rt := newRespRoundTripper(0, errors.New("blah")) rt.rec = testutil.NewRecorderStream() tp := &Transport{pipelineRt: rt} p := startTestPipeline(tp, picker) p.msgc <- raftpb.Message{Type: raftpb.MsgApp} if _, err := rt.rec.Wait(1); err != nil { t.Fatal(err) } p.stop() if p.followerStats.Counts.Fail != 1 { t.Errorf("fail = %d, want 1", p.followerStats.Counts.Fail) } } func TestPipelinePost(t *testing.T) { tr := &roundTripperRecorder{rec: &testutil.RecorderBuffered{}} picker := mustNewURLPicker(t, []string{"http://localhost:2380"}) tp := &Transport{ClusterID: types.ID(1), pipelineRt: tr} p := startTestPipeline(tp, picker) if err := p.post([]byte("some data")); err != nil { t.Fatalf("unexpected post error: %v", err) } act, err := tr.rec.Wait(1) if err != nil { t.Fatal(err) } p.stop() req := act[0].Params[0].(*http.Request) if g := req.Method; g != "POST" { t.Errorf("method = %s, want %s", g, "POST") } if g := req.URL.String(); g != "http://localhost:2380/raft" { t.Errorf("url = %s, want %s", g, "http://localhost:2380/raft") } if g := req.Header.Get("Content-Type"); g != "application/protobuf" { t.Errorf("content type = %s, want %s", g, "application/protobuf") } if g := req.Header.Get("X-Server-Version"); g != version.Version { t.Errorf("version = %s, want %s", g, version.Version) } if g := req.Header.Get("X-Min-Cluster-Version"); g != version.MinClusterVersion { t.Errorf("min version = %s, want %s", g, version.MinClusterVersion) } if g := req.Header.Get("X-Etcd-Cluster-ID"); g != "1" { t.Errorf("cluster id = %s, want %s", g, "1") } b, err := ioutil.ReadAll(req.Body) if err != nil { t.Fatalf("unexpected ReadAll error: %v", err) } if string(b) != "some data" { t.Errorf("body = %s, want %s", b, "some data") } } func TestPipelinePostBad(t *testing.T) { tests := []struct { u string code int err error }{ // RoundTrip returns error {"http://localhost:2380", 0, errors.New("blah")}, // unexpected response status code {"http://localhost:2380", http.StatusOK, nil}, {"http://localhost:2380", http.StatusCreated, nil}, } for i, tt := range tests { picker := mustNewURLPicker(t, []string{tt.u}) tp := &Transport{pipelineRt: newRespRoundTripper(tt.code, tt.err)} p := startTestPipeline(tp, picker) err := p.post([]byte("some data")) p.stop() if err == nil { t.Errorf("#%d: err = nil, want not nil", i) } } } func TestPipelinePostErrorc(t *testing.T) { tests := []struct { u string code int err error }{ {"http://localhost:2380", http.StatusForbidden, nil}, } for i, tt := range tests { picker := mustNewURLPicker(t, []string{tt.u}) tp := &Transport{pipelineRt: newRespRoundTripper(tt.code, tt.err)} p := startTestPipeline(tp, picker) p.post([]byte("some data")) p.stop() select { case <-p.errorc: default: t.Fatalf("#%d: cannot receive from errorc", i) } } } func TestStopBlockedPipeline(t *testing.T) { picker := mustNewURLPicker(t, []string{"http://localhost:2380"}) tp := &Transport{pipelineRt: newRoundTripperBlocker()} p := startTestPipeline(tp, picker) // send many messages that most of them will be blocked in buffer for i := 0; i < connPerPipeline*10; i++ { p.msgc <- raftpb.Message{} } done := make(chan struct{}) go func() { p.stop() done <- struct{}{} }() select { case <-done: case <-time.After(time.Second): t.Fatalf("failed to stop pipeline in 1s") } } type roundTripperBlocker struct { unblockc chan struct{} mu sync.Mutex cancel map[*http.Request]chan struct{} } func newRoundTripperBlocker() *roundTripperBlocker { return &roundTripperBlocker{ unblockc: make(chan struct{}), cancel: make(map[*http.Request]chan struct{}), } } func (t *roundTripperBlocker) unblock() { close(t.unblockc) } func (t *roundTripperBlocker) CancelRequest(req *http.Request) { t.mu.Lock() defer t.mu.Unlock() if c, ok := t.cancel[req]; ok { c <- struct{}{} delete(t.cancel, req) } } type respRoundTripper struct { mu sync.Mutex rec testutil.Recorder code int header http.Header err error } func newRespRoundTripper(code int, err error) *respRoundTripper { return &respRoundTripper{code: code, err: err} } func (t *respRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { t.mu.Lock() defer t.mu.Unlock() if t.rec != nil { t.rec.Record(testutil.Action{Name: "req", Params: []interface{}{req}}) } return &http.Response{StatusCode: t.code, Header: t.header, Body: &nopReadCloser{}}, t.err } type roundTripperRecorder struct { rec testutil.Recorder } func (t *roundTripperRecorder) RoundTrip(req *http.Request) (*http.Response, error) { if t.rec != nil { t.rec.Record(testutil.Action{Name: "req", Params: []interface{}{req}}) } return &http.Response{StatusCode: http.StatusNoContent, Body: &nopReadCloser{}}, nil } type nopReadCloser struct{} func (n *nopReadCloser) Read(p []byte) (int, error) { return 0, io.EOF } func (n *nopReadCloser) Close() error { return nil } func startTestPipeline(tr *Transport, picker *urlPicker) *pipeline { p := &pipeline{ peerID: types.ID(1), tr: tr, picker: picker, status: newPeerStatus(types.ID(1)), raft: &fakeRaft{}, followerStats: &stats.FollowerStats{}, errorc: make(chan error, 1), } p.start() return p }
{ "pile_set_name": "Github" }
/************************************************************************************************ NC_ALLOC.CPP * Copyright (c) 1997 * Mark of the Unicorn, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Mark of the Unicorn makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. ************************************************************************************************/ #include "nc_alloc.h" #include <string> #if defined (EH_NEW_HEADERS) # include <new> # include <cassert> # include <cstdlib> #else # include <assert.h> # include <stdlib.h> # include <new.h> #endif #if defined (EH_NEW_IOSTREAMS) # include <iostream> #else # include <iostream.h> #endif long alloc_count = 0; long object_count = 0; long TestController::possible_failure_count = 0; const char* TestController::current_test = "<unknown>"; const char* TestController::current_test_category = "no category"; const char* TestController::current_container = 0; bool TestController::nc_verbose = true; bool TestController::never_fail = false; bool TestController::track_allocations = false; bool TestController::leak_detection_enabled = false; TestController gTestController; //************************************************************************************************ void TestController::maybe_fail(long) { if (never_fail || Failure_threshold() == kNotInExceptionTest) return; // throw if allocation would satisfy the threshold if (possible_failure_count++ >= Failure_threshold()) { // what about doing some standard new_handler() behavior here (to test it!) ??? // reset and simulate an out-of-memory failure Failure_threshold() = kNotInExceptionTest; #ifndef EH_NO_EXCEPTIONS throw EH_STD::bad_alloc(); #endif } } #if defined (EH_HASHED_CONTAINERS_IMPLEMENTED) # if defined (__SGI_STL) # if defined (EH_NEW_HEADERS) # include <hash_set> # else # include <hash_set.h> # endif # elif defined (__MSL__) # include <hashset.h> # else # error what do I include to get hash_set? # endif #else # if defined (EH_NEW_HEADERS) # include <set> # else # include <set.h> # endif #endif #if !defined (EH_HASHED_CONTAINERS_IMPLEMENTED) typedef EH_STD::set<void*, EH_STD::less<void*> > allocation_set; #else USING_CSTD_NAME(size_t) struct hash_void { size_t operator()(void* x) const { return (size_t)x; } }; typedef EH_STD::hash_set<void*, ::hash_void, EH_STD::equal_to<void*> > allocation_set; #endif static allocation_set& alloc_set() { static allocation_set s; return s; } // Prevents infinite recursion during allocation static bool using_alloc_set = false; #if !defined (NO_FAST_ALLOCATOR) // // FastAllocator -- speeds up construction of TestClass objects when // TESTCLASS_DEEP_DATA is enabled, and speeds up tracking of allocations // when the suite is run with the -t option. // class FastAllocator { public: //FastAllocator() : mFree(0), mUsed(0) {} static void *Allocate(size_t s) { void *result = 0; if (s <= sizeof(Block)) { if (mFree != 0) { result = mFree; mFree = mFree->next; } else if (mBlocks != 0 && mUsed < kBlockCount) { result = (void*)&mBlocks[mUsed++]; } } return result; } static bool Free(void* p) { Block* b = (Block*)p; if (mBlocks == 0 || b < mBlocks || b >= mBlocks + kBlockCount) return false; b->next = mFree; mFree = b; return true; } struct Block; friend struct Block; enum { // Number of fast allocation blocks to create. kBlockCount = 1500, // You may need to adjust this number for your platform. // A good choice will speed tests. A bad choice will still work. kMinBlockSize = 48 }; struct Block { union { Block *next; double dummy; // fbp - force alignment char dummy2[kMinBlockSize]; }; }; static Block* mBlocks; static Block *mFree; static size_t mUsed; }; FastAllocator::Block *FastAllocator::mBlocks = (FastAllocator::Block*)EH_CSTD::calloc( sizeof(FastAllocator::Block), FastAllocator::kBlockCount ); FastAllocator::Block *FastAllocator::mFree; size_t FastAllocator::mUsed; static FastAllocator gFastAllocator; #endif inline char* AllocateBlock(size_t s) { #if !defined (NO_FAST_ALLOCATOR) char * const p = (char*)gFastAllocator.Allocate( s ); if (p != 0) return p; #endif return (char*)EH_CSTD::malloc(s); } static void* OperatorNew( size_t s ) { if (!using_alloc_set) { simulate_possible_failure(); ++alloc_count; } char *p = AllocateBlock(s); if (gTestController.TrackingEnabled() && gTestController.LeakDetectionEnabled() && !using_alloc_set) { using_alloc_set = true; bool inserted = alloc_set().insert(p).second; // Suppress warning about unused variable. inserted; EH_ASSERT(inserted); using_alloc_set = false; } return p; } void* _STLP_CALL operator new(size_t s) #ifdef EH_DELETE_HAS_THROW_SPEC throw(EH_STD::bad_alloc) #endif { return OperatorNew( s ); } #ifdef EH_USE_NOTHROW void* _STLP_CALL operator new(size_t size, const EH_STD::nothrow_t&) throw() { try { return OperatorNew( size ); } catch (...) { return 0; } } #endif #if 1 /* defined (EH_VECTOR_OPERATOR_NEW) */ void* _STLP_CALL operator new[](size_t size ) throw(EH_STD::bad_alloc) { return OperatorNew( size ); } # ifdef EH_USE_NOTHROW void* _STLP_CALL operator new[](size_t size, const EH_STD::nothrow_t&) throw() { try { return OperatorNew(size); } catch (...) { return 0; } } # endif void _STLP_CALL operator delete[](void* ptr) throw() { operator delete( ptr ); } #endif #if defined (EH_DELETE_HAS_THROW_SPEC) void _STLP_CALL operator delete(void* s) throw() #else void _STLP_CALL operator delete(void* s) #endif { if ( s != 0 ) { if ( !using_alloc_set ) { --alloc_count; if ( gTestController.TrackingEnabled() && gTestController.LeakDetectionEnabled() ) { using_alloc_set = true; allocation_set::iterator p = alloc_set().find( (char*)s ); EH_ASSERT( p != alloc_set().end() ); alloc_set().erase( p ); using_alloc_set = false; } } # if ! defined (NO_FAST_ALLOCATOR) if ( !gFastAllocator.Free( s ) ) # endif EH_CSTD::free(s); } } /*=================================================================================== ClearAllocationSet (private helper) EFFECTS: Empty the set of allocated blocks. ====================================================================================*/ void TestController::ClearAllocationSet() { if (!using_alloc_set) { using_alloc_set = true; alloc_set().clear(); using_alloc_set = false; } } bool TestController::ReportLeaked() { EndLeakDetection(); EH_ASSERT( !using_alloc_set || (alloc_count == static_cast<int>(alloc_set().size())) ); if (alloc_count != 0 || object_count != 0) { EH_STD::cerr<<"\nEH TEST FAILURE !\n"; PrintTestName(true); if (alloc_count) EH_STD::cerr << "ERROR : " << alloc_count << " outstanding allocations.\n"; if (object_count) EH_STD::cerr << "ERROR : " << object_count << " non-destroyed objects.\n"; alloc_count = object_count = 0; return true; } return false; } /*=================================================================================== PrintTestName EFFECTS: Prints information about the current test. If err is false, ends with an ellipsis, because the test is ongoing. If err is true an error is being reported, and the output ends with an endl. ====================================================================================*/ void TestController::PrintTestName(bool err) { if (current_container) EH_STD::cerr<<"["<<current_container<<"] :"; EH_STD::cerr<<"testing "<<current_test <<" (" << current_test_category <<")"; if (err) EH_STD::cerr<<EH_STD::endl; else EH_STD::cerr<<" ... "; } void TestController::ReportSuccess(int count) { if (nc_verbose) EH_STD::cerr<<(count+1)<<" try successful"<<EH_STD::endl; } long& TestController::Failure_threshold() { static long failure_threshold = kNotInExceptionTest; return failure_threshold; }
{ "pile_set_name": "Github" }
cave9 is a gravity cave-exploration game. Use only two buttons to activate the thrust jets of your ship in this first-person 3D version of the classic SF-Cave game. WWW: https://github.com/bart9h/cave9
{ "pile_set_name": "Github" }
module Psych ### # Psych::Handler is an abstract base class that defines the events used # when dealing with Psych::Parser. Clients who want to use Psych::Parser # should implement a class that inherits from Psych::Handler and define # events that they can handle. # # Psych::Handler defines all events that Psych::Parser can possibly send to # event handlers. # # See Psych::Parser for more details class Handler ### # Configuration options for dumping YAML. class DumperOptions attr_accessor :line_width, :indentation, :canonical def initialize @line_width = 0 @indentation = 2 @canonical = false end end # Default dumping options OPTIONS = DumperOptions.new # Events that a Handler should respond to. EVENTS = [ :alias, :empty, :end_document, :end_mapping, :end_sequence, :end_stream, :scalar, :start_document, :start_mapping, :start_sequence, :start_stream ] ### # Called with +encoding+ when the YAML stream starts. This method is # called once per stream. A stream may contain multiple documents. # # See the constants in Psych::Parser for the possible values of +encoding+. def start_stream encoding end ### # Called when the document starts with the declared +version+, # +tag_directives+, if the document is +implicit+. # # +version+ will be an array of integers indicating the YAML version being # dealt with, +tag_directives+ is a list of tuples indicating the prefix # and suffix of each tag, and +implicit+ is a boolean indicating whether # the document is started implicitly. # # === Example # # Given the following YAML: # # %YAML 1.1 # %TAG ! tag:tenderlovemaking.com,2009: # --- !squee # # The parameters for start_document must be this: # # version # => [1, 1] # tag_directives # => [["!", "tag:tenderlovemaking.com,2009:"]] # implicit # => false def start_document version, tag_directives, implicit end ### # Called with the document ends. +implicit+ is a boolean value indicating # whether or not the document has an implicit ending. # # === Example # # Given the following YAML: # # --- # hello world # # +implicit+ will be true. Given this YAML: # # --- # hello world # ... # # +implicit+ will be false. def end_document implicit end ### # Called when an alias is found to +anchor+. +anchor+ will be the name # of the anchor found. # # === Example # # Here we have an example of an array that references itself in YAML: # # --- &ponies # - first element # - *ponies # # &ponies is the achor, *ponies is the alias. In this case, alias is # called with "ponies". def alias anchor end ### # Called when a scalar +value+ is found. The scalar may have an # +anchor+, a +tag+, be implicitly +plain+ or implicitly +quoted+ # # +value+ is the string value of the scalar # +anchor+ is an associated anchor or nil # +tag+ is an associated tag or nil # +plain+ is a boolean value # +quoted+ is a boolean value # +style+ is an integer idicating the string style # # See the constants in Psych::Nodes::Scalar for the possible values of # +style+ # # === Example # # Here is a YAML document that exercises most of the possible ways this # method can be called: # # --- # - !str "foo" # - &anchor fun # - many # lines # - | # many # newlines # # The above YAML document contains a list with four strings. Here are # the parameters sent to this method in the same order: # # # value anchor tag plain quoted style # ["foo", nil, "!str", false, false, 3 ] # ["fun", "anchor", nil, true, false, 1 ] # ["many lines", nil, nil, true, false, 1 ] # ["many\nnewlines\n", nil, nil, false, true, 4 ] # def scalar value, anchor, tag, plain, quoted, style end ### # Called when a sequence is started. # # +anchor+ is the anchor associated with the sequence or nil. # +tag+ is the tag associated with the sequence or nil. # +implicit+ a boolean indicating whether or not the sequence was implicitly # started. # +style+ is an integer indicating the list style. # # See the constants in Psych::Nodes::Sequence for the possible values of # +style+. # # === Example # # Here is a YAML document that exercises most of the possible ways this # method can be called: # # --- # - !!seq [ # a # ] # - &pewpew # - b # # The above YAML document consists of three lists, an outer list that # contains two inner lists. Here is a matrix of the parameters sent # to represent these lists: # # # anchor tag implicit style # [nil, nil, true, 1 ] # [nil, "tag:yaml.org,2002:seq", false, 2 ] # ["pewpew", nil, true, 1 ] def start_sequence anchor, tag, implicit, style end ### # Called when a sequence ends. def end_sequence end ### # Called when a map starts. # # +anchor+ is the anchor associated with the map or +nil+. # +tag+ is the tag associated with the map or +nil+. # +implicit+ is a boolean indicating whether or not the map was implicitly # started. # +style+ is an integer indicating the mapping style. # # See the constants in Psych::Nodes::Mapping for the possible values of # +style+. # # === Example # # Here is a YAML document that exercises most of the possible ways this # method can be called: # # --- # k: !!map { hello: world } # v: &pewpew # hello: world # # The above YAML document consists of three maps, an outer map that contains # two inner maps. Below is a matrix of the parameters sent in order to # represent these three maps: # # # anchor tag implicit style # [nil, nil, true, 1 ] # [nil, "tag:yaml.org,2002:map", false, 2 ] # ["pewpew", nil, true, 1 ] def start_mapping anchor, tag, implicit, style end ### # Called when a map ends def end_mapping end ### # Called when an empty event happens. (Which, as far as I can tell, is # never). def empty end ### # Called when the YAML stream ends def end_stream end ### # Is this handler a streaming handler? def streaming? false end end end
{ "pile_set_name": "Github" }
<?php /** * Created by PhpStorm. * User: royalwang * Date: 2018/9/29 * Time: 1:05 PM */ defined('IN_ECJIA') or exit('No permission resources.'); /** * 获取公众平台列表 */ class platform_platform_account_list_api extends Component_Event_Api { /** * @param shop_id 店铺ID,默认为0 * @param platform 平台,wechat 微信,weapp 小程序 */ public function call(&$options) { $shop_id = array_get($options, 'shop_id', 0); $platform = array_get($options, 'platform', 'wechat'); $accountlist = with(new Ecjia\App\Platform\Frameworks\Platform\AccountManager($shop_id))->getAccountList($platform); return $accountlist; } }
{ "pile_set_name": "Github" }
// ************************************************ // wallace_cuda.hpp // authors: Lee Howes and David B. Thomas // // Wrapper for allowing the calling of CUDA // based Wallace generators from the test // framework. // ************************************************ #ifndef wallace_cuda_hpp #define wallace_cuda_hpp #include "../wallace_base.hpp" #include <cmath> #include "boost/random.hpp" #include "boost/smart_ptr.hpp" typedef void (*cuda_transform_func_t) (unsigned POOL_SIZE, unsigned BATCH_SIZE, unsigned BATCH_COUNT, unsigned seed, float *chi2Corr, // [in] BATCH_SIZE*BATCH_COUNT float *poolIn, // [in] POOL_SIZE*BATCH_COUNT (can be modified). float *poolOut, // [out] POOL_SIZE*BATCH_COUNT. poolIn!=poolOut float *output // [out] POOL_SIZE*BATCH_COUNT*BATCH_SIZE ); template < cuda_transform_func_t TRANSFORM_FUNC, unsigned POOL_SIZE, unsigned BATCH_SIZE = 16, unsigned BATCH_COUNT = 16 > class WallaceCUDA:public WallaceBase < POOL_SIZE * BATCH_COUNT, 1, 1, POOL_SIZE * BATCH_SIZE * BATCH_COUNT, false > { protected: // We pretend to WallaceBase that we have one thread, typedef WallaceBase < POOL_SIZE * BATCH_COUNT, 1, 1, POOL_SIZE * BATCH_SIZE * BATCH_COUNT, false > base_t; float m_chi2Corr[BATCH_SIZE * BATCH_COUNT]; unsigned m_seed; virtual void PreTransformSetup() { for (unsigned i = 0; i < BATCH_SIZE * BATCH_COUNT; i++) { m_chi2Corr[i] = MakeChi2Scale(POOL_SIZE); } m_seed = (1664525U * m_seed + 1013904223U) & 0xFFFFFFFF; } // Runs a kernel thread. Per thread arguments are managed by the inheritor. virtual void TransformKernel(unsigned tid, unsigned pass) { TRANSFORM_FUNC(POOL_SIZE, BATCH_SIZE, BATCH_COUNT, m_seed, m_chi2Corr, const_cast < float *>(base_t::GetRawInputPool()), base_t::GetRawOutputPool(), base_t::GetRawOutputBuffer()); } virtual void ReseedPoolImpl(float *poolStg) { for (unsigned k = 0; k < BATCH_SIZE; k++) { float *pool = poolStg + k * POOL_SIZE; double sumSquares = 0; for (unsigned i = 0; i < POOL_SIZE; i++) { pool[i] = RandN(); sumSquares += pool[i] * pool[i]; } double scale = sqrt(POOL_SIZE / sumSquares); for (unsigned i = 0; i < POOL_SIZE; i++) { pool[i] *= scale; } } } const char *m_name, *m_desc; public: WallaceCUDA(const char *name, const char *desc):m_seed(lrand48()), m_name(name), m_desc(desc) { base_t::ReseedPool(); } const char *Name() { return m_name; } const char *Description() { return m_desc; } }; #endif
{ "pile_set_name": "Github" }
<!-- Description: entry link title Expect: not bozo and entries[0]['links'][0]['title'] == u'Example title' --> <feed version="0.3" xmlns="http://purl.org/atom/ns#"> <entry> <link rel="alternate" type="text/html" title="Example title" href="http://www.example.com/"/> </entry> </feed>
{ "pile_set_name": "Github" }
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003-2011 - Stendhal * *************************************************************************** *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package games.stendhal.server.maps.semos.city; import java.awt.Rectangle; import java.awt.Shape; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.log4j.Level; import org.apache.log4j.Logger; import games.stendhal.common.parser.Sentence; import games.stendhal.server.core.config.ZoneConfigurator; import games.stendhal.server.core.engine.GameEvent; import games.stendhal.server.core.engine.SingletonRepository; import games.stendhal.server.core.engine.StendhalRPZone; import games.stendhal.server.core.pathfinder.FixedPath; import games.stendhal.server.core.pathfinder.Node; import games.stendhal.server.entity.CollisionAction; import games.stendhal.server.entity.Entity; import games.stendhal.server.entity.mapstuff.office.RentedSign; import games.stendhal.server.entity.mapstuff.office.RentedSignList; import games.stendhal.server.entity.npc.ChatAction; import games.stendhal.server.entity.npc.ChatCondition; import games.stendhal.server.entity.npc.ConversationPhrases; import games.stendhal.server.entity.npc.ConversationStates; import games.stendhal.server.entity.npc.EventRaiser; import games.stendhal.server.entity.npc.SpeakerNPC; import games.stendhal.server.entity.npc.action.RemoveStorableEntityAction; import games.stendhal.server.entity.npc.condition.AdminCondition; import games.stendhal.server.entity.npc.condition.AndCondition; import games.stendhal.server.entity.npc.condition.LevelGreaterThanCondition; import games.stendhal.server.entity.npc.condition.LevelLessThanCondition; import games.stendhal.server.entity.npc.condition.NotCondition; import games.stendhal.server.entity.npc.condition.PlayerHasItemWithHimCondition; import games.stendhal.server.entity.npc.condition.PlayerHasStorableEntityCondition; import games.stendhal.server.entity.npc.condition.TextHasParameterCondition; import games.stendhal.server.entity.player.Player; import games.stendhal.server.util.StringUtils; /** * A merchant (original name: Gordon) who rents signs to players. * * The player has to have at least level 5 to prevent abuse by newly created characters. */ public class SignLessorNPC implements ZoneConfigurator { protected String text; // 1.5 minutes private static final int CHAT_TIMEOUT = 90; private static final int MONEY = 100; protected RentedSignList rentedSignList; @Override public void configureZone(StendhalRPZone zone, Map<String, String> attributes) { final Shape shape = new Rectangle(21, 48, 17, 1); rentedSignList = new RentedSignList(zone, shape); buildNPC(zone); } private void buildNPC(final StendhalRPZone zone) { final SpeakerNPC npc = new SpeakerNPC("Gordon") { @Override public void createDialog() { addGreeting("Hi, I #rent signs and #remove outdated ones."); addJob("I #rent signs for a day."); addHelp("If you want to #rent a sign, just tell me what I should write on it."); setPlayerChatTimeout(CHAT_TIMEOUT); add(ConversationStates.ATTENDING, "", new AndCondition(getRentMatchCond(), new LevelLessThanCondition(6)), ConversationStates.ATTENDING, "Oh sorry, I don't rent signs to people who have so little experience as you.", null); add(ConversationStates.ATTENDING, "", new AndCondition(getRentMatchCond(), new LevelGreaterThanCondition(5), new NotCondition(new TextHasParameterCondition())), ConversationStates.ATTENDING, "Just tell me #rent followed by the text I should write on it.", null); add(ConversationStates.ATTENDING, "", new AndCondition(getRentMatchCond(), new LevelGreaterThanCondition(5), new TextHasParameterCondition()), ConversationStates.BUY_PRICE_OFFERED, null, new ChatAction() { @Override public void fire(final Player player, final Sentence sentence, final EventRaiser npc) { text = sentence.getOriginalText().substring(5).trim(); String reply = "A sign costs " + MONEY + " money for 24 hours. Do you want to rent one?"; if (rentedSignList.getByName(player.getName()) != null) { reply = reply + " Please note that I will replace the sign you already rented."; } npc.say(reply); } @Override public String toString() { return "remember text"; } }); add(ConversationStates.BUY_PRICE_OFFERED, ConversationPhrases.YES_MESSAGES, new NotCondition(new PlayerHasItemWithHimCondition("money", MONEY)), ConversationStates.ATTENDING, "Sorry, you do not have enough money", null); add(ConversationStates.BUY_PRICE_OFFERED, ConversationPhrases.YES_MESSAGES, new PlayerHasItemWithHimCondition("money", MONEY), ConversationStates.IDLE, null, new RentSignChatAction()); add(ConversationStates.BUY_PRICE_OFFERED, ConversationPhrases.NO_MESSAGES, null, ConversationStates.ATTENDING, "If you change your mind, just talk to me again.", null); add(ConversationStates.ATTENDING, "remove", new PlayerHasStorableEntityCondition(rentedSignList), ConversationStates.ATTENDING, "Ok, I am going to remove your sign.", new RemoveStorableEntityAction(rentedSignList)); add(ConversationStates.ATTENDING, "remove", new NotCondition(new PlayerHasStorableEntityCondition(rentedSignList)), ConversationStates.ATTENDING, "You did not rent any sign, so I cannot remove one.", null); // admins may remove signs (even low level admins) add(ConversationStates.ATTENDING, "delete", new AdminCondition(100), ConversationStates.ATTENDING, null, new ChatAction() { @Override public void fire(final Player player, final Sentence sentence, final EventRaiser npc) { if (sentence.getExpressions().size() < 2) { npc.say("Syntax: delete <nameofplayer>"); return; } final String playerName = sentence.getOriginalText().substring("delete ".length()).trim(); if (rentedSignList.removeByName(playerName)) { final String message = player.getName() + " deleted sign from " + playerName; SingletonRepository.getRuleProcessor().sendMessageToSupporters("SignLessorNPC", message); new GameEvent(player.getName(), "sign", "deleted", playerName).raise(); } else { player.sendPrivateText("I could not find a sign by " + playerName); } } @Override public String toString() { return "admin delete sign"; } }); addGoodbye(); } @Override protected void createPath() { final List<Node> nodes = new LinkedList<Node>(); nodes.add(new Node(20,50)); nodes.add(new Node(38, 50)); nodes.add(new Node(38, 51)); nodes.add(new Node(20, 51)); setPath(new FixedPath(nodes, true)); } }; npc.setPosition(20, 50); npc.setCollisionAction(CollisionAction.STOP); npc.setEntityClass("signguynpc"); zone.add(npc); npc.setDescription("You see Gordon. He keeps an eye on the signs close to him."); } private static ChatCondition getRentMatchCond() { return new ChatCondition() { @Override public boolean fire(Player player, Sentence sentence, Entity npc) { String txt = sentence.getOriginalText(); //TODO replaced by using sentence matching "[you] rent" if (txt.startsWith("rent") || txt.startsWith("you rent")) { return true; } else { return false; } } }; } class RentSignChatAction implements ChatAction { private final Logger logger = Logger.getLogger(RentSignChatAction.class); @Override public void fire(final Player player, final Sentence sentence, final EventRaiser npc) { if (text.length() > 1000) { text = text.substring(0, 1000) + "..."; } // do not accept all upper case if (StringUtils.countLowerCase(text) < StringUtils.countUpperCase(text) * 2) { text = text.toLowerCase(); } // put the sign up rentedSignList.removeByName(player.getName()); final RentedSign sign = new RentedSign(player, text); final boolean success = rentedSignList.add(sign); // confirm, log, tell postman if (success) { player.drop("money", MONEY); npc.say("OK, let me put your sign up."); // inform IRC using postman final Player postman = SingletonRepository.getRuleProcessor().getPlayer("postman"); String message = player.getName() + " rented a sign saying \"" + text + "\""; if (postman != null) { postman.sendPrivateText(message); } logger.log(Level.toLevel(System.getProperty("stendhal.support.loglevel"), Level.DEBUG), message); new GameEvent(player.getName(), "sign", "rent", text).raise(); } else { npc.say("Sorry, there are too many signs at the moment. I do not have a free spot left."); } } @Override public String toString() { return "put up sign"; } } }
{ "pile_set_name": "Github" }
-- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with -- the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. SELECT i_item_desc, i_category, i_class, i_current_price, sum(ss_ext_sales_price) AS itemrevenue, sum(ss_ext_sales_price) * 100 / sum(sum(ss_ext_sales_price)) OVER (PARTITION BY i_class) AS revenueratio FROM store_sales, item, date_dim WHERE ss_item_sk = i_item_sk AND i_category IN ('Sports', 'Books', 'Home') AND ss_sold_date_sk = d_date_sk AND d_date BETWEEN cast('1999-02-22' AS DATE) AND (cast('1999-02-22' AS DATE) + INTERVAL 30 days) GROUP BY i_item_id, i_item_desc, i_category, i_class, i_current_price ORDER BY i_category, i_class, i_item_id, i_item_desc, revenueratio
{ "pile_set_name": "Github" }
<component name="ProjectCodeStyleConfiguration"> <code_scheme name="Project" version="173"> <Objective-C-extensions> <file> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Import" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Macro" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Typedef" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Enum" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Constant" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Global" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Struct" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="FunctionPredecl" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Function" /> </file> <class> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Property" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="Synthesize" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InitMethod" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="StaticMethod" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="InstanceMethod" /> <option name="com.jetbrains.cidr.lang.util.OCDeclarationKind" value="DeallocMethod" /> </class> <extensions> <pair source="cpp" header="h" fileNamingConvention="NONE" /> <pair source="c" header="h" fileNamingConvention="NONE" /> </extensions> </Objective-C-extensions> </code_scheme> </component>
{ "pile_set_name": "Github" }
// file : liblava/fwd.hpp // copyright : Copyright (c) 2018-present, Lava Block OÜ // license : MIT; see accompanying LICENSE file #pragma once namespace lava { // liblava/app.hpp struct app; struct camera; struct forward_shading; struct gui; // liblava/base.hpp struct target_callback; struct vk_result; struct device_table; struct device_manager; struct device; struct instance; struct allocator; struct memory; struct physical_device; // liblava/block.hpp struct attachment; struct command; struct block; struct descriptor; struct pipeline_layout; struct pipeline; struct graphics_pipeline; struct compute_pipeline; struct render_pass; struct subpass; struct subpass_dependency; // liblava/core.hpp struct data_provider; struct data; struct scope_data; struct id; struct ids; struct id_obj; struct rect; struct timer; struct run_time; struct no_copy_no_move; struct interface; struct internal_version; struct version; // liblava/frame.hpp struct frame_config; struct frame; struct key_event; struct scroll_offset; struct scroll_event; struct mouse_position; struct mouse_move_event; struct mouse_button_event; struct mouse_active_event; struct input_callback; struct input; struct gamepad; struct gamepad_manager; struct render_target; struct render_thread; struct renderer; struct swapchain; struct window; // liblava/resource.hpp struct buffer; struct image; struct vertex; struct mesh_data; struct mesh; struct mesh_meta; struct file_format; struct texture; struct staging; struct scope_image; // liblava/util.hpp struct file_guard; struct file_system; struct file; struct file_data; struct file_callback; struct json_file; struct log_config; struct random_generator; struct pseudo_random_generator; struct telegram; struct dispatcher; struct thread_pool; } // namespace lava
{ "pile_set_name": "Github" }
RSpec.describe Listen::Adapter do let(:listener) { instance_double(Listen::Listener, options: {}) } before do allow(Listen::Adapter::BSD).to receive(:usable?) { false } allow(Listen::Adapter::Darwin).to receive(:usable?) { false } allow(Listen::Adapter::Linux).to receive(:usable?) { false } allow(Listen::Adapter::Windows).to receive(:usable?) { false } end describe '.select' do it 'returns Polling adapter if forced' do klass = Listen::Adapter.select(force_polling: true) expect(klass).to eq Listen::Adapter::Polling end it 'returns BSD adapter when usable' do allow(Listen::Adapter::BSD).to receive(:usable?) { true } klass = Listen::Adapter.select expect(klass).to eq Listen::Adapter::BSD end it 'returns Darwin adapter when usable' do allow(Listen::Adapter::Darwin).to receive(:usable?) { true } klass = Listen::Adapter.select expect(klass).to eq Listen::Adapter::Darwin end it 'returns Linux adapter when usable' do allow(Listen::Adapter::Linux).to receive(:usable?) { true } klass = Listen::Adapter.select expect(klass).to eq Listen::Adapter::Linux end it 'returns Windows adapter when usable' do allow(Listen::Adapter::Windows).to receive(:usable?) { true } klass = Listen::Adapter.select expect(klass).to eq Listen::Adapter::Windows end context 'no usable adapters' do before { allow(Kernel).to receive(:warn) } it 'returns Polling adapter' do klass = Listen::Adapter.select(force_polling: true) expect(klass).to eq Listen::Adapter::Polling end it 'warns polling fallback with default message' do msg = described_class::POLLING_FALLBACK_MESSAGE expect(Kernel).to receive(:warn).with("[Listen warning]:\n #{msg}") Listen::Adapter.select end it "doesn't warn if polling_fallback_message is false" do expect(Kernel).to_not receive(:warn) Listen::Adapter.select(polling_fallback_message: false) end it 'warns polling fallback with custom message if set' do expected_msg = "[Listen warning]:\n custom fallback message" expect(Kernel).to receive(:warn).with(expected_msg) msg = 'custom fallback message' Listen::Adapter.select(polling_fallback_message: msg) end end end end
{ "pile_set_name": "Github" }
#!/bin/csh ####/home/stgpzli/ /bin/kzmig \ sumerge /files1/data/syn.data \ /files1/data/syn.data \ | kzmig \ x1=0 y1=0 s1=0 l1=0 cdp1=1 \ x2=4000 y2=0 s2=4000 l2=0 cdp2=201 \ x3=0 y3=5000 s3=0 l3=5000 cdp3=10051 \ dds=20 ddl=100 \ fzo=0 nzo=490 dzo=5 \ sstart=0 ns=201 \ lstart=0 nl=51 \ ncpu=1 \ mlimit=1024 \ offmax=3000 apers=4000 aperl=5000 angmax=90. v0=2000. \ ttfile=/files1/data/syn.table.data \ jpfile=job.print \ > /files1/data/syn.kzmig.data exit
{ "pile_set_name": "Github" }
//////////////////////////////////////////////////////////////////////////////// // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////////// package org.apache.royale.html.beads.controllers { import org.apache.royale.core.IBeadController; import org.apache.royale.core.IStrand; import org.apache.royale.core.UIBase; import org.apache.royale.events.MouseEvent; import org.apache.royale.html.ImageButton; import org.apache.royale.html.beads.RangeStepperView; import org.apache.royale.html.beads.models.RangeModel; /** * The RangeStepperMouseController bead feeds mouse events to the RangeStepper and its * components. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public class RangeStepperMouseController implements IBeadController { /** * constructor. * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function RangeStepperMouseController() { } private var _strand:IStrand; private var _incrButton:ImageButton; private var _decrButton:ImageButton; /** * @copy org.apache.royale.core.IBead#strand * * @langversion 3.0 * @playerversion Flash 10.2 * @playerversion AIR 2.6 * @productversion Royale 0.0 */ public function set strand(value:IStrand):void { _strand = value; var stepperView:RangeStepperView = _strand.getBeadByType(RangeStepperView) as RangeStepperView; _incrButton = stepperView.incrementButton; _incrButton.addEventListener(MouseEvent.CLICK, handleIncrClick); _decrButton = stepperView.decrementButton; _decrButton.addEventListener(MouseEvent.CLICK, handleDecrClick); } private function handleIncrClick(event:MouseEvent):void { var model:RangeModel = (_strand as UIBase).model as RangeModel; var nextValue:Number = model.value + 1; if (nextValue >= model.maximum) nextValue = model.maximum; model.value = nextValue; } private function handleDecrClick(event:MouseEvent):void { var model:RangeModel = (_strand as UIBase).model as RangeModel; var nextValue:Number = model.value - 1; if (nextValue < model.minimum) nextValue = model.minimum; model.value = nextValue; } } }
{ "pile_set_name": "Github" }
#!/usr/bin/env python # encoding: utf-8 ''' @author: wujiyang @contact: wujiyang@hust.edu.cn @file: megaface.py @time: 2018/12/24 16:29 @desc: ''' import torchvision.transforms as transforms import torch.utils.data as data import numpy as np import cv2 import os import torch def img_loader(path): try: with open(path, 'rb') as f: img = cv2.imread(path) if len(img.shape) == 2: img = np.stack([img] * 3, 2) return img except IOError: print('Cannot load image ' + path) class MegaFace(data.Dataset): def __init__(self, facescrub_dir, megaface_dir, transform=None, loader=img_loader): self.transform = transform self.loader = loader test_image_file_list = [] print('Scanning files under facescrub and megaface...') for root, dirs, files in os.walk(facescrub_dir): for e in files: filename = os.path.join(root, e) ext = os.path.splitext(filename)[1].lower() if ext in ('.png', '.bmp', '.jpg', '.jpeg'): test_image_file_list.append(filename) for root, dirs, files in os.walk(megaface_dir): for e in files: filename = os.path.join(root, e) ext = os.path.splitext(filename)[1].lower() if ext in ('.png', '.bmp', '.jpg', '.jpeg'): test_image_file_list.append(filename) self.image_list = test_image_file_list def __getitem__(self, index): img_path = self.image_list[index] img = self.loader(img_path) #水平翻转图像 #img = cv2.flip(img, 1) if self.transform is not None: img = self.transform(img) else: img = torch.from_numpy(img) return img, img_path def __len__(self): return len(self.image_list) if __name__ == '__main__': facescrub = '/media/sda/megaface_test_kit/facescrub_align_112/' megaface = '/media/sda/megaface_test_kit/megaface_align_112/' transform = transforms.Compose([ transforms.ToTensor(), # range [0, 255] -> [0.0,1.0] transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5)) # range [0.0, 1.0] -> [-1.0,1.0] ]) dataset = MegaFace(facescrub, megaface, transform=transform) trainloader = data.DataLoader(dataset, batch_size=64, shuffle=False, num_workers=2, drop_last=False) print(len(dataset)) for data in trainloader: print(data.shape)
{ "pile_set_name": "Github" }
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Code generated by generate-types. DO NOT EDIT. package proto import ( "math" "unicode/utf8" "google.golang.org/protobuf/encoding/protowire" "google.golang.org/protobuf/internal/errors" "google.golang.org/protobuf/internal/strs" "google.golang.org/protobuf/reflect/protoreflect" ) var wireTypes = map[protoreflect.Kind]protowire.Type{ protoreflect.BoolKind: protowire.VarintType, protoreflect.EnumKind: protowire.VarintType, protoreflect.Int32Kind: protowire.VarintType, protoreflect.Sint32Kind: protowire.VarintType, protoreflect.Uint32Kind: protowire.VarintType, protoreflect.Int64Kind: protowire.VarintType, protoreflect.Sint64Kind: protowire.VarintType, protoreflect.Uint64Kind: protowire.VarintType, protoreflect.Sfixed32Kind: protowire.Fixed32Type, protoreflect.Fixed32Kind: protowire.Fixed32Type, protoreflect.FloatKind: protowire.Fixed32Type, protoreflect.Sfixed64Kind: protowire.Fixed64Type, protoreflect.Fixed64Kind: protowire.Fixed64Type, protoreflect.DoubleKind: protowire.Fixed64Type, protoreflect.StringKind: protowire.BytesType, protoreflect.BytesKind: protowire.BytesType, protoreflect.MessageKind: protowire.BytesType, protoreflect.GroupKind: protowire.StartGroupType, } func (o MarshalOptions) marshalSingular(b []byte, fd protoreflect.FieldDescriptor, v protoreflect.Value) ([]byte, error) { switch fd.Kind() { case protoreflect.BoolKind: b = protowire.AppendVarint(b, protowire.EncodeBool(v.Bool())) case protoreflect.EnumKind: b = protowire.AppendVarint(b, uint64(v.Enum())) case protoreflect.Int32Kind: b = protowire.AppendVarint(b, uint64(int32(v.Int()))) case protoreflect.Sint32Kind: b = protowire.AppendVarint(b, protowire.EncodeZigZag(int64(int32(v.Int())))) case protoreflect.Uint32Kind: b = protowire.AppendVarint(b, uint64(uint32(v.Uint()))) case protoreflect.Int64Kind: b = protowire.AppendVarint(b, uint64(v.Int())) case protoreflect.Sint64Kind: b = protowire.AppendVarint(b, protowire.EncodeZigZag(v.Int())) case protoreflect.Uint64Kind: b = protowire.AppendVarint(b, v.Uint()) case protoreflect.Sfixed32Kind: b = protowire.AppendFixed32(b, uint32(v.Int())) case protoreflect.Fixed32Kind: b = protowire.AppendFixed32(b, uint32(v.Uint())) case protoreflect.FloatKind: b = protowire.AppendFixed32(b, math.Float32bits(float32(v.Float()))) case protoreflect.Sfixed64Kind: b = protowire.AppendFixed64(b, uint64(v.Int())) case protoreflect.Fixed64Kind: b = protowire.AppendFixed64(b, v.Uint()) case protoreflect.DoubleKind: b = protowire.AppendFixed64(b, math.Float64bits(v.Float())) case protoreflect.StringKind: if strs.EnforceUTF8(fd) && !utf8.ValidString(v.String()) { return b, errors.InvalidUTF8(string(fd.FullName())) } b = protowire.AppendString(b, v.String()) case protoreflect.BytesKind: b = protowire.AppendBytes(b, v.Bytes()) case protoreflect.MessageKind: var pos int var err error b, pos = appendSpeculativeLength(b) b, err = o.marshalMessage(b, v.Message()) if err != nil { return b, err } b = finishSpeculativeLength(b, pos) case protoreflect.GroupKind: var err error b, err = o.marshalMessage(b, v.Message()) if err != nil { return b, err } b = protowire.AppendVarint(b, protowire.EncodeTag(fd.Number(), protowire.EndGroupType)) default: return b, errors.New("invalid kind %v", fd.Kind()) } return b, nil }
{ "pile_set_name": "Github" }
/* Copyright JS Foundation and other contributors, http://js.foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ let b = 5; eval('function b() { return 8; }; assert(b() === 8);'); assert(b === 5);
{ "pile_set_name": "Github" }
#import "Expecta.h" EXPMatcherInterface(beTruthy, (void));
{ "pile_set_name": "Github" }
<?php defined('IN_ECJIA') or exit('No permission resources.');?> <!-- {extends file="ecjia.dwt.php"} --> <!-- {block name="footer"} --> <script type="text/javascript"> ecjia.admin.shopping_admin.editFormSubmit(); </script> <!-- {/block} --> <!-- {block name="main_content"} --> <div> <h3 class="heading"> <!-- {if $ur_here}{$ur_here}{/if} --> {if $action_link} <a href="{$action_link.href}" class="btn plus_or_reply data-pjax" id="sticky_a"><i class="fontello-icon-reply"></i>{$action_link.text}</a> {/if} </h3> </div> <div class="row-fluid"> <div class="span12"> <form id="form-privilege" class="form-horizontal" name="editForm" action="{$form_action}" method="post" enctype="multipart/form-data" > <fieldset> <div class="control-group formSep"> <label class="control-label">{t domain="shipping"}名称:{/t}</label> <div class="controls"> <input class="w350" name="shipping_name" type="text" id="shipping_name" value="{$shipping.shipping_name|escape}" size="40" /> <span class="input-must">*</span> </div> </div> <div class="control-group formSep"> <label class="control-label">{t domain="shipping"}描述:{/t}</label> <div class="controls"> <textarea class="w350" id="shipping_desc" name="shipping_desc" cols="10" rows="6">{$shipping.shipping_desc|escape}</textarea> <span class="input-must">*</span> </div> </div> <!-- 保价费用--> <div class="control-group formSep"> <label class="control-label">{t domain="shipping"}保价费用:{/t}</label> <div class="controls"> <label class="p_t5">{if $shipping.insure}{$shipping.insure}{else}{t domain="shipping"}不支持{/t}{/if}</label> </div> </div> <!-- 货到付款--> <div class="control-group formSep"> <label class="control-label">{t domain="shipping"}是否支持货到付款:{/t}</label> <div class="controls"> <label class="p_t5">{if $shipping.support_cod == "1"}{t domain="shipping"}是{/t}{else}{t domain="shipping"}否{/t}{/if}</label> </div> </div> <div class="control-group"> <div class="controls"> <button class="btn btn-gebo" type="submit">{t domain="shipping"}确定{/t}</button> <input type="hidden" name="shipping_id" value="{$shipping.shipping_id}" /> <input type="hidden" name="shipping_code" value="{$shipping.shipping_code}" /> <input type="hidden" name="is_cod" value="{$shipping.is_cod}" /> <input type="hidden" name="support_cod" value="{$shipping.support_cod}" /> </div> </div> </fieldset> </form> </div> </div> <!-- {/block} -->
{ "pile_set_name": "Github" }
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #pragma once #include <memory> #include <string> #include <vector> #include "Eigen/Dense" #include "modules/perception/base/hdmap_struct.h" #include "modules/perception/base/object_pool_types.h" #include "modules/perception/base/point_cloud.h" #include "modules/perception/base/sensor_meta.h" namespace apollo { namespace perception { namespace lidar { struct LidarFrame { EIGEN_MAKE_ALIGNED_OPERATOR_NEW // point cloud std::shared_ptr<base::AttributePointCloud<base::PointF>> cloud; // world point cloud std::shared_ptr<base::AttributePointCloud<base::PointD>> world_cloud; // timestamp double timestamp = 0.0; // lidar to world pose Eigen::Affine3d lidar2world_pose = Eigen::Affine3d::Identity(); // lidar to world pose Eigen::Affine3d novatel2world_pose = Eigen::Affine3d::Identity(); // hdmap struct std::shared_ptr<base::HdmapStruct> hdmap_struct = nullptr; // segmented objects std::vector<std::shared_ptr<base::Object>> segmented_objects; // tracked objects std::vector<std::shared_ptr<base::Object>> tracked_objects; // point cloud roi indices base::PointIndices roi_indices; // point cloud non ground indices base::PointIndices non_ground_indices; // secondary segmentor indices base::PointIndices secondary_indices; // sensor info base::SensorInfo sensor_info; // reserve string std::string reserve; void Reset() { if (cloud) { cloud->clear(); } if (world_cloud) { world_cloud->clear(); } timestamp = 0.0; lidar2world_pose = Eigen::Affine3d::Identity(); novatel2world_pose = Eigen::Affine3d::Identity(); if (hdmap_struct) { hdmap_struct->road_boundary.clear(); hdmap_struct->road_polygons.clear(); hdmap_struct->junction_polygons.clear(); hdmap_struct->hole_polygons.clear(); } segmented_objects.clear(); tracked_objects.clear(); roi_indices.indices.clear(); non_ground_indices.indices.clear(); secondary_indices.indices.clear(); } void FilterPointCloud(base::PointCloud<base::PointF> *filtered_cloud, const std::vector<uint32_t> &indices) { if (cloud && filtered_cloud) { filtered_cloud->CopyPointCloudExclude(*cloud, indices); } } }; // struct LidarFrame } // namespace lidar } // namespace perception } // namespace apollo
{ "pile_set_name": "Github" }
rm -rf .directus-build git clone https://github.com/directus/directus.git .directus-build pushd .directus-build npm install gulp build gulp deploy popd rm -rf .directus-build
{ "pile_set_name": "Github" }
'use strict'; var assert = require('assert'), common = require('../common'), fork = require('child_process').fork, fork = require('child_process').fork; var cp = fork(common.fixturesDir + '/child-process-message-and-exit.js'); var gotMessage = false, gotExit = false, gotClose = false; cp.on('message', function(message) { assert(!gotMessage); assert(!gotClose); assert.strictEqual(message, 'hello'); gotMessage = true; }); cp.on('exit', function() { assert(!gotExit); assert(!gotClose); gotExit = true; }); cp.on('close', function() { assert(gotMessage); assert(gotExit); assert(!gotClose); gotClose = true; }); process.on('exit', function() { assert(gotMessage); assert(gotExit); assert(gotClose); });
{ "pile_set_name": "Github" }
#tb 0: 1/25 #media_type 0: video #codec_id 0: rawvideo #dimensions 0: 192x128 #sar 0: 0/1 0, 0, 0, 1, 36864, 0x954464be 0, 1, 1, 1, 36864, 0xace1d90b 0, 2, 2, 1, 36864, 0x8f149f03 0, 3, 3, 1, 36864, 0xea9b21eb 0, 4, 4, 1, 36864, 0xb51d9fe3 0, 5, 5, 1, 36864, 0x61bd11d7 0, 6, 6, 1, 36864, 0x9d36980f 0, 7, 7, 1, 36864, 0xa4192c5e 0, 8, 8, 1, 36864, 0x11006433 0, 9, 9, 1, 36864, 0x4a243e46 0, 10, 10, 1, 36864, 0x1807b5e8 0, 11, 11, 1, 36864, 0xbe37743c 0, 12, 12, 1, 36864, 0x82491319 0, 13, 13, 1, 36864, 0x006e9914 0, 14, 14, 1, 36864, 0xa5261884 0, 15, 15, 1, 36864, 0x2030c9d6 0, 16, 16, 1, 36864, 0xc80eb1ce 0, 17, 17, 1, 36864, 0x4d559791 0, 18, 18, 1, 36864, 0xf5f900ee 0, 19, 19, 1, 36864, 0x2cc9c0d7 0, 20, 20, 1, 36864, 0x5ba14186 0, 21, 21, 1, 36864, 0x47a46865 0, 22, 22, 1, 36864, 0x5ba180b7 0, 23, 23, 1, 36864, 0xc67c4876 0, 24, 24, 1, 36864, 0x4311d75d 0, 25, 25, 1, 36864, 0x56edb851 0, 26, 26, 1, 36864, 0x7e5aa3e0 0, 27, 27, 1, 36864, 0x8df8283a 0, 28, 28, 1, 36864, 0xb8583ddf 0, 29, 29, 1, 36864, 0xf33fb779 0, 30, 30, 1, 36864, 0xe9942ddc 0, 31, 31, 1, 36864, 0x2bc5f7fa 0, 32, 32, 1, 36864, 0xc7b66c65 0, 33, 33, 1, 36864, 0x1a524319 0, 34, 34, 1, 36864, 0xf60c6141 0, 35, 35, 1, 36864, 0x113f41f2 0, 36, 36, 1, 36864, 0xad191a31 0, 37, 37, 1, 36864, 0x3898264a 0, 38, 38, 1, 36864, 0x3c2f34a4 0, 39, 39, 1, 36864, 0xd0fc76aa 0, 40, 40, 1, 36864, 0x2870b546 0, 41, 41, 1, 36864, 0x7d326fb4 0, 42, 42, 1, 36864, 0xd7ed14e1 0, 43, 43, 1, 36864, 0x205174aa 0, 44, 44, 1, 36864, 0xa3a88be9 0, 45, 45, 1, 36864, 0xd6f01751 0, 46, 46, 1, 36864, 0x5420bb80 0, 47, 47, 1, 36864, 0xe14518f9 0, 48, 48, 1, 36864, 0x931db61e 0, 49, 49, 1, 36864, 0x052ecfae 0, 50, 50, 1, 36864, 0x29b1b0f5 0, 51, 51, 1, 36864, 0xa3057117 0, 52, 52, 1, 36864, 0x954464be 0, 53, 53, 1, 36864, 0xace1d90b 0, 54, 54, 1, 36864, 0x8f149f03 0, 55, 55, 1, 36864, 0x485722c5 0, 56, 56, 1, 36864, 0x534b18f9 0, 57, 57, 1, 36864, 0xc893a0a6 0, 58, 58, 1, 36864, 0x8b04e1dd 0, 59, 59, 1, 36864, 0xaf536964
{ "pile_set_name": "Github" }
\i setup.sql SELECT plan(656); SELECT has_function('pgr_bddijkstracost', ARRAY['text', 'bigint', 'bigint', 'boolean']); SELECT has_function('pgr_bddijkstracost', ARRAY['text', 'anyarray', 'bigint', 'boolean']); SELECT has_function('pgr_bddijkstracost', ARRAY['text', 'bigint', 'anyarray', 'boolean']); SELECT has_function('pgr_bddijkstracost', ARRAY['text', 'anyarray', 'anyarray', 'boolean']); SELECT function_returns('pgr_bddijkstracost', ARRAY['text', 'bigint', 'bigint', 'boolean'], 'setof record'); SELECT function_returns('pgr_bddijkstracost', ARRAY['text', 'bigint', 'anyarray', 'boolean'], 'setof record'); SELECT function_returns('pgr_bddijkstracost', ARRAY['text', 'anyarray', 'bigint', 'boolean'], 'setof record'); SELECT function_returns('pgr_bddijkstracost', ARRAY['text', 'anyarray', 'anyarray', 'boolean'], 'setof record'); SELECT style_dijkstra('pgr_bddijkstracost', ', 2, 3, true)'); SELECT style_dijkstra('pgr_bddijkstracost', ', 2, ARRAY[3], true)'); SELECT style_dijkstra('pgr_bddijkstracost', ', 2, ARRAY[3], true)'); SELECT style_dijkstra('pgr_bddijkstracost', ', ARRAY[2], ARRAY[3], true)'); SELECT style_dijkstra('pgr_bddijkstracost', ', 2, 3)'); SELECT style_dijkstra('pgr_bddijkstracost', ', 2, ARRAY[3])'); SELECT style_dijkstra('pgr_bddijkstracost', ', 2, ARRAY[3])'); SELECT style_dijkstra('pgr_bddijkstracost', ', ARRAY[2], ARRAY[3])'); SELECT style_dijkstra('pgr_bddijkstracost', ', 2, 3, false)'); SELECT style_dijkstra('pgr_bddijkstracost', ', 2, ARRAY[3], false)'); SELECT style_dijkstra('pgr_bddijkstracost', ', 2, ARRAY[3], false)'); SELECT style_dijkstra('pgr_bddijkstracost', ', ARRAY[2], ARRAY[3], false)'); SELECT finish(); ROLLBACK;
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Markup; using Granular.Collections; namespace System.Windows.Markup { public interface IDeferredValueKeyProvider { object GetValueKey(XamlElement element); } public class DeferredValueKeyProviderAttribute : Attribute { public Type ProviderType { get; private set; } public DeferredValueKeyProviderAttribute(Type providerType) { this.ProviderType = providerType; } } public static class DeferredValueKeyProviders { private static CacheDictionary<Type, IDeferredValueKeyProvider> DeferredValueKeyProviderCache = CacheDictionary<Type, IDeferredValueKeyProvider>.CreateUsingStringKeys(ResolveDeferredValueKeyProvider, type => type.FullName); public static IDeferredValueKeyProvider GetDeferredValueKeyProvider(Type type) { return DeferredValueKeyProviderCache.GetValue(type); } private static IDeferredValueKeyProvider ResolveDeferredValueKeyProvider(Type type) { DeferredValueKeyProviderAttribute deferredValueKeyProviderAttribute = type.GetCustomAttributes(typeof(DeferredValueKeyProviderAttribute), false).FirstOrDefault() as DeferredValueKeyProviderAttribute; if (deferredValueKeyProviderAttribute != null) { return Activator.CreateInstance(deferredValueKeyProviderAttribute.ProviderType) as IDeferredValueKeyProvider; } return null; } } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0"> <PropertyGroup> <PublishProtocol>FileSystem</PublishProtocol> <Configuration>Release</Configuration> <Platform>Any CPU</Platform> <TargetFramework>netcoreapp3.0</TargetFramework> <TrimUnusedDependencies>true</TrimUnusedDependencies> <PublishDir>bin\Release\</PublishDir> <RuntimeIdentifier>win-x86</RuntimeIdentifier> <SelfContained>true</SelfContained> </PropertyGroup> </Project>
{ "pile_set_name": "Github" }
// MESSAGE MISSION_SET_CURRENT PACKING #define MAVLINK_MSG_ID_MISSION_SET_CURRENT 41 typedef struct __mavlink_mission_set_current_t { uint16_t seq; ///< Sequence uint8_t target_system; ///< System ID uint8_t target_component; ///< Component ID } mavlink_mission_set_current_t; #define MAVLINK_MSG_ID_MISSION_SET_CURRENT_LEN 4 #define MAVLINK_MSG_ID_41_LEN 4 #define MAVLINK_MESSAGE_INFO_MISSION_SET_CURRENT \ { \ "MISSION_SET_CURRENT", \ 3, \ { \ { "seq", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_mission_set_current_t, seq) }, \ { "target_system", NULL, MAVLINK_TYPE_UINT8_T, 0, 2, offsetof(mavlink_mission_set_current_t, target_system) }, \ { "target_component", NULL, MAVLINK_TYPE_UINT8_T, 0, 3, offsetof(mavlink_mission_set_current_t, target_component) }, \ } \ } /** * @brief Pack a mission_set_current message * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param msg The MAVLink message to compress the data into * * @param target_system System ID * @param target_component Component ID * @param seq Sequence * @return length of the message in bytes (excluding serial stream start sign) */ static inline uint16_t mavlink_msg_mission_set_current_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t *msg, uint8_t target_system, uint8_t target_component, uint16_t seq) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[4]; _mav_put_uint16_t(buf, 0, seq); _mav_put_uint8_t(buf, 2, target_system); _mav_put_uint8_t(buf, 3, target_component); memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, 4); #else mavlink_mission_set_current_t packet; packet.seq = seq; packet.target_system = target_system; packet.target_component = target_component; memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, 4); #endif msg->msgid = MAVLINK_MSG_ID_MISSION_SET_CURRENT; return mavlink_finalize_message(msg, system_id, component_id, 4, 28); } /** * @brief Pack a mission_set_current message on a channel * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param chan The MAVLink channel this message was sent over * @param msg The MAVLink message to compress the data into * @param target_system System ID * @param target_component Component ID * @param seq Sequence * @return length of the message in bytes (excluding serial stream start sign) */ static inline uint16_t mavlink_msg_mission_set_current_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t *msg, uint8_t target_system, uint8_t target_component, uint16_t seq) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[4]; _mav_put_uint16_t(buf, 0, seq); _mav_put_uint8_t(buf, 2, target_system); _mav_put_uint8_t(buf, 3, target_component); memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, 4); #else mavlink_mission_set_current_t packet; packet.seq = seq; packet.target_system = target_system; packet.target_component = target_component; memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, 4); #endif msg->msgid = MAVLINK_MSG_ID_MISSION_SET_CURRENT; return mavlink_finalize_message_chan(msg, system_id, component_id, chan, 4, 28); } /** * @brief Encode a mission_set_current struct into a message * * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param msg The MAVLink message to compress the data into * @param mission_set_current C-struct to read the message contents from */ static inline uint16_t mavlink_msg_mission_set_current_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t *msg, const mavlink_mission_set_current_t *mission_set_current) { return mavlink_msg_mission_set_current_pack(system_id, component_id, msg, mission_set_current->target_system, mission_set_current->target_component, mission_set_current->seq); } /** * @brief Send a mission_set_current message * @param chan MAVLink channel to send the message * * @param target_system System ID * @param target_component Component ID * @param seq Sequence */ #ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS static inline void mavlink_msg_mission_set_current_send(mavlink_channel_t chan, uint8_t target_system, uint8_t target_component, uint16_t seq) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[4]; _mav_put_uint16_t(buf, 0, seq); _mav_put_uint8_t(buf, 2, target_system); _mav_put_uint8_t(buf, 3, target_component); _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_SET_CURRENT, buf, 4, 28); #else mavlink_mission_set_current_t packet; packet.seq = seq; packet.target_system = target_system; packet.target_component = target_component; _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_MISSION_SET_CURRENT, (const char *)&packet, 4, 28); #endif } #endif // ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS // MESSAGE MISSION_SET_CURRENT UNPACKING /** * @brief Get field target_system from mission_set_current message * * @return System ID */ static inline uint8_t mavlink_msg_mission_set_current_get_target_system(const mavlink_message_t *msg) { return _MAV_RETURN_uint8_t(msg, 2); } /** * @brief Get field target_component from mission_set_current message * * @return Component ID */ static inline uint8_t mavlink_msg_mission_set_current_get_target_component(const mavlink_message_t *msg) { return _MAV_RETURN_uint8_t(msg, 3); } /** * @brief Get field seq from mission_set_current message * * @return Sequence */ static inline uint16_t mavlink_msg_mission_set_current_get_seq(const mavlink_message_t *msg) { return _MAV_RETURN_uint16_t(msg, 0); } /** * @brief Decode a mission_set_current message into a struct * * @param msg The message to decode * @param mission_set_current C-struct to decode the message contents into */ static inline void mavlink_msg_mission_set_current_decode(const mavlink_message_t *msg, mavlink_mission_set_current_t *mission_set_current) { #if MAVLINK_NEED_BYTE_SWAP mission_set_current->seq = mavlink_msg_mission_set_current_get_seq(msg); mission_set_current->target_system = mavlink_msg_mission_set_current_get_target_system(msg); mission_set_current->target_component = mavlink_msg_mission_set_current_get_target_component(msg); #else memcpy(mission_set_current, _MAV_PAYLOAD(msg), 4); #endif }
{ "pile_set_name": "Github" }
Youkai Watch (JPN) Downloaded From Fort42: GateShark Credits and instructions: http://www.fort42.com/gateshark/game544/ ---------------------------------------------------- [Max Money] 08695118 000F423F [Items you own x99] C0000000 000000FE 28695850 00000063 DC000000 00000010 D1000000 00000000 [255 first yokai Max HP] C0000000 000000FE 18687F98 000003E7 18687FBC 000003E7 DC000000 000000C4 D1000000 00000000 [255 first yokai techniques masterized] C0000000 000000FE 28687F8A 0000000A 28687F8E 0000000A 28687F92 0000000A DC000000 000000C4 D1000000 00000000 [255 first yokai max stats] C0000000 000000FE 18687FBE 000003E7 18687FC0 000003E7 18687FC2 000003E7 18687FC4 000003E7 DC000000 000000C4 D1000000 00000000 [255 first yokai max strenght] C0000000 000000FE 18687FBE 000003E7 DC000000 000000C4 D1000000 00000000 [255 first yokai max spirit] C0000000 000000FE 18687FC0 000003E7 DC000000 000000C4 D1000000 00000000 [255 first yokai max defense] C0000000 000000FE 18687FC2 000003E7 DC000000 000000C4 D1000000 00000000 [255 first yokai max speed] C0000000 000000FE 18687FC4 000003E7 DC000000 000000C4 D1000000 00000000
{ "pile_set_name": "Github" }
@charset "utf-8"; //主页面皮肤下拉列表公共样式 $head-height: 56px !default; $line-height: 22px !default; $icon-size: $line-height !default; $action-font-size: 12px !default;; %page_home_skin_actions{ .action_skin, .action_exit, .action_home, .action_language{ display: inline-block; font-size: $action-font-size; height: $icon-size; line-height: $icon-size; &:before{ content:""; display: inline-block; height: $icon-size; line-height: $icon-size; width: $icon-size; margin-right: 3px; vertical-align: top; @include renderSpriteImage(); } } .action_skin:before { @extend %page_home_action_skin; } .action_exit:before { @extend %page_home_action_exit; } .action_home:before { @extend %page_home_action_home; } .action_language:before{ @extend %page_home_action_language; } } .skins { $arrow-width: 20px; $arrow-height: 14px; $skin-left: 15px; width: 140px; top: $line-height; padding-top: $arrow-height; position: absolute; left: -$skin-left; display: none; z-index: 9; .skins-cont { position: relative; border: 1px solid #ccc; background: #fff; padding: 15px 8px 5px 8px; } .skins-cont-top { position: absolute; z-index: 2; width: $arrow-width; height: $arrow-height; top: -$arrow-height; left: $skin-left + 10; //让箭头指向图标的中间 @include renderSpriteImage(); @extend %page_home_skin_arrow; } .skins-list { li { border: 1px solid #ccc; border-radius: 3px; background: #e6eef2; margin-bottom: 10px; list-style-type: none; &:hover { border-color: #fa0; span { background-color: #fa0; } } } div { position: relative; width: 120px; height: 88px; @include renderSpriteImage(); &.active { span { background-color: #ffaa00; padding-right: $icon-size; &:after { position: absolute; right: 0; width: $icon-size; height: $icon-size; content:""; @include renderSpriteImage(); @extend %page_home_skin_item_selected; } } } } span { position: absolute; right: 2px; bottom: 3px; background: #8d9294; height: $line-height; line-height: $line-height; padding: 0 10px; border-radius: 10px; font-size: 12px; } .skin-simple { @extend %page_home_skin_simple; } .skin-classics { @extend %page_home_skin_classic; } .skin-tabs { @extend %page_home_skin_tabs; } .skin-mobile { @extend %page_home_skin_mobile; } .skin-patrol { @extend %page_home_skin_patrol; } .skin-dynamic-patrol { @extend %page_home_skin_dynamic_patrol; } } }
{ "pile_set_name": "Github" }
Dominica 1 -6.190110E+01 1.554550E+01 -6.144157E+01 1.578591E+01 -6.084391E+01 1.557876E+01 -6.086251E+01 1.518179E+01 -6.170719E+01 1.487908E+01 -6.190110E+01 1.554550E+01 END END
{ "pile_set_name": "Github" }
--- id: 598f48a36c8c40764b4e52b3 title: Prevent Object Mutation challengeType: 1 forumTopicId: 301207 --- ## Description <section id='description'> As seen in the previous challenge, <code>const</code> declaration alone doesn't really protect your data from mutation. To ensure your data doesn't change, JavaScript provides a function <code>Object.freeze</code> to prevent data mutation. Once the object is frozen, you can no longer add, update, or delete properties from it. Any attempt at changing the object will be rejected without an error. ```js let obj = { name:"FreeCodeCamp", review:"Awesome" }; Object.freeze(obj); obj.review = "bad"; // will be ignored. Mutation not allowed obj.newProp = "Test"; // will be ignored. Mutation not allowed console.log(obj); // { name: "FreeCodeCamp", review:"Awesome"} ``` </section> ## Instructions <section id='instructions'> In this challenge you are going to use <code>Object.freeze</code> to prevent mathematical constants from changing. You need to freeze the <code>MATH_CONSTANTS</code> object so that no one is able to alter the value of <code>PI</code>, add, or delete properties. </section> ## Tests <section id='tests'> ```yml tests: - text: You should not replace <code>const</code> keyword. testString: getUserInput => assert(getUserInput('index').match(/const/g)); - text: <code>MATH_CONSTANTS</code> should be a constant variable (by using <code>const</code>). testString: getUserInput => assert(getUserInput('index').match(/const\s+MATH_CONSTANTS/g)); - text: You should not change original <code>MATH_CONSTANTS</code>. testString: getUserInput => assert(getUserInput('index').match(/const\s+MATH_CONSTANTS\s+=\s+{\s+PI:\s+3.14\s+};/g)); - text: <code>PI</code> should equal <code>3.14</code>. testString: assert(PI === 3.14); ``` </section> ## Challenge Seed <section id='challengeSeed'> <div id='js-seed'> ```js function freezeObj() { 'use strict'; const MATH_CONSTANTS = { PI: 3.14 }; // Only change code below this line // Only change code above this line try { MATH_CONSTANTS.PI = 99; } catch(ex) { console.log(ex); } return MATH_CONSTANTS.PI; } const PI = freezeObj(); ``` </div> </section> ## Solution <section id='solution'> ```js function freezeObj() { 'use strict'; const MATH_CONSTANTS = { PI: 3.14 }; Object.freeze(MATH_CONSTANTS); try { MATH_CONSTANTS.PI = 99; } catch(ex) { console.log(ex); } return MATH_CONSTANTS.PI; } const PI = freezeObj(); ``` </section>
{ "pile_set_name": "Github" }
our($ri1, $rf1, $rfe1); BEGIN { $ri1 = $^H; $rf1 = $^H{foo}; $rfe1 = exists($^H{foo}); } 1;
{ "pile_set_name": "Github" }
/* $Id: hfc_sx.h,v 1.2.6.1 2001/09/23 22:24:48 kai Exp $ * * specific defines for CCD's HFC 2BDS0 S+,SP chips * * Author Werner Cornelius * based on existing driver for CCD HFC PCI cards * Copyright by Werner Cornelius <werner@isdn4linux.de> * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ /*********************************************/ /* thresholds for transparent B-channel mode */ /* change mask and threshold simultaneously */ /*********************************************/ #define HFCSX_BTRANS_THRESHOLD 128 #define HFCSX_BTRANS_THRESMASK 0x00 /* GCI/IOM bus monitor registers */ #define HFCSX_C_I 0x02 #define HFCSX_TRxR 0x03 #define HFCSX_MON1_D 0x0A #define HFCSX_MON2_D 0x0B /* GCI/IOM bus timeslot registers */ #define HFCSX_B1_SSL 0x20 #define HFCSX_B2_SSL 0x21 #define HFCSX_AUX1_SSL 0x22 #define HFCSX_AUX2_SSL 0x23 #define HFCSX_B1_RSL 0x24 #define HFCSX_B2_RSL 0x25 #define HFCSX_AUX1_RSL 0x26 #define HFCSX_AUX2_RSL 0x27 /* GCI/IOM bus data registers */ #define HFCSX_B1_D 0x28 #define HFCSX_B2_D 0x29 #define HFCSX_AUX1_D 0x2A #define HFCSX_AUX2_D 0x2B /* GCI/IOM bus configuration registers */ #define HFCSX_MST_EMOD 0x2D #define HFCSX_MST_MODE 0x2E #define HFCSX_CONNECT 0x2F /* Interrupt and status registers */ #define HFCSX_TRM 0x12 #define HFCSX_B_MODE 0x13 #define HFCSX_CHIP_ID 0x16 #define HFCSX_CIRM 0x18 #define HFCSX_CTMT 0x19 #define HFCSX_INT_M1 0x1A #define HFCSX_INT_M2 0x1B #define HFCSX_INT_S1 0x1E #define HFCSX_INT_S2 0x1F #define HFCSX_STATUS 0x1C /* S/T section registers */ #define HFCSX_STATES 0x30 #define HFCSX_SCTRL 0x31 #define HFCSX_SCTRL_E 0x32 #define HFCSX_SCTRL_R 0x33 #define HFCSX_SQ 0x34 #define HFCSX_CLKDEL 0x37 #define HFCSX_B1_REC 0x3C #define HFCSX_B1_SEND 0x3C #define HFCSX_B2_REC 0x3D #define HFCSX_B2_SEND 0x3D #define HFCSX_D_REC 0x3E #define HFCSX_D_SEND 0x3E #define HFCSX_E_REC 0x3F /****************/ /* FIFO section */ /****************/ #define HFCSX_FIF_SEL 0x10 #define HFCSX_FIF_Z1L 0x80 #define HFCSX_FIF_Z1H 0x84 #define HFCSX_FIF_Z2L 0x88 #define HFCSX_FIF_Z2H 0x8C #define HFCSX_FIF_INCF1 0xA8 #define HFCSX_FIF_DWR 0xAC #define HFCSX_FIF_F1 0xB0 #define HFCSX_FIF_F2 0xB4 #define HFCSX_FIF_INCF2 0xB8 #define HFCSX_FIF_DRD 0xBC /* bits in status register (READ) */ #define HFCSX_SX_PROC 0x02 #define HFCSX_NBUSY 0x04 #define HFCSX_TIMER_ELAP 0x10 #define HFCSX_STATINT 0x20 #define HFCSX_FRAMEINT 0x40 #define HFCSX_ANYINT 0x80 /* bits in CTMT (Write) */ #define HFCSX_CLTIMER 0x80 #define HFCSX_TIM3_125 0x04 #define HFCSX_TIM25 0x10 #define HFCSX_TIM50 0x14 #define HFCSX_TIM400 0x18 #define HFCSX_TIM800 0x1C #define HFCSX_AUTO_TIMER 0x20 #define HFCSX_TRANSB2 0x02 #define HFCSX_TRANSB1 0x01 /* bits in CIRM (Write) */ #define HFCSX_IRQ_SELMSK 0x07 #define HFCSX_IRQ_SELDIS 0x00 #define HFCSX_RESET 0x08 #define HFCSX_FIFO_RESET 0x80 /* bits in INT_M1 and INT_S1 */ #define HFCSX_INTS_B1TRANS 0x01 #define HFCSX_INTS_B2TRANS 0x02 #define HFCSX_INTS_DTRANS 0x04 #define HFCSX_INTS_B1REC 0x08 #define HFCSX_INTS_B2REC 0x10 #define HFCSX_INTS_DREC 0x20 #define HFCSX_INTS_L1STATE 0x40 #define HFCSX_INTS_TIMER 0x80 /* bits in INT_M2 */ #define HFCSX_PROC_TRANS 0x01 #define HFCSX_GCI_I_CHG 0x02 #define HFCSX_GCI_MON_REC 0x04 #define HFCSX_IRQ_ENABLE 0x08 /* bits in STATES */ #define HFCSX_STATE_MSK 0x0F #define HFCSX_LOAD_STATE 0x10 #define HFCSX_ACTIVATE 0x20 #define HFCSX_DO_ACTION 0x40 #define HFCSX_NT_G2_G3 0x80 /* bits in HFCD_MST_MODE */ #define HFCSX_MASTER 0x01 #define HFCSX_SLAVE 0x00 /* remaining bits are for codecs control */ /* bits in HFCD_SCTRL */ #define SCTRL_B1_ENA 0x01 #define SCTRL_B2_ENA 0x02 #define SCTRL_MODE_TE 0x00 #define SCTRL_MODE_NT 0x04 #define SCTRL_LOW_PRIO 0x08 #define SCTRL_SQ_ENA 0x10 #define SCTRL_TEST 0x20 #define SCTRL_NONE_CAP 0x40 #define SCTRL_PWR_DOWN 0x80 /* bits in SCTRL_E */ #define HFCSX_AUTO_AWAKE 0x01 #define HFCSX_DBIT_1 0x04 #define HFCSX_IGNORE_COL 0x08 #define HFCSX_CHG_B1_B2 0x80 /**********************************/ /* definitions for FIFO selection */ /**********************************/ #define HFCSX_SEL_D_RX 5 #define HFCSX_SEL_D_TX 4 #define HFCSX_SEL_B1_RX 1 #define HFCSX_SEL_B1_TX 0 #define HFCSX_SEL_B2_RX 3 #define HFCSX_SEL_B2_TX 2 #define MAX_D_FRAMES 15 #define MAX_B_FRAMES 31 #define B_SUB_VAL_32K 0x0200 #define B_FIFO_SIZE_32K (0x2000 - B_SUB_VAL_32K) #define B_SUB_VAL_8K 0x1A00 #define B_FIFO_SIZE_8K (0x2000 - B_SUB_VAL_8K) #define D_FIFO_SIZE 512 #define D_FREG_MASK 0xF /************************************************************/ /* structure holding additional dynamic data -> send marker */ /************************************************************/ struct hfcsx_extra { unsigned short marker[2 * (MAX_B_FRAMES + 1) + (MAX_D_FRAMES + 1)]; }; extern void main_irq_hfcsx(struct BCState *bcs); extern void releasehfcsx(struct IsdnCardState *cs);
{ "pile_set_name": "Github" }
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved // Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license /** * @summary Creates layout for a form element * @name base * @selector .slds-form-element * @restrict div, fieldset, li * @support dev-ready * @variant */ .slds-form-element { position: relative; min-width: 0; } /** * @summary Creates label styles for our form elements * @selector .slds-form-element__label * @restrict .slds-form-element label, .slds-form-element span, .slds-form-element legend, .slds-form-element div, [class*='slds-checkbox'] span, [class*='slds-radio'] span */ .slds-form-element__label { @include hyphenate; display: inline-block; color: $color-text-label; font-size: $form-label-font-size; padding-right: $spacing-x-small; padding-top: $spacing-xx-small; margin-bottom: $spacing-xxx-small; &:empty { margin: 0; } } /** * @summary Wrapper to any form display element * @selector .slds-form-element__control * @restrict .slds-form-element div */ .slds-form-element__control { // This clear:left is due to the label of the form element being set to float: left since we don't know if the help-text icon is present in the DOM. Since legend elements can only be floated to modifiy layout to accomodate the help-text icon, we need to make sure the control stacks below the label by default clear: left; position: relative; // Force radios and checkboxes to be on own line when there are multiples in a group .slds-radio, .slds-checkbox { display: block; } } /** * @summary When an icon sits within a form element wrapper and adjacent to another element inside that wrapper such as a .form-element__label * @selector .slds-form-element__icon * @restrict .slds-form-element div */ .slds-form-element__icon { display: inline-block; position: relative; // Since this container can have a tooltip padding-top: $spacing-xx-small; vertical-align: top; line-height: $line-height-reset; z-index: 1; // Helps ensure the help-text icon is clickable in all implementations .slds-button_icon { position: relative; // Resetting position since the edit button icon to invoke inline-edit is set to position: absolute } } /** * @summary Creates inline help styles, sits below .form-element__control * @selector .slds-form-element__help * @restrict .slds-form-element div */ .slds-form-element__help, .slds-form-element__helper { font-size: $font-size-2; margin-top: $spacing-xxx-small; display: block; } /** * @summary Modifier on slds-form-element that it needs to reserve space for the inline-edit trigger button * @selector .slds-form-element_edit * @restrict .slds-form-element */ .slds-form-element_edit, .slds-form-element--edit { .slds-form-element__static { width: calc(100% - #{$square-icon-small-boundary}); // Leave space for edit icon } } /** * @summary When a form element is in view mode, we modify some styling * @selector .slds-form-element_readonly * @restrict .slds-form-element */ .slds-form-element_readonly { flex-basis: 0%; border-bottom: $border-width-thin solid $color-border; margin-bottom: 0; .slds-form-element__control { padding-top: $spacing-xxx-small; padding-bottom: $spacing-xxx-small; // Heads up: no touch-device() min-height is intended per design which deviates from touch input height system } // We want no spacing in read only and allow line-height to handle white-space .slds-form-element__label { margin-bottom: 0; } } /** * @summary The form element label when applied to a legend element * @selector .slds-form-element__legend * @restrict .slds-form-element legend, .slds-form-element span */ .slds-form-element__legend { font-weight: $font-weight-bold; float: left; // Required to be float: left to accommodate for help-text icon } /** * @summary Fixed text that sits to the left or right of an input * @selector .slds-form-element__addon * @restrict .slds-form-element span */ .slds-form-element__addon { display: inline-block; margin: 0 $spacing-x-small; align-self: center; } /** * @summary Read-only components are used to display immutable data within a form * @summary Initializes read-only form element * @selector .slds-form-element__static * @restrict .slds-form-element span, .slds-form-element div */ .slds-form-element__static { @include break-word; display: inline-block; font-size: $input-static-font-size; font-weight: $input-static-font-weight; color: $input-static-color; width: 100%; &.slds-text-longform *:last-child { margin-bottom: 0; } &:empty { min-height: calc(#{$var-font-size-7} + 1px); // 22px|20px + 1px vertical-align: bottom; } /** * @summary Inline Edit on static form element * @selector .slds-form-element__static_edit * @restrict .slds-form-element__static * @deprecated */ &--edit { width: calc(100% - #{$square-icon-small-boundary}); // Leave space for edit icon } } /** * @summary Required asterisk * @selector .slds-required * @restrict .slds-form-element abbr, abbr */ .slds-required { color: $color-text-error; margin: 0 $spacing-xxx-small; } /** * @summary Error styles for form element * @selector .slds-has-error * @restrict .slds-form-element * @modifier * @group feedback */ .slds-has-error { .slds-form-element__help { color: $color-text-error; } }
{ "pile_set_name": "Github" }
{"1179": 0.23512073149405358} {"1106": 0.228654571409621} {"652": 0.26706320871106765} {"617": 0.25888070620540204} {"529": 0.23796719398186578} {"1336": 0.22708931518452144} {"560": 0.2612410483304467} {"569": 0.25344843499981895, "556": 0.24737922264439613} {"864": 0.22093242105651731, "1369": 0.21443143954958546, "76": 0.40886685944828904, "1239": 0.21973134129865812} {"578": 0.24341360801328762} {"565": 0.22537008065000699} {"565": 0.22537008065000699} {"852": 0.24665007174833561} {"585": 0.20568709444011163, "593": 0.2111648504919568} {"798": 0.23752138082151483} {"1146": 0.26372473331822505} {"970": 0.49241241628743165} {"565": 0.22537008065000699} {"1179": 0.23512073149405358} {"1434": 0.24199816170253058} {"137": 0.2303888589730046} {"1310": 0.23764658131335351} {"1430": 0.25725355551917889} {"631": 0.22755810285217448} {"694": 0.23557849339442957} {"64": 0.24006964581180151} {"1006": 0.41449628448151665} {"674": 0.24046207318157189} {"523": 0.2326400032896663} {"523": 0.2326400032896663} {"293": 0.25487102517929688} {"745": 0.25646022913234029} {"964": 0.24960912218491935} {"899": 0.23962299579755325} {"678": 0.47617484462379728} {"1409": 0.22876936141504556} {"500": 0.25316108127895848} {"935": 0.25024624638360504} {"694": 0.23557849339442957} {"930": 0.24397712364164292} {"842": 0.24971400597247123} {"41": 0.23893312924561128} {"500": 0.25316108127895848} {"10": 0.23406045565083938} {"938": 0.24081849542597181} {"849": 0.21599952923357182, "1042": 0.21691626531835001, "1449": 0.22383080563615174, "1141": 0.21833538294901292, "247": 0.22693284763697358} {"560": 0.2612410483304467} {"567": 0.23239051559499777} {"44": 0.25088912095966992} {"578": 0.24341360801328762} {"925": 0.24438902348815275} {"685": 0.2407830851122072, "678": 0.22537824222837052} {"1012": 0.25750021664711448, "678": 0.22537824222837052} {"852": 0.24665007174833561} {"151": 0.26128454362670561} {"527": 0.24300391288770593} {"1347": 0.22790454872534552, "1175": 0.22357866579787608} {"942": 0.23721967139914463} {"141": 0.25581976709249948} {"788": 0.23779520229913709} {"578": 0.24341360801328762} {"969": 0.24555643831723051} {"930": 0.24397712364164292} {"578": 0.24341360801328762} {"593": 0.22307253104567326} {"565": 0.22537008065000699} {"36": 0.23543685280498811} {"952": 0.26686593300373918} {"738": 0.45426349478116546} {"44": 0.25088912095966992} {"694": 0.23557849339442957} {"915": 0.26148178514411891} {"694": 0.23557849339442957} {"576": 0.18564556757965958, "548": 0.18541124832192993, "581": 0.18863738882564113, "519": 0.18882982873769058, "1143": 0.17801192740093244, "492": 0.19238649675442196, "525": 0.18378408000683025, "498": 0.18214579951657511, "633": 0.1897550190960772, "535": 0.1838247094663058, "185": 0.18795764874691565, "603": 0.18373198921238931, "540": 0.19083171449275435, "574": 0.1789275813611691} {"1123": 0.24285689571356381} {"1347": 0.24075618836441365} {"1457": 0.23949186744617962} {"631": 0.22755810285217448} {"1007": 0.2437537198484607} {"1313": 0.25105740996079901} {"137": 0.2303888589730046} {"585": 0.43457176375036721} {"496": 0.24591901488043832, "619": 0.2407540709168863} {"1325": 0.2637374022414995} {"44": 0.25088912095966992} {"560": 0.2612410483304467} {"529": 0.23796719398186578} {"798": 0.23752138082151483} {"509": 0.25746384133671257} {"631": 0.22755810285217448} {"336": 0.23998904711335559} {"857": 0.24721943813444125} {"1123": 0.24285689571356381} {"102": 0.39871020965426923} {"921": 0.23885438399743503, "692": 0.2692890122309623} {"1061": 0.23418589807881479} {"513": 0.2421764047236647} {"1019": 0.46394596718371534} {"951": 0.23480360996586586} {"1000": 0.40487795347937966, "988": 0.43438296548875571}
{ "pile_set_name": "Github" }
#ifndef FIX43_SECURITYTYPES_H #define FIX43_SECURITYTYPES_H #include "Message.h" namespace FIX43 { class SecurityTypes : public Message { public: SecurityTypes() : Message(MsgType()) {} SecurityTypes(const FIX::Message& m) : Message(m) {} SecurityTypes(const Message& m) : Message(m) {} SecurityTypes(const SecurityTypes& m) : Message(m) {} static FIX::MsgType MsgType() { return FIX::MsgType("w"); } SecurityTypes( const FIX::SecurityReqID& aSecurityReqID, const FIX::SecurityResponseID& aSecurityResponseID, const FIX::SecurityResponseType& aSecurityResponseType ) : Message(MsgType()) { set(aSecurityReqID); set(aSecurityResponseID); set(aSecurityResponseType); } FIELD_SET(*this, FIX::SecurityReqID); FIELD_SET(*this, FIX::SecurityResponseID); FIELD_SET(*this, FIX::SecurityResponseType); FIELD_SET(*this, FIX::TotalNumSecurityTypes); FIELD_SET(*this, FIX::Text); FIELD_SET(*this, FIX::EncodedTextLen); FIELD_SET(*this, FIX::EncodedText); FIELD_SET(*this, FIX::TradingSessionID); FIELD_SET(*this, FIX::TradingSessionSubID); FIELD_SET(*this, FIX::SubscriptionRequestType); FIELD_SET(*this, FIX::NoSecurityTypes); class NoSecurityTypes: public FIX::Group { public: NoSecurityTypes() : FIX::Group(558,167,FIX::message_order(167,460,461,0)) {} FIELD_SET(*this, FIX::SecurityType); FIELD_SET(*this, FIX::Product); FIELD_SET(*this, FIX::CFICode); }; }; } #endif
{ "pile_set_name": "Github" }
/* SPDX-License-Identifier: GPL-2.0 */ #ifndef JSON_H #define JSON_H 1 #include "jsmn.h" jsmntok_t *parse_json(const char *fn, char **map, size_t *size, int *len); void free_json(char *map, size_t size, jsmntok_t *tokens); int json_line(char *map, jsmntok_t *t); const char *json_name(jsmntok_t *t); int json_streq(char *map, jsmntok_t *t, const char *s); int json_len(jsmntok_t *t); extern int verbose; #include <stdbool.h> extern int eprintf(int level, int var, const char *fmt, ...); #define pr_fmt(fmt) fmt #define pr_err(fmt, ...) \ eprintf(0, verbose, pr_fmt(fmt), ##__VA_ARGS__) #define pr_info(fmt, ...) \ eprintf(1, verbose, pr_fmt(fmt), ##__VA_ARGS__) #define pr_debug(fmt, ...) \ eprintf(2, verbose, pr_fmt(fmt), ##__VA_ARGS__) #ifndef roundup #define roundup(x, y) ( \ { \ const typeof(y) __y = y; \ (((x) + (__y - 1)) / __y) * __y; \ } \ ) #endif #endif
{ "pile_set_name": "Github" }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifdef __sun__ #include "support/solaris/xlocale.h" #include <stdarg.h> #include <stdio.h> #include <sys/localedef.h> extern "C" { int isxdigit_l(int __c, locale_t __l) { return isxdigit(__c); } int iswxdigit_l(wint_t __c, locale_t __l) { return isxdigit(__c); } // FIXME: This disregards the locale, which is Very Wrong #define vsnprintf_l(__s, __n, __l, __format, __va) \ vsnprintf(__s, __n, __format, __va) int snprintf_l(char *__s, size_t __n, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); int __res = vsnprintf_l(__s, __n , __l, __format, __va); va_end(__va); return __res; } int asprintf_l(char **__s, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); // FIXME: int __res = vasprintf(__s, __format, __va); va_end(__va); return __res; } int sscanf_l(const char *__s, locale_t __l, const char *__format, ...) { va_list __va; va_start(__va, __format); // FIXME: int __res = vsscanf(__s, __format, __va); va_end(__va); return __res; } size_t mbrtowc_l(wchar_t *__pwc, const char *__pmb, size_t __max, mbstate_t *__ps, locale_t __loc) { return mbrtowc(__pwc, __pmb, __max, __ps); } struct lconv *localeconv_l(locale_t __l) { return localeconv(); } }; #endif // __sun__
{ "pile_set_name": "Github" }
```python """ Please note, this script is for python3+. If you are using python2+, please modify it accordingly. Tutorial reference: http://www.scipy-lectures.org/intro/matplotlib/matplotlib.html """ import matplotlib.pyplot as plt import numpy as np x = np.linspace(-3, 3, 50) y1 = 2*x + 1 y2 = x**2 plt.figure() plt.plot(x, y2) # plot the second curve in this figure with certain parameters plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--') # set x limits plt.xlim((-1, 2)) plt.ylim((-2, 3)) # set new ticks new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks) # set tick labels plt.yticks([-2, -1.8, -1, 1.22, 3], ['$really\ bad$', '$bad$', '$normal$', '$good$', '$really\ good$']) # to use '$ $' for math text and nice looking, e.g. '$\pi$' # gca = 'get current axis' ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') # ACCEPTS: [ 'top' | 'bottom' | 'both' | 'default' | 'none' ] ax.spines['bottom'].set_position(('data', 0)) # the 1st is in 'outward' | 'axes' | 'data' # axes: percentage of y axis # data: depend on y data ax.yaxis.set_ticks_position('left') # ACCEPTS: [ 'left' | 'right' | 'both' | 'default' | 'none' ] ax.spines['left'].set_position(('data',0)) plt.show() ``` ![image](https://morvanzhou.github.io/static/results/plt/2_4_3.png)
{ "pile_set_name": "Github" }
DataverseUse test Query: SELECT ELEMENT [ Variable [ Name=$m ] ] FROM [ FunctionCall asterix.dataset@1[ LiteralExpr [STRING] [test.FacebookMessages] ] AS Variable [ Name=$m ] ] Where OperatorExpr [ FunctionCall asterix.spatial-intersect@2[ FieldAccessor [ Variable [ Name=$m ] Field=sender-location ] FunctionCall asterix.create-polygon@1[ OrderedListConstructor [ LiteralExpr [DOUBLE] [40.0] LiteralExpr [DOUBLE] [79.87] LiteralExpr [DOUBLE] [30.0] LiteralExpr [DOUBLE] [75.0] LiteralExpr [DOUBLE] [50.0] LiteralExpr [DOUBLE] [80.0] LiteralExpr [DOUBLE] [10.0] LiteralExpr [DOUBLE] [10.0] ] ] ] and OperatorExpr [ FieldAccessor [ Variable [ Name=$m ] Field=send-time ] < FunctionCall asterix.datetime@1[ LiteralExpr [STRING] [2012-11-20T10:10:00.000Z] ] ] ] Orderby FieldAccessor [ Variable [ Name=$m ] Field=send-time ] ASC
{ "pile_set_name": "Github" }
#========================================================================== # # Program: ParaView # # Copyright (c) 2005-2008 Sandia Corporation, Kitware Inc. # All rights reserved. # # ParaView is a free software; you can redistribute it and/or modify it # under the terms of the ParaView license version 1.2. # # See License_v1.2.txt for the full ParaView license. # A copy of this license can be obtained by contacting # Kitware Inc. # 28 Corporate Drive # Clifton Park, NY 12065 # USA # # 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 AUTHORS 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. # #========================================================================== set(classes vtkExtractsDeliveryHelper vtkLiveInsituLink vtkSMInsituStateLoader vtkSMLiveInsituLinkProxy vtkSteeringDataGenerator ) vtk_module_add_module(ParaView::RemotingLive CLASSES ${classes}) paraview_add_server_manager_xmls( XMLS Resources/live_utilities.xml)
{ "pile_set_name": "Github" }
//[hello #include <binlog/binlog.hpp> //] #include <fstream> #include <iostream> //[hello int main() { BINLOG_INFO("Hello {}!", "World"); std::ofstream logfile("hello.blog", std::ofstream::out|std::ofstream::binary); binlog::consume(logfile); //] if (! logfile) { std::cerr << "Failed to write hello.blog\n"; return 1; } std::cout << "Binary log written to hello.blog\n"; return 0; //[hello } //]
{ "pile_set_name": "Github" }
import * as React from "react"; import ReactTable, { TableProps } from "react-table"; import { useSelectableReactTable, SelectionBehaviour, } from "lib/useSelectableItemListing"; import { TableOutProps } from "lib/useSelectableItemListing/types"; import { Activity } from "../api/types"; interface Props { activities: Activity[]; selectableTableProps: TableOutProps<Activity>; } interface Row { value: Activity; } const ActivityCell: React.FunctionComponent<Row> = ({ value: activity }) => { return ( <div className="ActivityTable__row"> {activity && activity.details && activity.details.properties && activity.details.properties .filter(({ showInList }) => showInList) .map(({ name, value }, i: number) => { return ( <div className="ActivityTable__row-detail" key={i}> <b>{name}: </b> {value} </div> ); })} </div> ); }; const COLUMNS = [ { id: "activity", Header: "Activity", accessor: (u: Activity) => u, Cell: ActivityCell, }, ]; const ActivityTable: React.FunctionComponent<Props> = ({ selectableTableProps: { onKeyDown, tableProps }, }) => ( <div className="fill-space" tabIndex={0} onKeyDown={onKeyDown}> <ReactTable className="fill-space -striped -highlight" {...tableProps} /> </div> ); interface UseTable { componentProps: Props; } export const useTable = ( activities: Activity[], customTableProps?: Partial<TableProps>, ): UseTable => { const selectableTableProps = useSelectableReactTable<Activity>( { getKey: React.useCallback((v) => v.id, []), items: activities, selectionBehaviour: SelectionBehaviour.SINGLE, }, { columns: COLUMNS, ...customTableProps, }, ); return { componentProps: { selectableTableProps, activities, }, }; }; export default ActivityTable;
{ "pile_set_name": "Github" }
If you want to write an option parser, and have it be good, there are two ways to do it. The Right Way, and the Wrong Way. The Wrong Way is to sit down and write an option parser. We've all done that. The Right Way is to write some complex configurable program with so many options that you hit the limit of your frustration just trying to manage them all, and defer it with duct-tape solutions until you see exactly to the core of the problem, and finally snap and write an awesome option parser. If you want to write an option parser, don't write an option parser. Write a package manager, or a source control system, or a service restarter, or an operating system. You probably won't end up with a good one of those, but if you don't give up, and you are relentless and diligent enough in your procrastination, you may just end up with a very nice option parser. ## USAGE // my-program.js var nopt = require("nopt") , Stream = require("stream").Stream , path = require("path") , knownOpts = { "foo" : [String, null] , "bar" : [Stream, Number] , "baz" : path , "bloo" : [ "big", "medium", "small" ] , "flag" : Boolean , "pick" : Boolean , "many1" : [String, Array] , "many2" : [path] } , shortHands = { "foofoo" : ["--foo", "Mr. Foo"] , "b7" : ["--bar", "7"] , "m" : ["--bloo", "medium"] , "p" : ["--pick"] , "f" : ["--flag"] } // everything is optional. // knownOpts and shorthands default to {} // arg list defaults to process.argv // slice defaults to 2 , parsed = nopt(knownOpts, shortHands, process.argv, 2) console.log(parsed) This would give you support for any of the following: ```bash $ node my-program.js --foo "blerp" --no-flag { "foo" : "blerp", "flag" : false } $ node my-program.js ---bar 7 --foo "Mr. Hand" --flag { bar: 7, foo: "Mr. Hand", flag: true } $ node my-program.js --foo "blerp" -f -----p { foo: "blerp", flag: true, pick: true } $ node my-program.js -fp --foofoo { foo: "Mr. Foo", flag: true, pick: true } $ node my-program.js --foofoo -- -fp # -- stops the flag parsing. { foo: "Mr. Foo", argv: { remain: ["-fp"] } } $ node my-program.js --blatzk -fp # unknown opts are ok. { blatzk: true, flag: true, pick: true } $ node my-program.js --blatzk=1000 -fp # but you need to use = if they have a value { blatzk: 1000, flag: true, pick: true } $ node my-program.js --no-blatzk -fp # unless they start with "no-" { blatzk: false, flag: true, pick: true } $ node my-program.js --baz b/a/z # known paths are resolved. { baz: "/Users/isaacs/b/a/z" } # if Array is one of the types, then it can take many # values, and will always be an array. The other types provided # specify what types are allowed in the list. $ node my-program.js --many1 5 --many1 null --many1 foo { many1: ["5", "null", "foo"] } $ node my-program.js --many2 foo --many2 bar { many2: ["/path/to/foo", "path/to/bar"] } ``` Read the tests at the bottom of `lib/nopt.js` for more examples of what this puppy can do. ## Types The following types are supported, and defined on `nopt.typeDefs` * String: A normal string. No parsing is done. * path: A file system path. Gets resolved against cwd if not absolute. * url: A url. If it doesn't parse, it isn't accepted. * Number: Must be numeric. * Date: Must parse as a date. If it does, and `Date` is one of the options, then it will return a Date object, not a string. * Boolean: Must be either `true` or `false`. If an option is a boolean, then it does not need a value, and its presence will imply `true` as the value. To negate boolean flags, do `--no-whatever` or `--whatever false` * NaN: Means that the option is strictly not allowed. Any value will fail. * Stream: An object matching the "Stream" class in node. Valuable for use when validating programmatically. (npm uses this to let you supply any WriteStream on the `outfd` and `logfd` config options.) * Array: If `Array` is specified as one of the types, then the value will be parsed as a list of options. This means that multiple values can be specified, and that the value will always be an array. If a type is an array of values not on this list, then those are considered valid values. For instance, in the example above, the `--bloo` option can only be one of `"big"`, `"medium"`, or `"small"`, and any other value will be rejected. When parsing unknown fields, `"true"`, `"false"`, and `"null"` will be interpreted as their JavaScript equivalents. You can also mix types and values, or multiple types, in a list. For instance `{ blah: [Number, null] }` would allow a value to be set to either a Number or null. When types are ordered, this implies a preference, and the first type that can be used to properly interpret the value will be used. To define a new type, add it to `nopt.typeDefs`. Each item in that hash is an object with a `type` member and a `validate` method. The `type` member is an object that matches what goes in the type list. The `validate` method is a function that gets called with `validate(data, key, val)`. Validate methods should assign `data[key]` to the valid value of `val` if it can be handled properly, or return boolean `false` if it cannot. You can also call `nopt.clean(data, types, typeDefs)` to clean up a config object and remove its invalid properties. ## Error Handling By default, nopt outputs a warning to standard error when invalid values for known options are found. You can change this behavior by assigning a method to `nopt.invalidHandler`. This method will be called with the offending `nopt.invalidHandler(key, val, types)`. If no `nopt.invalidHandler` is assigned, then it will console.error its whining. If it is assigned to boolean `false` then the warning is suppressed. ## Abbreviations Yes, they are supported. If you define options like this: ```javascript { "foolhardyelephants" : Boolean , "pileofmonkeys" : Boolean } ``` Then this will work: ```bash node program.js --foolhar --pil node program.js --no-f --pileofmon # etc. ``` ## Shorthands Shorthands are a hash of shorter option names to a snippet of args that they expand to. If multiple one-character shorthands are all combined, and the combination does not unambiguously match any other option or shorthand, then they will be broken up into their constituent parts. For example: ```json { "s" : ["--loglevel", "silent"] , "g" : "--global" , "f" : "--force" , "p" : "--parseable" , "l" : "--long" } ``` ```bash npm ls -sgflp # just like doing this: npm ls --loglevel silent --global --force --long --parseable ``` ## The Rest of the args The config object returned by nopt is given a special member called `argv`, which is an object with the following fields: * `remain`: The remaining args after all the parsing has occurred. * `original`: The args as they originally appeared. * `cooked`: The args after flags and shorthands are expanded. ## Slicing Node programs are called with more or less the exact argv as it appears in C land, after the v8 and node-specific options have been plucked off. As such, `argv[0]` is always `node` and `argv[1]` is always the JavaScript program being run. That's usually not very useful to you. So they're sliced off by default. If you want them, then you can pass in `0` as the last argument, or any other number that you'd like to slice off the start of the list.
{ "pile_set_name": "Github" }
# frozen_string_literal: true class CreateTopicRevisions < ActiveRecord::Migration[4.2] def up create_table :topic_revisions do |t| t.belongs_to :user t.belongs_to :topic t.text :modifications t.integer :number t.timestamps null: false end execute "INSERT INTO topic_revisions (user_id, topic_id, modifications, number, created_at, updated_at) SELECT user_id, versioned_id, modifications, number, created_at, updated_at FROM versions WHERE versioned_type = 'Topic'" change_table :topic_revisions do |t| t.index :topic_id t.index [:topic_id, :number] end end def down drop_table :topic_revisions end end
{ "pile_set_name": "Github" }
import { Component, Inject } from '@angular/core'; import { MAT_DIALOG_DATA } from '@angular/material/dialog'; import { DynamicEntityObject } from '@app/dynamics'; @Component({ selector: 'app-entity-schema-modal', templateUrl: 'entity-schema-modal.component.html', }) export class EntitySchemaModalComponent { invalid: boolean; schema: DynamicEntityObject; constructor(@Inject(MAT_DIALOG_DATA) public defaultSchema: DynamicEntityObject) {} }
{ "pile_set_name": "Github" }
'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode');
{ "pile_set_name": "Github" }
<?xml version='1.0' encoding='utf-8'?> <section xmlns="https://code.dccouncil.us/schemas/dc-library" xmlns:codified="https://code.dccouncil.us/schemas/codified" xmlns:codify="https://code.dccouncil.us/schemas/codify" xmlns:xi="http://www.w3.org/2001/XInclude" containing-doc="D.C. Code"> <num>26-551.01</num> <heading>Short title.</heading> <text>This chapter may be cited as the “General Provisions of the 21st Century Financial Modernization Act of 2000”.</text> <annotations> <annotation doc="D.C. Law 13-308" type="History" path="§101">June 9, 2001, D.C. Law 13-308, § 101, 48 DCR 3244</annotation> <annotation type="Section References">This section is referenced in <cite path="§26-1401.02">§ 26-1401.02</cite>.</annotation> </annotations> </section>
{ "pile_set_name": "Github" }
## head命令格式 ```` head [OPTION]... [FILE]... ```` head命令默认打印文件开头10行。 ## head命令常用的参数 ```` -q 隐藏文件名 -v 显示文件名 -c<字节> 显示字节数 -n<行数> 显示的行数 ```` ## head命令 应用实例 * 显示文件的前5行 ```` ```` * 显示文件前10个字节 ```` ```` * 显示除了开头100个字符以后的内容 ```` ````
{ "pile_set_name": "Github" }
*maglev-runtime callCC "GsProcess>>value: fails to restore the clientData, we keep it in the RubyContinuation" | callCCReturn args clientData rubyCC | args := Array new: block numArgs. rubyCC := RubyContinuation new clientData: GsProcess _current clientData; yourself. args size > 0 ifTrue: [args at: 1 put: rubyCC]. callCCReturn := [:cc | rubyCC continuation: (cc clientData: nil; yourself). block valueWithArguments: args] callCC. (GsProcess _current clientData isNil and: [(clientData := rubyCC clientData) notNil]) ifTrue: ["resuming, restore client data" GsProcess _current clientData: clientData]. ^ callCCReturn
{ "pile_set_name": "Github" }
/* Copyright (c) 2008, Adobe Systems Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. * Neither the name of Adobe Systems Incorporated 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 OWNER 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. */ package com.adobe.serialization.json { /** * Class containing constant values for the different types * of tokens in a JSON encoded string. */ public class JSONTokenType { public static const UNKNOWN:int = -1; public static const COMMA:int = 0; public static const LEFT_BRACE:int = 1; public static const RIGHT_BRACE:int = 2; public static const LEFT_BRACKET:int = 3; public static const RIGHT_BRACKET:int = 4; public static const COLON:int = 6; public static const TRUE:int = 7; public static const FALSE:int = 8; public static const NULL:int = 9; public static const STRING:int = 10; public static const NUMBER:int = 11; } }
{ "pile_set_name": "Github" }
package sockaddr import ( "fmt" "math/big" "net" "strings" ) // Constants for the sizes of IPv3, IPv4, and IPv6 address types. const ( IPv3len = 6 IPv4len = 4 IPv6len = 16 ) // IPAddr is a generic IP address interface for IPv4 and IPv6 addresses, // networks, and socket endpoints. type IPAddr interface { SockAddr AddressBinString() string AddressHexString() string Cmp(SockAddr) int CmpAddress(SockAddr) int CmpPort(SockAddr) int FirstUsable() IPAddr Host() IPAddr IPPort() IPPort LastUsable() IPAddr Maskbits() int NetIP() *net.IP NetIPMask() *net.IPMask NetIPNet() *net.IPNet Network() IPAddr Octets() []int } // IPPort is the type for an IP port number for the TCP and UDP IP transports. type IPPort uint16 // IPPrefixLen is a typed integer representing the prefix length for a given // IPAddr. type IPPrefixLen byte // ipAddrAttrMap is a map of the IPAddr type-specific attributes. var ipAddrAttrMap map[AttrName]func(IPAddr) string var ipAddrAttrs []AttrName func init() { ipAddrInit() } // NewIPAddr creates a new IPAddr from a string. Returns nil if the string is // not an IPv4 or an IPv6 address. func NewIPAddr(addr string) (IPAddr, error) { ipv4Addr, err := NewIPv4Addr(addr) if err == nil { return ipv4Addr, nil } ipv6Addr, err := NewIPv6Addr(addr) if err == nil { return ipv6Addr, nil } return nil, fmt.Errorf("invalid IPAddr %v", addr) } // IPAddrAttr returns a string representation of an attribute for the given // IPAddr. func IPAddrAttr(ip IPAddr, selector AttrName) string { fn, found := ipAddrAttrMap[selector] if !found { return "" } return fn(ip) } // IPAttrs returns a list of attributes supported by the IPAddr type func IPAttrs() []AttrName { return ipAddrAttrs } // MustIPAddr is a helper method that must return an IPAddr or panic on invalid // input. func MustIPAddr(addr string) IPAddr { ip, err := NewIPAddr(addr) if err != nil { panic(fmt.Sprintf("Unable to create an IPAddr from %+q: %v", addr, err)) } return ip } // ipAddrInit is called once at init() func ipAddrInit() { // Sorted for human readability ipAddrAttrs = []AttrName{ "host", "address", "port", "netmask", "network", "mask_bits", "binary", "hex", "first_usable", "last_usable", "octets", } ipAddrAttrMap = map[AttrName]func(ip IPAddr) string{ "address": func(ip IPAddr) string { return ip.NetIP().String() }, "binary": func(ip IPAddr) string { return ip.AddressBinString() }, "first_usable": func(ip IPAddr) string { return ip.FirstUsable().String() }, "hex": func(ip IPAddr) string { return ip.AddressHexString() }, "host": func(ip IPAddr) string { return ip.Host().String() }, "last_usable": func(ip IPAddr) string { return ip.LastUsable().String() }, "mask_bits": func(ip IPAddr) string { return fmt.Sprintf("%d", ip.Maskbits()) }, "netmask": func(ip IPAddr) string { switch v := ip.(type) { case IPv4Addr: ipv4Mask := IPv4Addr{ Address: IPv4Address(v.Mask), Mask: IPv4HostMask, } return ipv4Mask.String() case IPv6Addr: ipv6Mask := new(big.Int) ipv6Mask.Set(v.Mask) ipv6MaskAddr := IPv6Addr{ Address: IPv6Address(ipv6Mask), Mask: ipv6HostMask, } return ipv6MaskAddr.String() default: return fmt.Sprintf("<unsupported type: %T>", ip) } }, "network": func(ip IPAddr) string { return ip.Network().NetIP().String() }, "octets": func(ip IPAddr) string { octets := ip.Octets() octetStrs := make([]string, 0, len(octets)) for _, octet := range octets { octetStrs = append(octetStrs, fmt.Sprintf("%d", octet)) } return strings.Join(octetStrs, " ") }, "port": func(ip IPAddr) string { return fmt.Sprintf("%d", ip.IPPort()) }, } }
{ "pile_set_name": "Github" }
57--Angler/57_Angler_peoplefishing_57_559.jpg 1 459.47246875 20.35271875 32.94453125 38.938203125 0.999190628529
{ "pile_set_name": "Github" }
package com.in28minutes.example.layering.data.database; import java.util.Arrays; import java.util.Date; import java.util.List; import org.springframework.stereotype.Component; import com.in28minutes.example.layering.model.api.client.Todo; //TODO : Ideally should use jdbc interfacing or an ORM // A Dummy database just to quickly work something out @Component public class Database { public List<Todo> retrieveTodos(String userName) { List<Todo> todos = Arrays.asList(new Todo( "Real Database - Complete Spring Tutorial", new Date(), false), new Todo("Real Database - Complete Spring MVC Tutorial", new Date(), false), new Todo( "Real Database - Complete All Tutorials", new Date(), false)); return todos; } }
{ "pile_set_name": "Github" }
#ifndef CT_VERIF_H #define CT_VERIF_H #ifndef COMPILE #include <smack.h> /* Security levels are the following. For inputs: - public - function requires (assumes) these to be equal. - private - no requirement (allowed to vary freely) For outputs (both by reference and return values): - public - function ensures these are equal can be used on left-hand side of implications everywhere - private - no guarantee (allowed to vary freely) - declassified - we only analyse executions in which these possibly private values are fixed. We omit annotations for private since nothing needs to be generated for them. We may need to add them back in for modular analyses. */ /* The abstract prototypes that form our annotation language */ void public_in(smack_value_t); void public_out(smack_value_t); void declassified_out(smack_value_t); void public_invariant(smack_value_t); void benign(void); #define __disjoint_regions(addr1,len1,addr2,len2) \ assume(addr1 + len1 * sizeof(*addr1) < addr2 || \ addr2 + len2 * sizeof(*addr2) < addr1) #else /* COMPILE */ #undef __SMACK_value #define __VERIFIER_assume(__a) #define __SMACK_value(__a) #define __SMACK_return_value(__a) #define __SMACK_values(__a,__b) #define __SMACK_return_values(__a) #define public_in(__a) #define public_out(__a) #define declassified_out(__a) #define public_invariant(__a) #define __disjoint_regions(addr1,len1,addr2,len2) #endif /* COMPILE */ #endif /* CT_VERIF_H */
{ "pile_set_name": "Github" }
/*============================================================================= Copyright (c) 2001-2014 Joel de Guzman Copyright (c) 2001-2011 Hartmut Kaiser Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ================================================_==============================*/ #if !defined(BOOST_SPIRIT_X3_PRINT_ATTRIBUTE_JANUARY_20_2013_0814AM) #define BOOST_SPIRIT_X3_PRINT_ATTRIBUTE_JANUARY_20_2013_0814AM #include <boost/variant.hpp> #include <boost/optional/optional.hpp> #include <boost/fusion/include/is_sequence.hpp> #include <boost/fusion/include/for_each.hpp> #include <boost/spirit/home/x3/support/traits/attribute_category.hpp> #include <boost/spirit/home/x3/support/traits/is_variant.hpp> namespace boost { namespace spirit { namespace x3 { namespace traits { template <typename Out, typename T> void print_attribute(Out& out, T const& val); template <typename Out> inline void print_attribute(Out&, unused_type) {} /////////////////////////////////////////////////////////////////////////// namespace detail { template <typename Out> struct print_fusion_sequence { print_fusion_sequence(Out& out) : out(out), is_first(true) {} typedef void result_type; template <typename T> void operator()(T const& val) const { if (is_first) is_first = false; else out << ", "; x3::traits::print_attribute(out, val); } Out& out; mutable bool is_first; }; // print elements in a variant template <typename Out> struct print_visitor : static_visitor<> { print_visitor(Out& out) : out(out) {} template <typename T> void operator()(T const& val) const { x3::traits::print_attribute(out, val); } Out& out; }; } template <typename Out, typename T, typename Enable = void> struct print_attribute_debug { // for plain data types template <typename T_> static void call(Out& out, T_ const& val, unused_attribute) { out << "unused"; } // for plain data types template <typename T_> static void call(Out& out, T_ const& val, plain_attribute) { out << val; } // for fusion data types template <typename T_> static void call(Out& out, T_ const& val, tuple_attribute) { out << '['; fusion::for_each(val, detail::print_fusion_sequence<Out>(out)); out << ']'; } // stl container template <typename T_> static void call(Out& out, T_ const& val, container_attribute) { out << '['; if (!traits::is_empty(val)) { bool first = true; typename container_iterator<T_ const>::type iend = traits::end(val); for (typename container_iterator<T_ const>::type i = traits::begin(val); !traits::compare(i, iend); traits::next(i)) { if (!first) out << ", "; first = false; x3::traits::print_attribute(out, traits::deref(i)); } } out << ']'; } // for variant types template <typename T_> static void call(Out& out, T_ const& val, variant_attribute) { apply_visitor(detail::print_visitor<Out>(out), val); } // for optional types template <typename T_> static void call(Out& out, T_ const& val, optional_attribute) { if (val) x3::traits::print_attribute(out, *val); else out << "[empty]"; } // main entry point static void call(Out& out, T const& val) { call(out, val, typename attribute_category<T>::type()); } }; /////////////////////////////////////////////////////////////////////////// template <typename Out, typename T> inline void print_attribute(Out& out, T const& val) { print_attribute_debug<Out, T>::call(out, val); } }}}} #endif
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="coqdoc.css" rel="stylesheet" type="text/css" /> <title>mathcomp.ssreflect.tuple</title> </head> <body> <div id="page"> <div id="header"> </div> <div id="main"> <table> <tr> <td>Global Index</td> <td><a href="index_global_A.html">A</a></td> <td><a href="index_global_B.html">B</a></td> <td><a href="index_global_C.html">C</a></td> <td><a href="index_global_D.html">D</a></td> <td><a href="index_global_E.html">E</a></td> <td><a href="index_global_F.html">F</a></td> <td><a href="index_global_G.html">G</a></td> <td><a href="index_global_H.html">H</a></td> <td><a href="index_global_I.html">I</a></td> <td><a href="index_global_J.html">J</a></td> <td><a href="index_global_K.html">K</a></td> <td><a href="index_global_L.html">L</a></td> <td><a href="index_global_M.html">M</a></td> <td><a href="index_global_N.html">N</a></td> <td><a href="index_global_O.html">O</a></td> <td><a href="index_global_P.html">P</a></td> <td><a href="index_global_Q.html">Q</a></td> <td><a href="index_global_R.html">R</a></td> <td><a href="index_global_S.html">S</a></td> <td><a href="index_global_T.html">T</a></td> <td><a href="index_global_U.html">U</a></td> <td><a href="index_global_V.html">V</a></td> <td><a href="index_global_W.html">W</a></td> <td><a href="index_global_X.html">X</a></td> <td>Y</td> <td><a href="index_global_Z.html">Z</a></td> <td>_</td> <td><a href="index_global_*.html">other</a></td> <td>(23233 entries)</td> </tr> <tr> <td>Notation Index</td> <td><a href="index_notation_A.html">A</a></td> <td><a href="index_notation_B.html">B</a></td> <td><a href="index_notation_C.html">C</a></td> <td><a href="index_notation_D.html">D</a></td> <td><a href="index_notation_E.html">E</a></td> <td><a href="index_notation_F.html">F</a></td> <td><a href="index_notation_G.html">G</a></td> <td>H</td> <td><a href="index_notation_I.html">I</a></td> <td>J</td> <td><a href="index_notation_K.html">K</a></td> <td><a href="index_notation_L.html">L</a></td> <td><a href="index_notation_M.html">M</a></td> <td><a href="index_notation_N.html">N</a></td> <td>O</td> <td><a href="index_notation_P.html">P</a></td> <td><a href="index_notation_Q.html">Q</a></td> <td><a href="index_notation_R.html">R</a></td> <td><a href="index_notation_S.html">S</a></td> <td>T</td> <td><a href="index_notation_U.html">U</a></td> <td><a href="index_notation_V.html">V</a></td> <td>W</td> <td>X</td> <td>Y</td> <td><a href="index_notation_Z.html">Z</a></td> <td>_</td> <td><a href="index_notation_*.html">other</a></td> <td>(1373 entries)</td> </tr> <tr> <td>Module Index</td> <td><a href="index_module_A.html">A</a></td> <td><a href="index_module_B.html">B</a></td> <td><a href="index_module_C.html">C</a></td> <td>D</td> <td><a href="index_module_E.html">E</a></td> <td><a href="index_module_F.html">F</a></td> <td><a href="index_module_G.html">G</a></td> <td>H</td> <td><a href="index_module_I.html">I</a></td> <td>J</td> <td>K</td> <td>L</td> <td><a href="index_module_M.html">M</a></td> <td><a href="index_module_N.html">N</a></td> <td>O</td> <td><a href="index_module_P.html">P</a></td> <td><a href="index_module_Q.html">Q</a></td> <td><a href="index_module_R.html">R</a></td> <td><a href="index_module_S.html">S</a></td> <td>T</td> <td><a href="index_module_U.html">U</a></td> <td><a href="index_module_V.html">V</a></td> <td>W</td> <td>X</td> <td>Y</td> <td>Z</td> <td>_</td> <td>other</td> <td>(213 entries)</td> </tr> <tr> <td>Variable Index</td> <td><a href="index_variable_A.html">A</a></td> <td><a href="index_variable_B.html">B</a></td> <td><a href="index_variable_C.html">C</a></td> <td><a href="index_variable_D.html">D</a></td> <td><a href="index_variable_E.html">E</a></td> <td><a href="index_variable_F.html">F</a></td> <td><a href="index_variable_G.html">G</a></td> <td><a href="index_variable_H.html">H</a></td> <td><a href="index_variable_I.html">I</a></td> <td>J</td> <td><a href="index_variable_K.html">K</a></td> <td><a href="index_variable_L.html">L</a></td> <td><a href="index_variable_M.html">M</a></td> <td><a href="index_variable_N.html">N</a></td> <td><a href="index_variable_O.html">O</a></td> <td><a href="index_variable_P.html">P</a></td> <td><a href="index_variable_Q.html">Q</a></td> <td><a href="index_variable_R.html">R</a></td> <td><a href="index_variable_S.html">S</a></td> <td><a href="index_variable_T.html">T</a></td> <td><a href="index_variable_U.html">U</a></td> <td><a href="index_variable_V.html">V</a></td> <td>W</td> <td>X</td> <td>Y</td> <td><a href="index_variable_Z.html">Z</a></td> <td>_</td> <td>other</td> <td>(3475 entries)</td> </tr> <tr> <td>Library Index</td> <td><a href="index_library_A.html">A</a></td> <td><a href="index_library_B.html">B</a></td> <td><a href="index_library_C.html">C</a></td> <td><a href="index_library_D.html">D</a></td> <td><a href="index_library_E.html">E</a></td> <td><a href="index_library_F.html">F</a></td> <td><a href="index_library_G.html">G</a></td> <td><a href="index_library_H.html">H</a></td> <td><a href="index_library_I.html">I</a></td> <td><a href="index_library_J.html">J</a></td> <td>K</td> <td>L</td> <td><a href="index_library_M.html">M</a></td> <td><a href="index_library_N.html">N</a></td> <td>O</td> <td><a href="index_library_P.html">P</a></td> <td><a href="index_library_Q.html">Q</a></td> <td><a href="index_library_R.html">R</a></td> <td><a href="index_library_S.html">S</a></td> <td><a href="index_library_T.html">T</a></td> <td>U</td> <td><a href="index_library_V.html">V</a></td> <td>W</td> <td>X</td> <td>Y</td> <td><a href="index_library_Z.html">Z</a></td> <td>_</td> <td>other</td> <td>(89 entries)</td> </tr> <tr> <td>Lemma Index</td> <td><a href="index_lemma_A.html">A</a></td> <td><a href="index_lemma_B.html">B</a></td> <td><a href="index_lemma_C.html">C</a></td> <td><a href="index_lemma_D.html">D</a></td> <td><a href="index_lemma_E.html">E</a></td> <td><a href="index_lemma_F.html">F</a></td> <td><a href="index_lemma_G.html">G</a></td> <td><a href="index_lemma_H.html">H</a></td> <td><a href="index_lemma_I.html">I</a></td> <td><a href="index_lemma_J.html">J</a></td> <td><a href="index_lemma_K.html">K</a></td> <td><a href="index_lemma_L.html">L</a></td> <td><a href="index_lemma_M.html">M</a></td> <td><a href="index_lemma_N.html">N</a></td> <td><a href="index_lemma_O.html">O</a></td> <td><a href="index_lemma_P.html">P</a></td> <td><a href="index_lemma_Q.html">Q</a></td> <td><a href="index_lemma_R.html">R</a></td> <td><a href="index_lemma_S.html">S</a></td> <td><a href="index_lemma_T.html">T</a></td> <td><a href="index_lemma_U.html">U</a></td> <td><a href="index_lemma_V.html">V</a></td> <td><a href="index_lemma_W.html">W</a></td> <td><a href="index_lemma_X.html">X</a></td> <td>Y</td> <td><a href="index_lemma_Z.html">Z</a></td> <td>_</td> <td>other</td> <td>(11853 entries)</td> </tr> <tr> <td>Constructor Index</td> <td><a href="index_constructor_A.html">A</a></td> <td><a href="index_constructor_B.html">B</a></td> <td><a href="index_constructor_C.html">C</a></td> <td><a href="index_constructor_D.html">D</a></td> <td><a href="index_constructor_E.html">E</a></td> <td><a href="index_constructor_F.html">F</a></td> <td><a href="index_constructor_G.html">G</a></td> <td><a href="index_constructor_H.html">H</a></td> <td><a href="index_constructor_I.html">I</a></td> <td>J</td> <td>K</td> <td><a href="index_constructor_L.html">L</a></td> <td><a href="index_constructor_M.html">M</a></td> <td><a href="index_constructor_N.html">N</a></td> <td><a href="index_constructor_O.html">O</a></td> <td><a href="index_constructor_P.html">P</a></td> <td><a href="index_constructor_Q.html">Q</a></td> <td><a href="index_constructor_R.html">R</a></td> <td><a href="index_constructor_S.html">S</a></td> <td><a href="index_constructor_T.html">T</a></td> <td><a href="index_constructor_U.html">U</a></td> <td><a href="index_constructor_V.html">V</a></td> <td>W</td> <td><a href="index_constructor_X.html">X</a></td> <td>Y</td> <td><a href="index_constructor_Z.html">Z</a></td> <td>_</td> <td>other</td> <td>(359 entries)</td> </tr> <tr> <td>Axiom Index</td> <td><a href="index_axiom_A.html">A</a></td> <td><a href="index_axiom_B.html">B</a></td> <td><a href="index_axiom_C.html">C</a></td> <td>D</td> <td><a href="index_axiom_E.html">E</a></td> <td><a href="index_axiom_F.html">F</a></td> <td>G</td> <td>H</td> <td><a href="index_axiom_I.html">I</a></td> <td>J</td> <td>K</td> <td>L</td> <td>M</td> <td>N</td> <td>O</td> <td><a href="index_axiom_P.html">P</a></td> <td>Q</td> <td><a href="index_axiom_R.html">R</a></td> <td><a href="index_axiom_S.html">S</a></td> <td>T</td> <td>U</td> <td>V</td> <td>W</td> <td>X</td> <td>Y</td> <td>Z</td> <td>_</td> <td>other</td> <td>(47 entries)</td> </tr> <tr> <td>Inductive Index</td> <td><a href="index_inductive_A.html">A</a></td> <td><a href="index_inductive_B.html">B</a></td> <td><a href="index_inductive_C.html">C</a></td> <td><a href="index_inductive_D.html">D</a></td> <td><a href="index_inductive_E.html">E</a></td> <td><a href="index_inductive_F.html">F</a></td> <td><a href="index_inductive_G.html">G</a></td> <td><a href="index_inductive_H.html">H</a></td> <td><a href="index_inductive_I.html">I</a></td> <td>J</td> <td>K</td> <td><a href="index_inductive_L.html">L</a></td> <td><a href="index_inductive_M.html">M</a></td> <td><a href="index_inductive_N.html">N</a></td> <td><a href="index_inductive_O.html">O</a></td> <td><a href="index_inductive_P.html">P</a></td> <td>Q</td> <td><a href="index_inductive_R.html">R</a></td> <td><a href="index_inductive_S.html">S</a></td> <td><a href="index_inductive_T.html">T</a></td> <td><a href="index_inductive_U.html">U</a></td> <td><a href="index_inductive_V.html">V</a></td> <td>W</td> <td><a href="index_inductive_X.html">X</a></td> <td>Y</td> <td>Z</td> <td>_</td> <td>other</td> <td>(103 entries)</td> </tr> <tr> <td>Projection Index</td> <td><a href="index_projection_A.html">A</a></td> <td><a href="index_projection_B.html">B</a></td> <td><a href="index_projection_C.html">C</a></td> <td>D</td> <td><a href="index_projection_E.html">E</a></td> <td><a href="index_projection_F.html">F</a></td> <td><a href="index_projection_G.html">G</a></td> <td>H</td> <td><a href="index_projection_I.html">I</a></td> <td>J</td> <td>K</td> <td>L</td> <td><a href="index_projection_M.html">M</a></td> <td><a href="index_projection_N.html">N</a></td> <td>O</td> <td><a href="index_projection_P.html">P</a></td> <td><a href="index_projection_Q.html">Q</a></td> <td><a href="index_projection_R.html">R</a></td> <td><a href="index_projection_S.html">S</a></td> <td><a href="index_projection_T.html">T</a></td> <td><a href="index_projection_U.html">U</a></td> <td><a href="index_projection_V.html">V</a></td> <td>W</td> <td>X</td> <td>Y</td> <td><a href="index_projection_Z.html">Z</a></td> <td>_</td> <td>other</td> <td>(266 entries)</td> </tr> <tr> <td>Section Index</td> <td><a href="index_section_A.html">A</a></td> <td><a href="index_section_B.html">B</a></td> <td><a href="index_section_C.html">C</a></td> <td><a href="index_section_D.html">D</a></td> <td><a href="index_section_E.html">E</a></td> <td><a href="index_section_F.html">F</a></td> <td><a href="index_section_G.html">G</a></td> <td><a href="index_section_H.html">H</a></td> <td><a href="index_section_I.html">I</a></td> <td>J</td> <td><a href="index_section_K.html">K</a></td> <td><a href="index_section_L.html">L</a></td> <td><a href="index_section_M.html">M</a></td> <td><a href="index_section_N.html">N</a></td> <td><a href="index_section_O.html">O</a></td> <td><a href="index_section_P.html">P</a></td> <td><a href="index_section_Q.html">Q</a></td> <td><a href="index_section_R.html">R</a></td> <td><a href="index_section_S.html">S</a></td> <td><a href="index_section_T.html">T</a></td> <td><a href="index_section_U.html">U</a></td> <td><a href="index_section_V.html">V</a></td> <td>W</td> <td>X</td> <td>Y</td> <td><a href="index_section_Z.html">Z</a></td> <td>_</td> <td>other</td> <td>(1118 entries)</td> </tr> <tr> <td>Abbreviation Index</td> <td><a href="index_abbreviation_A.html">A</a></td> <td><a href="index_abbreviation_B.html">B</a></td> <td><a href="index_abbreviation_C.html">C</a></td> <td><a href="index_abbreviation_D.html">D</a></td> <td><a href="index_abbreviation_E.html">E</a></td> <td><a href="index_abbreviation_F.html">F</a></td> <td><a href="index_abbreviation_G.html">G</a></td> <td><a href="index_abbreviation_H.html">H</a></td> <td><a href="index_abbreviation_I.html">I</a></td> <td><a href="index_abbreviation_J.html">J</a></td> <td><a href="index_abbreviation_K.html">K</a></td> <td><a href="index_abbreviation_L.html">L</a></td> <td><a href="index_abbreviation_M.html">M</a></td> <td><a href="index_abbreviation_N.html">N</a></td> <td><a href="index_abbreviation_O.html">O</a></td> <td><a href="index_abbreviation_P.html">P</a></td> <td><a href="index_abbreviation_Q.html">Q</a></td> <td><a href="index_abbreviation_R.html">R</a></td> <td><a href="index_abbreviation_S.html">S</a></td> <td><a href="index_abbreviation_T.html">T</a></td> <td><a href="index_abbreviation_U.html">U</a></td> <td><a href="index_abbreviation_V.html">V</a></td> <td><a href="index_abbreviation_W.html">W</a></td> <td><a href="index_abbreviation_X.html">X</a></td> <td>Y</td> <td><a href="index_abbreviation_Z.html">Z</a></td> <td>_</td> <td>other</td> <td>(691 entries)</td> </tr> <tr> <td>Definition Index</td> <td><a href="index_definition_A.html">A</a></td> <td><a href="index_definition_B.html">B</a></td> <td><a href="index_definition_C.html">C</a></td> <td><a href="index_definition_D.html">D</a></td> <td><a href="index_definition_E.html">E</a></td> <td><a href="index_definition_F.html">F</a></td> <td><a href="index_definition_G.html">G</a></td> <td><a href="index_definition_H.html">H</a></td> <td><a href="index_definition_I.html">I</a></td> <td><a href="index_definition_J.html">J</a></td> <td><a href="index_definition_K.html">K</a></td> <td><a href="index_definition_L.html">L</a></td> <td><a href="index_definition_M.html">M</a></td> <td><a href="index_definition_N.html">N</a></td> <td><a href="index_definition_O.html">O</a></td> <td><a href="index_definition_P.html">P</a></td> <td><a href="index_definition_Q.html">Q</a></td> <td><a href="index_definition_R.html">R</a></td> <td><a href="index_definition_S.html">S</a></td> <td><a href="index_definition_T.html">T</a></td> <td><a href="index_definition_U.html">U</a></td> <td><a href="index_definition_V.html">V</a></td> <td><a href="index_definition_W.html">W</a></td> <td><a href="index_definition_X.html">X</a></td> <td>Y</td> <td><a href="index_definition_Z.html">Z</a></td> <td>_</td> <td>other</td> <td>(3461 entries)</td> </tr> <tr> <td>Record Index</td> <td><a href="index_record_A.html">A</a></td> <td>B</td> <td><a href="index_record_C.html">C</a></td> <td>D</td> <td><a href="index_record_E.html">E</a></td> <td><a href="index_record_F.html">F</a></td> <td><a href="index_record_G.html">G</a></td> <td>H</td> <td><a href="index_record_I.html">I</a></td> <td>J</td> <td>K</td> <td>L</td> <td><a href="index_record_M.html">M</a></td> <td><a href="index_record_N.html">N</a></td> <td>O</td> <td><a href="index_record_P.html">P</a></td> <td><a href="index_record_Q.html">Q</a></td> <td><a href="index_record_R.html">R</a></td> <td><a href="index_record_S.html">S</a></td> <td><a href="index_record_T.html">T</a></td> <td><a href="index_record_U.html">U</a></td> <td><a href="index_record_V.html">V</a></td> <td>W</td> <td>X</td> <td>Y</td> <td><a href="index_record_Z.html">Z</a></td> <td>_</td> <td>other</td> <td>(185 entries)</td> </tr> </table> <hr/><a name="library_E"></a><h2>E (library)</h2> <a href="mathcomp.ssreflect.eqtype.html">eqtype</a> <br/> <a href="mathcomp.solvable.extraspecial.html">extraspecial</a> <br/> <a href="mathcomp.solvable.extremal.html">extremal</a> <br/> <br/><br/></div> <div id="footer"> <hr/><a href="index.html">Index</a><hr/>This page has been generated by <a href="http://coq.inria.fr/">coqdoc</a> </div> </div> </body> </html>
{ "pile_set_name": "Github" }
<line_state xmlns="http://oval.mitre.org/XMLSchema/oval-definitions-5#iosxe" comment="Affected configuration value" id="oval:org.cisecurity:ste:13062" version="1"> <config_line operation="pattern match">Enabled</config_line> </line_state>
{ "pile_set_name": "Github" }
#ifndef __DIGITS5x9_H #define __DIGITS5x9_H #define dig5x9 &Digits5x9 static const Font_TypeDef Digits5x9 = { 5, // Font width 9, // Font height 9, // Bytes per character FONT_H, // Vertical font scan lines 45, // First character: '-' 57, // Last character: '9' 48, // Unknown character: '0' { 0x00,0x00,0x00,0x00,0x1F,0x00,0x00,0x00,0x00, // '-' 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04, // '.' 0x10,0x10,0x08,0x08,0x04,0x02,0x02,0x01,0x01, // '/' 0x1F,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x1F, // '0' 0x04,0x06,0x04,0x04,0x04,0x04,0x04,0x04,0x0E, // '1' 0x1F,0x10,0x10,0x10,0x1F,0x01,0x01,0x01,0x1F, // '2' 0x1F,0x10,0x10,0x10,0x1E,0x10,0x10,0x10,0x1F, // '3' 0x11,0x11,0x11,0x11,0x1F,0x10,0x10,0x10,0x10, // '4' 0x1F,0x01,0x01,0x01,0x1F,0x10,0x10,0x10,0x1F, // '5' 0x1F,0x01,0x01,0x01,0x1F,0x11,0x11,0x11,0x1F, // '6' 0x1F,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10, // '7' 0x1F,0x11,0x11,0x11,0x1F,0x11,0x11,0x11,0x1F, // '8' 0x1F,0x11,0x11,0x11,0x1F,0x10,0x10,0x10,0x1F // '9' } }; #endif // __DIGITS5x9_H
{ "pile_set_name": "Github" }
// @flow import { Env } from './Env'; import { type LangMessage, langMessageToString } from './Lang'; import { LOG_LEVELS, STDOUT_WIDTH } from './constants'; import chalk from 'chalk'; export type LoggerOptions = { env: Env }; export type LogKind = $Keys<typeof LOG_LEVELS>; type FormatOptions = { prefix?: string | null, emoji?: string, style?: string => string, status?: boolean, title?: boolean }; type LogOptions = { emoji?: string, title?: boolean, status?: boolean, prefix?: boolean }; function toFormatOptions(logOptions: LogOptions, formatOptions: FormatOptions) { return { emoji: logOptions.emoji || formatOptions.emoji, prefix: logOptions.prefix !== false ? formatOptions.prefix : null, style: formatOptions.style, title: logOptions.title || formatOptions.title, status: logOptions.status || formatOptions.status }; } type Stream = 'stdout' | 'stderr'; export class Logger { env: Env; constructor(opts: LoggerOptions) { this.env = opts.env; } write( stream: 'stdout' | 'stderr', kind: LogKind, message: string, opts: FormatOptions = {} ) { let logLevel = LOG_LEVELS[kind]; let str = message; if (logLevel > this.env.logLevel) { return; } let prefix = opts.prefix ? `${opts.prefix} ` : ''; let fullPrefix = opts.emoji && !this.env.interface ? `${opts.emoji} ${prefix}` : prefix; str = opts.style ? opts.style(str) : str; str = fullPrefix == '' ? str : str .split('\n') .map(line => `${fullPrefix}${line}`) .join('\n'); if (this.env.interface) { if (opts.title) { this.env.interface.setTitle(str); } else if (opts.status) { this.env.interface.setStatus(str); } else { // this.env.interface.writeLog(str); } } else { if (stream === 'stdout') { console.log(str); } else { console.error(str); } } } title(message: LangMessage, opts: LogOptions = {}) { this.write( 'stderr', 'info', langMessageToString(message), toFormatOptions(opts, { style: chalk.bold.magenta, title: true }) ); } info(message: LangMessage, opts: LogOptions = {}) { this.write( 'stderr', 'info', langMessageToString(message), toFormatOptions(opts, { prefix: chalk.cyan('info') }) ); } success(message: LangMessage, opts: LogOptions = {}) { this.write( 'stderr', 'info', langMessageToString(message), toFormatOptions(opts, { prefix: chalk.green('success') }) ); } debug(message: LangMessage, opts: LogOptions = {}) { this.write( 'stderr', 'debug', langMessageToString(message), toFormatOptions(opts, { prefix: chalk.magenta('debug') }) ); } warn(message: LangMessage, opts: LogOptions = {}) { this.write( 'stderr', 'warn', langMessageToString(message), toFormatOptions(opts, { prefix: chalk.yellow('warn') }) ); } error(message: LangMessage, opts: LogOptions = {}) { this.write( 'stderr', 'error', langMessageToString(message), toFormatOptions(opts, { prefix: chalk.yellow('red') }) ); } line() { this.write( 'stderr', 'output', '\n' + chalk.gray('─'.repeat(STDOUT_WIDTH)) + '\n' ); } }
{ "pile_set_name": "Github" }
{ "author": "jonas747", "date": "14th Feb 2017", "title": "Version 0.19" } - **New Feed: Youtube video uploads**: Will post new videos from channels you specify in a discord channel - **Moderation: New command** `Warn @user reason`: warns a user, all warnings are stored and can be viewed with the `warnings` command - **Moderation: New command** `Warnings @user`: lists a users warnings. - **Moderation: New command** `EditWarning @user`: Edits the warning of a user, this cannot be undone. - **Control panel:** Major improvements to the site on mobile devices - **Control panel:** Role and channel dropdowns are finally sorted, and you wont see that everyone role either anymore... - **Control panel:** Major improvements to navigating the control panel in general - **Control panel:** Logs can now be sorted by ascending or descending - Dice command now also takes some rpg dice syntax - Server stats can now ignore channels - Messages that gets deleted will now also be marked as deleted in all logs they appear in, even after the logs was created (admins can still see them) - When a command fails to parse, also print the help for that command - When exec fails in custom commands, they will not stop executing and instead return the error message the command returned - You can now restrict commands to roles on a per channel basis (in the command settings) - Preliminary @everyone filtering in commands and other places, i would wait a couple days first before giving it @everyone permissions to see if i forgot to filter some places - More reliable username and nickname logging (users not in state coming online wouldn't get their nicknames/usernames checked)
{ "pile_set_name": "Github" }
#ifndef IIT_ROBOT_CT_DOUBLEINVERTEDPENDULUM_INERTIA_PROPERTIES_H_ #define IIT_ROBOT_CT_DOUBLEINVERTEDPENDULUM_INERTIA_PROPERTIES_H_ #include <iit/rbd/rbd.h> #include <iit/rbd/InertiaMatrix.h> #include <iit/rbd/utils.h> #include <iit/rbd/traits/DoubleTrait.h> #include "declarations.h" namespace iit { namespace ct_DoubleInvertedPendulum { /** * This namespace encloses classes and functions related to the Dynamics * of the robot ct_DoubleInvertedPendulum. */ namespace dyn { using InertiaMatrix = iit::rbd::InertiaMatrixDense; namespace tpl { template <typename TRAIT> class InertiaProperties { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef typename TRAIT::Scalar Scalar; typedef iit::rbd::Core<Scalar> CoreS; typedef iit::rbd::tpl::InertiaMatrixDense<Scalar> IMatrix; typedef typename CoreS::Vector3 Vec3d; InertiaProperties(); ~InertiaProperties(); const IMatrix& getTensor_Link1() const; const IMatrix& getTensor_Link2() const; Scalar getMass_Link1() const; Scalar getMass_Link2() const; const Vec3d& getCOM_Link1() const; const Vec3d& getCOM_Link2() const; Scalar getTotalMass() const; private: IMatrix tensor_Link1; IMatrix tensor_Link2; Vec3d com_Link1; Vec3d com_Link2; }; template <typename TRAIT> inline InertiaProperties<TRAIT>::~InertiaProperties() {} template <typename TRAIT> inline const typename InertiaProperties<TRAIT>::IMatrix& InertiaProperties<TRAIT>::getTensor_Link1() const { return this->tensor_Link1; } template <typename TRAIT> inline const typename InertiaProperties<TRAIT>::IMatrix& InertiaProperties<TRAIT>::getTensor_Link2() const { return this->tensor_Link2; } template <typename TRAIT> inline typename InertiaProperties<TRAIT>::Scalar InertiaProperties<TRAIT>::getMass_Link1() const { return this->tensor_Link1.getMass(); } template <typename TRAIT> inline typename InertiaProperties<TRAIT>::Scalar InertiaProperties<TRAIT>::getMass_Link2() const { return this->tensor_Link2.getMass(); } template <typename TRAIT> inline const typename InertiaProperties<TRAIT>::Vec3d& InertiaProperties<TRAIT>::getCOM_Link1() const { return this->com_Link1; } template <typename TRAIT> inline const typename InertiaProperties<TRAIT>::Vec3d& InertiaProperties<TRAIT>::getCOM_Link2() const { return this->com_Link2; } template <typename TRAIT> inline typename InertiaProperties<TRAIT>::Scalar InertiaProperties<TRAIT>::getTotalMass() const { return 1.0 + 1.0; } } using InertiaProperties = tpl::InertiaProperties<rbd::DoubleTrait>; } } } #include "inertia_properties.impl.h" #endif
{ "pile_set_name": "Github" }
{ Miranda IM: the free IM client for Microsoft* Windows* Copyright 2000-2003 Miranda ICQ/IM project, all portions of this codebase are copyrighted to the people listed in contributors.txt. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. } {$IFNDEF M_SKIN} {$DEFINE M_SKIN} const // event icons SKINICON_EVENT_MESSAGE = 100; SKINICON_EVENT_URL = 101; SKINICON_EVENT_FILE = 102; // msgbox icons SKINICON_INFORMATION = 150; SKINICON_WARNING = 151; SKINICON_ERROR = 152; SKINICON_FATAL = 153; // other icons SKINICON_OTHER_MIRANDA = 200; SKINICON_OTHER_EXIT = 201; SKINICON_OTHER_SHOWHIDE = 202; SKINICON_OTHER_GROUPOPEN = 203; SKINICON_OTHER_USERONLINE = 204; SKINICON_OTHER_GROUPSHUT = 205; SKINICON_OTHER_CONNECTING = 206; SKINICON_OTHER_ADDCONTACT = 207; SKINICON_OTHER_USERDETAILS = 208; SKINICON_OTHER_HISTORY = 209; SKINICON_OTHER_DOWNARROW = 210; SKINICON_OTHER_FINDUSER = 211; SKINICON_OTHER_OPTIONS = 212; SKINICON_OTHER_SENDEMAIL = 213; SKINICON_OTHER_DELETE = 214; SKINICON_OTHER_RENAME = 215; SKINICON_OTHER_SMS = 216; SKINICON_OTHER_SEARCHALL = 217; SKINICON_OTHER_TICK = 218; SKINICON_OTHER_NOTICK = 219; SKINICON_OTHER_HELP = 220; SKINICON_OTHER_MIRANDAWEB = 221; SKINICON_OTHER_TYPING = 222; SKINICON_OTHER_SMALLDOT = 223; SKINICON_OTHER_FILLEDBLOB = 224; SKINICON_OTHER_EMPTYBLOB = 225; SKINICON_OTHER_UNICODE = 226; SKINICON_OTHER_ANSI = 227; SKINICON_OTHER_LOADED = 228; SKINICON_OTHER_NOTLOADED = 229; SKINICON_OTHER_UNDO = 230; SKINICON_OTHER_WINDOW = 231; SKINICON_OTHER_WINDOWS = 232; SKINICON_OTHER_ACCMGR = 233; SKINICON_OTHER_MAINMENU = 234; SKINICON_OTHER_STATUS = 235; SKINICON_CHAT_JOIN = 236; SKINICON_CHAT_LEAVE = 237; SKINICON_OTHER_STATUS_LOCKED = 238; SKINICON_OTHER_GROUP = 239; SKINICON_OTHER_ON = 240; SKINICON_OTHER_OFF = 241; SKINICON_OTHER_LOADEDGRAY = 242; SKINICON_OTHER_NOTLOADEDGRAY = 243; SKINICON_OTHER_VISIBLE_ALL = 244; SKINICON_OTHER_INVISIBLE_ALL = 245; SKINICON_OTHER_FRAME = 246; SKINICON_AUTH_ADD = 247; SKINICON_AUTH_REQUEST = 248; SKINICON_AUTH_GRANT = 249; SKINICON_AUTH_REVOKE = 250; function Skin_LoadIcon(iconId:int; big:byte) : HICON; stdcall; external AppDLL; function Skin_GetIconHandle(iconId:int) : THANDLE; stdcall; external AppDLL; // status mode icons. NOTE: These are deprecated in favour of LoadSkinnedProtoIcon() const SKINICON_STATUS_OFFLINE = 0; SKINICON_STATUS_ONLINE = 1; SKINICON_STATUS_AWAY = 2; SKINICON_STATUS_NA = 3; SKINICON_STATUS_OCCUPIED = 4; SKINICON_STATUS_DND = 5; SKINICON_STATUS_FREE4CHAT = 6; SKINICON_STATUS_INVISIBLE = 7; function Skin_LoadProtoIcon(protoName:PAnsiChar; iconId:int; big:byte) : HICON; stdcall; external AppDLL; {$ENDIF}
{ "pile_set_name": "Github" }
# # Test of auto_increment; The test for BDB tables is in bdb.test # --disable_warnings drop table if exists t1; --enable_warnings create table t1 (a int not null auto_increment,b int, primary key (a)) engine=heap auto_increment=3; insert into t1 values (1,1),(NULL,3),(NULL,4); delete from t1 where a=4; insert into t1 values (NULL,5),(NULL,6); select * from t1; delete from t1 where a=6; #show table status like "t1"; replace t1 values (3,1); ALTER TABLE t1 add c int; replace t1 values (3,3,3); insert into t1 values (NULL,7,7); update t1 set a=8,b=b+1,c=c+1 where a=7; insert into t1 values (NULL,9,9); select * from t1; drop table t1; create table t1 ( skey tinyint unsigned NOT NULL auto_increment PRIMARY KEY, sval char(20) ) engine=heap; insert into t1 values (NULL, "hello"); insert into t1 values (NULL, "hey"); select * from t1; select _rowid,t1._rowid,skey,sval from t1; drop table t1; # End of 4.1 tests --echo # --echo # MDEV-16534 PPC64: Unexpected error with a negative values into auto-increment columns in HEAP, MyISAM, ARIA --echo # CREATE TABLE t1 ( id TINYINT NOT NULL AUTO_INCREMENT, name CHAR(30) NOT NULL, PRIMARY KEY (id) ) ENGINE=MEMORY; SHOW CREATE TABLE t1; INSERT INTO t1 (name) VALUES ('dog'); UPDATE t1 SET id=-1 WHERE id=1; INSERT INTO t1 (name) VALUES ('cat'); SELECT * FROM t1; DROP TABLE t1; --echo # --echo # End of 5.5 tests --echo # --echo # --echo # MDEV-15352 AUTO_INCREMENT breaks after updating a column value to a negative number --echo # SET @engine='MEMORY'; --source include/autoinc_mdev15353.inc --echo # --echo # End of 10.2 tests --echo #
{ "pile_set_name": "Github" }
require 'spec_helper' describe Attache::Delete do let(:app) { ->(env) { [200, env, "app"] } } let(:middleware) { Attache::Delete.new(app) } let(:params) { {} } let(:filename) { "hello#{rand}.gif" } let(:reldirname) { "path#{rand}" } let(:file) { StringIO.new(IO.binread("spec/fixtures/transparent.gif"), 'rb') } before do allow(Attache).to receive(:localdir).and_return(Dir.tmpdir) # forced, for safety allow_any_instance_of(Attache::VHost).to receive(:secret_key).and_return(nil) allow_any_instance_of(Attache::VHost).to receive(:storage).and_return(nil) allow_any_instance_of(Attache::VHost).to receive(:bucket).and_return(nil) end after do FileUtils.rm_rf(Attache.localdir) end it "should passthrough irrelevant request" do code, env = middleware.call Rack::MockRequest.env_for('http://example.com', {}) expect(code).to eq 200 end context "deleting" do let(:params) { Hash(paths: ['image1.jpg', filename].join("\n")) } subject { proc { middleware.call Rack::MockRequest.env_for('http://example.com/delete?' + params.collect {|k,v| "#{CGI.escape k.to_s}=#{CGI.escape v.to_s}"}.join('&'), method: 'DELETE', "HTTP_HOST" => "example.com") } } it 'should respond with json' do end it 'should delete file locally' do expect(Attache.cache).to receive(:delete) do |path| expect(path).to start_with('example.com') end.exactly(2).times code, headers, body = subject.call expect(code).to eq(200) end context 'delete fail locally' do before do expect(Attache.cache).to receive(:delete) do raise Exception.new end.at_least(1).times end it 'should respond with error' do code, headers, body = subject.call expect(code).to eq(500) end end context 'storage configured' do before do allow_any_instance_of(Attache::VHost).to receive(:storage).and_return(double(:storage)) allow_any_instance_of(Attache::VHost).to receive(:bucket).and_return(double(:bucket)) end it 'should delete file remotely' do expect_any_instance_of(Attache::VHost).to receive(:async) do |instance, method, path| expect(method).to eq(:storage_destroy) end.exactly(2).times subject.call end end context 'storage NOT configured' do it 'should NOT delete file remotely' do expect_any_instance_of(Attache::VHost).not_to receive(:async) subject.call end end context 'backup configured' do let(:backup) { double(:backup) } before do allow_any_instance_of(Attache::VHost).to receive(:backup).and_return(backup) end it 'should delete file in backup' do expect(backup).to receive(:async) do |method, path| expect(method).to eq(:storage_destroy) end.exactly(2).times subject.call end end context 'backup NOT configured' do it 'should NOT delete file in backup' do expect_any_instance_of(Attache::VHost).not_to receive(:async) subject.call end end context 'with secret_key' do let(:secret_key) { "topsecret#{rand}" } before do allow_any_instance_of(Attache::VHost).to receive(:secret_key).and_return(secret_key) end it 'should respond with error' do code, headers, body = subject.call expect(code).to eq(401) expect(headers['X-Exception']).to eq('Authorization failed') end context 'invalid auth' do let(:expiration) { (Time.now + 10).to_i } let(:uuid) { "hi#{rand}" } let(:digest) { OpenSSL::Digest.new('sha1') } let(:params) { Hash(file: filename, expiration: expiration, uuid: uuid, hmac: OpenSSL::HMAC.hexdigest(digest, "wrong#{secret_key}", "#{uuid}#{expiration}")) } it 'should respond with error' do code, headers, body = subject.call expect(code).to eq(401) expect(headers['X-Exception']).to eq('Authorization failed') end end context 'valid auth' do let(:expiration) { (Time.now + 10).to_i } let(:uuid) { "hi#{rand}" } let(:digest) { OpenSSL::Digest.new('sha1') } let(:params) { Hash(file: filename, expiration: expiration, uuid: uuid, hmac: OpenSSL::HMAC.hexdigest(digest, secret_key, "#{uuid}#{expiration}")) } it 'should respond with success' do code, headers, body = subject.call expect(code).to eq(200) end context 'expired' do let(:expiration) { (Time.now - 1).to_i } # the past it 'should respond with error' do code, headers, body = subject.call expect(code).to eq(401) expect(headers['X-Exception']).to eq('Authorization failed') end end end end end end
{ "pile_set_name": "Github" }
//{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by FreeOTFECypherRC6_Gladman.rc // // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 101 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif
{ "pile_set_name": "Github" }
<?xml version="1.0"?> <Document style="helpdocument"> <p style="htitle">Spår</p> <p style="hp">Spår är det enklaste och billigast sättet för transporter. De har också den lägsta kapaciteten. Det som är bra är att de bidrar inte till miljöförstöringen.</p> <p style="hp">Detta är ett spår</p> <img src="images/tiles/trackud.png" halign="center"/> <p style="hp">och detta är dess ikon</p> <img src="images/gui/buttonpanel/transport/tracks.png" halign="center"/> <p style="hsubtitle">Se också:</p> <li><a href="transport">Transport</a></li> <li><a href="commune">Kolmila</a></li> </Document>
{ "pile_set_name": "Github" }
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # """Implementation of non-blocking server. The main idea of the server is to receive and send requests only from the main thread. The thread poool should be sized for concurrent tasks, not maximum connections """ import threading import socket import Queue import select import struct import logging logger = logging.getLogger(__name__) from thrift.transport import TTransport from thrift.protocol.TBinaryProtocol import TBinaryProtocolFactory __all__ = ['TNonblockingServer'] class Worker(threading.Thread): """Worker is a small helper to process incoming connection.""" def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): """Process queries from task queue, stop if processor is None.""" while True: try: processor, iprot, oprot, otrans, callback = self.queue.get() if processor is None: break processor.process(iprot, oprot) callback(True, otrans.getvalue()) except Exception: logger.exception("Exception while processing request") callback(False, '') WAIT_LEN = 0 WAIT_MESSAGE = 1 WAIT_PROCESS = 2 SEND_ANSWER = 3 CLOSED = 4 def locked(func): """Decorator which locks self.lock.""" def nested(self, *args, **kwargs): self.lock.acquire() try: return func(self, *args, **kwargs) finally: self.lock.release() return nested def socket_exception(func): """Decorator close object on socket.error.""" def read(self, *args, **kwargs): try: return func(self, *args, **kwargs) except socket.error: self.close() return read class Connection: """Basic class is represented connection. It can be in state: WAIT_LEN --- connection is reading request len. WAIT_MESSAGE --- connection is reading request. WAIT_PROCESS --- connection has just read whole request and waits for call ready routine. SEND_ANSWER --- connection is sending answer string (including length of answer). CLOSED --- socket was closed and connection should be deleted. """ def __init__(self, new_socket, wake_up): self.socket = new_socket self.socket.setblocking(False) self.status = WAIT_LEN self.len = 0 self.message = '' self.lock = threading.Lock() self.wake_up = wake_up def _read_len(self): """Reads length of request. It's a safer alternative to self.socket.recv(4) """ read = self.socket.recv(4 - len(self.message)) if len(read) == 0: # if we read 0 bytes and self.message is empty, then # the client closed the connection if len(self.message) != 0: logger.error("can't read frame size from socket") self.close() return self.message += read if len(self.message) == 4: self.len, = struct.unpack('!i', self.message) if self.len < 0: logger.error("negative frame size, it seems client " "doesn't use FramedTransport") self.close() elif self.len == 0: logger.error("empty frame, it's really strange") self.close() else: self.message = '' self.status = WAIT_MESSAGE @socket_exception def read(self): """Reads data from stream and switch state.""" assert self.status in (WAIT_LEN, WAIT_MESSAGE) if self.status == WAIT_LEN: self._read_len() # go back to the main loop here for simplicity instead of # falling through, even though there is a good chance that # the message is already available elif self.status == WAIT_MESSAGE: read = self.socket.recv(self.len - len(self.message)) if len(read) == 0: logger.error("can't read frame from socket (get %d of " "%d bytes)" % (len(self.message), self.len)) self.close() return self.message += read if len(self.message) == self.len: self.status = WAIT_PROCESS @socket_exception def write(self): """Writes data from socket and switch state.""" assert self.status == SEND_ANSWER sent = self.socket.send(self.message) if sent == len(self.message): self.status = WAIT_LEN self.message = '' self.len = 0 else: self.message = self.message[sent:] @locked def ready(self, all_ok, message): """Callback function for switching state and waking up main thread. This function is the only function witch can be called asynchronous. The ready can switch Connection to three states: WAIT_LEN if request was oneway. SEND_ANSWER if request was processed in normal way. CLOSED if request throws unexpected exception. The one wakes up main thread. """ assert self.status == WAIT_PROCESS if not all_ok: self.close() self.wake_up() return self.len = '' if len(message) == 0: # it was a oneway request, do not write answer self.message = '' self.status = WAIT_LEN else: self.message = struct.pack('!i', len(message)) + message self.status = SEND_ANSWER self.wake_up() @locked def is_writeable(self): """Return True if connection should be added to write list of select""" return self.status == SEND_ANSWER # it's not necessary, but... @locked def is_readable(self): """Return True if connection should be added to read list of select""" return self.status in (WAIT_LEN, WAIT_MESSAGE) @locked def is_closed(self): """Returns True if connection is closed.""" return self.status == CLOSED def fileno(self): """Returns the file descriptor of the associated socket.""" return self.socket.fileno() def close(self): """Closes connection""" self.status = CLOSED self.socket.close() class TNonblockingServer: """Non-blocking server.""" def __init__(self, processor, lsocket, inputProtocolFactory=None, outputProtocolFactory=None, threads=10): self.processor = processor self.socket = lsocket self.in_protocol = inputProtocolFactory or TBinaryProtocolFactory() self.out_protocol = outputProtocolFactory or self.in_protocol self.threads = int(threads) self.clients = {} self.tasks = Queue.Queue() self._read, self._write = socket.socketpair() self.prepared = False self._stop = False def setNumThreads(self, num): """Set the number of worker threads that should be created.""" # implement ThreadPool interface assert not self.prepared, "Can't change number of threads after start" self.threads = num def prepare(self): """Prepares server for serve requests.""" if self.prepared: return self.socket.listen() for _ in xrange(self.threads): thread = Worker(self.tasks) thread.setDaemon(True) thread.start() self.prepared = True def wake_up(self): """Wake up main thread. The server usualy waits in select call in we should terminate one. The simplest way is using socketpair. Select always wait to read from the first socket of socketpair. In this case, we can just write anything to the second socket from socketpair. """ self._write.send('1') def stop(self): """Stop the server. This method causes the serve() method to return. stop() may be invoked from within your handler, or from another thread. After stop() is called, serve() will return but the server will still be listening on the socket. serve() may then be called again to resume processing requests. Alternatively, close() may be called after serve() returns to close the server socket and shutdown all worker threads. """ self._stop = True self.wake_up() def _select(self): """Does select on open connections.""" readable = [self.socket.handle.fileno(), self._read.fileno()] writable = [] for i, connection in self.clients.items(): if connection.is_readable(): readable.append(connection.fileno()) if connection.is_writeable(): writable.append(connection.fileno()) if connection.is_closed(): del self.clients[i] return select.select(readable, writable, readable) def handle(self): """Handle requests. WARNING! You must call prepare() BEFORE calling handle() """ assert self.prepared, "You have to call prepare before handle" rset, wset, xset = self._select() for readable in rset: if readable == self._read.fileno(): # don't care i just need to clean readable flag self._read.recv(1024) elif readable == self.socket.handle.fileno(): client = self.socket.accept().handle self.clients[client.fileno()] = Connection(client, self.wake_up) else: connection = self.clients[readable] connection.read() if connection.status == WAIT_PROCESS: itransport = TTransport.TMemoryBuffer(connection.message) otransport = TTransport.TMemoryBuffer() iprot = self.in_protocol.getProtocol(itransport) oprot = self.out_protocol.getProtocol(otransport) self.tasks.put([self.processor, iprot, oprot, otransport, connection.ready]) for writeable in wset: self.clients[writeable].write() for oob in xset: self.clients[oob].close() del self.clients[oob] def close(self): """Closes the server.""" for _ in xrange(self.threads): self.tasks.put([None, None, None, None, None]) self.socket.close() self.prepared = False def serve(self): """Serve requests. Serve requests forever, or until stop() is called. """ self._stop = False self.prepare() while not self._stop: self.handle()
{ "pile_set_name": "Github" }
/* * Copyright (C) 2005, 2006, 2008 Apple Inc. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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. */ #pragma once #include "EditCommand.h" namespace WebCore { class Text; class SplitTextNodeCommand : public SimpleEditCommand { public: static Ref<SplitTextNodeCommand> create(Ref<Text>&& node, int offset) { return adoptRef(*new SplitTextNodeCommand(WTFMove(node), offset)); } private: SplitTextNodeCommand(Ref<Text>&&, int offset); void doApply() override; void doUnapply() override; void doReapply() override; void insertText1AndTrimText2(); #ifndef NDEBUG void getNodesInCommand(HashSet<Node*>&) override; #endif RefPtr<Text> m_text1; Ref<Text> m_text2; unsigned m_offset; }; } // namespace WebCore
{ "pile_set_name": "Github" }
var InnerSubscription = function (s, o) { this._s = s; this._o = o; }; InnerSubscription.prototype.dispose = function () { if (!this._s.isDisposed && this._o !== null) { var idx = this._s.observers.indexOf(this._o); this._s.observers.splice(idx, 1); this._o = null; } };
{ "pile_set_name": "Github" }