_id stringlengths 2 6 | title stringlengths 9 130 | partition stringclasses 3 values | text stringlengths 66 10.5k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q20300 | Poise.Utils.check_block_arity! | train | def check_block_arity!(block, args)
# Convert the block to a lambda-style proc. You can't make this shit up.
obj = Object.new
obj.define_singleton_method(:block, &block)
block = obj.method(:block).to_proc
# Check
required_args = block.arity < 0 ? ~block.arity : block.arity
if args.length < required_args || (block.arity >= 0 && args.length > block.arity)
raise ArgumentError.new("wrong number of arguments (#{args.length} for #{required_args}#{block.arity < 0 ? '+' : ''})")
end
end | ruby | {
"resource": ""
} |
q20301 | Kong.Consumer.oauth_apps | train | def oauth_apps
apps = []
response = client.get("#{@api_end_point}#{self.id}/oauth2") rescue nil
if response
response['data'].each do |attributes|
apps << Kong::OAuthApp.new(attributes)
end
end
apps
end | ruby | {
"resource": ""
} |
q20302 | Cisco.RouterBgpAF.dampening_half_time | train | def dampening_half_time
return nil if dampening.nil? || dampening_routemap_configured?
if dampening.is_a?(Array) && !dampening.empty?
dampening[0].to_i
else
default_dampening_half_time
end
end | ruby | {
"resource": ""
} |
q20303 | Cisco.RouterBgpAF.method_missing | train | def method_missing(*args)
name = args[0].to_s
if args.length == 1 # Getter
if name =~ /^default_(.*)$/
config_get_default('bgp_af', Regexp.last_match(1))
else
config_get('bgp_af', name, @get_args)
end
elsif args.length == 2 && name =~ /^(.*)=$/ # Setter
set_args_keys(state: args[1] ? '' : 'no')
config_set('bgp_af', Regexp.last_match(1), @set_args)
else
super
end
end | ruby | {
"resource": ""
} |
q20304 | Cisco.RouterBgpAF.respond_to? | train | def respond_to?(method_sym, _include_private=false)
name = method_sym.to_s
key = :getter?
if name =~ /^(.*)=$/
name = Regexp.last_match(1)
# Use table_map_set() to set these properties
return false if name == 'table_map' || name == 'table_map_filter'
key = :setter?
elsif name =~ /^default_(.*)$/
name = Regexp.last_match(1)
key = :default_value?
end
begin
ref = node.cmd_ref.lookup('bgp_af', name)
ref.send(key)
rescue IndexError
super
end
end | ruby | {
"resource": ""
} |
q20305 | Cisco.Ace.ace_get | train | def ace_get
str = config_get('acl', 'ace', @get_args)
return nil if str.nil?
remark = Regexp.new('(?<seqno>\d+) remark (?<remark>.*)').match(str)
return remark unless remark.nil?
# specialized icmp protocol handling
return icmp_ace_get(str) if str.include?('icmp')
# rubocop:disable Metrics/LineLength
regexp = Regexp.new('(?<seqno>\d+) (?<action>\S+)'\
' *(?<proto>\d+|\S+)'\
' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<src_port>range \S+ \S+|(lt|eq|gt|neq|portgroup) \S+)?'\
' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<dst_port>range \S+ \S+|(lt|eq|gt|neq|portgroup) \S+)?'\
' *(?<tcp_flags>(ack *|fin *|urg *|syn *|psh *|rst *)*)?'\
' *(?<established>established)?'\
' *(?<precedence>precedence \S+)?'\
' *(?<dscp>dscp \S+)?'\
' *(?<time_range>time-range \S+)?'\
' *(?<packet_length>packet-length (range \d+ \d+|(lt|eq|gt|neq) \d+))?'\
' *(?<ttl>ttl \d+)?'\
' *(?<http_method>http-method (\d+|connect|delete|get|head|post|put|trace))?'\
' *(?<tcp_option_length>tcp-option-length \d+)?'\
' *(?<redirect>redirect \S+)?'\
' *(?<log>log)?')
# rubocop:enable Metrics/LineLength
regexp.match(str)
end | ruby | {
"resource": ""
} |
q20306 | Cisco.Ace.icmp_ace_get | train | def icmp_ace_get(str)
# rubocop:disable Metrics/LineLength
# fragments is nvgen at a different location than all other
# proto_option so get rid of it so as not to mess up other fields
str.sub!('fragments ', '')
regexp = Regexp.new('(?<seqno>\d+) (?<action>\S+)'\
' *(?<proto>\d+|\S+)'\
' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<proto_option>\S+)?'\
' *(?<precedence>precedence \S+)?'\
' *(?<dscp>dscp \S+)?'\
' *(?<time_range>time-range \S+)?'\
' *(?<packet_length>packet-length (range \d+ \d+|(lt|eq|gt|neq) \d+))?'\
' *(?<ttl>ttl \d+)?'\
' *(?<vlan>vlan \d+)?'\
' *(?<set_erspan_gre_proto>set-erspan-gre-proto \d+)?'\
' *(?<set_erspan_dscp>set-erspan-dscp \d+)?'\
' *(?<redirect>redirect \S+)?')
regexp_no_proto_option = Regexp.new('(?<seqno>\d+) (?<action>\S+)'\
' *(?<proto>\d+|\S+)'\
' *(?<src_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<dst_addr>any|host \S+|[:\.0-9a-fA-F]+ [:\.0-9a-fA-F]+|[:\.0-9a-fA-F]+\/\d+|addrgroup \S+)'\
' *(?<precedence>precedence \S+)?'\
' *(?<dscp>dscp \S+)?'\
' *(?<time_range>time-range \S+)?'\
' *(?<packet_length>packet-length (range \d+ \d+|(lt|eq|gt|neq) \d+))?'\
' *(?<ttl>ttl \d+)?'\
' *(?<vlan>vlan \d+)?'\
' *(?<set_erspan_gre_proto>set-erspan-gre-proto \d+)?'\
' *(?<set_erspan_dscp>set-erspan-dscp \d+)?'\
' *(?<redirect>redirect \S+)?')
temp = regexp.match(str)
po = temp[:proto_option]
if po.nil?
return temp
# redirect can be proto_option or an actual redirect to interface
elsif po.strip.match(/redirect$/)
if str.match(/Ethernet|port-channel/)
# if proto_option is given as redirect and also redirect to intf
# we need to do extra processing
return temp if check_redirect_repeat(str)
return regexp_no_proto_option.match(str)
end
# the reserved keywords check
elsif po.strip.match(/precedence$|dscp$|time-range$|packet-length$|ttl$|vlan$|set-erspan-gre-proto$|set-erspan-dscp$|log$/)
return regexp_no_proto_option.match(str)
else
return temp
end
# rubocop:enable Metrics/LineLength
end | ruby | {
"resource": ""
} |
q20307 | Cisco.Interface.hsrp_delay_minimum= | train | def hsrp_delay_minimum=(val)
Feature.hsrp_enable if val
config_set('interface', 'hsrp_delay', name: @name,
minimum: 'minimum', min: val, reload: '', rel: '')
end | ruby | {
"resource": ""
} |
q20308 | Cisco.StpGlobal.bd_total_range_with_vlans | train | def bd_total_range_with_vlans
hash = Vlan.vlans
arr = []
hash.keys.each do |id|
arr << id.to_i
end
Utils.array_to_str(arr)
ret_arr = []
ret_arr << Utils.array_to_str(arr)
end | ruby | {
"resource": ""
} |
q20309 | Cisco.ItdDeviceGroupNode.hs_weight | train | def hs_weight(hs, wt)
if hs != hot_standby && hot_standby == default_hot_standby
self.lweight = wt unless weight == wt
self.lhot_standby = hs
elsif hs != hot_standby && hot_standby != default_hot_standby
self.lhot_standby = hs
self.lweight = wt unless weight == wt
elsif wt != weight && weight == default_weight
self.lweight = wt
elsif wt != weight && weight != default_weight
self.lweight = wt
end
set_args_keys_default
end | ruby | {
"resource": ""
} |
q20310 | Cisco.BridgeDomainVNI.curr_bd_vni_hash | train | def curr_bd_vni_hash
final_bd_vni = {}
curr_vni = config_get('bridge_domain_vni', 'member_vni')
curr_bd_vni = config_get('bridge_domain_vni', 'member_vni_bd')
return final_bd_vni if curr_vni.empty? || curr_bd_vni.empty?
curr_vni_list = BridgeDomainVNI.string_to_array(curr_vni)
curr_bd_vni_list = BridgeDomainVNI.string_to_array(curr_bd_vni)
hash_map = Hash[curr_bd_vni_list.zip(curr_vni_list.map)]
@bd_ids_list.each do |bd|
final_bd_vni[bd.to_i] = hash_map[bd.to_i] if hash_map.key?(bd.to_i)
end
final_bd_vni
end | ruby | {
"resource": ""
} |
q20311 | Cisco.Node.massage_structured | train | def massage_structured(get_args, ref)
# Nothing to do unless nxapi_structured.
return [get_args, ref] unless
ref.hash['get_data_format'] == :nxapi_structured
# The CmdRef object will contain a get_value Array with 2 values.
# The first value is the key to identify the correct row in the table
# of structured output and the second is the key to identify the data
# to retrieve.
#
# Example: Get vlanshowbr-vlanname in the row that contains a specific
# vlan_id.
# "get_value"=>["vlanshowbr-vlanid-utf <vlan_id>", "vlanshowbr-vlanname"]
#
# TBD: Why do we need to check is_a?(Array) here?
if ref.hash['get_value'].is_a?(Array) && ref.hash['get_value'].size >= 2
# Replace the get_value hash entry with the value after any tokens
# specified in the yaml file have been replaced and set get_args[:value]
# to nil so that the structured table data can be retrieved properly.
ref.hash['get_value'] = get_args[:value]
ref.hash['drill_down'] = true
get_args[:value] = nil
cache_flush
end
[get_args, ref]
end | ruby | {
"resource": ""
} |
q20312 | Cisco.Node.massage | train | def massage(value, ref)
Cisco::Logger.debug "Massaging '#{value}' (#{value.inspect})"
value = drill_down_structured(value, ref)
if value.is_a?(Array) && !ref.multiple
fail "Expected zero/one value but got '#{value}'" if value.length > 1
value = value[0]
end
if (value.nil? || value.to_s.empty?) &&
ref.default_value? && ref.auto_default
Cisco::Logger.debug "Default: #{ref.default_value}"
return ref.default_value
end
if ref.multiple && ref.hash['get_data_format'] == :nxapi_structured
return value if value.nil?
value = [value.to_s] if value.is_a?(String) || value.is_a?(Fixnum)
end
return value unless ref.kind
value = massage_kind(value, ref)
Cisco::Logger.debug "Massaged to '#{value}'"
value
end | ruby | {
"resource": ""
} |
q20313 | Cisco.CommandReference.lookup | train | def lookup(feature, name)
value = @hash[feature]
value = value[name] if value.is_a? Hash
fail IndexError, "No CmdRef defined for #{feature}, #{name}" if value.nil?
value
end | ruby | {
"resource": ""
} |
q20314 | Cisco.CommandReference.validate_yaml | train | def validate_yaml(node, filename, depth=0, parents=nil)
return unless node && (mapping?(node) || node.children)
# Psych wraps everything in a Document instance, which we ignore.
unless node.class.ancestors.any? { |name| /Document/ =~ name.to_s }
depth += 1
end
debug "Validating #{node.class} at depth #{depth}"
# No special validation for non-mapping nodes - just recurse
unless mapping?(node)
node.children.each do |child|
validate_yaml(child, filename, depth, parents)
end
return
end
# For Mappings, we validate more extensively:
# 1. no duplicate keys are allowed (Psych doesn't catch this)
# 2. Features must be listed in alphabetical order for maintainability
# Take advantage of our known YAML structure to assign labels by depth
label = %w(feature name param).fetch(depth, 'key')
# Get the key nodes and value nodes under this mapping
key_children, val_children = get_keys_values_from_map(node)
# Get an array of key names
key_arr = key_children.map(&:value)
# Make sure no duplicate key names.
# If searching from the start of the array finds a name at one index,
# but searching from the end of the array finds it at a different one,
# then we have a duplicate.
dup = key_arr.detect { |e| key_arr.index(e) != key_arr.rindex(e) }
if dup
msg = "Duplicate #{label} '#{dup}'#{parents} in #{filename}!"
fail msg
end
# Enforce alphabetical ordering of features (only).
# We can extend this later to enforce ordering of names if desired
# by checking at depth 2 as well.
if depth == 1
last_key = nil
key_arr.each do |key|
if last_key && key < last_key
fail "features out of order in #{filename}: (#{last_key} > #{key})"
end
last_key = key
end
end
# Recurse to the children. We get a little fancy here so as to be able
# to provide more meaningful debug/error messages, such as:
# Duplicate param 'default_value' under feature 'foo', name 'bar'
key_children.zip(val_children).each do |key_node, val_node|
if parents
new_parents = parents + ", #{label} '#{key_node.value}'"
else
new_parents = " under #{label} '#{key_node.value}'"
end
validate_yaml(key_node, filename, depth, new_parents) # unnecessary?
validate_yaml(val_node, filename, depth, new_parents)
end
end | ruby | {
"resource": ""
} |
q20315 | Cisco.CommandReference.load_yaml | train | def load_yaml(yaml_file)
fail "File #{yaml_file} doesn't exist." unless File.exist?(yaml_file)
# Parse YAML file into a tree of nodes
# Psych::SyntaxError doesn't inherit from StandardError in some versions,
# so we want to explicitly catch it if using Psych.
rescue_errors = [::StandardError, ::Psych::SyntaxError]
yaml_parsed = File.open(yaml_file, 'r') do |f|
begin
YAML.parse(f)
rescue *rescue_errors => e
raise "unable to parse #{yaml_file}: #{e}"
end
end
return {} unless yaml_parsed
# Validate the node tree
validate_yaml(yaml_parsed, yaml_file)
# If validation passed, convert the node tree to a Ruby Hash.
yaml_parsed.transform
end | ruby | {
"resource": ""
} |
q20316 | Cisco.InterfaceOspf.message_digest_key_set | train | def message_digest_key_set(keyid, algtype, enctype, enc)
current_keyid = message_digest_key_id
if keyid == default_message_digest_key_id && current_keyid != keyid
config_set('interface_ospf', 'message_digest_key_set',
@interface.name, 'no', current_keyid,
'', '', '')
elsif keyid != default_message_digest_key_id
fail TypeError unless enc.is_a?(String)
fail ArgumentError unless enc.length > 0
enctype = Encryption.symbol_to_cli(enctype)
config_set('interface_ospf', 'message_digest_key_set',
@interface.name, '', keyid, algtype, enctype, enc)
end
end | ruby | {
"resource": ""
} |
q20317 | Cisco.InterfaceOspf.bfd | train | def bfd
val = config_get('interface_ospf', 'bfd', @interface.name)
return if val.nil?
val.include?('disable') ? false : true
end | ruby | {
"resource": ""
} |
q20318 | Cisco.InterfaceOspf.bfd= | train | def bfd=(val)
return if val == bfd
Feature.bfd_enable
state = (val == default_bfd) ? 'no' : ''
disable = val ? '' : 'disable'
config_set('interface_ospf', 'bfd', @interface.name,
state, disable)
end | ruby | {
"resource": ""
} |
q20319 | Cisco.InterfaceOspf.network_type= | train | def network_type=(type)
no_cmd = (type == default_network_type) ? 'no' : ''
network = (type == default_network_type) ? '' : type
network = 'point-to-point' if type.to_s == 'p2p'
config_set('interface_ospf', 'network_type', @interface.name,
no_cmd, network)
end | ruby | {
"resource": ""
} |
q20320 | Cisco.InterfaceOspf.passive_interface= | train | def passive_interface=(enable)
fail TypeError unless enable == true || enable == false
config_set('interface_ospf', 'passive_interface', @interface.name,
enable ? '' : 'no')
end | ruby | {
"resource": ""
} |
q20321 | Cisco.InterfaceOspf.priority= | train | def priority=(val)
no_cmd = (val == default_priority) ? 'no' : ''
pri = (val == default_priority) ? '' : val
config_set('interface_ospf', 'priority',
@interface.name, no_cmd, pri)
end | ruby | {
"resource": ""
} |
q20322 | Cisco.InterfaceOspf.transmit_delay= | train | def transmit_delay=(val)
no_cmd = (val == default_transmit_delay) ? 'no' : ''
delay = (val == default_transmit_delay) ? '' : val
config_set('interface_ospf', 'transmit_delay',
@interface.name, no_cmd, delay)
end | ruby | {
"resource": ""
} |
q20323 | Cisco.BfdGlobal.destroy | train | def destroy
return unless Feature.bfd_enabled?
[:interval,
:ipv4_interval,
:ipv6_interval,
:fabricpath_interval,
:echo_interface,
:echo_rx_interval,
:ipv4_echo_rx_interval,
:ipv6_echo_rx_interval,
:fabricpath_vlan,
:slow_timer,
:ipv4_slow_timer,
:ipv6_slow_timer,
:fabricpath_slow_timer,
:startup_timer,
].each do |prop|
send("#{prop}=", send("default_#{prop}")) if
send prop
end
set_args_keys_default
end | ruby | {
"resource": ""
} |
q20324 | Cisco.Vtp.domain= | train | def domain=(d)
d = d.to_s
fail ArgumentError unless d.length.between?(1, MAX_VTP_DOMAIN_NAME_SIZE)
config_set('vtp', 'domain', domain: d)
end | ruby | {
"resource": ""
} |
q20325 | Cisco.Vtp.password | train | def password
# Unfortunately nxapi returns "\\" when the password is not set
password = config_get('vtp', 'password') if Feature.vtp_enabled?
return '' if password.nil? || password == '\\'
password
rescue Cisco::RequestNotSupported => e
# Certain platforms generate a Cisco::RequestNotSupported when the
# vtp password is not set. We catch this specific error and
# return empty '' for the password.
return '' if e.message[/Structured output not supported/]
end | ruby | {
"resource": ""
} |
q20326 | Cisco.Vtp.password= | train | def password=(password)
fail TypeError if password.nil?
fail TypeError unless password.is_a? String
fail ArgumentError if password.length > MAX_VTP_PASSWORD_SIZE
Feature.vtp_enable
state = (password == default_password) ? 'no' : ''
config_set('vtp', 'password', state: state, password: password)
end | ruby | {
"resource": ""
} |
q20327 | Cisco.Vtp.filename= | train | def filename=(uri)
fail TypeError if uri.nil?
Feature.vtp_enable
uri = uri.to_s
state = uri.empty? ? 'no' : ''
config_set('vtp', 'filename', state: state, uri: uri)
end | ruby | {
"resource": ""
} |
q20328 | Cisco.RouterBgp.graceful_restart= | train | def graceful_restart=(enable)
if platform == :ios_xr && @vrf != 'default'
fail Cisco::UnsupportedError.new('bgp', 'graceful_restart', 'set',
'graceful_restart is not ' \
'configurable ' \
'on a per-VRF basis on IOS XR')
end
@set_args[:state] = (enable ? '' : 'no')
config_set('bgp', 'graceful_restart', @set_args)
set_args_keys_default
end | ruby | {
"resource": ""
} |
q20329 | Cisco.RouterBgp.timer_bgp_keepalive_hold_set | train | def timer_bgp_keepalive_hold_set(keepalive, hold)
if keepalive == default_timer_bgp_keepalive &&
hold == default_timer_bgp_holdtime
@set_args[:state] = 'no'
@set_args[:keepalive] = keepalive
@set_args[:hold] = hold
else
@set_args[:state] = ''
@set_args[:keepalive] = keepalive
@set_args[:hold] = hold
end
config_set('bgp', 'timer_bgp_keepalive_hold', @set_args)
set_args_keys_default
end | ruby | {
"resource": ""
} |
q20330 | Cisco.RouteMap.match_community | train | def match_community
str = config_get('route_map', 'match_community', @get_args)
if str.empty?
val = default_match_community
else
val = str.split
val.delete('exact-match')
end
val
end | ruby | {
"resource": ""
} |
q20331 | Cisco.RouteMap.match_metric | train | def match_metric
str = config_get('route_map', 'match_metric', @get_args)
return default_match_metric if str.empty?
rarr = []
larr = []
metrics = str.split
deviation = false
metrics.each do |metric|
deviation = true if metric == '+-'
if !larr.empty? && !deviation
larr << '0'
rarr << larr
larr = []
end
next if metric == '+-'
if !larr.empty? && deviation
larr << metric
rarr << larr
larr = []
deviation = false
next
end
larr << metric if larr.empty?
end
unless larr.empty?
larr << '0'
rarr << larr
end
rarr
end | ruby | {
"resource": ""
} |
q20332 | Cisco.RouteMap.match_ospf_area | train | def match_ospf_area
str = config_get('route_map', 'match_ospf_area', @get_args)
return if str.nil?
str.empty? ? default_match_ospf_area : str.split
end | ruby | {
"resource": ""
} |
q20333 | Cisco.RouteMap.match_mac_list | train | def match_mac_list
str = config_get('route_map', 'match_mac_list', @get_args)
return if str.nil?
str.empty? ? default_match_mac_list : str.split
end | ruby | {
"resource": ""
} |
q20334 | Cisco.RouteMap.match_evpn_route_type_get | train | def match_evpn_route_type_get
arr = config_get('route_map', 'match_evpn_route_type', @get_args)
return nil if arr.nil?
hash = {}
hash[:type1] = false
hash[:type3] = false
hash[:type4] = false
hash[:type5] = false
hash[:type6] = false
hash[:type_all] = false
hash[:type2_all] = false
hash[:type2_mac_ip] = false
hash[:type2_mac_only] = false
return hash if arr.empty?
hash[:type1] = true if arr.include?('1')
hash[:type3] = true if arr.include?('3')
hash[:type4] = true if arr.include?('4')
hash[:type5] = true if arr.include?('5')
hash[:type6] = true if arr.include?('6')
hash[:type_all] = true if arr.include?('all')
hash[:type2_all] = true if arr.include?('2 all')
hash[:type2_mac_ip] = true if arr.include?('2 mac-ip')
hash[:type2_mac_only] = true if arr.include?('2 mac-only')
hash
end | ruby | {
"resource": ""
} |
q20335 | Cisco.RouteMap.set_metric_get | train | def set_metric_get
hash = {}
hash[:additive] = false
hash[:bandwidth] = false
hash[:delay] = false
hash[:reliability] = false
hash[:effective_bandwidth] = false
hash[:mtu] = false
str = config_get('route_map', 'set_metric', @get_args)
return hash if str.nil?
arr = str.split
hash[:additive] = true if arr[0].include?('+')
hash[:bandwidth] = arr[0].delete('+').to_i
return hash if arr.size == 1
hash[:delay] = arr[1].to_i
hash[:reliability] = arr[2].to_i
hash[:effective_bandwidth] = arr[3].to_i
hash[:mtu] = arr[4].to_i
hash
end | ruby | {
"resource": ""
} |
q20336 | Cisco.RouteMap.set_dampening_get | train | def set_dampening_get
hash = {}
hash[:half_life] = false
hash[:reuse] = false
hash[:suppress] = false
hash[:max] = false
str = config_get('route_map', 'set_dampening', @get_args)
return hash if str.nil?
arr = str.split
hash[:half_life] = arr[0].to_i
hash[:reuse] = arr[1].to_i
hash[:suppress] = arr[2].to_i
hash[:max] = arr[3].to_i
hash
end | ruby | {
"resource": ""
} |
q20337 | Cisco.RouteMap.set_as_path_prepend | train | def set_as_path_prepend
arr = []
match = config_get('route_map', 'set_as_path_prepend', @get_args)
if arr
match.each do |line|
next if line.include?('last-as')
arr = line.strip.split
end
end
arr
end | ruby | {
"resource": ""
} |
q20338 | Cisco.RouteMap.set_ipv4_default_next_hop | train | def set_ipv4_default_next_hop
str = config_get('route_map', 'set_ipv4_default_next_hop', @get_args)
return if str.nil?
if str.empty?
val = default_set_ipv4_default_next_hop
else
val = str.split
val.delete('load-share')
end
val
end | ruby | {
"resource": ""
} |
q20339 | Cisco.RouteMap.set_ipv4_next_hop | train | def set_ipv4_next_hop
arr = config_get('route_map', 'set_ipv4_next_hop', @get_args)
val = default_set_ipv4_next_hop
arr.each do |str|
next if str.empty?
next if str.include?('peer-address')
next if str.include?('unchanged')
next if str.include?('redist-unchanged')
val = str.split
val.delete('load-share')
end
val
end | ruby | {
"resource": ""
} |
q20340 | Cisco.RouteMap.set_ipv4_next_hop_load_share | train | def set_ipv4_next_hop_load_share
arr = config_get('route_map', 'set_ipv4_next_hop', @get_args)
val = default_set_ipv4_next_hop_load_share
arr.each do |str|
next if str.empty?
return true if str.include?('load-share')
end
val
end | ruby | {
"resource": ""
} |
q20341 | Cisco.RouteMap.set_ipv6_default_next_hop | train | def set_ipv6_default_next_hop
str = config_get('route_map', 'set_ipv6_default_next_hop', @get_args)
return if str.nil?
if str.empty?
val = default_set_ipv6_default_next_hop
else
val = str.split
val.delete('load-share')
end
val
end | ruby | {
"resource": ""
} |
q20342 | Cisco.RouteMap.set_ipv6_next_hop | train | def set_ipv6_next_hop
arr = config_get('route_map', 'set_ipv6_next_hop', @get_args)
val = default_set_ipv6_next_hop
arr.each do |str|
next if str.empty?
next if str.include?('peer-address')
next if str.include?('unchanged')
next if str.include?('redist-unchanged')
val = str.split
val.delete('load-share')
end
val
end | ruby | {
"resource": ""
} |
q20343 | Cisco.RouteMap.set_ipv6_next_hop_load_share | train | def set_ipv6_next_hop_load_share
arr = config_get('route_map', 'set_ipv6_next_hop', @get_args)
val = default_set_ipv6_next_hop_load_share
arr.each do |str|
next if str.empty?
return true if str.include?('load-share')
end
val
end | ruby | {
"resource": ""
} |
q20344 | Cisco.RouteMap.set_extcommunity_cost_set | train | def set_extcommunity_cost_set(igp, pre)
str = ''
# reset first
if set_extcommunity_cost_device
cpre = set_extcommunity_cost_pre_bestpath
cigp = set_extcommunity_cost_igp
cpre.each do |id, val|
str.concat('pre-bestpath ' + id.to_s + ' ' + val.to_s + ' ')
end
cigp.each do |id, val|
str.concat('igp ' + id.to_s + ' ' + val.to_s + ' ')
end
end
set_args_keys(state: 'no', string: str)
config_set('route_map', 'set_extcommunity_cost', @set_args)
return if igp.empty? && pre.empty?
str = ''
pre.each do |id, val|
str.concat('pre-bestpath ' + id.to_s + ' ' + val.to_s + ' ')
end
igp.each do |id, val|
str.concat('igp ' + id.to_s + ' ' + val.to_s + ' ')
end
set_args_keys(state: '', string: str)
config_set('route_map', 'set_extcommunity_cost', @set_args)
end | ruby | {
"resource": ""
} |
q20345 | Cisco.OverlayGlobal.anycast_gateway_mac | train | def anycast_gateway_mac
mac = config_get('overlay_global', 'anycast_gateway_mac')
mac.nil? || mac.empty? ? default_anycast_gateway_mac : mac.downcase
end | ruby | {
"resource": ""
} |
q20346 | Cisco.TacacsServer.encryption_key_set | train | def encryption_key_set(enctype, password)
password = Utils.add_quotes(password)
# if enctype is TACACS_SERVER_ENC_UNKNOWN, we will unset the key
if enctype == TACACS_SERVER_ENC_UNKNOWN
# if current encryption type is not TACACS_SERVER_ENC_UNKNOWN, we
# need to unset it. Otherwise the box is not configured with key, we
# don't need to do anything
if encryption_type != TACACS_SERVER_ENC_UNKNOWN
config_set('tacacs_server', 'encryption', state: 'no',
option: encryption_type,
key: encryption_password)
end
else
config_set('tacacs_server', 'encryption', state: '', option: enctype,
key: password)
end
end | ruby | {
"resource": ""
} |
q20347 | Cisco.ItdService.ingress_interface= | train | def ingress_interface=(list)
ingress_interface_cleanup
@set_args[:state] = ''
list.each do |intf, next_hop|
@set_args[:interface] = intf
@set_args[:next] = ''
@set_args[:nhop] = ''
unless next_hop == '' || next_hop == 'default'
@set_args[:next] = 'next-hop'
@set_args[:nhop] = next_hop
end
config_set('itd_service', 'ingress_interface', @set_args)
end
set_args_keys_default
end | ruby | {
"resource": ""
} |
q20348 | TomlRB.Keygroup.ensure_key_not_defined | train | def ensure_key_not_defined(visited_keys)
fail ValueOverwriteError.new(full_key) if visited_keys.include?(full_key)
visited_keys << full_key
end | ruby | {
"resource": ""
} |
q20349 | Watir.Screenshot.save_stitch | train | def save_stitch(path, opts = {})
return @browser.screenshot.save(path) if base64_capable?
@options = opts
@path = path
calculate_dimensions
return self.save(@path) if (one_shot? || bug_shot?)
build_canvas
gather_slices
stitch_together
@combined_screenshot.write @path
end | ruby | {
"resource": ""
} |
q20350 | Watir.Screenshot.base64_canvas | train | def base64_canvas
return self.base64 if base64_capable?
output = nil
return self.base64 if one_shot? || bug_shot?
@browser.execute_script html2canvas_payload
@browser.execute_script h2c_activator
@browser.wait_until(timeout: MAXIMUM_SCREENSHOT_GENERATION_WAIT_TIME) {
output = @browser.execute_script "return window.canvasImgContentDecoded;"
}
raise "Could not generate screenshot blob within #{MAXIMUM_SCREENSHOT_GENERATION_WAIT_TIME} seconds" unless output
output.sub!(/^data\:image\/png\;base64,/, '')
end | ruby | {
"resource": ""
} |
q20351 | RedisFailover.Client.setup_zk | train | def setup_zk
@zk = ZK.new(@zkservers) if @zkservers
@zk.register(redis_nodes_path) { |event| handle_zk_event(event) }
if @safe_mode
@zk.on_expired_session { purge_clients }
end
@zk.on_connected { @zk.stat(redis_nodes_path, :watch => true) }
@zk.stat(redis_nodes_path, :watch => true)
update_znode_timestamp
end | ruby | {
"resource": ""
} |
q20352 | RedisFailover.Client.handle_zk_event | train | def handle_zk_event(event)
update_znode_timestamp
if event.node_created? || event.node_changed?
build_clients
elsif event.node_deleted?
purge_clients
@zk.stat(redis_nodes_path, :watch => true)
else
logger.error("Unknown ZK node event: #{event.inspect}")
end
ensure
@zk.stat(redis_nodes_path, :watch => true)
end | ruby | {
"resource": ""
} |
q20353 | RedisFailover.Client.dispatch | train | def dispatch(method, *args, &block)
if @safe_mode && !recently_heard_from_node_manager?
build_clients
end
verify_supported!(method)
tries = 0
begin
client_for(method).send(method, *args, &block)
rescue *CONNECTIVITY_ERRORS => ex
logger.error("Error while handling `#{method}` - #{ex.inspect}")
logger.error(ex.backtrace.join("\n"))
if tries < @max_retries
tries += 1
free_client
build_clients
sleep(RETRY_WAIT_TIME)
retry
end
raise
ensure
free_client
end
end | ruby | {
"resource": ""
} |
q20354 | RedisFailover.Client.fetch_nodes | train | def fetch_nodes
data = @zk.get(redis_nodes_path, :watch => true).first
nodes = symbolize_keys(decode(data))
logger.debug("Fetched nodes: #{nodes.inspect}")
nodes
rescue Zookeeper::Exceptions::InheritedConnectionError, ZK::Exceptions::InterruptedSession => ex
logger.debug { "Caught #{ex.class} '#{ex.message}' - reopening ZK client" }
@zk.reopen
retry
rescue *ZK_ERRORS => ex
logger.warn { "Caught #{ex.class} '#{ex.message}' - retrying" }
sleep(RETRY_WAIT_TIME)
retry
end | ruby | {
"resource": ""
} |
q20355 | RedisFailover.Client.new_clients_for | train | def new_clients_for(*nodes)
nodes.map do |node|
host, port = node.split(':')
opts = {:host => host, :port => port}
opts.update(:db => @db) if @db
opts.update(:password => @password) if @password
client = Redis.new(@redis_client_options.merge(opts))
if @namespace
client = Redis::Namespace.new(@namespace, :redis => client)
end
@node_addresses[client] = node
client
end
end | ruby | {
"resource": ""
} |
q20356 | RedisFailover.Client.verify_role! | train | def verify_role!(node, role)
current_role = node.info['role']
if current_role.to_sym != role
raise InvalidNodeRoleError.new(address_for(node), role, current_role)
end
role
end | ruby | {
"resource": ""
} |
q20357 | RedisFailover.Client.nodes_changed? | train | def nodes_changed?(new_nodes)
return true if address_for(@master) != new_nodes[:master]
return true if different?(addresses_for(@slaves), new_nodes[:slaves])
false
end | ruby | {
"resource": ""
} |
q20358 | RedisFailover.Client.client_for | train | def client_for(method)
stack = Thread.current[@current_client_key] ||= []
client = if stack.last
stack.last
elsif @master_only
master
elsif REDIS_READ_OPS.include?(method)
slave
else
master
end
stack << client
client
end | ruby | {
"resource": ""
} |
q20359 | RedisFailover.Client.parse_options | train | def parse_options(options)
@zk, @zkservers = options.values_at(:zk, :zkservers)
if [@zk, @zkservers].all? || [@zk, @zkservers].none?
raise ArgumentError, 'must specify :zk or :zkservers'
end
@root_znode = options.fetch(:znode_path, Util::DEFAULT_ROOT_ZNODE_PATH)
@namespace = options[:namespace]
@password = options[:password]
@db = options[:db]
@retry = options.fetch(:retry_failure, true)
@max_retries = @retry ? options.fetch(:max_retries, 3) : 0
@safe_mode = options.fetch(:safe_mode, true)
@master_only = options.fetch(:master_only, false)
@verify_role = options.fetch(:verify_role, true)
@redis_client_options = Redis::Client::DEFAULTS.keys.each_with_object({}) do |key, hash|
hash[key] = options[key]
end
end | ruby | {
"resource": ""
} |
q20360 | RedisFailover.Node.make_slave! | train | def make_slave!(node)
perform_operation do |redis|
unless slave_of?(node)
redis.slaveof(node.host, node.port)
logger.info("#{self} is now a slave of #{node}")
wakeup
end
end
end | ruby | {
"resource": ""
} |
q20361 | RedisFailover.Node.perform_operation | train | def perform_operation
redis = nil
Timeout.timeout(MAX_OP_WAIT_TIME) do
redis = new_client
yield redis
end
rescue Exception => ex
raise NodeUnavailableError, "#{ex.class}: #{ex.message}", ex.backtrace
ensure
if redis
begin
redis.client.disconnect
rescue Exception => ex
raise NodeUnavailableError, "#{ex.class}: #{ex.message}", ex.backtrace
end
end
end | ruby | {
"resource": ""
} |
q20362 | RedisFailover.NodeManager.setup_zk | train | def setup_zk
unless @zk
@zk = ZK.new("#{@options[:zkservers]}#{@options[:chroot] || ''}")
@zk.register(manual_failover_path) do |event|
handle_manual_failover_update(event)
end
@zk.on_connected { @zk.stat(manual_failover_path, :watch => true) }
end
create_path(@root_znode)
create_path(current_state_root)
@zk.stat(manual_failover_path, :watch => true)
end | ruby | {
"resource": ""
} |
q20363 | RedisFailover.NodeManager.handle_unavailable | train | def handle_unavailable(node, snapshots)
# no-op if we already know about this node
return if @unavailable.include?(node)
logger.info("Handling unavailable node: #{node}")
@unavailable << node
# find a new master if this node was a master
if node == @master
logger.info("Demoting currently unavailable master #{node}.")
promote_new_master(snapshots)
else
@slaves.delete(node)
end
end | ruby | {
"resource": ""
} |
q20364 | RedisFailover.NodeManager.handle_available | train | def handle_available(node, snapshots)
reconcile(node)
# no-op if we already know about this node
return if @master == node || (@master && @slaves.include?(node))
logger.info("Handling available node: #{node}")
if @master
# master already exists, make a slave
node.make_slave!(@master)
@slaves << node
else
# no master exists, make this the new master
promote_new_master(snapshots, node)
end
@unavailable.delete(node)
end | ruby | {
"resource": ""
} |
q20365 | RedisFailover.NodeManager.handle_syncing | train | def handle_syncing(node, snapshots)
reconcile(node)
if node.syncing_with_master? && node.prohibits_stale_reads?
logger.info("Node #{node} not ready yet, still syncing with master.")
force_unavailable_slave(node)
else
# otherwise, we can use this node
handle_available(node, snapshots)
end
end | ruby | {
"resource": ""
} |
q20366 | RedisFailover.NodeManager.handle_manual_failover | train | def handle_manual_failover(node, snapshots)
# no-op if node to be failed over is already master
return if @master == node
logger.info("Handling manual failover")
# ensure we can talk to the node
node.ping
# make current master a slave, and promote new master
@slaves << @master if @master
@slaves.delete(node)
promote_new_master(snapshots, node)
end | ruby | {
"resource": ""
} |
q20367 | RedisFailover.NodeManager.promote_new_master | train | def promote_new_master(snapshots, node = nil)
delete_path(redis_nodes_path)
@master = nil
# make a specific node or selected candidate the new master
candidate = node || failover_strategy_candidate(snapshots)
if candidate.nil?
logger.error('Failed to promote a new master, no candidate available.')
else
@slaves.delete(candidate)
@unavailable.delete(candidate)
redirect_slaves_to(candidate)
candidate.make_master!
@master = candidate
write_current_redis_nodes
@master_promotion_attempts = 0
logger.info("Successfully promoted #{candidate} to master.")
end
end | ruby | {
"resource": ""
} |
q20368 | RedisFailover.NodeManager.find_existing_master | train | def find_existing_master
if data = @zk.get(redis_nodes_path).first
nodes = symbolize_keys(decode(data))
master = node_from(nodes[:master])
logger.info("Master from existing znode config: #{master || 'none'}")
# Check for case where a node previously thought to be the master was
# somehow manually reconfigured to be a slave outside of the node manager's
# control.
begin
if master && master.slave?
raise InvalidNodeRoleError.new(master, :master, :slave)
end
rescue RedisFailover::NodeUnavailableError => ex
logger.warn("Failed to check whether existing master has invalid role: #{ex.inspect}")
end
master
end
rescue ZK::Exceptions::NoNode
# blank slate, no last known master
nil
end | ruby | {
"resource": ""
} |
q20369 | RedisFailover.NodeManager.node_from | train | def node_from(node_string)
return if node_string.nil?
host, port = node_string.split(':', 2)
Node.new(:host => host, :port => port, :password => @options[:password])
end | ruby | {
"resource": ""
} |
q20370 | RedisFailover.NodeManager.guess_master | train | def guess_master(nodes)
master_nodes = nodes.select { |node| node.master? }
raise NoMasterError if master_nodes.empty?
raise MultipleMastersError.new(master_nodes) if master_nodes.size > 1
master_nodes.first
end | ruby | {
"resource": ""
} |
q20371 | RedisFailover.NodeManager.redirect_slaves_to | train | def redirect_slaves_to(node)
@slaves.dup.each do |slave|
begin
slave.make_slave!(node)
rescue NodeUnavailableError
logger.info("Failed to redirect unreachable slave #{slave} to #{node}")
force_unavailable_slave(slave)
end
end
end | ruby | {
"resource": ""
} |
q20372 | RedisFailover.NodeManager.reconcile | train | def reconcile(node)
return if @master == node && node.master?
return if @master && node.slave_of?(@master)
logger.info("Reconciling node #{node}")
if @master == node && !node.master?
# we think the node is a master, but the node doesn't
node.make_master!
return
end
# verify that node is a slave for the current master
if @master && !node.slave_of?(@master)
node.make_slave!(@master)
end
end | ruby | {
"resource": ""
} |
q20373 | RedisFailover.NodeManager.delete_path | train | def delete_path(path)
@zk.delete(path)
logger.info("Deleted ZK node #{path}")
rescue ZK::Exceptions::NoNode => ex
logger.info("Tried to delete missing znode: #{ex.inspect}")
end | ruby | {
"resource": ""
} |
q20374 | RedisFailover.NodeManager.create_path | train | def create_path(path, options = {})
unless @zk.exists?(path)
@zk.create(path,
options[:initial_value],
:ephemeral => options.fetch(:ephemeral, false))
logger.info("Created ZK node #{path}")
end
rescue ZK::Exceptions::NodeExists
# best effort
end | ruby | {
"resource": ""
} |
q20375 | RedisFailover.NodeManager.write_state | train | def write_state(path, value, options = {})
create_path(path, options.merge(:initial_value => value))
@zk.set(path, value)
end | ruby | {
"resource": ""
} |
q20376 | RedisFailover.NodeManager.handle_manual_failover_update | train | def handle_manual_failover_update(event)
if event.node_created? || event.node_changed?
perform_manual_failover
end
rescue => ex
logger.error("Error scheduling a manual failover: #{ex.inspect}")
logger.error(ex.backtrace.join("\n"))
ensure
@zk.stat(manual_failover_path, :watch => true)
end | ruby | {
"resource": ""
} |
q20377 | RedisFailover.NodeManager.update_master_state | train | def update_master_state(node, snapshots)
state = @node_strategy.determine_state(node, snapshots)
case state
when :unavailable
handle_unavailable(node, snapshots)
when :available
if node.syncing_with_master?
handle_syncing(node, snapshots)
else
handle_available(node, snapshots)
end
else
raise InvalidNodeStateError.new(node, state)
end
rescue *ZK_ERRORS
# fail hard if this is a ZK connection-related error
raise
rescue => ex
logger.error("Error handling state report for #{[node, state].inspect}: #{ex.inspect}")
end | ruby | {
"resource": ""
} |
q20378 | RedisFailover.NodeManager.update_current_state | train | def update_current_state(node, state, latency = nil)
old_unavailable = @monitored_unavailable.dup
old_available = @monitored_available.dup
case state
when :unavailable
unless @monitored_unavailable.include?(node)
@monitored_unavailable << node
@monitored_available.delete(node)
write_current_monitored_state
end
when :available
last_latency = @monitored_available[node]
if last_latency.nil? || (latency - last_latency) > LATENCY_THRESHOLD
@monitored_available[node] = latency
@monitored_unavailable.delete(node)
write_current_monitored_state
end
else
raise InvalidNodeStateError.new(node, state)
end
rescue => ex
# if an error occurs, make sure that we rollback to the old state
@monitored_unavailable = old_unavailable
@monitored_available = old_available
raise
end | ruby | {
"resource": ""
} |
q20379 | RedisFailover.NodeManager.current_node_snapshots | train | def current_node_snapshots
nodes = {}
snapshots = Hash.new { |h, k| h[k] = NodeSnapshot.new(k) }
fetch_node_manager_states.each do |node_manager, states|
available, unavailable = states.values_at(:available, :unavailable)
available.each do |node_string, latency|
node = nodes[node_string] ||= node_from(node_string)
snapshots[node].viewable_by(node_manager, latency)
end
unavailable.each do |node_string|
node = nodes[node_string] ||= node_from(node_string)
snapshots[node].unviewable_by(node_manager)
end
end
snapshots
end | ruby | {
"resource": ""
} |
q20380 | RedisFailover.NodeManager.wait_until_master | train | def wait_until_master
logger.info('Waiting to become master Node Manager ...')
with_lock do
@master_manager = true
logger.info('Acquired master Node Manager lock.')
logger.info("Configured node strategy #{@node_strategy.class}")
logger.info("Configured failover strategy #{@failover_strategy.class}")
logger.info("Required Node Managers to make a decision: #{@required_node_managers}")
manage_nodes
end
end | ruby | {
"resource": ""
} |
q20381 | RedisFailover.NodeManager.manage_nodes | train | def manage_nodes
# Re-discover nodes, since the state of the world may have been changed
# by the time we've become the primary node manager.
discover_nodes
# ensure that slaves are correctly pointing to this master
redirect_slaves_to(@master)
# Periodically update master config state.
while running? && master_manager?
@zk_lock.assert!
sleep(CHECK_INTERVAL)
@lock.synchronize do
snapshots = current_node_snapshots
if ensure_sufficient_node_managers(snapshots)
snapshots.each_key do |node|
update_master_state(node, snapshots)
end
# flush current master state
write_current_redis_nodes
# check if we've exhausted our attempts to promote a master
unless @master
@master_promotion_attempts += 1
raise NoMasterError if @master_promotion_attempts > MAX_PROMOTION_ATTEMPTS
end
end
end
end
end | ruby | {
"resource": ""
} |
q20382 | RedisFailover.NodeManager.with_lock | train | def with_lock
@zk_lock ||= @zk.locker(current_lock_path)
begin
@zk_lock.lock!(true)
rescue Exception
# handle shutdown case
running? ? raise : return
end
if running?
@zk_lock.assert!
yield
end
ensure
if @zk_lock
begin
@zk_lock.unlock!
rescue => ex
logger.warn("Failed to release lock: #{ex.inspect}")
end
end
end | ruby | {
"resource": ""
} |
q20383 | RedisFailover.NodeManager.perform_manual_failover | train | def perform_manual_failover
@lock.synchronize do
return unless running? && @master_manager && @zk_lock
@zk_lock.assert!
new_master = @zk.get(manual_failover_path, :watch => true).first
return unless new_master && new_master.size > 0
logger.info("Received manual failover request for: #{new_master}")
logger.info("Current nodes: #{current_nodes.inspect}")
snapshots = current_node_snapshots
node = if new_master == ManualFailover::ANY_SLAVE
failover_strategy_candidate(snapshots)
else
node_from(new_master)
end
if node
handle_manual_failover(node, snapshots)
else
logger.error('Failed to perform manual failover, no candidate found.')
end
end
rescue => ex
logger.error("Error handling manual failover: #{ex.inspect}")
logger.error(ex.backtrace.join("\n"))
ensure
@zk.stat(manual_failover_path, :watch => true)
end | ruby | {
"resource": ""
} |
q20384 | RedisFailover.NodeManager.ensure_sufficient_node_managers | train | def ensure_sufficient_node_managers(snapshots)
currently_sufficient = true
snapshots.each do |node, snapshot|
node_managers = snapshot.node_managers
if node_managers.size < @required_node_managers
logger.error("Not enough Node Managers in snapshot for node #{node}. " +
"Required: #{@required_node_managers}, " +
"Available: #{node_managers.size} #{node_managers}")
currently_sufficient = false
end
end
if currently_sufficient && !@sufficient_node_managers
logger.info("Required Node Managers are visible: #{@required_node_managers}")
end
@sufficient_node_managers = currently_sufficient
@sufficient_node_managers
end | ruby | {
"resource": ""
} |
q20385 | RedisFailover.NodeManager.failover_strategy_candidate | train | def failover_strategy_candidate(snapshots)
# only include nodes that this master Node Manager can see
filtered_snapshots = snapshots.select do |node, snapshot|
snapshot.viewable_by?(manager_id)
end
logger.info('Attempting to find candidate from snapshots:')
logger.info("\n" + filtered_snapshots.values.join("\n"))
@failover_strategy.find_candidate(filtered_snapshots)
end | ruby | {
"resource": ""
} |
q20386 | PKCS11.Library.C_Initialize | train | def C_Initialize(args=nil)
case args
when Hash
pargs = CK_C_INITIALIZE_ARGS.new
args.each{|k,v| pargs.send("#{k}=", v) }
else
pargs = args
end
unwrapped_C_Initialize(pargs)
end | ruby | {
"resource": ""
} |
q20387 | PKCS11.Library.C_GetSlotList | train | def C_GetSlotList(tokenPresent=false)
slots = unwrapped_C_GetSlotList(tokenPresent)
slots.map{|slot|
Slot.new self, slot
}
end | ruby | {
"resource": ""
} |
q20388 | PKCS11.Session.C_FindObjects | train | def C_FindObjects(max_count)
objs = @pk.C_FindObjects(@sess, max_count)
objs.map{|obj| Object.new @pk, @sess, obj }
end | ruby | {
"resource": ""
} |
q20389 | PKCS11.Session.C_GenerateKey | train | def C_GenerateKey(mechanism, template={})
obj = @pk.C_GenerateKey(@sess, to_mechanism(mechanism), to_attributes(template))
Object.new @pk, @sess, obj
end | ruby | {
"resource": ""
} |
q20390 | PKCS11.Session.C_DeriveKey | train | def C_DeriveKey(mechanism, base_key, template={})
obj = @pk.C_DeriveKey(@sess, to_mechanism(mechanism), base_key, to_attributes(template))
Object.new @pk, @sess, obj
end | ruby | {
"resource": ""
} |
q20391 | PKCS11.Slot.C_OpenSession | train | def C_OpenSession(flags=CKF_SERIAL_SESSION)
nr = @pk.C_OpenSession(@slot, flags)
sess = Session.new @pk, nr
if block_given?
begin
yield sess
ensure
sess.close
end
else
sess
end
end | ruby | {
"resource": ""
} |
q20392 | PKCS11.Object.[] | train | def [](*attributes)
attrs = C_GetAttributeValue( attributes.flatten )
if attrs.length>1 || attributes.first.kind_of?(Array)
attrs.map(&:value)
else
attrs.first.value unless attrs.empty?
end
end | ruby | {
"resource": ""
} |
q20393 | PKCS11.Object.[]= | train | def []=(*attributes)
values = attributes.pop
values = [values] unless values.kind_of?(Array)
raise ArgumentError, "different number of attributes to set (#{attributes.length}) and given values (#{values.length})" unless attributes.length == values.length
map = values.each.with_index.inject({}){|s, v| s[attributes[v[1]]] = v[0]; s }
C_SetAttributeValue( map )
end | ruby | {
"resource": ""
} |
q20394 | PKCS11.Object.C_GetAttributeValue | train | def C_GetAttributeValue(*template)
case template.length
when 0
return @pk.vendor_all_attribute_names.map{|attr|
begin
attributes(@pk.vendor_const_get(attr))
rescue PKCS11::Error
end
}.flatten.compact
when 1
template = template[0]
end
template = to_attributes template
@pk.C_GetAttributeValue(@sess, @obj, template)
end | ruby | {
"resource": ""
} |
q20395 | Sendinblue.Mailin.get_campaigns_v2 | train | def get_campaigns_v2(data)
if data['type'] == "" and data['status'] == "" and data['page'] == "" and data['page_limit'] == ""
return self.get("campaign/detailsv2/","")
else
return self.get("campaign/detailsv2/type/" + data['type'] + "/status/" + data['status'] + "/page/" + data['page'].to_s + "/page_limit/" + data['page_limit'].to_s + "/","")
end
end | ruby | {
"resource": ""
} |
q20396 | Podio.Client.authenticate_with_auth_code | train | def authenticate_with_auth_code(authorization_code, redirect_uri)
response = @oauth_connection.post do |req|
req.url '/oauth/token'
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.body = {:grant_type => 'authorization_code', :client_id => api_key, :client_secret => api_secret, :code => authorization_code, :redirect_uri => redirect_uri}
end
@oauth_token = OAuthToken.new(response.body)
configure_oauth
@oauth_token
end | ruby | {
"resource": ""
} |
q20397 | Podio.Client.authenticate_with_credentials | train | def authenticate_with_credentials(username, password, offering_id=nil)
body = {:grant_type => 'password', :client_id => api_key, :client_secret => api_secret, :username => username, :password => password}
body[:offering_id] = offering_id if offering_id.present?
response = @oauth_connection.post do |req|
req.url '/oauth/token'
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.body = body
end
@oauth_token = OAuthToken.new(response.body)
configure_oauth
@oauth_token
end | ruby | {
"resource": ""
} |
q20398 | Podio.Client.authenticate_with_app | train | def authenticate_with_app(app_id, app_token)
response = @oauth_connection.post do |req|
req.url '/oauth/token'
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.body = {:grant_type => 'app', :client_id => api_key, :client_secret => api_secret, :app_id => app_id, :app_token => app_token}
end
@oauth_token = OAuthToken.new(response.body)
configure_oauth
@oauth_token
end | ruby | {
"resource": ""
} |
q20399 | Podio.Client.authenticate_with_transfer_token | train | def authenticate_with_transfer_token(transfer_token)
response = @oauth_connection.post do |req|
req.url '/oauth/token'
req.headers['Content-Type'] = 'application/x-www-form-urlencoded'
req.body = {:grant_type => 'transfer_token', :client_id => api_key, :client_secret => api_secret, :transfer_token => transfer_token}
end
@oauth_token = OAuthToken.new(response.body)
configure_oauth
@oauth_token
end | ruby | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.