_id
stringlengths
2
6
title
stringlengths
9
130
partition
stringclasses
3 values
text
stringlengths
66
10.5k
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: 0x01, # HID Get_Report wValue: (3 << 8) | report_number, wIndex: interface, dataIn: buffer_size ) end end
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) else usb_device.open { |handle| handle.string_descriptor_ascii(index) } end end HIDAPI.debug("read string at index #{index} for device #{path}: #{data.inspect}") data rescue =>e HIDAPI.debug("failed to read string at index #{index} for device #{path}: #{e.inspect}") on_failure || '' end end
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 in other audit (other_audit.change_log.keys - self.change_log.keys).each do |k| d[k] = [other_audit.change_log[k], nil] end # .. finally for keys present in both, but with different values self.change_log.keys.each do |k| if self.change_log[k] != other_audit.change_log[k] d[k] = [other_audit.change_log[k], self.change_log[k]] end end end end
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? audit.delta(older_audit).sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.collect do |k, v| next if k.to_s == 'created_at' || k.to_s == 'updated_at' "\n" + audited_model.class.human_attribute_name(k) + ":" + content_tag(:span, v.last, :class => 'current') + content_tag(:span, v.first, :class => 'previous') end else audit.change_log.sort{|x,y| audited_model.class.human_attribute_name(x.first) <=> audited_model.class.human_attribute_name(y.first)}.reject{|k, v| v.blank?}.collect {|k, v| "\n#{audited_model.class.human_attribute_name(k)}: #{v}"} end raw changes.join end end end raw res end
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 options[:input] if options[:output] Array(options[:output]).map do |output_dir| File.join(output_dir, input_file_dir, file_name) end else if input_file_dir == '' [file_name] else [File.join(input_file_dir, file_name)] end end end
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('.') else [base_name, extensions].flatten.join('.') end else [base_name, extensions, options[:default_ext]].flatten.compact.join('.') end end
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| if vapp[0].downcase == vAppName.downcase result = get_vapp(vapp[1]) end end result end
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" } response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.undeployVAppParams+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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" } response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.instantiateVAppTemplateParams+xml") vapp_id = headers[:location].gsub(/.*\/vApp\/vapp\-/, "") task = response.css("VApp Task[operationName='vdcInstantiateVapp']").first task_id = task["href"].gsub(/.*\/task\//, "") { :vapp_id => vapp_id, :task_id => task_id } end
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 } } } } } vm_list.each do |vm_name, vm_id| xml.SourcedItem { xml.Source("href" => "#{@api_url}/vAppTemplate/vm-#{vm_id}", "name" => 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_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") } } } xml.NetworkAssignment("containerNetwork" => network_config[:name], "innerNetwork" => network_config[:name]) } end xml.AllEULAsAccepted "true" } end params = { "method" => :post, "command" => "/vdc/#{vdc}/action/composeVApp" } response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.composeVAppParams+xml") vapp_id = headers[:location].gsub(/.*\/vApp\/vapp\-/, "") task = response.css("VApp Task[operationName='vdcComposeVapp']").first task_id = task["href"].gsub(/.*\/task\//, "") { :vapp_id => vapp_id, :task_id => task_id } 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") } } } xml.NetworkAssignment("containerNetwork" => network_config[:name], "innerNetwork" => network_config[:name]) } xml.AllEULAsAccepted "true" } end params = { "method" => :post, "command" => "/vApp/vapp-#{vapp[:id]}/action/recomposeVApp" } response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.recomposeVAppParams+xml") task = response.css("Task[operationName='vdcRecomposeVapp']").first task_id = task["href"].gsub(/.*\/task\//, "") task_id end
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 } end response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.cloneVAppParams+xml") vapp_id = headers[:location].gsub(/.*\/vApp\/vapp\-/, "") task = response.css("VApp Task[operationName='vdcCopyVapp']").first task_id = task["href"].gsub(/.*\/task\//, "") {:vapp_id => vapp_id, :task_id => task_id} end
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 parent_network = Nokogiri::XML::Node.new "ParentNetwork", ipscopes.parent end parent_network["name"] = "#{config[:parent_network][:name]}" parent_network["id"] = "#{config[:parent_network][:id]}" parent_network["href"] = "#{@api_url}/admin/network/#{config[:parent_network][:id]}" ipscopes.add_next_sibling(parent_network) if new_parent end data = netconfig_response.to_xml params = { 'method' => :put, 'command' => "/vApp/vapp-#{vappid}/networkConfigSection" } response, headers = send_request(params, data, "application/vnd.vmware.vcloud.networkConfigSection+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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] xml.VmNicId(nat_rule[:nat_vmnic_id] || "0") xml.InternalPort nat_rule[:nat_internal_port] xml.Protocol(nat_rule[:nat_protocol] || "TCP") } } end } } } } } end params = { 'method' => :put, 'command' => "/vApp/vapp-#{vappid}/networkConfigSection" } response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.networkConfigSection+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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 vmRule = rule.css('VmRule') nat_rules[rule.css('Id').text] = { :ExternalIpAddress => vmRule.css('ExternalIpAddress').text, :ExternalPort => vmRule.css('ExternalPort').text, :VAppScopedVmId => vmRule.css('VAppScopedVmId').text, :VmNicId => vmRule.css('VmNicId').text, :InternalPort => vmRule.css('InternalPort').text, :Protocol => vmRule.css('Protocol').text } end nat_rules end
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 "ParentNetwork", net_configuration parent_network["href"] = "#{@api_url}/network/#{config[:parent_network][:id]}" parent_network["name"] = config[:parent_network][:name] parent_network["type"] = "application/vnd.vmware.vcloud.network+xml" new_network.css('IpScopes').first.add_next_sibling(parent_network) end vapp_networks.to_xml.gsub("<PLACEHOLDER/>", new_network.css('Configuration').to_xml) end
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" } response, headers = send_request(params, network_section, "application/vnd.vmware.vcloud.networkConfigSection+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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 placeholder = Nokogiri::XML::Node.new "PLACEHOLDER", new_network new_network.add_child placeholder parent_section.add_child(new_network) vapp_networks end
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 { xml.IpRange { xml.StartAddress network_config[:start_address] xml.EndAddress network_config[:end_address] } } } } xml.FenceMode 'isolated' xml.RetainNetInfoAcrossDeployments(network_config[:retain_info] || false) } end builder.doc end
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]) if type.to_sym == :internal # Create a network configuration based on the config new_network = create_internal_network_node(config) else # Retrieve the requested network and prepare it for customization new_network = get_base_network(network[:id]) end merge_network_config(vapp_networks, new_network, config) end
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 extensibility_link = response.css("Link[rel='down:extensibility']") @extensibility = extensibility_link.first['href'] unless extensibility_link.empty? @auth_key = headers[:x_vcloud_authorization] end
ruby
{ "resource": "" }
q25621
VCloudClient.Connection.get_task
validation
def get_task(taskid) params = { 'method' => :get, 'command' => "/task/#{taskid}" } response, headers = send_request(params) task = response.css('Task').first status = task['status'] start_time = task['startTime'] end_time = task['endTime'] { :status => status, :start_time => start_time, :end_time => end_time, :response => response } end
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 errormsg = "Error code #{errormsg['majorErrorCode']} - #{errormsg['message']}" end { :status => task[:status], :errormsg => errormsg, :start_time => task[:start_time], :end_time => task[:end_time] } end
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}" end parsed_response = Nokogiri::XML(response) @logger.debug "Send request result: #{parsed_response}" [parsed_response, response.headers] end end
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 = { 'x-vcloud-authorization' => @auth_key, 'Content-Range' => contentRange, 'Content-Length' => rangeLen.to_s } begin uploadRequest = "#{@host_url}#{uploadURL}" connection = clnt.request('PUT', uploadRequest, nil, fileContent, extheader) if config[:progressbar_enable] == true && uploadFileHandle.size.to_i > chunkSize params = { 'method' => :get, 'command' => progressUrl } response, headers = send_request(params) response.css("Files File [name='#{fileName}']").each do |file| progressbar.progress=file[:bytesTransferred].to_i end end rescue retryTime = (config[:retry_time] || 5) @logger.warn "Range #{contentRange} failed to upload, retrying the chunk in #{retryTime.to_s} seconds, to stop the action press CTRL+C." sleep retryTime.to_i retry end end uploadFileHandle.close end
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 = {} response.css("CatalogItem[type='application/vnd.vmware.vcloud.catalogItem+xml']").each do |item| items[item['name']] = item['href'].gsub(/.*\/catalogItem\//, "") end { :id => catalogId, :description => description, :items => items } end
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? capacity = resource.attribute("capacity").text disks << { :name => name, :capacity => "#{capacity} MB" } end disks end
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, 'command' => "/vApp/vm-#{vmid}/virtualHardwareSection/disks" } put_response, headers = send_request(params, data, "application/vnd.vmware.vcloud.rasdItemsList+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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 get_response.css("rasd|ElementName").first.content = "#{cpu_number} virtual CPU(s)" get_response.css("rasd|VirtualQuantity").first.content = cpu_number params['method'] = :put put_response, headers = send_request(params, get_response.to_xml, "application/vnd.vmware.vcloud.rasdItem+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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 get_response.css("rasd|ElementName").first.content = "#{memory_size} MB of memory" get_response.css("rasd|VirtualQuantity").first.content = memory_size params['method'] = :put put_response, headers = send_request(params, get_response.to_xml, "application/vnd.vmware.vcloud.rasdItem+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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] end if config[:is_connected] node = picked_network.css('IsConnected').first node.content = config[:is_connected] end if config[:ip] node = picked_network.css('IpAddress').first node.content = config[:ip] end params = { 'method' => :put, 'command' => "/vApp/vm-#{vmId}/networkConnectionSection" } response, headers = send_request(params, netconfig_response.to_xml, "application/vnd.vmware.vcloud.networkConnectionSection+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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) end primary_index_node.content = config[:primary_index] || 0 new_network = Nokogiri::XML::Node.new "NetworkConnection", parent_section new_network["network"] = network[:name] new_network["needsCustomization"] = true idx_node = Nokogiri::XML::Node.new "NetworkConnectionIndex", new_network idx_node.content = config[:network_index] || networks_count new_network.add_child(idx_node) if config[:ip] ip_node = Nokogiri::XML::Node.new "IpAddress", new_network ip_node.content = config[:ip] new_network.add_child(ip_node) end is_connected_node = Nokogiri::XML::Node.new "IsConnected", new_network is_connected_node.content = config[:is_connected] || true new_network.add_child(is_connected_node) allocation_node = Nokogiri::XML::Node.new "IpAddressAllocationMode", new_network allocation_node.content = config[:ip_allocation_mode] || "POOL" new_network.add_child(allocation_node) parent_section.add_child(new_network) params = { 'method' => :put, 'command' => "/vApp/vm-#{vmId}/networkConnectionSection" } put_response, headers = send_request(params, netconfig_response.to_xml, "application/vnd.vmware.vcloud.networkConnectionSection+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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] end.first raise WrongItemIDError, "Network #{network[:name]} not found on this VM." unless picked_network picked_network.remove params = { 'method' => :put, 'command' => "/vApp/vm-#{vmId}/networkConnectionSection" } put_response, headers = send_request(params, netconfig_response.to_xml, "application/vnd.vmware.vcloud.networkConnectionSection+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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] xml.AdminPassword config[:admin_passwd] if config[:admin_passwd] xml.CustomizationScript config[:customization_script] if config[:customization_script] xml.ComputerName computer_name } end params = { 'method' => :put, 'command' => "/vApp/vm-#{vmid}/guestCustomizationSection" } response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.guestCustomizationSection+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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 = { :enabled => response.css('GuestCustomizationSection Enabled').first.text, :admin_passwd_enabled => response.css('GuestCustomizationSection AdminPasswordEnabled').first.text, :admin_passwd_auto => response.css('GuestCustomizationSection AdminPasswordAuto').first.text, :admin_passwd => admin_password, :reset_passwd_required => response.css('GuestCustomizationSection ResetPasswordRequired').first.text, :computer_name => response.css('GuestCustomizationSection ComputerName').first.text } { :id => vmId, :vm_name => vm_name, :os_desc => os_desc, :networks => networks, :guest_customizations => guest_customizations, :status => status } end
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 do |key, values| if key.downcase == vmName.downcase result = get_vm(values[:id]) end end result end
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" } response, headers = send_request(params, builder.to_xml, "application/vnd.vmware.vcloud.undeployVAppParams+xml") task_id = headers[:location].gsub(/.*\/task\//, "") task_id end
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 = {} if screen_ticket =~ /mks:\/\/([^\/]*)\/([^\?]*)\?ticket=(.*)/ result = { host: $1, moid: $2, token: $3 } result[:token] = URI.unescape result[:token] end result end
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') start_address = start_address.text unless start_address.nil? end_address = response.css('EndAddress') end_address = end_address.text unless end_address.nil? { :id => networkId, :name => name, :description => description, :gateway => gateway, :netmask => netmask, :fence_mode => fence_mode, :start_address => start_address, :end_address => end_address } end
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 = {} orgs.each do |org| results[org['name']] = org['href'].gsub(/.*\/org\//, "") end results end
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 << { :id => id, :operation => operation, :status => status, :error => error, :start_time => start_time, :end_time => end_time, :user_canceled => user_canceled } end tasks end
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 |vdc| if vdc[0].downcase == vdcName.downcase result = vdc[1] end end result end
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 result = get_vdc(vdc[1]) end end result end
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 ### add container's provides (simple providers) ### self.provides(container.provides) ### fallback provider ### @fallback_provider = container.fallback_provider.block if container.fallback_provider ### add container's data ### give!(container.data) 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) (Provider.new(*args_b).priority || self.default_priority) <=> (Provider.new(*args_a).priority || self.default_priority) end # if no skip option is given, opts[:skip].to_i will result in zero, so it'll grab thefirst from the array # if the array is empty, args will always turn out nil args = matching_provider_args[opts[:skip].to_i] return args.nil? ? nil : Provider.new(*args) end
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, @headers ) response.finish response.to_a else [status, @headers, response] end end
ruby
{ "resource": "" }
q25646
Scribble.Registry.for
validation
def for *classes, &proc classes.each { |receiver_class| ForClassContext.new(self, receiver_class).instance_eval &proc } end
ruby
{ "resource": "" }
q25647
Scribble.Registry.evaluate
validation
def evaluate name, receiver, args, call = nil, context = nil matcher = Support::Matcher.new self, name, receiver, args matcher.match.new(receiver, call, context).send name, *args end
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" end puts "\r\e[90m#{message}... OK\e[0m" result rescue StandardError puts "\r\e[90m#{message}...\e[0m \e[31mFAILED\e[0m" raise end
ruby
{ "resource": "" }
q25649
Bundleup.Console.tableize
validation
def tableize(rows, &block) rows = rows.map(&block) if block widths = max_length_of_each_column(rows) rows.map do |row| row.zip(widths).map { |value, width| value.ljust(width) }.join(" ") end end
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 if wait_for_exit(thread, periodic_wait) yield end thread.value end
ruby
{ "resource": "" }
q25651
Rescuetime.Collection.all
validation
def all requester = Rescuetime::Requester host = HOST parse_response requester.get(host, params) end
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) || raise(Errors::InvalidFormatError) @format = format self end
ruby
{ "resource": "" }
q25653
Rescuetime.Collection.parse_response
validation
def parse_response(body) report = CSV.new(body, headers: true, header_converters: :symbol, converters: :all) format = @format.to_s.downcase report_formatter = formatters.find(format) report_formatter.format report end
ruby
{ "resource": "" }
q25654
Rescuetime.ReportFormatters.find
validation
def find(name) formatter = formatters.find do |f| standardize(f.name) == standardize(name) end formatter || raise(Rescuetime::Errors::InvalidFormatError) end
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 raise Errors::InvalidQueryError, "#{interval} is not a valid interval" end add_to_query perspective: (order == 'time' ? 'interval' : order), resolution_time: interval end
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') add_to_query restrict_thing: name, restrict_thingy: document end
ruby
{ "resource": "" }
q25657
Rescuetime.QueryBuildable.add_to_query
validation
def add_to_query(**terms) if is_a? Rescuetime::Collection self << terms self else Rescuetime::Collection.new(BASE_PARAMS, state, terms) end end
ruby
{ "resource": "" }
q25658
Rescuetime.Client.valid_credentials?
validation
def valid_credentials? return false unless api_key? !activities.all.nil? rescue Rescuetime::Errors::InvalidCredentialsError false end
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 = Rescuetime.configuration.formatter_paths << local_path paths.each do |path| Dir[File.expand_path(path, __FILE__)].each { |file| require file } end end
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 send("#{target}=", parse_result(@doc.at(selector), delegate)) end end self end
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) hash[name.to_sym] = Array === value ? value.map(&converter) : converter[value] hash end end
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) ? :call : :parse) method.arity == 1 ? method[node] : method[node, self] else node end unless node.nil? end
ruby
{ "resource": "" }
q25663
Tweetburner.Scraper.get_document
validation
def get_document(url) URI === url ? Nokogiri::HTML::Document.parse(open(url), url.to_s, 'UTF-8') : url rescue OpenURI::HTTPError $stderr.puts "ERROR opening #{url}" Nokogiri('') end
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 @subject = transform_text('text/plain', subject).last end end @subject end
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 =~ test if test.is_a?(Regexp) } ignore ||= (part.body.decoded.strip.size == 0 ? true : nil) ignore.nil? ? false : true end
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 if part.part_type? == 'application/octet-stream' type = type_from_filename(filename?(part)) else type = part.part_type? end content = part.body.decoded end return type, nil if content.nil? || content.empty? log("#{self.class} writing file #{file}", :info) File.open(file, 'wb'){ |f| f.write(content) } return type, file end
ruby
{ "resource": "" }
q25667
MMS2R.MMS2R::Media.process_part
validation
def process_part(part) return if ignore_media?(part.part_type?, part) type, file = process_media(part) add_file(type, file) unless type.nil? || file.nil? end
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 end transforms.each do |transform| next unless transform.size == 2 p = transform.first r = transform.last text = text.gsub(p, r) rescue text end return type, text end
ruby
{ "resource": "" }
q25669
MMS2R.MMS2R::Media.transform_text_part
validation
def transform_text_part(part) type = part.part_type? text = part.body.decoded.strip transform_text(type, text) end
ruby
{ "resource": "" }
q25670
MMS2R.MMS2R::Media.temp_file
validation
def temp_file(part) file_name = filename?(part) File.expand_path(File.join(msg_tmp_dir(),File.basename(file_name))) end
ruby
{ "resource": "" }
q25671
MMS2R.MMS2R::Media.add_file
validation
def add_file(type, file) media[type] = [] unless media[type] media[type] << file end
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}")) FileUtils.mkdir_p(dir) dir end
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 name = (name =~ /\..{1,4}$/ ? name : "#{name}.#{self.default_ext(part.part_type?)}").strip # handle excessively large filenames if name.size > 255 ext = File.extname(name) base = File.basename(name, ext) name = "#{base[0, 255 - ext.size]}#{ext}" end name end
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| v == ext} ent.nil? ? nil : ent.first end
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 primary_keys(table_name.to_s).size == 0 end
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 result ensure # Ensure default configuration restoration begin execute_system_command('CHGJOB INQMSGRPY(*DFT)') execute_system_command('RMVRPYLE SEQNBR(9876)') rescue Exception => e raise unauthorized_error_message('CHGJOB INQMSGRPY(*DFT) and RMVRPYLE SEQNBR(9876)', e) end end end
ruby
{ "resource": "" }
q25677
TravisCustomDeploy.Deployment.get_transfer
validation
def get_transfer(type) type = type[0].upcase + type[1..-1] try_require(type) Transfer.const_get(type).new(@options, @files) end
ruby
{ "resource": "" }
q25678
Smurf.Javascript.peek
validation
def peek(aheadCount=1) history = [] aheadCount.times { history << @input.getc } history.reverse.each { |chr| @input.ungetc(chr) } return history.last.chr end
ruby
{ "resource": "" }
q25679
Motion.Capture.captureOutput
validation
def captureOutput(output, didFinishProcessingPhoto: photo, error: error) if error error_callback.call(error) else @capture_callback.call(photo.fileDataRepresentation) end end
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( forJPEGSampleBuffer: photo_sample_buffer, previewPhotoSampleBuffer: preview_photo_sample_buffer ) @capture_callback.call(jpeg_data) end end
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) { error ? error_callback.call(error) : block.call(asset_url) }) end
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 error_callback.call(error) else block.call(nil) # asset url is not returned in completion block end }) end
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 = orientation_mapping.fetch(device_orientation, AVCaptureVideoOrientationPortrait) connection.setVideoOrientation(video_orientation) if connection.videoOrientationSupported? end end
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 for j in index_left..index_right likelihood += - (data[j] - mean) ** 2 / (2.0 * variance) end likelihood += points_in_bin * (Math.log(points_in_bin / Float(n)) - 0.5 * Math.log( 2 * Math::PI * variance)) else likelihood += points_in_bin * Math.log(1.0 / bin_width / n) end end index_left = index_right + 1 end # Compute the Bayesian information criterion bic = 2 * likelihood - (3 * k - 1) * Math.log(Float(n)) if k == kmin max_bic = bic kopt = kmin elsif bic > max_bic max_bic = bic kopt = k end end kopt end
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 it could trigger weird crash when Jsonify these vars if value == 10 @config.include_instance_var = true @config.include_local_var = true end end
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 == self mw = self::StackMiddleware._mwares[name] = self::StackMiddleware._mwares[name].dup end mw else self::StackMiddleware.new(name, self, opts) end end
ruby
{ "resource": "" }
q25687
Pancake.Middleware.use
validation
def use(middleware, *_args, &block) stack(middleware).use(middleware, *_args, &block) end
ruby
{ "resource": "" }
q25688
Metadata::Ingest::Translators.FormToAttributes.attribute_lookup
validation
def attribute_lookup(assoc) group_data = @map[assoc.group.to_sym] return nil unless group_data attribute = group_data[assoc.type.to_sym] return attribute end
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 assoc.marked_for_destruction? assoc = @form.create_association end add_association_to_attribute_map(attribute, assoc) end
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 then @attributes[attribute] = [assoc] when Array then @attributes[attribute].push(assoc) end end
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 when 0 then values = nil when 1 then values = values.first end object.send("#{attribute}=", values) end
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, attribute_definition: attr_definition ) attr_trans.add_associations_to_form end
ruby
{ "resource": "" }
q25693
Pancake.Router.mount
validation
def mount(mounted_app, path, options = {}) mounted_app = MountedApplication.new(mounted_app, path, options) self.class.mounted_applications << mounted_app mounted_app end
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 } tp_self_caches.push tp_ins.self end end
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 = Levels[log_level] else @level = log_level end @log = stream @log.sync = true @mutex = (@@mutex[@log] ||= Mutex.new) end
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| paths = paths.reverse if invert result << paths.map{|p| File.join(root, p)} end end result.flatten end # if end
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] paths.each do |full_path| result << [path, full_path.gsub(path, "")] end end result end
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] output << ary if tally[ary[1]] == ary[0] end output.reverse end
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 just set persistence to the parent # object's value association.persisted = @source.persisted? return association end
ruby
{ "resource": "" }