_id
stringlengths 2
6
| title
stringlengths 9
130
| partition
stringclasses 3
values | text
stringlengths 30
4.3k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q25600
|
HIDAPI.Device.get_feature_report
|
validation
|
def get_feature_report(report_number, buffer_size = nil)
buffer_size ||= input_ep_max_packet_size
mutex.synchronize do
handle.control_transfer(
bmRequestType: LIBUSB::REQUEST_TYPE_CLASS | LIBUSB::RECIPIENT_INTERFACE | LIBUSB::ENDPOINT_IN,
bRequest:
|
ruby
|
{
"resource": ""
}
|
q25601
|
HIDAPI.Device.read_string
|
validation
|
def read_string(index, on_failure = '')
begin
# does not require an interface, so open from the usb_dev instead of using our open method.
data = mutex.synchronize do
if open?
handle.string_descriptor_ascii(index)
|
ruby
|
{
"resource": ""
}
|
q25602
|
SimpleAudit.Audit.delta
|
validation
|
def delta(other_audit)
return self.change_log if other_audit.nil?
{}.tap do |d|
# first for keys present only in this audit
(self.change_log.keys - other_audit.change_log.keys).each do |k|
d[k] = [nil, self.change_log[k]]
end
# .. then for keys present only
|
ruby
|
{
"resource": ""
}
|
q25603
|
SimpleAudit.Helper.render_audits
|
validation
|
def render_audits(audited_model)
return '' unless audited_model.respond_to?(:audits)
audits = (audited_model.audits || []).dup.sort{|a,b| b.created_at <=> a.created_at}
res = ''
audits.each_with_index do |audit, index|
older_audit = audits[index + 1]
res += content_tag(:div, :class => 'audit') do
content_tag(:div, audit.action, :class => "action #{audit.action}") +
content_tag(:div, audit.username, :class => "user") +
content_tag(:div, l(audit.created_at), :class => "timestamp") +
content_tag(:div, :class => 'changes') do
changes = if older_audit.present?
|
ruby
|
{
"resource": ""
}
|
q25604
|
Guard.Haml._output_paths
|
validation
|
def _output_paths(file)
input_file_dir = File.dirname(file)
file_name = _output_filename(file)
file_name = "#{file_name}.html" if _append_html_ext_to_output_path?(file_name)
input_file_dir = input_file_dir.gsub(Regexp.new("#{options[:input]}(\/){0,1}"), '') if
|
ruby
|
{
"resource": ""
}
|
q25605
|
Guard.Haml._output_filename
|
validation
|
def _output_filename(file)
sub_strings = File.basename(file).split('.')
base_name, extensions = sub_strings.first, sub_strings[1..-1]
if extensions.last == 'haml'
extensions.pop
if extensions.empty?
[base_name, options[:default_ext]].join('.')
|
ruby
|
{
"resource": ""
}
|
q25606
|
VCloudClient.Connection.get_vapp_by_name
|
validation
|
def get_vapp_by_name(organization, vdcName, vAppName)
result = nil
get_vdc_by_name(organization, vdcName)[:vapps].each do |vapp|
|
ruby
|
{
"resource": ""
}
|
q25607
|
VCloudClient.Connection.poweroff_vapp
|
validation
|
def poweroff_vapp(vAppId)
builder = Nokogiri::XML::Builder.new do |xml|
xml.UndeployVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5") {
xml.UndeployPowerAction 'powerOff'
}
end
params = {
'method' => :post,
'command' => "/vApp/vapp-#{vAppId}/action/undeploy"
|
ruby
|
{
"resource": ""
}
|
q25608
|
VCloudClient.Connection.create_vapp_from_template
|
validation
|
def create_vapp_from_template(vdc, vapp_name, vapp_description, vapp_templateid, poweron=false)
builder = Nokogiri::XML::Builder.new do |xml|
xml.InstantiateVAppTemplateParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:xsi" => "http://www.w3.org/2001/XMLSchema-instance",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"name" => vapp_name,
"deploy" => "true",
"powerOn" => poweron) {
xml.Description vapp_description
xml.Source("href" => "#{@api_url}/vAppTemplate/#{vapp_templateid}")
}
end
params = {
"method" => :post,
"command" => "/vdc/#{vdc}/action/instantiateVAppTemplate"
|
ruby
|
{
"resource": ""
}
|
q25609
|
VCloudClient.Connection.compose_vapp_from_vm
|
validation
|
def compose_vapp_from_vm(vdc, vapp_name, vapp_description, vm_list={}, network_config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.ComposeVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"name" => vapp_name) {
xml.Description vapp_description
xml.InstantiationParams {
xml.NetworkConfigSection {
xml['ovf'].Info "Configuration parameters for logical networks"
xml.NetworkConfig("networkName" => network_config[:name]) {
xml.Configuration {
xml.IpScopes {
xml.IpScope {
xml.IsInherited(network_config[:is_inherited] || "false")
xml.Gateway network_config[:gateway]
xml.Netmask network_config[:netmask]
xml.Dns1 network_config[:dns1] if network_config[:dns1]
xml.Dns2 network_config[:dns2] if network_config[:dns2]
xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]
xml.IpRanges {
xml.IpRange {
xml.StartAddress network_config[:start_address]
xml.EndAddress network_config[:end_address]
}
}
}
}
xml.ParentNetwork("href" => "#{@api_url}/network/#{network_config[:parent_network]}")
xml.FenceMode network_config[:fence_mode]
xml.Features {
xml.FirewallService {
xml.IsEnabled(network_config[:enable_firewall] || "false")
}
if network_config.has_key? :nat_type
xml.NatService {
xml.IsEnabled "true"
xml.NatType network_config[:nat_type]
xml.Policy(network_config[:nat_policy_type] || "allowTraffic")
}
end
}
}
|
ruby
|
{
"resource": ""
}
|
q25610
|
VCloudClient.Connection.add_vm_to_vapp
|
validation
|
def add_vm_to_vapp(vapp, vm, network_config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.RecomposeVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"name" => vapp[:name]) {
xml.SourcedItem {
xml.Source("href" => "#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}", "name" => vm[:vm_name])
xml.InstantiationParams {
xml.NetworkConnectionSection(
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1",
"type" => "application/vnd.vmware.vcloud.networkConnectionSection+xml",
"href" => "#{@api_url}/vAppTemplate/vm-#{vm[:template_id]}/networkConnectionSection/") {
xml['ovf'].Info "Network config for sourced item"
xml.PrimaryNetworkConnectionIndex "0"
xml.NetworkConnection("network" => network_config[:name]) {
xml.NetworkConnectionIndex "0"
xml.IsConnected "true"
xml.IpAddressAllocationMode(network_config[:ip_allocation_mode] || "POOL")
|
ruby
|
{
"resource": ""
}
|
q25611
|
VCloudClient.Connection.clone_vapp
|
validation
|
def clone_vapp(vdc_id, source_vapp_id, name, deploy="true", poweron="false", linked="false", delete_source="false")
params = {
"method" => :post,
"command" => "/vdc/#{vdc_id}/action/cloneVApp"
}
builder = Nokogiri::XML::Builder.new do |xml|
xml.CloneVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"name" => name,
"deploy"=> deploy,
"linkedClone"=> linked,
"powerOn"=> poweron
) {
xml.Source "href" => "#{@api_url}/vApp/vapp-#{source_vapp_id}"
xml.IsSourceDelete delete_source
|
ruby
|
{
"resource": ""
}
|
q25612
|
VCloudClient.Connection.set_vapp_network_config
|
validation
|
def set_vapp_network_config(vappid, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vapp-#{vappid}/networkConfigSection"
}
netconfig_response, headers = send_request(params)
picked_network = netconfig_response.css("NetworkConfig").select do |net|
net.attribute('networkName').text == network[:name]
end.first
raise WrongItemIDError, "Network named #{network[:name]} not found." unless picked_network
picked_network.css('FenceMode').first.content = config[:fence_mode] if config[:fence_mode]
picked_network.css('IsInherited').first.content = "true"
picked_network.css('RetainNetInfoAcrossDeployments').first.content = config[:retain_network] if config[:retain_network]
if config[:parent_network]
parent_network = picked_network.css('ParentNetwork').first
new_parent = false
unless parent_network
new_parent = true
ipscopes = picked_network.css('IpScopes').first
|
ruby
|
{
"resource": ""
}
|
q25613
|
VCloudClient.Connection.set_vapp_port_forwarding_rules
|
validation
|
def set_vapp_port_forwarding_rules(vappid, network_name, config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.NetworkConfigSection(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1") {
xml['ovf'].Info "Network configuration"
xml.NetworkConfig("networkName" => network_name) {
xml.Configuration {
xml.ParentNetwork("href" => "#{@api_url}/network/#{config[:parent_network]}")
xml.FenceMode(config[:fence_mode] || 'isolated')
xml.Features {
xml.NatService {
xml.IsEnabled "true"
xml.NatType "portForwarding"
xml.Policy(config[:nat_policy_type] || "allowTraffic")
config[:nat_rules].each do |nat_rule|
xml.NatRule {
xml.VmRule {
xml.ExternalPort nat_rule[:nat_external_port]
xml.VAppScopedVmId nat_rule[:vm_scoped_local_id]
|
ruby
|
{
"resource": ""
}
|
q25614
|
VCloudClient.Connection.get_vapp_port_forwarding_rules
|
validation
|
def get_vapp_port_forwarding_rules(vAppId)
params = {
'method' => :get,
'command' => "/vApp/vapp-#{vAppId}/networkConfigSection"
}
response, headers = send_request(params)
# FIXME: this will return nil if the vApp uses multiple vApp Networks
# with Edge devices in natRouted/portForwarding mode.
config = response.css('NetworkConfigSection/NetworkConfig/Configuration')
fenceMode = config.css('/FenceMode').text
natType = config.css('/Features/NatService/NatType').text
raise InvalidStateError, "Invalid request because FenceMode must be set to natRouted." unless fenceMode == "natRouted"
raise InvalidStateError, "Invalid request because NatType must be set to portForwarding." unless natType == "portForwarding"
nat_rules = {}
config.css('/Features/NatService/NatRule').each do |rule|
# portforwarding rules information
ruleId = rule.css('Id').text
|
ruby
|
{
"resource": ""
}
|
q25615
|
VCloudClient.Connection.merge_network_config
|
validation
|
def merge_network_config(vapp_networks, new_network, config)
net_configuration = new_network.css('Configuration').first
fence_mode = new_network.css('FenceMode').first
fence_mode.content = config[:fence_mode] || 'isolated'
network_features = Nokogiri::XML::Node.new "Features", net_configuration
firewall_service = Nokogiri::XML::Node.new "FirewallService", network_features
firewall_enabled = Nokogiri::XML::Node.new "IsEnabled", firewall_service
firewall_enabled.content = config[:firewall_enabled] || "false"
firewall_service.add_child(firewall_enabled)
network_features.add_child(firewall_service)
net_configuration.add_child(network_features)
if config[:parent_network]
# At this stage, set itself as parent network
parent_network = Nokogiri::XML::Node.new
|
ruby
|
{
"resource": ""
}
|
q25616
|
VCloudClient.Connection.add_network_to_vapp
|
validation
|
def add_network_to_vapp(vAppId, network_section)
params = {
'method' => :put,
'command' => "/vApp/vapp-#{vAppId}/networkConfigSection"
}
|
ruby
|
{
"resource": ""
}
|
q25617
|
VCloudClient.Connection.create_fake_network_node
|
validation
|
def create_fake_network_node(vapp_networks, network_name)
parent_section = vapp_networks.css('NetworkConfigSection').first
new_network = Nokogiri::XML::Node.new "NetworkConfig", parent_section
new_network['networkName'] = network_name
|
ruby
|
{
"resource": ""
}
|
q25618
|
VCloudClient.Connection.create_internal_network_node
|
validation
|
def create_internal_network_node(network_config)
builder = Nokogiri::XML::Builder.new do |xml|
xml.Configuration {
xml.IpScopes {
xml.IpScope {
xml.IsInherited(network_config[:is_inherited] || "false")
xml.Gateway network_config[:gateway]
xml.Netmask network_config[:netmask]
xml.Dns1 network_config[:dns1] if network_config[:dns1]
xml.Dns2 network_config[:dns2] if network_config[:dns2]
xml.DnsSuffix network_config[:dns_suffix] if network_config[:dns_suffix]
xml.IsEnabled(network_config[:is_enabled] || true)
xml.IpRanges
|
ruby
|
{
"resource": ""
}
|
q25619
|
VCloudClient.Connection.generate_network_section
|
validation
|
def generate_network_section(vAppId, network, config, type)
params = {
'method' => :get,
'command' => "/vApp/vapp-#{vAppId}/networkConfigSection"
}
vapp_networks, headers = send_request(params)
create_fake_network_node(vapp_networks, network[:name])
|
ruby
|
{
"resource": ""
}
|
q25620
|
VCloudClient.Connection.login
|
validation
|
def login
params = {
'method' => :post,
'command' => '/sessions'
}
response, headers = send_request(params)
if !headers.has_key?(:x_vcloud_authorization)
raise "Unable to authenticate: missing x_vcloud_authorization header"
end
|
ruby
|
{
"resource": ""
}
|
q25621
|
VCloudClient.Connection.get_task
|
validation
|
def get_task(taskid)
params = {
'method' => :get,
'command' => "/task/#{taskid}"
}
response, headers = send_request(params)
|
ruby
|
{
"resource": ""
}
|
q25622
|
VCloudClient.Connection.wait_task_completion
|
validation
|
def wait_task_completion(taskid)
errormsg = nil
task = {}
loop do
task = get_task(taskid)
break if task[:status] != 'running'
sleep 1
end
if task[:status] == 'error'
errormsg = task[:response].css("Error").first
|
ruby
|
{
"resource": ""
}
|
q25623
|
VCloudClient.Connection.send_request
|
validation
|
def send_request(params, payload=nil, content_type=nil)
req_params = setup_request(params, payload, content_type)
handled_request(req_params) do
request = RestClient::Request.new(req_params)
response = request.execute
if ![200, 201, 202, 204].include?(response.code)
@logger.warn "Warning: unattended code #{response.code}"
|
ruby
|
{
"resource": ""
}
|
q25624
|
VCloudClient.Connection.upload_file
|
validation
|
def upload_file(uploadURL, uploadFile, progressUrl, config={})
raise ::IOError, "#{uploadFile} not found." unless File.exists?(uploadFile)
# Set chunksize to 10M if not specified otherwise
chunkSize = (config[:chunksize] || 10485760)
# Set progress bar to default format if not specified otherwise
progressBarFormat = (config[:progressbar_format] || "%e <%B> %p%% %t")
# Set progress bar length to 120 if not specified otherwise
progressBarLength = (config[:progressbar_length] || 120)
# Open our file for upload
uploadFileHandle = File.new(uploadFile, "rb" )
fileName = File.basename(uploadFileHandle)
progressBarTitle = "Uploading: " + uploadFile.to_s
# Create a progressbar object if progress bar is enabled
if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize
progressbar = ProgressBar.create(
:title => progressBarTitle,
:starting_at => 0,
:total => uploadFileHandle.size.to_i,
:length => progressBarLength,
:format => progressBarFormat
)
else
@logger.info progressBarTitle
end
# Create a new HTTP client
clnt = HTTPClient.new
# Disable SSL cert verification
clnt.ssl_config.verify_mode=(OpenSSL::SSL::VERIFY_NONE)
# Suppress SSL depth message
clnt.ssl_config.verify_callback=proc{ |ok, ctx|; true };
# Perform ranged upload until the file reaches its end
until uploadFileHandle.eof?
# Create ranges for this chunk upload
rangeStart = uploadFileHandle.pos
rangeStop = uploadFileHandle.pos.to_i + chunkSize
# Read current chunk
fileContent = uploadFileHandle.read(chunkSize)
# If statement to handle last chunk transfer if is > than filesize
if rangeStop.to_i > uploadFileHandle.size.to_i
contentRange = "bytes #{rangeStart.to_s}-#{uploadFileHandle.size.to_s}/#{uploadFileHandle.size.to_s}"
rangeLen = uploadFileHandle.size.to_i - rangeStart.to_i
else
contentRange = "bytes #{rangeStart.to_s}-#{rangeStop.to_s}/#{uploadFileHandle.size.to_s}"
rangeLen = rangeStop.to_i - rangeStart.to_i
end
# Build headers
extheader = {
|
ruby
|
{
"resource": ""
}
|
q25625
|
VCloudClient.Connection.get_catalog
|
validation
|
def get_catalog(catalogId)
params = {
'method' => :get,
'command' => "/catalog/#{catalogId}"
}
response, headers = send_request(params)
description = response.css("Description").first
description = description.text unless description.nil?
items = {}
|
ruby
|
{
"resource": ""
}
|
q25626
|
VCloudClient.Connection.get_vm_disk_info
|
validation
|
def get_vm_disk_info(vmid)
response, headers = __get_disk_info(vmid)
disks = []
response.css("Item").each do |entry|
# Pick only entries with node "HostResource"
resource = entry.css("rasd|HostResource").first
next unless resource
name = entry.css("rasd|ElementName").first
name = name.text unless name.nil?
|
ruby
|
{
"resource": ""
}
|
q25627
|
VCloudClient.Connection.set_vm_disk_info
|
validation
|
def set_vm_disk_info(vmid, disk_info={})
get_response, headers = __get_disk_info(vmid)
if disk_info[:add]
data = add_disk(get_response, disk_info)
else
data = edit_disk(get_response, disk_info)
end
params = {
'method' => :put,
|
ruby
|
{
"resource": ""
}
|
q25628
|
VCloudClient.Connection.set_vm_cpus
|
validation
|
def set_vm_cpus(vmid, cpu_number)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/cpu"
}
get_response, headers = send_request(params)
# Change attributes from the previous invocation
|
ruby
|
{
"resource": ""
}
|
q25629
|
VCloudClient.Connection.set_vm_ram
|
validation
|
def set_vm_ram(vmid, memory_size)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/memory"
}
get_response, headers = send_request(params)
# Change attributes from the previous invocation
|
ruby
|
{
"resource": ""
}
|
q25630
|
VCloudClient.Connection.edit_vm_network
|
validation
|
def edit_vm_network(vmId, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
if config[:primary_index]
node = netconfig_response.css('PrimaryNetworkConnectionIndex').first
node.content = config[:primary_index]
end
picked_network = netconfig_response.css("NetworkConnection").select do |net|
net.attribute('network').text == network[:name]
end.first
raise WrongItemIDError, "Network named #{network[:name]} not found." unless picked_network
if config[:ip_allocation_mode]
node = picked_network.css('IpAddressAllocationMode').first
node.content = config[:ip_allocation_mode]
end
if config[:network_index]
node = picked_network.css('NetworkConnectionIndex').first
node.content = config[:network_index]
|
ruby
|
{
"resource": ""
}
|
q25631
|
VCloudClient.Connection.add_vm_network
|
validation
|
def add_vm_network(vmId, network, config={})
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
parent_section = netconfig_response.css('NetworkConnectionSection').first
# For some reasons these elements must be removed
netconfig_response.css("Link").each {|n| n.remove}
# Delete placeholder network if present (since vcloud 5.5 has been removed)
none_network = netconfig_response.css('NetworkConnection').find{|n| n.attribute('network').text == 'none'}
none_network.remove if none_network
networks_count = netconfig_response.css('NetworkConnection').count
primary_index_node = netconfig_response.css('PrimaryNetworkConnectionIndex').first
unless primary_index_node
primary_index_node = Nokogiri::XML::Node.new "PrimaryNetworkConnectionIndex", parent_section
parent_section.add_child(primary_index_node)
|
ruby
|
{
"resource": ""
}
|
q25632
|
VCloudClient.Connection.delete_vm_network
|
validation
|
def delete_vm_network(vmId, network)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}/networkConnectionSection"
}
netconfig_response, headers = send_request(params)
picked_network = netconfig_response.css("NetworkConnection").select do |net|
net.attribute('network').text == network[:name]
|
ruby
|
{
"resource": ""
}
|
q25633
|
VCloudClient.Connection.set_vm_guest_customization
|
validation
|
def set_vm_guest_customization(vmid, computer_name, config={})
builder = Nokogiri::XML::Builder.new do |xml|
xml.GuestCustomizationSection(
"xmlns" => "http://www.vmware.com/vcloud/v1.5",
"xmlns:ovf" => "http://schemas.dmtf.org/ovf/envelope/1") {
xml['ovf'].Info "VM Guest Customization configuration"
xml.Enabled config[:enabled] if config[:enabled]
xml.AdminPasswordEnabled config[:admin_passwd_enabled] if config[:admin_passwd_enabled]
|
ruby
|
{
"resource": ""
}
|
q25634
|
VCloudClient.Connection.get_vm
|
validation
|
def get_vm(vmId)
params = {
'method' => :get,
'command' => "/vApp/vm-#{vmId}"
}
response, headers = send_request(params)
vm_name = response.css('Vm').attribute("name")
vm_name = vm_name.text unless vm_name.nil?
status = convert_vapp_status(response.css('Vm').attribute("status").text)
os_desc = response.css('ovf|OperatingSystemSection ovf|Description').first.text
networks = {}
response.css('NetworkConnection').each do |network|
ip = network.css('IpAddress').first
ip = ip.text if ip
external_ip = network.css('ExternalIpAddress').first
external_ip = external_ip.text if external_ip
# Append NetworkConnectionIndex to network name to generate a unique hash key,
# otherwise different interfaces on the same network would use the same hash key
key = "#{network['network']}_#{network.css('NetworkConnectionIndex').first.text}"
networks[key] = {
:index => network.css('NetworkConnectionIndex').first.text,
:ip => ip,
:external_ip => external_ip,
:is_connected => network.css('IsConnected').first.text,
:mac_address => network.css('MACAddress').first.text,
:ip_allocation_mode => network.css('IpAddressAllocationMode').first.text
}
end
admin_password = response.css('GuestCustomizationSection AdminPassword').first
admin_password = admin_password.text if admin_password
guest_customizations = {
|
ruby
|
{
"resource": ""
}
|
q25635
|
VCloudClient.Connection.get_vm_by_name
|
validation
|
def get_vm_by_name(organization, vdcName, vAppName, vmName)
result = nil
get_vapp_by_name(organization, vdcName, vAppName)[:vms_hash].each
|
ruby
|
{
"resource": ""
}
|
q25636
|
VCloudClient.Connection.poweroff_vm
|
validation
|
def poweroff_vm(vmId)
builder = Nokogiri::XML::Builder.new do |xml|
xml.UndeployVAppParams(
"xmlns" => "http://www.vmware.com/vcloud/v1.5") {
xml.UndeployPowerAction 'powerOff'
}
end
params = {
'method' => :post,
'command' => "/vApp/vm-#{vmId}/action/undeploy"
|
ruby
|
{
"resource": ""
}
|
q25637
|
VCloudClient.Connection.acquire_ticket_vm
|
validation
|
def acquire_ticket_vm(vmId)
params = {
'method' => :post,
'command' => "/vApp/vm-#{vmId}/screen/action/acquireTicket"
}
response, headers = send_request(params)
screen_ticket = response.css("ScreenTicket").text
result
|
ruby
|
{
"resource": ""
}
|
q25638
|
VCloudClient.Connection.get_network
|
validation
|
def get_network(networkId)
response = get_base_network(networkId)
name = response.css('OrgVdcNetwork').attribute('name').text
description = response.css("Description").first
description = description.text unless description.nil?
gateway = response.css('Gateway')
gateway = gateway.text unless gateway.nil?
netmask = response.css('Netmask')
netmask = netmask.text unless netmask.nil?
fence_mode = response.css('FenceMode')
fence_mode = fence_mode.text unless fence_mode.nil?
start_address = response.css('StartAddress')
|
ruby
|
{
"resource": ""
}
|
q25639
|
VCloudClient.Connection.get_organizations
|
validation
|
def get_organizations
params = {
'method' => :get,
'command' => '/org'
}
response, headers = send_request(params)
orgs = response.css('OrgList Org')
results
|
ruby
|
{
"resource": ""
}
|
q25640
|
VCloudClient.Connection.get_tasks_list
|
validation
|
def get_tasks_list(id)
params = {
'method' => :get,
'command' => "/tasksList/#{id}"
}
response, headers = send_request(params)
tasks = []
response.css('Task').each do |task|
id = task['href'].gsub(/.*\/task\//, "")
operation = task['operationName']
status = task['status']
error = nil
error = task.css('Error').first['message'] if task['status'] == 'error'
start_time = task['startTime']
end_time = task['endTime']
user_canceled = task['cancelRequested'] == 'true'
tasks << {
|
ruby
|
{
"resource": ""
}
|
q25641
|
VCloudClient.Connection.get_vdc_id_by_name
|
validation
|
def get_vdc_id_by_name(organization, vdcName)
result = nil
organization[:vdcs].each do
|
ruby
|
{
"resource": ""
}
|
q25642
|
VCloudClient.Connection.get_vdc_by_name
|
validation
|
def get_vdc_by_name(organization, vdcName)
result = nil
organization[:vdcs].each do |vdc|
if vdc[0].downcase == vdcName.downcase
|
ruby
|
{
"resource": ""
}
|
q25643
|
DataProvider.Container.add!
|
validation
|
def add!(container)
### add container's providers ###
# internally providers are added in reverse order (last one first)
# so at runtime you it's easy and fast to grab the latest provider
# so when adding now, we have to reverse the providers to get them in the original order
container.providers.reverse.each do |definition|
add_provider(*definition)
end
|
ruby
|
{
"resource": ""
}
|
q25644
|
DataProvider.Container.get_provider
|
validation
|
def get_provider(id, opts = {})
# get all matching providers
matching_provider_args = providers.find_all{|args| args.first == id}
# sort providers on priority, form high to low
matching_provider_args.sort! do |args_a, args_b|
# we want to sort from high priority to low, but providers with the same priority level
# should stay in the same order because among those, the last one added has the highest priority
# (last added means first in the array, since they are pushed into the beginning of the array)
|
ruby
|
{
"resource": ""
}
|
q25645
|
Rack::Tidy.Cleaner.call!
|
validation
|
def call!(env)
@env = env.dup
status, @headers, response = @app.call(@env)
if should_clean?
@headers.delete('Content-Length')
response = Rack::Response.new(
tidy_markup(response.respond_to?(:body) ? response.body : response),
status,
|
ruby
|
{
"resource": ""
}
|
q25646
|
Scribble.Registry.for
|
validation
|
def for *classes, &proc
classes.each { |receiver_class|
|
ruby
|
{
"resource": ""
}
|
q25647
|
Scribble.Registry.evaluate
|
validation
|
def evaluate name, receiver, args, call = nil, context = nil
matcher = Support::Matcher.new self, name, receiver, args
|
ruby
|
{
"resource": ""
}
|
q25648
|
Bundleup.Console.progress
|
validation
|
def progress(message, &block)
spinner = %w[/ - \\ |].cycle
print "\e[90m#{message}... \e[0m"
result = observing_thread(block, 0.5, 0.1) do
print "\r\e[90m#{message}... #{spinner.next} \e[0m"
|
ruby
|
{
"resource": ""
}
|
q25649
|
Bundleup.Console.tableize
|
validation
|
def tableize(rows, &block)
rows = rows.map(&block) if block
widths = max_length_of_each_column(rows)
|
ruby
|
{
"resource": ""
}
|
q25650
|
Bundleup.Console.observing_thread
|
validation
|
def observing_thread(callable, initial_wait, periodic_wait)
thread = Thread.new(&callable)
wait_for_exit(thread, initial_wait)
loop do
break
|
ruby
|
{
"resource": ""
}
|
q25651
|
Rescuetime.Collection.all
|
validation
|
def all
requester = Rescuetime::Requester
|
ruby
|
{
"resource": ""
}
|
q25652
|
Rescuetime.Collection.format
|
validation
|
def format(format)
# Guard: fail if the passed format isn't on the whitelist
format = format.to_s
formatters.all.include?(format)
|
ruby
|
{
"resource": ""
}
|
q25653
|
Rescuetime.Collection.parse_response
|
validation
|
def parse_response(body)
report = CSV.new(body,
headers: true,
header_converters: :symbol,
converters: :all)
format
|
ruby
|
{
"resource": ""
}
|
q25654
|
Rescuetime.ReportFormatters.find
|
validation
|
def find(name)
formatter = formatters.find do |f|
standardize(f.name) ==
|
ruby
|
{
"resource": ""
}
|
q25655
|
Rescuetime.QueryBuildable.order_by
|
validation
|
def order_by(order, interval: nil)
# set order and intervals as symbols
order = order.to_s
interval = interval ? interval.to_s : nil
# guards against invalid order or interval
unless valid_order? order
raise Errors::InvalidQueryError, "#{order} is not a valid order"
end
unless valid_interval? interval
|
ruby
|
{
"resource": ""
}
|
q25656
|
Rescuetime.QueryBuildable.where
|
validation
|
def where(name: nil, document: nil)
# Stand-in for required keyword arguments
name || raise(ArgumentError, 'missing keyword: name')
|
ruby
|
{
"resource": ""
}
|
q25657
|
Rescuetime.QueryBuildable.add_to_query
|
validation
|
def add_to_query(**terms)
if is_a? Rescuetime::Collection
self << terms
self
else
|
ruby
|
{
"resource": ""
}
|
q25658
|
Rescuetime.Client.valid_credentials?
|
validation
|
def valid_credentials?
return false unless api_key?
!activities.all.nil?
|
ruby
|
{
"resource": ""
}
|
q25659
|
Rescuetime.Formatters.load_formatter_files
|
validation
|
def load_formatter_files(local_path: LOCAL_FORMATTER_PATH)
# require all formatters, local and configured
paths =
|
ruby
|
{
"resource": ""
}
|
q25660
|
NibblerMethods.InstanceMethods.parse
|
validation
|
def parse
self.class.rules.each do |target, (selector, delegate, plural)|
if plural
send(target).concat @doc.search(selector).map { |i| parse_result(i, delegate) }
else
|
ruby
|
{
"resource": ""
}
|
q25661
|
NibblerMethods.InstanceMethods.to_hash
|
validation
|
def to_hash
converter = lambda { |obj| obj.respond_to?(:to_hash) ? obj.to_hash : obj }
self.class.rules.keys.inject({}) do |hash, name|
value = send(name)
|
ruby
|
{
"resource": ""
}
|
q25662
|
NibblerMethods.InstanceMethods.parse_result
|
validation
|
def parse_result(node, delegate)
if delegate
method = delegate.is_a?(Proc) ? delegate : delegate.method(delegate.respond_to?(:call) ?
|
ruby
|
{
"resource": ""
}
|
q25663
|
Tweetburner.Scraper.get_document
|
validation
|
def get_document(url)
URI === url ? Nokogiri::HTML::Document.parse(open(url), url.to_s,
|
ruby
|
{
"resource": ""
}
|
q25664
|
MMS2R.MMS2R::Media.subject
|
validation
|
def subject
unless @subject
subject = mail.subject.strip rescue ""
ignores = config['ignore']['text/plain']
if ignores && ignores.detect{|s| s == subject}
@subject = ""
else
|
ruby
|
{
"resource": ""
}
|
q25665
|
MMS2R.MMS2R::Media.ignore_media?
|
validation
|
def ignore_media?(type, part)
ignores = config['ignore'][type] || []
ignore = ignores.detect{ |test| filename?(part) == test}
ignore ||= ignores.detect{ |test| filename?(part) =~ test if test.is_a?(Regexp) }
ignore ||= ignores.detect{ |test| part.body.decoded.strip
|
ruby
|
{
"resource": ""
}
|
q25666
|
MMS2R.MMS2R::Media.process_media
|
validation
|
def process_media(part)
# Mail body auto-magically decodes quoted
# printable for text/html type.
file = temp_file(part)
if part.part_type? =~ /^text\// ||
part.part_type? == 'application/smil'
type, content = transform_text_part(part)
else
|
ruby
|
{
"resource": ""
}
|
q25667
|
MMS2R.MMS2R::Media.process_part
|
validation
|
def process_part(part)
return if ignore_media?(part.part_type?, part)
|
ruby
|
{
"resource": ""
}
|
q25668
|
MMS2R.MMS2R::Media.transform_text
|
validation
|
def transform_text(type, text)
return type, text if !config['transform'] || !(transforms = config['transform'][type])
if RUBY_VERSION < "1.9"
require 'iconv'
ic = Iconv.new('UTF-8', 'ISO-8859-1')
text = ic.iconv(text)
text << ic.iconv(nil)
ic.close
|
ruby
|
{
"resource": ""
}
|
q25669
|
MMS2R.MMS2R::Media.transform_text_part
|
validation
|
def transform_text_part(part)
type = part.part_type?
text = part.body.decoded.strip
|
ruby
|
{
"resource": ""
}
|
q25670
|
MMS2R.MMS2R::Media.temp_file
|
validation
|
def temp_file(part)
file_name = filename?(part)
|
ruby
|
{
"resource": ""
}
|
q25671
|
MMS2R.MMS2R::Media.add_file
|
validation
|
def add_file(type, file)
media[type]
|
ruby
|
{
"resource": ""
}
|
q25672
|
MMS2R.MMS2R::Media.msg_tmp_dir
|
validation
|
def msg_tmp_dir
@dir_count += 1
dir = File.expand_path(File.join(@media_dir, "#{@dir_count}"))
|
ruby
|
{
"resource": ""
}
|
q25673
|
MMS2R.MMS2R::Media.filename?
|
validation
|
def filename?(part)
name = part.filename
if (name.nil? || name.empty?)
if part.content_id && (matched = /^<(.+)>$/.match(part.content_id))
name = matched[1]
else
name = "#{Time.now.to_f}.#{self.default_ext(part.part_type?)}"
end
end
# FIXME FWIW, janky look for dot extension 1 to 4 chars long
|
ruby
|
{
"resource": ""
}
|
q25674
|
MMS2R.MMS2R::Media.type_from_filename
|
validation
|
def type_from_filename(filename)
ext = filename.split('.').last
ent = MMS2R::EXT.detect{|k,v|
|
ruby
|
{
"resource": ""
}
|
q25675
|
ArJdbc.AS400.prefetch_primary_key?
|
validation
|
def prefetch_primary_key?(table_name = nil)
return true if table_name.nil?
table_name = table_name.to_s
|
ruby
|
{
"resource": ""
}
|
q25676
|
ArJdbc.AS400.execute_and_auto_confirm
|
validation
|
def execute_and_auto_confirm(sql, name = nil)
begin
execute_system_command('CHGJOB INQMSGRPY(*SYSRPYL)')
execute_system_command("ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')")
rescue Exception => e
raise unauthorized_error_message("CHGJOB INQMSGRPY(*SYSRPYL) and ADDRPYLE SEQNBR(9876) MSGID(CPA32B2) RPY('I')", e)
end
begin
result = execute(sql, name)
rescue Exception
raise
else
# Return if all work fine
|
ruby
|
{
"resource": ""
}
|
q25677
|
TravisCustomDeploy.Deployment.get_transfer
|
validation
|
def get_transfer(type)
type = type[0].upcase + type[1..-1]
try_require(type)
|
ruby
|
{
"resource": ""
}
|
q25678
|
Smurf.Javascript.peek
|
validation
|
def peek(aheadCount=1)
history = []
aheadCount.times { history << @input.getc }
|
ruby
|
{
"resource": ""
}
|
q25679
|
Motion.Capture.captureOutput
|
validation
|
def captureOutput(output, didFinishProcessingPhoto: photo, error: error)
if error
error_callback.call(error)
else
|
ruby
|
{
"resource": ""
}
|
q25680
|
Motion.Capture.captureOutput
|
validation
|
def captureOutput(output, didFinishProcessingPhotoSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer, resolvedSettings: resolved_settings, bracketSettings: bracket_settings, error: error)
if error
error_callback.call(error)
else
jpeg_data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(
|
ruby
|
{
"resource": ""
}
|
q25681
|
Motion.Capture.save_to_assets_library
|
validation
|
def save_to_assets_library(jpeg_data, &block)
assets_library.writeImageDataToSavedPhotosAlbum(jpeg_data, metadata: nil, completionBlock: -> (asset_url, error) {
|
ruby
|
{
"resource": ""
}
|
q25682
|
Motion.Capture.save_to_photo_library
|
validation
|
def save_to_photo_library(jpeg_data, &block)
photo_library.performChanges(-> {
image = UIImage.imageWithData(jpeg_data)
PHAssetChangeRequest.creationRequestForAssetFromImage(image)
}, completionHandler: -> (success, error) {
if error
|
ruby
|
{
"resource": ""
}
|
q25683
|
Motion.Capture.update_video_orientation!
|
validation
|
def update_video_orientation!
photo_output.connectionWithMediaType(AVMediaTypeVideo).tap do |connection|
device_orientation = UIDevice.currentDevice.orientation
video_orientation =
|
ruby
|
{
"resource": ""
}
|
q25684
|
OnedClusterer.Ckmeans.select_levels
|
validation
|
def select_levels(data, backtrack, kmin, kmax)
return kmin if kmin == kmax
method = :normal # "uniform" or "normal"
kopt = kmin
base = 1 # The position of first element in x: 1 or 0.
n = data.size - base
max_bic = 0.0
for k in kmin..kmax
cluster_sizes = []
kbacktrack = backtrack[0..k]
backtrack(kbacktrack) do |cluster, left, right|
cluster_sizes[cluster] = right - left + 1
end
index_left = base
index_right = 0
likelihood = 0
bin_left, bin_right = 0
for i in 0..(k-1)
points_in_bin = cluster_sizes[i + base]
index_right = index_left + points_in_bin - 1
if data[index_left] < data[index_right]
bin_left = data[index_left]
bin_right = data[index_right]
elsif data[index_left] == data[index_right]
bin_left = index_left == base ? data[base] : (data[index_left-1] + data[index_left]) / 2
bin_right = index_right < n-1+base ? (data[index_right] + data[index_right+1]) / 2 : data[n-1+base]
else
raise "ERROR: binLeft > binRight"
end
bin_width = bin_right - bin_left
if method == :uniform
likelihood += points_in_bin * Math.log(points_in_bin / bin_width / n)
else
mean = 0.0
variance = 0.0
for j in index_left..index_right
mean += data[j]
variance += data[j] ** 2
end
mean /= points_in_bin
variance = (variance - points_in_bin * mean ** 2) / (points_in_bin - 1) if points_in_bin > 1
if variance > 0
|
ruby
|
{
"resource": ""
}
|
q25685
|
SourceRoute.ParamsConfigParser.full_feature
|
validation
|
def full_feature(value=true)
return unless value
@config.formulize
@config.event = (@config.event + [:call, :return]).uniq
@config.import_return_to_call = true
@config.show_additional_attrs = [:path, :lineno]
# JSON serialize trigger many problems when handle complicated object(in rails?)
# a Back Door to open more data. but be care
|
ruby
|
{
"resource": ""
}
|
q25686
|
Pancake.Middleware.stack
|
validation
|
def stack(name = nil, opts = {})
if self::StackMiddleware._mwares[name] && mw = self::StackMiddleware._mwares[name]
unless mw.stack ==
|
ruby
|
{
"resource": ""
}
|
q25687
|
Pancake.Middleware.use
|
validation
|
def use(middleware, *_args, &block)
|
ruby
|
{
"resource": ""
}
|
q25688
|
Metadata::Ingest::Translators.FormToAttributes.attribute_lookup
|
validation
|
def attribute_lookup(assoc)
group_data = @map[assoc.group.to_sym]
|
ruby
|
{
"resource": ""
}
|
q25689
|
Metadata::Ingest::Translators.FormToAttributes.translate_association
|
validation
|
def translate_association(assoc)
attribute = attribute_lookup(assoc)
return unless attribute
# Make sure we properly handle destroyed values by forcing them to an
# empty association. We keep their state up to this point because the
# caller may be using the prior value for something.
if
|
ruby
|
{
"resource": ""
}
|
q25690
|
Metadata::Ingest::Translators.FormToAttributes.add_association_to_attribute_map
|
validation
|
def add_association_to_attribute_map(attribute, assoc)
current = @attributes[attribute]
# If there's already a value, we can safely ignore the empty association
return if current && assoc.blank?
case current
when nil
|
ruby
|
{
"resource": ""
}
|
q25691
|
Metadata::Ingest::Translators.FormToAttributes.store_associations_on_object
|
validation
|
def store_associations_on_object(object, attribute, associations)
values = associations.collect do |assoc|
assoc.internal.blank? ? assoc.value : assoc.internal
end
# Clean up values
values.compact!
case values.length
|
ruby
|
{
"resource": ""
}
|
q25692
|
Metadata::Ingest::Translators.AttributesToForm.setup_form
|
validation
|
def setup_form(group, type, attr_definition)
attr_trans = single_attribute_translator.new(
source: @source,
form: @form,
group: group,
type: type,
|
ruby
|
{
"resource": ""
}
|
q25693
|
Pancake.Router.mount
|
validation
|
def mount(mounted_app, path, options = {})
mounted_app = MountedApplication.new(mounted_app,
|
ruby
|
{
"resource": ""
}
|
q25694
|
SourceRoute.GenerateResult.assign_tp_self_caches
|
validation
|
def assign_tp_self_caches(tp_ins)
unless tp_self_caches.find { |tp_cache| tp_cache.object_id.equal? tp_ins.self.object_id }
|
ruby
|
{
"resource": ""
}
|
q25695
|
Pancake.Logger.set_log
|
validation
|
def set_log(stream = Pancake.configuration.log_stream,
log_level = Pancake.configuration.log_level,
delimiter = Pancake.configuration.log_delimiter,
auto_flush = Pancake.configuration.log_auto_flush)
@buffer = []
@delimiter = delimiter
@auto_flush = auto_flush
if Levels[log_level]
@level
|
ruby
|
{
"resource": ""
}
|
q25696
|
Pancake.Paths.dirs_for
|
validation
|
def dirs_for(name, opts = {})
if _load_paths[name].blank?
[]
else
result = []
invert = !!opts[:invert]
load_paths = invert ? _load_paths[name].reverse : _load_paths[name]
roots.each do |root|
load_paths.each do |paths, glob|
|
ruby
|
{
"resource": ""
}
|
q25697
|
Pancake.Paths.paths_for
|
validation
|
def paths_for(name, opts = {})
result = []
dirs_and_glob_for(name, opts).each do |path, glob|
next if glob.nil?
paths = Dir[File.join(path, glob)]
paths = paths.reverse if opts[:invert]
|
ruby
|
{
"resource": ""
}
|
q25698
|
Pancake.Paths.unique_paths_for
|
validation
|
def unique_paths_for(name, opts = {})
tally = {}
output = []
paths_for(name, opts).reverse.each do |ary|
tally[ary[1]] ||= ary[0]
|
ruby
|
{
"resource": ""
}
|
q25699
|
Metadata::Ingest::Translators.SingleAttributeTranslator.build_association
|
validation
|
def build_association(value)
association = @form.create_association(
group: @group.to_s,
type: @type.to_s,
value: value
)
# Since the associations are fake, we
|
ruby
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.