query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
Returns a mapping representing whether the current user has permission to view the embed for the project. Determined in a batch
def user_access_by_embed strong_memoize(:user_access_by_embed) do unique_embeds.each_with_object({}) do |embed, access| project = projects_by_path[embed.project_path] access[embed] = Ability.allowed?(user, embed.permission, project) end end end
[ "def visible_permissions(user = User.current)\n return @wiki_page_permissions if user.wiki_manager?(@project)\n dp = user.delegate_permission_for(@project)\n @wiki_page_permissions.select{|wpp| wpp if dp.principals_for_delegate.include?(wpp.principal)}\n end", "def visible?(user=User.current)\n user.allowed_to?(:view_project, self)\n end", "def can_edit?(project)\n current_user.id == project.created_by\n end", "def get_permission\n project_id_key = get_project_id_key()\n project = Project.find(params[project_id_key])\n\n if (current_user)\n permission = Permission.where({\n user_id: current_user.id,\n project_id: params[project_id_key]\n }).first\n end\n\n project.try(:public) || permission\n end", "def has_embed_permission?\n return get_bot_profile.permission?(:embed_links, command.event.channel)\n end", "def has_permission(snippet)\n if @current_user\n if @current_user.id == @snippet.user_id or @current_user.admin\n return true\n end\n end\n \n return false\n end", "def current_user_can_edit_public_project?(p = @project)\n logged_in? && current_user.projects_editable_on_public_site.include?(p)\n end", "def can_manage_project(project)\n @project = project\n @project.user_id == self.id ? true : false\n end", "def authorized_to_edit?(game)\r\n game.user == current_user\r\n end", "def project_permissions\n user.project_permissions(rule.project)\n end", "def can_view_any?(user)\n (self.perm_fields.collect {|f| f.to_s}).any? {|field| can_view?(user, field)}\n end", "def visible?(user=nil)\n (user || User.current).allowed_to?(:view_time_entries, self.project) do |role, user|\n if role.time_entries_visibility == 'all'\n true\n elsif role.time_entries_visibility == 'own'\n self.user == user\n else\n false\n end\n end\n end", "def viewer?\n user_role_id == UserRole::VIEWER\n end", "def can_edit?(document)\n if has_permission?('account_holder || administrator') || current_user.id == document.user_id\n true\n else\n false\n end\n end", "def can_access user\n return self.users.include? user\n end", "def projects_allowed_to_see(item)\r\n ([self] + projects).select{|p| item.is_view_permitted?(p)}\r\n end", "def authorized?\n !current_employee.popv_viewer?\n end", "def can_view_document(document)\n # allow access if user is logged in\n return true if !current_user.nil? and current_user.is_admin?\n # current user is a member of the category's\n # group for a document that is private\n unless document.category.group.nil? or current_user.nil?\n return current_user.member_of(document.category.group.id) if document.is_private?\n end\n return !document.is_private?\n end", "def showable?(mode=:view,organization,current_user)\n field_access_control = organization.field_access_controls.find_by(template_field_id: self.id)\n return true if field_access_control.nil? # meaning if no fac, there is no access defined\n org_specific_user_role_ids = current_user.roles.where(\"organization_id=?\",organization.id).map(&:id)\n field_access_control_roles = field_access_control.roles(mode)\n (field_access_control_roles & org_specific_user_role_ids.map(&:to_s)).any?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a unique list of embeds
def unique_embeds embeds_by_node.values.uniq end
[ "def embed_ids\n pluck(:embed_id)\n end", "def embedments\n @embedments ||= {}\n end", "def get_all_embeds()\n request(Net::HTTP::Get, \"/api/#{API_VERSION}/graph/embed\", nil, nil, false)\n end", "def embedments\n model.embedments\n end", "def embeddables\n self.page_items.collect{|qi| qi.embeddable}\n end", "def embed_tables\n tables.reject{|t| !t.embedded?}\n end", "def document_embeds\n self.relations.keys\n .select { |relation_name| self.relations[relation_name].embedded? }\n .reject { |relation_name| self.relations[relation_name].is_a? Mongoid::Association::Embedded::EmbeddedIn }\n .map(&:to_sym)\n end", "def get_all_tags\n to_return = []\n @embedded_objects.each do |embedded_object|\n to_return.push(embedded_object) if embedded_object.is_a? AppleNotesEmbeddedInlineHashtag\n end\n\n return to_return\n end", "def embeddings\n @embeddings ||= {}\n end", "def tracked_embeds_many\n @tracked_embeds_many ||= begin\n reflect_on_all_associations(:embeds_many)\n .map(&:key)\n .select { |rel| history_trackable_options[:relations][:embeds_many].include? rel }\n end\n end", "def index\n @embeds = Embed.all\n end", "def tracked_embeds_one\n @tracked_embeds_one ||= begin\n reflect_on_all_associations(:embeds_one)\n .map(&:key)\n .select { |rel| history_trackable_options[:relations][:embeds_one].include? rel }\n end\n end", "def embed_all( urls, options = [ ])\n\n\t\t\tmedias = [ ]\n\n\t\t\turls.each do | url |\n\t\t\t\tmedias[ url ] = self.embed( url, options )\n\t\t\tend\n\n\t\t\tmedias\n\t\tend", "def embed(*embeds)\n embeds = (query['_include'] || []) + embeds\n query('_include' => embeds)\n end", "def all_shows\n hosted_shows = self.shows.to_a\n team_shows = self.teams.map(&:hub_show).compact.to_a\n return (hosted_shows + team_shows).uniq\n end", "def not_word_videos\n word_videos = []\n word.word_videos.each do |word_video|\n unless lesson_word_videos.map(&:word_video_id).compact.include? word_video.id\n word_videos.push word_video\n end\n end\n\n word_videos\n end", "def embed_all_references\n return @master_objects unless params[:embed_all_references] == 'true' && @master_objects.present?\n\n @master_objects.each do |mo|\n mo.populate_embedded_items if mo.respond_to?(:populate_embedded_items)\n end\n @master_objects\n end", "def plays_genres\n genres = Array.new\n self.genres.each do |genre|\n genres << genre.printable\n end\n genres.uniq\n end", "def embed_tag_urls\n urls 'embed', 'src'\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Maps a project's full path to a Project object. Contains all of the Projects referenced in the metrics placeholder elements of the current document
def projects_by_path strong_memoize(:projects_by_path) do Project.eager_load(:route, namespace: [:route]) .where_full_path_in(unique_project_paths) .index_by(&:full_path) end end
[ "def projects_hash\n @projects ||= Project.eager_load(:route, namespace: [:route])\n .where_full_path_in(projects)\n .index_by(&:full_path)\n .transform_keys(&:downcase)\n end", "def build\n nodes.locate('Project').select { |node| node[:name] == project_name.read }.first\n end", "def projects\n refs = Set.new\n\n nodes.each do |node|\n node.to_html.scan(Project.markdown_reference_pattern) do\n refs << \"#{$~[:namespace]}/#{$~[:project]}\"\n end\n end\n\n refs.to_a\n end", "def build_project\n @id ||= @project.at('id').inner_html\n @api_url ||= \"#{CONFIG[:api_location]}/projects/#{@id}\"\n @url ||= \"http://www.pivotaltracker.com/projects/#{@id}\"\n @name = @project.at('name').inner_html\n @iteration_length = @project.at('iteration_length').inner_html\n @week_start_day = @project.at('week_start_day').inner_html\n @point_scale = @project.at('point_scale').inner_html.split(',')\n end", "def build_project\n @id ||= @project.at('id').inner_html\n @api_url ||= \"#{CONFIG[:api_url]}projects/#{@id}\"\n @url ||= \"http://www.pivotaltracker.com/projects/#{@id}\"\n @name = @project.at('name').inner_html\n @iteration_length = @project.at('iteration_length').inner_html\n @week_start_day = @project.at('week_start_day').inner_html\n @point_scale = @project.at('point_scale').inner_html.split(',')\n end", "def project_hash\n {\n Name: name,\n Number: number,\n Description: description,\n Path: path,\n Issue_count: issue_count,\n Issues: issue_hashes\n }\n end", "def projects\n weakref(:projects) do\n Project.list(\"member=uid=#{name},#{base}\")\n end\n end", "def projects_autocomplete\n current_user.authorized_projects.map do |p|\n { label: \"project: #{simple_sanitize(p.name_with_namespace)}\", url: project_path(p) }\n end\n end", "def projects_by_reference\n load_referenced.group_by(&:reference)\n end", "def projects_map\n {\n private_files_project: {\n old: projects_old_names_map[@user.private_files_project],\n new: projects_new_names_map[@user.private_files_project],\n },\n private_comparisons_project: {\n old: projects_old_names_map[@user.private_comparisons_project],\n new: projects_new_names_map[@user.private_comparisons_project],\n\n },\n public_files_project: {\n old: projects_old_names_map[@user.public_files_project],\n new: projects_new_names_map[@user.public_files_project],\n },\n public_comparisons_project: {\n old: projects_old_names_map[@user.public_comparisons_project],\n new: projects_new_names_map[@user.public_comparisons_project],\n },\n }\n end", "def analyze_projects\n @projects = Hash.new\n count = 0\n search_paths = Array.new\n search_paths << local_path+'modules/**/*.info'\n search_paths << local_path+'themes/**/*.info'\n search_paths << local_path+'profiles/*/*.info'\n search_paths << local_path+contrib_path+'modules/**/*.info'\n search_paths << local_path+contrib_path+'themes/**/*.info'\n search_paths.uniq! # contrib_path may be ''\n search_paths.each do |sp|\n Dir[sp.to_s].each do |p|\n pp = Drupid::PlatformProject.new(self, p)\n @projects[pp.name] = pp\n count += 1\n end\n end\n count\n end", "def parse_project(p)\n @builder.outline(\"text\" => p[\"name\"], \"type\" => \"link\", \"url\" => p[\"url\"], \"created\" => p[\"created\"]) do\n p[\"tasks\"].each { |t| parse_task(t) }\n end\n end", "def existing_projects\n Project.project_hashes\n end", "def _project\n @project\n end", "def project_all\n prj = { '_id' => 0 }\n prj.merge!(make_grp_prj_periods[1])\n prj.merge!(make_grp_prj_nodes[1])\n prj.merge!(project_bookingnet)\n prj.merge!(project_baselist) unless @sensitivity >= 2\n prj.merge!(project_standardcost) unless @sensitivity >= 1\n { '$project' => prj }\n end", "def projects_analysis\n @projects.each { |p| project_analysis(p) if File.directory?(p) }\n end", "def projects_new_names_map\n {\n @user.private_files_project => \"precisionfda-personal-files-#{orgname}\",\n @user.private_comparisons_project => \"precisionfda-personal-comparisons-#{orgname}\",\n @user.public_files_project => \"precisionfda-public-files-#{orgname}\",\n @user.public_comparisons_project => \"precisionfda-public-comparisons-#{orgname}\",\n }\n end", "def get_project(root_path)\n BRIX11.log(1, '[APC::Project] retrieving project [%s]', projects[root_path])\n projects[root_path]\n end", "def load_project\n puts \"Project: #{project}\"\n\n html = URI.parse(\"http://#{domain}/projects/#{project}/index.html\").read\n\n group_id = html[/(frs|tracker)\\/\\?group_id=\\d+/][/\\d+/].to_i\n @group_id = group_id\n\n if $DEBUG\n puts \"GROUP_ID = #{group_id}\"\n end\n\n html = URI.parse(\"http://rubyforge.org/frs/?group_id=#{group_id}\").read\n\n package = nil\n html.scan(/<h3>[^<]+|release_id=\\d+\">[^>]+|filemodule_id=\\d+/).each do |s|\n case s\n when /<h3>([^<]+)/ then\n package = $1.strip\n when /filemodule_id=(\\d+)/ then\n @package_ids[package] = $1.to_i\n when /release_id=(\\d+)\">([^<]+)/ then\n package_id = @package_ids[package]\n @release_ids[[package_id,$2]] = $1.to_i\n end\n end\n\n if $DEBUG\n p @package_ids, @release_ids\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of the full_paths of every project which has an embed in the doc
def unique_project_paths embeds_by_node.values.map(&:project_path).uniq end
[ "def relevant_directory_paths\n drafts.map { |doc| relative_draft_path(doc).split(\"/\")[0] }.uniq\n end", "def resources\n repo.doc_resources self.path\n end", "def projects\n refs = Set.new\n\n nodes.each do |node|\n node.to_html.scan(Project.markdown_reference_pattern) do\n refs << \"#{$~[:namespace]}/#{$~[:project]}\"\n end\n end\n\n refs.to_a\n end", "def contained_projects(project_or_workspace_pth)\n project_paths = []\n if File.extname(project_or_workspace_pth) == '.xcodeproj'\n project_paths = [project_or_workspace_pth]\n else\n workspace_contents_pth = File.join(project_or_workspace_pth, 'contents.xcworkspacedata')\n workspace_contents = File.read(workspace_contents_pth)\n project_paths = workspace_contents.scan(/\\\"group:(.*)\\\"/).collect do |current_match|\n # skip cocoapods projects\n return nil if current_match.end_with?('Pods/Pods.xcodeproj')\n\n File.join(File.expand_path('..', project_or_workspace_pth), current_match.first)\n end\n end\n project_paths\nend", "def projects\n wayfinder.decorated_ephemera_projects\n end", "def expanded_resources\n files = []\n resources.each do |pattern|\n pattern = pod_destroot + pattern\n pattern.glob.each do |file|\n files << file.relative_path_from(config.project_pods_root)\n end\n end\n files\n end", "def podlings\n ASF::Podling.current.select {|pod| project_owners.map(&:name).include? pod.name}\n end", "def paths\n defined?(@doc_dir) ? [ @doc_dir ] : nil\n end", "def documented_paths\n @documented_paths ||= begin\n @resources.inject([]) { |memo, r| memo += r[\"apis\"].map { |api| api[\"path\"] } }\n end\n end", "def get_project_files\n projects = []\n Find.find(PROJECT_FOLDER) do |file|\n if file=~/.yml$/\n projects << file\n end\n end\n\n projects\n end", "def project_space_paths\n @project_space_paths ||= projects.map { |p| Pathname.new(\"/fs/project/#{p}\") }.select {|p| p.directory? && p.readable? && p.executable? }\n end", "def familiar_documents\n self.known_documents.map {|doc_id| Document.find_by(id: doc_id)}\n end", "def document_embeds\n self.relations.keys\n .select { |relation_name| self.relations[relation_name].embedded? }\n .reject { |relation_name| self.relations[relation_name].is_a? Mongoid::Association::Embedded::EmbeddedIn }\n .map(&:to_sym)\n end", "def reachable_projects\n path.ascend.find_all{ |p| p.directory? }.flat_map do |dir|\n dir.children.select{ |p| p.extname == '.xcodeproj' }\n end\n end", "def filepaths\n object.object_files.map(&:relative_path)\n end", "def publication_docs\n publications.find.to_a\n end", "def reachable_projects\n path.ascend.find_all { |p| p.exist? && p.directory? }.flat_map do |dir|\n dir.children.select { |p| p.extname == '.xcodeproj' }\n end\n end", "def get_items_without_locations project\n arr = [ ]\n project.documents.each { |doc|\n arr.push doc if doc.location.nil? # doc.location returns nil if current user does not have a location for the doc\n }\n # add folders...\n return arr\n end", "def metadata_paths(path)\n arr = []\n @metadata_tree.with_subtree(path, nil, nil, nil) do |node|\n arr << node.doc_path\n end\n arr\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
:nodoc: Creates a new Cartage instance. If provided a Cartage::Config object in +config+, sets the configuration and resolves it. If +config+ is not provided, the default configuration will be loaded.
def initialize(config = nil) self.config = config || Cartage::Config.load(:default) end
[ "def cartage(config = nil)\n if defined?(@cartage) && @cartage && config\n fail \"Cannot provide another configuration after initialization.\"\n end\n @cartage ||= Cartage.new(config)\n end", "def set_config(config)\n\t\tend", "def initialize(config)\n case config\n when String\n @config = Snooper::Config.load config\n else\n @config = config\n end\n end", "def initialize(config)\n @config = config\n setup_delivery\n end", "def configure(config={})\n config.each do |(key, val)|\n self.config[key] = val\n end\n end", "def config=(value)\n @config = value\n end", "def config=(config)\n @config = config.clone\n\n %w(safe lsi highlighter baseurl exclude include future unpublished\n show_drafts limit_posts keep_files).each do |opt|\n send(\"#{opt}=\", config[opt])\n end\n\n # keep using `gems` to avoid breaking change\n self.gems = config[\"plugins\"]\n\n configure_cache\n configure_plugins\n configure_theme\n configure_include_paths\n configure_file_read_opts\n\n self.permalink_style = config[\"permalink\"].to_sym\n\n # Read in a _config.yml from the current theme-gem at the very end.\n @config = load_theme_configuration(config) if theme\n @config\n end", "def initialize\n loadConfig\n end", "def assign_config()\n\t\t$config = load_config()\n\t\t$config.define_singleton_method(:reload!, &method(:assign_config))\n\t\t$config\n\tend", "def configure(config = nil, &block)\n config ||= Util::BlockHashBuilder.build(&block)\n @config = config.dup.freeze\n end", "def config( path = nil )\n if ( !@config )\n @config = Config.new( path )\n end\n\n @config\n end", "def initialize(config = {})\n c = config.dup\n c[:root_url] = ROOT_URL\n\n super(c)\n end", "def config_load(config); end", "def initialize\n @config = {}\n load_config\n end", "def initialize(path, config)\n self.path = path\n self.config = config\n end", "def configuration=(config)\n Akephalos.configuration = config\n end", "def initialize(config_path = nil)\n self.config_path = config_path.nil? ? \"#{RAILS_ROOT}/config/uv_storage.yml\" : config_path\n self.config = YAML.load_file(self.config_path)\n self.config.stringify_keys!\n\n self.config = if RAILS_ENV.present?\n self.config[RAILS_ENV]\n elsif Rails.env.present?\n self.config[Rails.env]\n end\n end", "def load_config\n project = if ENV['BOLT_PROJECT']\n Bolt::Project.create_project(ENV['BOLT_PROJECT'], 'environment')\n elsif options[:project]\n dir = Pathname.new(options[:project])\n if (dir + Bolt::Project::BOLTDIR_NAME).directory?\n Bolt::Project.create_project(dir + Bolt::Project::BOLTDIR_NAME)\n else\n Bolt::Project.create_project(dir)\n end\n else\n Bolt::Project.find_boltdir(Dir.pwd)\n end\n @config = Bolt::Config.from_project(project, options)\n rescue Bolt::Error => e\n fatal_error(e)\n raise e\n end", "def initialize\n @config = config_from_file || empty_config\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
:attr_accessor: compression The compression to be applied to any tarballs created (either the final tarball or the dependency cache tarball).
def compression unless defined?(@compression) @compression = :bzip2 reset_computed_values end @compression end
[ "def compression\n configuration[:copy_compression] || :gzip\n end", "def tar_compression_flag\n case compression\n when :bzip2, \"bzip2\", nil\n \"j\"\n when :gzip, \"gzip\"\n \"z\"\n when :none, \"none\"\n \"\"\n end\n end", "def compress\n @env[:ui].info I18n.t(\"vagrant.actions.general.package.compressing\", :tar_path => tar_path)\n File.open(tar_path, Platform.tar_file_options) do |tar|\n Archive::Tar::Minitar::Output.open(tar) do |output|\n begin\n current_dir = FileUtils.pwd\n\n copy_include_files\n\n FileUtils.cd(@env[\"package.directory\"])\n Dir.glob(File.join(\".\", \"**\", \"*\")).each do |entry|\n Archive::Tar::Minitar.pack_file(entry, output)\n end\n ensure\n FileUtils.cd(current_dir)\n end\n end\n end\n end", "def compress\n compressor_klass = JekyllAssetPipeline::Compressor.subclasses.select do |c|\n c.filetype == @type\n end.last\n\n unless compressor_klass.nil?\n compressor = compressor_klass.new(@bundled)\n @bundled = compressor.compressed\n end\n end", "def compression_method; end", "def tar_compression_extension\n case compression\n when :bzip2, \"bzip2\", nil\n \".bz2\"\n when :gzip, \"gzip\"\n \".gz\"\n when :none, \"none\"\n \"\"\n end\n end", "def tar_compression_flag(path)\n case path\n when /\\.tar\\.bz2$/\n return \"-j\"\n when /\\.tar\\.gz$|\\.tgz$/\n return \"-z\"\n when /\\.tar\\.xz$/\n return \"-J\"\n else\n return nil\n end\n end", "def perform\n log system_messages[:archiving]; log system_messages[:compressing]\n run \"tar -czf #{File.join(tmp_path, compressed_file)} #{exclude_files} #{tar_files}\"\n end", "def default_compression; end", "def default_compression=(_arg0); end", "def perform\n log system_messages[:archiving]; log system_messages[:compressing]\n _compressed_file = File.join(tmp_path, compressed_file)\n run \"tar -cvf #{_compressed_file} #{exclude_files} #{tar_files}\"\n if !self.max_part.nil? && File.size(_compressed_file) > self.max_part\n file = File.join(tmp_path, \"/\", compressed_file)\n Dir.chdir(tmp_path)\n run \"split -b #{max_part} #{_compressed_file} -d #{_compressed_file}.part_\"\n compressed_part\n else\n puts _compressed_file\n self.final_file = add_archive_file(compressed_file)\n end\n end", "def compress(directory, file)\n case compression\n when :gzip, :gz then [\"tar\", \"czf\", file, directory]\n when :bzip2, :bz2 then [\"tar\", \"cjf\", file, directory]\n when :zip then [\"zip\", \"-qr\", file, directory]\n else raise ArgumentError, \"invalid compression type #{compression.inspect}\"\n end\n end", "def compress\n @assets.each do |asset|\n # Find a compressor to use\n klass = JAPR::Compressor.subclasses.select do |c|\n c.filetype == @type\n end.last\n\n return unless klass\n\n begin\n asset.content = klass.new(asset.content).compressed\n rescue Exception => e\n puts \"Asset Pipeline: Failed to compress '#{asset.filename}' \" \\\n \"with '#{klass}': #{e.message}\"\n raise e\n end\n end\n end", "def compression(value = true)\n options[:compression] = value\n end", "def compress(directory, file)\n case copy_compression\n when :gzip, :gz then [\"tar\", \"czf\", file, directory]\n when :bzip2, :bz2 then [\"tar\", \"cjf\", file, directory]\n when :zip then [\"zip\", \"-qr\", file, directory]\n else raise ArgumentError, \"invalid compression type #{copy_compression.inspect}\"\n end\n end", "def compress_source_tgz(path)\n tarfile = Tempfile.create([\"vagrant\", \".tar\"])\n tarfile.close\n tarfile = File.open(tarfile.path, \"wb+\")\n tgzfile = Tempfile.create([\"vagrant\", \".tgz\"])\n tgzfile.close\n tgzfile = File.open(tgzfile.path, \"wb\")\n tar = Gem::Package::TarWriter.new(tarfile)\n tgz = Zlib::GzipWriter.new(tgzfile)\n if File.file?(path)\n tar.add_file(File.basename(path), File.stat(path).mode) do |io|\n File.open(path, \"rb\") do |file|\n while bytes = file.read(4096)\n io.write(bytes)\n end\n end\n end\n else\n Dir.glob(File.join(path, \"**/**/*\")).each do |item|\n rel_path = item.sub(path, \"\")\n item_mode = File.stat(item).mode\n\n if File.directory?(item)\n tar.mkdir(rel_path, item_mode)\n else\n tar.add_file(rel_path, item_mode) do |io|\n File.open(item, \"rb\") do |file|\n while bytes = file.read(4096)\n io.write(bytes)\n end\n end\n end\n end\n end\n end\n tar.close\n tarfile.rewind\n while bytes = tarfile.read(4096)\n tgz.write bytes\n end\n tgz.close\n tgzfile.close\n tarfile.close\n File.delete(tarfile.path)\n tgzfile.path\n end", "def compress_command\n \"tar -czf #{filename} #{@backup.database}\"\n end", "def compress_application\n system(\"tar -zcf #{APPLICATION_FILE} #{APPLICATION_PATH}\")\n end", "def extract_tar_gz\n Gem::Package::TarReader.new(Zlib::GzipReader.open(base.package)) do |tar|\n\n # Progressbar\n progressbar = ProgressBar.create(format: PROGRESSBAR_FORMAT, total: tar.count)\n\n # tar.count move position pointer to end\n tar.rewind\n\n dest_file = nil\n tar.each do |entry|\n if entry.full_name == TAR_LONGLINK\n dest_file = File.join(@tmpdir, entry.read.strip)\n next\n end\n dest_file ||= File.join(@tmpdir, entry.full_name)\n if entry.directory?\n FileUtils.rm_rf(dest_file) unless File.directory?(dest_file)\n FileUtils.mkdir_p(dest_file, mode: entry.header.mode, verbose: false)\n elsif entry.file?\n FileUtils.rm_rf(dest_file) unless File.file?(dest_file)\n File.open(dest_file, 'wb') do |f|\n f.write(entry.read)\n end\n FileUtils.chmod(entry.header.mode, dest_file, verbose: false)\n elsif entry.header.typeflag == '2' # symlink\n File.symlink(entry.header.linkname, dest_file)\n end\n\n dest_file = nil\n progressbar.increment\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
:attr_accessor: dependency_cache_path Reads or sets the vendored dependency cache path. This is where the tarball of vendored dependencies in the working path will reside. On a CI system, this should be written somewhere that the CI system uses for build caching. On Semaphore CI, this would be $SEMAPHORE_CACHE.
def dependency_cache_path self.dependency_cache_path = tmp_path unless defined?(@dependency_cache_path) @dependency_cache_path end
[ "def cache_path\n File.join(Config.git_cache_dir, @install_dir)\n end", "def cache_path\n @cache_path ||= ensure_dir(File.join(gem_home, 'cache'))\n end", "def dependency_cache\n @dependency_cache ||= {}\n end", "def cache_repository_path\n File.absolute_path(File.join(Rails.root, 'cache', cached_directory))\n end", "def remote_cache_path\n File.join(shared_path, 'bundle', 'cache')\n end", "def cache_path\n File.join(Vendor.library_path, \"git\", Digest::MD5.hexdigest(uri)) if uri\n end", "def cache_path\n ::File.join(Chef::Config[:file_cache_path], \"artifact_file\")\n end", "def cache_path=(cache_path)\n @cache_path = Pathname.new(cache_path).expand_path\n end", "def repository_path\n File.absolute_path \"#{Config.cache_path}/#{cache_repository_name}\"\n end", "def cache_path\n Pathname.new(File.expand_path(File.join(ChefCLI::Helpers.package_home, \"cache\")))\n .join(\".cache\", \"git\", Digest::SHA1.hexdigest(uri))\n end", "def cache_path\n root.join(self[\"cache_path\"])\n end", "def caching_marker\n @project.path_to('use_ivy_caching')\n end", "def cache_dir; end", "def revision_cache_dir\n File.join(shared_cache_dir,revision.to_s)\n end", "def cache_path\n File.join @path, 'cache.ri'\n end", "def cache_path\n @cache_path ||= Pathname.new(\n ENV['YATVDB_CACHE_PATH'] ||\n ENV['TVDB_CACHE_PATH'] ||\n config['cache_path'] ||\n '~/.yatvdb'\n ).expand_path\n end", "def repo_cache_dir # :nodoc:\n File.join Gem.dir, 'cache', 'bundler', 'git', \"#{@name}-#{uri_hash}\"\n end", "def path\n (self.class.base_path + @repository.cache_key).tap{ |o| o.mkpath }\n end", "def caching_marker\n File.expand_path 'use_ivy_caching'\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The cartage configuration object, implemented as a recursive OpenStruct. This can return just the subset of configuration for a command or plugin by providing the +for_plugin+ or +for_command+ parameters.
def config(for_plugin: nil, for_command: nil) if for_plugin && for_command fail ArgumentError, "Cannot get config for plug-in and command together" elsif for_plugin @config.dig(:plugins, for_plugin.to_sym) || OpenStruct.new elsif for_command @config.dig(:commands, for_command.to_sym) || OpenStruct.new else @config end end
[ "def config\n yield @@config_options\n end", "def configurations\n return @configurations if @configurations\n \n configurations = CONFIGURATIONS_CLASS.new\n configurations.extend(IndifferentAccess) if @use_indifferent_access\n \n ancestors.reverse.each do |ancestor|\n next unless ancestor.kind_of?(ClassMethods)\n ancestor.config_registry.each_pair do |key, value|\n if value.nil?\n configurations.delete(key)\n else\n configurations[key] = value\n end\n end\n end\n \n configurations\n end", "def generate_configuration\n config = {}\n config[:logger] = logger\n config[:backends] = backends\n config[:yaml] = {:datadir => data_dir}\n config[:hierarchy] = generate_hierarchy\n config[:merge_behavior] = merge_behavior\n config.merge! additions if additions.is_a? Hash\n debug \"Generated configuration: #{config.inspect}\"\n config\n end", "def configuration\n @configuration ||= \n Cabar::Configuration.new\n end", "def config\n config = {}\n config['recipes'] = []\n config['recipes'] |= hash_path(@default_config, 'recipes', 'global') || []\n config['recipes'] |= hash_path(@default_config, 'recipes', self.ohai[\"platform_family\"]) || []\n @group_configs.each do |group_name, group_config|\n config['recipes'] |= hash_path(group_config, 'recipes', 'global') || []\n config['recipes'] |= hash_path(group_config, 'recipes', self.ohai[\"platform_family\"]) || []\n end\n people_recipes = @people_config['recipes'] || {}\n config['recipes'] |= people_recipes['global'] || []\n config['recipes'] |= people_recipes[self.ohai[\"platform_family\"]] || []\n config['attributes'] = {}\n config['attributes'].deep_merge!(@default_config['attributes'] || {}) { |key, old, new| Array.wrap(old) + Array.wrap(new) }\n @group_configs.each do |group_name, group_config|\n config['attributes'].deep_merge!(group_config['attributes']) { |key, old, new| Array.wrap(old) + Array.wrap(new) } unless group_config['attributes'].nil?\n end\n people_attributes = @people_config['attributes'] || {}\n Kitchenplan::Log.debug \"config(): @people_config = #{@people_config.inspect}\"\n Kitchenplan::Log.debug \"config(): @group_configs = #{@group_configs.inspect}\"\n Kitchenplan::Log.debug \"config(): @default_config = #{@default_config.inspect}\"\n config['attributes'].deep_merge!(people_attributes) { |key, old, new| Array.wrap(old) + Array.wrap(new) }\n config\n end", "def config\n \n # TODO: Re-enable:\n # # Display the value for a specific machine.\n # $ rudy -e prod -r db config param-name\n \n if @@config.nil? || @@config.empty?\n return if @@global.quiet\n raise Rudy::NoConfig\n end\n\n outform = @@global.format == :json ? :to_json : :to_yaml\n \n types = @option.marshal_dump.keys & @@config.keys # Intersections only\n types = @@config.keys if @option.all\n types = [:machines] if types.empty?\n \n if @option.project\n rf = File.join(RUDY_HOME, 'Rudyfile')\n raise \"Cannot find: #{rf}\" unless File.exists?(rf)\n li File.read(rf)\n \n elsif @option.script\n conf = fetch_script_config\n li conf.to_hash.send(outform) if conf\n \n else\n #li \"# ACCOUNTS: [not displayed]\" if types.delete(:accounts)\n types.each do |conftype|\n li \"# #{conftype.to_s.upcase}\"\n next unless @@config[conftype] # Nothing to output\n if conftype == :accounts\n skey = @@config[conftype][:aws][:secretkey]\n @@config[conftype][:aws][:secretkey] = hide_secret_key(skey)\n end\n \n li @@config[conftype].to_hash.send(outform)\n end\n end\n \n end", "def config\n config = {}\n config['recipes'] = []\n config['recipes'] |= hash_path(@default_config, 'recipes', 'global') || []\n config['recipes'] |= hash_path(@default_config, 'recipes', @platform) || []\n @group_configs.each do |group_name, group_config|\n config['recipes'] |= hash_path(group_config, 'recipes', 'global') || []\n config['recipes'] |= hash_path(group_config, 'recipes', @platform) || []\n end\n people_recipes = @people_config['recipes'] || {}\n config['recipes'] |= people_recipes['global'] || []\n config['recipes'] |= people_recipes[@platform] || []\n config['attributes'] = {}\n config['attributes'].deep_merge!(@default_config['attributes'] || {}) { |key, old, new| Array.wrap(old) + Array.wrap(new) }\n @group_configs.each do |group_name, group_config|\n config['attributes'].deep_merge!(group_config['attributes']) { |key, old, new| Array.wrap(old) + Array.wrap(new) } unless group_config['attributes'].nil?\n end\n people_attributes = @people_config['attributes'] || {}\n config['attributes'].deep_merge!(people_attributes) { |key, old, new| Array.wrap(old) + Array.wrap(new) }\n config\n end", "def configuration\n @configuration ||= ActiveCommand::Configuration.new\n end", "def configure\n yield Prov.configuration\n end", "def config\n @config ||= compile\n end", "def as_config\n Configureasy::Config.new self.parse\n end", "def config\n unless @proxy_config\n config = super\n adapter_config = adapter.config if adapter.class.include?(Config)\n\n @proxy_config =\n if config && adapter_config\n adapter_members = adapter_config.members - config.members\n members = config.members + adapter_members\n struct = Struct.new(*members)\n\n values = config.values + adapter_config.to_h.values_at(*adapter_members)\n struct.new(*values)\n else\n config || adapter_config\n end\n end\n\n @proxy_config\n end", "def build_config\n conf = micro # returns {} if there isn't a saved config\n\n override(conf, :vmx, true) do\n locate_vmx(McfCommand.platform)\n end\n\n override(conf, :vmrun, true) do\n CFMicro::VMrun.locate(McfCommand.platform)\n end\n\n override(conf, :password) do\n ask(\"Please enter your MCF VM password (vcap user) password\", :echo => \"*\")\n end\n\n conf[:platform] = McfCommand.platform\n\n conf\n end", "def plugin_config\n @configuration.get_inmode_config(@mode, true)\n end", "def config(with_environment: true, for_plugin: nil)\n env = environment.to_sym if with_environment && environment\n plug = for_plugin.to_sym if for_plugin\n\n cfg = if env\n base_config[env]\n else\n base_config\n end\n\n cfg = cfg.plugins[plug] if plug && cfg.plugins\n cfg\n end", "def configurations()\n proxy.ListConfigurations(:configurationType => 2)\n end", "def config(&block)\n yield(Gko::Config)\n end", "def current_configuration\n configuration || begin\n if Origen.top_level\n Origen.top_level.current_configuration\n end\n end\n end", "def configs\n @configs ||= begin\n configs = {}\n \n ancestors.reverse.each do |ancestor|\n next unless ancestor.kind_of?(ClassMethods)\n ancestor.config_registry.each_pair do |key, value|\n if value.nil?\n configs.delete(key)\n else\n configs[key] = value\n end\n end\n end\n \n configs.extend Conversions\n configs\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The release metadata that will be written for the package.
def release_metadata @release_metadata ||= { package: { name: name, repo: { type: "git", # Hardcoded until we have other support url: repo_url }, hashref: release_hashref, timestamp: timestamp } } end
[ "def final_release_metadata_json\n @final_release_metadata_json ||= Pathname(\"#{final_name}-release-metadata.json\")\n end", "def package_metadata\n @package_metadata ||= ::ChefDk::Helpers.metadata_for(\n channel: channel,\n version: version,\n platform: node['platform'],\n platform_version: node['platform_version'],\n machine: node['kernel']['machine']\n )\n end", "def metadata\r\n hash = {}\r\n hash[:uuid] = config.uuid\r\n hash[:gamefic_version] = \"#{Gamefic::VERSION}\"\r\n hash[:sdk_version] = \"#{Gamefic::Sdk::VERSION}\"\r\n hash[:build_date] = \"#{DateTime.now}\"\r\n hash\r\n end", "def build_metadata\n require 'json'\n require 'tempfile'\n\n metadata = {\n \"description\" => DESCRIPTION,\n \"short_description\" => DESCRIPTION,\n \"name\" => \"manageiq/master\",\n \"versions\" => map_releases\n }\n\n metadata_file = Tempfile.new\n metadata_file.write metadata.to_json\n metadata_file.close\n\n metadata_file\n end", "def package_metadata\n @package_metadata ||= ::ChefDk::Helpers.metadata_for(node, new_resource)\n end", "def save_release_metadata(local: false)\n display \"Saving release metadata...\"\n json = JSON.generate(release_metadata)\n\n if local\n Pathname(\".\").join(\"release-metadata.json\").write(json)\n else\n work_path.join(\"release-metadata.json\").write(json)\n final_release_metadata_json.write(json)\n end\n end", "def info\n unless release = shift_argument\n error(\"Usage: heroku releases:info RELEASE\")\n end\n validate_arguments!\n\n release_data = api.get_release(app, release).body\n\n data = {\n 'By' => release_data['user'],\n 'Change' => release_data['descr'],\n 'When' => time_ago(Time.now.to_i - Time.parse(release_data[\"created_at\"]).to_i)\n }\n\n unless release_data['addons'].empty?\n data['Addons'] = release_data['addons']\n end\n\n styled_header(\"Release #{release}\")\n styled_hash(data)\n\n display\n\n styled_header(\"#{release} Config Vars\")\n unless release_data['env'].empty?\n if options[:shell]\n release_data['env'].keys.sort.each do |key|\n display(\"#{key}=#{release_data['env'][key]}\")\n end\n else\n styled_hash(release_data['env'])\n end\n else\n display(\"#{release} has no config vars.\")\n end\n end", "def release(options)\n options = options.rekey\n\n unixname = self.unixname\n\n package = options[:package] || metadata.name\n version = options[:version] || metadata.version\n\n date = options[:date] || metadata.released || Time::now.strftime('%Y-%m-%d %H:%M')\n\n changes = options[:changes] || project.history.releases[0].changes\n notes = options[:notes] || project.history.releases[0].note\n\n release = options[:release] || version\n\n files = options[:files] || options[:file] || []\n\n #store = options[:store] || 'pkg'\n\n processor = options[:processor] || 'Any'\n\n is_public = !options[:private]\n\n #raise ArgumentError, \"missing unixname\" unless unixname\n raise ArgumentError, \"missing package\" unless package\n raise ArgumentError, \"missing release\" unless release\n\n # package name has to be 3+ characters.\n if package.size < 3\n package = package + \"'s\"\n end\n\n # sub in for version if %s is used in release name.\n release = release % version if release.index(\"%s\")\n\n release_notes = notes\n release_changes = changes\n\n # Gather package files to release.\n if files.empty?\n files = find_packages(version)\n else\n files = files.map do |file|\n if File.directory?(file)\n find_packages(version, file)\n else\n file\n end\n end\n files = files.flatten\n end\n files = files.select{ |f| File.file?(f) }\n\n abort \"No package files.\" if files.empty?\n\n files.each do |file|\n abort \"Not a file -- #{file}\" unless File.exist?(file)\n puts \"Release file: #{File.basename(file)}\"\n end\n\n # which package types\n #rtypes = [ 'tgz', 'tbz', 'tar.gz', 'tar.bz2', 'deb', 'gem', 'ebuild', 'zip' ]\n #rtypes -= exclude\n #rtypes = rtypes.collect{ |rt| Regexp.escape( rt ) }\n #re_rtypes = Regexp.new('[.](' << rtypes.join('|') << ')$')\n\n puts \"Releasing #{package} #{release} to #{unixname} project...\" #unless options['quiet']\n\n login do\n\n raise ArgumentError, \"missing group_id\" unless group_id\n\n unless package_id = package?(package)\n if trial?\n puts \"Package '#{package}' does not exist.\"\n puts \"Create package #{package}.\"\n abort \"Cannot continue in trial mode.\"\n else\n #unless options['force']\n q = \"Package '#{package}' does not exist. Create?\"\n a = ask(q, 'yN')\n abort \"Task canceled.\" unless ['y', 'yes', 'okay'].include?(a.downcase)\n #end\n puts \"Creating package #{package}...\"\n create_package(package, is_public)\n unless package_id = package?(package)\n raise \"Package creation failed.\"\n end\n end\n end\n if release_id = release?(release, package_id)\n #unless options[:force]\n if trial?\n puts \"Release #{release} already exists.\"\n else\n q = \"Release #{release} already exists. Re-release?\"\n a = ask(q, 'yN')\n abort \"Task canceled.\" unless ['y', 'yes', 'okay'].include?(a.downcase)\n #puts \"Use -f option to force re-release.\"\n #return\n end\n files.each do |file|\n fname = File.basename(file)\n if file_id = file?(fname, package)\n if trial?\n puts \"Remove file #{fname}.\"\n else\n puts \"Removing file #{fname}...\"\n remove_file(file_id, release_id, package_id)\n end\n end\n if trial?\n puts \"Add file #{fname}.\"\n else\n puts \"Adding file #{fname}...\"\n add_file(file, release_id, package_id, processor)\n end\n end\n else\n if trial?\n puts \"Add release #{release}.\"\n else\n puts \"Adding release #{release}...\"\n add_release(release, package_id, files,\n :processor => processor,\n :release_date => date,\n :release_changes => release_changes,\n :release_notes => release_notes,\n :preformatted => '1'\n )\n unless release_id = release?(release, package_id)\n raise \"Release creation failed.\"\n end\n end\n #files.each do |file|\n # puts \"Added file #{File.basename(file)}.\"\n #end\n end\n end\n puts \"Release complete!\" unless trial?\n end", "def locked_package_metadata\n @locked_package_metadata ||= Packages::Composer::Metadatum\n .for_package(@name, @project.id)\n .locked_for_update\n end", "def release_name\n @release_name ||= [\n metadata['name'],\n metadata['version']\n ].join('-')\n end", "def metadata\n project_metadata&.data\n end", "def meta\n @meta ||= LicenseMeta.from_yaml(yaml)\n end", "def info\n release = args.shift.downcase.strip rescue nil\n raise(CommandFailed, \"Specify a release\") unless release\n\n release = heroku.release(app, release)\n\n display \"=== Release #{release['name']}\"\n display_info(\"Change\", release[\"descr\"])\n display_info(\"By\", release[\"user\"])\n display_info(\"When\", time_ago(Time.now.to_i - Time.parse(release[\"created_at\"]).to_i))\n display_info(\"Addons\", release[\"addons\"].join(\", \"))\n display_vars(release[\"env\"])\n end", "def info\n release = args.shift.downcase.strip rescue nil\n raise(CommandFailed, \"Specify a release\") unless release\n\n release = heroku.release(extract_app, release)\n\n display \"=== Release #{release['name']}\"\n display_info(\"Change\", release[\"descr\"])\n display_info(\"By\", release[\"user\"])\n display_info(\"When\", delta_format(Time.parse(release[\"created_at\"])))\n display_info(\"Addons\", release[\"addons\"].join(\", \"))\n display_vars(release[\"env\"])\n end", "def metadata\n return @metadata if @metadata\n\n @lock.synchronize do\n @metadata = {\n 'license_key' => license_key,\n 'agent_run_token' => agent_id\n }\n @metadata.merge!(request_headers_map)\n merge_gzip_metadata\n end\n end", "def project_metadata\n @project_metadata ||= Shomen::Metadata.new\n end", "def generate_metadata_file\n @metadata_filename = @config.get(:tmp_directory) + '/versions.' + @config.environment_name + '.' + @config.instance_id + '.json'\n File.open(@metadata_filename, 'w') do |io|\n io.print @config.registry.to_s\n end\n if @config.group_ownership\n begin\n FileUtils.chown nil, @config.group_ownership, @metadata_filename\n FileUtils.chmod \"g+w\", @metadata_filename\n rescue ArgumentError, Errno::EPERM\n end\n end\n @log.debug 'Generated metadata file ' + @metadata_filename\n end", "def write_pkg_metadata\n render_template(resource_path(\"gen.manifestfile.erb\"),\n destination: pkg_metadata_file,\n variables: {\n name: safe_base_package_name,\n fmri_package_name: fmri_package_name,\n description: project.description,\n summary: project.friendly_name,\n arch: safe_architecture,\n })\n\n # Append the contents of symlinks_file if it exists\n if symlinks_file\n File.open(pkg_metadata_file, \"a\") do |symlink|\n symlink.write(render_symlinks)\n end\n end\n\n # Print the full contents of the rendered template file to generate package contents\n log.debug(log_key) { \"Rendered Template:\\n\" + File.read(pkg_metadata_file) }\n end", "def package_information\n puts\n puts \"%30s%s\" % [\"Plugin information : \", @package.metadata[:name]]\n puts \"%30s%s\" % [\"-\" * 22, \"-\" * 22]\n puts \"%30s%s\" % [\"Plugin Type : \", @package.plugintype.capitalize]\n puts \"%30s%s\" % [\"Package Output Format : \", @package_type.upcase]\n puts \"%30s%s\" % [\"Version : \", @package.metadata[:version]]\n puts \"%30s%s\" % [\"Iteration : \", @package.iteration]\n puts \"%30s%s\" % [\"Vendor : \", @package.vendor]\n puts \"%30s%s\" % [\"Post Install Script : \", @package.postinstall] if @package.postinstall\n puts \"%30s%s\" % [\"Author : \", @package.metadata[:author]]\n puts \"%30s%s\" % [\"License : \", @package.metadata[:license]]\n puts \"%30s%s\" % [\"URL : \", @package.metadata[:url]]\n\n if @package.packagedata.size > 0\n @package.packagedata = @package.packagedata.select{|k, v| v != nil}\n @package.packagedata.each_with_index do |values, i|\n if i == 0\n puts \"%30s%s\" % [\"Identified Packages : \", values[0]]\n else\n puts \"%30s%s\" % [\" \", values[0]]\n end\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the release hashref.
def release_hashref @release_hashref ||= `git rev-parse HEAD`.chomp end
[ "def release_hashref(save_to: nil)\n @release_hashref ||= %x(git rev-parse HEAD).chomp\n File.open(save_to, 'w') { |f| f.write @release_hashref } if save_to\n @release_hashref\n end", "def final_release_hashref\n @final_release_hashref ||=\n Pathname(\"#{final_name}-release-hashref.txt\")\n end", "def _get_release_number\n version.release\n end", "def lastRelease\n raise 'updateDelivInfo() not called' unless @releaseKind\n n=@lastReleaseNum\n if n then\n return \"#{@releasePrefix}#{n}\"\n else\n return nil\n end\n end", "def get_release(release_id)\n query_and_build \"releases/#{release_id}\"\n end", "def last_release_tag\n ReleaseTag.latest\n end", "def resource_hash\n Digest::SHA1.hexdigest(\"#{PROTOCOL_VERSION}\\000#{@repository.checkout_hash}\\000#{@pos}\")\n end", "def revision\n deployment.real_release\n end", "def get_latest_release(project)\n api_url = \"https://api.github.com/repos/#{PROJECT_PERFIX}/#{project}/releases/latest\"\n data = URI.parse(api_url).read\n obj = JSON.parse(data)\n version = obj[\"tag_name\"]\n sha_url = \"https://github.com/#{PROJECT_PERFIX}/#{project}/releases/download/#{version}/#{project}-darwin.sha256\"\n sha = URI.parse(sha_url).read\n url = \"https://github.com/#{PROJECT_PERFIX}/#{project}/releases/download/#{version}/#{project}-darwin\"\n sha256 = sha.split(\" \").first\n return url,sha256, version\nend", "def release\n fetch(:@release) { |grid_string| grid_string[7,10] }\n end", "def active_release\n @active_release || latest_release\n end", "def _get_snapshot_number\n version.snapshot\n end", "def release\n @status.current[:monit][:platform][:release]\n end", "def version_guid\n \"git:#{current_revision}\"\n end", "def release_state\n \"public_release\"\n end", "def hash\n if @hash_value.nil?\n @hash_value = (name.hash * 53) ^ version.hash\n end\n @hash_value\n end", "def get_current_release_commit\n host, user, deploy_to, current_path = fetch_host_infos\n sha = \"\"\n\n begin\n guard_command = Command.new.raw!(\"[ -f #{deploy_to}/current/REVISION ]\")\n cat_command = Command.new.cat!(\"#{deploy_to}/current/REVISION\")\n main_command = Command.and(guard_command, cat_command)\n\n Net::SSH.start(host, user, keys: [SETTINGS['ssh_private_key']]) do |ssh|\n stdout, stderr = ssh.exec!(main_command)\n sha = stdout.strip if stdout\n\n if sha.empty?\n tail_command = Command.new.tail!(\"#{deploy_to}/revisions.log\")\n output = ssh.exec!(tail_command)\n sha = /\\(at.(\\w*)\\)/.match(output)[1] if /\\(at.(\\w*)\\)/.match(output)\n end\n end\n rescue\n end\n\n if sha.empty? || !(/(\\A\\S*\\z)/.match(sha))\n logger.debug \"the commit oid cannot be parsed\"\n raise \"cannot fetch remote host #{self.application_url}\"\n else\n return sha\n end\n end", "def release_metadata\n @release_metadata ||= {\n package: {\n name: name,\n repo: {\n type: \"git\", # Hardcoded until we have other support\n url: repo_url\n },\n hashref: release_hashref,\n timestamp: timestamp\n }\n }\n end", "def get_latest_release(project, bin)\n api_url = \"https://api.github.com/repos/#{project}/releases/latest\"\n data = URI.parse(api_url).read\n obj = JSON.parse(data)\n version = obj[\"name\"]\n sha_url = \"https://github.com/#{project}/releases/download/#{version}/#{bin}.sha256\"\n sha = URI.parse(sha_url).read\n url = \"https://github.com/#{project}/releases/download/#{version}/#{bin}\"\n sha256 = sha.split(\" \").first\n\n return url, sha256, version\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The working path for the job, in tmp_path.
def work_path @work_path ||= tmp_path.join(name) end
[ "def tmp_path\n @tmpfile.path\n end", "def tmp_path\n File.join(home_path, \"tmp\")\n end", "def tmp_path\n Default.tmp_path / pool.name / name\n end", "def tmp_path(path)\n return File.expand_path(File.join(@@config['tmpPath'], path))\n end", "def tmp_dir\n File.expand_path(self.relative_tmp_dir, @options[:root_dir])\n end", "def tmp_path\n File.join(TMP_PATH, TRIGGER)\n end", "def temporary_path(path=nil)\n if path\n File.join(temporary_directory, path)\n else\n temporary_directory\n end\n end", "def tmp_dir\n File.join(gitpusshuten_dir, 'tmp')\n end", "def remote_tmp_path\n '/tmp'\n end", "def work_dir\n File.join(tmpdir, @gem_spec.gem_dirname)\n end", "def relative_tmp_dir\n sd = self.instance.send(\"#{self.attribute}_tmp_dir\")\n if options[:tmp_dir].is_a?( Proc )\n sd ||= options[:tmp_dir].call(self.instance, self.attribute)\n else\n sd ||= options[:tmp_dir]\n end\n return sd\n end", "def job_output_path\n data[:job_output_path]\n end", "def path\n tempfile.path\n end", "def get_temp_directory\n defined?(Rails) ? \"#{Rails.root}/tmp\" : \"/tmp\"\n end", "def path\n tempfile.path\n end", "def temp_storage_path\n assert_path_environment\n \"#{ENV['HOME']}/Library/Caches/com.runningwithcrayons.Alfred-2/Workflow Data/#{bundle_id}\"\n end", "def temp_base\n File.join(Rails.root, \"tmp\")\n end", "def temp_storage_path\n \"#{Dir.tmpdir}/cloud_crowd_tmp\"\n end", "def temp_dir\n name = 'tmp_' + rand.to_s.gsub(/\\D/, '')\n File.join(@temp_root, name)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The path to the resulting releasemetadata.json file.
def final_release_metadata_json @final_release_metadata_json ||= Pathname("#{final_name}-release-metadata.json") end
[ "def path_for(package)\n \"#{package.path}.metadata.json\"\n end", "def path_for(package)\n \"#{package.path}.metadata.json\"\n end", "def metadatafile\n @tagdir + '/' + @name + '.json'\n end", "def save_release_metadata(local: false)\n display \"Saving release metadata...\"\n json = JSON.generate(release_metadata)\n\n if local\n Pathname(\".\").join(\"release-metadata.json\").write(json)\n else\n work_path.join(\"release-metadata.json\").write(json)\n final_release_metadata_json.write(json)\n end\n end", "def release_path\n ::File.join(install_path, artifact_name, artifact_version)\n end", "def metadata_path\n \"#{path}/metadata\"\n end", "def generate_metadata_file\n @metadata_filename = @config.get(:tmp_directory) + '/versions.' + @config.environment_name + '.' + @config.instance_id + '.json'\n File.open(@metadata_filename, 'w') do |io|\n io.print @config.registry.to_s\n end\n if @config.group_ownership\n begin\n FileUtils.chown nil, @config.group_ownership, @metadata_filename\n FileUtils.chmod \"g+w\", @metadata_filename\n rescue ArgumentError, Errno::EPERM\n end\n end\n @log.debug 'Generated metadata file ' + @metadata_filename\n end", "def final_release_hashref\n @final_release_hashref ||=\n Pathname(\"#{final_name}-release-hashref.txt\")\n end", "def release_path\n @release_path ||= Pathname.new(source_dir).join(data['release_path'] || './release').to_s\n end", "def manifest_path\n build_output_dir.join('manifest.json')\n end", "def json_path\n bundle.path + path + 'Contents.json'\n end", "def metadata_file_for url\n File.join(Ydl::CONFIG.directory, \"metadata\", url.md5ify + \".info.json\")\n end", "def project_manifest_path(project, channel)\n File.join(metadata_dir, channel, \"#{project}-manifest.json\")\n end", "def package_json_path\n current_dir / PACKAGE_JSON\n end", "def build_metadata\n require 'json'\n require 'tempfile'\n\n metadata = {\n \"description\" => DESCRIPTION,\n \"short_description\" => DESCRIPTION,\n \"name\" => \"manageiq/master\",\n \"versions\" => map_releases\n }\n\n metadata_file = Tempfile.new\n metadata_file.write metadata.to_json\n metadata_file.close\n\n metadata_file\n end", "def release_path\n @config[:remote_path] + '/' + release_dir\n end", "def current_release_path\n File.join( config.remote_dir, config.public_dir )\n end", "def compile_metadata(out = self.path)\n filepath = File.join(out, Metadata::COMPILED_FILE_NAME)\n File.open(filepath, \"w+\") do |f|\n f.write(metadata.to_json)\n end\n\n filepath\n end", "def release_file\n File.join(source_dir, \".release\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create the release package(s). Requests: +:vendor_dependencies+ (vendor_dependencies, path) +:pre_build_package+ +:build_package+ +:post_build_package+
def build_package # Force timestamp to be initialized before anything else. This gives us a # stable timestamp for the process. timestamp # Prepare the work area: copy files from root_path to work_path based on # the resolved Manifest.txt. prepare_work_area # Anything that has been modified locally needs to be reset. restore_modified_files # Save both the final release metadata and the in-package release metadata. save_release_metadata # Vendor the dependencies for the package. vendor_dependencies # Request that supporting plug-ins build the package. request_build_package end
[ "def create_package(package_meta, release_dir)\n name = package_meta['name']\n version = package_meta['version']\n\n package_attrs = {\n release: @release_model,\n name: name,\n sha1: nil,\n blobstore_id: nil,\n fingerprint: package_meta['fingerprint'],\n version: version,\n }\n\n package = Models::Package.new(package_attrs)\n package.dependency_set = package_meta['dependencies']\n\n save_package_source_blob(package, package_meta, release_dir) unless @compiled_release\n\n package.save\n end", "def build_release\n build_dependency\n puts '### release build ###'\n `gulp release`\n puts '### release build done ###'\n post_build\nend", "def create_package(logger:, release_model:, fix:, compiled_release:, package_meta:, release_dir:)\n name = package_meta['name']\n version = package_meta['version']\n\n package_attrs = {\n release: release_model,\n name: name,\n sha1: nil,\n blobstore_id: nil,\n fingerprint: package_meta['fingerprint'],\n version: version,\n }\n\n package = Models::Package.new(package_attrs)\n package.dependency_set = package_meta['dependencies']\n\n save_package_source_blob(logger, package, fix, package_meta, release_dir) unless compiled_release\n\n package.save\n end", "def create_packages\n begin\n puts \"Building module for #{@package_name} plugin.\"\n\n @tmpdir = Dir.mktmpdir('mcollective_packager')\n make_module\n run_build\n move_package\n\n puts \"Completed building module for #{@package_name} plugin.\"\n ensure\n if @keep_artifacts\n puts 'Keeping build artifacts'\n puts \"Build artifacts saved - #{@tmpdir}\"\n else\n cleanup_tmpdirs\n end\n end\n end", "def generate_package(project) # rubocop:disable Metrics/AbcSize\n target_dir = project.repo ? output_dir(project.repo) : output_dir\n\n # Here we maintain backward compatibility with older vanagon versions\n # that did this by default. This shim should get removed at some point\n # in favor of just letting the makefile deliver the bill-of-materials\n # to the correct directory. This shouldn't be required at all then.\n if project.bill_of_materials.nil?\n bom_install = [\n # Move bill-of-materials into a docdir\n \"mkdir -p $(tempdir)/osx/build/root/#{project.name}-#{project.version}/usr/local/share/doc/#{project.name}\",\n \"mv $(tempdir)/osx/build/root/#{project.name}-#{project.version}/bill-of-materials $(tempdir)/osx/build/root/#{project.name}-#{project.version}/usr/local/share/doc/#{project.name}/bill-of-materials\",\n ]\n else\n bom_install = []\n end\n\n if project.extra_files_to_sign.any?\n sign_commands = Vanagon::Utilities::ExtraFilesSigner.commands(project, @mktemp, \"/osx/build/root/#{project.name}-#{project.version}\")\n else\n sign_commands = []\n end\n\n # Setup build directories\n [\"bash -c 'mkdir -p $(tempdir)/osx/build/{dmg,pkg,scripts,resources,root,payload,plugins}'\",\n \"mkdir -p $(tempdir)/osx/build/root/#{project.name}-#{project.version}\",\n \"mkdir -p $(tempdir)/osx/build/pkg\",\n # Grab distribution xml, scripts and other external resources\n \"cp #{project.name}-installer.xml $(tempdir)/osx/build/\",\n #copy the uninstaller to the pkg dir, where eventually the installer will go too\n \"cp #{project.name}-uninstaller.tool $(tempdir)/osx/build/pkg/\",\n \"cp scripts/* $(tempdir)/osx/build/scripts/\",\n \"if [ -d resources/osx/productbuild ] ; then cp -r resources/osx/productbuild/* $(tempdir)/osx/build/; fi\",\n # Unpack the project\n \"gunzip -c #{project.name}-#{project.version}.tar.gz | '#{@tar}' -C '$(tempdir)/osx/build/root/#{project.name}-#{project.version}' --strip-components 1 -xf -\",\n\n bom_install,\n\n # Sign extra files\n sign_commands,\n\n # Package the project\n \"(cd $(tempdir)/osx/build/; #{@pkgbuild} --root root/#{project.name}-#{project.version} \\\n --scripts $(tempdir)/osx/build/scripts \\\n --identifier #{project.identifier}.#{project.name} \\\n --version #{project.version} \\\n --preserve-xattr \\\n --install-location / \\\n payload/#{project.name}-#{project.version}-#{project.release}.pkg)\",\n # Create a custom installer using the pkg above\n \"(cd $(tempdir)/osx/build/; #{@productbuild} --distribution #{project.name}-installer.xml \\\n --identifier #{project.identifier}.#{project.name}-installer \\\n --package-path payload/ \\\n --resources $(tempdir)/osx/build/resources \\\n --plugins $(tempdir)/osx/build/plugins \\\n pkg/#{project.name}-#{project.version}-#{project.release}-installer.pkg)\",\n # Create a dmg and ship it to the output directory\n \"(cd $(tempdir)/osx/build; \\\n #{@hdiutil} create \\\n -volname #{project.name}-#{project.version} \\\n -fs JHFS+ \\\n -format UDBZ \\\n -srcfolder pkg \\\n dmg/#{project.package_name})\",\n \"mkdir -p output/#{target_dir}\",\n \"cp $(tempdir)/osx/build/dmg/#{project.package_name} ./output/#{target_dir}\"].flatten.compact\n end", "def create_autobuild_package\n Ops::Tools.create_autobuild_package(vcs, name, raw_local_dir)\n end", "def release(options)\n options = options.rekey\n\n version = options[:version]\n project = options[:project] || @project\n package = options[:package] || project\n release = options[:release] || version\n name = options[:name] || package\n files = options[:file] || []\n date = options[:date] || Time::now.strftime('%Y-%m-%d %H:%M')\n processor = options[:processor] || 'Any'\n store = options[:store] || 'pkg'\n changelog = options[:changelog]\n notelog = options[:notelog]\n\n is_public = options[:is_public].nil? ? true : options[:is_public]\n\n raise ArgumentError, \"missing group_id\" unless group_id\n raise ArgumentError, \"missing project\" unless project\n raise ArgumentError, \"missing package\" unless package\n raise ArgumentError, \"missing release\" unless release\n\n if files.empty?\n files = Dir.glob(File.join(store,\"#{name}-#{version}*\"))\n end\n\n files = files.reject{ |f| File.directory?(f) }\n\n abort \"No package files.\" if files.empty?\n\n files.each do |file|\n abort \"Not a file -- #{file}\" unless File.exist?(file)\n end\n\n # which package types\n #rtypes = [ 'tgz', 'tbz', 'tar.gz', 'tar.bz2', 'deb', 'gem', 'ebuild', 'zip' ]\n #rtypes -= exclude\n #rtypes = rtypes.collect{ |rt| Regexp.escape( rt ) }\n #re_rtypes = Regexp.new('[.](' << rtypes.join('|') << ')$')\n\n puts \"Releasing #{package} #{release}...\" #unless options['quiet']\n\n login do\n\n unless package_id = package?(package)\n #unless options['force']\n q = \"Package '#{package}' does not exist. Create?\"\n a = ask(q, 'yN')\n abort \"Task canceled.\" unless ['y', 'yes', 'okay'].include?(a.downcase)\n #end\n puts \"Creating package #{package}...\"\n abort \"Cannot continue in dry-run mode.\" if dryrun?\n create_package(package, is_public)\n unless package_id = package?(package)\n raise \"Package creation failed.\"\n end\n end\n if release_id = release?(release, package_id)\n #unless options[:force]\n q = \"Release #{release} already exists. Re-release?\"\n a = ask(q, 'yN')\n abort \"Task canceled.\" unless ['y', 'yes', 'okay'].include?(a.downcase)\n #puts \"Use -f option to force re-release.\"\n #return\n #end\n files.each do |file|\n fname = File.basename(file)\n if file_id = file?(fname, package)\n puts \"Removing file #{fname}...\"\n remove_file(file_id, release_id, package_id) unless dryrun?\n end\n puts \"Adding file #{fname}...\"\n add_file(file, release_id, package_id, processor) unless dryrun?\n end\n else\n puts \"Adding release #{release}...\"\n unless dryrun?\n add_release(release, package_id, files,\n :processor => processor,\n :release_date => date,\n :release_changes => changelog,\n :release_notes => notelog,\n :preformatted => '1'\n )\n unless release_id = release?(release, package_id)\n raise \"Release creation failed.\"\n end\n end\n #files.each do |file|\n # puts \"Added file #{File.basename(file)}.\"\n #end\n end\n end\n puts \"Release complete!\"\n end", "def build_product_pkg\n command = <<-EOH.gsub(/^ {8}/, '')\n productbuild \\\\\n --distribution \"#{distribution_file}\" \\\\\n --resources \"#{staging_resources_path}\" \\\\\n EOH\n\n command << %Q( --sign \"#{Config.signing_identity}\" \\\\\\n) if Config.sign_pkg\n command << %Q( \"#{final_pkg}\")\n command << %Q(\\n)\n\n execute(command)\n end", "def create_packages\n begin\n puts \"Building packages for #{@package_name} plugin.\"\n\n @tmpdir = Dir.mktmpdir('mcollective_packager')\n @build_dir = File.join(@tmpdir, \"#{@package_name}_#{@plugin.metadata[:version]}\")\n Dir.mkdir(@build_dir)\n\n create_debian_dir\n @plugin.packagedata.each do |type, data|\n prepare_tmpdirs(data)\n create_install_file(type, data)\n create_pre_and_post_install(type)\n end\n create_debian_files\n create_tar\n run_build\n move_packages\n\n puts \"Completed building all packages for #{@package_name} plugin.\"\n ensure\n if @keep_artifacts\n puts 'Keeping build artifacts.'\n puts \"Build artifacts saved - #{@tmpdir}\"\n else\n puts 'Removing build artifacts.'\n cleanup_tmpdirs\n end\n end\n end", "def build_product_pkg\n command = <<~EOH\n productbuild \\\\\n --distribution \"#{staging_dir}/Distribution\" \\\\\n --resources \"#{resources_dir}\" \\\\\n EOH\n\n command << %Q{ --sign \"#{signing_identity}\" \\\\\\n} if signing_identity\n command << %Q{ \"#{final_pkg}\"}\n command << %Q{\\n}\n\n Dir.chdir(staging_dir) do\n shellout!(command)\n end\n end", "def create_package(product_code='DSO', flavor='OPENSOURCE')\n check_if_type_supplied(product_code, flavor)\n\n depends :init, :compile\n call_actions :__assemble, :__package\n end", "def build_pkg(dist, arch, deps)\n start_dir = Dir.pwd\n build_dir = \"/tmp/rhobuild\"\n version = Rhoconnect::VERSION\n description = '\"Rhoconnect production environment\"'\n prefix = \"/opt/rhoconnect/installer\"\n gem_name = \"rhoconnect-#{version}.gem\"\n\n before_install_script = \"#{build_dir}/unix-like/pre_install.sh\"\n after_install_script = \"#{build_dir}/unix-like/post_install.sh\"\n before_remove_script = \"#{build_dir}/unix-like/pre_uninstall.sh\"\n after_remove_script = \"#{build_dir}/unix-like/post_uninstall.sh\"\n\n `rm -rf #{build_dir}` if File.exist?(\"#{build_dir}\")\n Dir.mkdir(\"#{build_dir}\")\n Dir.mkdir(\"#{build_dir}/unix-like\")\n\n # Copy all necessary Files into the build_dir\n system(\"cp install.sh Gemfile Gemfile.lock #{build_dir}\")\n system(\"cp -r installer/unix-like/*.sh #{build_dir}/unix-like\")\n system(\"cp -r installer/unix-like/*.rb #{build_dir}/unix-like\")\n system(\"cp pkg/#{gem_name} #{build_dir}\")\n\n # cd into the pkg dir so that fpm will create the package into the pkg dir.\n Dir.chdir(\"./pkg\") # it created by build task and should already exist\n\n # Construct fpm command\n fpm_cmd = \"fpm -s dir -t #{dist} -n rhoconnect -v #{version} -a #{arch} -C #{build_dir} --epoch 1 \" +\n \"--before-install #{before_install_script} --after-install #{after_install_script} \" +\n \"--before-remove #{before_remove_script} --after-remove #{after_remove_script} \" +\n \"--prefix #{prefix} --description #{description}\"\n # Add the list of dependencies to the fpm call\n deps.each { |dep| fpm_cmd << \" -d '#{dep}'\" }\n fpm_cmd << \" './'\"\n # Create the package\n system(fpm_cmd)\n # Leave no trace...\n system(\"rm -rf #{build_dir}\")\n Dir.chdir(start_dir)\nend", "def process_packages(release_dir)\n new_packages, existing_packages, registered_packages = PackageProcessor.process(\n @release_version_model,\n @release_model,\n @name,\n @version,\n manifest_packages,\n logger,\n )\n\n created_package_refs = create_packages(new_packages, release_dir)\n\n existing_package_refs = use_existing_packages(existing_packages, release_dir)\n\n\n if @compiled_release\n registered_package_refs = registered_packages.map do |pkg, pkg_meta|\n {\n package: pkg,\n package_meta: pkg_meta,\n }\n end\n\n all_package_refs = Array(created_package_refs) | Array(existing_package_refs) | registered_package_refs\n create_compiled_packages(all_package_refs, release_dir)\n return\n end\n\n backfill_source_for_packages(registered_packages, release_dir)\n end", "def packageDependency(dep)\n info \"Starting packaging #{dep}\"\n\n if dep.is_a? String\n instance = getDependencyObjectByName dep\n else\n instance = dep\n end\n\n if !instance\n onError \"Invalid dependency name: #{dep}\"\n end\n\n files = instance.getInstalledFiles\n\n if !files || files.length == 0\n onError \"Dependency '#{dep}' has no files to package\"\n end\n\n precompiledName = instance.getNameForPrecompiled + \"_\" + CurrentPlatform\n zipName = precompiledName + \".7z\"\n infoFile = precompiledName + \"_info.txt\"\n hashFile = precompiledName + \"_hash.txt\"\n\n # Check that all exist\n Dir.chdir(DependencyInstallFolder){\n\n files.each{|f|\n\n if !File.exists? f\n onError \"Dependency file that should be packaged doesn't exist: #{f}\"\n end\n }\n\n File.open(infoFile, 'w') {|f|\n f.puts \"RubySetupSystem precompiled library for #{CurrentPlatform}\"\n f.puts instance.Name + \" retrieved from \" + instance.RepoURL\n f.puts instance.Version.to_s + \" Packaged at \" + Time.now.to_s\n f.puts \"\"\n f.puts \"You can probably find license from the repo url if it isn't included here\"\n f.puts \"This info file is included in \" + zipName\n }\n\n runSystemSafe(*[p7zip, \"a\", zipName, infoFile, files].flatten)\n\n if !File.exists? zipName\n onError \"Failed to create zip file\"\n end\n\n hash = SHA3::Digest::SHA256.file(zipName).hexdigest\n\n # Write hash to file\n File.open(hashFile, 'w') {|f|\n f.puts hash\n }\n\n success \"Done with #{dep}, created: #{zipName}\"\n info \"#{zipName} SHA3: \" + hash\n # info \"#{zipName} PLATFORM: \" + CurrentPlatform\n return {name: precompiledName, hash: hash}\n }\nend", "def build\n create_build_dir\n\n stage_module_in_build_dir\n build_package\n\n package_file\n ensure\n cleanup_build_dir\n end", "def create_package(config, version, options)\n config = generate_config(config, version)\n project = @solution.project(config['project'])\n changes, changelog = package_changes(config, project.dir)\n log.info \"#{config['id']} unchanged...\" unless changes\n return unless changes || options[:force]\n generate_package(project, config, options[:debug], changelog)\n push_packages(config) if options[:push]\n end", "def build\n create_build_dir\n\n stage_module_in_build_dir\n build_package\n\n package_file\n ensure\n cleanup_build_dir\n end", "def release_step\n super\n\n unless @config.rubygems_api_key\n fail CapsuleCD::Error::ReleaseCredentialsMissing, 'cannot deploy package to rubygems, credentials missing'\n return\n end\n\n # write the config file.\n rubygems_cred_path = File.expand_path('~/.gem')\n\n FileUtils.mkdir_p(rubygems_cred_path)\n File.open(rubygems_cred_path + '/credentials', 'w+', 0600) do |file|\n file.write(<<-EOT.gsub(/^\\s+/, '')\n ---\n :rubygems_api_key: #{@config.rubygems_api_key}\n EOT\n )\n end\n\n # run gem push *.gem\n gems = Dir.glob(@source_git_local_path + '/*.gem')\n if gems.empty?\n fail CapsuleCD::Error::TestDependenciesError, 'Ruby gem file could not be found'\n end\n gem_path = gems.first\n Open3.popen3('gem push ' + File.basename(gem_path), chdir: @source_git_local_path) do |_stdin, stdout, stderr, external|\n { stdout: stdout, stderr: stderr }. each do |name, stream_buffer|\n Thread.new do\n until (line = stream_buffer.gets).nil?\n puts \"#{name} -> #{line}\"\n end\n end\n end\n # wait for process\n external.join\n unless external.value.success?\n fail CapsuleCD::Error::ReleasePackageError, 'Pushing gem to RubyGems.org using `gem push` failed. Check log for exact error'\n end\n end\n end", "def release(options)\n options = options.rekey\n\n unixname = self.unixname\n\n package = options[:package] || metadata.name\n version = options[:version] || metadata.version\n\n date = options[:date] || metadata.released || Time::now.strftime('%Y-%m-%d %H:%M')\n\n changes = options[:changes] || project.history.releases[0].changes\n notes = options[:notes] || project.history.releases[0].note\n\n release = options[:release] || version\n\n files = options[:files] || options[:file] || []\n\n #store = options[:store] || 'pkg'\n\n processor = options[:processor] || 'Any'\n\n is_public = !options[:private]\n\n #raise ArgumentError, \"missing unixname\" unless unixname\n raise ArgumentError, \"missing package\" unless package\n raise ArgumentError, \"missing release\" unless release\n\n # package name has to be 3+ characters.\n if package.size < 3\n package = package + \"'s\"\n end\n\n # sub in for version if %s is used in release name.\n release = release % version if release.index(\"%s\")\n\n release_notes = notes\n release_changes = changes\n\n # Gather package files to release.\n if files.empty?\n files = find_packages(version)\n else\n files = files.map do |file|\n if File.directory?(file)\n find_packages(version, file)\n else\n file\n end\n end\n files = files.flatten\n end\n files = files.select{ |f| File.file?(f) }\n\n abort \"No package files.\" if files.empty?\n\n files.each do |file|\n abort \"Not a file -- #{file}\" unless File.exist?(file)\n puts \"Release file: #{File.basename(file)}\"\n end\n\n # which package types\n #rtypes = [ 'tgz', 'tbz', 'tar.gz', 'tar.bz2', 'deb', 'gem', 'ebuild', 'zip' ]\n #rtypes -= exclude\n #rtypes = rtypes.collect{ |rt| Regexp.escape( rt ) }\n #re_rtypes = Regexp.new('[.](' << rtypes.join('|') << ')$')\n\n puts \"Releasing #{package} #{release} to #{unixname} project...\" #unless options['quiet']\n\n login do\n\n raise ArgumentError, \"missing group_id\" unless group_id\n\n unless package_id = package?(package)\n if trial?\n puts \"Package '#{package}' does not exist.\"\n puts \"Create package #{package}.\"\n abort \"Cannot continue in trial mode.\"\n else\n #unless options['force']\n q = \"Package '#{package}' does not exist. Create?\"\n a = ask(q, 'yN')\n abort \"Task canceled.\" unless ['y', 'yes', 'okay'].include?(a.downcase)\n #end\n puts \"Creating package #{package}...\"\n create_package(package, is_public)\n unless package_id = package?(package)\n raise \"Package creation failed.\"\n end\n end\n end\n if release_id = release?(release, package_id)\n #unless options[:force]\n if trial?\n puts \"Release #{release} already exists.\"\n else\n q = \"Release #{release} already exists. Re-release?\"\n a = ask(q, 'yN')\n abort \"Task canceled.\" unless ['y', 'yes', 'okay'].include?(a.downcase)\n #puts \"Use -f option to force re-release.\"\n #return\n end\n files.each do |file|\n fname = File.basename(file)\n if file_id = file?(fname, package)\n if trial?\n puts \"Remove file #{fname}.\"\n else\n puts \"Removing file #{fname}...\"\n remove_file(file_id, release_id, package_id)\n end\n end\n if trial?\n puts \"Add file #{fname}.\"\n else\n puts \"Adding file #{fname}...\"\n add_file(file, release_id, package_id, processor)\n end\n end\n else\n if trial?\n puts \"Add release #{release}.\"\n else\n puts \"Adding release #{release}...\"\n add_release(release, package_id, files,\n :processor => processor,\n :release_date => date,\n :release_changes => release_changes,\n :release_notes => release_notes,\n :preformatted => '1'\n )\n unless release_id = release?(release, package_id)\n raise \"Release creation failed.\"\n end\n end\n #files.each do |file|\n # puts \"Added file #{File.basename(file)}.\"\n #end\n end\n end\n puts \"Release complete!\" unless trial?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Just save the release metadata.
def save_release_metadata(local: false) display "Saving release metadata..." json = JSON.generate(release_metadata) if local Pathname(".").join("release-metadata.json").write(json) else work_path.join("release-metadata.json").write(json) final_release_metadata_json.write(json) end end
[ "def release_metadata\n @release_metadata ||= {\n package: {\n name: name,\n repo: {\n type: \"git\", # Hardcoded until we have other support\n url: repo_url\n },\n hashref: release_hashref,\n timestamp: timestamp\n }\n }\n end", "def save_metadata!\n sanity_check\n metadata_contexts.each do |context|\n output_filename = File.join(base_path, metadata_file_path(context))\n File.open(output_filename, \"w\") do |metadata_file|\n metadata_file << archive_org_metadata(context)\n end\n end\n end", "def final_release_metadata_json\n @final_release_metadata_json ||= Pathname(\"#{final_name}-release-metadata.json\")\n end", "def save_metadata\n metadata.build(doi: self, xml: xml, namespace: schema_version) if xml.present? && xml_changed?\n end", "def write_metadata; end", "def save_release_note()\n puts \"Saving the release note of \" + @version + \" ...\"\n r_note = Nokogiri::HTML(open(@release_note_url))\n File.open(@r_note_filepath, \"w\") do |f|\n f.puts(r_note)\n end\n end", "def save_metadata\n ActiveJobMetadata.write(job_id, metadata)\n \n metadata\n end", "def save_metadata!\n @service.save_blob_metadata(self)\n end", "def write_release(payload)\n info 'Creating new release on GitHub'\n rel = payload[:data][:github_kit].delete(:release)\n release = github_client.create_release(\n rel[:repository],\n rel[:tag_name],\n :name => rel[:name],\n :target_commitish => rel[:reference],\n :prerelease => rel[:prerelease],\n :body => rel[:body]\n )\n\n api_release_url = release.rels[:self].href\n public_release_url = release.rels[:html].href\n\n info 'New release created on GitHub. Uploading assets.'\n assets = rel[:assets].map do |asset|\n debug \"Uploading release asset - #{asset}\"\n response = github_client.upload_asset(\n api_release_url,\n asset_store.get(asset),\n :name => asset.sub(/^.+?_/, ''),\n :content_type => 'application/octet-stream'\n )\n debug \"Completed release asset upload - #{asset}\"\n Smash.new(\n :url => response[:url],\n :browser_url => response[:browser_download_url],\n :name => response[:name],\n :id => response[:id]\n )\n end\n payload.set(:data, :github_kit, :release, :assets, assets)\n payload.set(:data, :github_kit, :release, :api_url, api_release_url)\n payload.set(:data, :github_kit, :release, :public_url, public_release_url)\n\n true\n end", "def put\n check_config(require_destination: true)\n cartage.display \"Uploading to #{name}...\"\n put_file cartage.final_release_metadata_json\n cartage.plugins.request_map(:build_package, :package_name).each do |name|\n put_file name\n end\n end", "def write_metadata\n unless disabled?\n Jekyll.logger.debug \"Writing Metadata:\", \".jekyll-metadata\"\n File.binwrite(metadata_file, Marshal.dump(metadata))\n end\n end", "def save\n prepare\n h = {}\n h[:title] = @title\n h[:sequence] = @sequence.map(&:export)\n outfile = File.join(@basedir, \"#{@name}.json\")\n File.open(outfile, 'w') do |f|\n f.write JSON.pretty_generate(h)\n end\n end", "def autosave; end", "def save\n unless empty?\n recipes = @recipes.keys.sort\n metadata_content = <<-EOS\ndescription \"Automatically generated repo, do not modify\"\n#{recipes.map { |r| \"recipe \\\"#{COOKBOOK_NAME}::#{r}\\\", \\\"RightScript < #{@recipes[r]} >\\\"\" }.join(\"\\n\")}\n EOS\n metadata_path = File.join(@cookbook_dir, 'metadata.rb')\n File.open(metadata_path, 'w') { |f| f.puts metadata_content }\n end\n @saved = true\n end", "def save(bump_info)\n File.write @file, to_yaml(bump_info)\n end", "def save( oid, metadata )\n\t\toid = normalize_oid( oid )\n\t\t@storage[ oid ] = metadata.dup\n\tend", "def create_release(attrs = {})\n release = build_release(attrs)\n release.save\n release\n end", "def save\n params = { name: @name }\n self.metadata.each { |key, value| params[key] = value }\n @bookalope.http_post(@url, params)\n end", "def write_release\n @layer_dir ? write_release_toml : write_release_yaml\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the flag to use with +tar+ given the value of +compression+.
def tar_compression_flag case compression when :bzip2, "bzip2", nil "j" when :gzip, "gzip" "z" when :none, "none" "" end end
[ "def tar_compression_flag(path)\n case path\n when /\\.tar\\.bz2$/\n return \"-j\"\n when /\\.tar\\.gz$|\\.tgz$/\n return \"-z\"\n when /\\.tar\\.xz$/\n return \"-J\"\n else\n return nil\n end\n end", "def tar_compression_extension\n case compression\n when :bzip2, \"bzip2\", nil\n \".bz2\"\n when :gzip, \"gzip\"\n \".gz\"\n when :none, \"none\"\n \"\"\n end\n end", "def compression\n if user_specified_options.has_key?(:compression)\n return user_specified_options[:compression]\n end\n case ::File.extname(uri.path).downcase\n when /gz/, /gunzip/\n :gz\n when /zip/\n :zip\n when /bz2/, /bunzip2/\n :bz2\n when /exe/\n :exe\n end\n end", "def packing\n if user_specified_options.has_key?(:packing)\n return user_specified_options[:packing]\n end\n if uri.path =~ %r{\\.tar(?:\\.|$)}i\n :tar\n end\n end", "def tar_gzip(archive, tarfile, pkg_time, distribution = nil)\n\n # Make sure no distribution information leaks into the package\n if distribution and archive =~ /~#{distribution}/\n archive_plain_name = archive.gsub(/~#{distribution}/,\"\")\n FileUtils.cp_r archive, archive_plain_name\n else\n archive_plain_name = archive\n end\n\n\n Packager.info \"Tar archive: #{archive_plain_name} into #{tarfile}\"\n # Make sure that the tar files checksum remains the same by\n # overriding the modification timestamps in the tarball with\n # some external source timestamp and using gzip --no-name\n #\n # exclude hidden files an directories\n mtime = pkg_time.iso8601()\n # Exclude hidden files and directories at top level\n cmd_tar = \"tar --mtime='#{mtime}' --format=gnu -c --exclude '.+' --exclude-backups --exclude-vcs --exclude #{archive_plain_name}/debian --exclude build #{archive_plain_name} | gzip --no-name > #{tarfile}\"\n\n if system(cmd_tar)\n Packager.info \"Package: successfully created archive using command '#{cmd_tar}' -- pwd #{Dir.pwd} -- #{Dir.glob(\"**\")}\"\n checksum = `sha256sum #{tarfile}`\n Packager.info \"Package: sha256sum: #{checksum}\"\n return true\n else\n Packager.info \"Package: failed to create archive using command '#{cmd_tar}' -- pwd #{Dir.pwd}\"\n return false\n end\n end", "def compression(value = true)\n options[:compression] = value\n end", "def tar_cmd\n # Rely on gnu tar for solaris and OSX.\n case %x{uname -s}.chomp\n when \"SunOS\"\n return \"gtar\"\n when \"Darwin\"\n return \"gnutar\"\n else\n return \"tar\"\n end\n end", "def has_tar?; @has_tar = has_tool?('tar --usage', @has_tar); end", "def tar_cmd\n return @@tar_cmd if defined? @@tar_cmd\n\n # FIXME: don't assume current directory writeable\n emptyfile = Stud::Temporary.pathname\n testarchive = Stud::Temporary.pathname\n\n FileUtils.touch([emptyfile])\n\n # Prefer tar that supports more of the features we want, stop if we find tar of our dreams\n best=\"tar\"\n bestscore=0\n @@tar_cmd_deterministic = false\n # GNU Tar, if not the default, is usually on the path as gtar, but\n # Mac OS X 10.8 and earlier shipped it as /usr/bin/gnutar\n [\"tar\", \"gtar\", \"gnutar\"].each do |tar|\n opts=[]\n score=0\n [\"--sort=name\", \"--mtime=@0\"].each do |opt|\n system(\"#{tar} #{opt} -cf #{testarchive} #{emptyfile} > /dev/null 2>&1\")\n if $?.exitstatus == 0\n opts << opt\n score += 1\n end\n end\n if score > bestscore\n best=tar\n bestscore=score\n if score == 2\n @@tar_cmd_deterministic = true\n break\n end\n end\n end\n @@tar_cmd = best\n FileUtils.rm_f([testarchive, emptyfile])\n\n return @@tar_cmd\n end", "def tar\n Omnibus.which(\"gtar\") ? \"gtar\" : \"tar\"\n end", "def compression\n @j_del.isCompressionSupported\n end", "def detect_compression!\n # If nil we have not tried to detect yet\n if @compression.nil?\n path = Pathname.new(@patch_filename)\n if path.exist?\n @compression = path.compression_type\n @compression ||= :none # If nil, convert to :none\n end\n end\n end", "def tar_gzip(archive, tarfile, pkg_time, distribution = nil,\n logfile: nil)\n\n # Make sure no distribution information leaks into the package\n if distribution and archive =~ /~#{distribution}/\n archive_plain_name = archive.gsub(/~#{distribution}/,\"\")\n FileUtils.cp_r archive, archive_plain_name\n else\n archive_plain_name = archive\n end\n\n\n Packager.info \"Tar archive: #{archive_plain_name} into #{tarfile}\"\n # Make sure that the tar files checksum remains the same by\n # overriding the modification timestamps in the tarball with\n # some external source timestamp and using gzip --no-name\n #\n # exclude hidden files an directories\n mtime = pkg_time.iso8601()\n # Exclude hidden files and directories at top level\n cmd_tar = \"tar --mtime='#{mtime}' --format=gnu -c --exclude '.+' --exclude-backups --exclude-vcs --exclude #{archive_plain_name}/debian --exclude build #{archive_plain_name} | gzip --no-name > #{tarfile}\"\n\n if system(cmd_tar, [:out,:err] => redirection(logfile, \"a\"))\n Packager.info \"Package: successfully created archive using command '#{cmd_tar}' -- pwd #{Dir.pwd} -- #{Dir.glob(\"**\")}\"\n checksum = `sha256sum #{tarfile}`\n Packager.info \"Package: sha256sum: #{checksum}\"\n return true\n else\n Packager.info \"Package: failed to create archive using command '#{cmd_tar}' -- pwd #{Dir.pwd}\"\n return false\n end\n end", "def compress_command\n \"tar -czf #{filename} #{@backup.database}\"\n end", "def general_purpose_flags\n @compression_level\n end", "def test_get_compression\n assert(Tpkg::get_compression(@pkgfile).nil?)\n assert_equal('gzip', Tpkg::get_compression(@gzip_pkgfile))\n assert_equal('bz2', Tpkg::get_compression(@bz2_pkgfile))\n assert(['bz2', 'gzip'].include?(Tpkg::get_compression(@default_compression_pkgfile)))\n assert(Tpkg::get_compression(@uncompressed_pkgfile).nil?)\n end", "def is_tgz? archive, type=nil\n type == :tgz || !archive.match(/\\.tgz$/).nil? || !archive.match(/\\.tar.gz$/).nil?\n end", "def compression\n unless defined?(@compression)\n @compression = :bzip2\n reset_computed_values\n end\n @compression\n end", "def download_tar?\n return @can_use_tar unless @can_use_tar.nil?\n if installed? 'tar'\n @can_use_tar = true\n true\n else\n @can_use_tar = false\n false\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the extension to use with +tar+ given the value of +compression+.
def tar_compression_extension case compression when :bzip2, "bzip2", nil ".bz2" when :gzip, "gzip" ".gz" when :none, "none" "" end end
[ "def tar_compression_flag\n case compression\n when :bzip2, \"bzip2\", nil\n \"j\"\n when :gzip, \"gzip\"\n \"z\"\n when :none, \"none\"\n \"\"\n end\n end", "def tar_compression_flag(path)\n case path\n when /\\.tar\\.bz2$/\n return \"-j\"\n when /\\.tar\\.gz$|\\.tgz$/\n return \"-z\"\n when /\\.tar\\.xz$/\n return \"-J\"\n else\n return nil\n end\n end", "def compression\n if user_specified_options.has_key?(:compression)\n return user_specified_options[:compression]\n end\n case ::File.extname(uri.path).downcase\n when /gz/, /gunzip/\n :gz\n when /zip/\n :zip\n when /bz2/, /bunzip2/\n :bz2\n when /exe/\n :exe\n end\n end", "def guess_compression(url)\n extname = extname(url).downcase\n case extname\n when /gz/, /gunzip/\n :gz\n when /zip/\n :zip\n when /bz2/, /bunzip2/\n :bz2\n when /exe/\n :exe\n end\n end", "def downloaded_file(name, compressor)\n \"#{name}.tar.#{compressor}\"\n end", "def compression_type\n { 1 => 'None',\n 2 => 'PalmDOC',\n 17480 => 'HUFF/CDIC'\n }.fetch(raw_compression_type)\n end", "def compression_codec_id\n metadata & METADATA_COMPRESSION\n end", "def guess_packing(url)\n basename = basename(url).downcase\n if basename.include?('.tar') or basename.include?('.tgz')\n :tar\n end\n end", "def compressed_archive_name=(name, ext = File.extname(name))\n if ext.downcase == '.tgz'\n @archive_name = File.basename(name, ext.downcase) << '.tar'\n else\n @archive_name = File.basename(name, ext)\n end\n @compressed_archive_name = name\n end", "def raw_compression_type\n @compression_type ||= @data[0, 2].unpack('n*')[0]\n end", "def detect_compression!\n # If nil we have not tried to detect yet\n if @compression.nil?\n path = Pathname.new(@patch_filename)\n if path.exist?\n @compression = path.compression_type\n @compression ||= :none # If nil, convert to :none\n end\n end\n end", "def compression_codec\n cluster.config.compression_codec if compressed?\n end", "def is_tgz? archive, type=nil\n type == :tgz || !archive.match(/\\.tgz$/).nil? || !archive.match(/\\.tar.gz$/).nil?\n end", "def compression\n unless defined?(@compression)\n @compression = :bzip2\n reset_computed_values\n end\n @compression\n end", "def compression_type(val = NULL)\n if null?(val)\n @compression_type || :gzip\n else\n unless val.is_a?(Symbol) && %i{gzip bzip2 xz}.member?(val)\n raise InvalidValue.new(:compression_type, \"be a Symbol (:gzip, :bzip2, or :xz)\")\n end\n\n @compression_type = val\n end\n end", "def packing\n if user_specified_options.has_key?(:packing)\n return user_specified_options[:packing]\n end\n if uri.path =~ %r{\\.tar(?:\\.|$)}i\n :tar\n end\n end", "def tar_gz_file\n \"#{package_name}.tar.gz\"\n end", "def test_get_compression\n assert(Tpkg::get_compression(@pkgfile).nil?)\n assert_equal('gzip', Tpkg::get_compression(@gzip_pkgfile))\n assert_equal('bz2', Tpkg::get_compression(@bz2_pkgfile))\n assert(['bz2', 'gzip'].include?(Tpkg::get_compression(@default_compression_pkgfile)))\n assert(Tpkg::get_compression(@uncompressed_pkgfile).nil?)\n end", "def tar_cmd\n # Rely on gnu tar for solaris and OSX.\n case %x{uname -s}.chomp\n when \"SunOS\"\n return \"gtar\"\n when \"Darwin\"\n return \"gnutar\"\n else\n return \"tar\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recursively copy a provided +path+ to the work_path, using a tar pipeline. The target location can be amended by the use of the +to+ parameter as a relative path to work_path. If a relative +path+ is provided, it will be treated as relative to root_path, and it will be used unmodified for writing to the target location. If an absolute path is provided, only the last part of the path will be used as the target name. An error will be raised if either +path+ or +to+ contains a parentrelative reference (../), or if the tar pipeline fails. === Examples cartage.recursive_copy('public/assets') This will cause root_path/public/assets to be copied into work_path/public/assets. cartage.recursive_copy('/tmp/public/assets') This will cause /tmp/public/assets to be copied into work_path/assets. cartage.recursive_copy('/tmp/public/assets', to: 'public') This will cause /tmp/public/assets to be copied into work_path/public/assets.
def recursive_copy(path, to: nil) path = Pathname(path) to = Pathname(to) if to if path.to_s =~ %r{\.\./} || (to && to.to_s =~ %r{\.\./}) fail StandardError, "Recursive copy parameters cannot contain '/../'" end if path.relative? parent = root_path else parent, path = path.split end target = work_path target /= to if to tar_cf_cmd = ["tar", "cf", "-", "-h", "-C", parent, path].map(&:to_s) tar_xf_cmd = ["tar", "xf", "-", "-C", target].map(&:to_s) IO.popen(tar_cf_cmd) do |cf| IO.popen(tar_xf_cmd, "w") do |xf| xf.write cf.read end fail StandardError, "Error running #{tar_xf_cmd.join(" ")}" unless $?.success? end fail StandardError, "Error running #{tar_cf_cmd.join(" ")}" unless $?.success? end
[ "def copy(from, to, recursive = false)\n allTargets = []\n from = [from] unless from.kind_of?(Array)\n from.each { |t| allTargets.concat(dirGlob(t)) }\n\n raise \"copy: no source files matched\" if allTargets.length == 0\n if allTargets.length > 1 || recursive\n raise \"copy: destination directory does not exist\" unless @toFs.fileExists?(to)\n raise \"copy: destination must be a directory for multi-file copy\" unless @toFs.fileDirectory?(to)\n end\n\n allTargets.each do |f|\n owd = @fromFs.pwd\n @fromFs.chdir(File.dirname(f))\n f = File.basename(f)\n\n #\n # Copy plain files.\n #\n if @fromFs.fileFile?(f)\n if @toFs.fileDirectory?(to)\n tf = File.join(to, File.basename(f))\n else\n tf = to\n end\n copySingle(f, tf)\n next\n end\n\n #\n # If the recursive flag is not set, skip directories.\n #\n next unless recursive\n\n #\n # Recursively copy directory sub-tree.\n #\n @fromFs.chdir(f)\n td = File.join(to, f)\n @toFs.dirMkdir(td) unless @toFs.fileExists?(td)\n @fromFs.findEach('.') do |ff|\n tf = File.join(td, ff)\n if @fromFs.fileDirectory?(ff)\n @toFs.dirMkdir(tf)\n elsif @fromFs.fileFile?(ff)\n copySingle(ff, tf)\n end\n end # findEach\n @fromFs.chdir(owd)\n end # allTargets.each\n end", "def copy(source, destination_path)\n # TODO: Honor file mode\n\n source = Pathname.new(source) unless source.is_a?(Pathname)\n random = random_dir\n\n # Add Dockerfile instruction\n if source.directory?\n self << 'ADD ' + random + ' ' + destination_path\n files = [ [ source, random ] ]\n else\n self << 'ADD ' + random + '/' + source.basename.to_s + ' ' + destination_path\n files = [ [ source, random + '/' ] ]\n end\n\n # Create directory for this instruction\n tar.mkdir(random, 750)\n\n # Add all the files recursively\n while !files.empty? do\n source, destination_path = files.shift\n\n # Directory\n if source.directory?\n source.each_entry do |child|\n next if child.fnmatch?('..') or child.fnmatch?('.')\n @tar.mkdir(\"#{destination_path}/#{child}\", 0750) if child.directory?\n files << [ source + child, \"#{destination_path}/#{child}\" ]\n end\n\n # File\n elsif source.file?\n # If we are adding 'file.txt' to 'dest/': we need to append filename\n destination_path += source.basename.to_s if destination_path.end_with?('/')\n\n # Add file copy\n @tar.add_file(destination_path, 0640) do |out_stream|\n in_stream = source.open('r')\n IO.copy_stream(in_stream, out_stream)\n end\n end\n end\n end", "def copy_to(relpath, abspath)\n raise ArgumentError, \"Revision #{revision} of #{repository.url} was never checked out -- can't iterate over files\" unless @dir\n\n Pathname.new(abspath).dirname.mkpath\n FileUtils.cp(@dir + relpath, abspath)\n end", "def copy_directory(source_path, *args, **options, &block)\n source_path = source_path.to_s\n check_path(source_path)\n source = escape_glob_path(source_path)\n dest_path = (args.first || source).to_s\n opts = {recursive: true}.merge(options)\n pattern = opts[:recursive] ? ::File.join(source, '**') : source\n glob_pattern = ::File.join(pattern, '*')\n\n Dir.glob(glob_pattern, ::File::FNM_DOTMATCH).sort.each do |file_source|\n next if ::File.directory?(file_source)\n next if opts[:exclude] && file_source.match(opts[:exclude])\n\n dest = ::File.join(dest_path, file_source.gsub(source_path, '.'))\n file_dest = ::Pathname.new(dest).cleanpath.to_s\n\n copy_file(file_source, file_dest, **options, &block)\n end\n end", "def cp_r(to)\n FileUtils.cp_r(@path, to)\n end", "def file_copy(from_path, to_path)\n params = {\n \"root\" => @root,\n \"from_path\" => format_path(from_path, false),\n \"to_path\" => format_path(to_path, false),\n }\n response = @session.do_post build_url(\"/fileops/copy\", params)\n parse_response(response)\n end", "def cp_r(src, dest)\n Dir[File.join(src, '**/*')].each do |path|\n dest_path = File.join(dest, Pathname.new(path).relative_path_from(src))\n\n if File.directory? path\n FileUtils.mkdir_p dest_path\n next\n elsif File.symlink? path\n path = File.realpath(path)\n end\n FileUtils.cp(path, dest_path)\n end\n end", "def copy_to(path)\n raise CommandError, 'Destination exists' if File.exist?(expand path)\n FileUtils.mkdir_p(File.dirname(expand path))\n FileUtils.cp_r(@working_dir, expand(path))\n end", "def copy_helper(folder, target, opts)\n recursive = opts[:recursive]\n \n # 'name', 'leaf', and 'ntype' are copied, id is not\n new_folder = folder.dup\n new_folder.filespace = target.filespace\n target.children << new_folder\n target.save\n \n # Create new links for all documents in the original folder. Don't\n # use ActiveRecord, since it can all be done in a single database\n # query without multiple trips to the database server.\n sql = <<-\"EOS\" \n INSERT INTO links (folder_id, document_id)\n SELECT #{new_folder.id}, document_id from links\n WHERE folder_id = #{folder.id}\n EOS\n \n # Will throw exeception if this fails.\n ActiveRecord::Base.connection.execute(sql)\n \n if (recursive)\n folder.children.each do |subfolder|\n copy_helper(subfolder, new_folder, opts)\n end\n end\n new_folder\n end", "def copy(from_path, to_path, ctype=nil, recursive=false, replace=false)\n if to_path.end_with? '/'\n # copy into to_path, not to to_path\n to_path = File.join(to_path, File.basename(from_path))\n end\n\n count = 0\n prune = recursive ? nil : 1\n @content_tree.with_subtree(from_path, ctype, prune) do |node|\n ntype = node.node_type\n basename = node.path.split(from_path, 2)[1]\n dest = basename.empty? ? to_path : File.join(to_path, basename)\n if (! replace) and (@content_tree.exist? dest, ntype)\n raise NodeExists, \"'#{dest}' exists [#{ntype}]\"\n end\n new_node = @content_tree.clone(node, dest)\n copy_doc_resources(from_path, to_path) if ntype == :document\n copy_metadata(node.path, dest, ntype)\n notify(EVENT_CLONE, node.path, ctype, dest)\n count += 1\n end\n\n count\n end", "def copy_files(path_from, path_to)\n FileUtils.mkdir_p(path_to)\n files = Dir[path_from + '/*']\n \n puts ''\n puts '-------------------'\n puts '🚚 Copying files 🚚'\n puts '-------------------'\n puts ''\n\n files.each do |file|\n if File.directory?(file)\n FileUtils.cp_r(file, path_to)\n else\n FileUtils.cp(file, path_to)\n end\n\n puts '✅ Copied - ' + File.basename(file)\n end\nend", "def copy_files(root, files, dest, flatten)\n puts \"Copying #{files.length} file(s) to '#{dest}'\"\n for file in files\n from_file = File.join(root, file)\n if flatten\n to_file = File.join(dest, File.basename(file))\n else\n to_file = File.join(dest, file)\n end\n to_dir = File.dirname(to_file)\n FileUtils.makedirs(to_dir) if not File.exists?(to_dir)\n FileUtils.cp(from_file, to_file)\n end\n end", "def cp_r(local_src_path, remote_dest_path, options={})\r\n rm_rf remote_dest_path if options[:overwrite]\r\n create_dir_structure(local_src_path, remote_dest_path)\r\n copy_files(local_src_path, remote_dest_path)\r\n end", "def copy_to(target)\n target.parent.mkdirs\n factory.system.copy_dir(@path, target.path)\n end", "def copy_to(relpath, abspath)\n end", "def recursiveCopy(fromGroup, toGroup)\n \n if shouldIgnoreGroup(fromGroup)\n return\n end\n \n puts \"copying from group: \" + self.getGroupName(fromGroup) + \" to group: \" + self.getGroupName(toGroup)\n \n newGroup = toGroup.new_group(self.getGroupName(fromGroup), fromGroup.real_path)\n \n addedFiles = []\n \n Array(fromGroup.files).each do |child|\n unless shouldIgnoreFile(child) then\n puts \"copying file: \" + child.path\n addedFiles << newGroup.new_file(child.real_path)\n end\n end\n \n addFilesToTargets(addedFiles)\n\n Array(fromGroup.groups).each do |child|\n recursiveCopy(child, newGroup)\n end\n \n end", "def copy(target, copied_folder = nil)\n new_folder = self.dup\n new_folder.parent = target\n new_folder.save!\n\n copied_folder = new_folder if copied_folder.nil?\n\n self.assets.each do |assets|\n assets.copy(new_folder)\n end\n\n self.children.each do |folder|\n unless folder == copied_folder\n folder.copy(new_folder, copied_folder)\n end\n end\n new_folder\n end", "def cp_r(src, dest, options = {})\r\n fu_check_options options, :preserve, :noop, :verbose\r\n fu_output_message \"cp -r#{options[:preserve] ? 'p' : ''} #{[src,dest].flatten.join ' '}\" if options[:verbose]\r\n return if options[:noop]\r\n\r\n fu_each_src_dest(src, dest) do |s,d|\r\n if File.directory?(s)\r\n fu_copy_dir s, d, '.', options[:preserve]\r\n else\r\n fu_p_copy s, d, options[:preserve]\r\n end\r\n end\r\n end", "def copy_from(abspath, relpath)\n raise ArgumentError, \"Revision #{revision} of #{repository.url} was never checked out -- can't iterate over files\" unless @dir\n\n target = @dir + relpath\n Pathname.new(target).dirname.mkpath\n FileUtils.cp(abspath, target)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This started out as a straight line drawn to step barbs, but at a certain point it also started being used to draw straight lines with no arrow heads from step barbs to calm barbs.
def render_to_step_barb(calm=false) stroke ARROW_STROKE_COLOR stroke_weight ARROW_STROKE_WEIGHT # Initial trig calculations for the arrow head adj = @to_barb.pos.x - @from_barb.pos.x opp = @to_barb.pos.y - @from_barb.pos.y angle = Math.atan(opp/adj) if adj>0 and opp<0.001 and opp>-0.001 line_from = Point.new(@from_barb.pos.x+OFFSET_LENGTH, @from_barb.pos.y) line_to = Point.new(@to_barb.pos.x-OFFSET_LENGTH, @to_barb.pos.y) elsif adj<0 and opp<0.001 and opp>-0.001 line_from = Point.new(@from_barb.pos.x-OFFSET_LENGTH, @from_barb.pos.y) line_to = Point.new(@to_barb.pos.x+OFFSET_LENGTH, @to_barb.pos.y) elsif adj<0.001 and adj>-0.001 and opp<0 line_from = Point.new(@from_barb.pos.x, @from_barb.pos.y-OFFSET_LENGTH) line_to = Point.new(@to_barb.pos.x, @to_barb.pos.y+OFFSET_LENGTH) elsif adj<0.001 and adj>-0.001 and opp>0 line_from = Point.new(@from_barb.pos.x, @from_barb.pos.y+OFFSET_LENGTH) line_to = Point.new(@to_barb.pos.x, @to_barb.pos.y-OFFSET_LENGTH) elsif adj>0 and opp<0 line_from = Point.new(@from_barb.pos.x+OFFSET_LENGTH*(Math.cos(angle)).abs, @from_barb.pos.y-OFFSET_LENGTH*(Math.sin(angle)).abs) line_to = Point.new(@to_barb.pos.x-OFFSET_LENGTH*(Math.cos(angle)).abs, @to_barb.pos.y+OFFSET_LENGTH*(Math.sin(angle)).abs) elsif adj<0 and opp<0 line_from = Point.new(@from_barb.pos.x-OFFSET_LENGTH*Math.cos(angle), @from_barb.pos.y-OFFSET_LENGTH*(Math.sin(angle)).abs) line_to = Point.new(@to_barb.pos.x+OFFSET_LENGTH*Math.cos(angle), @to_barb.pos.y+OFFSET_LENGTH*(Math.sin(angle)).abs) elsif adj<0 and opp>0 line_from = Point.new(@from_barb.pos.x-OFFSET_LENGTH*Math.cos(angle), @from_barb.pos.y+OFFSET_LENGTH*(Math.sin(angle)).abs) line_to = Point.new(@to_barb.pos.x+OFFSET_LENGTH*Math.cos(angle), @to_barb.pos.y-OFFSET_LENGTH*(Math.sin(angle)).abs) elsif adj>0 and opp>0 line_from = Point.new(@from_barb.pos.x+OFFSET_LENGTH*Math.cos(angle), @from_barb.pos.y+OFFSET_LENGTH*(Math.sin(angle)).abs) line_to = Point.new(@to_barb.pos.x-OFFSET_LENGTH*Math.cos(angle), @to_barb.pos.y-OFFSET_LENGTH*(Math.sin(angle)).abs) else puts "default arrow" line_from = @from_barb.pos line_to = @to_barb.pos end # Draw a line from one point to the next. line line_from.x, line_from.y, line_to.x, line_to.y # Draw the arrow head if !calm push_matrix translate line_to.x, line_to.y rotate calculate_rotation(adj, opp, angle) line 0, 0, ARROW_WIDTH, -ARROW_HEIGHT line 0, 0, -ARROW_WIDTH, -ARROW_HEIGHT pop_matrix end end
[ "def straight\n @line_type = '--'\n self\n end", "def draw_line; draw_horizontal_line(@draw_y + (line_height / 2) - 1, 2); end", "def forward(steps)\n validate_steps(steps)\n normal_radians = to_rad(flip_turtle_and_normal(@heading))\n new_pt = [@xy[0] + steps * cos(normal_radians),\n @xy[1] + steps * sin(normal_radians)]\n\n add_segment_to_track @xy, new_pt if self.pen_down?\n @xy = new_pt\n end", "def draw_alt_line\n @dim.times do |i|\n if i.even?\n print draw_x\n else\n if @type == \"allx\"\n print draw_x\n elsif @type == \"alt\"\n print draw_dot\n end\n end\n end\n end", "def add turtle, state \n @turtles[0] << state\n if @turtles[0].length > 1 \n @turtles[0][-2].print\n \n x0, y0 = @turtles[0][-2][:x], @turtles[0][-2][:y]\n x1, y1 = state.x, state.y \n @lines << Line2D::Double.new( x0, y0, x1, y1 )\n \n Screen::refresh\n\n end\n \n #if pen down add to line \n end", "def draw_temp_line(pt1, pt2, view)\r\n #view.drawing_color = \"red\"\r\n view.set_color_from_line(pt1, pt2)\r\n #view.line_stipple=\"-.-\"\r\n if view.inference_locked?\r\n view.line_width=2\r\n end\r\n @bbp = [pt1, pt2]\r\n view.draw_line(pt1, pt2)\r\n end", "def draw_lines\n @dim.times do |i|\n if @type.nil?\n draw_line(i+1)\n draw_edge\n puts\n elsif @type == \"allx\" || @type == \"alt\"\n draw_alt_line\n draw_edge\n puts\n end\n end\n end", "def plot_line; end", "def draw_line\n print H_SEP * columns\n end", "def draw_force_arrow(context, start, finish)\n arrow_size = 50\n\n # Get vector\n dx = finish.x - start.x\n dy = finish.y - start.y\n\n combined = dx.abs + dy.abs\n length = Math.hypot(dx, dy)\n if length < arrow_size\n length = arrow_size\n dx = length * (dx/combined)\n dy = length * (dy/combined)\n end\n\n # Creates points for arrow\n arrow_points = []\n arrow_points << CGPointMake(0, -5) << CGPointMake(length - arrow_size, -5) << CGPointMake(length - arrow_size, -40)\n arrow_points << CGPointMake(length, 0)\n arrow_points << CGPointMake(length - arrow_size, 40) << CGPointMake(length - arrow_size, 5) << CGPointMake(0, 5)\n\n cosine = dx / length\n sine = dy / length\n\n arrow_transform_pointer = Pointer.new(CGAffineTransform.type)\n arrow_transform_pointer[0] = CGAffineTransform.new(cosine, sine, -sine, cosine, start.x, start.y)\n\n path = CGPathCreateMutable()\n CGPathMoveToPoint(path, arrow_transform_pointer, 0, 0)\n arrow_points.each do |point|\n CGPathAddLineToPoint(path, arrow_transform_pointer, point.x, point.y)\n end\n CGContextAddPath(context, path)\n CGContextSetFillColorWithColor(context, UIColor.redColor.CGColor)\n CGContextDrawPath(context, KCGPathFill)\n end", "def draw_line(x1,y1,x2,y2,r,g,b,graph_function=false)\r\n if ( @line_dot_size > 1 )\n self.draw_dotted_line(x1,y1,x2,y2,@line_dot_size,r,g,b,graph_function)\n else\n r = 0 if ( r < 0 ) \n r = 255 if ( r > 255 ) \r\n g = 0 if ( g < 0 ) \n g = 255 if ( g > 255 ) \r\n b = 0 if ( b < 0 ) \n b = 255 if ( b > 255 ) \r\n distance = Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)) \r\n if ( distance == 0 )\r\n #return -1\n else \r\n xstep = (x2-x1) / distance\r\n ystep = (y2-y1) / distance\r\n i =0\n while i<=distance \r\n x = i * xstep + x1\r\n y = i * ystep + y1\r\n if((x >= @garea_x1 && x <= @garea_x2&& y >= @garea_y1 && y <= @garea_y2) || !graph_function )\r\n if ( @line_width == 1 )\r\n self.draw_antialias_pixel(x,y,r,g,b)\n else\r\n start_offset = -(@line_width/2) \n end_offset = (@line_width/2)\n j = start_offset\n while j<=end_offset\n self.draw_antialias_pixel(x+j,y+j,r,g,b)\n end \r\n end\r\n end\n i =i+1\r\n end\n end \n end \r\n end", "def draw_witch(x)\n move_to_top\n @witch.each do |line|\n line_at x, line\n end\n end", "def drawarrow(*)\n super\n end", "def draw_horizontal_lines_with(canvas, step_size)\n # rounded down numbers of lines.\n (y_pixels-1).times do |idx|\n draw_line(canvas, Point2f.new(0, (idx)*step_size), Point2f.new(width_pixels*step_size, (idx)*step_size))\n end\n end", "def drawDashedLine(x0,y0,x1,y1,thickness=1,color=\"grey\") ;\n @device.drawDashedLine(x0,y0,x1,y1,thickness,color) ;\n end", "def line x1, y1, x2, y2, c, aa = true\n h = self.h\n renderer.draw_line x1, h-y1-1, x2, h-y2-1, color[c], aa\n end", "def curved\n @line_type = '..'\n self\n end", "def draw_line(number)\n @dim.times do |i|\n if i+1 == number || @dim-i == number\n print draw_x\n else\n print draw_dot\n end\n end\n end", "def line(_start = nil, _finish = nil, steps: nil, inclusive: nil)\n #This is a stub, used for indexing\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hovers the widget defined by +name+ and optional +args+.
def hover(name, *args) widget(name, *args).hover end
[ "def hover(*args)\n if args.empty?\n root.hover\n else\n widget(*args).hover\n end\n end", "def hover(&blk)\n @__app__.current_slot.hover(blk)\n end", "def show_hover_alert(name = \"\", icon = 0, *args)\n if (name.nil? || name.empty?) && (icon.nil? || icon == 0)\n @hover_alert = @hover_alert_queue.empty? ? nil : @hover_alert_queue.shift\n else\n alert = MA_HoverAlert::HoverAlert.new(name, icon, *args) \n @hover_alert ? @hover_alert_queue.push(alert) : @hover_alert = alert\n end\n end", "def hover(&blk)\n @__app__.current_slot.hover(&blk)\n end", "def hover\n base.image_for(\"#{name}_hover\")\n end", "def hover_click(*args)\n if args.size == 1\n driver.action.click(element).perform\n else\n sym,id = args\n driver.action.click(driver.find_element(sym.to_sym,id)).perform\n end\n\n end", "def mouse_over(locator)\n do_command(\"mouseOver\", [locator,])\n end", "def hover(*element)\n if element.length == 1 && element[0] !~ /\\A(li|div|button|a|span)\\Z/\n element = ['li', text: element[0]]\n end\n puts \"Hovering over #{element[1][:text].inspect}...\".light_black rescue nil\n session.find(*Array(element)).hover\n end", "def lbSetTooltip _args\n \"lbSetTooltip _args;\" \n end", "def hover_over_button(text)\n # dispatch\n custom_method = \"hover_over_#{text.tr(' ', '_')}_button\"\n return send(custom_method) if respond_to?(custom_method, true)\n\n # default generic implementation\n find(\"button\", text: text).hover\n end", "def widget(name, *args)\n eventually { document.widget(name, *args) }\n end", "def double_click(name, *args)\n widget(name, *args).double_click\n end", "def right_click(name, *args)\n widget(name, *args).right_click\n end", "def mouse_over(&block)\n self.listen_to :event => :mouseover, &block\n end", "def isAutoHoverOn _args\n \"isAutoHoverOn _args;\" \n end", "def hover_element (element)\n element = element.downcase.gsub(' ', '_')\n wait_until{send(\"#{element}?\")}\n\n select = send(\"#{element}_element\")\n wait_until{select.visible?}\n\n select.hover\n end", "def draw_element(*args)\n image_to_draw = hovering? && !image_hover.nil? ? image_hover : image\n image_to_draw.draw(point.x, point.y, *args)\n end", "def widgets(name, *args)\n document.widgets(name, *args)\n end", "def hover\n synchronize { base.hover }\n self\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Double clicks the widget defined by +name+ and optional +args+.
def double_click(name, *args) widget(name, *args).double_click end
[ "def double_click(*args)\n if args.empty?\n root.double_click\n else\n widget(*args).double_click\n end\n end", "def right_click(name, *args)\n widget(name, *args).right_click\n end", "def double_click(*args)\n case args.length\n when 1 then click_image(args[0], true)\n when 2 then click_point(args[0], args[1], true)\n else raise ArgumentError\n end\n end", "def onDoubleClick _obj, _args\n \"_obj onDoubleClick _args;\" \n end", "def double_click(locator)\n do_command(\"doubleClick\", [locator,])\n end", "def double_click obj = nil\n move_mouse_to obj if obj\n Mouse.double_click\n end", "def double_click\n Bewildr::Mouse.double_click(clickable_point)\n end", "def double_click!\n fire_event :dblclick\n browser.after_hooks.run\n end", "def double_click_box\n cq = @parent.core_query(@selector)\n elem = cq[0]\n elem.double_click\n cq.done\n end", "def double_click\n element_center.double_click.perform\n end", "def click(*args)\n if args.empty?\n root.click\n else\n widget(*args).click\n end\n end", "def on_double_click(&blk)\n @on_double_action = blk\n def self.performDoubleAction(sender); @on_double_action.call(sender, self.clickedColumn, self.clickedRow); end\n setDoubleAction(\"performDoubleAction:\")\n end", "def right_click(*args)\n if args.empty?\n root.right_click\n else\n widget(*args).right_click\n end\n end", "def hover_click(*args)\n if args.size == 1\n driver.action.click(element).perform\n else\n sym,id = args\n driver.action.click(driver.find_element(sym.to_sym,id)).perform\n end\n\n end", "def double_click_at(locator,coordString)\n do_command(\"doubleClickAt\", [locator,coordString,])\n end", "def dClick\n # double click the date label instead\n @date.dClick\n end", "def double_click(element_name)\n begin\n $driver.action.double_click(el(element_name)).perform\n rescue Exception => e\n $LOG.error \"error in perform double click on element \\n element name : #{element_name} \"+e.message\n $driver.save_screenshot(\"log/webscreenshot/webScreenshot_#{$webscreenshot}.png\")\n $webscreenshot = $webscreenshot+1\n raise \"error in perform double click on element \\n element name : #{element_name} \"+e.message\n end\n end", "def double_click(locator, offset = {})\n x = offset.fetch(:x, 0)\n y = offset.fetch(:y, 0)\n\n element = find_element(locator)\n\n action\n .move_to(element, x, y)\n .double_click\n .perform\n end", "def double_click_button_with_popup_inside_frame(browser_handle, frame_prop, frame_prop_val, button_prop, button_prop_val)\n browser_handle.frame(frame_prop.intern, /#{frame_prop_val}/).button(button_prop.intern, /#{button_prop_val}/).fire_event_no_wait(\"ondblclick\")\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Right clicks the widget defined by +name+ and optional +args+.
def right_click(name, *args) widget(name, *args).right_click end
[ "def double_click(name, *args)\n widget(name, *args).double_click\n end", "def right_click(*args)\n if args.empty?\n root.right_click\n else\n widget(*args).right_click\n end\n end", "def click(*args)\n if args.empty?\n root.click\n else\n widget(*args).click\n end\n end", "def double_click(*args)\n if args.empty?\n root.double_click\n else\n widget(*args).double_click\n end\n end", "def click(*args)\n\t\t\t# if no argument has been provided, click on the\n\t\t\t# window itself\n\t\t\th = (args.length == 0) ? @handle : child(args[0]).handle\n\t\t\t\n\t\t\trectangle = [0, 0, 0, 0].pack 'LLLL'\n\t\t\tget_window_rect h, rectangle\n\t\t\tleft, top, right, bottom = rectangle.unpack 'LLLL'\n\t\t\t\n\t\t\tcenter = [(left + right) / 2, (top + bottom) / 2]\n\t\t\tset_cursor_pos *center\n\t\t\t\n\t\t\tmouse_event MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0\n\t\t\tmouse_event MOUSEEVENTF_LEFTUP, 0, 0, 0, 0\n\t\tend", "def hover_click(*args)\n if args.size == 1\n driver.action.click(element).perform\n else\n sym,id = args\n driver.action.click(driver.find_element(sym.to_sym,id)).perform\n end\n\n end", "def double_click(*args)\n case args.length\n when 1 then click_image(args[0], true)\n when 2 then click_point(args[0], args[1], true)\n else raise ArgumentError\n end\n end", "def onDoubleClick _obj, _args\n \"_obj onDoubleClick _args;\" \n end", "def right_click\n Bewildr::Mouse.right_click(clickable_point)\n end", "def right_click_element(*args)\r\n begin\r\n offset= false\r\n how = args[0]\r\n what =args[1]\r\n msg=\"\"\r\n if args.size >=3\r\n msg= args[2] + \" ---->\"\r\n end\r\n if args.size >=4\r\n offset= args[3]\r\n end\r\n if @@debug==1\r\n @util.logging(\"-->Right Clicking #{msg} #{what} of type #{how}\")\r\n end\r\n wait = Selenium::WebDriver::Wait.new(:timeout => 60)\r\n element =\"\"\r\n cb = wait.until {\r\n element = @driver.find_element(how , what)\r\n element if element.displayed?\r\n }\r\n #cb.click\r\n if @@brws !='firefox' && offset==true\r\n @driver.action.move_to(element,0,@@downOffset).click.perform\r\n elsif @@brws=='firefox'\r\n a = @driver.find_element(how, what)\r\n @driver.action.context_click(a).perform\r\n else\r\n a = @driver.find_element(how, what)\r\n @driver.action.context_click(a).perform\r\n end\r\n sleep(@@actionsleep)\r\n\r\n if what ==\"commit\" || what == \"submit\"\r\n newUrl = @driver.current_url\r\n @util.logging(\"Current URL =#{newUrl}\")\r\n end\r\n true\r\n rescue Selenium::WebDriver::Error::NoSuchElementError\r\n @util.logging \"1 Failed find element for #{how} and #{what} to click\"\r\n false\r\n rescue Selenium::WebDriver::Error::UnknownError\r\n @util.logging \"2 Failed find element for #{how} and #{what}\"\r\n false\r\n else\r\n\r\n end\r\n end", "def click; end", "def double_click(locator)\n do_command(\"doubleClick\", [locator,])\n end", "def right_click()\n right_mouse_down\n right_mouse_up\n stall :right_click\n end", "def click\n perform_action\n end", "def right_click(locator, offset = {})\n x = offset.fetch(:x, 0)\n y = offset.fetch(:y, 0)\n\n element = find_element(locator)\n action.move_to(element, x, y).context_click.perform\n end", "def _button_2_command(*args)\n\n end", "def click_button_with_name(name, opts={})\r\n find_element(:name, name).click\r\n end", "def click(text)\n click_on text\n @log.debug \" clicking #{text}\"\n end", "def click_on(*args, context: page)\n label = self.class.labels[args[0]] # attempt to get the label\n context = context.element if context.respond_to? :element\n label.present? ? context.click_on(label) : context.click_on(*args)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a widget instance for the given name.
def widget(name, *args) eventually { document.widget(name, *args) } end
[ "def get_object(name)\n gtk_builder_get_object(@builder, name)\n end", "def jmaki_load_widget(name)\n # Return previously parsed content (if any)\n if !@jmaki_widgets\n @jmaki_widgets = { }\n end\n previous = @jmaki_widgets[name]\n if previous\n return previous\n end\n content = \"\"\n filename = JMAKI_RESOURCES + name.tr('.', '/') + \"/widget.json\"\n File.open(filename, \"r\") do |file|\n while line = file.gets(nil)\n content += line\n end\n end\n current = jmaki_parse_json(content, filename)\n @jmaki_widgets[name] = current\n current\n end", "def widget(name, type_or_widget, &block)\n\t\t\t\traise ArgumentError, \"Widget name \" + name.to_s + \" already taken\" unless @widgets[name.to_sym].nil?\n\n\t\t\t\tif type_or_widget.respond_to?(:render)\n\t\t\t\t\t@widgets[name.to_sym] = type_or_widget\n\t\t\t\telse\n\t\t\t\t\traise ArgumentError, \"Widget \" + name.to_s + \" specified without block.\" if block.nil?\n\n\t\t\t\t\tbegin\n\t\t\t\t\t\tklass = Statusboard.const_get(type_or_widget.to_s.capitalize + \"Widget\")\n\t\t\t\t\trescue NameError\n\t\t\t\t\t\traise ArgumentError, \"Invalid widget type \" + type_or_widget.to_s + \" specified.\"\n\t\t\t\t\tend\n\n\t\t\t\t\t@widgets[name.to_sym] = klass.new(&block)\n\t\t\t\tend\n\t\t\tend", "def widget_name\n @widget_name\n end", "def get_control(name)\n for control in @controls\n if control[\"name\"] == name\n return control\n end\n end\n return nil\n end", "def instantiate_widget(klass)\n klass.new(self)\n end", "def widget\n NexaasID::Resources::Widget.new(api_token, config)\n end", "def get_widget_instance(widget_id)\n get_widget_instances.select{|instance| widget_id == (instance.get_param(\"widget_instance_id\").to_s)}.first\n end", "def widget_instance_by_id(instance_id)\n instances = get_widget_instances.collect{|instance|}\n get_widget_instances.select{|instance| instance.id = instance_id}.first\n end", "def netzke(name, config = {})\n ::ActiveSupport::Deprecation.warn(\"widget_class_name option is deprecated. Use class_name instead\", caller) if config[:widget_class_name]\n class_name = config[:class_name] ||= config[:widget_class_name] || name.to_s.camelcase\n config[:name] = name\n Netzke::Base.reg_widget(config)\n w = Netzke::Base.instance_by_config(config)\n w.before_load # inform the widget about initial load\n content_for :netzke_js_classes, w.js_missing_code(@rendered_classes ||= [])\n content_for :netzke_on_ready, \"#{w.js_widget_instance}\\n\\n#{w.js_widget_render}\"\n \n # Now mark this widget's class as rendered, so that we only generate it once per view\n @rendered_classes << class_name unless @rendered_classes.include?(class_name)\n\n # Return the html for this widget\n w.js_widget_html\n end", "def create_tag_widget(name)\n tag_widget = TagButton.new(@window, @tag_textview, name, @tags_editable, @tag_spacing)\n tag_widget.signal_connect(TagButton::CHANGED) { |widget, command, old_name, new_name, state| on_edited(command, old_name, new_name, state) }\n tag_widget.signal_connect(TagButton::ON_MENU) { |widget, command| on_menu(command) }\n tag_widget\n end", "def get_instance_by_name(group, name)\n get_instances(group).each {|instance|\n return instance if (instance.tags['name_s'] || \"\").casecmp(name) == 0\n return instance if (instance.tags['Name'] || \"\").casecmp(name) == 0\n }\n raise \"unknown instance: #{name} in group #{group} \"\n end", "def named(name)\n NamedMarkup.new self, name\n end", "def widget\n @widget = \"#{params[:name].camelize}Widget\".constantize.new(current_user)\n respond_to do |format|\n format.js\n end\n end", "def find_by_name name\n response = fetch \"GetShowByName/#{name}\"\n Show.new response\n end", "def find_by_name(name)\n result = MysqlAdapter.execute \"SHOW DATABASES LIKE '#{name}'\"\n row = result.fetch_row\n return nil if result.num_rows == 0\n\n instance = new\n instance.name = row[0]\n instance\n rescue Mysql::Error\n nil\n end", "def static_widget\n \n # look for existing static widget\n self.widgets.each do |widget| \n return widget if widget.name == \"Static Widget\"\n end\n \n # create widget if non-existent\n self.widgets.create({:name => \"Static Widget\", :module => \"StaticWidget\"})\n end", "def get_instance(name)\n name = name[0, 2].upcase\n cls = case name\n when 'ET'\n 'Rbeapi::Api::EthernetInterface'\n when 'PO'\n 'Rbeapi::Api::PortchannelInterface'\n when 'VX'\n 'Rbeapi::Api::VxlanInterface'\n when 'VL'\n 'Rbeapi::Api::VlanInterface'\n else\n 'Rbeapi::Api::BaseInterface'\n end\n\n return @instances[name] if @instances.include?(cls)\n instance = Rbeapi::Utils.class_from_string(cls).new(@node)\n @instances[name] = instance\n instance\n end", "def widget\n PassaporteWeb::Resources::Widget.new(api)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of widget instances for the given name.
def widgets(name, *args) document.widgets(name, *args) end
[ "def widgets(win_name)\n @driver.getQuickWidgetList(win_name).map do |java_widget|\n case java_widget.getType\n when QuickWidget::WIDGET_ENUM_MAP[:button]\n QuickButton.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:checkbox]\n QuickCheckbox.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:dialogtab]\n QuickDialogTab.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:dropdown]\n QuickDropdown.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:editfield]\n QuickEditField.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:label]\n QuickLabel.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:radiobutton]\n QuickRadioButton.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:treeview]\n QuickTreeView.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:treeitem]\n QuickTreeItem.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:thumbnail]\n QuickTreeItem.new(self,java_widget)\n else\n QuickWidget.new(self,java_widget)\n end\n end.to_a\n end", "def widgets\n names = []\n if FileTest.directory?(@path)\n FileUtils.cd(@path) { names += Dir[\"*\"] }\n end\n if FileTest.directory?(@system_path)\n FileUtils.cd(@system_path) { names += Dir[\"*\"] }\n end\n names.uniq!\n names\n end", "def widgets(window)\n\n # If window specifies window name, and the active window has this name\n # use its id to get the widgets,\n if window.is_a? String\n active_win_id = driver.getActiveQuickWindowID()\n active_win_name = driver.getQuickWindowName(active_win_id)\n\n #If the active window is of same type, then grab that one, not first\n if active_win_name == window #e.g. Both Document Window\n window = active_win_id\n end\n end\n driver.getQuickWidgetList(window).map do |java_widget|\n case java_widget.getType\n when QuickWidget::WIDGET_ENUM_MAP[:button]\n QuickButton.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:checkbox]\n QuickCheckbox.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:dialogtab]\n QuickDialogTab.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:dropdown]\n QuickDropdown.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:editfield]\n QuickEditField.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:label]\n QuickLabel.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:radiobutton]\n QuickRadioButton.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:treeview]\n QuickTreeView.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:treeitem]\n QuickTreeItem.new(self,java_widget)\n when QuickWidget::WIDGET_ENUM_MAP[:thumbnail]\n QuickTreeItem.new(self,java_widget)\n else\n QuickWidget.new(self,java_widget)\n end\n end.to_a\n end", "def all(options = {})\n widgets = []\n \n Dir.new(widgetizer_config[:widget_path_full]).entries.each do |dir|\n next if dir =~ @@dir_regex\n \n Dir.new(widgetizer_config[:widget_path_full] + '/' + dir).entries.each do |file|\n next if file =~ @@dir_regex\n \n widgets << { :name => parse_name(file), :view => get_view_html(dir, file) }\n end\n end\n \n raise widgets.pretty_inspect\n end", "def list(filter=KalturaNotImplemented, pager=KalturaNotImplemented)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'filter', filter);\n\t\t\tclient.add_param(kparams, 'pager', pager);\n\t\t\tclient.queue_service_action_call('widget', 'list', kparams);\n\t\t\tif (client.is_multirequest)\n\t\t\t\treturn nil;\n\t\t\tend\n\t\t\treturn client.do_queue();\n\t\tend", "def widgets\n project_widgets.map { |pw| pw.widgetable}\n end", "def all_widgets\n self.widgets\n end", "def widgets\n @party.get(\"reports/#{@id}/widgets\")['Widgets']\n end", "def index\n # List all widget instances, but only for the current user.\n @widget_instances = WidgetInstance.where(user_id: current_user.id)\n end", "def initialize_widgets\n @widgets = []\n\n config.widgets.each do |widget, config|\n class_name = \"Sonia::Widgets::#{widget.to_s}\"\n log.info(\"Server\") { \"Created widget #{widget} with #{config.inspect}\" }\n @widgets << module_eval(class_name).new(config)\n end\n end", "def available_widgets\n options = {:page_template => page.page_template, :block => block_type}\n UbiquoDesign::Structure.get(options)[:widgets].map(&:keys).flatten\n end", "def all_visible_widgets\n user_id = params[:id]\n api_link = VISIBLE_WIDGETS_URL + client_id + '&client_secret=' + client_secret\n response = showoff_api_call(api_link, 'get')\n @widgets = response['data']['widgets']\n code = response['code']\n flash[:error] = response['message'] if code != 0\n rescue StandardError => e\n flash[:error] = \"Something went wrong in widgets index! #{e}\"\n end", "def all_elements_by_name(name, options = {})\n default_options = {\n :count => :all,\n :from_page => :all,\n :language => session[:language]\n }\n options = default_options.merge(options)\n if options[:from_page] == :all\n elements = Element.find_all_by_name_and_public(name, true, :limit => options[:count] == :all ? nil : options[:count])\n elsif options[:from_page].class == String\n page = Page.find_by_page_layout_and_language(options[:from_page], options[:language])\n return [] if page.blank?\n elements = page.elements.find_all_by_name_and_public(name, true, :limit => options[:count] == :all ? nil : options[:count])\n else\n elements = options[:from_page].elements.find_all_by_name_and_public(name, true, :limit => options[:count] == :all ? nil : options[:count])\n end\n end", "def get_widgets_list\n dataset_array = []\n @site.contexts.each {|c| c.context_datasets.each {|d| dataset_array << d.dataset_id}}\n dataset_array.uniq!\n widgets = Widget.where(dataset_id: dataset_array)\n widgets.map{|w| {id: w.id, name: w.name, visualization: w.visualization, description: w.description}}\n end", "def get_widgets(property)\n widgets = []\n\n type = property.type\n values = property.values\n\n label = Gtk::Label.new(\"#{property.label}:\")\n label.xalign = 0\n\n widget, getter, setter = create_widget(property, type, values)\n\n val = property.get(@instance)\n setter.call(val) unless setter.nil?\n\n return [label, widget], [getter, setter, property]\n end", "def get_cards_by_name(name)\n get_all_cards.select { |slot| slot.name.match(name) }\n end", "def index\n @widgets = request_widgets(visible_widgets_url)\n end", "def get_widget_instances\n @ordered_instances ||= self.widget_instances\n @ordered_instances.each{|instance| instance.layout_section = self}\n @ordered_instances\n end", "def data_source_widgets\n [@widget]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
D: return the objects total face count.
def get_face_count count = 0 @groups.each_value do |grp| count += grp.faces.size end return count end
[ "def game_objects_count\n @game_objects.count\n end", "def count_objects\n ObjectSpace.count_objects\n end", "def count\n \n return @objects.count\n \n end", "def size() \n return @n_objects\n end", "def number_of_verts\n\t\t@number_of_verts ||= begin\n\t\t\tsize = 0\n\t\t\t@primitives.each do |primitive|\n\t\t\t\tprimitive[:verts].each do |index|\n\t\t\t\t\tvert = @verts[index]\n\t\t\t\t\tsize += vert[:vector].length\n\t\t\t\tend\n\t\t\tend\n\t\t\tsize\n\t\tend\n\tend", "def object_stats\n hsh = ObjectSpace.count_objects\n hsh.default = 0\n\n ObjectSpace.each_object do |c|\n hsh[c] += 1\n end\n\n hsh\n end", "def type_count\n @game_objects.type_count\n end", "def num_paintings\n self.paintings.count \n end", "def face_pairs_count\n face_count_values.count(2)\n end", "def size\n count = 0\n @properties.each do |gid, values|\n if ! values.empty?\n count += 1\n end\n end\n return count\n end", "def relationship_count\n count = 0\n self.people.each do |person|\n count += person.offspring.size\n count += person.spouses.size\n end\n return count\n end", "def length\n @objects.length\n end", "def get_total_stat_boxes\n return @stats.length\n end", "def object_shape_count\n ::RubyVM::YJIT.runtime_stats[:object_shape_count]\n end", "def count_entities(object_var)\n type = (object_var).typename\n case type\n when 'Edge'\n @nr_edges += 1\n when 'Face'\n @nr_faces += 1\n when 'ComponentInstance'\n @nr_cinstances += 1\n when 'Group'\n @nr_groups += 1\n when 'Image'\n @nr_images += 1\n when 'SectionPlane'\n @nr_sectionplanes += 1\n when 'DimensionLinear'\n @nr_dimensions += 1\n when 'DimensionRadial'\n @nr_dimensions += 1\n when 'Text'\n @nr_texts += 1\n when 'ConstructionLine'\n @nr_clines += 1\n when 'ConstructionPoint'\n @nr_cpoints += 1\n end\n end", "def get_total_games_played\n return games.size\n end", "def count(obj)\n `if (obj != undefined) {\n var total = 0;\n\n for (var i = 0; i < self.length; i++) {\n if (#{`self[i]` == obj}.$r) {\n total++;\n }\n }\n\n return total;\n } else {\n return self.length;\n }`\n end", "def total_people\n legislatures.map(&:person_count).inject(:+)\n end", "def shape_count\r\n \r\n return @shapes.size\r\n\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
D: Read a .obj file and turn the lines into data points to create the object.
def parse wo_lines = IO.readlines( @file_dir ) @current_group = get_group( "default" ) @current_material_name = "default" puts("+Loading .obj file:\n \"#{@file_dir.sub(ROOT, '')}\"") if @verbose # parse file context wo_lines.each do |line| tokens = line.split # make sense of the object tokens string = line.sub("\r", "") process_line(tokens[0], tokens[1..tokens.length-1], string.sub("\n", "")) end @object_name = @file_dir.split('/').last @object_name.sub!(".obj", '') # verbose status updates puts("+Object name is \"#{@object_name}\" with (#{@objects.size}) Internal Objects.") if @verbose if get_group("default").faces.empty? @groups.delete("default") end @current_group = nil @current_material_name = nil end
[ "def read_objects(file, objects)\n objects.each do |data_type|\n num = DataNumber.new.read(file).data\n\n # use i to indentify the type of object.\n num.times do ||\n _obj = data_type.new.read(file)\n end\n end\n end", "def parse\n infile = File.open @infilename\n \n while l = infile.gets do \n if l =~ /^object/ \n # we've found a line like \"object capacitor:2076 {\"\n # the index is \"capacitor:2076\"\n index = l.split[1].chomp(';')\n # the type is \"capacitor\"\n type = index.split(':')[0].chomp('{')\n \n # gather up all the lines of input that define the current object\n # into lines\n lines = []\n lines << (l = infile.gets) until l =~ /^\\s*\\}/\n # remove the last line, \"}\"\n lines.pop\n \n # see if there's a class (defined below) that corresponds to the type\n # of object we've found\n klass = Module.const_get(type.to_class_name) rescue nil\n if klass.is_a?(Class) && klass.ancestors.include?(GLMObject)\n # if there is a class corresponding to the current object type,\n # instantiate it and let it initialize itself based on #lines\n puts \"Parsing #{index}\"\n obj = klass.new lines\n obj[:name] = index if obj[:name].nil?\n \n # add the new object to the appropriate list (:nodes, :edges, etc.)\n @lists[obj.list] << obj\n \n # if the new object has a \"parent\" attribute, create and save\n # a dummy edge linking the parent to the new object\n if obj[:parent]\n dummy = Edge.dummy obj[:parent], obj[:name]\n @lists[:edges] << dummy\n end\n else\n # if there's no class corresponding to the object type, skip it\n puts \"Ignoring #{index}\"\n end\n end\n end\n \n infile.close\n end", "def populate_from_file(dec_line, infile)\n comment_count = blank_count = 0\n done = false\n \n if /^\\s*(\\w+\\s+)?object\\s+(\\w+)(:(\\d*))?\\s+{/.match(dec_line) && !$2.nil?\n @class = $2\n self[:id] = $1.strip unless $1.nil? # this will usually be nil, but some objects are named\n self[:num] = $4 unless $4.nil?\n end\n \n until done do\n l = infile.gets.strip\n case l\n when /^\\}/\n done = true\n @semicolon = l[-1] == ';'\n when ''\n self[('blank' + blank_count.to_s).to_sym] = ''\n blank_count += 1\n when /^\\/\\//\n self[('comment' + comment_count.to_s).to_sym] = l\n comment_count += 1\n when GLMWrangler::OBJ_REGEX\n push_nested self.class.new(@wrangler, {dec_line: l, infile: infile}, self)\n when /^([\\w.]+)\\s+([^;]+);(.*)$/\n # note: there will be trouble here if a property is set to a quoted\n # string that contains a ';'\n key = $1.to_sym\n self[key] = $2\n # Preserve any non-whitespace that appeared on this line after the\n # semicolon. There's no facility for editing this trailing junk,\n # it's just preserved.\n @trailing_junk[key] = $3 unless $3.empty?\n else\n raise \"Object property parser hit a line it doesn't understand: '#{l}'\"\n end\n end\n self\n end", "def load_object(filename)\n \n file = File.open(filename, 'r')\n \n while not file.eof\n a,b,c = file.read(12).unpack('N3')\n load_instruction(a, b, c)\n end\n \n end", "def convert_from_raw objects\n objects.each do | obj |\n decl = obj[:declaration].join\n if decl.count(\"(\") == 1 and decl.count(\")\") == 1\n @functions.push SourceCfunction.new(obj,@style,@filename)\n else \n @descriptions.push SourceCremark.new(obj,@style,@filename)\n end\n end\n if @descriptions.size == 0\n # inject fake header\n obj = Hash.new\n obj[:remark_prefix] = []\n obj[:remark] = [ \"/*\", \"*/\" ]\n obj[:declaration] = []\n obj[:code] = \"\"\n @descriptions.push SourceCremark.new(obj,@style,@filename)\n end\n end", "def obj_file source\n ext = @data['extensions'][@language]['source']\n obj, src = builddir(source.sub(/#{ext}$/, objext)), srcdir(source)\n d = File.dirname(obj)\n\n directory d\n file obj => [ d, src ] do\n make_object obj, src\n end\n CLEAN.include obj\n\n obj\n end", "def to_objects\n objects = []\n file = File.open(@input_path)\n CSV.table(file, {header_converters: header_converter}).each do |row|\n objects << new_object(row.to_hash)\n end\n objects\n end", "def convert_from_raw objects\n objects.each do | obj |\n if obj['kind'] == 'function'\n @functions.push TexInfoCfunction.new(obj)\n elsif obj['kind'] == 'variable'\n @variables.push TexInfoCvariable.new(obj)\n elsif obj['kind'] == 'struct'\n @structs.push TexInfoCstruct.new(obj)\n elsif obj['kind'] == 'global'\n @descriptions.push TexInfoCremark.new(obj)\n else\n raise \"Unknow type <#{obj['kind']}>\"\n end\n end\n end", "def convert_from_raw objects\n objects.each do | obj |\n if obj['kind'] == 'function'\n @functions.push DoxyCfunction.new(obj)\n elsif obj['kind'] == 'variable'\n @variables.push DoxyCvariable.new(obj)\n elsif obj['kind'] == 'struct'\n @structs.push DoxyCstruct.new(obj)\n elsif obj['kind'] == 'global'\n @descriptions.push DoxyCremark.new(obj)\n else\n raise \"Unknow type <#{obj['kind']}>\"\n end\n end\n end", "def load(obj) original_load Pa===obj ? File.read(obj.p) : obj end", "def source_file_to_object_file source_file\n source_file.pathmap(\"#{OBJECT_DIR}/%X.o\")\nend", "def read_points(points_file)\n points = []\n\n File.open \"../../samples/\" << points_file do |file|\n file.each_line do |line|\n coordinates = line.split(' ').map { |x| x.to_f }\n points << Geometry::Point.new(coordinates[0], coordinates[1])\n end\n end\n points\nend", "def load\n \tshapeArray = Array.new\n \tf = File.open(@filename, \"r\")\n \tf.each_line do |line|\n \t\twords = line.split\n \t\tnumbers = Array.new\n \t\twords.each do |word|\n\t\t\t\tnumbers.push(word.to_f)\n\t\t\tend\n\t \tif numbers[0] == 1\n \tshapeArray.push(Quad.new(numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6],numbers[7],numbers[8]))\n\t \t\telsif numbers[0] == 2\n \t\tshapeArray.push(Circle.new(numbers[1],numbers[2],numbers[1]+numbers[3],numbers[2]))\n \t\tend\n \tend\n \tf.close\n\t\treturn shapeArray\n\tend", "def read_data\r\n object = nil\r\n File.open(Filename,\"rb\") { |file| \r\n object = Marshal.load(file)\r\n }\r\n \r\n return object\r\n end", "def write_obj_file output_path\n File.open(output_path, 'w') do |f|\n @vbuffer.each_triple do |a,b,c|\n f.puts \"v #{a} #{b} #{c}\"\n end\n @vnbuffer.each_triple do |a,b,c|\n f.puts \"vn #{a} #{b} #{c}\"\n end\n @fbuffer.each_triple do |a,b,c|\n f.puts \"f #{a+1}//#{a+1} #{b+1}//#{b+1} #{c+1}//#{c+1}\"\n end\n end\n self\n end", "def load_obj_file\n if self.use_wavefrontOBJ_loader() == nil\n # there was an issue loading the object data, dont bother with the image file.\n return nil\n end\n # save the @texture refrence as its refered to later and you dont want to loose the refrence object.\n if @obj_filename != @texture_file\n file = \"Media/Textures/#{@texture_file}.png\"\n else # nest the object file, keeps the directory cleaner this way.\n file = \"Media/3dModels/#{@texture_file}/#{@texture_file}.png\"\n end\n file_dir = File.join(ROOT, file)\n image = Gosu::Image.new(file_dir, retro: true) rescue nil\n if image.nil?\n puts(\"Texture image file was not found for: #{file_dir}\")\n unless TEXTURE_DEBUG\n exit\n else\n return true\n end\n end\n @texture = Yume::Texture.new(image)\n puts(\"Using local 3D object file texture setting:\\n \\\"#{file}\\\"\")\n #--------------------------------------\n # https://www.rubydoc.info/github/gosu/gosu/master/Gosu/Image#gl_tex_info-instance_method\n # @tex_info = @texture.gl_tex_info # helper structure that contains image data\n # not very reliably held to tho, needs a proper class object formater to load images as textures.\n return true # success\n end", "def load obj\n\t\t\t\t# we need to do the nameid first, as it provides the map for later user defined properties\n\t\t\t\tif nameid_obj = obj.children.find { |child| child.name =~ NAMEID_RX }\n\t\t\t\t\t@nameid = PropertyStore.parse_nameid nameid_obj\n\t\t\t\t\t# hack to make it available to all msg files from the same ole storage object\n\t\t\t\t\t# FIXME - come up with a neater way\n\t\t\t\t\tclass << obj.ole\n\t\t\t\t\t\tattr_accessor :msg_nameid\n\t\t\t\t\tend\n\t\t\t\t\tobj.ole.msg_nameid = @nameid\n\t\t\t\telsif obj.ole\n\t\t\t\t\t@nameid = obj.ole.msg_nameid rescue nil\n\t\t\t\tend\n\t\t\t\t# now parse the actual properties. i think dirs that match the substg should be decoded\n\t\t\t\t# as properties to. 0x000d is just another encoding, the dir encoding. it should match\n\t\t\t\t# whether the object is file / dir. currently only example is embedded msgs anyway\n\t\t\t\tobj.children.each do |child|\n\t\t\t\t\tnext unless child.file?\n\t\t\t\t\tcase child.name\n\t\t\t\t\twhen PROPERTIES_RX\n\t\t\t\t\t\tparse_properties child\n\t\t\t\t\twhen SUBSTG_RX\n\t\t\t\t\t\tparse_substg(*($~[1..-1].map { |num| num.hex rescue nil } + [child]))\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend", "def load_sample_obj(filename: nil)\n # path to sample objects\n p = './spec/fixtures/sample_objects/'\n p << filename unless filename.nil?\n file_list = Dir[p + '*.txt']\n p = file_list[rand(0..file_list.size - 1)] if filename.nil?\n File.read(p)\nend", "def save_dataE(obj, filename) \r\n File.open(filename, \"wb\") { |f|\r\n Marshal.dump(obj, f)\r\n }\r\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Records when was the world seen into the world's coordinator record
def add_record(id, time = Time.now) record = find_world id @executor[id] ||= record.data[:class] == 'Dynflow::Coordinator::ExecutorWorld' record.data[:meta].update(:last_seen => self.class.format_time(time)) @world.coordinator.update_record(record) end
[ "def last_seen_at() ; info_time(:last_seen) ; end", "def record_seen(headers)\n return unless headers.include?(\"seen-by\")\n\n c_out = processor_type == \"federation\" ? \"collective\" : \"federation\"\n c_in = processor_type\n\n (headers[\"seen-by\"] ||= []) << [\n @broker.connections[c_in].connected_server.to_s,\n \"%s:%s\" % [cluster_name, instance_name],\n @broker.connections[c_out].connected_server.to_s\n ]\n end", "def stamp\n self.dateChanged = Time.now\n self.changedBy = ApplicationController.application_name\n end", "def altered_world_event; end", "def stamp_changed\n self.dateChanged = Time.now\n self.changedBy = ApplicationController.application_name\n end", "def show_now\n update_attribute(:show_annotations, Time.now)\n end", "def seen\r\n @last_seen = Time.now\r\n @times_seen += 1\r\n end", "def record_outgoing_interaction\n client&.update(\n last_interaction_at: Time.now.to_datetime,\n attention_needed_since: nil\n )\n end", "def last_seen\n @employee.entrances.where('clocked_at between ? and ?', DateTime.now.at_beginning_of_day,DateTime.now.at_end_of_day).destroy_all\n entrance = Entrance.create( employee: @employee, clocked_at: DateTime.parse(params[:at]))\n @employee.update_attributes( last_seen: entrance.clocked_at)\n entrance.update_attributes entrance_type: PRESENT\n head(:ok) and return if entrance\n head(404)\n end", "def altered_world_event\n fetch('games.control.altered_world_event')\n end", "def visited\n self.visited_at = Time.now\n self.save!\n end", "def sync_analyzer_server_date\n @logger.debug(\"++-Begin to sync server date\")\n ts=Time.now()\n @session.set_date_time(ts.year, ts.month, ts.day, ts.strftime(\"%H\").to_i, ts.strftime(\"%M\").to_i, ts.strftime(\"%S\").to_i)\n @logger.debug(\"++-end to sync server date\")\n end", "def event_history_update(date, location, attendees_hash)\n @event_log = {date => [location, attendees_hash]}\n end", "def record\n unless @actions.empty?\n $record_keeper && $record_keeper.output(self) || ActiveRecord::Base.logger.info(\"This is an historic event!\\n#{xml}\")\n @actions.clear\n end\n end", "def visible_history_start_date_time\n return @visible_history_start_date_time\n end", "def worlds_visited\n\t\t@worlds_visited\n\n\tend", "def touch_when_logging\n self.log_updated_at = Time.zone.now\n save\n end", "def tracker_was\n Tracker.find_by_id(tracker_id_was)\n end", "def stamp_changed\n return unless changed?\n\n self.dateChanged = Time.now\n self.changedBy = ApplicationController.application_name\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Looks into the cache whether the world has an executor
def executor?(id) @executor[id] end
[ "def _loaded?\n !!@executed\n end", "def cached?(name)\n @cached.include?(name)\n end", "def is_executor_for? proj\n if proj.team.team_memberships.where(:team_member_id => self.id).present?\n return (proj.team.team_memberships.where(:team_member_id => self.id).first.role == \"executor\")\n else\n return false\n end\n end", "def caching_jobs?\n !! is_caching_jobs\n end", "def cached?(identification, commands)\n clear_cache_if_stale(identification, commands)\n return caching? && File.exists?(cache_filename(identification, commands))\n end", "def create_cached_executor\r\n create_executor CACHED_EXECUTOR\r\n end", "def cached?(location)\n raise NotImplementedError\n end", "def cache_topology?\n @cache_topology\n end", "def executor!\n @executor = true\n end", "def runnable?\n self.info.has_key? :run\n end", "def cached?\n @cached.exist?\n end", "def lut_cache_exists?(name)\n !lut_read_cache_item(name, 0).nil?\n end", "def executed?\r\n @executed\r\n end", "def executing?(name)\n !stack(name).empty?\n end", "def has_location?(repo_location)\n cache.has_key? repo_location\n end", "def cached_write?\n !@used.any?\n end", "def sync_exec_required?\n Thread.current != DisplayProxy.thread\n end", "def cache_exists_and_current\n File.exists?(cache_file)\n end", "def using_cache?\n @cache ? true : false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads the coordinator record from the database and checks whether the world was last seen within the time limit
def fresh_record?(id) record = find_world(id) return false if record.nil? @executor[id] = record.data[:class] == 'Dynflow::Coordinator::ExecutorWorld' time = self.class.load_time(record.data[:meta][:last_seen]) time >= Time.now - @max_age end
[ "def check_if_possible_duplicate\n return unless self.foursquare_place_id.present?\n last_time = LocationContext.where(:user_id => self.user_id).order('created_at DESC').limit(1)\n if last_time.present? and last_time.first.foursquare_place_id == self.foursquare_place_id and last_time.first.created_at > Time.zone.now-3.hours\n self.possible_duplicate = true\n end\n end", "def data_is_recent_enough?\n # It's possible for a replica to not replay WAL data for a while,\n # despite being up to date. This can happen when a primary does not\n # receive any writes for a while.\n #\n # To prevent this from happening we check if the lag size (in bytes)\n # of the replica is small enough for the replica to be useful. We\n # only do this if we haven't replicated in a while so we only need\n # to connect to the primary when truly necessary.\n if (lag_size = replication_lag_size)\n lag_size <= load_balancer.configuration.max_replication_difference\n else\n false\n end\n end", "def add_record(id, time = Time.now)\n record = find_world id\n @executor[id] ||= record.data[:class] == 'Dynflow::Coordinator::ExecutorWorld'\n record.data[:meta].update(:last_seen => self.class.format_time(time))\n @world.coordinator.update_record(record)\n end", "def movies_stale?\n Time.new - self.movies.last.updated_at >= 900\n end", "def refresh_db_related\n return if @table_follows.empty?\n\n @first_db_entry = @table_follows.first\n @last_follow_time = @first_db_entry[:follow_time]\n end", "def last_seen\n @employee.entrances.where('clocked_at between ? and ?', DateTime.now.at_beginning_of_day,DateTime.now.at_end_of_day).destroy_all\n entrance = Entrance.create( employee: @employee, clocked_at: DateTime.parse(params[:at]))\n @employee.update_attributes( last_seen: entrance.clocked_at)\n entrance.update_attributes entrance_type: PRESENT\n head(:ok) and return if entrance\n head(404)\n end", "def store_seen_records?\n false\n end", "def existed_at?(aTime)\n return @creation >= aTime\n end", "def is_stale?\n frequency = dispatchable.frequency.name\n created_at < time_for_interval(frequency)\n end", "def reported_location_current\n reported_location_expires && \n reported_location_expires + MaxReportedLocStaleness*3600 > Time.now\n end", "def should_be_offline?\n time_ago = (update_frequency.seconds * 4.8).ago\n # Provides leeway for new stations\n if created_at > time_ago\n return false\n end\n observations.since(time_ago).order(created_at: :desc).count < 3\n end", "def online?\n self.last_seen > 15.minutes.ago\n end", "def check_timestamp\n @recent.save! if Time.now - @recent.updated_at >= 600\n end", "def in_time?\n return true unless conf['every']\n last_updated = File.mtime(\"#{DB_PATH}/#{name}\") rescue nil\n return true unless last_updated # db.file not exist\n last_updated + every <= Time.now\n end", "def fetch\n return self if last_fetch_at.present? && (Time.now.utc - self.last_fetch_at < 1.minute)\n fetch!\n end", "def existed_last_update?(game_object)\n @last_spatials.find {|previous_game_object| game_object == previous_game_object}\n end", "def old?\r\n return !blocked? && Time.now - @last_seen > 7776000\r\n end", "def online?\n (Time.now - (last_access || 1.day.ago)) <= 60\n end", "def test_location_rss_log_life_cycle\n User.current = rolf\n time = 1.minute.ago\n\n loc = Location.new(\n name: \"Test Location\",\n north: 54,\n south: 53,\n west: -101,\n east: -100,\n high: 100,\n low: 0\n )\n\n assert_nil(loc.rss_log)\n assert_save(loc)\n loc_id = loc.id\n assert_not_nil(rss_log = loc.rss_log)\n assert_equal(:location, rss_log.target_type)\n assert_equal(loc.id, loc.rss_log.location_id)\n assert_rss_log_lines(1, rss_log)\n assert_rss_log_has_tag(:log_location_created, rss_log)\n\n RssLog.update(rss_log.id, updated_at: time)\n rss_log.reload\n loc.log(:test_message, arg: \"val\")\n rss_log.reload\n assert_rss_log_lines(2, rss_log)\n assert_rss_log_has_tag(:test_message, rss_log)\n assert(rss_log.updated_at > time)\n\n RssLog.update(rss_log.id, updated_at: time)\n rss_log.reload\n Location.update(loc.id, display_name: \"New Location\")\n rss_log.reload\n assert_rss_log_lines(3, rss_log)\n assert_rss_log_has_tag(:log_location_updated, rss_log)\n assert(rss_log.updated_at > time)\n\n location_with_notes = locations(:albion)\n RssLog.update(rss_log.id, updated_at: time)\n rss_log.reload\n location_with_notes.merge(loc)\n rss_log.reload\n # (extra line for orphan title)\n assert_rss_log_lines(5, rss_log)\n assert_rss_log_has_tag(:log_location_merged, rss_log)\n assert(rss_log.updated_at > time)\n assert_nil(Location.safe_find(loc_id))\n assert_nil(rss_log.target_type)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Records when was the world with provided id last seen using a PingCache
def add_ping_cache_record(id) log Logger::DEBUG, "adding ping cache record for #{id}" @ping_cache.add_record id end
[ "def last_seen_at() ; info_time(:last_seen) ; end", "def add_record(id, time = Time.now)\n record = find_world id\n @executor[id] ||= record.data[:class] == 'Dynflow::Coordinator::ExecutorWorld'\n record.data[:meta].update(:last_seen => self.class.format_time(time))\n @world.coordinator.update_record(record)\n end", "def cache_key(id); end", "def fresh_record?(id)\n record = find_world(id)\n return false if record.nil?\n @executor[id] = record.data[:class] == 'Dynflow::Coordinator::ExecutorWorld'\n time = self.class.load_time(record.data[:meta][:last_seen])\n time >= Time.now - @max_age\n end", "def updated_sessoin id\r\n return nil unless session_exists? id\r\n @sessions[id]['lastUpdate'] = Time.now\r\n @sessions[id]\r\n end", "def cache_id; end", "def store_last_viewed( ad_id )\n session[:history] ||= []\n session[:history].delete_at(0) if session[:history].size >= 5\n session[:history] << ad_id unless session[:history].include?( ad_id )\n end", "def timestamp_cache_key\n self.class.timestamp_cache_key(id)\n end", "def last_visited\n\t Deck.find(params[:id]).update_attribute(:last_visited, DateTime.now)\n\tend", "def seen\r\n @last_seen = Time.now\r\n @times_seen += 1\r\n end", "def host(id)\r\n cache.fetch(Host.cache_key(:id, id)) do\r\n interface.hostRetrieve(id)\r\n end\r\n end", "def history(id)\n @simplegeo.records_dispatch(:get_history, id)\n end", "def time(id)\n Time.at(((id >> Rubyflake::FLAKE_TIMESTAMP_SHIFT) / 1000) + @epoch)\n end", "def cache_record(record)\n return unless @monitor_thread\n if record.is_a?(Dnsruby::RR) and\n (!record.respond_to?(:address) or Rex::Socket.is_ip_addr?(record.address.to_s)) and\n record.name.to_s.match(MATCH_HOSTNAME)\n add(record, Time.now.to_i + record.ttl)\n else\n raise \"Invalid record for cache entry - #{record.inspect}\"\n end\n end", "def last_seen(user)\n seen_when = @db.get_first_value(\"SELECT seen_at FROM last_seen WHERE user = ? COLLATE NOCASE\", user)\n puts \"Last time %s joined was last seen at timestamp \" % [user.to_s, time_ago_in_words(DateTime.parse(seen_when))]\n return \"Last time %s joined was %s ago\" % [user, time_ago_in_words(DateTime.parse(seen_when))]\n end", "def cache_key\n \"me/#{object.id}-#{object.updated_at.utc.to_s(:number)}\"\n end", "def ping(args)\r\n @server.write('PONG :' + args[:id])\r\n @pings += 1\r\n end", "def record\n @record ||= Rails.cache.fetch(\"statuses/#{id}\") { twitter_client.status(id) }\n end", "def update_last_seen\n unless session[:user_id].nil?\n logged_in_user.update_attributes({ \"last_seen\" => Time.now, \"last_ip\" => request.env['REMOTE_HOST'] })\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries to reduce the number of sent Ping requests by first looking into a cache. If the destination world is an executor world, the result is resolved solely from the cache. For client worlds the Ping might be sent if the cache record is stale.
def with_ping_request_caching(request, future) return yield unless request.is_a?(Dynflow::Dispatcher::Ping) return yield unless request.use_cache if @ping_cache.fresh_record?(request.receiver_id) future.fulfill(true) else if @ping_cache.executor?(request.receiver_id) future.reject false else yield end end end
[ "def test_pulls_from_cache_if_in_cache_and_not_expired\n actual = @apache.resolve_ip '1.1.1.1'\n\n assert_equal '1111.org', actual\n end", "def try_route_with_internal_cache(type, name)\n if host = self.cache[name]\n logger.debug \"Found '#{host}' for #{type} '#{name}' from Internal Cache.\"\n host\n else\n logger.warn \"No entry in Internal Cache...\"\n try_route_with_new_redis_connection(type, name)\n end\n end", "def status_from_cache ip\n clean_cache\n node['cloudflare']['threat_control']['status_cache'].fetch(ip)['status'].to_sym\nrescue KeyError\n # not found\n :none\nend", "def try_with_cache(obj, source, consume_all)\n beg = source.bytepos\n \n # Not in cache yet? Return early.\n unless entry = lookup(obj, beg)\n result = obj.try(source, self, consume_all)\n \n if obj.cached?\n set obj, beg, [result, source.bytepos-beg]\n end\n \n return result\n end\n\n # the condition in unless has returned true, so entry is not nil.\n result, advance = entry\n\n # The data we're skipping here has been read before. (since it is in \n # the cache) PLUS the actual contents are not interesting anymore since\n # we know obj matches at beg. So skip reading.\n source.bytepos = beg + advance\n return result\n end", "def fetch\n @raw_result = opts_for_cache_proxy[:raw] == true\n\n result = if refresh_cache?\n execute_find(@raw_result)\n elsif cached.is_a?(AridCache::CacheProxy::Result)\n if cached.has_ids? && @raw_result\n self.cached # return it unmodified\n elsif cached.has_ids?\n fetch_from_cache # return a list of active records after applying options\n else # true if we have only calculated the count thus far\n execute_find(@raw_result)\n end\n else\n cached # some base type, return it unmodified\n end\n end", "def geocoding_cache_lookup\n location = self.address\n puts self.address\n puts \"Problem related to redis might appear here, need to do more testing\"\n puts \"sidekiq running, reindex solr, then run server (fixed it on my end), maybe the redis version/Gemfile has an impact too\"\n begin\n redis = Redis.new\n #this was not finding a location but returning 0\n #so the condition was satistifed and it executed the code\n #weird\n if redis.exists(location)!=0 && !redis.get(location).nil?\n puts(redis.get(location))\n puts \"Seems like it can be Nil, should maybe put a condition to check if it's nil here (added)\"\n self.latitude, self.longitude = JSON.parse(redis.get(location))\n Rails.logger.info(\"Re-using: #{location}\")\n end\n rescue StandardError => e\n raise e unless Rails.env.production?\n puts \"Redis error: #{e.message}\"\n end\n end", "def cache_get\n result = EOAT.cache.get(@host, @uri)\n result.from_cache = true if result\n result\n end", "def get_cached_reverse_path(src, dst)\n path = HistoricalReversePath.new(src, dst)\n \n src = Inet::aton(hostname2ip[src])\n dst = Inet::aton(dst)\n old_dst = dst\n ts = 0\n \n # find matching revtrs\n begin\n \n sql = \"select * from cache_rtrs where src=#{src} and dest=#{dst} \"\n if (@@freshness_minutes > 0) then\n buffer = @@freshness_minutes\n #if max_staleness > 0 and max_staleness > @@freshness_minutes then buffer = max_staleness else buffer=@@freshness_minutes end\n sql += \" and date > from_unixtime(#{Time.now.to_i-(buffer*60)})\"\n end\n sql += \" order by date desc limit 11\"\n \n # no match, try remapping to next hop\n results = @connection.query sql\n if not results.next\n if @@do_remapping\n sql = \"select inet_ntoa(endpoint) as e, last_hop from endpoint_mappings where src=#{src} and endpoint=#{dst} limit 1\"\n results = @connection.query sql\n if not not results.next \n results.each_hash{|row|\n old_dst = dst\n dst = row[\"last_hop\"].to_i\n }\n @logger.debug { \"No matches for #{Inet::ntoa(old_dst)}, remapping endpoint to #{Inet::ntoa(dst)}\" }\n end\n \n sql = \"select * from cache_rtrs where src=#{src} and dest=#{dst} \"\n if (@@freshness_minutes > 0) then\n buffer = @@freshness_minutes\n #if max_staleness > 0 and max_staleness > @@freshness_minutes then buffer = max_staleness else buffer=@@freshness_minutes end\n sql += \" and date > from_unixtime(#{Time.now.to_i-(buffer*60)})\"\n end\n sql += \" order by date desc limit 11\"\n \n # still no match, so output the status for probing this node\n results = @connection.query sql\n end # end if do_remapping\n if not results.next \n reason = \"not yet attempted\"\n sql = \"select state, lastUpdate from isolation_target_probe_state where src=\" +\n \"#{src} and dst=#{dst}\"\n # @logger.puts sql\n begin\n results = @connection.query sql\n results.each_hash{|row|\n reason = row[\"state\"] + \" at \" + row[\"lastUpdate\"]\n }\n rescue java.lang.OutOfMemoryError => e\n raise \"OOM here! #{e.backtrace.inspect}\"\n rescue Exception\n @logger.warn { \"Error with query: #{sql}\" }\n @logger.puts $!\n end\n \n @logger.debug { \"No matches in the past #{@@freshness_minutes} minutes!\\nProbe status: #{reason}\" }\n \n path.valid = false\n path.invalid_reason = reason\n \n return path\n end\n end # not results.next == 0\n \n # ok, we have results, let's start parsing them\n results.each_hash do |row|\n ts = row[\"date\"]\n 1.upto(@@max_hops) do |i|\n val = row[\"hop\"+(i).to_s].to_i\n type = row[\"type\"+(i).to_s].to_i\n case type\n when 1..2\n type = \"rr\"\n when 3..6\n type = \"ts\"\n when 7\n type = \"sym\"\n when 8\n type = \"tr2src\"\n when 9\n type = \"dst-sym\"\n else\n type = \"unk\"\n end\n\n reasons = nil\n\n if i > 1 and (type==\"sym\" or type==\"dst-sym\")\n reasons = get_symmetric_reasons(src, val)\n end \n \n path << ReverseHop.new(Inet::ntoa(val), i, type, reasons, @ipInfo) if val > 0 or !path.empty? # empty hops also represented as 0\n end # 1.upto()\n\n break unless path.empty?\n end # results.each_hash\n rescue java.lang.OutOfMemoryError => e\n raise \"OOM here! #{e.backtrace.inspect}\"\n rescue Exception\n @logger.info { \"Error with query: #{sql}\" }\n @logger.puts $!\n end # begin\n \n path.pop while !path.empty? and path[-1].ip==\"0.0.0.0\"\n path.valid = true if !path.empty?\n # all data has been generated, add it to the object for eventual return\n path.timestamp = ts\n return path\n end", "def sync\n caches = []\n from_scratch = false\n mapped = Service.nmap\n\n return if mapped.empty?\n\n # iterate through boxes, removing any who don't respond\n # so we do not waste time sending out updates to down boxes\n mapped.delete_if do |box|\n resp = Service.net_get(\"http://#{box}:3000\")\n if resp\n c = JSON.parse(resp)\n if c.empty?\n from_scratch = true\n else\n caches << [box,c]\n end\n false\n else\n true\n end\n end\n\n if from_scratch\n newest = [`hostname`.strip,Service.discovery]\n else\n newest = caches.sort{|a,b| a.last['timestamp'] <=> b.last['timestamp']}.last\n mapped.delete_if{|x| newest.first == x}\n end\n\n puts 'Sending to: ' + mapped.inspect\n\n # perform the POST, the URI is always required\n mapped.peach do |box|\n # do a post to services/set_cache\n post_uri = URI \"http://#{box}:3000/services/set_cache\"\n post = Net::HTTP::Post.new post_uri.path\n post.set_form_data 'newest' => newest.last.to_json\n if box == `hostname`.strip\n Rails.cache.write(Service.cache_key,newest.last)\n else\n http = Net::HTTP::Persistent.new box\n http.request post_uri, post\n end\n end\n render :text => \"Caches should be synced, with #{newest.first} as the winner!\"\n end", "def do_not_cache!; end", "def cache_online(mysql_conf:, ping_time:)\n query = <<~SQL\n SELECT hostname FROM lastping WHERE ping_time = '#{ping_time}'\n SQL\n online = {}\n WIKK::SQL.connect(mysql_conf) do |sql|\n sql.each_hash(query) do |row|\n online[row['hostname']] = true\n end\n end\n return online\nend", "def _fetch\n cache_get(:_fetch) || @opts[:fetch]\n end", "def fetch(opts = {})\n fetched = opts[:ignore_cache] ? nil : fetch_cache\n fetched ||= fetch_remote\n if fetched\n @contents = fetched\n @old_contents = @contents\n save_cache if remote?\n end\n !!fetched\n end", "def do_get(request, response)\n request_path = request.unparsed_uri\n page_response = cache.get(request_path)\n\n if page_response.nil?\n destination = destination_resolver.get_destination_for_path(request_path)\n LOG.info \"cache miss, forwarding the request on to: #{destination}\"\n\n page_response = forward_request(destination)\n cache.put(request_path, page_response)\n end\n\n response.status, response.body = page_response\n end", "def lookup(request)\n resp = cache_entries_for(request)[request]\n return if resp.nil?\n\n resp.authoritative = false\n\n resp\n end", "def select_proxy(older_than=-1)\n proxy_id, proxy_ts = nil, nil\n # Select the least recently used proxy, get its timestamp, then update its timestamp\n proxy_pool_lock.lock do\n proxy_info = proxy_pool.range(0, 0, with_scores: true)\n proxy_id, proxy_ts = proxy_info.first\n touch_proxy(proxy_id)\n end\n\n begin\n threshold_ts = (Time.now - older_than.seconds).to_i\n if proxy_ts.nil?\n # We didn't find a proxy\n # Enqueue the performance analyzer for the site so that we may have\n # a proxy by the time the client requests a proxy again.\n detail_log('api', event: 'no_proxies', site: self.name)\n Resque.enqueue(Jobs::SitePerformanceAnalyzer, self.id)\n Proxy::NoProxy\n elsif proxy_ts > threshold_ts\n # The proxy we found was too recently used.\n detail_log('api',\n event: 'no_proxy_ready',\n site: self.name,\n lru_proxy_unix_time: proxy_ts,\n threshold_unix_time: threshold_ts\n )\n Proxy::NotReady.new(proxy_ts, threshold_ts, proxy_id)\n else\n Proxy.find(proxy_id)\n end\n rescue ActiveRecord::RecordNotFound => e\n Proxy::NoProxy\n end\n end", "def warm_poa_for_oldest_cached_records\n start_time = Time.zone.now\n oldest_bgs_poa_records.limit(LIMITS[:OLDEST_CACHED]).each do |bgs_poa|\n begin\n bgs_poa.save_with_updated_bgs_record! if bgs_poa.stale_attributes?\n rescue Errno::ECONNRESET, Savon::HTTPError\n # do nothing\n rescue StandardError => error\n capture_exception(error: error)\n end\n end\n datadog_report_time_segment(segment: \"warm_poa_bgs_oldest\", start_time: start_time)\n end", "def check_dns_cache dst_scheme, dst_host, dst_host_type, dst_port, dst_transport\n if dst_host_type == :domain and @conf[:use_dns_cache]\n dns_cache_key = \"#{dst_scheme}|#{dst_host}|#{dst_port}|#{dst_transport}\"\n if (result = @conf[:dns_cache][dns_cache_key])\n log_system_debug \"destination found in the DNS cache\" if $oversip_debug\n if result.is_a? ::Symbol\n rfc3263_failed result\n else\n rfc3263_succeeded result\n end\n return true\n else\n return dns_cache_key\n end\n else\n return nil\n end\n end", "def global_performance_analysis!\n cached_latest_scrape_time = latest_proxy_info.proxy_ts\n self.proxy_performances.active.each do |proxy_performance|\n disable_proxy_if_bad proxy_performance.proxy\n end\n # We only want more proxies if the site has used proxies recently\n if !cached_latest_scrape_time.nil? \\\n && cached_latest_scrape_time > (Time.now - proxy_age_timeout.seconds).to_i\n\n request_more_proxies\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /dor_masters GET /dor_masters.json
def index @dor_masters = DorMaster.all end
[ "def index\n @djrmasters = Djrmaster.all\n end", "def index\n @masters = Master.all\n end", "def index\n @nomination_masters = NominationMaster.all\n end", "def index\n @puppetmasters = Puppetmaster.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @puppetmasters }\n end\n end", "def index\n @town_masters = TownMaster.all\n end", "def index\n @building_masters = BuildingMaster.all\n end", "def index\n @masterservices = Masterservice.all\n end", "def index\n @webmasters = Webmaster.all\n end", "def index\n @site_masters = SiteMaster.all\n end", "def index\n @landmasters = Landmaster.all\n end", "def index\n @build_mirrors = BuildMirror.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @build_mirrors }\n end\n end", "def show\n @master_server = MasterServer.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @master_server }\n end\n end", "def index\n @source_masters = SourceMaster.all\n end", "def index\n @m_directors = MDirector.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @m_directors }\n end\n end", "def index\n @luxire_vendor_masters = LuxireVendorMaster.all\n end", "def index\n @distros = getmydata(\"Distro\")\n pagination\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @distros }\n end\n end", "def index\n @township_masters = TownshipMaster.all\n end", "def index\n @ac_masters = AcMaster.all\n end", "def index\n @gratuity_masters = GratuityMaster.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /dor_masters POST /dor_masters.json
def create @dor_master = DorMaster.new(dor_master_params) respond_to do |format| if @dor_master.save format.html { redirect_to @dor_master, notice: 'Dor master was successfully created.' } format.json { render :show, status: :created, location: @dor_master } else format.html { render :new } format.json { render json: @dor_master.errors, status: :unprocessable_entity } end end end
[ "def create\n @master = Master.new(master_params)\n\n respond_to do |format|\n if @master.save\n format.html { redirect_to @master, notice: \"Master was successfully created.\" }\n format.json { render :show, status: :created, location: @master }\n else\n format.html { render :new }\n format.json { render json: @master.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @master = Master.new(master_params)\n\n respond_to do |format|\n if @master.save\n format.html { redirect_to @master, notice: 'Master was successfully created.' }\n format.json { render :show, status: :created, location: @master }\n else\n format.html { render :new }\n format.json { render json: @master.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @maker_master = MakerMaster.new(maker_master_params)\n\n respond_to do |format|\n if @maker_master.save\n format.html { redirect_to @maker_master, notice: 'Maker master was successfully created.' }\n format.json { render :show, status: :created, location: @maker_master }\n else\n format.html { render :new }\n format.json { render json: @maker_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @djrmaster = Djrmaster.new(djrmaster_params)\n\n respond_to do |format|\n if @djrmaster.save\n format.html { redirect_to @djrmaster, notice: 'Djrmaster was successfully created.' }\n format.json { render :show, status: :created, location: @djrmaster }\n else\n format.html { render :new }\n format.json { render json: @djrmaster.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @regions = RegionMaster.all\n @districts = DistrictMaster.all\n\n @town_master = TownMaster.new(town_master_params)\n prefix = @town_master.name\n @town_master.town_id = TownMaster.gen_assigned_code(prefix)\n town_idd = @town_master.town_id\n\n respond_to do |format|\n if @town_master.save\n format.html { redirect_to @town_master, notice: \"Town master was successfully created.\" }\n format.json { render :show, status: :created, location: @town_master }\n else\n logger.info \"Here ===== #{@town_master.errors.messages.inspect}\"\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @town_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_master\n @rider = Rider.new(rider_params)\n @rider.rider_type = 'master'\n\n respond_to do |format|\n if @rider.save\n format.json { render :show, status: :created, location: api_v1_master_rider_url(@rider) }\n else\n format.json { render json: @rider.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @site_master = SiteMaster.new(site_master_params)\n\n respond_to do |format|\n if @site_master.save\n format.html { redirect_to @site_master, notice: 'Site master was successfully created.' }\n format.json { render :show, status: :created, location: @site_master }\n else\n format.html { render :new }\n format.json { render json: @site_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @dor_masters = DorMaster.all\n \n end", "def create\n @building_master = BuildingMaster.new(building_master_params)\n\n respond_to do |format|\n if @building_master.save\n format.html { redirect_to @building_master, notice: 'Building master was successfully created.' }\n format.json { render :show, status: :created, location: @building_master }\n else\n format.html { render :new }\n format.json { render json: @building_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @childmaster = Childmaster.new(params[:childmaster])\n\n respond_to do |format|\n if @childmaster.save\n format.html { redirect_to @childmaster, notice: 'Childmaster was successfully created.' }\n format.json { render json: @childmaster, status: :created, location: @childmaster }\n else\n format.html { render action: \"new\" }\n format.json { render json: @childmaster.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @association_master = AssociationMaster.new(association_master_params)\n\n respond_to do |format|\n if @association_master.save\n format.html { redirect_to @association_master, notice: 'Association master was successfully created.' }\n format.json { render :show, status: :created, location: @association_master }\n else\n format.html { render :new }\n format.json { render json: @association_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_master\n @rider = Rider.new(rider_params)\n @rider.rider_type = 'master'\n\n respond_to do |format|\n if @rider.save\n format.html { redirect_to master_rider_path(@rider), notice: 'Rider was successfully created.' }\n format.json { render :show_master, status: :created, location: @rider }\n else\n format.html { render :new_master }\n format.json { render json: @rider.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @township_master = TownshipMaster.new(township_master_params)\n\n respond_to do |format|\n if @township_master.save\n format.html { redirect_to @township_master, notice: 'Township master was successfully created.' }\n format.json { render :show, status: :created, location: @township_master }\n else\n format.html { render :new }\n format.json { render json: @township_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @landmaster = Landmaster.new(landmaster_params)\n \n respond_to do |format|\n if @landmaster.save\n format.html { redirect_to landmasters_path, notice: 'Landmaster was successfully created.' }\n format.json { render :show, status: :created, location: @landmaster }\n else\n format.html { render :new }\n format.json { render json: @landmaster.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @district_master = DistrictMaster.new(district_master_params)\n prefix = @district_master.name\n # @district_master.region_code = prefix[0..3].downcase\n @district_master.district_id = DistrictMaster.gen_assigned_code(prefix)\n\n @regions = RegionMaster.all\n @district_types = DistrictTypeMaster.all\n \n respond_to do |format|\n if @district_master.save\n format.html { redirect_to @district_master, notice: \"District master was successfully created.\" }\n format.json { render :show, status: :created, location: @district_master }\n else\n logger.info \"Here now ===== #{@district_master.errors.messages.inspect}\"\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @district_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @pagemaster = Pagemaster.new(pagemaster_params)\n\n respond_to do |format|\n if @pagemaster.save\n format.html { redirect_to @pagemaster, notice: 'Pagemaster was successfully created.' }\n format.json { render :show, status: :created, location: @pagemaster }\n else\n format.html { render :new }\n format.json { render json: @pagemaster.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @master_server = MasterServer.new(params[:master_server])\n\n respond_to do |format|\n if @master_server.save\n format.html { redirect_to @master_server, notice: 'Master server was successfully created.' }\n format.json { render json: @master_server, status: :created, location: @master_server }\n else\n format.html { render action: \"new\" }\n format.json { render json: @master_server.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @mastery = Mastery.new(mastery_params)\n\n respond_to do |format|\n if @mastery.save\n format.html { redirect_to masteries_url, notice: 'Mastery was successfully created.' }\n format.json { render action: 'show', status: :created, location: @mastery }\n else\n format.html { render action: 'new' }\n format.json { render json: @mastery.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @page_master = PageMaster.new(page_master_params)\n\n respond_to do |format|\n if @page_master.save\n format.html { redirect_to @page_master, notice: 'Page master was successfully created.' }\n format.json { render :show, status: :created, location: @page_master }\n else\n format.html { render :new }\n format.json { render json: @page_master.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /dor_masters/1 PATCH/PUT /dor_masters/1.json
def update respond_to do |format| if @dor_master.update(dor_master_params) format.html { redirect_to @dor_master, notice: 'Dor master was successfully updated.' } format.json { render :show, status: :ok, location: @dor_master } else format.html { render :edit } format.json { render json: @dor_master.errors, status: :unprocessable_entity } end end end
[ "def update_master\n respond_to do |format|\n if @rider.update(rider_params)\n format.json { render :show, status: :ok, location: api_v1_master_rider_url(@rider) }\n else\n format.json { render json: @rider.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @master.update(master_params)\n format.html { redirect_to @master, notice: \"Master was successfully updated.\" }\n format.json { render :show, status: :ok, location: @master }\n else\n format.html { render :edit }\n format.json { render json: @master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @master.update(master_params)\n format.html { redirect_to @master, notice: 'Master was successfully updated.' }\n format.json { render :show, status: :ok, location: @master }\n else\n format.html { render :edit }\n format.json { render json: @master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @master_data.update_attributes(params[:master_data])\n\n format.html { redirect_to edit_master_data_path(@master_data), notice: I18n.t('controllers.create_success', name: @master_data.class.model_name.human) }\n format.json { head :no_content }\n format.xml { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @master_data.errors, status: :unprocessable_entity }\n format.xml { render xml: @master_data.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @maker_master.update(maker_master_params)\n format.html { redirect_to @maker_master, notice: 'Maker master was successfully updated.' }\n format.json { render :show, status: :ok, location: @maker_master }\n else\n format.html { render :edit }\n format.json { render json: @maker_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @master_server = MasterServer.find(params[:id])\n\n respond_to do |format|\n if @master_server.update_attributes(params[:master_server])\n format.html { redirect_to @master_server, notice: 'Master server was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @master_server.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cello_master.update(cello_master_params)\n format.html { redirect_to @cello_master, notice: 'Cello master was successfully updated.' }\n format.json { render :show, status: :ok, location: @cello_master }\n else\n format.html { render :edit }\n format.json { render json: @cello_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_master\n respond_to do |format|\n if @rider.update(rider_params)\n format.html { redirect_to master_rider_path(@rider), notice: 'Rider was successfully updated.' }\n format.json { render :show_master, status: :ok, location: @rider }\n else\n format.html { render :edit_master }\n format.json { render json: @rider.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @association_master.update(association_master_params)\n format.html { redirect_to @association_master, notice: 'Association master was successfully updated.' }\n format.json { render :show, status: :ok, location: @association_master }\n else\n format.html { render :edit }\n format.json { render json: @association_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_mobile_carrier(args = {}) \n put(\"/mobile.json/#{args[:carrierId]}\", args)\nend", "def update\n @test_master = TestMaster.find(params[:id])\n\n respond_to do |format|\n if @test_master.update_attributes(params[:test_master])\n format.html { redirect_to @test_master, notice: 'Test master was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @test_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @gs1_master.update(gs1_master_params)\n format.html { redirect_to @gs1_master, notice: UPDATE_NOTICE }\n format.json { render :show, status: :ok, location: @gs1_master }\n else\n format.html { render :edit }\n format.json { render json: @gs1_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @company_master.update(company_master_params)\n format.html { redirect_to @company_master, notice: 'Company master was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render 'edit' }\n format.json { render json: @company_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @ab_master.update(ab_master_params)\n format.html { redirect_to @ab_master, notice: 'Ab master was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @ab_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @childmaster = Childmaster.find(params[:id])\n\n respond_to do |format|\n if @childmaster.update_attributes(params[:childmaster])\n format.html { redirect_to @childmaster, notice: 'Childmaster was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @childmaster.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @djrmaster.update(djrmaster_params)\n format.html { redirect_to @djrmaster, notice: 'Djrmaster was successfully updated.' }\n format.json { render :show, status: :ok, location: @djrmaster }\n else\n format.html { render :edit }\n format.json { render json: @djrmaster.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @source_master.update(source_master_params)\n format.html { redirect_to @source_master, notice: \"Source master was successfully updated.\" }\n format.json { render :show, status: :ok, location: @source_master }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @source_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @consultant_master = ConsultantMaster.find(params[:id])\n\n respond_to do |format|\n if @consultant_master.update_attributes(params[:consultant_master])\n format.html { redirect_to @consultant_master, notice: 'Consultant master was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @consultant_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @generic_master.update(generic_master_params)\n format.html { redirect_to @generic_master, notice: \"#{@generic_master.table_name.titleize.singularize} was successfully updated.\" }\n format.json { render :show, status: :ok, location: @generic_master }\n else\n format.html { render :edit }\n format.json { render json: @generic_master.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /dor_masters/1 DELETE /dor_masters/1.json
def destroy @dor_master.destroy respond_to do |format| format.html { redirect_to dor_masters_url, notice: 'Dor master was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @gs1_master.destroy\n respond_to do |format|\n format.html { redirect_to gs1_masters_url, notice: DELETE_NOTICE }\n format.json { head :no_content }\n end\n end", "def destroy\n @mastery.destroy\n respond_to do |format|\n format.html { redirect_to masteries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ab_master.destroy\n respond_to do |format|\n format.html { redirect_to ab_masters_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mast.destroy\n respond_to do |format|\n format.html { redirect_to masts_url }\n format.json { head :no_content }\n end\n end", "def delete_mobile_carrier(args = {}) \n delete(\"/mobile.json/#{args[:carrierId]}\", args)\nend", "def destroy_master\n @rider.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @hot_master.destroy\n respond_to do |format|\n format.html { redirect_to hot_masters_url, notice: DELETE_NOTICE }\n format.json { head :no_content }\n end\n end", "def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def destroy\n @regulation_master.destroy\n respond_to do |format|\n format.html { redirect_to regulation_masters_url, notice: DELETE_NOTICE }\n format.json { head :no_content }\n end\n end", "def destroy\n @master_server = MasterServer.find(params[:id])\n @master_server.destroy\n\n respond_to do |format|\n format.html { redirect_to master_servers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @master.destroy\n\n respond_to do |format|\n format.html { redirect_to masters_url, notice: \"Master was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @childmaster = Childmaster.find(params[:id])\n @childmaster.destroy\n\n respond_to do |format|\n format.html { redirect_to childmasters_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @pharmaceutical_master.destroy\n respond_to do |format|\n format.html { redirect_to pharmaceutical_masters_url, notice: DELETE_NOTICE }\n format.json { head :no_content }\n end\n end", "def destroy\n @master.destroy\n respond_to do |format|\n format.html { redirect_to masters_url, notice: 'Master was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @test_master = TestMaster.find(params[:id])\n @test_master.destroy\n\n respond_to do |format|\n format.html { redirect_to test_masters_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @district_master.destroy\n respond_to do |format|\n format.html { redirect_to district_masters_url, notice: \"District master was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def destroy\n @djrmaster.destroy\n respond_to do |format|\n format.html { redirect_to djrmasters_url, notice: 'Djrmaster was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
What is the longest height based on width of dp[i][j]
def expand(dp, i, j) height = 0 width = dp[i][j] # Up i.downto(0).each do |m| break if dp[m][j] < width height += 1 end # Down (i+1..dp.size-1).each do |m| break if dp[m][j] < width height += 1 end height*width end
[ "def size_longest_side(img, size)\n img.resize_to_fit(size)\n end", "def height\n [self.left_height, self.right_height].max\n end", "def largestRectangle(h)\n max = 0\n h.each_with_index do |element, index|\n height = 0\n # height += 1\n height += get_from_right(h[index..h.length], element)\n if index-1 >= 0\n height += get_from_right(h[0..index-1].reverse, element)\n end\n height *= element\n # p height\n # p \"============\"\n if max < height\n max = height\n end\n end\n max\nend", "def calculate_height(keymap)\n keymap.map{|coords, _size|coords.last}.max+1\n end", "def get_width(n) # returns width of the last (and largest) row\n width = 0\n n.times do |i|\n i += 1\n width += (i * n).to_s.size + 1\n end\n width\nend", "def longest_word(board)\n longest_word_length = -1\n board.each do |line|\n line.each do |word|\n longest_word_length = [word.length, longest_word_length].max\n end\n end\n longest_word_length\nend", "def maximal_square(a)\n\treturn 0 if a.size == 0 || a == nil\n\trows = a.size\n\tcols = a[0].size\n\tlargest = 0\n\tdp = Array.new(rows+1) { Array.new(cols+1) }\n\tfor i in 0..rows do\n\t\tfor j in 0..cols do\n\t\t\t# Initialize first row and column of matrix with 0\n\t\t\tif i==0 || j==0\n\t\t\t\tdp[i][j] = 0 \n\t\t\t# If matrix cell value for specific row and cell is 1, take minimum of left, right, diagonal and add 1.\n\t\t\t# As all these 3 directions should be checked and must contain 1. Store it to dp corresponding cell.\n\t\t\t# Keep track of largest matrix by comparing with dp cell value.\n\t\t\telsif a[i-1][j-1] == '1'\n\t\t\t\tdp[i][j] = [ dp[i-1][j], dp[i][j-1], dp[i-1][j-1] ].min + 1\n\t\t\t\tlargest = dp[i][j] if dp[i][j] > largest\n\t\t\t# If element equals 0 then put 0 in dp corresponding cell\n\t\t\telse\n\t\t\t\tdp[i][j] = 0\n\t\t\tend\t\n\t\tend\t\n\tend\t\n\treturn (largest*largest) # Return area by multiplying largest element to itself.\nend", "def diagonal_max(grid, rows, cols, length)\n max = 0\n # For each column\n ((length-1)...rows).each do |y|\n # Each entry in the column\n ((length-1)...cols).each do |x|\n # Multiply that entry and the length-1 entries before it and compare\n p = (0...length).inject(1) {|product, i| product * grid[y-i][x-i]}\n max = p if max < p\n end\n end\n (0...(rows-length)).each do |y|\n # Each entry in the column\n ((length-1)...cols).each do |x|\n # Multiply that entry and the length-1 entries before it and compare\n p = (0...length).inject(1) {|product, i| product * grid[y+i][x-i]}\n max = p if max < p\n end\n end\n max\n end", "def longest_slide_down(pyramid)\n slide_sum = pyramid.reverse.each.inject(0) do |sum, n|\n n.map.with_index {|val, i| val + [sum[i], sum[i+1]].max}\n end\n slide_sum[0]\nend", "def longest_slide_down(pyramid)\n pyramid.each_with_index do |row, ri|\n row.each_with_index do |elem, ei|\n next if ri < 1\n # set variables\n left = pyramid[ri - 1][ei - 1]\n right = pyramid[ri - 1][ei]\n left = left.nil? ? 0 : left\n right = right.nil? ? 0 : right\n pyramid[ri][ei] += left > right ? left : right\n end\n end\n return pyramid.last.max\nend", "def longest_key_col(data)\n data.map { |d| d[0].size + opts[:padding] + (opts[:indent] * d[2]) }.max\n end", "def vertical_max(grid, rows, cols, length)\n max = 0\n # For each column\n (0...cols).each do |x|\n # Each entry in the column\n ((length-1)...rows).each do |y|\n # Multiply that entry and the length-1 entries before it and compare\n p = ((y-length+1)..y).inject(1) {|product, i| product * grid[i][x]}\n max = p if max < p\n end\n end\n max\n end", "def max_area(heights)\n result = 0\n hs = heights.slice(0..heights.length - 1)\n until hs.length <= 1 do \n if hs.first >= hs.last\n area = hs.last * (hs.length - 1)\n result = result >= area ? result : area\n hs = hs.slice(0..hs.length - 2)\n else\n area = hs.first * (hs.length - 1)\n result = result >= area ? result : area\n hs = hs.slice(1..hs.length - 1)\n end\n end\n result\nend", "def right_width\n @buildings[(@index_max_height + 1)..-1].length\n end", "def top_to_bottom_approach\n largest_prod_of_all_cols = 0\n for each_row in (0..15)\n for each_col in (0..19)\n curr_prod_in_col = $grid_of_numbers[each_row][each_col] * $grid_of_numbers[each_row + 1][each_col] * $grid_of_numbers[each_row + 2][each_col] * $grid_of_numbers[each_row + 3][each_col]\n if curr_prod_in_col > largest_prod_of_all_cols\n largest_prod_of_all_cols = curr_prod_in_col\n end\n end\n end\n \n return largest_prod_of_all_cols\nend", "def binary_tree_height(array_tree)\n # write your code here\n result_left = 1\n result_right = 1\n\n i = 0\n while i < array_tree.length\n result_left += 1 if array_tree[2 * i + 1]\n i = 2 * i + 1\n end\n\n j = 0\n while j < array_tree.length\n result_right += 1 if array_tree[2 * j + 2]\n j = 2 * j + 2\n end\n\n [result_left, result_right].max\nend", "def getHeight\n return @board.length\n end", "def longest_slide_down(pyramid) # rubocop:disable Metrics/AbcSize\n (pyramid.size - 2).downto(0) do |row|\n 0.upto(pyramid[row].size - 1) do |col|\n pyramid[row][col] += [\n pyramid[row + 1][col] || 0,\n pyramid[row + 1][col + 1] || 0\n ].max\n end\n end\n pyramid[0][0]\nend", "def long_edge\n # return the size of the longer edge of this zone\n [self.width, self.height].max\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /announcements/new GET /announcements/new.xml
def new @announcement = Announcement.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @announcement } end end
[ "def new\n @announce = Announce.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @announce }\n end\n end", "def new\n @announce = Announce.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @announce }\n end\n end", "def new\n @announcement_type = AnnouncementType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @announcement_type }\n end\n end", "def new\n @announcement = Announcement.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @announcement }\n end\n end", "def new\n @announcement = Announcement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @announcement }\n end\n end", "def new\n @announcement = Announcement.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @announcement }\n end\n end", "def new\n @announcementcategory = Announcementcategory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @announcementcategory }\n end\n end", "def new\n @announcer = Announcer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @announcer }\n end\n end", "def new\n @annoucement = Annoucement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @annoucement }\n end\n end", "def new\n @announcement = Announcement.new\n @title = 'New announcement'\n end", "def create\n @announcement = Announcement.new(params[:announcement])\n\n respond_to do |format|\n if @announcement.save\n flash[:notice] = 'Announcement was successfully created.'\n format.html { redirect_to(@announcement) }\n format.xml { render :xml => @announcement, :status => :created, :location => @announcement }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @announcement.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @announcement = Announcement.new(params[:announcement])\n\n respond_to do |format|\n if @announcement.save\n format.html { redirect_to(@announcement, :notice => 'Announcement was successfully created.') }\n format.xml { render :xml => @announcement, :status => :created, :location => @announcement }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @announcement.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @admin_announcement = Admin::Announcement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @admin_announcement }\n end\n end", "def new\n @announce_c = AnnounceC.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @announce_c }\n end\n end", "def new\n @announcement = Announcement.new\n end", "def announce_new\n info.announce_new\n end", "def new\n @announce_i = AnnounceI.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @announce_i }\n end\n end", "def new\n @content_announcement = ContentAnnouncement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @content_announcement }\n end\n end", "def new\n @emailannouncement = Emailannouncement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @emailannouncement }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /announcements POST /announcements.xml
def create @announcement = Announcement.new(params[:announcement]) respond_to do |format| if @announcement.save flash[:notice] = 'Announcement was successfully created.' format.html { redirect_to announcements_path } format.xml { render :xml => @announcement, :status => :created, :location => @announcement } else format.html do flash[:notice] = 'Announcement was not Successfully created' render :action => "new" end format.xml { render :xml => @announcement.errors, :status => :unprocessable_entity } end end end
[ "def create\n @announcement = Announcement.new(params[:announcement])\n\n respond_to do |format|\n if @announcement.save\n flash[:notice] = 'Announcement was successfully created.'\n format.html { redirect_to(@announcement) }\n format.xml { render :xml => @announcement, :status => :created, :location => @announcement }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @announcement.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @announcement = Announcement.new(params[:announcement])\n\n respond_to do |format|\n if @announcement.save\n format.html { redirect_to(@announcement, :notice => 'Announcement was successfully created.') }\n format.xml { render :xml => @announcement, :status => :created, :location => @announcement }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @announcement.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n\t@announcement = Announcement.new(announcement_params)\n\n\trespond_to do |format|\n\t if @announcement.save\n\t\tformat.html { redirect_to @announcement, notice: 'Announcement was successfully created.' }\n\t\tformat.json { render :show, status: :created, location: @announcement }\n\t else\n\t\tformat.html { render :new }\n\t\tformat.json { render json: @announcement.errors, status: :unprocessable_entity }\n\t end\n\tend\n end", "def create\n @announcement = Announcement.new(announcement_params)\n\n respond_to do |format|\n if @announcement.save\n format.html { render html: '200' }\n format.json { render 'announcements/announcement', status: :created, announcement: @announcement }\n else\n format.html { render html: '500', status: :unprocessable_entity }\n format.json { render json: @announcement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @announcement = Announcement.new(params[:announcement])\n\n respond_to do |format|\n if @announcement.save\n flash[:notice] = I18n.t(\"{{value}} was successfully created.\", :default => \"{{value}} was successfully created.\", :value => I18n.t(\"Announcement\", :default => \"Announcement\"))\n format.html { redirect_to announcements_path }\n format.xml { render :xml => @announcement, :status => :created, :location => @announcement }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @announcement.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @announcement = Announcement.new(params[:announcement])\n\n respond_to do |format|\n if @announcement.save\n format.html { redirect_to @announcement, notice: 'Announcement was successfully created.' }\n format.json { render json: @announcement, status: :created, location: @announcement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @announcement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @announcement = Announcement.new(announcement_params)\n\n respond_to do |format|\n if @announcement.save\n format.html { redirect_to medical_entities_announcement_path(@announcement), notice: 'Announcement was successfully created.' }\n format.json { render :show, status: :created, location: @announcement }\n else\n format.html { render :new }\n format.json { render json: @announcement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @admin_announcement = Admin::Announcement.new(params[:admin_announcement])\n\n respond_to do |format|\n if @admin_announcement.save\n format.html { redirect_to @admin_announcement, notice: 'Announcement was successfully created.' }\n format.json { render json: @admin_announcement, status: :created, location: @admin_announcement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @admin_announcement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_announcement(payload)\n JSON.parse Announcement.create_announcement(@base_url, @headers, payload.to_json)\n end", "def create\n @cms_announcement = Cms::Announcement.new(cms_announcement_params)\n\n respond_to do |format|\n if @cms_announcement.save\n format.html { redirect_to @cms_announcement, notice: 'Announcement was successfully created.' }\n format.json { render :show, status: :created, location: @cms_announcement }\n else\n format.html { render :new }\n format.json { render json: @cms_announcement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @announcement_for = AnnouncementFor.new(announcement_for_params)\n\n respond_to do |format|\n if @announcement_for.save\n\n \n format.html { redirect_to @announcement_for, notice: 'Announcement for was successfully created.' }\n format.json { render :show, status: :created, location: @announcement_for }\n else\n format.html { render :new }\n format.json { render json: @announcement_for.errors, status: :unprocessable_entity }\n end\n end\n end", "def http_announce announcement\n announce announcement\n end", "def create\n @announcement_type = AnnouncementType.new(params[:announcement_type])\n\n respond_to do |format|\n if @announcement_type.save\n flash[:notice] = 'AnnouncementType was successfully created.'\n format.html { redirect_to(@announcement_type) }\n format.xml { render :xml => @announcement_type, :status => :created, :location => @announcement_type }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @announcement_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @announce = Announce.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @announce }\n end\n end", "def create_announcement\n create_announcement_helper\n return\n end", "def new\n @announcement = Announcement.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @announcement }\n end\n end", "def create\n @content_announcement = ContentAnnouncement.new(params[:content_announcement])\n\n respond_to do |format|\n if @content_announcement.save\n format.html { redirect_to content_announcements_path, notice: 'Content announcement was successfully created.' }\n format.json { render json: @content_announcement, status: :created, location: @content_announcement }\n else\n format.html { render action: \"new\" }\n format.json { render json: @content_announcement.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @announce_i = AnnounceI.new(params[:announce_i])\n\n respond_to do |format|\n if @announce_i.save\n format.html { redirect_to @announce_i, notice: 'Announce i was successfully created.' }\n format.json { render json: @announce_i, status: :created, location: @announce_i }\n else\n format.html { render action: \"new\" }\n format.json { render json: @announce_i.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @announcement = Announcement.new(announcement_params)\n @announcement.user = current_user\n if @announcement.save\n flash[:success] = 'New announcement created!'\n redirect_to announcement_path(@announcement)\n else\n flash[:error] = 'Please see errors below'\n render :new\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A utility method for escaping XML names of tags and names of attributes. xml_name_escape('1 "1___2___3" It follows the requirements of the specification:
def xml_name_escape(name) name = name.to_s return "" if name.blank? return name if name.match?(SAFE_XML_TAG_NAME_REGEXP) starting_char = name[0] starting_char.gsub!(INVALID_TAG_NAME_START_REGEXP, TAG_NAME_REPLACEMENT_CHAR) return starting_char if name.size == 1 following_chars = name[1..-1] following_chars.gsub!(INVALID_TAG_NAME_FOLLOWING_REGEXP, TAG_NAME_REPLACEMENT_CHAR) starting_char << following_chars end
[ "def xml_name_escape(name); end", "def xml_escape(input); end", "def xml_attr_escape\n replacements = {\"<\" => \"&lt;\", \">\" => \"&gt;\", \"&\" => \"&amp;\", \"\\\"\" => \"&quot;\", \"'\" => \"&apos;\"}\n gsub(/([<>&\\'\\\"])/) { replacements[$1] }\n end", "def html_attribute_name_escape(name)\n name.to_s.gsub(ATTRIBUTE_NAME_INVALID_CHARS, '-')\n end", "def escape_xml_attr(value)\n escape_xml(value).gsub(XML_ATTR_ESCAPES_RE) { |c| XML_ATTR_ESCAPES[c] }\n end", "def escape_xml(xml_in) \n return xml_in.gsub(/&/,'&amp;').gsub(/</,'&lt;')\n end", "def xml_escape(for_attribute=false)\n out = gsub(\"&\", \"&amp;\")\n out = out.gsub('\"', '&quot;').gsub(\"'\", \"&apos;\") if for_attribute\n out = out.gsub(\"<\", \"&lt;\").gsub(\">\", \"&gt;\")\n out\n end", "def escape_xml(string)\n string.gsub!(\"&\", \"&amp;\")\n string.gsub!(\"<\", \"&lt;\")\n string.gsub!(\">\", \"&gt;\")\n string.gsub!(\"'\", \"&apos;\")\n string.gsub!(\"\\\"\", \"&quot;\")\n\n return string\n end", "def escape_xml(string) \n string.gsub(/[&<>\\'\\\"]/) do | match |\n case match\n when '&' then '&amp;'\n when '<' then '&lt;'\n when '>' then '&gt;'\n when '\"' then '&quot;'\n when \"'\" then '&apos;'\n end\n end \n end", "def tagattr(name, expr, value=nil, escape=true)\n if !expr\n return ''\n elsif escape\n return \" #{name}=\\\"#{escape_xml((value || expr).to_s)}\\\"\"\n else\n return \" #{name}=\\\"#{value || expr}\\\"\"\n end\n end", "def force_correct_attribute_escaping!(node)\n return unless Nokogiri::VersionInfo.instance.libxml2?\n\n node.attribute_nodes.each do |attr_node|\n next unless LibxmlWorkarounds::BROKEN_ESCAPING_ATTRIBUTES.include?(attr_node.name)\n\n tag_name = LibxmlWorkarounds::BROKEN_ESCAPING_ATTRIBUTES_QUALIFYING_TAG[attr_node.name]\n next unless tag_name.nil? || tag_name == node.name\n\n #\n # this block is just like CGI.escape in Ruby 2.4, but\n # only encodes space and double-quote, to mimic\n # pre-2.9.2 behavior\n #\n encoding = attr_node.value.encoding\n attr_node.value = attr_node.value.gsub(/[ \"]/) do |m|\n \"%\" + m.unpack(\"H2\" * m.bytesize).join(\"%\").upcase\n end.force_encoding(encoding)\n end\n end", "def escape_xml_characters(ssml)\n # Sanitize any already escaped character to ensure they are not\n # escaped more than once.\n sanitized_input = ssml.gsub(/&amp;|&lt;|&gt;|&quot;|&apos;/, '')\n\n ssml.gsub(/([&'\"><])/) { |c| INVALID_XML_CHARACTERS_MAPPING[c] }\n end", "def escape_attr input\n escape input, attr_regexp, attr_mapping\n end", "def force_correct_attribute_escaping!(node); end", "def xml_name\n self.name.gsub(/\\s/, \"_\")\n end", "def _xml_conditional_escape(opts={})\n opts[:escape] ? self._xml_escape : self.to_s\n end", "def xml_serialize_name_proc(opts=OPTS)\n pr = if opts[:name_proc]\n opts[:name_proc]\n elsif opts[:dasherize]\n DASHERIZE\n elsif opts[:camelize]\n CAMELIZE\n else\n IDENTITY\n end\n proc{|s| \"#{pr[s]}_\"}\n end", "def escape\n gsub(/([\"\\\\])/, \"\\\\\\&\")\n end", "def escape_variable(name)\n \"$#{name}: \\\\$#{name};\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ps:dynos [QTY] DEPRECATED: use `heroku ps:scale dynos=N` scale to QTY web processes if QTY is not specified, display the number of web processes currently running Example: $ heroku ps:dynos 3 Scaling dynos... done, now running 3
def dynos # deprecation notice added to v2.21.3 on 03/16/12 display("~ `heroku ps:dynos QTY` has been deprecated and replaced with `heroku ps:scale dynos=QTY`") dynos = shift_argument validate_arguments! if dynos action("Scaling dynos") do new_dynos = api.put_dynos(app, dynos).body["dynos"] status("now running #{new_dynos}") end else app_data = api.get_app(app).body if app_data["stack"] == "cedar" raise(Heroku::Command::CommandFailed, "For Cedar apps, use `heroku ps`") else display("#{app} is running #{quantify("dyno", app_data["dynos"])}") end end end
[ "def set_dynos qty\n progress \"starting #{qty} dyno(s) \"\n\n heroku.post_ps_scale app, 'web', qty\n # heroku.set_dynos app, qty\n while true\n progress \".\"\n sleep 1.0\n dynos = heroku.get_ps(app).body\n web_synos = []\n dynos.each do |dyno|\n if dyno[\"process\"].to_s.match(/^web/) != nil && (dyno[\"state\"] == \"up\" || dyno[\"state\"] == \"idle\")\n web_synos << dyno\n end\n end\n break if web_synos.size == qty\n end\n \n progress \"done\\n\"\n end", "def scale\n app = extract_app\n current_process = nil\n changes = args.inject({}) do |hash, process_amount|\n if process_amount =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n hash[$1] = $2\n end\n hash\n end\n\n error \"Usage: heroku ps:scale web=2 worker+1\" if changes.empty?\n\n changes.each do |process, amount|\n display \"Scaling #{process} processes... \", false\n amount.gsub!(\"=\", \"\")\n new_qty = heroku.ps_scale(app, :type => process, :qty => amount)\n display \"done, now running #{new_qty}\"\n end\n end", "def resize\n app\n changes = {}\n args.each do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)=(\\d+)([xX]?)$/\n changes[$1] = { \"size\" => $2.to_i }\n end\n end\n\n if changes.empty?\n message = [\n \"Usage: heroku ps:resize PROCESS1=1X|2X [PROCESS2=1X|2X ...]\",\n \"Must specify PROCESS and SIZE to resize.\"\n ]\n error(message.join(\"\\n\"))\n end\n\n action(\"Resizing dynos and restarting specified processes\") do\n api.put_formation(app, json_encode(changes))\n end\n changes.each do |type, options|\n size = options[\"size\"]\n price = sprintf(\"%.2f\", 0.05 * size)\n display \"#{type} dynos now #{size}X ($#{price}/dyno-hour)\"\n end\n end", "def resize\n app\n change_map = {}\n\n changes = args.map do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)=(\\w+)$/\n change_map[$1] = $2\n { \"process\" => $1, \"size\" => $2 }\n end\n end.compact\n\n if changes.empty?\n message = [\n \"Usage: heroku ps:resize DYNO1=1X|2X|PX [DYNO2=1X|2X|PX ...]\",\n \"Must specify DYNO and SIZE to resize.\"\n ]\n error(message.join(\"\\n\"))\n end\n\n resp = nil\n action(\"Resizing and restarting the specified dynos\") do\n resp = api.request(\n :expects => 200,\n :method => :patch,\n :path => \"/apps/#{app}/formation\",\n :body => json_encode(\"updates\" => changes),\n :headers => {\n \"Accept\" => \"application/vnd.heroku+json; version=3\",\n \"Content-Type\" => \"application/json\"\n }\n )\n end\n\n resp.body.select {|p| change_map.key?(p['type']) }.each do |p|\n size = p[\"size\"]\n price = if size.to_i > 0\n sprintf(\"%.2f\", 0.05 * size.to_i)\n else\n sprintf(\"%.2f\", PRICES[size])\n end\n display \"#{p[\"type\"]} dynos now #{size} ($#{price}/dyno-hour)\"\n end\n end", "def scale\n change_map = {}\n\n changes = args.map do |arg|\n if change = arg.scan(/^([a-zA-Z0-9_]+)([=+-]\\d+)(?::(\\w+))?$/).first\n formation, quantity, size = change\n quantity.gsub!(\"=\", \"\") # only allow + and - on quantity\n change_map[formation] = [quantity, size]\n { \"process\" => formation, \"quantity\" => quantity, \"size\" => size}\n end\n end.compact\n\n if changes.empty?\n error(\"Usage: heroku ps:scale DYNO1=AMOUNT1[:SIZE] [DYNO2=AMOUNT2 ...]\\nMust specify DYNO and AMOUNT to scale.\")\n end\n\n action(\"Scaling dynos\") do\n # The V3 API supports atomic scale+resize, so we make a raw request here\n # since the heroku-api gem still only supports V2.\n resp = api.request(\n :expects => 200,\n :method => :patch,\n :path => \"/apps/#{app}/formation\",\n :body => json_encode(\"updates\" => changes),\n :headers => {\n \"Accept\" => \"application/vnd.heroku+json; version=3\",\n \"Content-Type\" => \"application/json\"\n }\n )\n new_scales = resp.body.\n select {|p| change_map[p['type']] }.\n map {|p| \"#{p[\"type\"]} at #{p[\"quantity\"]}:#{p[\"size\"]}\" }\n status(\"now running \" + new_scales.join(\", \") + \".\")\n end\n end", "def scale\n changes = {}\n args.each do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n changes[$1] = $2\n end\n end\n\n if changes.empty?\n error(\"Usage: heroku ps:scale PROCESS1=AMOUNT1 [PROCESS2=AMOUNT2 ...]\\nMust specify PROCESS and AMOUNT to scale.\")\n end\n\n changes.keys.sort.each do |process|\n amount = changes[process]\n action(\"Scaling #{process} processes\") do\n amount.gsub!(\"=\", \"\")\n new_qty = api.post_ps_scale(app, process, amount).body\n status(\"now running #{new_qty}\")\n end\n end\n end", "def scale\n release = options[:version]\n changes = {}\n args.each do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n changes[$1] = $2\n end\n end\n\n if changes.empty?\n error(\"Usage: heroku ps:scale PROCESS1=AMOUNT1 [PROCESS2=AMOUNT2 ...]\\nMust specify PROCESS and AMOUNT to scale.\")\n end\n\n changes.keys.sort.each do |process|\n amount = changes[process]\n action(\"Scaling #{process} processes\") do\n amount.gsub!(\"=\", \"\")\n new_qty = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/apps/#{app}/ps/scale\",\n :query => {\n 'type' => process,\n 'qty' => amount,\n 'release' => release\n }\n ).body\n status(\"now running #{new_qty}\")\n end\n end\n end", "def workers\n # deprecation notice added to v2.21.3 on 03/16/12\n display(\"~ `heroku ps:workers QTY` has been deprecated and replaced with `heroku ps:scale workers=QTY`\")\n\n workers = shift_argument\n validate_arguments!\n\n if workers\n action(\"Scaling workers\") do\n new_workers = api.put_workers(app, workers).body[\"workers\"]\n status(\"now running #{new_workers}\")\n end\n else\n app_data = api.get_app(app).body\n if app_data[\"stack\"] == \"cedar\"\n raise(Heroku::Command::CommandFailed, \"For Cedar apps, use `heroku ps`\")\n else\n display(\"#{app} is running #{quantify(\"worker\", app_data[\"workers\"])}\")\n end\n end\n end", "def scale_dynos_down(dyno_name, count, current_count)\n dynos_for_type(dyno_name).sort_by { |d| d['elapsed'] }.reverse.take(current_count - count).each do |dyno|\n run_heroku_api_command(:post_ps_stop, app, { 'ps' => dyno['process'] })\n end\n end", "def dyno\n @dyno ||= @analytics[:dynos].max_by {|name, count| count }\n end", "def get_processes\n heroku.get_ps(ENV['APP_NAME']).body.group_by do |process|\n process['process'].split('.').first\n end\nend", "def dynos_maxed_out?\n return false if @dynos_in_use.nil?\n @dynos_in_use >= NimbleNodes::Dynos.max\n end", "def start_process(n)\n heroku.post_ps(\n ENV['APP_NAME'],\n \"rake count_to[#{n}]\",\n attach: false\n )\nend", "def dynos\n dyno_data = HireFire::Resource.dynos.inject(String.new) do |json, dyno|\n json << %(,{\"name\":\"#{dyno[:name]}\",\"quantity\":#{dyno[:quantity].call || \"null\"}})\n json\n end\n\n \"[#{dyno_data.sub(\",\",\"\")}]\"\n end", "def getps\n case Facter.value(:operatingsystem)\n when 'OpenWrt'\n 'ps www'\n when 'FreeBSD', 'NetBSD', 'OpenBSD', 'Darwin', 'DragonFly'\n 'ps auxwww'\n else\n 'ps -ef'\n end\n end", "def stop\n dyno = shift_argument\n validate_arguments!\n\n message, options = case dyno\n when NilClass\n error(\"Usage: heroku ps:stop DYNO\\nMust specify DYNO to stop.\")\n when /.+\\..+/\n ps = args.first\n [\"Stopping #{ps} dyno\", { :ps => ps }]\n else\n type = args.first\n [\"Stopping #{type} dynos\", { :type => type }]\n end\n\n action(message) do\n api.post_ps_stop(app, options)\n end\n end", "def linux_worker_pids\n `ps -A -o pid,command | grep -E \"[r]esque:work|[r]esque:\\sStarting|[r]esque-[0-9]\" | grep -v \"resque-web\"`.split(\"\\n\").map do |line|\n line.split(' ')[0]\n end\n end", "def dyno_size\n @dyno_size_resource ||= DynoSize.new(@client)\n end", "def ps\n `ps haxo pid,ppid,cmd`\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ps:workers [QTY] DEPRECATED: use `heroku ps:scale workers=N` scale to QTY background processes if QTY is not specified, display the number of background processes currently running Example: $ heroku ps:dynos 3 Scaling workers... done, now running 3
def workers # deprecation notice added to v2.21.3 on 03/16/12 display("~ `heroku ps:workers QTY` has been deprecated and replaced with `heroku ps:scale workers=QTY`") workers = shift_argument validate_arguments! if workers action("Scaling workers") do new_workers = api.put_workers(app, workers).body["workers"] status("now running #{new_workers}") end else app_data = api.get_app(app).body if app_data["stack"] == "cedar" raise(Heroku::Command::CommandFailed, "For Cedar apps, use `heroku ps`") else display("#{app} is running #{quantify("worker", app_data["workers"])}") end end end
[ "def scale\n app = extract_app\n current_process = nil\n changes = args.inject({}) do |hash, process_amount|\n if process_amount =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n hash[$1] = $2\n end\n hash\n end\n\n error \"Usage: heroku ps:scale web=2 worker+1\" if changes.empty?\n\n changes.each do |process, amount|\n display \"Scaling #{process} processes... \", false\n amount.gsub!(\"=\", \"\")\n new_qty = heroku.ps_scale(app, :type => process, :qty => amount)\n display \"done, now running #{new_qty}\"\n end\n end", "def linux_worker_pids\n `ps -A -o pid,command | grep -E \"[r]esque:work|[r]esque:\\sStarting|[r]esque-[0-9]\" | grep -v \"resque-web\"`.split(\"\\n\").map do |line|\n line.split(' ')[0]\n end\n end", "def scale\n changes = {}\n args.each do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n changes[$1] = $2\n end\n end\n\n if changes.empty?\n error(\"Usage: heroku ps:scale PROCESS1=AMOUNT1 [PROCESS2=AMOUNT2 ...]\\nMust specify PROCESS and AMOUNT to scale.\")\n end\n\n changes.keys.sort.each do |process|\n amount = changes[process]\n action(\"Scaling #{process} processes\") do\n amount.gsub!(\"=\", \"\")\n new_qty = api.post_ps_scale(app, process, amount).body\n status(\"now running #{new_qty}\")\n end\n end\n end", "def worker_processes(nr)\n set_int(:worker_processes, nr, 1)\n end", "def scale\n release = options[:version]\n changes = {}\n args.each do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)([=+-]\\d+)$/\n changes[$1] = $2\n end\n end\n\n if changes.empty?\n error(\"Usage: heroku ps:scale PROCESS1=AMOUNT1 [PROCESS2=AMOUNT2 ...]\\nMust specify PROCESS and AMOUNT to scale.\")\n end\n\n changes.keys.sort.each do |process|\n amount = changes[process]\n action(\"Scaling #{process} processes\") do\n amount.gsub!(\"=\", \"\")\n new_qty = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/apps/#{app}/ps/scale\",\n :query => {\n 'type' => process,\n 'qty' => amount,\n 'release' => release\n }\n ).body\n status(\"now running #{new_qty}\")\n end\n end\n end", "def dynos\n # deprecation notice added to v2.21.3 on 03/16/12\n display(\"~ `heroku ps:dynos QTY` has been deprecated and replaced with `heroku ps:scale dynos=QTY`\")\n\n dynos = shift_argument\n validate_arguments!\n\n if dynos\n action(\"Scaling dynos\") do\n new_dynos = api.put_dynos(app, dynos).body[\"dynos\"]\n status(\"now running #{new_dynos}\")\n end\n else\n app_data = api.get_app(app).body\n if app_data[\"stack\"] == \"cedar\"\n raise(Heroku::Command::CommandFailed, \"For Cedar apps, use `heroku ps`\")\n else\n display(\"#{app} is running #{quantify(\"dyno\", app_data[\"dynos\"])}\")\n end\n end\n end", "def worker_cpus\n Gitlab['node']['cpu']['total'].to_i + 1\n end", "def solaris_worker_pids\n get_worker_pids('ps -A -o pid,args')\n end", "def workers=(n)\n if n != @workers || !known?\n p \"Scaling #{type} to #{n}\"\n heroku_set_workers(n)\n know n\n end\n end", "def workers_pids\n pgrep_result = `pgrep -f '#{WORKER_CMDLINE_PATTERN}'`.split(\"\\n\")\n return unless $CHILD_STATUS.success?\n\n pgrep_result\n end", "def worker_info\n\n (@context.storage.get('variables', 'workers') || {})['workers']\n end", "def compute_workers(ncpus)\n return 0 unless Process.respond_to?(:fork)\n\n compute_workers_from_env(LISTENER_WORKERS) ||\n compute_workers_from_env(PUMA_WORKERS) ||\n ncpus * PUMA_WORKERS_CPUMULT\n end", "def solaris_worker_pids\n `ps -A -o pid,comm | grep \"[r]uby\" | grep -v \"resque-web\"`.split(\"\\n\").map do |line|\n real_pid = line.split(' ')[0]\n pargs_command = `pargs -a #{real_pid} 2>/dev/null | grep [r]esque | grep -v \"resque-web\"`\n if pargs_command.split(':')[1] == \" resque-#{Resque::VERSION}\"\n real_pid\n end\n end.compact\n end", "def resize\n app\n changes = {}\n args.each do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)=(\\d+)([xX]?)$/\n changes[$1] = { \"size\" => $2.to_i }\n end\n end\n\n if changes.empty?\n message = [\n \"Usage: heroku ps:resize PROCESS1=1X|2X [PROCESS2=1X|2X ...]\",\n \"Must specify PROCESS and SIZE to resize.\"\n ]\n error(message.join(\"\\n\"))\n end\n\n action(\"Resizing dynos and restarting specified processes\") do\n api.put_formation(app, json_encode(changes))\n end\n changes.each do |type, options|\n size = options[\"size\"]\n price = sprintf(\"%.2f\", 0.05 * size)\n display \"#{type} dynos now #{size}X ($#{price}/dyno-hour)\"\n end\n end", "def worker_count\n return 1 if is_local_dev?\n case node[:ec2][:instance_type]\n when 'm1.small': worker_count = 2\n when 'c1.medium': worker_count = 4\n when 'c1.xlarge': worker_count = 8\n else\n worker_count = 4\n end\n worker_count\n end", "def scale\n change_map = {}\n\n changes = args.map do |arg|\n if change = arg.scan(/^([a-zA-Z0-9_]+)([=+-]\\d+)(?::(\\w+))?$/).first\n formation, quantity, size = change\n quantity.gsub!(\"=\", \"\") # only allow + and - on quantity\n change_map[formation] = [quantity, size]\n { \"process\" => formation, \"quantity\" => quantity, \"size\" => size}\n end\n end.compact\n\n if changes.empty?\n error(\"Usage: heroku ps:scale DYNO1=AMOUNT1[:SIZE] [DYNO2=AMOUNT2 ...]\\nMust specify DYNO and AMOUNT to scale.\")\n end\n\n action(\"Scaling dynos\") do\n # The V3 API supports atomic scale+resize, so we make a raw request here\n # since the heroku-api gem still only supports V2.\n resp = api.request(\n :expects => 200,\n :method => :patch,\n :path => \"/apps/#{app}/formation\",\n :body => json_encode(\"updates\" => changes),\n :headers => {\n \"Accept\" => \"application/vnd.heroku+json; version=3\",\n \"Content-Type\" => \"application/json\"\n }\n )\n new_scales = resp.body.\n select {|p| change_map[p['type']] }.\n map {|p| \"#{p[\"type\"]} at #{p[\"quantity\"]}:#{p[\"size\"]}\" }\n status(\"now running \" + new_scales.join(\", \") + \".\")\n end\n end", "def passenger_workers_details\n passenger_memory_status_path = `env -i which passenger-memory-stats`\n `env -i #{ passenger_memory_status_path }`\n end", "def get_processes\n heroku.get_ps(ENV['APP_NAME']).body.group_by do |process|\n process['process'].split('.').first\n end\nend", "def resize\n app\n change_map = {}\n\n changes = args.map do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)=(\\w+)$/\n change_map[$1] = $2\n { \"process\" => $1, \"size\" => $2 }\n end\n end.compact\n\n if changes.empty?\n message = [\n \"Usage: heroku ps:resize DYNO1=1X|2X|PX [DYNO2=1X|2X|PX ...]\",\n \"Must specify DYNO and SIZE to resize.\"\n ]\n error(message.join(\"\\n\"))\n end\n\n resp = nil\n action(\"Resizing and restarting the specified dynos\") do\n resp = api.request(\n :expects => 200,\n :method => :patch,\n :path => \"/apps/#{app}/formation\",\n :body => json_encode(\"updates\" => changes),\n :headers => {\n \"Accept\" => \"application/vnd.heroku+json; version=3\",\n \"Content-Type\" => \"application/json\"\n }\n )\n end\n\n resp.body.select {|p| change_map.key?(p['type']) }.each do |p|\n size = p[\"size\"]\n price = if size.to_i > 0\n sprintf(\"%.2f\", 0.05 * size.to_i)\n else\n sprintf(\"%.2f\", PRICES[size])\n end\n display \"#{p[\"type\"]} dynos now #{size} ($#{price}/dyno-hour)\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ps:restart [DYNO] restart an app dyno if DYNO is not specified, restarts all dynos on the app Examples: $ heroku ps:restart web.1 Restarting web.1 dyno... done $ heroku ps:restart web Restarting web dyno... done $ heroku ps:restart Restarting dynos... done
def restart dyno = shift_argument validate_arguments! message, options = case dyno when NilClass ["Restarting dynos", {}] when /.+\..+/ ps = args.first ["Restarting #{ps} dyno", { :ps => ps }] else type = args.first ["Restarting #{type} dynos", { :type => type }] end action(message) do api.post_ps_restart(app, options) end end
[ "def restart\n app = extract_app\n\n opts = case args.first\n when NilClass then\n display \"Restarting processes... \", false\n {}\n when /.+\\..+/\n ps = args.first\n display \"Restarting #{ps} process... \", false\n { :ps => ps }\n else\n type = args.first\n display \"Restarting #{type} processes... \", false\n { :type => type }\n end\n heroku.ps_restart(app, opts)\n display \"done\"\n end", "def stop\n dyno = shift_argument\n validate_arguments!\n\n message, options = case dyno\n when NilClass\n error(\"Usage: heroku ps:stop DYNO\\nMust specify DYNO to stop.\")\n when /.+\\..+/\n ps = args.first\n [\"Stopping #{ps} dyno\", { :ps => ps }]\n else\n type = args.first\n [\"Stopping #{type} dynos\", { :type => type }]\n end\n\n action(message) do\n api.post_ps_stop(app, options)\n end\n end", "def dynos\n # deprecation notice added to v2.21.3 on 03/16/12\n display(\"~ `heroku ps:dynos QTY` has been deprecated and replaced with `heroku ps:scale dynos=QTY`\")\n\n dynos = shift_argument\n validate_arguments!\n\n if dynos\n action(\"Scaling dynos\") do\n new_dynos = api.put_dynos(app, dynos).body[\"dynos\"]\n status(\"now running #{new_dynos}\")\n end\n else\n app_data = api.get_app(app).body\n if app_data[\"stack\"] == \"cedar\"\n raise(Heroku::Command::CommandFailed, \"For Cedar apps, use `heroku ps`\")\n else\n display(\"#{app} is running #{quantify(\"dyno\", app_data[\"dynos\"])}\")\n end\n end\n end", "def restart\n process = shift_argument\n validate_arguments!\n\n message, options = case process\n when NilClass\n [\"Restarting processes\", {}]\n when /.+\\..+/\n ps = args.first\n [\"Restarting #{ps} process\", { :ps => ps }]\n else\n type = args.first\n [\"Restarting #{type} processes\", { :type => type }]\n end\n\n action(message) do\n api.post_ps_restart(app, options)\n end\n end", "def set_dynos qty\n progress \"starting #{qty} dyno(s) \"\n\n heroku.post_ps_scale app, 'web', qty\n # heroku.set_dynos app, qty\n while true\n progress \".\"\n sleep 1.0\n dynos = heroku.get_ps(app).body\n web_synos = []\n dynos.each do |dyno|\n if dyno[\"process\"].to_s.match(/^web/) != nil && (dyno[\"state\"] == \"up\" || dyno[\"state\"] == \"idle\")\n web_synos << dyno\n end\n end\n break if web_synos.size == qty\n end\n \n progress \"done\\n\"\n end", "def restart\n process = shift_argument\n validate_arguments!\n release = options[:version]\n\n message, options = case process\n when NilClass\n [\"Restarting processes\", { }]\n when /.+\\..+/\n ps = args.first\n [\"Restarting #{ps} process\", { :ps => ps }]\n else\n type = args.first\n [\"Restarting #{type} processes\", { :type => type }]\n end\n\n action(message) do\n api.post_ps_restart(app, options.merge(:release => release))\n end\n end", "def kill_process(ps)\n heroku.post_ps_stop(\n ENV['APP_NAME'],\n ps: ps\n )\nend", "def resize\n app\n change_map = {}\n\n changes = args.map do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)=(\\w+)$/\n change_map[$1] = $2\n { \"process\" => $1, \"size\" => $2 }\n end\n end.compact\n\n if changes.empty?\n message = [\n \"Usage: heroku ps:resize DYNO1=1X|2X|PX [DYNO2=1X|2X|PX ...]\",\n \"Must specify DYNO and SIZE to resize.\"\n ]\n error(message.join(\"\\n\"))\n end\n\n resp = nil\n action(\"Resizing and restarting the specified dynos\") do\n resp = api.request(\n :expects => 200,\n :method => :patch,\n :path => \"/apps/#{app}/formation\",\n :body => json_encode(\"updates\" => changes),\n :headers => {\n \"Accept\" => \"application/vnd.heroku+json; version=3\",\n \"Content-Type\" => \"application/json\"\n }\n )\n end\n\n resp.body.select {|p| change_map.key?(p['type']) }.each do |p|\n size = p[\"size\"]\n price = if size.to_i > 0\n sprintf(\"%.2f\", 0.05 * size.to_i)\n else\n sprintf(\"%.2f\", PRICES[size])\n end\n display \"#{p[\"type\"]} dynos now #{size} ($#{price}/dyno-hour)\"\n end\n end", "def app_restart\n return unless restart_required?\n callback(:app_restart) do\n notify(:app_restart)\n heroku.app_restart\n end\n end", "def restart options=nil\n with_server_apps options,\n :msg => \"Running restart script\",\n :send => :restart\n end", "def restart\n ctl_proxy('restart','httpd restarted')\n end", "def resize\n app\n changes = {}\n args.each do |arg|\n if arg =~ /^([a-zA-Z0-9_]+)=(\\d+)([xX]?)$/\n changes[$1] = { \"size\" => $2.to_i }\n end\n end\n\n if changes.empty?\n message = [\n \"Usage: heroku ps:resize PROCESS1=1X|2X [PROCESS2=1X|2X ...]\",\n \"Must specify PROCESS and SIZE to resize.\"\n ]\n error(message.join(\"\\n\"))\n end\n\n action(\"Resizing dynos and restarting specified processes\") do\n api.put_formation(app, json_encode(changes))\n end\n changes.each do |type, options|\n size = options[\"size\"]\n price = sprintf(\"%.2f\", 0.05 * size)\n display \"#{type} dynos now #{size}X ($#{price}/dyno-hour)\"\n end\n end", "def restart(opts=[]) daemon('restart', opts); end", "def stop\n app = extract_app\n opt =\n if (args.first =~ /.+\\..+/)\n ps = args.first\n display \"Stopping #{ps} process... \", false\n {:ps => ps}\n elsif args.first\n type = args.first\n display \"Stopping #{type} processes... \", false\n {:type => type}\n else\n error \"Usage: heroku ps:stop PROCESS\"\n end\n\n heroku.ps_stop(app, opt)\n display \"done\"\n end", "def restart\n invoke :stop, :all => input[:all], :apps => input[:apps]\n\n line unless quiet?\n\n input[:apps].each do |app|\n unless input[:command].nil?\n app.command = input[:command]\n end\n app.update!\n end\n\n invoke :start, :all => input[:all], :apps => input[:apps],\n :debug_mode => input[:debug_mode]\n end", "def hard_restart\n Samson::ErrorNotifier.notify('Hard restarting, requests will be lost', sync: true)\n output 'Error: Sending SIGTERM to hard restart'\n Process.kill(:SIGTERM, Process.pid)\n sleep 5\n output 'Error: Sending SIGKILL to hard restart'\n Process.kill(:SIGKILL, Process.pid)\n end", "def restart_unicorn\n %Q%\n #{duplicate_unicorn}\n\n sleep #{unicorn_restart_sleep_time}; # in order to wait for the (old) pidfile to show up\n\n if #{old_unicorn_is_running?}; then\n #{unicorn_send_signal('QUIT', get_old_unicorn_pid)};\n fi;\n %\n end", "def restart_unicorn\n stop_unicorn\n start_unicorn\nend", "def restart_service\n service 'consul-haproxy' do\n action :restart\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ps:stop DYNOS stop an app dyno Examples: $ heroku stop run.3 Stopping run.3 dyno... done $ heroku stop run Stopping run dynos... done
def stop dyno = shift_argument validate_arguments! message, options = case dyno when NilClass error("Usage: heroku ps:stop DYNO\nMust specify DYNO to stop.") when /.+\..+/ ps = args.first ["Stopping #{ps} dyno", { :ps => ps }] else type = args.first ["Stopping #{type} dynos", { :type => type }] end action(message) do api.post_ps_stop(app, options) end end
[ "def kill_process(ps)\n heroku.post_ps_stop(\n ENV['APP_NAME'],\n ps: ps\n )\nend", "def stop\n app = extract_app\n opt =\n if (args.first =~ /.+\\..+/)\n ps = args.first\n display \"Stopping #{ps} process... \", false\n {:ps => ps}\n elsif args.first\n type = args.first\n display \"Stopping #{type} processes... \", false\n {:type => type}\n else\n error \"Usage: heroku ps:stop PROCESS\"\n end\n\n heroku.ps_stop(app, opt)\n display \"done\"\n end", "def stop\n process = shift_argument\n validate_arguments!\n\n message, options = case process\n when NilClass\n error(\"Usage: heroku ps:stop PROCESS\\nMust specify PROCESS to stop.\")\n when /.+\\..+/\n ps = args.first\n [\"Stopping #{ps} process\", { :ps => ps }]\n else\n type = args.first\n [\"Stopping #{type} processes\", { :type => type }]\n end\n\n action(message) do\n api.post_ps_stop(app, options)\n end\n end", "def dynos\n # deprecation notice added to v2.21.3 on 03/16/12\n display(\"~ `heroku ps:dynos QTY` has been deprecated and replaced with `heroku ps:scale dynos=QTY`\")\n\n dynos = shift_argument\n validate_arguments!\n\n if dynos\n action(\"Scaling dynos\") do\n new_dynos = api.put_dynos(app, dynos).body[\"dynos\"]\n status(\"now running #{new_dynos}\")\n end\n else\n app_data = api.get_app(app).body\n if app_data[\"stack\"] == \"cedar\"\n raise(Heroku::Command::CommandFailed, \"For Cedar apps, use `heroku ps`\")\n else\n display(\"#{app} is running #{quantify(\"dyno\", app_data[\"dynos\"])}\")\n end\n end\n end", "def scale_dynos_down(dyno_name, count, current_count)\n dynos_for_type(dyno_name).sort_by { |d| d['elapsed'] }.reverse.take(current_count - count).each do |dyno|\n run_heroku_api_command(:post_ps_stop, app, { 'ps' => dyno['process'] })\n end\n end", "def stop! options=nil\n with_server_apps options,\n :msg => \"Running stop script\",\n :send => :stop!\n end", "def stop options=nil\n with_server_apps options,\n :msg => \"Running stop script\",\n :send => :stop\n end", "def stop\n system(\"ps -aux | grep rackup\")\n puts \"Stoping clusters...\"\n for app in @apps\n if @env == :deployment\n pid_file = \"#{APP_PATH}/log/doozer.#{app[:port]}.pid\"\n puts \"=> Reading pid from #{pid_file}\" \n if File.exist?(pid_file)\n File.open(pid_file, 'r'){ | f | \n pid = f.gets.to_i\n puts \"=> Shutting down process #{pid}\"\n system(\"kill -9 #{pid}\")\n\n }\n File.delete(pid_file) \n else\n puts \"ERROR => pid file doesn't exist\"\n end\n end\n end\n sleep(1)\n system(\"ps -aux | grep rackup\")\nend", "def _stop_cmd\n exit_on_failure stop_cmd, STOP_FAILED_CODE,\n \"Could not kill #{@name} pid for #{@app.name}\"\n end", "def stop(opts=[]) daemon('stop', opts); end", "def restart\n dyno = shift_argument\n validate_arguments!\n\n message, options = case dyno\n when NilClass\n [\"Restarting dynos\", {}]\n when /.+\\..+/\n ps = args.first\n [\"Restarting #{ps} dyno\", { :ps => ps }]\n else\n type = args.first\n [\"Restarting #{type} dynos\", { :type => type }]\n end\n\n action(message) do\n api.post_ps_restart(app, options)\n end\n end", "def stop\n ctl_proxy('stop','httpd stopped')\n end", "def set_dynos qty\n progress \"starting #{qty} dyno(s) \"\n\n heroku.post_ps_scale app, 'web', qty\n # heroku.set_dynos app, qty\n while true\n progress \".\"\n sleep 1.0\n dynos = heroku.get_ps(app).body\n web_synos = []\n dynos.each do |dyno|\n if dyno[\"process\"].to_s.match(/^web/) != nil && (dyno[\"state\"] == \"up\" || dyno[\"state\"] == \"idle\")\n web_synos << dyno\n end\n end\n break if web_synos.size == qty\n end\n \n progress \"done\\n\"\n end", "def stop_webrick\n res = `ps aux | grep [r]uby | grep [s]cript/server`\n pid = res.split[1]\n return unless pid\n puts \"#{$0} STOPPING WEBRick pid=#{pid}\"\n Process.kill \"KILL\", pid.to_i\n end", "def stop_apt_services()\n\t@pids.each do |app_name, pid|\n\t begin\n\t\tif !pid.nil? && pid > 0\n\t\t Process.kill('TERM', pid)\n\t\t puts \"[#{Time.now.strftime('%T.%L')}] Stopped #{app_name}\"\n\t\tend\n\t rescue\n\t\t# Process wasn't running\n\t end\n\t @pids[app_name] = 0\n\tend\n end", "def stop\n # use pid in controlling process, webrick in server process\n @webrick.shutdown if @webrick\n Process.kill('INT', @pid) if @pid\n end", "def server_stop\n Process.kill 'INT', 0\n end", "def stop_app (app_name)\n if is_app_running?(app_name)\n #TODO 4: insert command for stopping the app\n command = \"cf stop #{app_name}\"\n log_message = \"- 4) Stopping #{app_name}\"\n\n execute_cf_command(command, log_message)\n end\n end", "def stop_server(type, date)\n Shell.execute \"stop #{upstart_script_filename(type, date).gsub(/^#{script_directory}\\//, '').gsub(/\\.conf$/, '')}\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
ps:type [TYPE | DYNO=TYPE [DYNO=TYPE ...]] manage dyno types called with no arguments shows the current dyno type called with one argument sets the type where type is one of free|hobby|standard1x|standard2x|performance called with 1..n DYNO=TYPE arguments sets the type per dyno
def type requires_preauth app formation = get_formation changes = if args.any?{|arg| arg =~ /=/} args.map do |arg| if arg =~ /^([a-zA-Z0-9_]+)=([\w-]+)$/ type, new_size = $1, $2 current_p = formation.find{|f| f["type"] == type} if current_p.nil? error("Type '#{type}' not found in process formation.") end p = current_p.clone p["size"] = new_size p end end.compact elsif args.any? size = shift_argument.downcase validate_arguments! formation.map{|p| p["size"] = size; p} end scale_dynos(formation, changes) if changes display_dyno_type_and_costs(get_formation) end
[ "def dynos\n # deprecation notice added to v2.21.3 on 03/16/12\n display(\"~ `heroku ps:dynos QTY` has been deprecated and replaced with `heroku ps:scale dynos=QTY`\")\n\n dynos = shift_argument\n validate_arguments!\n\n if dynos\n action(\"Scaling dynos\") do\n new_dynos = api.put_dynos(app, dynos).body[\"dynos\"]\n status(\"now running #{new_dynos}\")\n end\n else\n app_data = api.get_app(app).body\n if app_data[\"stack\"] == \"cedar\"\n raise(Heroku::Command::CommandFailed, \"For Cedar apps, use `heroku ps`\")\n else\n display(\"#{app} is running #{quantify(\"dyno\", app_data[\"dynos\"])}\")\n end\n end\n end", "def set_dynos qty\n progress \"starting #{qty} dyno(s) \"\n\n heroku.post_ps_scale app, 'web', qty\n # heroku.set_dynos app, qty\n while true\n progress \".\"\n sleep 1.0\n dynos = heroku.get_ps(app).body\n web_synos = []\n dynos.each do |dyno|\n if dyno[\"process\"].to_s.match(/^web/) != nil && (dyno[\"state\"] == \"up\" || dyno[\"state\"] == \"idle\")\n web_synos << dyno\n end\n end\n break if web_synos.size == qty\n end\n \n progress \"done\\n\"\n end", "def dyno\n @dyno ||= @analytics[:dynos].max_by {|name, count| count }\n end", "def describe_scaling_process_types()\n request({\n 'Action' => 'DescribeScalingProcessTypes',\n :idempotent => true,\n :parser => Fog::Parsers::AWS::AutoScaling::DescribeScalingProcessTypes.new\n })\n end", "def dyno_map\n {\n \"Standard-1X\": \"Private-S\",\n \"Standard-2X\": \"Private-S\",\n \"Performance-M\": \"Private-M\",\n \"Performance-L\": \"Private-L\",\n }\n end", "def stop\n dyno = shift_argument\n validate_arguments!\n\n message, options = case dyno\n when NilClass\n error(\"Usage: heroku ps:stop DYNO\\nMust specify DYNO to stop.\")\n when /.+\\..+/\n ps = args.first\n [\"Stopping #{ps} dyno\", { :ps => ps }]\n else\n type = args.first\n [\"Stopping #{type} dynos\", { :type => type }]\n end\n\n action(message) do\n api.post_ps_stop(app, options)\n end\n end", "def possible_types; end", "def cmd_types argv\n setup argv\n response = @api.types\n msg response\n return response\n end", "def make_type(type)\n if type == \"todo\"\n desc = cli_interface.ask \"What is the task\"\n due = cli_interface.ask \"When is it due?\"\n priority = cli_interface.ask \"How important is it? low, medium or high?\"\n list.add(type, desc ,due:due, priority:priority)\n elsif type == \"link\"\n url = cli_interface.ask \"What is the url?\"\n site = cli_interface.ask \"What is the site?\"\n list.add(type, url,site_name: site)\n else\n desc = cli_interface.ask \"What is the event?\"\n date_start = cli_interface.ask \"What is the start date?\"\n date_end = cli_interface.ask \"What is the end date?\"\n list.add(type,desc,start_date:date_start,end_date:date_end)\n end\n puts \"Printing new list with changes\"\n puts list.all\n end", "def sproc_type=(type)\n @sproc_type = type\n @opts[:sql] = ''\n end", "def my_type()\n\t\tputs \"I am a #{@type} robot.\"\n\tend", "def type\n types = [\"page\", \"background_page\", \"service_worker\", \"browser\"]\n if types.include? target_info[\"type\"]\n target_info[\"type\"]\n else\n \"other\"\n end\n end", "def default_process_types\n raise \"must subclass\"\n end", "def available_types\n # TODO pull this from DB or config\n [\n :kiosk,\n :ride,\n :store,\n :restaurant\n ]\n end", "def post_type\n @type = params[:type].blank? ? \"Post\" : params[:type]\n @type.constantize\n end", "def type\n @props[:type]\n end", "def generate_puppet_type_list\n @items = Registry.all(:puppet_type).sort_by { |t| t.name.to_s }\n @list_title = 'Resource Type List'\n @list_type = 'puppet_type'\n generate_list_contents\nend", "def set_type_counts\n vars = \"\"\n Repo::REPO_TYPES.each do |t|\n vars << \"@#{t}_count = #{t.camelize.constantize}.count;\"\n end\n eval(vars)\n end", "def prepare_type\n @type = params[:type]\n @klass = @type.constantize\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds multiple Populator::Record instances and calls save_records them when :per_query limit option is reached.
def build_records(amount, per_query, &block) amount.times do record = Record.new(@model_class, last_id_in_database + @records.size + 1) @records << record block.call(record) if block save_records if @records.size >= per_query end end
[ "def build_records(amount, &block)\n amount.times do\n record = Record.new(@collection)\n block.call(record) if block\n @records << record.attributes.delete_if {|k,v| v.is_a?(MongoSkip) }\n save_records \n end\n end", "def create_retrievals\n work_ids = Work.pluck(:id)\n existing_ids = RetrievalStatus.where(:source_id => id).pluck(:work_id)\n\n (0...work_ids.length).step(1000) do |offset|\n ids = work_ids[offset...offset + 1000] & existing_ids\n InsertRetrievalJob.perform_later(self, ids)\n end\n end", "def save_records\n unless @records.empty?\n @model_class.connection.populate(@model_class.quoted_table_name, columns_sql, rows_sql_arr, \"#{@model_class.name} Populate\")\n @last_id_in_database = @records.last.id\n @records.clear\n end\n end", "def run\r\n ridFieldName = @qbc.lookupFieldNameFromID( \"3\")\r\n records = Records.new\r\n @qbc.iterateRecords(@dbid,@qbc.getFieldNames(@dbid),nil,@id,nil,qyclst()){|qb_record|\r\n record = Record.new\r\n record.build(@qbc,ridFieldName, qb_record)\r\n records << record\r\n }\r\n records\r\n end", "def create_batch!(_records)\n # no-op, can be overwritten\n end", "def mediators_for_new_records\n _generate_thread_local(mediator_new_array_key, Array)\n end", "def setup_records\n self.records = []\n self.responce.each do |r|\n self.records << self.record_class.new(r)\n end\n return(self.records)\n end", "def create_retrievals\n article_ids = RetrievalStatus.where(:source_id => id).pluck(:article_id)\n\n (0...article_ids.length).step(1000) do |offset|\n ids = article_ids[offset...offset + 1000]\n delay(priority: 2, queue: \"retrieval-status\").insert_retrievals(ids)\n end\n end", "def batch_create\n @values = record_batch_params.values.reject { |p| p.values.all?(&:blank?) }\n @records = record_class.create(@values)\n\n respond_to do |format|\n if @records.all?(&:valid?)\n format.html { redirect_to url_for(action: 'index'), notice: \"#{record_class.model_name.plural.humanize} were successfully created.\" }\n format.json { render :index, status: :created }\n else\n @records = @records.fill(@records.size..BATCH_SIZE) { record_class.new }\n\n format.html { render :batch_new }\n format.json { render json: @records.map(&:errors), status: :unprocessable_entity }\n end\n end\n end", "def new_records monitor, opts = {}\n sql = \"SELECT \" + new_records_select(monitor) +\n \"\\nFROM \" + new_records_from(monitor,opts) +\n \"\\nWHERE \" + new_records_where(monitor) +\n \";\"\n @db.connect do\n #require 'ruby-debug'\n puts sql if @opts[:d]\n ## special case for union where we might have\n # hundreds of millions of record taht can't fit\n # into memory\n if @opts[:union] || !@sql_fetch_all\n @db.con.query_with_result = false\n @db.query(sql)\n res = @db.con.use_result\n else\n res = @db.query(sql)\n ## sends back the number of rows to the caller \n ## so it can update progression in real time\n opts[:proc].call(res.num_rows) if opts[:proc]\n Logger.<<(__FILE__,\"INFO\",\"Retrieved #{res.num_rows} records to be analyzed from #{@source.name} ...\")\n end\n res.each_hash do |row|\n yield RubyUtil::symbolize(row)\n end\n\n #debugger if @opts[:d]\n if @opts[:union] || !@sql_fetch_all\n res.free\n @db.con.query_with_result = true\n end\n end\n end", "def get_records_for(options={})\n sql, records_info = build_query_for(options)\n records = execute_query(sql)\n record_set = build_record_set(records)\n options[:instance_order] = records_info[:instance_ids] if options[:entity]\n records = record_set_to_json(record_set, options)\n # if the records are for an entity, build proper structure\n if options[:entity]\n instances = {}\n \n instances[:total_resources] = records_info[:total_resources]\n instances[:resources_returned] = records_info[:resources_returned]\n instances[:start_index] = options[:start_index].to_i\n instances[:order_by] = options[:order_by]\n instances[:direction] = options[:direction].downcase if options[:direction]\n instances[:resources] = records\n instances[:resource_type] = 'instance'\n return instances \n else\n #records[:resource_type] = 'instance'\n return records\n end\n end", "def fill_recs(opts={})\n opts = {\n :per_page => 20\n }.update(opts)\n per_page = opts[:per_page]\n opts.delete(:per_page)\n options = generate_search_options(:search)\n \n #if there's a manual filter then we have to and it to any conditions that allready exist\n if current_user_can?(:sqlSearchBoxes) && !@search_params[:manual_filters].blank?\n options ||= {}\n if options[:conditions].blank?\n options[:conditions] = @search_params[:manual_filters]\n else\n and_it = \"(#{options[:conditions]}) and (#{@search_params[:manual_filters]})\"\n # if it's an array then the condition string is at the 0th position (i.e. like for ActiveRecord.find)\n # otherwise the condition should be a string\n case options[:conditions]\n when Array\n options[:conditions][0] = and_it\n when String\n options[:conditions] = and_it\n end\n end\n end\n if options || @display_all\n options ||= {}\n options.update(opts) # pass any other options through to Record.search\n @records = Record.search(options)\n unless @records.empty?\n @records = @records.sort_by{|r| apply_sort_rule(r) } \n @records.reverse! if @search_params[:desc] || @search_params[:order_current] =~ /DESC/\n end\n end\n @records ||= []\n @records = @records.paginate(:page => @search_params[:page],:per_page => per_page) if @search_params[:paginate]=='yes' && !@records.empty?\n end", "def fill_and_order_records(opts)\n options = {:per_page => 20}.update(opts)\n #This method uses Record.gather, which pulls un-filtered records out of the database and then filters them via ruby.\n search_rules = generate_search_options(:locate)\n if current_user_can?(:sqlSearchBoxes) && !@search_params[:manual_filters].blank?\n search_rules = search_rules.nil? ? @search_params[:manual_filters] : \"(#{search_rules}) and (#{@search_params[:manual_filters]})\"\n end\n if search_rules || @display_all\n if @records\n options = {:filters => search_rules,:records => @records}.update(options)\n @records = Record.gather(options)\n else\n options = {:filters => search_rules,:workflow_state_filter => @search_params[:status]}.update(options)\n @records = Listings.get_list(@listing_name, options)\n end\n unless @records.empty?\n if @search_params['on_main'] == 'my_records'\n @records.delete_if{|r| \n @use_createdby_workflows.include?(r.workflow_state) ? \n !@ids_to_check.include?(r.H_CreatedBy) : \n !@ids_to_check.include?(r.H_ClaimedBy) } \n end\n unless @records.empty?\n @records = @records.sort_by{|r| apply_sort_rule(r) } \n @records.reverse! if @search_params[:desc] || @search_params[:order_current] =~ /DESC/\n end\n end\n elsif @records && @records.size > 0\n @records = []\n end\n @records ||= []\n @records = @records.paginate(:page => @search_params[:page],:per_page => per_page) if @search_params[:paginate]=='yes' && !@records.empty?\n end", "def records\n @records ||= process_records!\n end", "def create_records(klass, count)\n RecordCountChangeMatcher.new.for(klass).by(count)\n end", "def upload_records(&block)\n record_count = 0\n records = []\n loop do\n record = block.call\n break if record.nil?\n records << record\n if records.size % slice_size == 0\n record_count += records.size\n insert(records)\n records = []\n end\n end\n if records.size > 0\n record_count += records.size\n insert(records)\n end\n record_count\n end", "def generate_builders\n @builders = @data.map do |object|\n Builder.new(object, @settings, @options)\n end\n end", "def call_records call_id\n LazyArray.new do |page, size|\n records, _headers = get \"calls/#{call_id}/recordings\", page: page, size: size\n\n records.map do |record|\n Types::Record.new record\n end\n end\n end", "def add_records(records)\n records.each { |r| add_record(r) }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the records to the database by calling populate on the current database adapter.
def save_records unless @records.empty? @model_class.connection.populate(@model_class.quoted_table_name, columns_sql, rows_sql_arr, "#{@model_class.name} Populate") @last_id_in_database = @records.last.id @records.clear end end
[ "def save_records\n @records.each do |record|\n @collection.insert(record)\n end\n @records.clear\n end", "def save\n storage.save(records)\n end", "def save(record)\n @db.put_item(table_name: record.table, item: record.items)\n end", "def save_all\n RelaxDB.bulk_save self, *save_list\n end", "def update_records\n find(:all).each do |record|\n record.update_record\n end\n end", "def save\n run_callbacks :save do\n persist_models\n end\n end", "def apply\n # Make sure the source data is up-to-date\n refresh\n # Make sure the source data is indexed by the primary key\n ensure_indexed_source_data\n # Make sure that all of the affected records are loaded\n refresh_affected_records\n # Preload all key-value pairs needed to fully associate this record.\n preload_association_data\n # Wrap all of the updates in a single transaction\n @klass.transaction do\n if @options[:batch_size]\n @affected_records.each_slice(@options[:batch_size]) do |batch|\n @klass.import batch.map{ |pk, record| update_record(pk, record); record }\n end\n else\n @affected_records.each do |pk, record|\n update_record pk, record\n end\n end\n end\n end", "def seed_db\n @records.each do |row|\n $db.execute(\n \"INSERT INTO records\n (report_type, patient_name, service_from, service_thru, paid_date, hic_num, gross_reimb, cash_deduct, blood_deduct, coins, net_reimb)\n VALUES\n ('#{record.report_type}', '#{record.patient_name}', '#{record.service_from}', '#{record.service_thru}', '#{record.paid_date}', '#{record.hic_num}', '#{record.gross_reimb}', '#{record.cash}', '#{record.blood_deduct}', '#{record.coins}', '#{record.net_reimb}');\")\n end\n end", "def save_items!\n return if(clean?) # If there are no items, nothing was modified\n @assoc_source.save! unless(@assoc_source.id)\n @items.each do |item|\n item.save!\n end\n @items = nil unless(loaded?) # Otherwise we'll have trouble reload-and merging\n end", "def save\n ensure_no_extra_fields if self.respond_to?(:ensure_no_extra_fields, true)\n\n if persisted?\n data_model.update(self)\n else\n @id = data_model.store(self)\n end\n end", "def save\n Ribs.with_handle(self.database) do |h|\n if self.class.persistent?(self.model)\n h.update_obj(self.model)\n else\n h.insert_obj(self.model)\n self.class.persistent(self.model)\n end\n end\n self.model\n end", "def save_collection_places\n CollectionPlace.delete_all :conditions => [\"collection_id = ?\", self.id]\n inserts = (what.query[:places].values.map { |place_id| \"('#{self.id}','#{place_id}')\" }).join(\",\")\n CollectionPlace.connection.insert(\"insert into collection_places (collection_id, place_id) values #{inserts}\")\n end", "def save\n @data.map(&:save)\n end", "def update_records(model)\n records = records_for(model)\n result = yield records\n write_records(model, records)\n result\n end", "def save_records\n @records.each do |record|\n\n if record.valid?\n record.persisted? ? self.updated_count += 1 : self.created_count += 1\n record.save\n else\n self.discards.build(\n :identifier => record.send(@identifier),\n :description => ImportDiscard.description_for(record)\n )\n end\n\n end\n end", "def save_providers\n Array(providers).map(&:save)\n self\n end", "def flush\n # Push remaining data to database\n bulk_insert(@data_array)\n # Clear Hash Array\n @data_array.clear\n # Close Database connection.\n @connection.close()\n end", "def populate_sugar(records, type)\n module_type = get_sugarcrm_module_type(type)\n case @action\n when 'initial_run'\n @logger.info(\"Creating new records for #{type} type\")\n records.each do |record|\n create_sugar_record(module_type, record, type)\n end\n when 'update'\n records.each do |record|\n record = convert_string_to_datetime(record)\n existing_record = find_sugarcrm_object(type, 'sf_id', record['sf_id'])\n existing_record = existing_record.first if existing_record.is_a?(Array)\n if existing_record\n #TODO Nil values are not handled properly by SugarCRM in update_attributes, so we must transform them into blank values\n #remove this loop and use the main one!!\n record.each do |key, val|\n record[key] = \"\" if val.nil?\n end\n @logger.info(\"Updating record for #{type} #{record['name']}\")\n existing_record.update_attributes!(record)\n else\n @logger.info(\"Creating new record for #{type} #{record['name']}\")\n create_sugar_record(module_type, record, type)\n end\n end\n end\n end", "def save\n @associations.values.each { |a| a._save }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
in the array. The array will never be empty and the numbers will always be positive integers. given an array of integer calculate the average of all numbers numbers are all > 0 iterate over array , sum them and divide by the size of the array
def average(array) return 0 if array.empty? array.sum / array.size end
[ "def average(array)\n sum = 0\n array.each do |int|\n sum += int\n end\n sum / array.length\nend", "def average(array)\n sum = 0.0 # Initialize as float to avoid integer division\n\n for int in array # Sum all numbers in array\n sum += int\n end\n\n sum / array.size # Divide by number of numbers\nend", "def average(anArray)\r\n\tif anArray.size > 0 then\r\n\t\treturn sum(anArray) / anArray.size\r\n\telse\r\n\t\treturn 0.0\r\n\tend\r\nend", "def array_int_avg(array=nil)\n # If we didn't get an actual array, return 0\n return 0 if array.nil?\n # If the array has 0 elements in it, return 0\n return 0 if array.size < 1\n # Use some array inject magic to sum all elements, then divide by the array size\n # Use float to keep fidelity until the next step\n average = array.inject{ |sum, el| sum + el }.to_f / array.size\n # Return the integer value of the average\n return average.to_i\nend", "def averages(arr)\n\taverages = []\n\treturn averages if arr.nil? || arr.empty?\n\n\tarr.each_with_index do |num, index| #[1, 3, 5, 1, -10]\n\t\taverages << ((num + arr[index + 1])/2.0)# (1 + 3)/2\n\t\tbreak if index == (arr.size - 2)\n\tend\n\treturn averages\nend", "def average_array (array)\n return array.sum * 1.0 / array.length * 1.0 \nend", "def average(anArray)\n\tif anArray.empty? then\n\t\treturn 0.0\n\telse \n\t\treturn sum(anArray)/anArray.size\n\tend\nend", "def averages(arr)\n all_averages = []\n return [] if arr == nil\n (1..arr.size - 1).each do |index|\n num = (arr[index] + arr[index - 1])\n all_averages << num.to_f / 2 if num.odd?\n all_averages << num / 2 if num.even?\n end\n all_averages\nend", "def average\n @array.inject(0.0) {|total, n| total + n} / @array.size\n end", "def average (anArray)\n\n\t#if the array is empty...\n\tif anArray.empty?\n\t\treturn 0.0\n\n\t# otherwise, return the sum divided by the number of values\n\telse\n\t\treturn sum(anArray) / anArray.size\n\tend\nend", "def average(anArray)\n\tif anArray.size > 0 then\n\t\treturn sum(anArray) / anArray.size\n\telse\n\t\treturn 0.0\n\tend\nend", "def average_of_array(array)\n\tn = [10, 15, 25]\n\taverage = n.inject(0.0) { | total, num | total + num } / n.count\n\taverage.round\nend", "def mean array\n length = array.length\n sum = 0 \n array.each do |x|\n sum += x\n end\n sum / length\nend", "def array_average(arr)\n return arr.reduce(:+).to_f / arr.size\n end", "def average(array)\n sum = array.inject(:+)\n average = sum / array.size\n average\nend", "def average(array)\n # array.reduce(:+) / array.size\n array.reduce { |sum, n| sum + n } / array.size\n # array.sum / array.size\nend", "def average_of_array(array)\n (array.inject(&:+).to_f/array.length).round\nend", "def average_of_array(array)\n (array.inject(:+) / array.size.to_f).round\nend", "def average_of_array(array)\n sum_of_array = array.inject{ |x, y| x + y }.to_f\n (sum_of_array.to_f/array.length).round\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /families/1 GET /families/1.xml
def show @family ||= Family.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @family } end end
[ "def index\n @families = Family.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @families }\n end\n end", "def index\n @families = Family.find_all_by_member_and_current(true,true, :order => :name)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @families }\n end\n end", "def retrieve_families(user_id)\n start.uri('/api/user/family')\n .url_parameter('userId', user_id)\n .get()\n .go()\n end", "def retrieve_families(user_id)\n start.uri('/api/user/family')\n .url_parameter('userId', user_id)\n .get()\n .go()\n end", "def index\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @families }\n end\n end", "def family(email, name)\n get(\"/developers/#{email}/appfamilies/name\")\n end", "def index\n @index_action = true\n @families = Family.all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @families }\n end\n end", "def index\n @family_members = @current_family.family_members\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @family_members }\n end\n end", "def index\n @product_families = ProductFamily.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @product_families }\n end\n end", "def show\n @host_family_info = HostFamilyInfo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @host_family_info }\n end\n end", "def show\n @family = Family.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @family }\n end\n end", "def show\n @family = Family.find(params[:id])\n end", "def families(email, expand=false)\n get(\"/developers/#{email}/appfamilies\", {:expand => expand})\n end", "def list_families\n http_get(:uri=>\"/plugins/families\", :fields=>x_cookie)\n end", "def index\n @host_family_infos = HostFamilyInfo.all.paginate(:page => params[:page], :per_page => 10)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @host_family_infos }\n end\n end", "def index\n @families = Family.all.paginate(page: params[:page])\n render json: @families\n end", "def index\n @extended_families = ExtendedFamily.all\n end", "def list_families\n http_get(uri: '/plugins/families', fields: x_cookie)\n end", "def show\n @product_family = ProductFamily.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @product_family }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /families/new GET /families/new.xml
def new @family = Family.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @family } end end
[ "def new\n @family = Family.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @family }\n end\n end", "def new\n @child = @family.children.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @child }\n end\n end", "def new\n @family = Family.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @family }\n end\n end", "def new\n @family = Family.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @family }\n end\n end", "def new\n @family_member = FamilyMember.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @family_member }\n end\n end", "def create\n @family = Family.new(params[:family])\n respond_to do |format|\n if @family.save\n flash[:notice] = 'Family was successfully created.'\n format.html { redirect_to(@family) }\n format.xml { render :xml => @family, :status => :created, :location => @family }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @family.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @family = Family.new(params[:family])\n\n respond_to do |format|\n if @family.save\n flash[:notice] = 'Family was successfully created.'\n format.html { redirect_to(@family) }\n format.xml { render :xml => @family, :status => :created, :location => @family }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @family.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @family_type = FamilyType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @family_type }\n end\n end", "def new\n @people = People.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @people }\n end\n end", "def new\n @product_family = ProductFamily.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @product_family }\n end\n end", "def new\n @people = People.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @people }\n end\n end", "def new\n @family_member = FamilyMember.new\n \n respond_to do |format|\n format.fbml # new.fbml.erb\n format.xml { render :xml => @family_member }\n end\n end", "def new\n respond_to do |format|\n format.html { render_template } # new.html.erb\n format.xml { render xml: @product_family }\n end\n end", "def new\n @lookup_ref = LookupRef.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @lookup_ref }\n end\n end", "def new\n @groups_happening = GroupsHappening.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @groups_happening }\n end\n end", "def new\n if params[:family_id]\n @family = Family.find(params[:family_id])\n else\n @family = nil\n end\n @fish = Fish.new\n @fish.family = @family\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fish }\n end\n end", "def new\n @entree = Entree.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @entree }\n end\n end", "def index\n @families = Family.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @families }\n end\n end", "def new\n @lookup_set = LookupSet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @lookup_set }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /families POST /families.xml
def create @family = Family.new(params[:family]) respond_to do |format| if @family.save flash[:notice] = 'Family was successfully created.' format.html { redirect_to(@family) } format.xml { render :xml => @family, :status => :created, :location => @family } else format.html { render :action => "new" } format.xml { render :xml => @family.errors, :status => :unprocessable_entity } end end end
[ "def create_family(family_id, request)\n start.uri('/api/user/family')\n .url_segment(family_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .post()\n .go()\n end", "def create_family(family_id, request)\n start.uri('/api/user/family')\n .url_segment(family_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .post()\n .go()\n end", "def create\n @family = Family.new(params[:family])\n\n respond_to do |format|\n if @family.save\n flash[:notice] = 'Family was successfully created.'\n format.html { redirect_to(@family) }\n format.xml { render :xml => @family, :status => :created, :location => @family }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @family.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @family = Family.new(family_params)\n addMembers\n respond_to do |format|\n if @family.save\n format.html { redirect_to @family, notice: 'Family was successfully created.' }\n format.json { render :show, status: :created, location: @family }\n else\n format.html { render :new }\n format.json { render json: @family.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_jobfamily\n @jobfamily = @company.jobfamilies.create(name: params[:jobfamily][:name])\n respond_to do |format|\n format.json { render json: @jobfamily }\n end\n end", "def create\n @family = Family.new(params[:family])\n\n respond_to do |format|\n if @family.save\n format.html { redirect_to @family, :notice => 'Control family was successfully created.' }\n format.json { render :json => @family, :status => :created, :location => @control_family }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @family.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @adminagentfamily = Adminagentfamily.new(adminagentfamily_params)\n\n respond_to do |format|\n if @adminagentfamily.save\n format.html { redirect_to @adminagentfamily, notice: 'Adminagentfamily was successfully created.' }\n format.json { render action: 'show', status: :created, location: @adminagentfamily }\n else\n format.html { render action: 'new' }\n format.json { render json: @adminagentfamily.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @family_relation = FamilyRelation.new(family_relation_params)\n\n respond_to do |format|\n if @family_relation.save\n format.html { redirect_to @family_relation, notice: 'Family relation was successfully created.' }\n format.json { render :show, status: :created, location: @family_relation }\n else\n format.html { render :new }\n format.json { render json: @family_relation.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @family_relationship = FamilyRelationship.new(family_relationship_params)\n\n respond_to do |format|\n if @family_relationship.save\n format.html { redirect_to @family_relationship, notice: 'Family relationship was successfully created.' }\n format.json { render :show, status: :created, location: @family_relationship }\n else\n format.html { render :new }\n format.json { render json: @family_relationship.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @family_group = FamilyGroup.new(family_group_params)\n\n respond_to do |format|\n if @family_group.save\n format.html { redirect_to family_groups_url, notice: 'Family group was successfully created.' }\n format.json { render :show, status: :created, location: @family_group }\n else\n format.html { render :new }\n format.json { render json: @family_group.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @families = Family.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @families }\n end\n end", "def index\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @families }\n end\n end", "def add_family(id, params = {})\n params = { :variations => [], :subset => 'default' }.merge(params)\n !!Client.post(\"/kits/#{@id}/families/#{id}\", :query => params)\n end", "def create\n @os_family = OsFamily.new(os_family_params)\n\n respond_to do |format|\n if @os_family.save\n format.html { redirect_to @os_family, notice: 'Os family was successfully created.' }\n format.json { render :show, status: :created, location: @os_family }\n else\n format.html { render :new }\n format.json { render json: @os_family.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @family_group = FamilyGroup.new(params[:family_group])\n\n respond_to do |format|\n if @family_group.save\n format.html { redirect_to @family_group, notice: 'Family group was successfully created.' }\n format.json { render json: @family_group, status: :created, location: @family_group }\n else\n format.html { render action: \"new\" }\n format.json { render json: @family_group.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @family_detail = FamilyDetail.new(family_detail_params)\n\n respond_to do |format|\n if @family_detail.save\n format.html { redirect_to @family_detail, notice: 'Family detail was successfully created.' }\n format.json { render :show, status: :created, location: @family_detail }\n else\n format.html { render :new }\n format.json { render json: @family_detail.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n admin_store_url\n \n @product_family = ProductFamily.create(params[:product_family])\n leaf_ids = params[:leaf_ids]\n \n unless leaf_ids.blank?\n leaf_ids.each do |lid|\n cat = Category.find(lid)\n cat.add_family(@product_family)\n end\n end\n \n respond_to do |format|\n if @product_family.save\n flash[:notice] = 'Product Family was successfully created.'\n format.html { redirect_to(admin_product_families_path)}\n format.xml { render :xml => @product_family, :status => :created,\n :location => @product_family }\n else\n format.html do\n @leaf_categories = Category.get_available_leaves\n render :action => \"new\"\n end\n format.xml { render :xml => @product_family.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @family_type = FamilyType.new(family_type_params)\n\n respond_to do |format|\n if @family_type.save\n format.html { redirect_to @family_type, notice: 'Family type was successfully created.' }\n format.json { render :show, status: :created, location: @family_type }\n else\n format.html { render :new }\n format.json { render json: @family_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @species_family = SpeciesFamily.new(species_family_params)\n respond_to do |format|\n if @species_family.save\n format.html { redirect_to @species_family, notice: 'Species family was successfully created.' }\n format.json { render :show, status: :created, location: @species_family }\n else\n format.html { render :new }\n format.json { render json: @species_family.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /families/1 PUT /families/1.xml
def update @family ||= Family.find(params[:id]) respond_to do |format| if @family.update_attributes(params[:family]) flash[:notice] = 'Family was successfully updated.' format.html { redirect_to(@family) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @family.errors, :status => :unprocessable_entity } end end end
[ "def update\n @family = Family.find(params[:id])\n\n respond_to do |format|\n if @family.update_attributes(params[:family])\n AuditTrail.audit(\"Family #{@family.familyname} updated by #{current_user.login}\", family_url(@family))\n flash[:notice] = 'Families was successfully updated.'\n format.html { redirect_to(families_path) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @family.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @family = Family.find(params[:id])\n\n respond_to do |format|\n if @family.update_attributes(params[:family])\n flash[:notice] = 'Family was successfully updated.'\n format.html { redirect_to(@family) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @family.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @family = Family.find(params[:id])\n\n respond_to do |format|\n if @family.update_attributes(params[:family])\n flash[:notice] = \"Family #{@family.business_name} was successfully updated.\"\n format.html { redirect_to(@family) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @family.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @family = Family.find(params[:id])\n\n respond_to do |format|\n if @family.update_attributes(params[:family])\n format.html { redirect_to @family, :notice => 'Control family was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @family.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @family = Family.find(params[:id])\n\n respond_to do |format|\n if @family.update_attributes(params[:family])\n format.html { redirect_to @family, notice: 'Family was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @family.errors, status: :unprocessable_entity }\n end\n end\n end", "def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post 'update', opts\n end", "def update opts = {}\n opts[:headers] ||= {}\n opts[:headers]['Content-Type'] ||= 'text/xml'\n post opts.fetch(:path, update_path), opts\n end", "def add_user_to_family(family_id, request)\n start.uri('/api/user/family')\n .url_segment(family_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .put()\n .go()\n end", "def add_user_to_family(family_id, request)\n start.uri('/api/user/family')\n .url_segment(family_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .put()\n .go()\n end", "def update\n respond_to do |format|\n if @family.update(family_params)\n format.html { redirect_to @family, notice: 'Family was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @family.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @os_family.update(os_family_params)\n format.html { redirect_to @os_family, notice: 'Os family was successfully updated.' }\n format.json { render :show, status: :ok, location: @os_family }\n else\n format.html { render :edit }\n format.json { render json: @os_family.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n\t\t@family ||= Family.find(params[:id])\n @family.destroy\n respond_to do |format|\n format.html { redirect_to(families_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @family = Family.find(params[:id])\n @family.destroy\n\n respond_to do |format|\n format.html { redirect_to(families_url) }\n format.xml { head :ok }\n end\n end", "def create_family(family_id, request)\n start.uri('/api/user/family')\n .url_segment(family_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .post()\n .go()\n end", "def update\n @family_type = FamilyType.find(params[:id])\n\n respond_to do |format|\n if @family_type.update_attributes(params[:family_type])\n format.html { redirect_to @family_type, notice: 'Family type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @family_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @species_family.update(species_family_params)\n format.html { redirect_to @species_family, notice: 'Species family was successfully updated.' }\n format.json { render :show, status: :ok, location: @species_family }\n else\n format.html { render :edit }\n format.json { render json: @species_family.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_family(family_id, request)\n start.uri('/api/user/family')\n .url_segment(family_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .post()\n .go()\n end", "def edit_family\n @family = Family.find(params[:id])\n \n respond_to do |format|\n format.html {render :layout => 'plain'}\n end\n end", "def update\n respond_to do |format|\n if @family_relation.update(family_relation_params)\n format.html { redirect_to @family_relation, notice: 'Family relation was successfully updated.' }\n format.json { render :show, status: :ok, location: @family_relation }\n else\n format.html { render :edit }\n format.json { render json: @family_relation.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /families/1 DELETE /families/1.xml
def destroy @family ||= Family.find(params[:id]) @family.destroy respond_to do |format| format.html { redirect_to(families_url) } format.xml { head :ok } end end
[ "def destroy\n @family = Family.find(params[:id])\n @family.destroy\n\n respond_to do |format|\n format.html { redirect_to(families_url) }\n format.xml { head :ok }\n end\n end", "def delete_family(id)\n !!Client.delete(\"/kits/#{@id}/families/#{id}\")\n end", "def delete_family(email, name)\n delete(\"/developers/#{email}/appfamilies/#{name}\")\n end", "def destroy\n# @family = Family.find(params[:id])\n# @family.destroy\n#\n# respond_to do |format|\n# format.html { redirect_to(families_url) }\n# format.xml { head :ok }\n# end\n end", "def destroy\n @host_family_info = HostFamilyInfo.find(params[:id])\n @host_family_info.destroy\n\n respond_to do |format|\n format.html { redirect_to(host_family_infos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @family = Family.find(params[:id])\n @family.destroy\n\n respond_to do |format|\n format.html { redirect_to families_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @family.destroy\n respond_to do |format|\n format.html { redirect_to families_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @adminagentfamily.destroy\n respond_to do |format|\n format.html { redirect_to adminagentfamilies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @os_family.destroy\n respond_to do |format|\n format.html { redirect_to os_families_url, notice: 'Os family was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @productfamily = Productfamily.find(params[:id])\n @productfamily.destroy\n\n respond_to do |format|\n format.html { redirect_to(productfamilies_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n admin_store_url\n @product_family = ProductFamily.find(params[:id])\n @product_family.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_product_families_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @medium_family = MediumFamily.find(params[:id])\n @medium_family.destroy\n\n respond_to do |format|\n format.html { redirect_to medium_families_url }\n format.json { head :no_content }\n end\n end", "def destroy\n genus = Genu.all;\n genus.each do |genu|\n if(genu.sub_family_id == @sub_family.id)\n genu.destroy\n end\n end\n @sub_family.destroy\n respond_to do |format|\n format.html { redirect_to sub_families_url, notice: 'Sub família foi deletada.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @taxe_group = Taxe::Group.find(params[:id])\n @taxe_group.destroy\n\n respond_to do |format|\n format.html { redirect_to(taxe_groups_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @product_family = ProductFamily.find(params[:id])\n @product_family.destroy\n\n respond_to do |format|\n format.html { redirect_to(product_families_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @family_relation.destroy\n respond_to do |format|\n format.html { redirect_to family_relations_url, notice: 'Family relation was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @browsenodeid = Browsenodeid.find(params[:id])\n @browsenodeid.destroy\n\n respond_to do |format|\n format.html { redirect_to(browsenodeids_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @family_group = FamilyGroup.find(params[:id])\n @family_group.destroy\n\n respond_to do |format|\n format.html { redirect_to family_groups_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @family_member = FamilyMember.find(params[:id])\n @family_member.destroy\n\n respond_to do |format|\n format.html { redirect_to(family_family_members_url(@current_family)) }\n format.xml { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /contact_stores GET /contact_stores.json
def index @contact_stores = ContactStore.all end
[ "def index\n @stores = Store.all\n\n render json: @stores\n end", "def index\n @stores = Store.all\n render json: @stores\n end", "def index\n @api_v1_stores = Store.all\n json_response(@api_v1_stores)\n end", "def index\n @admin_stores = Admin::Store.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @admin_stores }\n end\n end", "def index\n @store_classes = StoreClass.all\n\n render json: @store_classes\n end", "def index\n @customer_stores = CustomerStore.all\n end", "def index\n @products_stores = ProductsStore.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @products_stores }\n end\n end", "def contacts\n get('contacts')\n end", "def index\n @user_stores = UserStore.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @user_stores }\n end\n end", "def create\n @contact_store = ContactStore.new(contact_store_params)\n\n respond_to do |format|\n if @contact_store.save\n format.html { redirect_to @contact_store, notice: 'Contact store was successfully created.' }\n format.json { render :show, status: :created, location: @contact_store }\n else\n format.html { render :new }\n format.json { render json: @contact_store.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @supplier_contacts = @supplier.supplier_account.supplier_contacts\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @supplier_contacts }\n end\n end", "def index\n @online_stores = OnlineStore.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @online_stores }\n end\n end", "def index\n @stores = Store.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @stores }\n format.json { render :json => @stores }\n end\n end", "def index\n @contactos = Contacto.all\n render json:@contactos\n end", "def index\n @cakestores = Cakestore.all\n end", "def index\n @store_credits = StoreCredit.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @store_credits }\n end\n end", "def index\n\t\tbegin\n\t\t\tif params[:lat].present? && params[:lng].present?\n\t\t\t\t@address = Geokit::Geocoders::GoogleGeocoder.reverse_geocode \"#{params[:lat]},#{params[:lng]}\"\n\t\t\t\tparams[:postal_code] = @address.try(:zip) if @address.success\n\t\t\tend\n\t\t\t@search = Store.search do\n\t\t\t\tfulltext(params[:postal_code]) do\n\t\t\t\t\tfields(:postal_code)\n\t\t\t\tend\n\t\t\tend\n\t\t\tif @address.present?\n\t\t\t\t@stores = @search.results.sort_by{|s| s.distance_to([@address.lat,@address.lng])}\n\t\t\telse\n\t\t\t\t@stores = @search.results\n\t\t\tend\n\t\t\t\t@postal_code = params[:postal_code]\n\t\t\t\t@stores =\t@stores.first(5) if params[:type] == \"collection\"\n\t\t\trender :index, status: :ok\n\t\trescue Exception => e\n\t\t\terror_handling_bad_request(e)\n\t\tend\n\tend", "def index\n @stores = StoreIt.all\n end", "def index\n @shipping_categories = @shop.shipping_categories\n respond_to do |format|\n format.html\n format.json { render json: @shipping_categories }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /contact_stores POST /contact_stores.json
def create @contact_store = ContactStore.new(contact_store_params) respond_to do |format| if @contact_store.save format.html { redirect_to @contact_store, notice: 'Contact store was successfully created.' } format.json { render :show, status: :created, location: @contact_store } else format.html { render :new } format.json { render json: @contact_store.errors, status: :unprocessable_entity } end end end
[ "def create\n @store = Store.new(store_params)\n\n if @store.save\n render json: @store, status: :created, location: @store\n else\n render json: @store.errors, status: :unprocessable_entity\n end\n end", "def create\n @customer_store = CustomerStore.new(customer_store_params)\n\n respond_to do |format|\n if @customer_store.save\n format.html { redirect_to @customer_store, notice: 'Customer store was successfully created.' }\n format.json { render :show, status: :created, location: @customer_store }\n else\n format.html { render :new }\n format.json { render json: @customer_store.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @cakestore = Cakestore.new(cakestore_params)\n\n respond_to do |format|\n if @cakestore.save\n format.html { redirect_to @cakestore, notice: 'Cakestore was successfully created.' }\n format.json { render :show, status: :created, location: @cakestore }\n else\n format.html { render :new }\n format.json { render json: @cakestore.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @store = current_user.stores.new(params[:store])\n \n respond_to do |format|\n if @store.save\n format.html { redirect_to @store, notice: 'Store was successfully created.' }\n format.json { render json: @store, status: :created, location: @store }\n else\n format.html { render action: \"new\" }\n format.json { render json: @store.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @store = Store.new(store_params)\n\n respond_to do |format|\n if @store.save\n format.html { redirect_to [:phone, @store], notice: 'Store was successfully created.' }\n format.json { render action: 'show', status: :created, location: @store }\n else\n format.html { render action: 'new' }\n format.json { render json: @store.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @store = Store.new(params[:store])\n\n respond_to do |format|\n if @store.save\n format.html { redirect_to @store, :notice => 'Store was successfully created.' }\n format.json { render :json => @store, :status => :created, :location => @store }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @store.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @has_store = HasStore.new(has_store_params)\n\n respond_to do |format|\n if @has_store.save\n format.html { redirect_to @has_store, notice: \"Has store was successfully created.\" }\n format.json { render :show, status: :created, location: @has_store }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @has_store.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n store = Store.new(store_params)\n\n # check if saved correctly\n if store.save\n render json: {status: 'SUCCESS', message:'Added the new store', data:store},status: :ok\n else\n render json: {status: 'ERROR', message:'Could not add the new store', data:store},status: :unprocessable_entity\n end\n end", "def create\n @shop_store = ShopStore.new(shop_store_params)\n\n respond_to do |format|\n if @shop_store.save\n format.html { redirect_to @shop_store, notice: 'Shop store was successfully created.' }\n format.json { render :show, status: :created, location: @shop_store }\n else\n format.html { render :new }\n format.json { render json: @shop_store.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @contact = Contact.create!(contact_params)\n render json: Contact.all\n end", "def create\n @store = Store.new(store_params)\n\n respond_to do |format|\n if @store.save\n format.html { redirect_to [:admin, @store], notice: 'Store was successfully created.' }\n format.json { render action: 'show', status: :created, location: @store }\n else\n format.html { render action: 'new' }\n format.json { render json: @store.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @store_add = StoreAdd.new(store_add_params)\n\n respond_to do |format|\n if @store_add.save\n format.html { redirect_to @store_add, notice: 'Store add was successfully created.' }\n format.json { render :show, status: :created, location: @store_add }\n else\n format.html { render :new }\n format.json { render json: @store_add.errors, status: :unprocessable_entity }\n end\n end\n end", "def create(add_params = nil)\n params = {\n }\n api_call('/stores(.:format)',:post,params,add_params)\n end", "def index\n @contact_stores = ContactStore.all\n end", "def create\n @order_store = OrderStore.new(order_store_params)\n\n respond_to do |format|\n if @order_store.save\n format.html { redirect_to @order_store, notice: 'Order store was successfully created.' }\n format.json { render :show, status: :created, location: @order_store }\n else\n format.html { render :new }\n format.json { render json: @order_store.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @admin_store = current_user.stores.build(admin_store_params)\n respond_to do |format|\n if @admin_store.save\n format.html { redirect_to admin_store_path(@admin_store), notice: 'Store was successfully created.' }\n format.json { render :show, status: :created, location: @admin_store }\n else\n format.html { render :new }\n format.json { render json: @admin_store.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @store_class = StoreClass.new(store_class_params)\n\n if @store_class.save\n render json: @store_class, status: :created, location: @store_class\n else\n render json: @store_class.errors, status: :unprocessable_entity\n end\n end", "def create\n @store_info = StoreInfo.new(store_info_params)\n\n respond_to do |format|\n if @store_info.save\n format.html { redirect_to @store_info, notice: 'Store info was successfully created.' }\n format.json { render :show, status: :created, location: @store_info }\n else\n format.html { render :new }\n format.json { render json: @store_info.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @stores_book = StoresBook.new(stores_book_params)\n\n respond_to do |format|\n if @stores_book.save\n format.html { redirect_to @stores_book, notice: \"Stores book was successfully created.\" }\n format.json { render :show, status: :created, location: @stores_book }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @stores_book.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /contact_stores/1 PATCH/PUT /contact_stores/1.json
def update respond_to do |format| if @contact_store.update(contact_store_params) format.html { redirect_to @contact_store, notice: 'Contact store was successfully updated.' } format.json { render :show, status: :ok, location: @contact_store } else format.html { render :edit } format.json { render json: @contact_store.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @store.update(store_params)\n format.html { redirect_to [:phone, @store], notice: 'Store was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @store.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @store = Store.find(params[:id])\n\n respond_to do |format|\n if @store.update_attributes(params[:store])\n format.html { redirect_to api_v1_store_path(@store.id), notice: 'Store was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @store.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @api_v1_store = Store.find(params[:id])\n\n if @api_v1_store.update(api_v1_store_params)\n head :no_content\n else\n render json: @api_v1_store.errors, status: :unprocessable_entity\n end\n end", "def update\n if @store.update(store_params)\n render json: @store\n else\n render json: @store.errors, status: :unprocessable_entity\n end\n end", "def update\n @contact.update(contact_params)\n if @contact.valid?\n render json: @contact\n end\n end", "def update\n respond_to do |format|\n if @cakestore.update(cakestore_params)\n format.html { redirect_to @cakestore, notice: 'Cakestore was successfully updated.' }\n format.json { render :show, status: :ok, location: @cakestore }\n else\n format.html { render :edit }\n format.json { render json: @cakestore.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @contact.update(contact_params)\n fresh_when(@contact)\n render json: @contact, status: :ok, location: @contact\n else\n render json: { errors: @contact.errors.messages }, status: :unprocessable_entity\n end\n end", "def update_mobile_carrier(args = {}) \n put(\"/mobile.json/#{args[:carrierId]}\", args)\nend", "def update\n begin\n @api_v1_store.update!(api_v1_store_params)\n head :no_content\n rescue => ex\n json_response({error: ex.message}, :unprocessable_entity)\n end\n end", "def update\n respond_to do |format|\n if @customer_store.update(customer_store_params)\n format.html { redirect_to @customer_store, notice: 'Customer store was successfully updated.' }\n format.json { render :show, status: :ok, location: @customer_store }\n else\n format.html { render :edit }\n format.json { render json: @customer_store.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @customer = Customer.find(params[:customer_id])\n @cust_contact = @customer.cust_contacts.find(params[:id])\n\n respond_to do |format|\n if @cust_contact.update_attributes(params[:cust_contact])\n format.html { redirect_to customer_path(@customer), :notice => 'Contact was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @cust_contact.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @admin_contact_detail = Admin::ContactDetail.find(params[:id])\n\n respond_to do |format|\n if @admin_contact_detail.update_attributes(params[:admin_contact_detail])\n format.html { redirect_to admin_suppliers_url }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @admin_contact_detail.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @contact_info = ContactInfo.find(params[:id])\n\n if @contact_info.update(contact_info_params(params[:contact_info]))\n head :no_content\n else\n render json: @contact_info.errors, status: :unprocessable_entity\n end\n end", "def update\n if @contact.address.update(address_params)\n render json: @contact.address\n else\n render json: @contact.errors, status: :unprocessable_entity\n end\n end", "def update\n @contactlocation = Contactlocation.find(params[:id])\n @contact = @contactlocation.contact_id\n @client = @contact.client_id\n\n respond_to do |format|\n if @contactlocation.update_attributes(params[:contactlocation])\n format.html { redirect_to client_path(@client), notice: 'contactlocation was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @contactlocation.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_contact_in_salesforce\n \tsf = Salesforce::API.connect_to_salesforce\n \tcontact_id = self.sf_contact_id\n \tsf.update(\n \"Contact\",\n Id: \"#{contact_id}\",\n Name: \"#{self.first_name}\",\n Email: \"#{self.email}\",\n )\n end", "def update\n respond_to do |format|\n if @contact.update(contact_params)\n format.html{redirect_to([@scenario, @contact], notice: 'Contact was successfully updated.')}\n format.json{render :show, status: :ok, location: @contact}\n else\n format.html{redirect_to :back, flash: {error: \"Error saving contact\"}}\n format.json{render json: @contact.errors, status: :unprocessable_entity}\n end\n end\n end", "def update\n @client_additional_contact = ClientAdditionalContact.find(params[:id])\n\n respond_to do |format|\n if @client_additional_contact.update_attributes(client_additional_contact_params)\n format.html { redirect_to @client_additional_contact, notice: 'Client additional contact was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @client_additional_contact.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @edit_contact.update(edit_contact_params)\n format.html { redirect_to @edit_contact, notice: 'Edit contact was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @edit_contact.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /contact_stores/1 DELETE /contact_stores/1.json
def destroy @contact_store.destroy respond_to do |format| format.html { redirect_to contact_stores_url, notice: 'Contact store was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @store = Store.find(params[:id])\n @store.destroy\n\n respond_to do |format|\n format.html { redirect_to api_v1_stores_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @cakestore.destroy\n respond_to do |format|\n format.html { redirect_to cakestores_url, notice: 'Cakestore was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @store.destroy\n respond_to do |format|\n format.html { redirect_to phone_stores_url, notice: 'Store was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @store = Store.find(params[:id])\n @store.destroy\n\n respond_to do |format|\n format.html { redirect_to stores_url }\n format.json { head :ok }\n end\n end", "def destroy\n @store = Store.find(params[:id])\n @store.destroy\n\n respond_to do |format|\n format.html { redirect_to stores_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_v1_store.destroy\n\n head :no_content\n end", "def destroy\n @admin_store = Admin::Store.find(params[:id])\n @admin_store.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_stores_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @datastore = Datastore.find(params[:id])\n @datastore.destroy\n\n respond_to do |format|\n format.html { redirect_to datastores_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @customer_store.destroy\n respond_to do |format|\n format.html { redirect_to customer_stores_url, notice: 'Customer store was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @at_store.destroy\n respond_to do |format|\n format.html { redirect_to at_stores_url, notice: 'At store was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @contact.destroy\n render json: {status: 204}\n end", "def destroy\n @admin_store = Store.find(params[:id])\n @admin_store.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_stores_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @store = Store.find(params[:id])\n @store.destroy\n\n respond_to do |format|\n format.html { redirect_to(stores_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @store = Store.find(params[:id])\n @store.destroy\n\n respond_to do |format|\n format.html { redirect_to(stores_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @bookstore = Bookstore.find(params[:id])\n @bookstore.destroy\n\n respond_to do |format|\n format.html { redirect_to bookstores_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @bread_store.destroy\n respond_to do |format|\n format.html { redirect_to bread_stores_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @in_store = InStore.find(params[:id])\n @in_store.destroy\n\n respond_to do |format|\n format.html { redirect_to in_stores_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @store_add.destroy\n respond_to do |format|\n format.html { redirect_to store_adds_url, notice: 'Store add was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_mobile_carrier(args = {}) \n delete(\"/mobile.json/#{args[:carrierId]}\", args)\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
SUPPLEMENTS SUMMARY Total summary
def total_summary products = {} products.store(:item_cost, item_cost) products.store(:extras_cost, extras_cost) supplements = {} supplements.store(:pick_up_place, pickup_place_cost) supplements.store(:return_place, return_place_cost) supplements.store(:time_from_cost, time_from_cost) supplements.store(:time_to_cost, time_to_cost) supplements.store(:driver_age_cost, driver_age_cost) supplements.store(:category_supplement_1, category_supplement_1_cost) supplements.store(:category_supplement_2, category_supplement_2_cost) supplements.store(:category_supplement_3, category_supplement_3_cost) supplements.store(:supplement_1, supplement_1_cost) supplements.store(:supplement_2, supplement_2_cost) supplements.store(:supplement_3, supplement_3_cost) deposit = {} deposit.store(:product_deposit_cost, product_deposit_cost) totals = {} totals.store(:total_cost, total_cost) totals.store(:total_paid, total_paid) totals.store(:total_pending, total_pending) summary = {products: products, supplements: supplements, deposit: deposit, totals: totals } end
[ "def summary; end", "def apply_summary; nil; end", "def summary\n return \"\\nNo results identified.\\n\" if tally.keys.empty?\n result = [ \"\\nSummary of identified results:\\n\" ]\n sum = 0\n tally.keys.sort_by {|k| -1*tally[k] }.each do |k|\n sum += tally[k]\n result << \"%30s: %6d\" % [k, tally[k]]\n end\n result << \"%30s: %6d\" % ['TOTAL', sum]\n result.join \"\\n\"\n end", "def total_all \n subtotals.sum \n end", "def totals_pipeline\n Offer.totals_pipeline(self)\n end", "def summary(param)\n extract_values_from_cart_summary[param]\n end", "def summary\r\n @collection[:summary] ||= {}\r\n end", "def summary\n @summary\n end", "def summary\n @items.map { |i| \"* #{i.title}\" }.join(\"\\n\")\n end", "def packing_summary\n output = []\n output << \"Melinda, here's your packing list!\"\n output << \"Day: #{@attributes[:days_of_the_week]}, Weather: #{@attributes[:weather]}\"\n output << \"\"\n @items.each do |item|\n output << \"- #{item}\"\n end\n output.join(\"\\n\")\n end", "def emi_summary\n end", "def summary\n summary = \"= #{name}\"\n summary << \"\\n Number of rows: #{nrows}\"\n @vectors.each do |v|\n summary << \"\\n Element:[#{v}]\\n\"\n summary << self[v].summary(1)\n end\n summary\n end", "def total_acres\n self.dig_for_string(\"listingSummary\", \"totalAcres\")\n end", "def summary_dl; @summary; end", "def totals_table\n strings = []\n strings << \"#{@labels[:subtotal]}:\"\n strings << @document.subtotal\n strings << \"#{@labels[:tax]}:\"\n strings << @document.tax\n strings << \"#{@labels[:tax2]}:\"\n strings << @document.tax2\n strings << \"#{@labels[:tax3]}:\"\n strings << @document.tax3\n strings << \"#{@labels[:total]}:\"\n strings << @document.total\n strings\n end", "def wrt_total_purchs(count, options = {})\n format = options[:format] || 6\n $report_file.puts(\"Total Purchases:\" + \"%#{format}s\" % count.to_s)\nend", "def summary\n return @summary\n end", "def total_compulsory_savings\n self.group_loan_memberships.sum(\"total_compulsory_savings\")\n end", "def spending_table(hash, total)\n puts \"\".center(80, \"_\")\n hash.each{ |item, value| puts tabled_format(item, value) }\n puts \"\".center(80, \"_\")\n total = hash.values.inject(:+)\n puts tabled_format(\"Total\", total)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BOOKING LINES Add a booking line to the reservation == Parameters:: item_id:: The item id quantity:: The quantity
def add_booking_line(item_id, quantity) # Check if the booking includes the item_id product_lines = self.booking_lines.select do |booking_line| booking_line.item_id == item_id end if product_lines.empty? if product = ::Yito::Model::Booking::BookingCategory.get(item_id) product_customer_translation = product.translate(customer_language) product_unit_cost = product_item_cost_base = product.unit_price(self.date_from, self.days, nil, self.sales_channel_code).round(0) product_deposit_cost = product.deposit ## Apply promotion code and offers rates_promotion_code = if !self.promotion_code.nil? and !self.promotion.code.empty? ::Yito::Model::Rates::PromotionCode.first(promotion_code: self.promotion_code) else nil end discount = ::Yito::Model::Booking::BookingCategory.discount(product_unit_cost, item_id, self.date_from, self.date_to, rates_promotion_code) || 0 product_unit_cost = (product_unit_cost - discount).round(0) if discount > 0 ## End apply offers ## Category supplements product_supplement_1_unit_cost = product.category_supplement_1_cost || 0 product_supplement_2_unit_cost = product.category_supplement_2_cost || 0 product_supplement_3_unit_cost = product.category_supplement_3_cost || 0 if sales_channel_code if bcsc = Yito::Model::Booking::BookingCategoriesSalesChannel.first(conditions: {'sales_channel.code': sales_channel_code, booking_category_code: product.code }) product_supplement_1_unit_cost = bcsc.category_supplement_1_cost || 0 product_supplement_2_unit_cost = bcsc.category_supplement_2_cost || 0 product_supplement_3_unit_cost = bcsc.category_supplement_3_cost || 0 end end ## End of category supplements transaction do # Create booking line booking_line = BookingDataSystem::BookingLine.new booking_line.booking = self booking_line.item_id = item_id booking_line.item_description = product.name booking_line.item_description_customer_translation = (product_customer_translation.nil? ? product.name : product_customer_translation.name) booking_line.item_unit_cost_base = product_item_cost_base booking_line.item_unit_cost = product_unit_cost booking_line.item_cost = product_unit_cost * quantity booking_line.quantity = quantity booking_line.product_deposit_unit_cost = product_deposit_cost booking_line.product_deposit_cost = product_deposit_cost * quantity booking_line.category_supplement_1_unit_cost = product_supplement_1_unit_cost booking_line.category_supplement_1_cost = product_supplement_1_unit_cost * quantity booking_line.category_supplement_2_unit_cost = product_supplement_2_unit_cost booking_line.category_supplement_2_cost = product_supplement_2_unit_cost * quantity booking_line.category_supplement_3_unit_cost = product_supplement_3_unit_cost booking_line.category_supplement_3_cost = product_supplement_3_unit_cost * quantity booking_line.save # Create booking line resources (1..quantity).each do |resource_number| booking_line_resource = BookingDataSystem::BookingLineResource.new booking_line_resource.booking_line = booking_line booking_line_resource.save end # Update booking cost self.item_cost += (product_unit_cost * quantity) self.product_deposit_cost += (product_deposit_cost * quantity) self.category_supplement_1_cost += (product_supplement_1_unit_cost * quantity) self.category_supplement_2_cost += (product_supplement_2_unit_cost * quantity) self.category_supplement_3_cost += (product_supplement_3_unit_cost * quantity) self.calculate_cost(false, false) self.save # Assign available stock if status == :pending_confirmation if created_by_manager assign_available_stock if SystemConfiguration::Variable.get_value('booking.assignation.automatic_resource_assignation_on_backoffice_request').to_bool else assign_available_stock if SystemConfiguration::Variable.get_value('booking.assignation.automatic_resource_assignation_on_web_request').to_bool end elsif status == :confirmed if SystemConfiguration::Variable.get_value('booking.assignation.automatic_resource_assignation', 'false').to_bool assign_available_stock end end # Create newsfeed ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking', action: 'add_booking_line', identifier: self.id.to_s, description: BookingDataSystem.r18n.t.booking_news_feed.created_booking_line(item_id, quantity), attributes_updated: {item_id: item_id, quantity: quantity}.merge({booking: newsfeed_summary}).to_json) end self.reload end end end
[ "def adds_line_item(fields)\r\n @b.link(:id, \"add_line_item\").click\r\n @b.wait()\r\n \r\n trows = line_items_rows\r\n index = trows.length\r\n edits_line_item(index, fields)\r\n index\r\n end", "def create_line_item_from_inventory_item inventory_item, qty, payable_party, billable_party, include_price_in_expense, include_price_in_revenue, notes\n # Vendor\n l1 = LineItem.create!(\n :line_item_type => \"Goods\", :line_item_sub_type => \"Menu-Item\",\n :sku => inventory_item.sku, :name => inventory_item.name_vendor, :quantity => qty,\n :unit_price_expense => inventory_item.cogs,\n :tax_rate_expense => 0,\n :payable_party => payable_party,\n :include_price_in_expense => include_price_in_expense,\n :inventory_item => inventory_item, :notes => notes, :event => self)\n\n # Account\n l2 = LineItem.create!(\n :line_item_type => \"Goods\", :line_item_sub_type => \"Menu-Item\",\n :sku => inventory_item.sku, :name => inventory_item.name_public, :quantity => qty,\n :unit_price_revenue => calculate_sell_price_from_inventory_item(inventory_item),\n :billable_party => billable_party,\n :include_price_in_revenue => include_price_in_revenue,\n :inventory_item => inventory_item, :notes => notes, :event => self)\n\n l1.opposing_line_item = l2\n l2.opposing_line_item = l1\n l1.save\n l2.save\n\n [l1, l2]\n end", "def create_line_item_from_inventory_item_id inventory_item_id, qty, include_price_in_expense, include_price_in_revenue, notes\n # Inventory item\n inventory_item = InventoryItem.find(inventory_item_id)\n line_items.push(create_line_item_from_inventory_item(\n inventory_item, qty,\n inventory_item.vendor, account,\n include_price_in_expense, include_price_in_revenue, notes))\n end", "def create_line_item_from_inventory_item_id inventory_item_id, qty, include_price_in_expense, include_price_in_revenue, notes\n # Inventory item\n inventory_item = InventoryItem.find(inventory_item_id)\n new_line_items = create_line_item_from_inventory_item(\n inventory_item, qty,\n inventory_item.vendor, account,\n include_price_in_expense, include_price_in_revenue, notes)\n line_items.push(new_line_items)\n new_line_items\n end", "def create_line_item_from_inventory_item inventory_item, qty, payable_party, billable_party, include_price_in_expense, include_price_in_revenue, notes\n\n [\n # Vendor\n LineItem.create(\n :line_item_type => \"Goods\", :line_item_sub_type => \"Menu-Item\",\n :sku => inventory_item.sku, :name => inventory_item.name_vendor, :quantity => qty,\n :unit_price_expense => inventory_item.cogs,\n :tax_rate_expense => 0,\n :payable_party => payable_party,\n :include_price_in_expense => include_price_in_expense,\n :inventory_item => inventory_item, :notes => notes),\n\n # Account\n LineItem.create(\n :line_item_type => \"Goods\", :line_item_sub_type => \"Menu-Item\",\n :sku => inventory_item.sku, :name => inventory_item.name_public, :quantity => qty,\n :unit_price_revenue => calculate_sell_price_from_inventory_item(inventory_item),\n :billable_party => billable_party,\n :include_price_in_revenue => include_price_in_revenue,\n :inventory_item => inventory_item, :notes => notes)\n ]\n end", "def add_line_item(params)\r\n # Creates line items counter necessary for prefix.\r\n @LINE_ITEMS = 0 if !@LINE_ITEMS \r\n @LINE_ITEMS += 1 # VALUE REQUIRED IN:\r\n prefix = \"LV3_ITEM#{@LINE_ITEMS}_\" # USA | CANADA\r\n @PARAM_HASH[prefix + 'UNIT_COST'] = params[:unit_cost] # * *\r\n @PARAM_HASH[prefix + 'QUANTITY'] = params[:quantity] # * *\r\n @PARAM_HASH[prefix + 'ITEM_SKU'] = params[:item_sku] || '' # *\r\n @PARAM_HASH[prefix + 'ITEM_DESCRIPTOR'] = params[:descriptor] || '' # * *\r\n @PARAM_HASH[prefix + 'COMMODITY_CODE'] = params[:commodity_code] || '' # * *\r\n @PARAM_HASH[prefix + 'PRODUCT_CODE'] = params[:product_code] || '' # * \r\n @PARAM_HASH[prefix + 'MEASURE_UNITS'] = params[:measure_units] || '' # * *\r\n @PARAM_HASH[prefix + 'ITEM_DISCOUNT'] = params[:item_discount] || '' # *\r\n @PARAM_HASH[prefix + 'TAX_RATE'] = params[:tax_rate] || '' # * \r\n @PARAM_HASH[prefix + 'GOODS_TAX_RATE'] = params[:goods_tax_rate] || '' # *\r\n @PARAM_HASH[prefix + 'TAX_AMOUNT'] = params[:tax_amount] || '' # * \r\n @PARAM_HASH[prefix + 'GOODS_TAX_AMOUNT'] = params[:goods_tax_amount] || '' # *\r\n @PARAM_HASH[prefix + 'CITY_TAX_RATE'] = params[:city_tax_rate] || '' #\r\n @PARAM_HASH[prefix + 'CITY_TAX_AMOUNT'] = params[:city_tax_amount] || '' #\r\n @PARAM_HASH[prefix + 'COUNTY_TAX_RATE'] = params[:county_tax_rate] || '' #\r\n @PARAM_HASH[prefix + 'COUNTY_TAX_AMOUNT'] = params[:county_tax_amount] || '' #\r\n @PARAM_HASH[prefix + 'STATE_TAX_RATE'] = params[:state_tax_rate] || '' #\r\n @PARAM_HASH[prefix + 'STATE_TAX_AMOUNT'] = params[:state_tax_amount] || '' #\r\n @PARAM_HASH[prefix + 'CUST_SKU'] = params[:cust_sku] || '' #\r\n @PARAM_HASH[prefix + 'CUST_PO'] = params[:cust_po] || '' #\r\n @PARAM_HASH[prefix + 'SUPPLEMENTAL_DATA'] = params[:supplemental_data] || '' #\r\n @PARAM_HASH[prefix + 'GL_ACCOUNT_NUMBER'] = params[:gl_account_number] || '' #\r\n @PARAM_HASH[prefix + 'DIVISION_NUMBER'] = params[:division_number] || '' #\r\n @PARAM_HASH[prefix + 'PO_LINE_NUMBER'] = params[:po_line_number] || '' #\r\n @PARAM_HASH[prefix + 'LINE_ITEM_TOTAL'] = params[:line_item_total] || '' # * \r\n end", "def add_item(item)\n line_item = self.line_items.find_by(item_id: item)\n if line_item\n line_item.quantity += 1\n else\n line_item = self.line_items.build(cart_id: self.id, item_id: item)\n end\n line_item\n end", "def add(product, qty)\n l = LineItem.new\n l.set_from_product(product, qty)\n @lines << l\n end", "def lock_new_invoice_line_items party, document\n # Generate fixed-price post sub total line items from percentage based sub total line items\n subtotal = revenue_subtotal_by_party(party, false)\n line_items_after_subtotal_percentage_by_billable_party(party).each do |li|\n fixed_price = li.revenue_total_with_percentage subtotal\n line_items.create!(li.attributes.merge({unit_price_revenue: fixed_price, name: \"#{li.name} (#{li.unit_price_revenue}%)\", percentage_of_subtotal: false, parent_id: li.id}))\n end\n\n line_items_fixed_by_billable_party_including_add_ons(party, false).each do |li|\n li.document = document\n li.save\n end\n end", "def create\n @item_lines = ItemLine.new(item_line_params)\n\n if @item_lines.save\n render json: @item_lines, status: :created, location: @item_lines\n else\n render json: @item_lines.errors, status: :unprocessable_entity\n end\n end", "def create_line_item(table)\r\n values = []\r\n if table_exists?(table)\r\n columns = get_column_names(table)[1..-1]\r\n insert = Array.new(columns).fill('?').join(\", \")\r\n get_data_types(table).each_with_index do |type, i|\r\n prefix = nil\r\n prefix = columns[i].split('_id').join if /[_id]$/.match(columns[i])\r\n if !get_tables.include? prefix\r\n values << get_number(columns[i]) if type == 'INTEGER' || type == 'INT'\r\n values << get_string(columns[i]) if type == 'VARCHAR(255)'\r\n values << get_boolean(columns[i]) if type == 'BOOLEAN'\r\n else\r\n puts \"#{columns[i]} references table #{prefix}\"\r\n puts \"would you like to see that table now?\"\r\n print_table(prefix) if get_response == 'yes'\r\n puts \"would you like to reference one of the available lines?\"\r\n response = get_response\r\n if response == 'no' || get_ids(prefix).empty?\r\n puts \"That table has no lines to reference. We'll have to make a new one.\" if response == 'yes'\r\n puts \"Alright! We will now create a new line for you to reference\"\r\n create_line_item(prefix)\r\n values << get_ids(prefix)[-1]\r\n else \r\n puts \"Alright! Please input the id of the line you'd like to reference\"\r\n values << get_valid_id(prefix)\r\n end\r\n end\r\n end\r\n @db.execute(\"INSERT INTO #{table} (#{columns.join(\", \")}) VALUES (#{insert})\", values)\r\n end\r\n end", "def create_requested_line_item(bill_item)\r\n requested_line_item_config = bill_item.convert_to_requested_line_item\r\n self.material_request.items.create(requested_line_item_config)\r\n \tend", "def create\n @receivable = Receivable.find(params[:receivable_id])\n @receivable_line = @receivable.receivable_lines.build(params[:receivable_line])\n\n respond_to do |format|\n if @receivable_line.save\n format.html { redirect_to(new_receivable_receivable_line_path(@receivable), :notice => 'Line item was successfully created.') }\n format.json { render :json => @receivable_line, :status => :created, :location => [@receivable_line.receivable, @receivable_line] }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @receivable_line.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @line_item = @order.line_items.new(line_item_params)\n\n if @line_item.save\n render json: @line_item, status: :created, location: [@order, @line_item]\n else\n render json: @line_item.errors, status: :unprocessable_entity\n end\n end", "def create \n @line_item = LineItem.new(line_item_params)\n respond_to do |format|\n if @line_item.save\n format.html { redirect_to '/line_items', notice: \"Line item was successfully created.\" }\n format.json { render :show, status: :created, location: @line_item }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @line_item.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_line_item_for_per_person_charge_2 qty, event_vendor, include_price_in_expense, include_price_in_revenue, notes\n\n [\n # Vendor\n LineItem.create(\n :line_item_type => \"Goods\", :line_item_sub_type => \"Menu-Fee\",\n :sku => \"MT-\" + event_vendor.menu_template_id.to_s.rjust(7, '0'), :name => \"* Per Person Charge (\" + event_vendor.vendor.name + \")\", :quantity => qty,\n :unit_price_expense => event_vendor.calculate_menu_level_cogs,\n :tax_rate_expense => 0,\n :payable_party => event_vendor.vendor,\n :include_price_in_expense => include_price_in_expense,\n :menu_template => event_vendor.menu_template),\n\n # Account\n LineItem.create(\n :line_item_type => \"Goods\", :line_item_sub_type => \"Menu-Fee\",\n :sku => \"MT-\" + event_vendor.menu_template_id.to_s.rjust(7, '0'), :name => \"* Per Person Charge (\" + event_vendor.vendor.name + \")\", :quantity => qty,\n :unit_price_revenue => event_vendor.calculate_menu_level_sell_price,\n :billable_party => account,\n :include_price_in_revenue => include_price_in_revenue,\n :menu_template => event_vendor.menu_template)\n ]\n end", "def scan_serials_for_item( item_id )\r\n self.sales_lines.each do |line|\r\n \r\n # Skip to next unless the item id is matched and serial number is not blank\r\n # TODO:\r\n # Recognize changes of this serial number (RETURNED / CANCELED / BACKORDER / NONE)\r\n next unless (line.item_id == item_id) && (line.sales_item_reservation_number?)\r\n \r\n ERP::SerialNumber.find_or_create(\r\n :account_num => self.customer.account_num,\r\n :item_id => item_id,\r\n :sales_id => self.sales_id,\r\n :serial => line.sales_item_reservation_number\r\n )\r\n end\r\n end", "def line_item_insert(h)\n\t\trows = @database.execute <<-SQL\n\t\tINSERT INTO invoice_lines\n\t\t\t\t(number\n\t\t\t\t, invoice_id\n\t\t\t\t, line_id\n\t\t\t\t, _order\n\t\t\t\t, description\n\t\t\t\t, amount\n\t\t\t\t, first_expense_id\n\t\t \t, first_time_entry_id\n\t\t\t\t, line_item_date\n\t\t\t\t, person\n\t\t\t\t, name\n\t\t\t\t, matter\n\t\t\t\t, unit_cost\n\t\t\t\t, quantity\n\t\t\t\t, type\n\t\t\t\t, updated\n\t\t\t\t)\n\t\tVALUES\n\t\t\t ('#{h['number']}'\n\t\t\t , '#{h['invoice_id']}'\n\t\t\t , '#{h['line_id']}'\n\t\t\t , '#{h['order']}'\n\t\t\t , '#{h['description']}'\n\t\t\t , '#{h['amount']}'\n\t\t\t , '#{h['first_expense_id']}'\n\t\t\t , '#{h['first_time_entry_id']}'\n\t\t\t , '#{h['line_item_date']}'\n\t\t , '#{h['person']}'\n\t\t\t , '#{h['name']}'\n\t\t\t , '#{h['matter']}'\n\t\t\t , '#{h['unit_cost']}'\n\t\t\t , '#{h['quantity']}'\n\t\t\t , '#{h['type']}'\n\t\t\t , '#{h['updated']}'\n\t\t\t )\n\t\tSQL\n\tend", "def create\n @v1_item_line = V1::ItemLine.new(v1_item_line_params)\n\n if @v1_item_line.save\n render json: @v1_item_line, status: :created, location: @v1_item_line\n else\n render json: @v1_item_line.errors, status: :unprocessable_entity\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Destroy a booking line == Parameters:: item_id:: The item line id
def destroy_booking_line(item_id) product_lines = self.booking_lines.select do |booking_line| booking_line.item_id == item_id end if booking_line = product_lines.first transaction do self.item_cost -= booking_line.item_cost self.product_deposit_cost -= booking_line.product_deposit_cost self.category_supplement_1_cost -= booking_line.category_supplement_1_cost self.category_supplement_2_cost -= booking_line.category_supplement_2_cost self.category_supplement_3_cost -= booking_line.category_supplement_3_cost self.calculate_cost(false, false) self.save booking_line.destroy # Create newsfeed ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking', action: 'destroy_booking_line', identifier: self.id.to_s, description: BookingDataSystem.r18n.t.booking_news_feed.destroyed_booking_line(item_id), attributes_updated: {item_id: item_id}.merge({booking: newsfeed_summary}).to_json) end self.reload end end
[ "def destroy\n @item_line = ItemLine.find(params[:id])\n @item_line.destroy\n\n respond_to do |format|\n format.html { redirect_to item_lines_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @receivable = Receivable.find(params[:receivable_id])\n @receivable_line = @receivable.receivable_lines.find(params[:id])\n @receivable_line.destroy\n\n respond_to do |format|\n format.html { redirect_to(new_receivable_receivable_line_path(@receivable), :notice => 'Line item was successfully deleted.') }\n format.json { head :ok }\n end\n end", "def destroy\n @v1_item_line = V1::ItemLine.find(params[:id])\n @v1_item_line.destroy\n\n head :no_content\n end", "def destroy\n @line_item = LineItem.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :ok }\n end\n end", "def destroy\n @lineitem = Lineitem.find(params[:id])\n @lineitem.destroy\n\n respond_to do |format|\n format.html { redirect_to lineitems_url }\n format.json { head :ok }\n end\n end", "def destroy\n @line_item = LineItem.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to line_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @line_items = LineItem.find(params[:id])\n @line_item.destroy\n if @line_item.destroy\n render json: {status: :successfully}\n else\n render json: { status: error}\n end\n end", "def destroy\n @line_item = LineItem.find(params[:id])\n @line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to(line_items_url) }\n format.xml { head :ok }\n end\n end", "def destroy\r\n @lineitem = Lineitem.find(params[:id])\r\n @lineitem.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to(lineitems_url) }\r\n format.xml { head :ok }\r\n end\r\n end", "def destroy\n @invoice_line_item = InvoiceLineItem.find(params[:id])\n @invoice_line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to invoice_line_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @invoice_line_item = InvoiceLineItem.find(params[:id])\n @invoice_line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to invoice_line_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @payable = Payable.find(params[:payable_id])\n @payable_line = @payable.payable_lines.find(params[:id])\n @payable_line.destroy\n\n respond_to do |format|\n format.html { redirect_to(new_payable_payable_line_path(@payable), :notice => 'Line item was successfully deleted.') }\n format.json { head :ok }\n end\n end", "def destroy\n @schedule_line_item.destroy\n respond_to do |format|\n format.html { redirect_to schedule_line_items_url, notice: 'Schedule line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @invoice_line_item.destroy\n respond_to do |format|\n format.html { redirect_to invoice_line_items_url, notice: 'Invoice line item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @purchase_order_item_line = PurchaseOrderItemLine.find(params[:id])\n @purchase_order_item_line.destroy\n\n respond_to do |format|\n format.html { redirect_to purchase_order_item_lines_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @pit_form_lineitem.destroy\n respond_to do |format|\n format.html { redirect_to pit_form_lineitems_url, notice: 'Pit form lineitem was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n # destroys the line_item\n @line_item.destroy\n respond_to do |format|\n # AJAX is used to destroy the line item and remove it from the basket view without being\n # redirected to a list of line items\n # format.js is used to handle a javascript response.\n format.js\n end\n # the total cost of the basket is decreased by the price of the game\n @basket.total_cost -= @line_item.game.price\n # saves the basket because the total cost of the basket has been updated\n @basket.save\n end", "def destroy\n @service_line_item = ServiceLineItem.find(params[:id])\n @service_line_item.destroy\n\n respond_to do |format|\n format.html { redirect_to service_line_items_url }\n format.json { head :no_content }\n end\n end", "def destroy\n\n @po_line.so_line.destroy if @po_line.destroy && @po_line.so_line\n\n respond_to do |format|\n format.html { redirect_to new_po_header_po_line_path(@po_header), :notice => 'Line item was successfully deleted.' }\n format.json { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
EXTRAS Add a booking extra to the reservation
def add_booking_extra(extra_id, quantity) booking_extras = self.booking_extras.select do |booking_extra| booking_extra.extra_id == extra_id end if booking_extras.empty? if extra = ::Yito::Model::Booking::BookingExtra.get(extra_id) extra_translation = extra.translate(customer_language) booking_deposit = SystemConfiguration::Variable.get_value('booking.deposit', 0).to_i extra_unit_cost = extra.unit_price(self.date_from, self.days) transaction do # Create the booking extra line booking_extra = BookingDataSystem::BookingExtra.new booking_extra.booking = self booking_extra.extra_id = extra_id booking_extra.extra_description = extra.name booking_extra.extra_description_customer_translation = extra_translation.nil? ? extra.name : extra_translation.name booking_extra.quantity = quantity booking_extra.extra_unit_cost = extra_unit_cost booking_extra.extra_cost = extra_unit_cost * quantity booking_extra.save # Updates the booking self.extras_cost += (extra_unit_cost * quantity) self.calculate_cost(false, false) self.save # Create newsfeed ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking', action: 'add_booking_extra', identifier: self.id.to_s, description: BookingDataSystem.r18n.t.booking_news_feed.created_booking_extra(extra_id, quantity), attributes_updated: {extra_id: extra_id, quantity: quantity}.merge({booking: newsfeed_summary}).to_json) end end end end
[ "def add_reservation(start_date, end_date)\n @bookings << [start_date, end_date]\n end", "def add_reservation(reservation)\n @reservations << reservation\n end", "def add_extra_fields(*args)\n @extra_fields += [ *args ]\n @retain_fields += [ *args ]\n end", "def add_extra(extra_code, extra_description, quantity, extra_unit_cost)\n\t\t\tshopping_cart_extra = ShoppingCartExtraRenting.new\n\t\t\tshopping_cart_extra.shopping_cart = self\n\t\t\tself.extras << shopping_cart_extra\n\t\t\tshopping_cart_extra.set_item(extra_code, extra_description, \n\t\t\t\t\t\t\t\t\t\t extra_unit_cost, quantity)\n\t\tend", "def extra; @extra; end", "def added_extras=(_arg0); end", "def add_reservation_to_list(reservation)\n raise ArgumentError.new('Not a valid reservation.') if reservation.class != Hotel::Reservation\n @reservations << reservation\n end", "def add ( booking )\n raise Exception.new(\"The file has alreay been closed, cannot add new booking\") if @closed\n #the first booking decides wether all values are po or negative\n @value_pos = booking.pos? if bookings.empty?\n raise Exception.new(\"The prefix within bookings changed from #{@value_pos} to #{booking.pos?}\") if @value_pos != booking.pos?\n bookings << booking\n end", "def inject_reservation_book(reservation_book)\n @reservation_book = reservation_book\n end", "def extend\n reservation = Reservation.new(user_credentials)\n unless reservation.reservation_with_id(params[:id]).nil?\n @reservation = reservation.reservation_with_id(params[:id])\n \n # Current reservation times\n @start_time_string = Time.at(@reservation[:start_time].to_i).strftime(\"%I:%M %p %d/%m/%Y\")\n @end_time = Time.at(@reservation[:end_time].to_i)\n end_date = @end_time.to_date\n @end_time_string = @end_time.strftime(\"%I:%M %p %d/%m/%Y\")\n \n form_selection_options\n end\n end", "def place_reservation_for_instrument(ordered_by, instrument, account, reserve_start, extra_reservation_attrs = nil, purchased: false)\n order_detail = place_product_order(ordered_by, instrument.facility, instrument, account, purchased)\n\n instrument.schedule_rules.create(FactoryBot.attributes_for(:schedule_rule)) if instrument.schedule_rules.empty?\n res_attrs = {\n reserve_start_at: reserve_start,\n order_detail: order_detail,\n duration_mins: 60,\n split_times: true,\n }\n\n res_attrs.merge!(extra_reservation_attrs) if extra_reservation_attrs\n instrument.reservations.create(res_attrs)\nend", "def iamswer_extra_fields *extra_fields\n @iamswer_defined_extra_fields ||= []\n\n extra_fields.each do |extra_field|\n @iamswer_defined_extra_fields << extra_field.to_sym\n define_extra_field extra_field\n end\n end", "def addBook(book)\n\t\tinventories.create(book_id: book.id)\n\tend", "def add_additional_charge_line(section, al)\n # Note that all of these lines are 'Source' lines...\n @additional_charges_accounting_lines[section].add(al.merge({type: :source}))\n end", "def add ( booking )\n raise \"The file has alreay been closed, cannot add new booking\" if @closed\n #the first booking decides wether all values are po or negative\n @value_pos = booking.pos? if bookings.empty?\n raise \"The prefix within bookings changed from #{@value_pos} to #{booking.pos?}\" if @value_pos != booking.pos?\n bookings << booking\n end", "def place_reservation_for_instrument(ordered_by, instrument, account, reserve_start, extra_reservation_attrs=nil)\n order_detail = place_product_order(ordered_by, instrument.facility, instrument, account, false)\n\n instrument.schedule_rules.create(FactoryGirl.attributes_for(:schedule_rule)) if instrument.schedule_rules.empty?\n res_attrs={\n :reserve_start_at => reserve_start,\n :order_detail => order_detail,\n :duration_value => 60,\n :duration_unit => 'minutes'\n }\n\n res_attrs.merge!(extra_reservation_attrs) if extra_reservation_attrs\n instrument.reservations.create(res_attrs)\n end", "def add_book(book)\n @books << book\n puts \"We have just added the following NEW book '#{book.title}' to the Library\"\n end", "def add_extra_credit()\n raise \"unimplemented\"\n end", "def extras_resources_occupation(date_from, date_to, category=nil)\n\n hours_cadency = SystemConfiguration::Variable.get_value('booking.hours_cadence','2').to_f / 24\n\n\n # 1. Build the required_extras\n #\n # - The key is the extra_code\n # - The valus is a Hash\n #\n # :total # of resource urges for this extra (that has not been already assigned) [AFTER AUTO REASSIGN]\n # :assignation_pending List of reservations that requires the extra [AFTER AUTO REASSIGN]\n # :original_total # of resource urges for this extra [BEFORE AUTO REASSIGN]\n # :original_assignation_pending List of reservations that requires the item [BEFORE AUTO REASSIGN]\n # :reassign_total # of resource urges for this extra [HAVE BEEN AUTO REASSIGNED]\n # :reassigned_assignation_pending List of reservations that requires the extra [HAVE BEEN AUTO REASSIGNED]\n # :stock is a Hash\n # - The key the is the extra item reference\n # - The value is an array with the assigned (+ automatically assigned) reservations\n #\n extras = ::Yito::Model::Booking::BookingExtra.all(conditions: {active: true}, fields: [:code, :max_quantity], order: [:code])\n\n required_extras = extras.inject({}) do |result, extra|\n result.store(extra.code, {category_stock: extra.stock,\n total: 0,\n assignation_pending: [],\n original_total: 0,\n original_assignation_pending: [],\n reassigned_total: 0,\n reassigned_assignation_pending: [],\n stock: {}})\n result\n end\n\n #\n # 2. Build the stock detail structure\n #\n stock_detail = {}\n\n # 2.b create dummy resources (has has not stock items)\n required_extras.each do |extra_code, extra_value|\n if extra_value[:category_stock] > extra_value[:stock].size\n ((extra_value[:stock].size+1)..extra_value[:category_stock]).each do |idx|\n stock_id = \"DUMMY-#{extra_code}-#{idx}\"\n # Add dummy resource to the category stock detail\n extra_value[:stock].store(stock_id, [])\n # Add dummy resource to the stock detail\n stock_detail.store(stock_id, {category: extra_code,\n available: true,\n estimation: []})\n end\n end\n end\n\n #\n # 3. Fill with reservations urges\n #\n extras_urges = extras_urges(date_from, date_to)\n extras_urges.each do |extra_urge|\n extra_urge.instance_eval { class << self; self end }.send(:attr_accessor, :preassigned_item_reference)\n # Not assigned resource stock\n if required_extras.has_key?(extra_urge.extra_id)\n required_extras[extra_urge.extra_id][:total] += 1\n required_extras[extra_urge.extra_id][:assignation_pending] << extra_urge\n end\n end\n\n #\n # 4. Try to automatically assign stock to assignation pending (extras_urges)\n #\n required_extras.each do |required_extra_key, required_extra_value|\n\n required_extras[required_extra_key][:original_total] = required_extras[required_extra_key][:total]\n required_extras[required_extra_key][:original_assignation_pending] = required_extras[required_extra_key][:assignation_pending].clone\n\n # Clones the assignation pending resource urges (because we are going to manipulate it)\n assignation_pending_sources = required_extra_value[:assignation_pending].clone\n assignation_pending_sources.each do |assignation_pending_source|\n # Search stock items candidates\n candidates = required_extra_value[:stock].select do |item_reference, item_reference_assigned_reservations|\n item_reference_assigned_reservations.all? do |assigned|\n assign_pend_d_f = parse_date_time_from(assignation_pending_source.date_from, assignation_pending_source.time_from)\n assign_pend_d_t = parse_date_time_to(assignation_pending_source.date_to, assignation_pending_source.time_to)\n assigned_d_f = parse_date_time_from(assigned.date_from, assigned.time_from)\n assigned_d_t = parse_date_time_from(assigned.date_to, assigned.time_to)\n assignation_pending_source.date_to < (assigned.date_from - hours_cadency) || assignation_pending_source.date_from > (assigned.date_to + hours_cadency)\n end\n end\n\n if candidates.size > 0\n candidate_item_reference = candidates.keys.first\n # Apply reassignation\n required_extra_value[:total] -= 1\n required_extra_value[:assignation_pending].delete(assignation_pending_source)\n # Holds for history\n required_extra_value[:reassigned_total] += 1\n required_extra_value[:reassigned_assignation_pending] << assignation_pending_source\n # Append the assignation pending to the stock assigned\n required_extra_value[:stock][candidate_item_reference] << assignation_pending_source\n required_extra_value[:stock][candidate_item_reference].sort! {|x,y| x.date_from <=> y.date_from }\n if stock_detail.has_key?(candidate_item_reference)\n stock_detail[candidate_item_reference][:estimation] << assignation_pending_source\n end\n assignation_pending_source.preassigned_item_reference = candidate_item_reference\n stock_detail[candidate_item_reference][:available] = false\n end\n\n end\n\n end\n #\n #\n #\n extras_occupation = {}\n\n request_date_from =parse_date_time_from(date_from)\n request_date_to = parse_date_time_to(date_to)\n\n required_extras.each do |required_extra_key, required_extra_value|\n\n stock = required_extra_value[:category_stock]\n occupation = (stock_detail.select {|k,v| v[:category] == required_extra_key && (!v[:estimation].empty?) }).keys.count\n available_stock = (stock_detail.select {|k,v| v[:category] == required_extra_key && v[:estimation].empty? }).keys\n automatically_preassigned_stock = (stock_detail.select {|k,v| v[:category] == required_extra_key && !v[:estimation].empty? }).keys\n available_assignable_resource = (stock_detail.select do\n |k,v| v[:category] == required_extra_key && v[:estimation].empty? && stock_detail[k][:assignable]\n end).keys.count\n # If there is not stock, check if there are available assignable resources in order to admit reservations\n stock = occupation + available_assignable_resource if (stock <= occupation)\n\n extras_occupation.store(required_extra_key,\n {stock: stock,\n occupation: occupation,\n available_stock: available_stock ,\n automatically_preassigned_stock: automatically_preassigned_stock,\n assignation_pending: required_extra_value[:assignation_pending]})\n\n end\n\n return [stock_detail, extras_occupation]\n\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
BOOKING CHARGE Add a booking charge
def add_booking_charge(date, amount, payment_method_id) transaction do charge = Payments::Charge.new charge.date = date charge.amount = amount charge.payment_method_id = payment_method_id charge.status = :pending charge.currency = SystemConfiguration::Variable.get_value('payments.default_currency', 'EUR') charge.save booking_charge = BookingDataSystem::BookingCharge.new booking_charge.booking = self booking_charge.charge = charge booking_charge.save charge.update(:status => :done) self.reload # Create newsfeed ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking', action: 'add_booking_charge', identifier: self.id.to_s, description: BookingDataSystem.r18n.t.booking_news_feed.added_booking_charge(".2f" % amount, payment_method_id), attributes_updated: {date: date, amount: amount, payment_method_id: payment_method_id}.merge({booking: newsfeed_summary}).to_json) end end
[ "def add_charge()\n prompt = TTY::Prompt.new(symbols: {marker: \">\"})\n system('clear')\n puts \"Add new charge to #{@name} account ID: #{@id}\\n\\n\\n\"\n\n description = prompt.ask(\"Description:\", default: \"Work done on #{Debug::Date}\") do |q|\n q.validate(/^[\\:\\-\\/\\\\\\d\\w ]+$/)\n q.messages[:valid?] = \"Invalid Description, must be alphanumeric\"\n end\n flatfee = prompt.ask(\"Flat fee:\", default: 0) do |q|\n q.convert(:float, \"Invalid number\")\n end\n hours = prompt.ask(\"Total hours:\", default: 0) do |q|\n q.convert(:float, \"Invalid number\")\n end\n chargeperhour = prompt.ask(\"Charge per hour\", default: 0) do |q|\n q.convert(:float, \"Invalid number\")\n end\n\n @pendingcharges.push({\n description: description,\n hours: hours,\n chargeperhour: chargeperhour,\n flatfee: flatfee\n })\n save()\n end", "def add_charge(desc, bond)\n self[:charges] << {\n :desc => desc.to_s.strip,\n :bond => bond.to_s.gsub('$', '').strip.to_i\n \t}\n Log.d(\"Adding charge: #{self[:charges].last[:desc]}, #{self[:charges].last[:bond]}\")\n end", "def create_charge\n customer = Stripe::Customer.create(\n :email => params[:stripeEmail],\n :card => params[:stripeToken]\n )\n\n charge = Stripe::Charge.create(\n :customer => customer.id,\n :amount => Deal.find(current_consumer.orders.last[:deal_id]).price.to_i * 100,\n :description => 'Prlayvous Ticket',\n :currency => 'usd'\n )\n\n #After paying with Stripe, consumers are prompt to confirm their shipping address.\n redirect_to edit_consumer_order_path(current_consumer, @order)\n\n rescue Stripe::CardError => e\n flash[:error] = e.message\n redirect_to charges_path\n end", "def build_deposit_charge_detail\n\n charge_detail = [{:item_reference => 'DEPOSIT',\n \t :item_description => booking.charge_item_detail,\n \t :item_units => 1,\n \t :item_price => booking.booking_amount}]\n\n end", "def pay_service(number)\n percentage = num / 100.0\n current=self.my_current_booking\n #update the booking with the percentage for service charge\n current.update(service_charge: percentage) \n end", "def add_booking(gymclass)\n numofbookings = gymclass.count_num_of_bookings()\n if gymclass.check_space(numofbookings) == true\n save()\n else\n return \"We can't book it!\"\n end\n end", "def charge(amount)\n @balance += amount\n end", "def book_command\n Domain::Commands::BookCargoCommand.new(\n booking_amount: params.require(:booking_amount).to_i,\n origin_location: params.require(:origin_location),\n dest_location: params.require(:dest_location),\n dest_arrival_deadline: params.require(:dest_arrival_deadline).to_datetime\n )\n end", "def charge!\n # connect with FakepayApi\n # call method responsible for charge\n # update billing_date in subscription record\n puts \"Subscription ##{id} charged!\"\n end", "def create_booking(params)\n raise NotImplementedError\n end", "def new(cab_type, pickup_lat, pickup_long, drop_lat, drop_long)\n user = User.new(pickup_lat, pickup_long, drop_lat, drop_long)\n booking = Booking.new(@fleet, cab_type)\n\n return booking.new(user)\n end", "def make_booking(fitness_class)\n Booking.new('member_id' => @id, 'fitness_class_id' => fitness_class.id).save()\n update()\n end", "def buy_20_credits\n x_tran_key=\"9Pk82B77ab9nh7Nq\"\n @order=Purchase.new\n baseprice = 50\n amount = baseprice\t\n amount = amount.to_s() + \".00\"\n @amount = amount\n @order.amount = amount\n @order.credits = 20\n @order.number = number\n @order.state = \"pending\"\n loginid=\"8Ty3NvP8z7z\"\n fp = InsertFP(loginid, x_tran_key, @amount, \"0001\")\n id = session[:company_id]\n @company = Company.find(id)\n @order.company = id\n @order.save\n end", "def create\n @booking = Booking.new(booking_params)\n \n unless params[:subject_id].empty?\n @subject = Subject.find(params[:subject_id])\n end\n # TODO date and time validation\n begin\n date = (params['date_part'] + \" \" + params['time_part']).to_datetime\n rescue ArgumentError\n @booking.errors.add(:date, \"is invalid\")\n date = Date.new\n end\n @booking.booking_date = date\n # TODO: Refactor for admin booking creation\n @booking.shared = params[\"shared\"]\n @booking.subject = @subject\n # Add this customer as owner. \n @booking.creator = current_user.customer\n @booking.customers << current_user.customer\n @booking.booked_customers.first.number_students = params[:booking][:booked_customers][:number_students]\n @booking.period = 2\n \n # Create closed booking if customer came from searching or enquiring.\n if params[:presenter_id].present?\n presenter = Presenter.find(params[:presenter_id])\n if presenter.available? @booking.booking_date, @booking.duration_minutes\n @booking.chosen_presenter = Presenter.find(params[:presenter_id])\n @booking.rate = presenter.rate\n @booking.creator = current_user.customer\n else\n @booking.errors.add(:presenter, \"is not available at this time\")\n end\n end \n \n if @booking.save\n # Only send messages to customers if booking is shared\n @message = \"A new #{@booking.subject.name} booking has been created that you may be interested in.\"\n if @booking.shared?\n Notification.notify_applicable_users(current_user, @booking, \"customer\", booking_path(@booking), @message, :interested_booking)\n end\n # Only send messages to presenters if booking is open\n if @booking.chosen_presenter.nil?\n Notification.notify_applicable_users(current_user, @booking, \"presenter\", booking_path(@booking), @message, :interested_booking)\n end\n Notification.notify_admin(\"A new booking has been created\", booking_path(@booking), :booking)\n\n # Add booking to booked customers\n current_user.customer.created_bookings << @booking\n\n #clear search session \n session[:search_params] = nil\n redirect_to @booking\n else\n @date_part = params['date_part']\n @time_part = params['time_part']\n render :new\n end\n\n end", "def create_new_booking_oct(customer, space)\n new_booking = Booking.new\n new_booking.user = customer\n new_booking.space = space\n new_booking.date_start = DateTime.strptime(\"10/14/2019\", \"%m/%d/%Y\")\n new_booking.date_end = DateTime.strptime(\"10/14/2019\", \"%m/%d/%Y\")\n return new_booking\nend", "def create\n @accommodation_charge = @company.accommodation_charges.build(accommodation_charge_params)\n\n if @accommodation_charge.save\n redirect_to company_accommodation_charges_path( @company ), notice: t('notice.create', model_name: f(AccommodationCharge))\n else\n render :new\n end\n end", "def add_additional_charges(post, options)\n charges = options[:additional_charges]\n\n return if charges.blank?\n\n post[:Charges] = []\n\n charges.each do |charge|\n post[:Charges] << { Name: charge[:name], ConsumerPrice: charge[:price] }\n end\n end", "def booking_amount\n self.charges.booking.inject(0){|sum, charge| sum + charge.amount}\n end", "def register_booking\n return unless booked_at\n\n self.booked_at = ClockIn.new.recorded_as booked_time: booked_at.to_date,\n add_time: true\n credits.register_booking(self)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Destroy a booking charge
def destroy_booking_charge(charge_id) if booking_charge = BookingDataSystem::BookingCharge.first(:booking_id => self.id, :charge_id => charge_id) charge = booking_charge.charge transaction do if charge.status == :done self.total_paid -= charge.amount self.total_pending += charge.amount self.save end charge.destroy booking_charge.destroy # Create newsfeed ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking', action: 'destroy_booking_charge', identifier: self.id.to_s, description: BookingDataSystem.r18n.t.booking_news_feed.destroyed_booking_charge(".2f" % charge.amount, charge.payment_method_id), attributes_updated: {amount: charge.amount, payment_method_id: charge.payment_method_id}.to_json) end self.reload end end
[ "def destroy\n @booking_slot.destroy\n\n head :no_content\n end", "def destroy\n @charge = Charge.find(params[:id])\n @charge.destroy\n\n respond_to do |format|\n format.html { redirect_to charges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @set_booking_number.destroy\n\n head :no_content\n end", "def destroy\n @accommodation_charge.destroy\n respond_to do |format|\n format.html { redirect_to accommodation_charges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @charge = Charge.find(params[:id])\n @charge.destroy\n\n respond_to do |format|\n format.html { redirect_to(charges_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @charge.destroy\n respond_to do |format|\n format.html { redirect_to charges_url, notice: 'Charge was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @booking_time_control.destroy\n\n head :no_content\n end", "def destroy\n @batterycharge = Batterycharge.find(params[:id])\n @batterycharge.destroy\n\n respond_to do |format|\n format.html { redirect_to batterycharges_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @booking_clerk.destroy\n respond_to do |format|\n format.html { redirect_to booking_clerks_url, notice: 'Booking clerk was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @seller_charge.destroy\n respond_to do |format|\n format.html { redirect_to seller_charges_url, notice: 'Seller charge was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @c2charge.destroy\n respond_to do |format|\n format.html { redirect_to c2charges_url, notice: 'C2charge was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @auto_bill_payment.destroy\n redirect_to account_auto_bill_payments_url, notice: 'Auto bill payment was successfully destroyed.'\n end", "def destroy\n @event_charge = @event.charges.find(params[:id])\n @event_charge.destroy\n\n respond_to do |format|\n format.html { redirect_to event_path(@event, anchor: 'charges') }\n format.json { head :no_content }\n end\n end", "def destroy\n current_booking = current_user.bookings.last\n current_booking.destroy\n render status: :ok\n end", "def destroy\n @advance_booking.destroy\n respond_to do |format|\n format.html { redirect_to advance_bookings_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @billing_cycle.destroy\n respond_to do |format|\n format.html { redirect_to billing_cycles_url, notice: 'Billing cycle was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @call_charge.destroy\n respond_to do |format|\n format.html { redirect_to call_charges_url, notice: 'Call charge was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @consultationcharge = Consultationcharge.find(params[:id])\n @consultationcharge.destroy\n\n respond_to do |format|\n format.html { redirect_to(consultationcharges_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @gbooking = Gbooking.find(params[:id])\n @gbooking.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_gbookings_url) }\n format.xml { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the category of the reserved items
def category booking_lines and booking_lines.size > 0 ? ::Yito::Model::Booking::BookingCategory.get(booking_lines[0].item_id) : nil end
[ "def category\n fetch('fishbrain.equipment.categories')\n end", "def assigned_categories\n cats = quotations.collect { |q| q.categories }.flatten\n cat_ids = cats.collect { |c| c.id }.uniq\n Category.find(cat_ids)\n end", "def categories_for(item)\n return [] unless @items[item]\n\n @items[item].categories\n end", "def categories_items\n all_items = self.all_active_items\n categories_given_items(all_items)\n end", "def category\n return self.complaint_category.category\n end", "def agenda_item_category_name\n agenda_item_category.name if agenda_item_category\n end", "def reserved_stock_availabilty_in_distribution_center dc_id, items_count\n stock_inventories.available_stock_for_reduce(dc_id, items_count)\n end", "def category_with_name(name)\n categorized_items = categories_items\n categorized_items.detect{ |sub_item_array| sub_item_array[0].name == name }\n end", "def items_with_category(category, items=nil)\n items = @items if items.nil?\n items.select { |item| has_category?( item, category ) }\n end", "def categories_items_without(user)\n all_items = self.all_active_items\n categories_given_without(all_items,user)\n end", "def category\n # {{{\n if !@category then\n @category = Category.find(1).with(:is_private.is('t') & \n :category_id.in(User_Category.select(User_Category.category_id) { |cid| \n cid.where(User_Category.user_group_id == user_group_id)\n })).entity\n @category = Category.unassigned_category unless @category\n end\n @category\n end", "def categories\n value(\"CATEGORIES\")\n end", "def categories\n value('CATEGORIES')\n end", "def special_category\n @special_category ||= if character and character.group\n group_special = character.group.special\n if group_special.blank?\n nil\n else\n Category.specials(group_special)\n end\n elsif links_character\n Category.special_role(:links)\n elsif rps_character\n Category.special_role(:rps)\n end\n end", "def category\n return @category\n end", "def items_with_category(category)\n warn \"[DEPRECATION] \"+caller[0]+\"`items_with_category` is deprecated. Please use `items_with` instead.\"\n @items.select { |i| (i[:category] == category) }\n end", "def category(jid,node)\n info = get_info(jid,node)\n return info['category']\n end", "def user_category_selections\n categories = Category.find(:all, :order => \"feed_item_categories_count desc\", :limit => 20)\n categories << Category.new(:id => -1, :name => '--')\n categories << self.category unless self.category.nil?\n categories\n end", "def get_custom_gradebook_items(course_id, custom_category_id)\r\n get(Path::COURSES_GRADEBOOK_CUSTOMCATEGORIES_CUSTOMITEMS % [course_id, custom_category_id])\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the payment cadence is allowed
def payment_cadence_allowed? begin config_payment_cadence = SystemConfiguration::Variable.get_value('booking.payment_cadence').to_i _date_from_str = "#{self.date_from.strftime('%Y-%m-%d')}T#{self.time_from}:00#{self.date_from.strftime("%:z")}" _date_from = DateTime.strptime(_date_from_str,'%Y-%m-%dT%H:%M:%S%:z') diff_in_hours = ((_date_from.to_time - self.creation_date.to_time).to_f * 24).to_i allowed = diff_in_hours > 0 && (diff_in_hours >= config_payment_cadence) allowed || force_allow_payment rescue => error p "Error #{id} #{date_from} #{time_from} #{date_to} #{time_to} #{driver_date_of_birth} #{driver_driving_license_date}" return false end end
[ "def charge_is_allowed?\n\t\tif not customer_has_authorized_payment?\n\t\t\terrors.add :base, I18n.t('views.customer_file.new_charge.you_are_not_authorized')\n\t\t\tfalse\n\t\telsif valid? and charge_amount.present? and authorized_amount and charge_amount.to_i <= authorized_amount\n\t\t\ttrue\n\t\telse\n\t\t\terrors.add :charge_amount, I18n.t('views.customer_file.new_charge.invalid', amount: charge_amount_usd) if errors.empty?\n\t\t\tfalse\n\t\tend\n\tend", "def guard_check_payment\n true\n end", "def can_credit?(payment)\n payment.completed? && payment.credit_allowed > 0\n end", "def can_pay_deposit?\n\n conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool\n conf_payment_deposit = (['deposit','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit')))\n\n if self.status == :pending_confirmation\n (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and self.total_paid == 0 and ((!expired? and payment_cadence_allowed?) or force_allow_payment)\n elsif self.status == :confirmed # Confirmed in the back-office without payment\n (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and self.total_paid == 0 and self.total_pending > 0\n else\n return false\n end\n\n end", "def user_has_enough_credit?\n case @campaign.payment_type\n when \"coin\"\n if @campaign.owner.coin_credit < 0\n @campaign.errors.add(:budget, :not_enough_credit)\n end\n when \"like\"\n if @campaign.owner.like_credit < 0\n @campaign.errors.add(:budget, :not_enough_credit)\n end\n end\n end", "def valid?\n p = build_payment\n p.valid?\n end", "def payment_possible_for?(listing)\n listing.price && listing.price > 0 && payments_in_use?\n end", "def can_pay_pending?\n conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool\n conf_payment_deposit = (['deposit','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit')))\n conf_payment_pending = SystemConfiguration::Variable.get_value('booking.allow_pending_payment', 'false').to_bool\n if (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and conf_payment_pending and self.status != :cancelled\n self.total_paid > 0\n else\n return false\n end\n end", "def validate_balance_is_available\n if AccountTransaction.sufficient_funds?(self.request.startup.account, self.amount_paid, :escrow)\n self.errors.add(:request, \"startup doesn't have enough helpfuls to pay you, sorry\")\n false\n else\n true\n end\n end", "def payment_possible_for?(listing)\n listing.price && listing.price > 0 && stripe_in_use?\n end", "def paying_with_credit_card?\n payment_type == \"credit\"\n end", "def check(payment)\n retval\n end", "def can_accept_online_payment?\n if self.is_region_unit_meeting? and self.has_region_merchant_acct? and\n !self.region_merchant_currency.blank?\n return true\n end\n\n if self.is_section_unit_meeting? and self.has_section_merchant_acct? and\n !self.section_merchant_currency.blank?\n return true\n end\n\n return false\n end", "def claim_amount_required?\n @full_repayment_of_ads != 'Y'\n end", "def can_pay_deposit?\n\n conf_allow_deposit_payment = shopping_cart_items.any? { |shopping_cart_item| shopping_cart_item.item_custom_payment_allow_deposit_payment }\n can_pay_deposit = conf_allow_deposit_payment && payment_cadence?\n\n end", "def can_accept_donations\n self.goal_amount > 0\n end", "def payment_can_be_run?\n #@order.gift_card? || (!(backorder_allowed? && @order.order_items.any? {|e| e.product.out_of_stock?(current_system, e.quantity)}) && (is_sizzix? || (is_er? && @order && @order.address)) && !@order.payment.try(:purchase_order))\n !(backorder_allowed? && !is_er_us? && @order.order_items.any? {|e| e.product.out_of_stock?(current_system, e.quantity)}) && (is_sizzix? || (is_er? && @order && @order.address)) && !@order.payment.try(:purchase_order)\n end", "def payment_cadence?\n\n result = true\n shopping_cart_items.each do |item|\n result = result && Order.payment_cadence?(item.date) unless item.date.nil?\n end\n return result\n \n end", "def payment_success?\n @fields['decision'] == 'ACCEPT'\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the booking deposit can be paid
def can_pay_deposit? conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool conf_payment_deposit = (['deposit','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit'))) if self.status == :pending_confirmation (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and self.total_paid == 0 and ((!expired? and payment_cadence_allowed?) or force_allow_payment) elsif self.status == :confirmed # Confirmed in the back-office without payment (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and self.total_paid == 0 and self.total_pending > 0 else return false end end
[ "def can_pay_pending?\n conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool\n conf_payment_deposit = (['deposit','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit')))\n conf_payment_pending = SystemConfiguration::Variable.get_value('booking.allow_pending_payment', 'false').to_bool\n if (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and conf_payment_pending and self.status != :cancelled\n self.total_paid > 0\n else\n return false\n end\n end", "def payment_cadence_allowed?\n begin\n config_payment_cadence = SystemConfiguration::Variable.get_value('booking.payment_cadence').to_i\n _date_from_str = \"#{self.date_from.strftime('%Y-%m-%d')}T#{self.time_from}:00#{self.date_from.strftime(\"%:z\")}\"\n _date_from = DateTime.strptime(_date_from_str,'%Y-%m-%dT%H:%M:%S%:z')\n diff_in_hours = ((_date_from.to_time - self.creation_date.to_time).to_f * 24).to_i\n allowed = diff_in_hours > 0 && (diff_in_hours >= config_payment_cadence)\n allowed || force_allow_payment\n rescue => error\n p \"Error #{id} #{date_from} #{time_from} #{date_to} #{time_to} #{driver_date_of_birth} #{driver_driving_license_date}\"\n return false\n end\n end", "def deposit?\n !withdrawal?\n end", "def can_pay_deposit?\n\n conf_allow_deposit_payment = shopping_cart_items.any? { |shopping_cart_item| shopping_cart_item.item_custom_payment_allow_deposit_payment }\n can_pay_deposit = conf_allow_deposit_payment && payment_cadence?\n\n end", "def paid?\n !payment_entry.nil?\n end", "def can_pay_total?\n\n conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool\n conf_payment_total = (['total','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit')))\n\n if self.status == :pending_confirmation\n (conf_payment_enabled or force_allow_payment) and conf_payment_total and self.total_paid == 0 and ((!expired? and payment_cadence_allowed?) or force_allow_payment)\n elsif self.status == :confirmed # Confirmed in the back-office without payment\n (conf_payment_enabled or force_allow_payment) and conf_payment_total and self.total_paid == 0 and self.total_pending > 0\n else\n return false\n end\n\n end", "def payment_possible_for?(listing)\n listing.price && listing.price > 0 && payments_in_use?\n end", "def check_if_unpaying\n return false if self.paid_changed? && self.paid == false\n end", "def paid?\n status == 'paid'\n end", "def deposit_charged\n return @rate.deposit > 0\n end", "def prepaid?\n not postpaid?\n end", "def paid_in_full?\n !payment_outstanding?\n end", "def payed?\n !payment_entry.nil?\n end", "def can_be_paid?\n on_hold? && order_items.all? {|e| e.product.available?(self.system) && e.product.quantity(self.system) >= e.quantity}\n end", "def payment_possible_for?(listing)\n listing.price && listing.price > 0 && stripe_in_use?\n end", "def claim_amount_required?\n @full_repayment_of_ads != 'Y'\n end", "def can_payout\n Action::Payout if run_trains? && !declared_earnings?\n end", "def partially_paid?\n state_name == :partially_paid\n end", "def needs_to_pay?\n return false if self.admin? # admin always true\n \n # 30 days, really needs to pay\n return true if self.subscription.nil? && 14.days.ago > self.created_at \n \n # False if they need to pay their bill\n return true if self.subscription.nil?\n return false\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the booking pending amout can be paid
def can_pay_pending? conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool conf_payment_deposit = (['deposit','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit'))) conf_payment_pending = SystemConfiguration::Variable.get_value('booking.allow_pending_payment', 'false').to_bool if (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and conf_payment_pending and self.status != :cancelled self.total_paid > 0 else return false end end
[ "def paid_in_full?\n !payment_outstanding?\n end", "def is_pending?\n generated_at.nil? && !paid_on.nil?\n end", "def check_if_unpaying\n return false if self.paid_changed? && self.paid == false\n end", "def partially_paid?\n state_name == :partially_paid\n end", "def can_pay_deposit?\n\n conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool\n conf_payment_deposit = (['deposit','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit')))\n\n if self.status == :pending_confirmation\n (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and self.total_paid == 0 and ((!expired? and payment_cadence_allowed?) or force_allow_payment)\n elsif self.status == :confirmed # Confirmed in the back-office without payment\n (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and self.total_paid == 0 and self.total_pending > 0\n else\n return false\n end\n\n end", "def paid?\n status == 'paid'\n end", "def can_finish?\n self.payment_status == PTE::PaymentStatus.processing\n end", "def billed_or_paid?\n status == PAID || status == BILLED\n end", "def can_be_paid?\n on_hold? && order_items.all? {|e| e.product.available?(self.system) && e.product.quantity(self.system) >= e.quantity}\n end", "def can_pay_total?\n\n conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool\n conf_payment_total = (['total','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit')))\n\n if self.status == :pending_confirmation\n (conf_payment_enabled or force_allow_payment) and conf_payment_total and self.total_paid == 0 and ((!expired? and payment_cadence_allowed?) or force_allow_payment)\n elsif self.status == :confirmed # Confirmed in the back-office without payment\n (conf_payment_enabled or force_allow_payment) and conf_payment_total and self.total_paid == 0 and self.total_pending > 0\n else\n return false\n end\n\n end", "def must_pay_to_avoid_cancellation\n\t\tif @event.start_date < (Time.now + 1.week) && @event.paid == false \n\t\t\t#cannot book event\n\t\tend\n\tend", "def payment_pending?\n payment_state == PAYMENT_PENDING\n end", "def prepaid?\n not postpaid?\n end", "def paid?\n !payment_entry.nil?\n end", "def paid_up?\n if payment_item.is_a? GeneralPaymentItem\n outstanding_amount <= 0.0\n else\n nil\n end\n end", "def can_payout\n Action::Payout if run_trains? && !declared_earnings?\n end", "def not_paid_at_all\n\t\tget_cart_pending_balance == get_cart_price\n\tend", "def booked?\n if self.appointments.count == 0\n return false # It is not booked.\n elsif self.appointments.count == 2\n return true # It is booked.\n elsif self.appointments.count == 1 and !self.appointments.last.closed?\n return false # It is not booked.\n else\n return true # It is booked.\n end\n end", "def incomplete_payment?\n past_due || incomplete\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the booking total can be paid
def can_pay_total? conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool conf_payment_total = (['total','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit'))) if self.status == :pending_confirmation (conf_payment_enabled or force_allow_payment) and conf_payment_total and self.total_paid == 0 and ((!expired? and payment_cadence_allowed?) or force_allow_payment) elsif self.status == :confirmed # Confirmed in the back-office without payment (conf_payment_enabled or force_allow_payment) and conf_payment_total and self.total_paid == 0 and self.total_pending > 0 else return false end end
[ "def paid_enough?\n errors.add(:paid,'You don\\'t paid enough') unless self.product.value <= self.total_paid\n end", "def can_pay_pending?\n conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool\n conf_payment_deposit = (['deposit','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit')))\n conf_payment_pending = SystemConfiguration::Variable.get_value('booking.allow_pending_payment', 'false').to_bool\n if (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and conf_payment_pending and self.status != :cancelled\n self.total_paid > 0\n else\n return false\n end\n end", "def check_paid\n self.paid_amount = 0\n self.paid = false\n payments.each do |payment|\n self.paid_amount += payment.amount\n end\n \n if self.paid_amount - self.gross_amount >= 0\n self.paid = true\n end\n end", "def check_paid\n self.paid_amount = 0\n self.paid = false\n payments.each do |payment|\n self.paid_amount += payment.amount\n end\n\n if self.paid_amount - self.gross_amount >= 0\n self.paid = true\n end\n end", "def payment_possible_for?(listing)\n listing.price && listing.price > 0 && payments_in_use?\n end", "def paid_in_full?\n !payment_outstanding?\n end", "def can_be_paid?\n on_hold? && order_items.all? {|e| e.product.available?(self.system) && e.product.quantity(self.system) >= e.quantity}\n end", "def can_pay_deposit?\n\n conf_payment_enabled = SystemConfiguration::Variable.get_value('booking.payment', 'false').to_bool\n conf_payment_deposit = (['deposit','deposit_and_total'].include?(SystemConfiguration::Variable.get_value('booking.payment_amount_setup', 'deposit')))\n\n if self.status == :pending_confirmation\n (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and self.total_paid == 0 and ((!expired? and payment_cadence_allowed?) or force_allow_payment)\n elsif self.status == :confirmed # Confirmed in the back-office without payment\n (conf_payment_enabled or force_allow_payment) and conf_payment_deposit and self.total_paid == 0 and self.total_pending > 0\n else\n return false\n end\n\n end", "def check_if_unpaying\n return false if self.paid_changed? && self.paid == false\n end", "def paid?\n status == 'paid'\n end", "def paid?\n !payment_entry.nil?\n end", "def not_paid_at_all\n\t\tget_cart_pending_balance == get_cart_price\n\tend", "def postpaid?\n postpaid.to_i == 1\n end", "def payment_possible_for?(listing)\n listing.price && listing.price > 0 && stripe_in_use?\n end", "def validate_amount\n amount = sale.total_amount\n sales_id = sale.id\n sale_penalty = sale.penalty\n total_payment = 0\n total_amount_sale = amount + sale_penalty\n payments_query = Payment.where(sale_id: sales_id)\n payments_query.each do |payment|\n total_payment += payment.amount\n end\n if total_payment == total_amount_sale\n sale.customer.update(state: \"sinDeuda\")\n sale.pago!\n else\n unless sale.customer.state == \"conDeuda\"\n sale.customer.update(state: \"conDeuda\")\n end\n end\n end", "def balance_sufficient?\n @money_required <= @balance\n end", "def paid_up?\n if payment_item.is_a? GeneralPaymentItem\n outstanding_amount <= 0.0\n else\n nil\n end\n end", "def paid?\n unless self.last_paid_at.blank?\n return Time.now - 365.days < self.last_paid_at\n else\n return false\n end\n end", "def claim_amount_required?\n @full_repayment_of_ads != 'Y'\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of the other people involved in the contract (extracted from resources)
def contract_other_people result = [] booking_line_resources.each do |resource| result << { :name => resource.resource_user_name, :surname => resource.resource_user_surname, :document_id => resource.resource_user_document_id, :phone => resource.resource_user_phone, :email => resource.resource_user_email } if resource.resource_user_name != customer_name and resource.resource_user_surname != customer_surname if resource.pax == 2 result << { :name => resource.resource_user_2_name, :surname => resource.resource_user_2_surname, :document_id => resource.resource_user_2_document_id, :phone => resource.resource_user_2_phone, :email => resource.resource_user_2_email } if resource.resource_user_2_name != customer_name and resource.resource_user_2_surname != customer_surname end end return result end
[ "def involved_users\n involv_splits = self.project_splits.where(role: \"Involved\")\n names = []\n if involv_splits.any?\n\n # put names into array\n involv_splits.each do |x|\n names << x.user.name\n end\n # Return names in array\n names\n else\n names << \"None\"\n end\n end", "def owners\n find_related_frbr_objects( :is_owned_by, :which_roles?) \n end", "def find_participants_and_coordinators\n hash = {}\n x = self.find_coordinators\n x.each do |c|\n hash[c.name] = c.own_participants\n end\n return hash\n end", "def owners\n cars_serviced.map do |car|\n car.owner\n end\n end", "def collect_everyone_related_to_this_reservation\n party_people = participants + participations.active.includes(:user).map(&:user)\n owners = [user]\n (party_people + owners + coaches).uniq.select do |entity|\n # We are not interested in Guests\n [User, Coach, Group].any?(&entity.method(:is_a?))\n end\n end", "def owners_of_cars_serviced\n self.personal_mechanic_of.map{|owner_obj| owner_obj.name}\nend", "def participants #igger loudin\n participating_users.includes(:user).map(&:user)\n end", "def participants\n expose Challenge.participants(@oauth_token, params[:challenge_id].strip)\n end", "def get_related_party\n party = observers.map { |o| o.user.cybozu_id }\n party += participants.map { |p| p.user.cybozu_id }\n party.uniq.compact\n end", "def owners\n api_path = '/users'\n @resp = self.class.get(api_path, default_request_data)\n resp_parsing\n end", "def specific_endorsing_orgs\n candidate = Candidate.find_by(user: self)\n endorsements = Endorsement.where(candidate: candidate)\n twitterusers = endorsements.reverse.map { |endorsement| endorsement.user.twitteruser\n }\n end", "def find_other_people(my_role, their_role)\n events = find_events(my_role)\n other_participants = Array.new\n events.each do |e| \n e.participations.each do |p|\n other_participants << p.person if (p.role == their_role.to_s and !p.person.nil? and p.person != self)\n end\n end\n other_participants\n end", "def owners\n get_emails @properties['Owner']\n end", "def people\n\t\t\t\t\tif @people.nil?\n\t\t\t\t\t\t@people = self.class.people(self.ref, self.params)\n\t\t\t\t\tend\n\t\t\t\t\treturn @people\n\t\t\t\tend", "def get_other_contacts(matter)\n client_contacts = matter.client_contacts\n client_contacts << matter.primary_matter_contact\n client_contacts.compact\n end", "def originator_list \n @board_design_entries = BoardDesignEntry.get_user_entries(@logged_in_user)\n @other_entries = BoardDesignEntry.get_other_pending_entries(@logged_in_user)\n end", "def getParticipants\r\n\t\t\t\t\treturn @participants\r\n\t\t\t\tend", "def participants\n return @participants\n end", "def additional_owners()\n return @additional_owners\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an online charge
def create_online_charge!(charge_payment, charge_payment_method_id) if total_pending > 0 and charge_payment_method = Payments::PaymentMethod.get(charge_payment_method_id.to_sym) and not charge_payment_method.is_a?Payments::OfflinePaymentMethod and !([:deposit, :pending, :total].find_index(charge_payment.to_sym)).nil? amount = case charge_payment.to_sym when :deposit booking_deposit when :total total_cost when :pending total_pending end charge = new_charge!(charge_payment_method_id, amount) if amount > 0 save return charge end end
[ "def create_online_charge!(charge_payment, charge_payment_method_id)\n \n if total_pending > 0 and \n charge_payment_method = Payments::PaymentMethod.get(charge_payment_method_id.to_sym) and\n not charge_payment_method.is_a?Payments::OfflinePaymentMethod \n\n amount = case charge_payment.to_sym\n when :deposit\n reservation_amount\n when :total\n total_cost\n when :pending\n total_pending\n end\n \n charge = new_charge!(charge_payment_method_id, amount) if amount > 0\n save\n return charge\n end \n\n end", "def create_charge\n customer = Stripe::Customer.create(\n :email => params[:stripeEmail],\n :card => params[:stripeToken]\n )\n\n charge = Stripe::Charge.create(\n :customer => customer.id,\n :amount => Deal.find(current_consumer.orders.last[:deal_id]).price.to_i * 100,\n :description => 'Prlayvous Ticket',\n :currency => 'usd'\n )\n\n #After paying with Stripe, consumers are prompt to confirm their shipping address.\n redirect_to edit_consumer_order_path(current_consumer, @order)\n\n rescue Stripe::CardError => e\n flash[:error] = e.message\n redirect_to charges_path\n end", "def create\n customer = StripeTool.create_customer(email: params[:stripeEmail], stripe_token: params[:stripeToken])\n\n\tcharge = StripeTool.create_charge(customer_id: customer.id, amount: @amount, description: @description)\n\n current_user.stripe_id = customer.id\n\n\treceipt = Charge.new charge_stripe_token: charge.id, price: @amount, description: @description)\n\n\tif Charge.save\n\n\telse\n\n\tend", "def create_gocardless_subscription\n GO_CARDLESS_CLIENT.subscriptions.create(\n params: {\n amount: User::PLAN_AMOUNT.to_i,\n currency: User::GO_CARDLESS_CURRENCY,\n name: User::GO_CARDLESS_NAME,\n interval_unit: User::INTERVAL_UNIT,\n interval: 1,\n start_date: Date.current + 2.month,\n day_of_month: 1,\n links: {\n mandate: current_user.go_cardless_mandate\n }\n }\n )\n end", "def charge!\n # connect with FakepayApi\n # call method responsible for charge\n # update billing_date in subscription record\n puts \"Subscription ##{id} charged!\"\n end", "def create\n @curpg = :discharges\n @discharge = Discharge.new(params[:discharge])\n\n respond_to do |format|\n if @discharge.save\n format.html { redirect_to :controller => \"discharges\", :action => \"index\" }\n format.json { render json: @discharge, status: :created, location: @discharge }\n else\n format.html { render action: \"new\" }\n format.json { render json: @discharge.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_charge()\n prompt = TTY::Prompt.new(symbols: {marker: \">\"})\n system('clear')\n puts \"Add new charge to #{@name} account ID: #{@id}\\n\\n\\n\"\n\n description = prompt.ask(\"Description:\", default: \"Work done on #{Debug::Date}\") do |q|\n q.validate(/^[\\:\\-\\/\\\\\\d\\w ]+$/)\n q.messages[:valid?] = \"Invalid Description, must be alphanumeric\"\n end\n flatfee = prompt.ask(\"Flat fee:\", default: 0) do |q|\n q.convert(:float, \"Invalid number\")\n end\n hours = prompt.ask(\"Total hours:\", default: 0) do |q|\n q.convert(:float, \"Invalid number\")\n end\n chargeperhour = prompt.ask(\"Charge per hour\", default: 0) do |q|\n q.convert(:float, \"Invalid number\")\n end\n\n @pendingcharges.push({\n description: description,\n hours: hours,\n chargeperhour: chargeperhour,\n flatfee: flatfee\n })\n save()\n end", "def charge!\n\t\tprice = self.service.price\n\t\tself.lendee.charge!(price)\n\tend", "def create\n @gnc_charge = GncCharge.new(gnc_charge_params)\n\n respond_to do |format|\n if @gnc_charge.save\n format.html { redirect_to @gnc_charge, notice: \"Gnc charge was successfully created.\" }\n format.json { render :show, status: :created, location: @gnc_charge }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @gnc_charge.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @credit_charge = CreditCharge.new(credit_charge_params)\n\n respond_to do |format|\n if @credit_charge.save\n format.html { redirect_to @credit_charge, notice: 'Credit charge was successfully created.' }\n format.json { render :show, status: :created, location: @credit_charge }\n else\n format.html { render :new }\n format.json { render json: @credit_charge.errors, status: :unprocessable_entity }\n end\n end\n end", "def charge_card\n\t\tbegin\n\t\t\t#Sovrascrive altri metodi\n\t\t\tsave!\n\t\t\t\n\t\t\tcharge = Stripe::Charge.create(\n\t\t\t\tamount: self.amount,\n\t\t\t\tcurrency: \"eur\",\n\t\t\t\tcard: self.stripe_token,\n\t\t\t\tdescription: \"vendita di un contenuto\"\n\t\t\t\t) \n\t\t\tself.update(stripe_id: charge.id)\n\t\t\t#Sovrascrivere le operazioni precedenti\n\t\t\tself.complete!\n\n\t\t#Se c'è qualche problema con la transazione \n\t\trescue Stipe::StripeError => e\n\t\t\tself.update_attributes(error: e.message)\n\t\t\tself.fail!\n\t\tend\n\n\tend", "def stripepay\n @rent = Rent.find(params[:id])\n @tenant = Tenant.find(session[:user_id])\n @property = Property.find(@tenant.property_id)\n @manager = Manager.find(@property.manager_id)\n @Customer = Stripe::Customer.retrieve(@tenant.stripe_user_id)\n @charge = Stripe::Charge.create({\n :amount => @tenant.rentNum,\n :currency => 'usd',\n :customer => @Customer,\n :destination => {\n :acount => @manager.stripe_user_id } ,\n :description => \"#{@property.name} Rent #{@rent.due}, #{@tenant.name}\"})\n end", "def create\n @breadcrumb = 'create'\n @charge_account = ChargeAccount.new(params[:charge_account])\n @charge_account.created_by = current_user.id if !current_user.nil?\n\n respond_to do |format|\n if @charge_account.save\n format.html { redirect_to @charge_account, notice: crud_notice('created', @charge_account) }\n format.json { render json: @charge_account, status: :created, location: @charge_account }\n else\n @projects = projects_dropdown\n @groups = groups_dropdown\n @ledger_accounts = projects_ledger_accounts(@projects)\n format.html { render action: \"new\" }\n format.json { render json: @charge_account.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @charge_master = ChargeMaster.new(params[:charge_master])\n end", "def buy_20_credits\n x_tran_key=\"9Pk82B77ab9nh7Nq\"\n @order=Purchase.new\n baseprice = 50\n amount = baseprice\t\n amount = amount.to_s() + \".00\"\n @amount = amount\n @order.amount = amount\n @order.credits = 20\n @order.number = number\n @order.state = \"pending\"\n loginid=\"8Ty3NvP8z7z\"\n fp = InsertFP(loginid, x_tran_key, @amount, \"0001\")\n id = session[:company_id]\n @company = Company.find(id)\n @order.company = id\n @order.save\n end", "def add_booking_charge(date, amount, payment_method_id)\n\n transaction do\n charge = Payments::Charge.new\n charge.date = date\n charge.amount = amount\n charge.payment_method_id = payment_method_id\n charge.status = :pending\n charge.currency = SystemConfiguration::Variable.get_value('payments.default_currency', 'EUR')\n charge.save\n booking_charge = BookingDataSystem::BookingCharge.new\n booking_charge.booking = self\n booking_charge.charge = charge\n booking_charge.save\n charge.update(:status => :done)\n self.reload\n # Create newsfeed\n ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking',\n action: 'add_booking_charge',\n identifier: self.id.to_s,\n description: BookingDataSystem.r18n.t.booking_news_feed.added_booking_charge(\".2f\" % amount, payment_method_id),\n attributes_updated: {date: date, amount: amount, payment_method_id: payment_method_id}.merge({booking: newsfeed_summary}).to_json)\n end\n\n end", "def create\n @charge_cpm = ChargeCpm.new(params[:charge_cpm])\n\n respond_to do |format|\n if @charge_cpm.save\n flash[:notice] = 'ChargeCpm was successfully created.'\n format.html { redirect_to(@charge_cpm) }\n format.xml { render :xml => @charge_cpm, :status => :created, :location => @charge_cpm }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @charge_cpm.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @credit_card_charge = CreditCardCharge.new(credit_card_charge_params)\n\n respond_to do |format|\n if @credit_card_charge.save\n format.html { redirect_to @credit_card_charge, notice: 'Credit card charge was successfully created.' }\n format.json { render :show, status: :created, location: @credit_card_charge }\n else\n format.html { render :new }\n format.json { render json: @credit_card_charge.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @call_charge = CallCharge.new(call_charge_params)\n\n respond_to do |format|\n if @call_charge.save\n format.html { redirect_to @call_charge, notice: 'Call charge was successfully created.' }\n format.json { render :show, status: :created, location: @call_charge }\n else\n format.html { render :new }\n format.json { render json: @call_charge.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Confirms the booking A booking can only be confirmed if it's pending confirmation and contains a done charge
def confirm if status == :pending_confirmation and not charges.select { |charge| charge.status == :done }.empty? transaction do self.status = :confirmed self.save # Assign available stock assign_available_stock if SystemConfiguration::Variable.get_value('booking.assignation.automatic_resource_assignation', 'false').to_bool # Create newsfeed ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking', action: 'confirm_booking', identifier: self.id.to_s, description: BookingDataSystem.r18n.t.confirmed_booking) end send_booking_confirmation_notifications else p "Could not confirm booking #{id} #{status}" end self end
[ "def confirm!\n if @status == Done then\n @status = Confirmed\n @completed_at = Date.today\n end\n end", "def confirm!\n self.pending = false\n self.save\n self.createDebts\n end", "def confirm\n if status == :pending_confirmation and\n not charges.select { |charge| charge.status == :done }.empty?\n self.status = :confirmed\n order_items.each do |order_item|\n order_item.status = :confirmed \n end\n save\n notify_manager_confirmation\n notify_customer \n else\n p \"Could not confirm order #{id} #{status}\"\n end\n \n self\n end", "def confirmed?\n self.status >= 0\n end", "def confirmed?\n confirmations >= 120\n end", "def confirmed?\n if confirmed\n true\n else\n false\n end\n end", "def confirmed?\n confirmation == 'yes'\n end", "def confirm!\n if status == :pending_confirmation\n transaction do\n update(:status => :confirmed)\n # Assign available stock\n assign_available_stock if SystemConfiguration::Variable.get_value('booking.assignation.automatic_resource_assignation', 'false').to_bool\n # Create newsfeed\n ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking',\n action: 'confirm_booking',\n identifier: self.id.to_s,\n description: BookingDataSystem.r18n.t.confirmed_booking)\n end\n send_booking_confirmation_notifications\n end\n self\n end", "def ensure_eligible_for_confirmation\n unless @offering.confirmations_allowed?\n flash[:error] = \"We're sorry, but the confirmation process is currently disabled.\"\n redirect_to apply_url(@offering) and return\n end\n unless @user_application.passed_status?(\"fully_accepted\") || @user_application.passed_status?(\"fully_accepted_vad\")\n flash[:error] = \"You cannot go through the confirmation process until your application has been fully accepted.\"\n redirect_to apply_url(@offering) and return\n end\n end", "def confirm_advanced_payment\n self.status = :waiting_for_payment\n # byebug\n send_confirmation_mail Mailtemplate.find_by(key: 'booking_confirmation_email_advanced_payment')\n end", "def confirmar!\n unless confirmado?\n self.account_movement_payments.each do |payment|\n payment.update(confirmed: true)\n payment.confirmar\n end\n set_total_and_amount_available ##redundante?\n set_saldo\n self.active = true\n self.tiempo_de_confirmacion = DateTime.now ##bloquea el movimiento para que el saldo y el total no vuelvan a ser calculado\n self.save\n self.client.update_debt ##para que actualice su saldo con este movimiento de cuenta corriente\n end\n end", "def confirmed?\n\t\tconfirmed\n\tend", "def confirmed?\n confirmation == 'yes'\n end", "def is_confirmed?\n return self.status == Erp::QuickOrders::Order::STATUS_CONFIRMED\n end", "def confirmed?\n state == 'confirmed'\n end", "def confirm!\n no_stock_of = self.order_items.select(&:validate_stock_levels)\n unless no_stock_of.empty?\n raise Shoppe::Errors::InsufficientStockToFulfil, :order => self, :out_of_stock_items => no_stock_of\n end\n \n run_callbacks :confirmation do\n # If we have successfully charged the card (i.e. no exception) we can go ahead and mark this\n # order as 'received' which means it can be accepted by staff.\n self.status = 'received'\n self.received_at = Time.now\n self.save!\n\n self.order_items.each(&:confirm!)\n\n # Send an email to the customer\n deliver_received_order_email\n end\n \n # We're all good.\n true\n end", "def confirmed?\n self.contributions.each do |contribution|\n return false if contribution.isPending?\n end\n return true\n end", "def confirm!\n no_stock_of = self.order_items.select(&:validate_stock_levels)\n unless no_stock_of.empty?\n raise Errors::InsufficientStockToFulfil, :order => self, :out_of_stock_items => no_stock_of\n end\n \n run_callbacks :confirmation do\n # If we have successfully charged the card (i.e. no exception) we can go ahead and mark this\n # order as 'received' which means it can be accepted by staff.\n self.status = 'received'\n self.received_at = Time.now\n self.save!\n\n self.order_items.each(&:confirm!)\n\n # Send an email to the customer\n OrderMailer.received(self).deliver\n end\n \n # We're all good.\n true\n end", "def awaiting_confirmation\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Confirm the booking without checking the charges
def confirm! if status == :pending_confirmation transaction do update(:status => :confirmed) # Assign available stock assign_available_stock if SystemConfiguration::Variable.get_value('booking.assignation.automatic_resource_assignation', 'false').to_bool # Create newsfeed ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking', action: 'confirm_booking', identifier: self.id.to_s, description: BookingDataSystem.r18n.t.confirmed_booking) end send_booking_confirmation_notifications end self end
[ "def confirm\n if status == :pending_confirmation and\n not charges.select { |charge| charge.status == :done }.empty?\n transaction do\n self.status = :confirmed\n self.save\n # Assign available stock\n assign_available_stock if SystemConfiguration::Variable.get_value('booking.assignation.automatic_resource_assignation', 'false').to_bool\n # Create newsfeed\n ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking',\n action: 'confirm_booking',\n identifier: self.id.to_s,\n description: BookingDataSystem.r18n.t.confirmed_booking)\n end\n send_booking_confirmation_notifications\n else\n p \"Could not confirm booking #{id} #{status}\"\n end\n \n self\n end", "def confirm_advanced_payment\n self.status = :waiting_for_payment\n # byebug\n send_confirmation_mail Mailtemplate.find_by(key: 'booking_confirmation_email_advanced_payment')\n end", "def confirm!\n self.pending = false\n self.save\n self.createDebts\n end", "def confirm!\n if @status == Done then\n @status = Confirmed\n @completed_at = Date.today\n end\n end", "def booking_confirmation\n booking.try(:confirmation)\n end", "def awaiting_confirmation\n end", "def ensure_eligible_for_confirmation\n unless @offering.confirmations_allowed?\n flash[:error] = \"We're sorry, but the confirmation process is currently disabled.\"\n redirect_to apply_url(@offering) and return\n end\n unless @user_application.passed_status?(\"fully_accepted\") || @user_application.passed_status?(\"fully_accepted_vad\")\n flash[:error] = \"You cannot go through the confirmation process until your application has been fully accepted.\"\n redirect_to apply_url(@offering) and return\n end\n end", "def confirm\n # Cannot do with guest account\n return unless current_user \n do_checkout\n end", "def confirm\n ur = UserReservation.find(params[:user_reservation_id])\n\n ur.transaction do\n case_history = ur.ur_turk_case.ur_turk_case_histories.new({\n action:UrTurkCaseHistory.actions[:confirm], action_by:current_user.id\n })\n case_history.save!\n ur.operator_confirmed!\n ur.reservation_confirmed!\n\n #send out email\n UserReservationMailer.operator_confirmed(ur).deliver_later\n end\n\n #TODO: handle if transaction failed\n head :ok\n end", "def confirmar!\n unless confirmado?\n self.account_movement_payments.each do |payment|\n payment.update(confirmed: true)\n payment.confirmar\n end\n set_total_and_amount_available ##redundante?\n set_saldo\n self.active = true\n self.tiempo_de_confirmacion = DateTime.now ##bloquea el movimiento para que el saldo y el total no vuelvan a ser calculado\n self.save\n self.client.update_debt ##para que actualice su saldo con este movimiento de cuenta corriente\n end\n end", "def cancel_booking\n data = Booking.booking_cancel_finder(@booking,params[:drop_off_date].to_date)\n if data.class == Stripe::InvalidRequestError\n redirect_to :back, :notice => \"Stripe error: #{data.message}\"\n else\n Message.create(:sender_id => @booking.user_id, :recipient_id => @booking.poster_id,\n :post_id => @booking.post_id,:body => \"Booking is cancel\")\n transfer_payment = @booking.update_columns(refund_finder: data)\n Post.add_area(@booking)\n PaymentHistory.create(:name => \"cancel\", :booking_id => @booking.id)\n flash[:notice] = \"Booking is cancel & $#{data} is refunded\"\n redirect_to booking_path(@booking.id)\n end\n end", "def confirmation_abonnement\n \n end", "def accept\n\t\t@enquiry.status = :accepted\n\t\t@enquiry.save\n\t\tif current_user.customer?\n\t\t\t@message = \"#{@enquiry.presenter.get_private_full_name(current_user)} has accepted the request, please confirm the booking.\"\n\t\t\tflash[:success] = \"Please confirm the booking.\"\n\t\telsif current_user.presenter?\n\t\t\t@message = \"#{@enquiry.customer.school_info.school_name} has accepted the request, please confirm the booking.\"\n\t\tflash[:success] = \"Enquiry sent and accepted.\"\n\t\tend\n\t\tNotification.send_message(@enquiry.customer.user, @message, enquiry_path(@enquiry), :accept_enquiry)\n\t\tNotification.notify_admin(@message, enquiry_path(@enquiry), :accept_enquiry)\n\t\tredirect_to enquiry_path(@enquiry)\n\tend", "def confirmation\n\n end", "def confirm_standard_payment\n self.status = :confirmed\n if product.is_a? OnlineEvent\n mailtemplate_key = 'booking_confirmation_email_online_event'\n else\n mailtemplate_key = 'booking_confirmation_email'\n end\n send_confirmation_mail Mailtemplate.find_by(key: mailtemplate_key)\n end", "def confirm_account\n confirm\n end", "def cancel\n \n reservation = Reservation.where(:id => params[:reservation_id]).first\n room_info = reservation.reservation_rooms.where(:id => params[:res_room]).first \n @booking_information = Reservation.get_cancel_reservation_info(reservation,room_info)\n \n if request.post?\n booking_data = {\n \"itinerary_id\" => params[:itinerary_number],\n \"confirmation_number\" => params[:confirmation_number],\n \"email\" => params[:email]\n }\n \n (HotelService.new).cancel(booking_data)\n \n tooltip = \"Booking Amount: #{room_info.rate}<br/>\n Cancellation Charge: #{room_info.rate - params[:refund].to_f}<br/>\n Refund: #{params[:refund].to_f}\"\n room_info.update_attributes({:status => 'Cancelled',\n :rate => room_info.rate - params[:refund].to_f,\n :taxes_fees => 0,\n :tooltip => tooltip}) \n \n \n UserMailer.cancellation_mail(reservation.user_email,@booking_information).deliver \n reservation.update_total_rate_and_status_and_adults_and_children\n redirect_to reservation_path(params[:reservation_id])\n return \n end\n end", "def cancel_booking\n\n\t\tamount = @booking.price\n\t\tdata = Booking.booking_cancel(@booking)\n\t\tif data.class == Stripe::InvalidRequestError\n\t\t redirect_to :back, :notice => \"Stripe error while creating customer: #{data.message}\"\n\t\telse\n\t\t PaymentHistory.create(:name => \"cancel\", :booking_id => @booking.id)\n\t flash[:notice] = \"Booking is cancel & $#{amount} is refunded. \"\n\t redirect_to order_receives_path\n\t\tend\n\tend", "def check_expiration\n return unless @reservation.booking_request_expired?\n\n flash[:danger] = 'Booking request has expired.'\n redirect_to your_reservations_path\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cancels a booking A booking can only be cancelled if it isn't already cancelled
def cancel unless status == :cancelled transaction do if total_paid > 0 update(:status => :cancelled, :payment_status => :refunded, :total_paid => 0, :total_pending => total_cost) else update(:status => :cancelled) end # Create newsfeed ::Yito::Model::Newsfeed::Newsfeed.create(category: 'booking', action: 'cancel_booking', identifier: self.id.to_s, description: BookingDataSystem.r18n.t.canceled_booking) charges.each do |charge| charge.refund end end end self end
[ "def canceled?\n !!booking.try(:canceled?)\n end", "def cancel_booking\n @booking = Booking.find(params[:id])\n if @booking.booking_date > Time.now\n if params[:cancellation_message].strip == \"\" || params[:cancellation_message].nil?\n flash[:danger] = \"Message needs to be specified before cancelling a booking.\"\n redirect_to booking_path(@booking)\n else\n if current_user.customer == @booking.creator || current_user.presenter == @booking.chosen_presenter || current_user.admin?\n @booking.cancellation_message = params[:cancellation_message]\n @booking.destroy\n # TODO: Notifications dont appear to be sent \n Notification.cancelled_booking(@booking, booking_path(@booking))\n @booking.save\n flash[:success] = \"Booking has been cancelled and potential participants notified!\"\n redirect_to booking_path(@booking)\n else\n redirect_to root_url\n end\n end\n else\n flash[:danger] = \"Booking cannot be cancelled as it has already been completed\"\n redirect_to booking_path(@booking)\n end\n end", "def cancel_booking\n\n\t\tamount = @booking.price\n\t\tdata = Booking.booking_cancel(@booking)\n\t\tif data.class == Stripe::InvalidRequestError\n\t\t redirect_to :back, :notice => \"Stripe error while creating customer: #{data.message}\"\n\t\telse\n\t\t PaymentHistory.create(:name => \"cancel\", :booking_id => @booking.id)\n\t flash[:notice] = \"Booking is cancel & $#{amount} is refunded. \"\n\t redirect_to order_receives_path\n\t\tend\n\tend", "def cancel!\n return true if self.cancelled?\n \n if self.invoiced?\n self.errors.add(:status,\"has already been set to invoiced and cannot be changed\")\n return false\n else\n self.status = 'cancelled'\n self.save\n end\n end", "def cancel_bookings\n self.bookings.each do |booking|\n booking.cancel\n end\n end", "def cancel!\n if charged && !canceled\n refund!\n recharge!\n end\n end", "def handle_cancel(booking_data)\n status = booking_data.xpath('./status').text();\n bookingcom_booking_id = booking_data.xpath('./id').text()\n if status == BookingcomBooking::TYPE_CANCEL\n\n Booking.find_all_by_bookingcom_booking_id(bookingcom_booking_id).each do |existing_booking|\n\n last_booking_xml = Nokogiri::XML(existing_booking.booking_xml)\n room_reservation_id = booking_data.search(\"[text()*='#{existing_booking.bookingcom_room_reservation_id}']\")\n\n if room_reservation_id.blank? and !EquivalentXml.equivalent?(last_booking_xml, booking_data, opts = { :element_order => false, :normalize_whitespace => true })\n existing_booking.status = status\n existing_booking.booking_xml = booking_data.to_s\n\n existing_booking.amount = 0\n existing_booking.save\n end\n end\n end\n end", "def cancel\n success = true \n results = bookingcancellation_request_params.map do |bc_req|\n \n itin = @traveler.itineraries.find_by(id: bc_req[:itinerary_id]) ||\n @traveler.bookings.find_by(confirmation: bc_req[:booking_confirmation]).try(:itinerary)\n trip_type= itin.trip_type\n response = booking_response_base(itin).merge({success: false})\n\n next response unless itin\n \n # CANCEL THE ITINERARY, unselecting it and updating the booking object\n cancellation_result = itin.booked? ? itin.cancel : itin.unselect\n\n # This is done to support FMR individual leg cancelling. \n # If this logic ever changes, ensure that FMR individual leg cancelling is not affected.\n # If this is a round trip, mark any remaining pieces as 1 way\n if cancellation_result\n # Handle the case when the trip is the return trip.\n trip = itin.trip\n trip.previous_trip = nil\n if trip.details\n trip.details[:trip_type]=trip_type\n else\n trip.details = {trip_type: trip_type}\n end\n trip.save \n\n # Handle the case when the trip is the outbound trip.\n next_trip = itin.trip.next_trip\n if next_trip\n if next_trip.details\n next_trip.details[:trip_type]=trip_type\n else\n next_trip.details = {trip_type: trip_type}\n end\n next_trip.previous_trip = nil\n next_trip.save\n end\n\n end\n\n # Package response as per API V1 docsion\n cancellation_response = bookingcancellation_response_hash(cancellation_result)\n if not cancellation_response[:success] \n success = false \n end\n next response.merge(cancellation_response)\n end\n status = (success ? 200 : 406)\n render status: status, json: {cancellation_results: results}\n end", "def cancel!\n state_guard { modify_call 'Status' => 'cancelled' }\n end", "def cancel_booking\n data = Booking.booking_cancel_finder(@booking,params[:drop_off_date].to_date)\n if data.class == Stripe::InvalidRequestError\n redirect_to :back, :notice => \"Stripe error: #{data.message}\"\n else\n Message.create(:sender_id => @booking.user_id, :recipient_id => @booking.poster_id,\n :post_id => @booking.post_id,:body => \"Booking is cancel\")\n transfer_payment = @booking.update_columns(refund_finder: data)\n Post.add_area(@booking)\n PaymentHistory.create(:name => \"cancel\", :booking_id => @booking.id)\n flash[:notice] = \"Booking is cancel & $#{data} is refunded\"\n redirect_to booking_path(@booking.id)\n end\n end", "def cancel\n self.update_status :cancelled\n end", "def cancel_request\n @cancelled = true\n end", "def cancel\n if self.state != \"completed\"\n self.cancelled!\n end\n end", "def cancelled?\n cancelled\n end", "def destroy\n booking = Booking.find(params[:id])\n booking.status = 'cancelled'\n booking.save\n flash[:success] = 'Booking Cancelled!'\n redirect_to tours_path\n end", "def cancel\n self.cancelled=true\n self.save\nend", "def cancel?\n self.state == CANCEL\n end", "def cancel\r\n # Ignore if already cancelled.\r\n unless self.cancelled?\r\n self.status = :cancelled\r\n self.save\r\n\r\n # Send email to all students.\r\n self.course_selections.current.each do |selection|\r\n student = selection.application.student\r\n StudentMailer.course_cancelled(student, self).deliver_later\r\n StudentMessenger.new.course_cancelled(student, self)\r\n end\r\n\r\n return true\r\n end\r\n false\r\n end", "def cancel_booking(booking_id:,\n body:)\n new_api_call_builder\n .request(new_request_builder(HttpMethodEnum::POST,\n '/v2/bookings/{booking_id}/cancel',\n 'default')\n .template_param(new_parameter(booking_id, key: 'booking_id')\n .should_encode(true))\n .header_param(new_parameter('application/json', key: 'Content-Type'))\n .body_param(new_parameter(body))\n .header_param(new_parameter('application/json', key: 'accept'))\n .body_serializer(proc do |param| param.to_json unless param.nil? end)\n .auth(Single.new('global')))\n .response(new_response_handler\n .deserializer(APIHelper.method(:json_deserialize))\n .is_api_response(true)\n .convertor(ApiResponse.method(:create)))\n .execute\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the payment method instance
def payment_method if payment_method_id.nil? return nil else @payment_method ||= Payments::PaymentMethod.get(payment_method_id.to_sym) end end
[ "def payment_method\n @payment_method ||= PaymentMethod.get(payment_method_id.to_sym)\n end", "def payment_method\n Zapi::Models::PaymentMethod.new\n end", "def payment_method\n @payment_method ||= PAYMENT_METHOD[mapping_for()]\n end", "def payment_method\n @payment_method ||= Gateway::AdyenHPP.last # find(params[:merchantReturnData])\n end", "def payment_method\n @payment_method ||= PAYMENT_METHOD[mapping_for(:payment_method)]\n end", "def payment\n Spree::Payment.find(:first, :conditions => {\n :payment_method_id => @payment_method.id,\n :order_id => @attributes[:order_id]} ) || raise(ActiveRecord::RecordNotFound)\n end", "def payment\n @payment ||= user.try(:payment_method).try(:to_payment)\n end", "def payment_method(type)\n payment_method = payment_methods.actives.detect do |payment_method|\n payment_method.get_option('type') == type\n end\n if payment_method.nil?\n raise ArgumentError, \"Payment method #{type} is not found\"\n end\n payment_method\n end", "def payment_method\n has_puntopagos_payment_method? ? payments.from_puntopagos.order(:id).last.payment_method : nil\n end", "def as_stripe_payment_method\n @payment_method\n end", "def payment_method(type)\n payment_method = payment_methods.actives.detect do |payment_method|\n payment_method.get_option('type') == type\n end\n if payment_method.nil?\n raise ArgumentError, \"Payment method #{type} is not found\"\n end\n payment_method\n end", "def payment_method\n raise NotImplementedError.new(\"'#payment_method' must be implemented in specific class\")\n end", "def payment\n @payment ||= payment_source.payments.first\n end", "def payment\n Zapi::Models::Payment.new\n end", "def payment_factory\n\t\t\tpayment = Payment.new\n\t\t\treturn payment\n\t\tend", "def get_payment_method(user)\n user.payments.reload\n payment_methods = user.payments_list \n payment_methods << \"Add a new method of payment\"\n method = $prompt.select(\"Choose a payment method: \", payment_methods)\n case method \n when \"Add a new method of payment\"\n new_method = $prompt.ask(\"Enter your new payment method\")\n p = Payment.create(method_payment: new_method)\n else \n p = Payment.find_by(method_payment: method)\n end \n p\n end", "def info\n @info ||= user.payment_method || PaymentMethod.new\n end", "def get_payment_adapter(type)\n payment_adapters.find_by(type: type)\n end", "def payment\n payments.last\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Automatic resource assignation Assign available stock to unassigned items
def assign_available_stock stock_detail, category_occupation = BookingDataSystem::Booking.categories_availability(self.rental_location_code, self.date_from, self.time_from, self.date_to, self.time_to, nil, { origin: 'booking', id: self.id }) #p "stock_detail: #{stock_detail.inspect}" #p "category_occupation: #{category_occupation.inspect}" transaction do booking_lines.each do |booking_line| booking_line.booking_line_resources.each do |booking_line_resource| if booking_line_resource.booking_item_reference.nil? p "assign_available_stock -- #{booking_line_resource.booking_item_reference} -- available: #{category_occupation[booking_line.item_id][:available_stock].inspect} -- available_assignable: #{category_occupation[booking_line.item_id][:available_assignable_stock].inspect}" if booking_item_reference = category_occupation[booking_line.item_id][:available_assignable_stock].first and !booking_item_reference.nil? booking_line_resource.assign_resource(booking_item_reference) category_occupation[booking_line.item_id][:available_assignable_stock].delete_at(0) end end end end end end
[ "def review_assigned_stock\n\n automatic_assignation = SystemConfiguration::Variable.get_value('booking.assignation.automatic_resource_assignation', 'false').to_bool\n\n # Search availability\n product_search = ::Yito::Model::Booking::BookingCategory.search(self.rental_location_code,\n self.date_from,\n self.time_from,\n self.date_to,\n self.time_to,\n self.days,\n {\n locale: self.customer_language,\n full_information: true,\n product_code: nil,\n web_public: false,\n sales_channel_code: self.sales_channel_code,\n apply_promotion_code: self.promotion_code.nil? ? false : true,\n promotion_code: self.promotion_code,\n include_stock: true,\n ignore_urge: {origin: 'booking', id: self.id}\n })\n free_resources = product_search.inject([]) do |result, item|\n result.concat(item.resources)\n end\n\n p \"free_resources: #{free_resources}\"\n\n self.booking_line_resources.each do |booking_line_resource|\n\n if !booking_line_resource.booking_item_reference.nil? # Assigned resource\n if free_resources.index(booking_line_resource.booking_item_reference).nil? # Not found\n if product = product_search.select { |item| item.code == booking_line_resource.booking_line.item_id }.first\n if product.availability and product.resources.size > 0\n if automatic_assignation\n p \"booking : #{self.id} reassigned #{product.resources.first} instead of #{booking_line_resource.booking_item_reference}\"\n booking_line_resource.assign_resource(product.resources.first)\n product.resources.delete_at(0)\n end\n else\n booking_line_resource.clear_assignation\n p \"booking : #{self.id} clear assignation #{booking_line_resource.booking_item_reference} -- not free resources\"\n end\n else\n p \"booking : #{self.id} #{booking_line_resource.booking_item_reference} product #{booking_line_resource.booking_line.item_id} not found\"\n end\n else\n p \"booking: #{self.id} kept: #{booking_line_resource.booking_item_reference}\"\n end\n else # Not assigned resource\n if automatic_assignation\n if product = product_search.select { |item| item.code == booking_line_resource.booking_line.item_id }.first\n if product.availability and product.resources.size > 0\n p \"booking : #{self.id} assigned #{product.resources.first}\"\n booking_line_resource.assign_resource(product.resources.first)\n product.resources.delete_at(0)\n end\n end\n end\n end\n end\n end", "def assign_inventory\n self.shipment = self.available_shipment\n\n # assign the inventory from the [Shipment] or if not available from the []Order] \n self.quantity_shipped.times do\n assign_inventory_by_type(:shipped)\n end\n\n self.quantity_slashed.times do\n assign_inventory_by_type(:slashed)\n end\n\n end", "def reserved_stock_availabilty_in_distribution_center dc_id, items_count\n stock_inventories.available_stock_for_reduce(dc_id, items_count)\n end", "def assign_stock_entry( item , quantity ) \n # Find the empty stock entry. assign himself\n # if it is not enough, split into multiple stock_entry_usage \n requested_quantity = quantity \n supplied_quantity = 0 \n is_first = true \n while supplied_quantity != requested_quantity\n unfulfilled_quantity = requested_quantity - supplied_quantity \n stock_entry = StockEntry.first_available_stock( item )\n # what if 1 stock entry quantity is not enough?\n # get it from the next stock entry. However, it means that we need to use \n # NEW StockEntryUsage.. recursive call? \n\n # stock_entry.nil? raise error # later.. \n if stock_entry.nil?\n raise ActiveRecord::Rollback, \"Can't be executed. No Item in the stock\" \n end\n\n available_quantity = stock_entry.available_quantity \n\n served_quantity = 0 \n if unfulfilled_quantity <= available_quantity \n served_quantity = unfulfilled_quantity \n else\n served_quantity = available_quantity \n end\n\n stock_entry.update_usage(served_quantity) \n if is_first\n self.stock_entry_id = stock_entry.id \n self.quantity = served_quantity\n self.save\n is_first = false \n else\n StockEntryUsage.create(\n :stock_entry_id => stock_entry.id , \n :quantity => served_quantity, \n :source_document_entry_id => self.source_document_entry_id,\n :source_document_id => self.source_document_id, \n :source_document_entry => self.source_document_entry,\n :source_document => self.source_document,\n :case => self.case \n )\n end\n \n supplied_quantity += served_quantity \n end \n end", "def reserve_inventory\n begin\n @product_reserved_stock = @product.reserved_stock_availabilty_in_distribution_center(\n @distribution_center.id, inventory_stock_params[:items_count]).first\n unless @product_reserved_stock.present?\n @product_reserved_stock = @product.stock_inventories.create!(available: false,\n items_count: 0,\n distribution_center_id:\n @distribution_center.id)\n end\n if @product_available_stock.update_attribute(:items_count,\n @product_available_stock.items_count -\n inventory_stock_params[:items_count]) &&\n @product_reserved_stock.update_attribute(:items_count,\n @product_reserved_stock.items_count +\n inventory_stock_params[:items_count])\n\n response = {message: 'Inventory has been reserved of particular product stock in specified distribution center.'}\n status_code = 200\n else\n response = {errors:\n [{detail: \"We can't apply this operation at this time, please try later.\"}]}\n status_code = 403\n end\n rescue => ex\n response = {errors: [{detail: ex.message}]}\n status_code = 403\n end\n render json: response, status: status_code\n end", "def nonreserved_stock_availability_in_distribution_center dc_id, items_count\n stock_inventories.available_stock_for_reserve(dc_id, items_count)\n end", "def allocate_unallocated_stock!\n if self.ordered_item.stock_control? && self.unallocated_stock != 0\n self.ordered_item.stock_level_adjustments.create!(:parent => self, :adjustment => 0 - self.unallocated_stock, :description => \"Order ##{self.order.number}\")\n end\n end", "def discount_stock\n if @supplies.nil?\n else\n @supplies.each do |sub_array|\n sub_array.each do |item|\n id_supply = item[0]\n quantity = item[1]\n\n # For history of supplies used in an order\n HasUsedSupply.create(order_id: @order_id, supply_id: id_supply,\n quantity: quantity)\n\n # Update supply with the new stock\n @supply = Supply.find(id_supply)\n new_stock = @supply.stock - Integer(quantity)\n @supply.update(:stock => new_stock)\n end\n end\n end\n end", "def allocate_stock_to_kit\n kit = self.kit\n lowest_stock = (self.variant.fba_quantity/self.quantity).to_i\n kit.kit_products.each_with_index do |kp, ind|\n qty = (kp.variant.fba_quantity/kp.quantity).to_i\n if ind == 0\n lowest_stock = qty \n elsif (ind!=0 && lowest_stock > qty)\n lowest_stock = qty\n end\n end\n kit.product.master.update_column(:fba_quantity, lowest_stock)\n kit.update_attributes!(:quantity=>lowest_stock) \n msg = 'Model - Kit Product / allocate stock for kit'\n kit.product.master.add_log_on_update(msg) rescue QTY_LOG.error \"#{Time.zone.now} Error -- #{msg}\"\n end", "def restock\n difference = @max_stock - @quantity_available\n num_bundles = difference / @bundles\n flowers_to_order = num_bundles * @bundles\n @quantity_available += flowers_to_order\n end", "def assign_waiter\n #check if they have capacity\n waiter = Waiter.all.find{|w| w.selling_style == self.host.best_selling_style}\n self.update(waiter_id: waiter.id)\n waiter\n end", "def recalculate_availability\n copies = self.available_copies\n #Below code need to discuss with Darya.\n #copies -= self.new_or_pending_holds.count\n status = copies > 0 ? 'available' : 'unavailable'\n self.update_attribute :availability, status\n end", "def reduce_stock\n @stock -= 1\n end", "def reduction_product_stock\n if order_items.present?\n order_items.each do |item|\n product = item.product\n product.stock = product.stock - item.quantity\n product.save\n end\n end\n end", "def item_stock(item)\n item_stocks.create(item_id: item.id)\n end", "def set_quantity_and_swaps!\n if self.exclusivity_id == Exclusivity.total_id\n if self.experience_id.presence\n self.quantity = self.experience_swaps unless self.quantity.presence\n end\n self.swaps = nil\n elsif self.exclusivity_id == Exclusivity.by_industry_id\n if self.efi_id.presence\n self.quantity = experience.industry_swaps(self.efi) if not self.quantity.presence and not self.experience_id.nil?\n end\n self.swaps = nil\n else\n self.quantity = nil\n end\n end", "def set_stock_items\n @stock_items = StockItem.all.order(:name)\n end", "def defined_stock\n BookingItem.all(category_code: code, active: true, assignable: true).count\n end", "def update_cancel_stock\n\n self.orderitems.each do |orderitem|\n if orderitem.status != \"Shipped\"\n product = orderitem.product\n product.stock += orderitem.quantity\n product.save\n end\n end\n\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Review the assigned stock when the user changes dates
def review_assigned_stock automatic_assignation = SystemConfiguration::Variable.get_value('booking.assignation.automatic_resource_assignation', 'false').to_bool # Search availability product_search = ::Yito::Model::Booking::BookingCategory.search(self.rental_location_code, self.date_from, self.time_from, self.date_to, self.time_to, self.days, { locale: self.customer_language, full_information: true, product_code: nil, web_public: false, sales_channel_code: self.sales_channel_code, apply_promotion_code: self.promotion_code.nil? ? false : true, promotion_code: self.promotion_code, include_stock: true, ignore_urge: {origin: 'booking', id: self.id} }) free_resources = product_search.inject([]) do |result, item| result.concat(item.resources) end p "free_resources: #{free_resources}" self.booking_line_resources.each do |booking_line_resource| if !booking_line_resource.booking_item_reference.nil? # Assigned resource if free_resources.index(booking_line_resource.booking_item_reference).nil? # Not found if product = product_search.select { |item| item.code == booking_line_resource.booking_line.item_id }.first if product.availability and product.resources.size > 0 if automatic_assignation p "booking : #{self.id} reassigned #{product.resources.first} instead of #{booking_line_resource.booking_item_reference}" booking_line_resource.assign_resource(product.resources.first) product.resources.delete_at(0) end else booking_line_resource.clear_assignation p "booking : #{self.id} clear assignation #{booking_line_resource.booking_item_reference} -- not free resources" end else p "booking : #{self.id} #{booking_line_resource.booking_item_reference} product #{booking_line_resource.booking_line.item_id} not found" end else p "booking: #{self.id} kept: #{booking_line_resource.booking_item_reference}" end else # Not assigned resource if automatic_assignation if product = product_search.select { |item| item.code == booking_line_resource.booking_line.item_id }.first if product.availability and product.resources.size > 0 p "booking : #{self.id} assigned #{product.resources.first}" booking_line_resource.assign_resource(product.resources.first) product.resources.delete_at(0) end end end end end end
[ "def update_due_date(item_name,new_due_date)\n \t@items.each do |value|\n \t if value.description == item_name # check each item against input item\n \t\t value.due_date = new_due_date\n \t\t @report_file.puts \"Item: #{item_name} due date updated to #{new_due_date}\"\n \t end\n end\n end", "def check_stock!\n purchase_temp = Purchase.new(exchange_id: self.exchanges.last.id,\n rut: '123456785',\n email: 'test@acid.cl',\n password: '12345678')\n\n if purchase_temp.valid?\n unless self.sold_at.nil?\n self.sold_at = nil\n self.save\n end\n else\n unless self.sold_at.presence\n self.sold_at = DateTime.now\n self.save\n end\n end\n end", "def markDue\n login = Login.find(params[:id]) unless params[:id].blank?\n\t \n if !login.blank?\n\t \n\t controller = params[:from]\n\t user = login.person if controller.match('people')\n\t user = login.organisation if controller.match('organisations')\n \n\t myItem = BorrowedItem.find(params[:borrowed_item])\n \n if myItem != nil\n\t myItem.date_due=Time.now()\n\t myItem.date_renewed=nil;\n\t myItem.save()\n end\n \n\t redirect_to :controller => controller, :action => 'privileges_list', :id => user\n end\n \nend", "def approve!\n self.update_attribute(:status, APPROVED)\n self.stock_entries.update_all(status: StockEntry::ACTIVE)\n true\n end", "def old_checkin_change(date = \"yesterday\")\n if date == \"yesterday\"\n timeframe = Time.current - 1.day\n else\n timeframe = Time.current - 2.days\n end\n time_range = (Time.current - 2.hours)..Time.current\n # get all answers together\n ratings = rating_answers.where(:created_at => time_range)\n comments = comment_answers.where(:created_at => time_range)\n booleans = boolean_answers.where(:created_at => time_range)\n # ANSWERS.each { |x| x.update(created_at: 1.day.ago) }\n ratings.each { |x| x.update(created_at: timeframe) }\n comments.each { |x| x.update(created_at: timeframe) }\n booleans.each { |x| x.update(created_at: timeframe) }\n end", "def user_update(user_id)\n trade_lines.each do |x|\n if x.inventory_own.user_id != user_id\n x.user_from_accepted = false \n else\n x.user_from_accepted = true\n end\n x.save\n end\n end", "def approve!\n inventory.restock!(self, Time.current, inventory_check)\n update!(adjustment: difference)\n end", "def day_change\n api_toucher.yahoo_multistock_day_change(symbols)\n end", "def place_on_hold(current_time = Time.now)\n self.review_status = ReviewStatus.find(:first, \n :conditions => \"name='Review On-Hold'\")\n self.placed_on_hold_on = current_time\n self.save\n end", "def rev_allocation_change(project, current_user, effective_date)\n @project = project\n @current_user = current_user\n\n # only send notifications to roles that have had a change of percentage.\n roles = []\n @project.team_memberships.each do | tm |\n if tm.previous_changes.has_key? \"percentage\"\n roles << tm.role.name.downcase.gsub(/ /, \"_\").to_sym\n end\n end\n\n tokens = {}\n project.team_memberships.each do |m|\n tokens.store(\"#{m.member.name} (#{m.role.name})\", m.percentage.to_s + \"%\")\n end\n\n tokens.store('Effective Date', effective_date)\n\n tokens['Published'] = 'No'\n\n if @project.project_grid_table_row.production_task_name == \"Production Complete\"\n tokens['Published'] = 'Yes'\n tokens['Publication Date'] = @project.published_file.publication_date unless @project.published_file.nil? || @project.published_file.publication_date.nil?\n end\n\n user_subject = \"Revenue Allocation for #{project.book_title}\"\n admin_subject = \"New Project Revenue Allocation from #{current_user.name} for #{project.book_title}\"\n\n send_email_message('rev_allocation_change', tokens, get_project_recipient_list(@project, roles: roles), user_subject)\n send_email_message('rev_allocation_change_admin', tokens, admin_rev_allocation_change_list, admin_subject)\n end", "def shift_reviews\n if((days_behind = review_days_behind) > 0)\n Review.update_all(\"scheduled_at = scheduled_at + INTERVAL '#{days_behind} days'\")\n end\n end", "def rent(stock_item_id, customer_id, rental_date, return_due_date, theatre)\n# park this for now - see what the form sends, whether these arguments should be\n# listed or an options hash\n# might need to pass in the actual objects for updating stock items\n error_code=0\n @stock_item_id=stock_item_id\n error_code += 1 if ( StockItem.find_by_id(@stock_item_id).status > 1 )\n @customer_id=customer_id\n error_code +=2 if ( Customer.find_by_id(@customer_id).get_warnings > 1 )\n if !error_code\n @theatre=theatre\n if (rental_date)\n @rental_date=rental_date\n # update item status to booked, unavailable\n else\n @rental_date=Date.today.strftime('%Y-%m-%d')\n # update item status to out on loan\n end\n if (return_due_date !=nil)\n @return_due_date=return_due_date\n elsif theatre\n @return_due_date=(rental_date+7).strftime('%Y-%m-%d')\n else\n @return_due_date=(rental_date+2).strftime('%Y-%m-%d')\n end\n @return_code=1\n if @id == nil\n save\n # @transaction_id=Transaction.new(@id).id\n end\n update\n # add transactions as an extension later\n end\n return error_code\n # 0: ok, 1: item unavailable, 2: customer banned, 3: both banned and unavailable\n end", "def update_stock_on_create\n # Update current Stock\n if !update_stock(product, store, quantity, true)\n return false\n end\n true\n end", "def update_stock_on_update\n # What has changed?\n product_has_changed = product_changed? rescue false\n store_has_changed = store_changed? rescue false\n quantity_has_changed = quantity_changed? rescue false\n # Previous values\n product_prev = product_was rescue product\n store_prev = store_was rescue store\n quantity_prev = quantity_was rescue quantity\n # Stock\n if product_has_changed || store_has_changed\n # Current Stock\n if !update_stock(product, store, quantity, true)\n return false\n end\n # Roll back Previous Stock\n if !update_stock(product_prev, store_prev, quantity_prev, false)\n return false\n end\n elsif quantity_has_changed\n # Current Stock\n if !update_stock(product, store, quantity - quantity_prev, true)\n return false\n end\n end\n true\n end", "def update_stock_and_price_on_update\n # What has changed?\n product_has_changed = product_changed? rescue false\n store_has_changed = store_changed? rescue false\n quantity_has_changed = quantity_changed? rescue false\n supplier_has_changed = receipt_note.supplier_changed? rescue false\n price_has_changed = price_changed? rescue false\n code_has_changed = code_changed? rescue false\n discount_pct_has_changed = discount_pct_changed? rescue false\n discount_has_changed = discount_changed? rescue false\n # Previous values\n product_prev = product_was rescue product\n store_prev = store_was rescue store\n quantity_prev = quantity_was rescue quantity\n supplier_prev = receipt_note.supplier_was rescue receipt_note.supplier\n amount_prev = amount_was rescue amount\n price_prev = price_was rescue price\n discount_pct_prev = discount_pct_was rescue discount_pct\n discount_prev = discount_was rescue discount\n net_price_prev = price_prev - discount_prev\n # PurchasePrice\n if product_has_changed || supplier_has_changed\n # Current PurchasePrice\n if !update_purchase_price(product, receipt_note.supplier, price, code, 1, discount_pct)\n return false\n end\n # Roll back Previous PurchasePrice\n if !update_purchase_price(product_prev, supplier_prev, price, code, 2, discount_pct)\n return false\n end\n elsif price_has_changed || code_has_changed || discount_pct_has_changed\n # Current PurchasePrice\n if !update_purchase_price(product, receipt_note.supplier, price, code, 0, discount_pct)\n return false\n end\n end\n # Product\n if product_has_changed\n # Current Product\n if !update_product(product, amount, quantity, net_price, true, 1)\n return false\n end\n # Previous Product\n if !update_product(product_prev, amount_prev, quantity_prev, net_price_prev, false, 2)\n return false\n end\n elsif quantity_has_changed || price_has_changed || discount_has_changed\n # Current Product\n if !update_product(product, amount - amount_prev, quantity - quantity_prev, net_price, true, 0)\n return false\n end\n end\n # ProductCompanyPrice\n if product_has_changed || store_has_changed || supplier_has_changed\n # Current ProductCompanyPrice\n if !update_product_company_price(product, store.company, amount, quantity, net_price, true, 1, receipt_note.supplier)\n return false\n end\n # Previous ProductCompanyPrice\n if !update_product_company_price(product_prev, store_prev.company, amount_prev, quantity_prev, net_price_prev, false, 2, supplier_prev)\n return false\n end\n elsif quantity_has_changed || price_has_changed || discount_has_changed\n # Current ProductCompanyPrice\n if !update_product_company_price(product, store.company, amount - amount_prev, quantity - quantity_prev, net_price, true, 0, receipt_note.supplier)\n return false\n end\n end\n # Stock\n if product_has_changed || store_has_changed\n # Current Stock\n if !update_stock(product, store, quantity, true)\n return false\n end\n # Roll back Previous Stock\n if !update_stock(product_prev, store_prev, quantity_prev, false)\n return false\n end\n elsif quantity_has_changed\n # Current Stock\n if !update_stock(product, store, quantity - quantity_prev, true)\n return false\n end\n end\n # Everything run smoothly\n true\n end", "def display_drinks_on_date(user, date)\n users_drinks_on_date = user.drinks_on_date(date)\n user.display_drinks(users_drinks_on_date)\nend", "def update_stock\n mercaderia.update(stock: nueva_cantidad) if cantidad_changed? || deleted?\n end", "def resell_to_user\n @reservation.update_by_admin = true\n create_reservation_owner\n\n if @reservation.resell_to_user(@owner)\n SegmentAnalytics.sold_resell_booking(@reservation, current_user || current_admin)\n ActivityLog.record_log(:reservation_updated, current_admin.company.id, current_admin, @reservation)\n head :ok\n else\n render json: { errors: { '0' => @reservation.errors.full_messages } }, status: :unprocessable_entity\n end\n end", "def date_purchased=(value)\n @date_purchased = value\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new business event to notify a booking has been created
def create_new_booking_business_event! BusinessEvents::BusinessEvent.fire_event(:new_booking, {:booking_id => id}) end
[ "def create\n @business_event = BusinessEvent.new(business_event_params)\n\n respond_to do |format|\n if @business_event.save\n format.html { redirect_to @business_event, notice: 'Business event was successfully created.' }\n format.json { render :show, status: :created, location: @business_event }\n else\n format.html { render :new }\n format.json { render json: @business_event.errors, status: :unprocessable_entity }\n end\n end\n end", "def send_outbound_create_event\n # check for the therapist associated with this appointment\n send_outbound_event(\"created\")\n end", "def create_booking(day)\n new_booking = Booking.create(host_id: self.id,day: day)\n puts \"A new booking has been created for #{self.name} on #{day}.\"\n new_booking.assign_waiter\n puts \"#{new_booking.waiter.name} has been assigned to #{self.name}'s booking'.\"\n end", "def new_booking_created(user_id, booking_id)\n @company = Company.first\n\n @user = User.find(user_id)\n @booking = Booking.find booking_id\n\n mail(to: @company.email, subject: \"For admin: #{ @user.full_name} just created a booking\")\n end", "def create_booking(params)\n raise NotImplementedError\n end", "def create\n event = Event.find(params[:event_id])\n @bus = event.buses.build(bus_params)\n respond_to do |format|\n if @bus.save\n format.html { redirect_to event_path(@bus.event), notice: 'Bus was successfully created.' }\n format.json { render :show, status: :created, location: @bus }\n else\n format.html { render :new }\n format.json { render json: @bus.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @bid_event = BidEvent.new(bid_event_params)\n\n respond_to do |format|\n if @bid_event.save\n format.html { redirect_to :back }\n format.json { render :show, status: :created, location: @bid_event }\n else\n format.html { redirect_to :back }\n format.json { render json: @bid_event.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @booking = Booking.new(booking_params)\n \n unless params[:subject_id].empty?\n @subject = Subject.find(params[:subject_id])\n end\n # TODO date and time validation\n begin\n date = (params['date_part'] + \" \" + params['time_part']).to_datetime\n rescue ArgumentError\n @booking.errors.add(:date, \"is invalid\")\n date = Date.new\n end\n @booking.booking_date = date\n # TODO: Refactor for admin booking creation\n @booking.shared = params[\"shared\"]\n @booking.subject = @subject\n # Add this customer as owner. \n @booking.creator = current_user.customer\n @booking.customers << current_user.customer\n @booking.booked_customers.first.number_students = params[:booking][:booked_customers][:number_students]\n @booking.period = 2\n \n # Create closed booking if customer came from searching or enquiring.\n if params[:presenter_id].present?\n presenter = Presenter.find(params[:presenter_id])\n if presenter.available? @booking.booking_date, @booking.duration_minutes\n @booking.chosen_presenter = Presenter.find(params[:presenter_id])\n @booking.rate = presenter.rate\n @booking.creator = current_user.customer\n else\n @booking.errors.add(:presenter, \"is not available at this time\")\n end\n end \n \n if @booking.save\n # Only send messages to customers if booking is shared\n @message = \"A new #{@booking.subject.name} booking has been created that you may be interested in.\"\n if @booking.shared?\n Notification.notify_applicable_users(current_user, @booking, \"customer\", booking_path(@booking), @message, :interested_booking)\n end\n # Only send messages to presenters if booking is open\n if @booking.chosen_presenter.nil?\n Notification.notify_applicable_users(current_user, @booking, \"presenter\", booking_path(@booking), @message, :interested_booking)\n end\n Notification.notify_admin(\"A new booking has been created\", booking_path(@booking), :booking)\n\n # Add booking to booked customers\n current_user.customer.created_bookings << @booking\n\n #clear search session \n session[:search_params] = nil\n redirect_to @booking\n else\n @date_part = params['date_part']\n @time_part = params['time_part']\n render :new\n end\n\n end", "def event\n event = super\n if event.present?\n event.booking = self\n end\n return event\n end", "def create_booking(body:)\n new_api_call_builder\n .request(new_request_builder(HttpMethodEnum::POST,\n '/v2/bookings',\n 'default')\n .header_param(new_parameter('application/json', key: 'Content-Type'))\n .body_param(new_parameter(body))\n .header_param(new_parameter('application/json', key: 'accept'))\n .body_serializer(proc do |param| param.to_json unless param.nil? end)\n .auth(Single.new('global')))\n .response(new_response_handler\n .deserializer(APIHelper.method(:json_deserialize))\n .is_api_response(true)\n .convertor(ApiResponse.method(:create)))\n .execute\n end", "def report_new_event_to_dingo(the_event)\n @event = the_event\n mail(:from => self.dingo_email,:to => Settings.DINGO_EMAIL,:subject => 'A New Event Has Been Created')\n end", "def create\n @bet_event = BetEvent.new(bet_event_params)\n\n respond_to do |format|\n if @bet_event.save\n format.html { redirect_to @bet_event, notice: 'Bet event was successfully created.' }\n format.json { render :show, status: :created, location: @bet_event }\n else\n format.html { render :new }\n format.json { render json: @bet_event.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_calendar_event(start_date,end_date,email,name)\n event = Google::Apis::CalendarV3::Event.new({\n summary: \"#{name}'s Paid Time Off\",\n location: '',\n description: '',\n start: {\n date: \"#{start_date}\"\n },\n end: {\n date: \"#{end_date}\"\n },\n # recurrence: [\n # 'RRULE:FREQ=DAILY;COUNT=2'\n # ],\n attendees: [\n {email: \"wvtimeclockdev@gmail.com\"}\n ]\n # reminders: {\n # use_default: false,\n # overrides: [\n # {'method' => 'email', 'minutes': 24 * 60},\n # {'method' => 'popup', 'minutes': 10},\n # ],\n # },\n })\n \n result = service.insert_event('primary', event)\n puts \"Event created: #{result.html_link}\"\n end", "def create_appointment(starts_at,ends_at)\n return create_event('appointment', starts_at, ends_at)\n end", "def create\n @event = Event.new(event_params)\n @event.user = @user\n @event.save\n # Cehck if there is any highschooler interested in talking to this undergraduate\n notify_highschooler if @user.interested_in_me.present?\n end", "def create\n @ticketing_event = Ticketing::Event.new(params[:ticketing_event])\n\n respond_to do |format|\n if @ticketing_event.save\n format.html { redirect_to ticketing_events_path }\n format.json { render json: @ticketing_event, status: :created, location: @ticketing_event }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ticketing_event.errors, status: :unprocessable_entity }\n end\n end\n end", "def new_bundle\n @event = BundleEvent.new\n # @event.start_date = (Time.now + 14.day).strftime('%Y-%m-%d 10:00:00')\n # @event.end_date = (Time.now + 14.day).strftime('%Y-%m-%d 18:00:00')\n # @event.latest_signup_date = (Time.now + 12.day).strftime('%Y-%m-%d 00:00:00')\n # @event.reservation_expiry = (Time.now + 10.day).strftime('%Y-%m-%d 00:00:00')\n @event.maxparticipants = 10\n @event.max_additional_participants = 0\n render 'new'\n end", "def create\n @bus_event = BusEvent.new(bus_event_params)\n @bus_event.event_time = DateTime.parse(bus_event_params[:event_time])\n respond_to do |format|\n if @bus_event.save\n format.html { redirect_to @bus_event, notice: 'Bus event was successfully created.' }\n format.json { render :show, status: :created, location: @bus_event }\n else\n format.html { render :new }\n format.json { render json: @bus_event.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_owner(owner)\n @user = User.find(owner)\n @owner = @user\n @app = @user.appointments.create(:booking_id => self.id, :owner => true, :confirmed => true, :status => 'booked')\n if @app.save\n BookingMailer.booking_email(@user, @app.booking, @owner).deliver\n end \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
First octet of the SMSDELIVER PDU
def sms_deliver_first_octet octet = 0 octet |= 0x04 unless @opts[:more_to_send] octet |= 0x80 if @opts[:has_udh] octet.chr end
[ "def sms_submit_first_octet\n octet = 1\n octet |= 0x80 if @opts[:has_udh]\n octet.chr\n end", "def pdu\n message.pdu\n end", "def service_number\n @binary_components[0]\n end", "def prepend_length(msg)\n size = msg.length.to_s(16) # 16 bit \n header = size.to_s.length.upto(MESSAGE_HEADER_SIZE-1).collect{0}\n header = header + size.split('')\n return header.to_s + msg\n end", "def next_byte\n byte = slice!(0)\n byte.nil? ? 0 : byte.unpack1('c')\n end", "def header\n if @bytes.length < INES_HEADER_SIZE\n raise 'invalid or missing header'\n end\n\n return @bytes.slice(0, INES_HEADER_SIZE)\n end", "def getSerialNumber ()\n return readValue(\"rPDUIdentSerialNumber.0\")\n end", "def bytes\n # preamble + payload + error_correction\n payload\n end", "def header\n _, @count, @stringOffset = @bytes[0, 6].unpack('nnn')\n end", "def checksum\n @header[ACTIVE_MAILBOX_CHECKSUM]\n end", "def get_sequence_header(sequence_bytes)\n return sequence_bytes[HEADER_START_INDEX..HEADER_END_INDEX]\n end", "def ungetbyte(fixnum)\n #This is a stub, used for indexing\n end", "def pseudo_bytes(p0) end", "def pdu_client_confirm_active()\n pdu = \"\\xea\\x03\\x01\\x00\" + # shareId: 66538\n \"\\xea\\x03\" + # originatorId\n \"\\x06\\x00\" + # lengthSourceDescriptor: 6\n \"\\x3e\\x02\" + # lengthCombinedCapabilities: ???\n \"\\x4d\\x53\\x54\\x53\\x43\\x00\" + # SourceDescriptor: 'MSTSC'\n \"\\x17\\x00\" + # numberCapabilities: 23\n \"\\x00\\x00\" + # pad2Octets\n \"\\x01\\x00\" + # capabilitySetType: 1 - TS_GENERAL_CAPABILITYSET\n \"\\x18\\x00\" + # lengthCapability: 24\n \"\\x01\\x00\\x03\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x1d\\x04\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\" +\n \"\\x02\\x00\" + # capabilitySetType: 2 - TS_BITMAP_CAPABILITYSET\n \"\\x1c\\x00\" + # lengthCapability: 28\n \"\\x20\\x00\\x01\\x00\\x01\\x00\\x01\\x00\\x80\\x07\\x38\\x04\\x00\\x00\\x01\\x00\" +\n \"\\x01\\x00\\x00\\x1a\\x01\\x00\\x00\\x00\" +\n \"\\x03\\x00\" + # capabilitySetType: 3 - TS_ORDER_CAPABILITYSET\n \"\\x58\\x00\" + # lengthCapability: 88\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x01\\x00\\x14\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xaa\\x00\" +\n \"\\x01\\x01\\x01\\x01\\x01\\x00\\x00\\x01\\x01\\x01\\x00\\x01\\x00\\x00\\x00\\x01\" +\n \"\\x01\\x01\\x01\\x01\\x01\\x01\\x01\\x00\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\" +\n \"\\xa1\\x06\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x84\\x03\\x00\\x00\\x00\\x00\\x00\" +\n \"\\xe4\\x04\\x00\\x00\\x13\\x00\\x28\\x00\\x03\\x00\\x00\\x03\\x78\\x00\\x00\\x00\" +\n \"\\x78\\x00\\x00\\x00\\xfc\\x09\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x0a\\x00\" + # capabilitySetType: 10 - ??\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x06\\x00\\x00\\x00\" +\n \"\\x07\\x00\" + # capabilitySetType: 7 - TSWINDOWACTIVATION_CAPABILITYSET\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x05\\x00\" + # capabilitySetType: 5 - TS_CONTROL_CAPABILITYSET\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x00\\x00\\x00\\x00\\x02\\x00\\x02\\x00\" +\n \"\\x08\\x00\" + # capabilitySetType: 8 - TS_POINTER_CAPABILITYSET\n \"\\x0a\\x00\" + # lengthCapability: 10\n \"\\x01\\x00\\x14\\x00\\x15\\x00\" +\n \"\\x09\\x00\" + # capabilitySetType: 9 - TS_SHARE_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x00\\x00\\x00\\x00\" +\n \"\\x0d\\x00\" + # capabilitySetType: 13 - TS_INPUT_CAPABILITYSET\n \"\\x58\\x00\" + # lengthCapability: 88\n \"\\x91\\x00\\x20\\x00\\x09\\x04\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\" +\n \"\\x0c\\x00\" + # capabilitySetType: 12 - TS_SOUND_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" +\n \"\\x0e\\x00\" + # capabilitySetType: 14 - TS_FONT_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" +\n \"\\x10\\x00\" + # capabilitySetType: 16 - TS_GLYPHCAChE_CAPABILITYSET\n \"\\x34\\x00\" + # lengthCapability: 52\n \"\\xfe\\x00\\x04\\x00\\xfe\\x00\\x04\\x00\\xfe\\x00\\x08\\x00\\xfe\\x00\\x08\\x00\" +\n \"\\xfe\\x00\\x10\\x00\\xfe\\x00\\x20\\x00\\xfe\\x00\\x40\\x00\\xfe\\x00\\x80\\x00\" +\n \"\\xfe\\x00\\x00\\x01\\x40\\x00\\x00\\x08\\x00\\x01\\x00\\x01\\x03\\x00\\x00\\x00\" +\n \"\\x0f\\x00\" + # capabilitySetType: 15 - TS_BRUSH_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" +\n \"\\x11\\x00\" + # capabilitySetType: ??\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x01\\x00\\x00\\x00\\x00\\x28\\x64\\x00\" +\n \"\\x14\\x00\" + # capabilitySetType: ??\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x15\\x00\" + # capabilitySetType: ??\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x02\\x00\\x00\\x00\\x00\\x0a\\x00\\x01\" +\n \"\\x1a\\x00\" + # capabilitySetType: ??\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\xaf\\x94\\x00\\x00\" +\n \"\\x1c\\x00\" + # capabilitySetType: ??\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x12\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x1b\\x00\" + # capabilitySetType: ??\n \"\\x06\\x00\" + # lengthCapability: 6\n \"\\x01\\x00\" +\n \"\\x1e\\x00\" + # capabilitySetType: ??\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" +\n \"\\x18\\x00\" + # capabilitySetType: ??\n \"\\x0b\\x00\" + # lengthCapability: 11\n \"\\x02\\x00\\x00\\x00\\x03\\x0c\\x00\" +\n \"\\x1d\\x00\" + # capabilitySetType: ??\n \"\\x5f\\x00\" + # lengthCapability: 95\n \"\\x02\\xb9\\x1b\\x8d\\xca\\x0f\\x00\\x4f\\x15\\x58\\x9f\\xae\\x2d\\x1a\\x87\\xe2\" +\n \"\\xd6\\x01\\x03\\x00\\x01\\x01\\x03\\xd4\\xcc\\x44\\x27\\x8a\\x9d\\x74\\x4e\\x80\" +\n \"\\x3c\\x0e\\xcb\\xee\\xa1\\x9c\\x54\\x05\\x31\\x00\\x31\\x00\\x00\\x00\\x01\\x00\" +\n \"\\x00\\x00\\x25\\x00\\x00\\x00\\xc0\\xcb\\x08\\x00\\x00\\x00\\x01\\x00\\xc1\\xcb\" +\n \"\\x1d\\x00\\x00\\x00\\x01\\xc0\\xcf\\x02\\x00\\x08\\x00\\x00\\x01\\x40\\x00\\x02\" +\n \"\\x01\\x01\\x01\\x00\\x01\\x40\\x00\\x02\\x01\\x01\\x04\"\n\n ## type = 0x13 = TS_PROTOCOL_VERSION | PDUTYPE_CONFIRMACTIVEPDU\n return(rdp_build_share_control_header(0x13, pdu))\n end", "def pick_byte!\n pick_char![0]\n end", "def sample_packhdr_le_usec\n \"\\xD4\\xC3\\xB2\\xA1\" +\n \"\\x8Ab\\xD2S\\x1Fh\\x0E\\x00f\\x01\\x00\\x00f\\x01\\x00\\x00\" +\n \"\\x00\\x00\\xFF\\xFF\\x00\\x00\\x00\\x01\" # padding\nend", "def sample_packhdr_be_usec\n \"\\xA1\\xB2\\xC3\\xD4\" +\n \"S\\xD2b\\x8A\\x00\\x0Eh\\x1F\\x00\\x00\\x01f\\x00\\x00\\x01f\" +\n \"\\x00\\x00\\xFF\\xFF\\x00\\x00\\x00\\x01\" # padding\nend", "def extractCommandID(msgID)\n retVal = \"000\"\n\n # Check if the ID is a hexadecimal number\n if msgID =~ /(0x)?[0-9a-fA-F]+/\n # Convert the message ID from a string to a value\n val = msgID.to_i(16)\n\n # Strip off all but the last 12 bits and convert the value to a\n # hexadecimal string\n retVal = \"%03x\" % (val & 0x7ff)\n end\n\n return \"0x\" + retVal\nend", "def get_signature\n str_sz = get(1).unpack('C')[0]\n ret = @buffy.slice(@idx, str_sz)\n raise IncompleteBufferException if @idx + str_sz + 1 >= @buffy.size\n @idx += str_sz\n if @buffy[@idx] != 0\n raise InvalidPacketException, \"Type is not nul-terminated\"\n end\n @idx += 1\n # no exception, see check above\n ret\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
First octet of the SMSSUBMIT PDU
def sms_submit_first_octet octet = 1 octet |= 0x80 if @opts[:has_udh] octet.chr end
[ "def sms_deliver_first_octet\n octet = 0\n octet |= 0x04 unless @opts[:more_to_send]\n octet |= 0x80 if @opts[:has_udh]\n octet.chr\n end", "def pdu\n message.pdu\n end", "def get_signature\n str_sz = get(1).unpack('C')[0]\n ret = @buffy.slice(@idx, str_sz)\n raise IncompleteBufferException if @idx + str_sz + 1 >= @buffy.size\n @idx += str_sz\n if @buffy[@idx] != 0\n raise InvalidPacketException, \"Type is not nul-terminated\"\n end\n @idx += 1\n # no exception, see check above\n ret\n end", "def pdu_client_confirm_active()\n pdu = \"\\xea\\x03\\x01\\x00\" + # shareId: 66538\n \"\\xea\\x03\" + # originatorId\n \"\\x06\\x00\" + # lengthSourceDescriptor: 6\n \"\\x3e\\x02\" + # lengthCombinedCapabilities: ???\n \"\\x4d\\x53\\x54\\x53\\x43\\x00\" + # SourceDescriptor: 'MSTSC'\n \"\\x17\\x00\" + # numberCapabilities: 23\n \"\\x00\\x00\" + # pad2Octets\n \"\\x01\\x00\" + # capabilitySetType: 1 - TS_GENERAL_CAPABILITYSET\n \"\\x18\\x00\" + # lengthCapability: 24\n \"\\x01\\x00\\x03\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x1d\\x04\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\" +\n \"\\x02\\x00\" + # capabilitySetType: 2 - TS_BITMAP_CAPABILITYSET\n \"\\x1c\\x00\" + # lengthCapability: 28\n \"\\x20\\x00\\x01\\x00\\x01\\x00\\x01\\x00\\x80\\x07\\x38\\x04\\x00\\x00\\x01\\x00\" +\n \"\\x01\\x00\\x00\\x1a\\x01\\x00\\x00\\x00\" +\n \"\\x03\\x00\" + # capabilitySetType: 3 - TS_ORDER_CAPABILITYSET\n \"\\x58\\x00\" + # lengthCapability: 88\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x01\\x00\\x14\\x00\\x00\\x00\\x01\\x00\\x00\\x00\\xaa\\x00\" +\n \"\\x01\\x01\\x01\\x01\\x01\\x00\\x00\\x01\\x01\\x01\\x00\\x01\\x00\\x00\\x00\\x01\" +\n \"\\x01\\x01\\x01\\x01\\x01\\x01\\x01\\x00\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\" +\n \"\\xa1\\x06\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x84\\x03\\x00\\x00\\x00\\x00\\x00\" +\n \"\\xe4\\x04\\x00\\x00\\x13\\x00\\x28\\x00\\x03\\x00\\x00\\x03\\x78\\x00\\x00\\x00\" +\n \"\\x78\\x00\\x00\\x00\\xfc\\x09\\x00\\x80\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x0a\\x00\" + # capabilitySetType: 10 - ??\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x06\\x00\\x00\\x00\" +\n \"\\x07\\x00\" + # capabilitySetType: 7 - TSWINDOWACTIVATION_CAPABILITYSET\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x05\\x00\" + # capabilitySetType: 5 - TS_CONTROL_CAPABILITYSET\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x00\\x00\\x00\\x00\\x02\\x00\\x02\\x00\" +\n \"\\x08\\x00\" + # capabilitySetType: 8 - TS_POINTER_CAPABILITYSET\n \"\\x0a\\x00\" + # lengthCapability: 10\n \"\\x01\\x00\\x14\\x00\\x15\\x00\" +\n \"\\x09\\x00\" + # capabilitySetType: 9 - TS_SHARE_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x00\\x00\\x00\\x00\" +\n \"\\x0d\\x00\" + # capabilitySetType: 13 - TS_INPUT_CAPABILITYSET\n \"\\x58\\x00\" + # lengthCapability: 88\n \"\\x91\\x00\\x20\\x00\\x09\\x04\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x00\\x00\\x00\\x00\" +\n \"\\x0c\\x00\" + # capabilitySetType: 12 - TS_SOUND_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" +\n \"\\x0e\\x00\" + # capabilitySetType: 14 - TS_FONT_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" +\n \"\\x10\\x00\" + # capabilitySetType: 16 - TS_GLYPHCAChE_CAPABILITYSET\n \"\\x34\\x00\" + # lengthCapability: 52\n \"\\xfe\\x00\\x04\\x00\\xfe\\x00\\x04\\x00\\xfe\\x00\\x08\\x00\\xfe\\x00\\x08\\x00\" +\n \"\\xfe\\x00\\x10\\x00\\xfe\\x00\\x20\\x00\\xfe\\x00\\x40\\x00\\xfe\\x00\\x80\\x00\" +\n \"\\xfe\\x00\\x00\\x01\\x40\\x00\\x00\\x08\\x00\\x01\\x00\\x01\\x03\\x00\\x00\\x00\" +\n \"\\x0f\\x00\" + # capabilitySetType: 15 - TS_BRUSH_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" +\n \"\\x11\\x00\" + # capabilitySetType: ??\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x01\\x00\\x00\\x00\\x00\\x28\\x64\\x00\" +\n \"\\x14\\x00\" + # capabilitySetType: ??\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x15\\x00\" + # capabilitySetType: ??\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x02\\x00\\x00\\x00\\x00\\x0a\\x00\\x01\" +\n \"\\x1a\\x00\" + # capabilitySetType: ??\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\xaf\\x94\\x00\\x00\" +\n \"\\x1c\\x00\" + # capabilitySetType: ??\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x12\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" +\n \"\\x1b\\x00\" + # capabilitySetType: ??\n \"\\x06\\x00\" + # lengthCapability: 6\n \"\\x01\\x00\" +\n \"\\x1e\\x00\" + # capabilitySetType: ??\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" +\n \"\\x18\\x00\" + # capabilitySetType: ??\n \"\\x0b\\x00\" + # lengthCapability: 11\n \"\\x02\\x00\\x00\\x00\\x03\\x0c\\x00\" +\n \"\\x1d\\x00\" + # capabilitySetType: ??\n \"\\x5f\\x00\" + # lengthCapability: 95\n \"\\x02\\xb9\\x1b\\x8d\\xca\\x0f\\x00\\x4f\\x15\\x58\\x9f\\xae\\x2d\\x1a\\x87\\xe2\" +\n \"\\xd6\\x01\\x03\\x00\\x01\\x01\\x03\\xd4\\xcc\\x44\\x27\\x8a\\x9d\\x74\\x4e\\x80\" +\n \"\\x3c\\x0e\\xcb\\xee\\xa1\\x9c\\x54\\x05\\x31\\x00\\x31\\x00\\x00\\x00\\x01\\x00\" +\n \"\\x00\\x00\\x25\\x00\\x00\\x00\\xc0\\xcb\\x08\\x00\\x00\\x00\\x01\\x00\\xc1\\xcb\" +\n \"\\x1d\\x00\\x00\\x00\\x01\\xc0\\xcf\\x02\\x00\\x08\\x00\\x00\\x01\\x40\\x00\\x02\" +\n \"\\x01\\x01\\x01\\x00\\x01\\x40\\x00\\x02\\x01\\x01\\x04\"\n\n ## type = 0x13 = TS_PROTOCOL_VERSION | PDUTYPE_CONFIRMACTIVEPDU\n return(rdp_build_share_control_header(0x13, pdu))\n end", "def getSerialNumber ()\n return readValue(\"rPDUIdentSerialNumber.0\")\n end", "def generate_short_payload_singlesig_address\n ConvertAddress.encode(prefix, short_payload(CODE_HASH_INDEX_SINGLESIG))\n end", "def header\n\t\th = String.new\n\t\t# five nulls for the sign to detenct the baud rate\n\t\t5.times do\n\t\t\th << NULL\n\t\tend\n\t\t# Start of header (SOH)\n\t\th << SOH\n\t\t# Broadcast to all signs\n\t\th << 'Z00'\n\t\t# Start of text (STX)\n\t\th << STX\n\t\treturn h\n\tend", "def sample_packhdr_be_nsec\n \"\\xA1\\xB2<M\" +\n \"S\\xFEn')6\\xA0)\\x00\\x00\\x02\\x1F\\x00\\x00\\x02\\x1F\" +\n \"\\x00\\x00\\xFF\\xFF\\x00\\x00\\x00\\x01\" # padding\nend", "def pdu_client_confirm_active\n pdu =\n \"\\xea\\x03\\x01\\x00\" + # shareId: 66538\n \"\\xea\\x03\" + # originatorId\n \"\\x06\\x00\" + # lengthSourceDescriptor: 6\n \"\\x8e\\x01\" + # lengthCombinedCapabilities: 398\n \"\\x4d\\x53\\x54\\x53\\x43\\x00\" + # SourceDescriptor: 'MSTSC'\n \"\\x0e\\x00\" + # numberCapabilities: 14\n \"\\x00\\x00\" + # pad2Octets\n \"\\x01\\x00\" + # capabilitySetType: 1 - TS_GENERAL_CAPABILITYSET\n \"\\x18\\x00\" + # lengthCapability: 24\n \"\\x01\\x00\\x03\\x00\\x00\\x02\\x00\\x00\\x00\\x00\\x0d\\x04\\x00\\x00\\x00\\x00\" + #\n \"\\x00\\x00\\x00\\x00\" + #\n \"\\x02\\x00\" + # capabilitySetType: 2 - TS_BITMAP_CAPABILITYSET\n \"\\x1c\\x00\" + # lengthCapability: 28\n \"\\x10\\x00\\x01\\x00\\x01\\x00\\x01\\x00\\x20\\x03\\x58\\x02\\x00\\x00\\x01\\x00\" + #\n \"\\x01\\x00\\x00\\x00\\x01\\x00\\x00\\x00\" + #\n \"\\x03\\x00\" + # capabilitySetType: 3 - TS_ORDER_CAPABILITYSET\n \"\\x58\\x00\" + # lengthCapability: 88\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\x00\\x00\\x00\\x00\\x01\\x00\\x14\\x00\\x00\\x00\\x01\\x00\\x47\\x01\\x2a\\x00\" + #\n \"\\x01\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x01\\x01\\x01\\x01\\x00\\x01\\x01\\x00\" + #\n \"\\x00\\x00\\x00\\x00\\x01\\x01\\x01\\x00\\x00\\x01\\x01\\x01\\x00\\x00\\x00\\x00\" + #\n \"\\xa1\\x06\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x84\\x03\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\xe4\\x04\\x00\\x00\\x13\\x00\\x28\\x00\\x00\\x00\\x00\\x03\\x78\\x00\\x00\\x00\" + #\n \"\\x78\\x00\\x00\\x00\\x50\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\x08\\x00\" + # capabilitySetType: 8 - TS_POINTER_CAPABILITYSET\n \"\\x0a\\x00\" + # lengthCapability: 10\n \"\\x01\\x00\\x14\\x00\\x14\\x00\" + #\n \"\\x0a\\x00\" + # capabilitySetType: 10 - TS_COLORTABLE_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x06\\x00\\x00\\x00\" + #\n \"\\x07\\x00\" + # capabilitySetType: 7 - TSWINDOWACTIVATION_CAPABILITYSET\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\x05\\x00\" + # capabilitySetType: 5 - TS_CONTROL_CAPABILITYSET\n \"\\x0c\\x00\" + # lengthCapability: 12\n \"\\x00\\x00\\x00\\x00\\x02\\x00\\x02\\x00\" + #\n \"\\x09\\x00\" + # capabilitySetType: 9 - TS_SHARE_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x00\\x00\\x00\\x00\" + #\n \"\\x0f\\x00\" + # capabilitySetType: 15 - TS_BRUSH_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" + #\n \"\\x0d\\x00\" + # capabilitySetType: 13 - TS_INPUT_CAPABILITYSET\n \"\\x58\\x00\" + # lengthCapability: 88\n \"\\x01\\x00\\x00\\x00\\x09\\x04\\x00\\x00\\x04\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\x0c\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\" + #\n \"\\x00\\x00\\x00\\x00\" + #\n \"\\x0c\\x00\" + # capabilitySetType: 12 - TS_SOUND_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" + #\n \"\\x0e\\x00\" + # capabilitySetType: 14 - TS_FONT_CAPABILITYSET\n \"\\x08\\x00\" + # lengthCapability: 8\n \"\\x01\\x00\\x00\\x00\" + #\n \"\\x10\\x00\" + # capabilitySetType: 16 - TS_GLYPHCAChE_CAPABILITYSET\n \"\\x34\\x00\" + # lengthCapability: 52\n \"\\xfe\\x00\\x04\\x00\\xfe\\x00\\x04\\x00\\xfe\\x00\\x08\\x00\\xfe\\x00\\x08\\x00\" + #\n \"\\xfe\\x00\\x10\\x00\\xfe\\x00\\x20\\x00\\xfe\\x00\\x40\\x00\\xfe\\x00\\x80\\x00\" + #\n \"\\xfe\\x00\\x00\\x01\\x40\\x00\\x00\\x08\\x00\\x01\\x00\\x01\\x02\\x00\\x00\\x00\"\n\n # type = 0x13 = TS_PROTOCOL_VERSION | PDUTYPE_CONFIRMACTIVEPDU\n build_share_control_header(0x13, pdu)\n end", "def service_number\n @binary_components[0]\n end", "def pick_byte!\n pick_char![0]\n end", "def next_byte\n byte = slice!(0)\n byte.nil? ? 0 : byte.unpack1('c')\n end", "def smb1_sign(packet)\n # Pack the Sequence counter into a int64le\n packed_sequence_counter = [sequence_counter].pack('Q<')\n packet.smb_header.security_features = packed_sequence_counter\n signature = OpenSSL::Digest::MD5.digest(session_key + packet.to_binary_s)[0, 8]\n packet.smb_header.security_features = signature\n @sequence_counter += 1\n\n packet\n end", "def smb1_sign(packet)\n if self.signing_required && !self.session_key.empty?\n # Pack the Sequence counter into a int64le\n packed_sequence_counter = [self.sequence_counter].pack('Q<')\n packet.smb_header.security_features = packed_sequence_counter\n signature = OpenSSL::Digest::MD5.digest(self.session_key + packet.to_binary_s)[0,8]\n packet.smb_header.security_features = signature\n self.sequence_counter += 1\n packet\n else\n packet\n end\n end", "def smb1_sign(packet)\n packet = Signing::smb1_sign(packet, @session_key, @sequence_counter)\n @sequence_counter += 1\n\n packet\n end", "def make_netbios(payload)\n [payload.length & 0x00ffffff, payload].pack(\"Na*\")\nend", "def card_identification\n message.fields[6].strip\n end", "def header\n if @bytes.length < INES_HEADER_SIZE\n raise 'invalid or missing header'\n end\n\n return @bytes.slice(0, INES_HEADER_SIZE)\n end", "def checksum\n @header[ACTIVE_MAILBOX_CHECKSUM]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Consider the following "magic" 3gon ring, filled with the numbers 1 to 6, and each line adding to nine. (4) \ (3) / \ (1)(2)(6) / (5) Working clockwise, and starting from the group of three with the numerically lowest external node (4,3,2 in this example), each solution can be described uniquely. For example, the above solution can be described by the set: 4,3,2; 6,2,1; 5,1,3. It is possible to complete the ring with four different totals: 9, 10, 11, and 12. There are eight solutions in total. Total Solution Set 9 4,2,3; 5,3,1; 6,1,2 9 4,3,2; 6,2,1; 5,1,3 10 2,3,5; 4,5,1; 6,1,3 10 2,5,3; 6,3,1; 4,1,5 11 1,4,6; 3,6,2; 5,2,4 11 1,6,4; 5,4,2; 3,2,6 12 1,5,6; 2,6,4; 3,4,5 12 1,6,5; 3,5,4; 2,4,6 By concatenating each group it is possible to form 9digit strings; the maximum string for a 3gon ring is 432621513. Using the numbers 1 to 10, and depending on arrangements, it is possible to form 16 and 17digit strings. What is the maximum 16digit string for a "magic" 5gon ring? ( ) \ ( ) ( ) / \ / ( ) ( ) / \ / ( ) ( )( )( ) \ ( )
def solve( n = 16 ) max = 0 (1..10).each do |a| (1..10).each do |b| next if b == a (1..10).each do |c| next if c == b || c == a (1..10).each do |d| next if d == c || d == b || d == a (1..10).each do |e| next if e == d || e == c || e == b || e == a rotate = 3*[a, b, c, d, e].each_with_index.min[1] (1..10).each do |f| next if f == e || f == d || f == c || f == b || f == a (1..10).each do |g| next if g == f || g == e || g == d || g == c || g == b || g == a t = a + f + g (1..10).each do |h| next if h == g || h == f || h == e || h == d || h == c || h == b || h == a next unless t == b + g + h (1..10).each do |i| next if i == h || i == g || i == f || i == e || i == d || i == c || i == b || i == a next unless t == c + h + i (1..10).each do |j| next if j == i || j == h || j == g || j == f || j == e || j == d || j == c || j == b || j == a next unless t == d + i + j && t == e + j + f s = [a, f, g, b, g, h, c, h, i, d, i, j, e, j, f] rotate.times {s.push s.shift} s = s.join next if n != s.length max = [max, s.to_i].max end end end end end end end end end end max end
[ "def tetragon_ring\n [*1..6].reverse.permutation do |a,b,c,d,e,f|\n sum = a+d+e\n next unless b+e+f == sum && c+f+d == sum && a < b && a < c\n return [[a,d,e],[b,e,f],[c,f,d]].flatten.join.to_i\n end\nend", "def gen_rings\n shortc = (0..9).collect{|i| i unless @longc.include?(i) }.compact\n raise DataError if shortc.nil?\n long = @longc.collect{|i| (0..9).collect{|j| i*10+j } }.flatten\n raise DataError if long.nil?\n @shortc = shortc.dup\n\n word = @full_key.dup\n word.scan(/./) do |c|\n if 'ESANTIRU'.include? c then\n ind = shortc.shift\n else\n ind = long.shift\n end\n @alpha[c] = ind.to_s\n @ralpha[ind.to_s] = c\n end\n end", "def combinationThree(num, start, final) \n # check the first \"if\" statement.\n if num > (final - start + 1)\n []\n # check the second statement, and \n # return a list a single number string.\n elsif num == 1\n (start.to_s..final.to_s).to_a\n # if the combination number equals to (end - start),\n # then return a single string of numbers as a list.\n elsif num == (final - start + 1)\n line = start.to_s\n while start < final\n start += 1\n line << (\" \" + start.to_s)\n end\n [line]\n # make a for loop to call every sub combination function, and then,\n # if the sub-function return a actually list, add the frist element\n # into each string, such as:\n # list = combination(1, 2, 3); <-- return {\"2\", \"3\"};\n # for loop add each string \"1 \";\n # so it will return {\"1 2\", \"1 3\"};\n # if the string.length == 0, then it won't add additional number. \n else\n line_set = [];\n for i in ((start + 1)..final)\n for line in combinationThree(num - 1, i, final)\n if line.length > 0\n line.insert(0, (i - 1).to_s + \" \")\n line_set << line\n end\n end\n end\n line_set\n end\nend", "def find_combinations(sequence, m_max, i_max, d_max)\n if sequence.length > 1\n # If the length of the sequence is more than 1, it is dividable\n\n left_tree = find_combinations(sequence[0..(sequence.length/2).floor-1], m_max, i_max, d_max)\n right_tree = find_combinations(sequence[(sequence.length/2).floor..-1], m_max, i_max, d_max)\n else\n # If it is not dividable, create each combination of mismatches, insertions, and deletions\n # for that particular character, and return.\n\n insertion_combinations = []\n i_max.times { |i|\n insertion_combinations << Leaf.new('[^N]' * (i+1) + sequence, mismatches=0, insertions=i+1, deletions=0)\n insertion_combinations << Leaf.new(sequence + '[^N]' * (i+1), mismatches=0, insertions=i+1, deletions=0)\n }\n\n return [Leaf.new(sequence, mismatches=0, insertions=0, deletions=0),\n Leaf.new(\"[^#{sequence}N]\", mismatches=1, insertions=0, deletions=0),\n Leaf.new('', mismatches=0, insertions=0, deletions=1)] + insertion_combinations\n end\n\n combined = []\n\n # Hash table containing all unique combinations in this recursion step\n unique_combinations = Hash.new\n\n # Combines each leaf from the left tree with each leaf in the right tree,\n # thus creating all possible combinations of each tree.\n\n left_tree.each{ |left_leaf|\n right_tree.each{ |right_leaf|\n\n # If a combination would lead to a violation of the given maximum number of\n # mismatches, insertions, or deletions, the iteration will be skipped.\n\n if (left_leaf.mismatches + right_leaf.mismatches) > m_max \\\n or (left_leaf.insertions + right_leaf.insertions) > i_max \\\n or (left_leaf.deletions + right_leaf.deletions) > d_max\n\n next\n end\n\n # If one of the combination exists in the {unique} table, it will be skipped\n # This is possible due to the fact that {Hash.has_key} has O(1) time complexity.\n\n if unique_combinations.has_key? (left_leaf.value + right_leaf.value)\n @counter += 1\n else\n\n # Otherwise we add it to the table\n unique_combinations[left_leaf.value + right_leaf.value] = true\n\n combined << Leaf.new(left_leaf.value + right_leaf.value,\n mismatches=left_leaf.mismatches + right_leaf.mismatches,\n insertions=left_leaf.insertions + right_leaf.insertions,\n deletions=left_leaf.deletions + right_leaf.deletions)\n end\n }\n }\n\n return combined\n end", "def solve( n = 2_000 )\n # We can classify every tile according to its angular position around the\n # unit circle, setting position 0 at the top since that's where each row\n # starts in the problem statement. Positions 1-5 then follow every 60° as\n # we work our way counter-clockwise. Depending on which of these positions\n # each tile falls (or between which pair of positions), we use different\n # formulae to calculate its six neighbors to the N, NW, SW, S, SE, and NE:\n # \n # Pos 0: n even = fhp\n # N = n + ring (g) S = n - ring + 6 (a)\n # NW = n + ring + 1 (h) SE = n + ring - 1 (f)\n # SW = n + 1 NE = n + (2*ring + 5) (p)\n #\n # Pos 0-1: n even = bh, n odd = ag \n # N = n + ring (g) S = n - ring + 6 (a)\n # NW = n + ring + 1 (h) SE = n - ring + 5 (b)\n # SW = n + 1 NE = n - 1\n #\n # Pos 1: n even = bh, n odd = gi\n # N = n + ring (g) S = n + 1\n # NW = n + ring + 1 (h) SE = n - ring + 5 (b)\n # SW = n + ring + 2 (i) NE = n - 1\n #\n # Pos 1-2: n even = bh, n odd = ci\n # N = n - 1 S = n + 1\n # NW = n + ring + 1 (h) SE = n - ring + 5 (b)\n # SW = n + ring + 2 (i) NE = n - ring + 4 (c)\n #\n # Pos 2: n even = hj\n # N = n - 1 S = n + ring + 3 (j)\n # NW = n + ring + 1 (h) SE = n + 1\n # SW = n + ring + 2 (i) NE = n - ring + 4 (c)\n #\n # Pos 2-3: n even = dj, n odd = ci\n # N = n - ring + 3 (d) S = n + ring + 3 (j)\n # NW = n - 1 SE = n + 1\n # SW = n + ring + 2 (i) NE = n - ring + 4 (c)\n #\n # Pos 3: n even = dj, n odd = ik\n # N = n - ring + 3 (d) S = n + ring + 3 (j)\n # NW = n - 1 SE = n + ring + 4 (k)\n # SW = n + ring + 2 (i) NE = n + 1\n #\n # Pos 3-4: n even = dj, n odd = ek\n # N = n - ring + 3 (d) S = n + ring + 3 (j)\n # NW = n - ring + 2 (e) SE = n + ring + 4 (k)\n # SW = n - 1 NE = n + 1\n #\n # Pos 4: n even = jl\n # N = n + 1 S = n + ring + 3 (j)\n # NW = n - ring + 2 (e) SE = n + ring + 4 (k)\n # SW = n - 1 NE = n + ring + 5 (l)\n #\n # Pos 4-5: n even = fl, n odd = ek\n # N = n + 1 S = n - 1\n # NW = n - ring + 2 (e) SE = n + ring + 4 (k)\n # SW = n - ring + 1 (f) NE = n + ring + 5 (l)\n #\n # Pos 5: n even = fl, n odd = km\n # N = n + ring + 6 (m) S = n - 1\n # NW = n + 1 SE = n + ring + 4 (k)\n # SW = n - ring + 1 (f) NE = n + ring + 5 (l)\n #\n # Pos 5-0, except last: n even = fl, n odd = gm\n # N = n + ring + 6 (m) S = n - ring (g)\n # NW = n + 1 SE = n - 1\n # SW = n - ring + 1 (f) NE = n + ring + 5 (l)\n #\n # Pos 5-0, only last: n even = flo, n odd = gmo\n # N = n + ring + 6 (m) S = n - ring (g)\n # NW = n - ring + 1 (f) SE = n - 1\n # SW = n - (2*ring - 7) (o) NE = n + ring + 5 (l)\n #\n # From these formula, we can derive the difference between a tile and each\n # of its neighbors. If we arrange all potential differences in ascending\n # order, it becomes obvious that for n even or odd, some deltas will al-\n # ways be even, and thus can never be prime (>2).\n #\n # Furthermore, we can see that only in certain positions will a tile ever\n # differ from three neighbors by odd amounts (position 0 and just to the\n # right of position 0). In all other cases, at most two deltas will be\n # odd, meaning PD(n) will be 2 or less.\n #\n # n even n odd\n # a = ring - 6 even a\n # b = ring - 5 b even\n # c = ring - 4 even c\n # d = ring - 3 d even\n # e = ring - 2 even e\n # f = ring - 1 f even\n # g = ring even g\n # h = ring + 1 h even\n # i = ring + 2 even i\n # j = ring + 3 j even\n # k = ring + 4 even k\n # l = ring + 5 l even\n # m = ring + 6 even m\n # o = 2ring - 7 o o\n # p = 2ring + 5 p p\n pd3 = [1, 2]\n base, ring = 8, 12\n \n while pd3.size < n\n # Only at position 0 and one tile to the right will there ever be three\n # odd deltas, so those are the only ones we have to check for primality.\n # Both share a delta of f = ring - 1.\n if (ring - 1).prime?\n # Check the other odd deltas for position 0. \n pd3 << base if (ring + 1).prime? && (2*ring + 5).prime?\n\n # Check the other odd deltas for one tile to the right of position 0.\n pd3 << base + ring - 1 if (ring + 5).prime? && (2*ring - 7).prime?\n end\n\n # Advance the first tile of the current ring (base), and the number of\n # tiles it contains (ring). \n base += ring\n ring += 6\n end\n\n pd3[-1]\n end", "def find_ring_and_corner_square(square)\n\tshifted_square = square - 1\n\t\n\tmultiples = (shifted_square.fdiv 8).ceil\n\n\tcandidate_ring = 0\n\tcorner_multiple = 0\n\tmax_mulitple = 0\n\n\twhile multiples > max_mulitple\n\t\tcandidate_ring += 1\n\n\t\t# Store the previous ring's max for finding the corner square\n\t\tcorner_multiple = max_mulitple\n\n\t\t# There are (Ring #) multiples in each ring\n\t\tmax_mulitple += candidate_ring\n\tend\n\n\tlargest_corner = (corner_multiple * 8) + 1\n\t[candidate_ring, largest_corner]\nend", "def generate_grids\n return if @all_patterns.size > 0\n\n # all 9 bit patterns which have 5 bits set\n patts = []\n (0..4).each do |b1|\n (b1+1..5).each do |b2|\n (b2+1..6).each do |b3|\n (b3+1..7).each do |b4|\n (b4+1..8).each do |b5|\n patts << ((1<<b1)|(1<<b2)|(1<<b3)|(1<<b4)|(1<<b5))\n end\n end\n end\n end\n end\n raise \"Sanity error\" if patts.size != 126\n\n # try all combinations of three row patterns\n patts.each do |p1|\n patts.each do |p2|\n pp = p1 | p2\n patts.each do |p3|\n next unless pp | p3 == 0x1ff\n p = ((p1 << 18) | (p2 << 9) | p3)\n @all_patterns << p\n\n # Now index this pattern by category\n cat = p1.to_s(2).to_i(32) +\n p2.to_s(2).to_i(32) +\n p3.to_s(2).to_i(32)\n @cats[cat] ||= []\n @cats[cat] << p\n end\n end\n end\n end", "def formingMagicSquare(s)\n# all 8 of them\n magic_three_squares = [\n [[8, 1, 6], [3, 5, 7], [4, 9, 2]],\n [[6, 1, 8], [7, 5, 3], [2, 9, 4]],\n [[4, 9, 2], [3, 5, 7], [8, 1, 6]],\n [[2, 9, 4], [7, 5, 3], [6, 1, 8]],\n [[8, 3, 4], [1, 5, 9], [6, 7, 2]],\n [[4, 3, 8], [9, 5, 1], [2, 7, 6]],\n [[6, 7, 2], [1, 5, 9], [8, 3, 4]],\n [[2, 7, 6], [9, 5, 1], [4, 3, 8]],\n ]\n costs = magic_three_squares.map {|ms| cost_of_transformation(ms, s)}\n return costs.min\nend", "def solve( n = 30 )\n # Solving this with combinatorics quickly turned into a major headache.\n # Instead, tackle it inductively by considering how the total changes as\n # as each new day's trinary string is added one by one. By keeping track\n # of certain characteristics for a string of length m, we can then make\n # simple statements about how those characteristics changes when we in-\n # crease the string's length to m + 1.\n #\n # Given some (valid, \"prize\") string S to which we will prepend either L,\n # O, or A, we know the result will also be valid provided:\n #\n # o We prepend O\n # o We prepend L AND S doesn't contain L already\n # o We prepend A AND S doesn't already start with AA\n #\n # This gives us an idea of what characteristics might be helpful to record\n # for each n:\n #\n # U = count of prize S containing L\n # V = count of prize S starting with A\n # W = count of prize S starting with AA\n # X = count of U ∩ V (contains L and starts with A)\n # Y = count of U ∩ W (contains L and starts with AA)\n # Z = count of prize S\n #\n # Now we can formulate functions to take U, V, W, ... to U', V', W', etc.\n # as n increases. That is, given U_n, V_n, W_n, etc., how do we compute\n # U_(n+1), V_(n+1), W_(n+1), ...?\n #\n # Given U valid strings containing L, we know they'll remain valid after\n # we prepend O, so U' will be at least O. We also know that we can do the\n # same for A, as long as we skip S that start with AA, so we need to in-\n # crease U' by an additional U - Y. Similarly, we know we can create Z - U\n # new L strings by prepending it to existing prizes strings. So, U' will\n # be given by U' = U + (U - Y) + (Z - U) = U - Y + Z.\n #\n # To compute V', note that we will have added A to all strings except the\n # ones starting with AA, but the ones that had started with A shouldn't be\n # counted (since they will now start with AA). V' = Z - V - W.\n #\n # W' is simply the count of valid strings previously starting with A,\n # since those are the only ones that could conceivably now begin with AA.\n # W' = V. Similarly, Y' = X.\n #\n # X' must necessarily be less than U (since not all L strings will start\n # with A), and in fact, we must subtract members that had been counted,\n # since they will have had A prepended and now start with AA. Similarly,\n # we shouldn't count the Y strings toward X' either, since they will not\n # start with A now. X' = U - X - Y.\n #\n # With the first five quantities defined in terms of the previous values,\n # we can now derive a formula for the total number of valid prize strings.\n # For every valid string of length m, there will be corresponding strings\n # of length m + 1 such that:\n #\n # o it is identical except for a new leading L, except for strings that\n # already contain L (Z - U new items),\n # o it is identical except for a new leading O (Z new items), or\n # o it is identical except for a new leading A, except for strings that\n # already started with AA (Z - W new items)\n #\n # Therefore, Z' = Z - U + Z + Z - W = 3Z - U - W.\n u, v, w, x, y, z = 1, 1, 0, 0, 0, 3\n \n (n - 1).times do\n u, v, w, x, y, z = u - y + z, z - v - w, v, u - x - y, x, 3*z - u - w\n end\n\n z\n end", "def solution(a)\n # We have to be careful to put the pseudo gates in the right order, otherwise we could ski past the\n # finish line and continue to ski on the mirror image gates. To ensure that once we turn, we cannot\n # access any of the gates on the slope image prior to the turn, we have to put the pseudo gates\n # in the sequence in order from farthest to nearest.\n offset = a.max * 2 + 2 # we want to make sure that no points on the offset maps overlaps points on the other maps\n gates = []\n a.each do |g|\n gates.push(offset + g) # the second set of gates, after the second turn, going left again\n gates.push(offset - g)\n gates.push(g)\n end\n # Now all we have to do is find the length of the longest increasing subsequence of gates\n # m[i] holds the last value in the best sequence of length i\n # I don't know why it's called \"m\", maybe for \"memoize\", but that's what it is called in the\n # literature I'm stealing from, so I'll use it.\n\n max_length = 1\n m = [-1, gates.shift]\n gates.each do |g|\n # Find the longest sequence to add this gate to.\n # Built in bsearch finds the minimum value greater than, so actually it returns the shortest sequence\n # we cannot add this gate to, which is fine. By adding this gate to the sequence one shorter, we\n # create a new, better sequence of this length.\n too_long_idx = (1..max_length).bsearch { |i| m[i] > g }\n unless too_long_idx\n max_length += 1\n m[max_length] = g\n else\n m[too_long_idx] = g\n end\n end\n max_length\nend", "def connect_to_borders(yx)\n 2.upto(@gsize-1) do |n|\n AROUND.each do |c|\n i = (c[0]<0 ? @gsize : c[0]*n) + c[1] # n,1,n,gsize\n j = (c[2]<0 ? @gsize : c[2]*n) + c[3] # 1,n,gsize,n\n if yx[j][i]==EMPTY\n i2= (c[0]<0 ? @gsize-1 : c[0]*n) + c[1]*2 # n,2,n,gsize-1\n j2= (c[2]<0 ? @gsize-1 : c[2]*n) + c[3]*2 # 2,n,gsize-1,n\n i3= (c[0]<0 ? @gsize : c[0]*(n+1)) + c[1] # n+1,1,n+1,gsize\n j3= (c[2]<0 ? @gsize : c[2]*(n+1)) + c[3] # 1,n+1,gsize,n+1\n i4= (c[0]<0 ? @gsize : c[0]*(n-1)) + c[1] # n-1,1,n-1,gsize\n j4= (c[2]<0 ? @gsize : c[2]*(n-1)) + c[3] # 1,n-1,gsize,n-1\n next2border = yx[j2][i2]\n if next2border!=EMPTY and yx[j3][i3]==EMPTY and yx[j4][i4]==EMPTY\n add_stone(yx, i, j, next2border)\n end\n end\n end\n end\n end", "def problem_86a\n m = 1818\n# m = 100\n\n p3 = lambda do |mm,nn|\n raise \"bad value\" if mm == nn\n mm,nn = nn,mm if mm < nn\n m2 = mm*mm\n n2 = nn*nn\n a,b,c = [m2 - n2, 2*mm*nn, m2 + n2]\n [m2 - n2, 2*mm*nn, m2 + n2]\n end\n\n in_range = lambda {|a,b,c| a <= m && b <= 2*m}\n\n solutions = lambda do |ret,x,b,c|\n return unless x <= m\n# puts \"#{x} #{b} #{c}\"\n bm = (b >= m) ? m-1 : b-1\n bm = x-1 if x <= bm\n if x < b \n ys = b - x\n else\n ys = 1\n end\n p1 = c.to_f # Math.sqrt(x**2 + (y+z)**2)\n z = b - ys\n if p1 <= Math.sqrt(ys**2 + (x+z)**2) &&\n p1 <= Math.sqrt(z**2 + (x+ys)**2)\n if false\n p = [b,x].sort\n if r = ret[p]\n puts \"dup r = #{r} #{bm-ys+1}\"\n end\n ret[p] = bm-ys+1\n else\n ys.upto(bm) do |y|\n ret[[x,y,b-y].sort] = true\n end\n end\n end\n end\n\n hits = Hash.new\n hit = 0\n (1..(m/2)).each do |x|\n ((x+1)..(m/2+1)).each do |y|\n next unless (x+y).odd? && x.gcd(y) == 1\n sides = p3.call(x,y).sort\n next unless in_range.call(*sides)\n hits[sides] = true\n hit += 1\n end\n end\n puts \"Generated primative triangles\"\n good = {}\n # Sort the primative triangles into sets according to\n # max M value. Then for each increase, pick the groups with\n # factors into the M and solutions.call.\n # This should let us slide out.\n \n hits.each_key do |p|\n a,b,c = p\n (1..(2*m/([a,b].max))).each do |k|\n aa,bb,cc = a*k, b*k, c*k\n solutions.call(good,aa,bb,cc)\n solutions.call(good,bb,aa,cc)\n# good += solutions.call(aa,bb,cc)\n# good += solutions.call(bb,aa,cc)\n end\n end\n# good.compact!\n puts good.length\n puts \"Triangles => #{hit}\"\n puts \"Unique Triangles => #{hits.length}\"\n# good = good.map {|a| a.sort }.uniq.sort\n# good = good.sort.uniq\n puts \"sorted\"\n\n# hit = 0\n# good.each_pair do |p,v|\n# puts \"#{p} => #{v}\"\n# hit += v\n# end\n# puts \"Hit = #{hit}\"\n\n good.length\nend", "def generate_shape(n)\n (\"#{\"+\" * n}\\n\" * n).chop\nend", "def generate_all_magic_squares\n all = []\n digits = [1,2,3,4,5,6,7,8,9]\n permutations = digits.permutation.to_a\n permutations.each do |p|\n a = [[p[0],p[1],p[2]],[p[3],p[4],p[5]],[p[6],p[7],p[8]]]\n all << a if is_magic?(a)\n end\n all\nend", "def kolakoski(n)\r\n queue = [2]\r\n seq = \"122\" # start with 122 \r\n lastLenOne = false\r\n \r\n while seq.length < n.to_i\r\n blockLen = queue.shift\r\n last = seq[-1]\r\n \r\n opp = last == \"1\" ? \"2\" : \"1\"\r\n \r\n if blockLen == 1\r\n seq << opp\r\n queue.push(opp.to_i)\r\n lastLenOne = true\r\n elsif blockLen == 2 && seq[-2] != last && !lastLenOne\r\n seq << last\r\n queue.push(last.to_i)\r\n lastLenOne = false\r\n else\r\n seq << opp << opp\r\n queue.push(opp.to_i)\r\n queue.push(opp.to_i)\r\n lastLenOne = false\r\n end\r\n end\r\n \r\n if seq.length > n.to_i\r\n seq = seq[0...n.to_i] # remove excess symbols\r\n end\r\n \r\n return seq\r\nend", "def climb(mountain)\n # take the last row\n routes = []\n\n if mountain.size == 1\n # subsitute the o with ^ to mark path\n # mountain[0] is a string, so we use [] to put it back into an array again\n puts \"hello\"\n return routes.push( [ mountain[0].gsub('O', '^') ] )\n end\n\n # mountain[-1] is the bottom row, for a mountain of 4\n # it is \"O O O O\"\n mountain[-1].split(\"\").each_with_index do |char, index|\n if char == 'O'\n # call climb helper on the smaller mountain, with starting position\n #if (index - 1 > 0)\n\n # if the left upper char is a 'O', climb the rest of the mountain\n # with that as the starting position\n if mountain[-2][index-1] == 'O'\n puts \"climb: call helper on left #{index-1}\"\n # mountain[0..-2] is the mountain with the last row trimmed off\n routes_subset = climb_helper(mountain[0..-2], index-1)\n # initialize starting position with all blanks\n starting_position = \" \"*mountain[-1].length\n # mark the starting position\n starting_position[index] = '^'\n # puts starting_position\n\n # for each subset route, append the starting position\n routes_subset.each do |route_in_subset|\n routes.push( route_in_subset.concat([starting_position]) )\n end\n\n # to undo: old bug that was causing less routes to be returned\n # uncomment this in four places in this code to reproduce the bug\n # because i have two routes returned from routes_subset\n # but I am pushing both into routes\n #routes.push( routes_subset.concat([starting_position]) );\n\n end\n #end\n\n #if (index + 1 < mountain[-1].length )\n\n if mountain[-2][index+1] == 'O'\n # puts \"climb: calling helper on right #{index+1}\"\n routes_subset = climb_helper(mountain[0..-2], index+1)\n # initialize starting position with all blanks\n starting_position = \" \"*mountain[-1].length\n # mark the starting position\n starting_position[index] = '^'\n # puts starting_position\n\n # for each subset route, append the starting position\n routes_subset.each do |route_in_subset|\n routes.push( route_in_subset.concat([starting_position]) )\n end\n #to undo: old bug\n #routes.push( routes_subset.concat([starting_position]) );\n\n end\n\n #end\n\n end\n end\n\n return routes\nend", "def tower_builder_x(n)\n (1..n).map do |lvl|\n space = ' ' * (n - lvl)\n stars = '*' * (lvl * 2 - 1)\n space + stars + space\n end\nend", "def problem_114a(squares = 50)\n num = 1 # Allow for all black\n\n # Return the number of possible allocations\n comb = lambda do |num,items|\n return 1 if num == 1 || items == 0\n return num if items == 1\n ret = num # Allow for [num,0,0], [0,num,0], [0,0,num]\n items.groupings do |a|\n if a.length <= num\n while a.length < num\n a << 0\n end\n #puts \"items => #{a.inspect}\"\n ret += a.permutations\n end\n true\n end\n ret\n end\n\n min_size = 3\n max_red_blocks = (squares+1)/(min_size+1)\n 1.upto(max_red_blocks) do |red_blocks|\n # red_blocks is the number of red elements\n # black_blocks is the number of black elements\n black_blocks = red_blocks + 1\n (red_blocks*min_size).upto((squares - red_blocks) + 1) do |red_squares|\n keep = []\n black_squares = squares - red_squares + 2\n \n rs = comb.call(red_blocks,red_squares - red_blocks * min_size)\n bs = comb.call(black_blocks,black_squares - black_blocks)\n puts \"rb = #{red_blocks}/#{red_squares} bs = #{black_blocks}/#{black_squares} => rs=#{rs} bs=#{bs}\"\n num += rs * bs\n end\n end\n num\nend", "def do_chain_layout(sugar) \n seen_chains = []\n sugar.residue_composition.select { |r| ['GlcNAc','Gal'].include?(r.name(:ic)) }.each { |chain_start|\n debug(\"CHAIN:Start residue name is #{chain_start.name(:ic)}\")\n next if seen_chains.include?(chain_start)\n debug(\"CHAIN:Not seen before\")\n child_chains = sugar.get_chains_from_residue(chain_start).sort_by { |chain| chain.size }\n debug(\"CHAIN:In total there are #{child_chains.size} chains from this position\")\n child_chains.each { |child_chain|\n debug(\"CHAIN:A chain size is #{child_chain.size}\")\n next unless child_chain.size > 1\n debug(\"CHAIN: Doing a chain layout\")\n chain_desc = child_chain.collect {|r| r.name(:ic)+\"#{r.anomer},#{r.paired_residue_position}\"}.join(',')\n debug(\"CHAIN:Chain is #{chain_desc}\")\n\n chain_end = child_chain[-1]\n \n child_chain.reject! { |c| seen_chains.include?(c) }\n\n if child_chain.size > 0\n layout_chain(child_chain)\n seen_chains += child_chain\n end\n debug(\"CHAIN:Trying to arrange children for #{chain_end.name(:ic)}\")\n \n layout_chain_terminals(chain_end)\n\n seen_chains += (sugar.residue_composition(chain_end))[1..-1]\n }\n }\n return seen_chains\n # All chains should be starting at 0,0 and be laid out as straight (or shifted up for 6) lines\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The xpath to the collection that the item belongs to (relative path from the item node)
def collection_xpath "ancestor::#{Ead::Collection.root_xpath}[1]" end
[ "def item_xpath\n \"ancestor::#{Ead::Item.root_xpath}[1]\"\n end", "def xpaths\n self.feeds.last.xpaths\n end", "def xpath\n [parent_xpath, local_xpath].flatten.compact.join(\"/\")\n end", "def xpath\n attr_value('xpath')\n end", "def xpath\n xml.xpath\n end", "def get_item_path(item)\n\treturn item.getLocalisedPathNames.join(\"/\")\nend", "def item_node_set(input_element)\n input_element.xpath(XPATH[:item])\n end", "def items\n @document.xpath('//results/page/items/*')\n end", "def navmap_elements\n xmldoc.xpath(items_xpath)\n end", "def collection_path\n self.class.collection_path\n end", "def xpath_str_for_parent_item_li\n # get the grandparent li ( = li[2]), which will be the parent Master List Item\n './ancestor::li[2]'\nend", "def collection_path(path = nil)\n if path.nil?\n @_her_collection_path ||= root_element.to_s.pluralize\n else\n @_her_collection_path = path\n @_her_resource_path = \"#{path}/:id\"\n end\n end", "def collection_path\n self.class.collection_path\n end", "def collection_path\n @prefix + '/' + @resource.collection_path.to_s\n end", "def as_xpath\n xpath = '/'\n @path.each{|x|\n case x\n when String\n xpath += '/' + x\n when Hash\n xpath += '['\n x.each_with_index do |(name, value), index|\n if index > 0\n xpath += ' and '\n end\n xpath += '@' + name.to_s + '=\"' + value + '\"'\n end\n xpath += ']'\n end\n }\n xpath\n end", "def collection_node; end", "def xpath_of(node)\n node.xpath.to_s\n end", "def relative_xpath(noroot=false)\n xp = xpath_recurse(true)\n xp.gsub!(/^\\//,'') # remove initial path divider if present\n if noroot\n return xp.gsub(/^\\w+\\//,'') # remove first path tag (root)\n else\n return xp\n end\n end", "def collection_uri\n self.class.collection_uri\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Overridden from the Commits::CreateService, to skip some validations we don't need: validate_on_branch! Not needed, the patches are applied on top of HEAD if the branch did not exist validate_branch_existence! Not needed because we continue applying patches on the branch if it already existed, and create it if it did not exist.
def validate! validate_patches! validate_new_branch_name! if new_branch? validate_permissions! end
[ "def create_patch(repo_path, commit, branch)\n `(cd \"#{repo_path}\" && git format-patch --stdout #{commit}..#{branch})`\n end", "def create_default_branch!\n target_repository.create_file(\n git_user,\n \".CopyDesignCollectionService_#{Time.now.to_i}\",\n '.gitlab',\n message: \"Commit to create #{merge_branch} branch in CopyDesignCollectionService\",\n branch_name: merge_branch\n )\n end", "def patch_branch\n num = 1\n branch_name = form_data[\"title\"].parameterize\n return branch_name unless branch_exists?(branch_name)\n branch = \"#{branch_name}-#{num}\"\n while branch_exists?(branch) do\n num = num + 1\n branch = \"#{branch_name}-#{num}\"\n end\n branch\n end", "def patch_branch\n @patch_branch ||= begin\n num = 1\n branch = \"patch-#{num}\"\n puts branches.inspect\n while branches.any? { |b| b.name == branch } do\n num = num + 1\n branch = \"patch-#{num}\"\n end\n branch\n end\n end", "def create_remote_branch\n Gitlab.create_branch(GITLAB_DOCS_REPO, @docs_branch, 'master')\n puts \"Remote branch '#{@docs_branch}' created\"\nrescue Gitlab::Error::BadRequest\n puts \"Remote branch '#{@docs_branch}' already exists\"\nend", "def create_branch(issue_key)\n ui.info \"Checking for existing branch...\"\n unless @git.branches.collect {|branch| branch.name }.include? issue_key\n\n #create the new branch\n branch_repo(issue_key)\n\n # create, update and write the new cookbook version\n increment_version(@issue.issuetype, @cookbook_name, @cookbook_path)\n\n # commit our changes and push\n @git.commit_all(\"Creating new branch for #{issue_key}\")\n @git.push(@git.remote, issue_key)\n\n # add a comment to the issue\n @issue.comment(\"Created new branch: #{issue_key}\")\n else\n ui.info \"Using existing branch: #{issue_key}\"\n @git.checkout(issue_key)\n end\n end", "def remove_via_api!\n Support::Retrier.retry_until(max_duration: 60, sleep_interval: 1, message: \"Waiting for branch #{branch_name} to be protected\") do\n # We confirm it exists before removal because there's no creation event when the default branch is automatically protected by GitLab itself, and there's a slight delay between creating the repo and protecting the default branch\n exists?\n end\n\n super\n end", "def create_remote_branch\n Gitlab.create_branch(GITLAB_DOCS_REPO, docs_branch, 'master')\n puts \"Remote branch '#{docs_branch}' created\"\nrescue Gitlab::Error::BadRequest\n puts \"Remote branch '#{docs_branch}' already exists\"\nend", "def git_branch_create(new_branch_name)\n repo.create_branch(new_branch_name)\n end", "def create_branch(branch, base_branch)\r\n switch_branch(@basedir)\r\n ex(\"bzr branch #{base_branch} #{branch}\")\r\n switch_branch(branch)\r\n end", "def patch_branch\n num = 1\n branch_name = params['title'].parameterize\n return branch_name unless branch_exists?(branch_name)\n branch = \"#{branch_name}-#{num}\"\n while branch_exists?(branch)\n num += 1\n branch = \"#{branch_name}-#{num}\"\n end\n branch\n end", "def prepare_branch(branch)\n # N.B.: the git 1.8.1.2 on the Heroku stack image does not support -B\n begin\n git %W(branch #{branch})\n rescue ->(e) { e.message =~ /fatal: A branch named .* already exists\\./ }\n # ignore\n end\n git %W(checkout #{branch})\n # TODO: it would be useful to create a commit moving us to master branch\n # without actually losing commit history\n git %w(reset --hard master)\n end", "def create_branch(branch, base_branch)\r\n switch_branch(base_branch)\r\n ex(\"git branch -q #{branch}\")\r\n switch_branch(branch)\r\n end", "def start\n create_branch\n process(nil)\n if @repo_updated\n create_pull_request\n else\n delete_branch\n end\n end", "def branch_protection(repo, branch, options = T.unsafe(nil)); end", "def comment_mr_branch_presence_changed\n presence = @push.branch_added? ? :add : :delete\n\n merge_requests_for_source_branch.each do |merge_request|\n SystemNoteService.change_branch_presence(\n merge_request, merge_request.project, @current_user,\n :source, @push.branch_name, presence)\n end\n end", "def create_or_update_git_branch(issue_id, papers_repo, journal_alias)\n id = \"%05d\" % issue_id\n branch = \"#{journal_alias}.#{id}\"\n ref = \"heads/#{branch}\"\n\n begin\n # First grab the files in this branch\n files = github_client.contents(papers_repo,\n :path => branch,\n :ref => ref)\n\n files.each do |file|\n github_client.delete_contents(papers_repo,\n file.path,\n \"Deleting #{file.name}\",\n file.sha,\n :branch => branch)\n end\n\n # Delete the old branch\n github_client.delete_ref(papers_repo, \"heads/#{journal_alias}.#{id}\")\n\n # Then create it again\n github_client.create_ref(papers_repo, \"heads/#{journal_alias}.#{id}\", get_master_ref(papers_repo))\n rescue Octokit::NotFound # If the branch doesn't exist, or there aren't any commits in the branch then create it!\n begin\n github_client.create_ref(papers_repo, \"heads/#{journal_alias}.#{id}\", get_master_ref(papers_repo))\n rescue Octokit::UnprocessableEntity\n # If the branch already exists move on...\n end\n end\n end", "def handle_repo_push_request\n return unless @repository\n\n branch_name = payload[\"ref\"].sub(%r{\\Arefs/heads/}, '')\n branch = @repository.branches.where(name: branch_name).first\n if branch.present? && branch.convergence? && @repository.run_ci?\n sha = payload[\"after\"]\n branch.kickoff_new_build_unless_currently_busy(sha)\n end\n end", "def create_branch new_branch_name\n repo.create_branch new_branch_name\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
share_folders sets up the shared folder definitions on the VirtualBox VM. The transient parameter determines if we're FORCING transient or not. If this is false, then any shared folders will be shared as nontransient unless they've specifically asked for transient.
def share_folders(machine, folders, transient) defs = [] warn_user_symlink = false folders.each do |id, data| hostpath = data[:hostpath] if !data[:hostpath_exact] hostpath = Vagrant::Util::Platform.cygwin_windows_path(hostpath) end enable_symlink_create = true if ENV['VAGRANT_DISABLE_VBOXSYMLINKCREATE'] enable_symlink_create = false end unless data[:SharedFoldersEnableSymlinksCreate].nil? enable_symlink_create = data[:SharedFoldersEnableSymlinksCreate] end warn_user_symlink ||= enable_symlink_create # Only setup the shared folders that match our transient level if (!!data[:transient]) == transient defs << { name: os_friendly_id(id), hostpath: hostpath.to_s, transient: transient, SharedFoldersEnableSymlinksCreate: enable_symlink_create, automount: !!data[:automount] } end end if warn_user_symlink display_symlink_create_warning(machine.env) end driver(machine).share_folders(defs) end
[ "def share_folders(prefix, folders)\n folders.each do |type, local_path, remote_path|\n if type == :host\n env[:machine].config.vm.share_folder(\n \"v-#{prefix}-#{self.class.get_and_update_counter(:shared_folder)}\",\n remote_path, local_path, :nfs => config.nfs)\n end\n end\n end", "def share_folders(folders)\n end", "def share_folders(folders)\n folders.each do |folder|\n # Add the shared folder\n execute_prlctl('set', @uuid,\n '--shf-host-add', folder[:name],\n '--path', folder[:hostpath])\n end\n end", "def share_folders(root_config, prefix, folders, existing = nil)\n existing_set = Set.new\n (existing || []).each do |_, fs|\n fs.each do |_id, data|\n existing_set.add(data[:guestpath])\n end\n end\n\n folders.each do |type, local_path, remote_path|\n next if type != :host\n\n root_config.vm.synced_folder(local_path, remote_path, opts(prefix, remote_path))\n end\n end", "def shared_folders\n {}.tap do |result|\n @env[:machine].config.vm.synced_folders.each do |id, data|\n # Ignore NFS shared folders\n next if !data[:type] == :nfs\n\n # This to prevent overwriting the actual shared folders data\n result[id] = data.dup\n end\n end\n end", "def verify_shared_folders(folders)\n folders.each do |folder|\n # Warm up PoSH communicator for new instances - any stderr results\n # in failure: https://github.com/mefellows/vagrant-dsc/issues/21\n @machine.communicate.test(\"test -d #{folder}\", sudo: true)\n\n @logger.info(\"Checking for shared folder: #{folder}\")\n if !@machine.communicate.test(\"test -d #{folder}\", sudo: true)\n raise DSCError, :missing_shared_folders\n end\n end\n end", "def machine_shares(machine)\n @config['shares'].each do |src, dst|\n machine.vm.synced_folder(\n src,\n dst,\n create: true,\n type: share_type,\n SharedFoldersEnableSymlinksCreate: false\n )\n end\n end", "def shared_folders\n manifest[:shared_folders]\n end", "def prepare_folders\n shared_folders.each do |_id, options|\n hostpath = Pathname.new(options[:hostpath]).expand_path(@env[:root_path])\n\n next unless !hostpath.directory? && options[:create]\n # Host path doesn't exist, so let's create it.\n @logger.debug(\"Host path doesn't exist, creating: #{hostpath}\")\n\n begin\n hostpath.mkpath\n rescue Errno::EACCES\n raise Vagrant::Errors::SharedFolderCreateFailed,\n path: hostpath.to_s\n end\n end\n end", "def synced_folders(vm, host, global)\n if folders = get_config_parameter(host, global, 'synced_folders')\n folders.each do |folder|\n vm.synced_folder folder['src'], folder['dest'], folder['options']\n end\n end\nend", "def prepare_folders\n synced_folders.each do |id, options|\n hostpath = Pathname.new(options[:hostpath]).expand_path(@env[:root_path])\n\n if !hostpath.directory? && options[:create]\n # Host path doesn't exist, so let's create it.\n @logger.debug(\"Host path doesn't exist, creating: #{hostpath}\")\n\n begin\n hostpath.mkpath\n rescue Errno::EACCES\n raise Vagrant::Errors::SharedFolderCreateFailed,\n :path => hostpath.to_s\n end\n end\n end\n end", "def sharedfolders\n\t\t@folders = current_user.folders unless current_user.nil?\n\t\t@shared_folders = []\n\t\tSharefolder.where(:shared_owner => current_user.id).each do |sharedfolder|\n\t\t\t@shared_folders << Folder.find(sharedfolder.folder_id)\n\t\tend\n\tend", "def sync_folders(override, settings)\n synced_folders = settings.include?('synced_folders') ? settings['synced_folders'] : []\n\n # Get value of option if defined, or use a default.\n def option_value(synced_folder, option, default)\n return synced_folder.include?(option) ? synced_folder[option] : default;\n end\n\n # Set the value of an option if defined.\n def set_option(options, option, synced_folder)\n if (synced_folder.include?(option))\n options[option] = synced_folder[option]\n end\n end\n\n # Set up each sync folder\n for synced_folder in synced_folders;\n options = {\n rsync__auto: \"true\",\n rsync__exclude: option_value(synced_folder, 'excluded_paths', []),\n create: option_value(synced_folder, 'create', true),\n mount_options: option_value(synced_folder, 'mount_options', [])\n }\n set_option(options, 'type', synced_folder)\n set_option(options, 'owner', synced_folder)\n set_option(options, 'group', synced_folder)\n override.vm.synced_folder synced_folder['local_path'], synced_folder['destination'], options\n end\nend", "def mount_folders\n @env[:ui].info I18n.t(\"vagrant.actions.vm.nfs.mounting\")\n\n # Only mount the folders which have a guest path specified\n mount_folders = {}\n folders.each do |name, opts|\n if opts[:guestpath]\n mount_folders[name] = opts.dup\n end\n end\n\n @env[:machine].guest.mount_nfs(host_ip, mount_folders)\n end", "def sync_shared_items\n return unless @deployment_settings.include? 'shared'\n\n Log.info \"#@deployment_name: Synchronizing shared items...\"\n\n @deployment_settings['shared'].each do |item|\n remote_shared_item_path = \"#{@deployment_settings['deployment_path']}/shared/#{item.gsub '.example', ''}\"\n remote_cache_item_path = \"#{@deployment_settings['deployment_path']}/cache/#{item}\"\n\n unless path_exists? remote_shared_item_path\n if item.include? '.example'\n create_base_folder_for_shared item\n copy remote_cache_item_path, remote_shared_item_path\n else\n raise(Exceptions::DeployerError, \"Non-example shared item #{item} is git-tracked, and cannot be sym-linked.\") if path_exists?(remote_cache_item_path)\n create_base_folder_for_shared item\n create_shared_item remote_shared_item_path\n end\n\n chmod 'g+w', remote_shared_item_path\n end\n end\n end", "def share(box, localpath, serverpath) \n localpath = requireServerDataFolder(localpath)\n box.vm.synced_folder localpath, serverpath, type: \"nfs\", create: true\n #puts ' mount point: '+ localpath +' => '+ serverpath\nend", "def mount_shared_folder(ssh, name, guestpath); end", "def synced_folders &thunk\n (self.common_field \"synced_folders\").each &thunk\n ((self.local_field \"synced_folders\") || []).each &thunk\n end", "def configure_synced_folders(node, node_details)\n synced_folders = node_details['synced_folders']\n synced_folders && synced_folders.each do |synced_folder|\n node.vm.synced_folder synced_folder['host'], synced_folder['guest'], type: synced_folder['type']\n end\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /corges GET /corges.json
def index @corges = Corge.all end
[ "def index\n @cages = Cage.where(query_params)\n render json: @cages\n end", "def index\n @corredors = Corredor.all\n end", "def index\n @corals = Coral.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @corals }\n end\n end", "def index\n @cartridges = Cartridge.all\n\n respond_to do |format|\n format.html\n format.json { render json: @cartridges }\n end\n end", "def index\n @corrals = Corral.all\n end", "def index\n @corridas = Corrida.all\n end", "def index\n @cages = current_user.cages\n\n respond_to do |format|\n format.json { render json: @cages }\n end\n end", "def index\n @casos = Caso.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @casos }\n end\n end", "def index\n @corretoras = Corretora.all\n end", "def index\n @clues = Clue.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clues }\n end\n end", "def index\n @conges = Conge.all\n end", "def index\n # @composers = Composer.all\n @composers = @category.composers \n\n render json: @composers \n end", "def index\n @colegios = Colegio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @colegios }\n end\n end", "def index\n @coletors = Coletor.all\n end", "def cities\n self.class.get(\"/v1/cities\")\n end", "def index\n puts 'about to get all crimes'\n @crimes = Crime.all\n puts 'finished with crimes'\n @crimes.to_json\n end", "def index\n @ss_corals = SsCoral.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ss_corals }\n end\n end", "def show\n\n respond_to do |format|\n format.json { render json: @cage }\n end\n end", "def index\n @collages = Collage.order(\"created_at DESC\").all\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @collages }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /corges POST /corges.json
def create @corge = Corge.new(corge_params) respond_to do |format| if @corge.save format.html { redirect_to @corge, notice: 'Corge was successfully created.' } format.json { render :show, status: :created, location: @corge } else format.html { render :new } format.json { render json: @corge.errors, status: :unprocessable_entity } end end end
[ "def create\n @cage = Cage.new(cage_params)\n\n if @cage.save\n render json: @cage, status: :created, location: @cage\n else\n render json: @cage.errors, status: :unprocessable_entity\n end\n end", "def create\n @corrida = Corrida.new(corrida_params)\n\n respond_to do |format|\n if @corrida.save\n format.html { redirect_to @corrida, notice: 'Corrida creada satisfactoriamente.' }\n format.json { render :show, status: :created, location: @corrida }\n else\n format.html { render :new }\n format.json { render json: @corrida.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @conge = current_user.conges.build(conge_params)\n\n respond_to do |format|\n if @conge.save\n @conges = Conge.all\n format.html { redirect_to @conge, notice: 'Conge was successfully created.' }\n format.json { render :show, status: :created, location: @conge }\n format.js\n else\n format.html { render :new }\n format.json { render json: @conge.errors, status: :unprocessable_entity }\n format.js\n end\n end\n end", "def create\n @cage = current_user.cages.new(params[:cage])\n\n respond_to do |format|\n if @cage.save\n format.json { render json: @cage, status: :created, location: @cage }\n else\n format.json { render json: @cage.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @coral = Coral.new(params[:coral])\n\n respond_to do |format|\n if @coral.save\n format.html { redirect_to @coral, notice: 'Coral was successfully created.' }\n format.json { render json: @coral, status: :created, location: @coral }\n else\n format.html { render action: \"new\" }\n format.json { render json: @coral.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @corretora = Corretora.new(corretora_params)\n\n respond_to do |format|\n if @corretora.save\n format.html { redirect_to @corretora, notice: 'Corretora was successfully created.' }\n format.json { render action: 'show', status: :created, location: @corretora }\n else\n format.html { render action: 'new' }\n format.json { render json: @corretora.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @coral = Coral.new(coral_params)\n\n respond_to do |format|\n if @coral.save\n format.html { redirect_to @coral, flash: {success: 'Coral was successfully created.' } }\n format.json { render json: @coral, status: :created, location: @coral }\n else\n format.html { render action: \"new\" }\n format.json { render json: @coral.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @cargo = Cargo.new(cargo_params)\n if @cargo.save\n render json: @cargo\n else\n render json: @cargo.errors, status: :unprocessable_entity\n end\n end", "def create\n @rate_corpo = RateCorpo.new(params[:rate_corpo])\n\n respond_to do |format|\n if @rate_corpo.save\n format.html { redirect_to @rate_corpo, notice: 'Rate corpo was successfully created.' }\n format.json { render json: @rate_corpo, status: :created, location: @rate_corpo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @rate_corpo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @coletor = Coletor.new(coletor_params)\n\n respond_to do |format|\n if @coletor.save\n format.html { redirect_to @coletor, notice: 'Coletor was successfully created.' }\n format.json { render :show, status: :created, location: @coletor }\n else\n format.html { render :new }\n format.json { render json: @coletor.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @cercle = Cercle.new(cercle_params)\n\n respond_to do |format|\n if @cercle.save\n format.html { redirect_to @cercle, notice: 'Cercle was successfully created.' }\n format.json { render :show, status: :created, location: @cercle }\n else\n format.html { render :new }\n format.json { render json: @cercle.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @cerc = Cerc.new(params[:cerc])\n\n if @cerc.save\n render json: @cerc, status: :created, location: @cerc\n else\n render json: @cerc.errors, status: :unprocessable_entity\n end\n end", "def create\n @covariate = Covariate.new(covariate_params)\n\n respond_to do |format|\n if @covariate.save\n format.html { redirect_to @covariate, notice: 'Covariate was successfully created.' }\n format.json { render :show, status: :created, location: @covariate }\n else\n format.html { render :new }\n format.json { render json: @covariate.errors, status: :unprocessable_entity }\n end\n end\n end", "def createCharities\n\tcharity_list = [\"Direct Relief\", \"Catholic Medical Mission Board\", \"MAP International\", \"United Nations Foundation\", \"The Rotary Foundation of Rotary International\", \"Samaritan's Purse\", \"Institute of International Education\", \"International Rescue Committee\", \"Compassion International\", \"United States Fund for UNICEF\"]\n\tcharity_list.each do |charity|\n\t\tRestClient.post 'http://api.reimaginebanking.com/merchants?key=e0486a76005721ee6d86b140eaea2a40', { \"name\": \"#{charity}\"}.to_json, :content_type => :json, :accept => :json\n\tend\nend", "def create\n @crime = Crime.new(crime_params)\n\n if @crime.save\n render json: @crime, status: :created, location: @crime\n else\n render json: @crime.errors, status: :unprocessable_entity\n end\n end", "def create\n @correlation = Correlation.new(params[:correlation])\n\n respond_to do |format|\n if @correlation.save\n format.html { redirect_to @correlation, notice: 'Correlation was successfully created.' }\n format.json { render json: @correlation, status: :created, location: @correlation }\n else\n format.html { render action: \"new\" }\n format.json { render json: @correlation.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_tenant_circle(args = {}) \n post(\"/tenantcircles.json/\", args)\nend", "def create\n @cachorro = Cachorro.new(cachorro_params)\n\n respond_to do |format|\n if @cachorro.save\n format.html { redirect_to @cachorro, notice: 'Cachorro was successfully created.' }\n format.json { render :show, status: :created, location: @cachorro }\n else\n format.html { render :new }\n format.json { render json: @cachorro.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @correlation = Correlation.new(correlation_params)\n\n respond_to do |format|\n if @correlation.save\n format.html { redirect_to @correlation, notice: 'Correlation was successfully created.' }\n format.json { render :show, status: :created, location: @correlation }\n else\n format.html { render :new }\n format.json { render json: @correlation.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /corges/1 PATCH/PUT /corges/1.json
def update respond_to do |format| if @corge.update(corge_params) format.html { redirect_to @corge, notice: 'Corge was successfully updated.' } format.json { render :show, status: :ok, location: @corge } else format.html { render :edit } format.json { render json: @corge.errors, status: :unprocessable_entity } end end end
[ "def patch *args\n make_request :patch, *args\n end", "def update_tenant_circle(args = {}) \n put(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend", "def patch(path, params: {}, headers: {})\n request_json :patch, path, params, headers\n end", "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def update\n \n respond_to do |format|\n if @cage.update_attributes(params[:cage])\n format.json { head :no_content }\n else\n format.json { render json: @cage.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_mobile_carrier(args = {}) \n put(\"/mobile.json/#{args[:carrierId]}\", args)\nend", "def favorite\n url = Addressable::URI.new(\n scheme: 'http',\n host: 'localhost',\n port: 3000,\n path: '/contacts/2/favorite'\n ).to_s\n\n puts RestClient.patch(\n url,{}\n )\nend", "def update\n @company_id = company_params[:company_id]\n @reponse = HTTParty.put(\"https://rails-api-ipo.herokuapp.com/api/v1/companies/#{@company_id}.json\",\n :body => {:company_name => company_params[:company_name]}.to_json,\n :headers => { 'Content-Type' => 'application/json' } )\n respond_to do |format|\n format.html { redirect_to '/companies/'+(@reponse['id'].to_s), notice: 'Company was successfully created.' }\n end\n end", "def update\n respond_to do |format|\n if @corredor.update(corredor_params)\n format.html { redirect_to @corredor, notice: 'Corredor was successfully updated.' }\n format.json { render :show, status: :ok, location: @corredor }\n else\n format.html { render :edit }\n format.json { render json: @corredor.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @rogome = Rogome.find(params[:id])\n\n respond_to do |format|\n if @rogome.update_attributes(params[:rogome])\n format.html { redirect_to @rogome, notice: 'Rogome was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @rogome.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch?; request_method == \"PATCH\" end", "def update\n respond_to do |format|\n if @clients_has_conjoint.update(clients_has_conjoint_params)\n format.html { redirect_to @clients_has_conjoint, notice: 'Clients has conjoint was successfully updated.' }\n format.json { render :show, status: :ok, location: @clients_has_conjoint }\n else\n format.html { render :edit }\n format.json { render json: @clients_has_conjoint.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @cocktail.update(cocktail_params)\n if (params['cocktail']['ingredients'] != nil)\n for id in params['cocktail']['ingredients']\n @cocktail.ingredients << Ingredient.find(id)\n end\n end\n format.html {redirect_to @cocktail, notice: 'Cocktail was successfully updated.'}\n format.json {render :show, status: :ok, location: @cocktail}\n else\n format.html {render :edit}\n format.json {render json: @cocktail.errors, status: :unprocessable_entity}\n end\n end\n end", "def update\n respond_to do |format|\n if @corrida.update(corrida_params)\n format.html { redirect_to @corrida, notice: 'Corrida actualizada correctamente.' }\n format.json { render :show, status: :ok, location: @corrida }\n else\n format.html { render :edit }\n format.json { render json: @corrida.errors, status: :unprocessable_entity }\n end\n end\n end", "def rest_edit(path, options={}, &blk)\n callback = Proc.new { |*args|\n @object = yield(*args) or pass\n rest_params.each { |k, v| @object.send :\"#{k}=\", v unless k == 'id' }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object\n }\n\n # Make it work with `Backbone.emulateHTTP` on.\n put path, &callback\n post path, &callback\n end", "def update\n @coral = Coral.find(params[:id])\n\n respond_to do |format|\n if @coral.update_attributes(params[:coral])\n format.html { redirect_to @coral, notice: 'Coral was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @coral.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @clonet = Clonet.find(params[:id])\n\n respond_to do |format|\n if @clonet.update_attributes(params[:clonet])\n format.html { redirect_to @clonet, notice: 'Clonet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @clonet.errors, status: :unprocessable_entity }\n end\n end\n end", "def patch(data, options={})\n raise NotImplementedError, \"We only patchs to singular resources.\" if count > 1\n first.patch(data, options)\n end", "def update\n respond_to do |format|\n if @corretora.update(corretora_params)\n format.html { redirect_to @corretora, notice: 'Corretora was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @corretora.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes the large amount of words from enable.txt and puts them into an array.
def generate_words ret = [] File.open('enable.txt').each do |line| new_line = line # We don't care for the new line character in the game of hangman. new_line = new_line.delete("\n") ret << new_line end return ret end
[ "def word_array(sort_file)\n get_file(sort_file).downcase.gsub(/[^a-z0-9\\s\\--]/,'').split(' ')\nend", "def ReadFromFile()\n wordArray = Array.new\n File.open(\"mastermindWordList.txt\", \"r\") do |file| # Uncomment this to have a larger list (466000+ words)\n # Note: Only use if in original repository that contains words.txt\n # File.open(\"mastermindWordList.txt\", \"r\") do |file| # Comment this if previous line is uncommented\n file.each_line do |word|\n if CheckValidWord(word) == true\n wordArray.push(word.chomp.downcase)\n end\n end\n end\n return wordArray\nend", "def make_array\n @phrase_string.downcase.split(WORD_SPLIT).reject(&:empty?)\n end", "def prepare_words(filename)\n @words = []\n File.readlines(filename).each do |line|\n line.split.each {|word| @words << word}\n end\n end", "def load_words(file_name)\n words_loaded = []\n File.open(file_name).readlines.each do |line|\n words_loaded << line if line.length.between?(5, 12)\n end\n words_loaded\n end", "def loadWords\n @words = Array.new\n file = File.new(@path, \"rb\")\n while (line = file.gets) do\n @words.push(line.chomp)\n end\n file.close\n end", "def generate_word_array( text )\n return [] unless text \n text.downcase.split(\" \").map{|w| w.tr('.?!-;:\"()[]{}/','')}.uniq # load array of unique words w/ downcase conversion\n # 1) convert to downcase, 2) split into array, 3) remove punctuation, 4) remove duplicates\nend", "def load(textfile_name)\n array = []\n \n File.foreach(\"#{textfile_name}\") do |line| \n\n array_line = []\n line.each_char { |char| array_line << char }\n array << array_line\n\n end\n\n return array\n end", "def read_all\n words = []\n\n read_each do |word|\n words << word\n end\n\n words\n end", "def get_word_list\n words = \"\"\n File.open('mots.txt', 'r') do |file|\n while line = file.gets\n words += line\n end\n end\n list = words.split\n end", "def to_array\n @word.split(\" \") #or @word.chars will work too.\n end", "def words\n @words_array = @phrase.split(' ')\n end", "def valid_words(rack)\n # Load the words\n list_of_words = load_words\n array_of_valid_words = []\n # for each word check if all the letters of word are in rack\n list_of_words.each do |word|\n array_of_valid_words << word if check_word(word, rack)\n end\n array_of_valid_words\nend", "def generate_word_array\n @word = @word.chars\n end", "def word_selector array \n while @word_count.size > 0\n number = @word_count.shift\n @answer.push(@letter_array[0...number])\n @letter_array.slice!(0...number)\n number = nil\n end \n end", "def load_dict\n words = []\n File.open(\"dict.txt\").each do |line| # Hard code for now\n if line.length.between?(5, 12)\n words << line.rstrip.downcase\n end\n end\n words\n end", "def scan\n data_str = $data.join('')\n $words = $words + data_str.split\nend", "def load_words\n File.readlines(\"#{WORD_DIR}/#{language}.txt\").map(&:strip)\n end", "def read_tokens\n @tokens = []\n\n File.open(@filename) do |input_file|\n input_file.each do |line|\n line.split.each do |word|\n word = normalize(word)\n @tokens << word unless word.empty?\n end\n end\n end\n\n @tokens\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converting PDF to PNG
def convert_to_png(input_pdf, output_file) pdf = Magick::ImageList.new(input_pdf) { self.density = 200 } pdf.write(output_file) end
[ "def convert_pdf_to_png(pdfPage, pngOut)\n command = \"convert -density 600x600 -resize 800x560 -quality 90 #{pdfPage} #{pngOut}\"\n proc = subprocess.Popen(command, shell=True)\n # Wait for the process to finish\n proc.wait() \n end", "def process_pdf(image_path, new_image_path)\n MiniMagick::Tool::Convert.new do |convert|\n convert.render\n convert.density(300)\n # TODO: Check to resize image first or later\n convert.background('white')\n convert.flatten\n convert << image_path\n convert << new_image_path\n end\n end", "def convert_pdf2jpg(output_path, ratio)\n @pdf_folder = File.dirname(output_path)\n enlarged_path = output_path.gsub(/.pdf$/, \"_enlarged.pdf\")\n target = HexaPDF::Document.new\n src = HexaPDF::Document.open(output_path)\n src.pages.each do |page|\n form = target.import(page.to_form_xobject)\n width = form.box.width * ratio\n height = form.box.height * ratio\n canvas = target.pages.add([0, 0, width, height]).canvas\n canvas.xobject(form, at: [0, 0], width: width, height: height)\n end\n target.write(enlarged_path, optimize: true)\n @enlarged_pdf_base_name = File.basename(enlarged_path)\n @jpg_base_name = File.basename(output_path).gsub(/.pdf$/, \".jpg\")\n commend = \"cd #{@pdf_folder} && vips copy #{@enlarged_pdf_base_name}[n=-1] #{@jpg_base_name}\"\n system(commend)\n system(\"rm #{enlarged_path}\")\n end", "def convertPDFtoPNG(pdfList)\n pdfList.each{ |pdfFile|\n #puts convertCmd = \"convert -density #{opthash[pngDensity]} #{pdfFile} #{pdfFile.gsub(/pdf/, \"PNG\")}\"\n #`#{convertCmd}`\n }\n\n end", "def convert_to_png\n convert_cmd = \"/usr/bin/pdftoppm -png -r 300 #{@pdf_filename} #{@basename}\"\n `#{convert_cmd}`\n\n # return list of png files from conversion\n @png_files = Dir[ \"#{@basename}*.png\" ]\n\n # sort files by name and return\n @png_files.sort\n end", "def build_pdf_object(document)\n if compression_method != 0\n raise Errors::UnsupportedImageType,\n 'PNG uses an unsupported compression method'\n end\n\n if filter_method != 0\n raise Errors::UnsupportedImageType,\n 'PNG uses an unsupported filter method'\n end\n\n if interlace_method != 0\n raise Errors::UnsupportedImageType,\n 'PNG uses unsupported interlace method'\n end\n\n # some PNG types store the colour and alpha channel data together,\n # which the PDF spec doesn't like, so split it out.\n split_alpha_channel!\n\n case colors\n when 1\n color = :DeviceGray\n when 3\n color = :DeviceRGB\n else\n raise Errors::UnsupportedImageType,\n \"PNG uses an unsupported number of colors (#{png.colors})\"\n end\n\n # build the image dict\n obj = document.ref!(\n Type: :XObject,\n Subtype: :Image,\n Height: height,\n Width: width,\n BitsPerComponent: bits\n )\n\n # append the actual image data to the object as a stream\n obj << img_data\n\n obj.stream.filters << {\n FlateDecode: {\n Predictor: 15,\n Colors: colors,\n BitsPerComponent: bits,\n Columns: width\n }\n }\n\n # sort out the colours of the image\n if palette.empty?\n obj.data[:ColorSpace] = color\n else\n # embed the colour palette in the PDF as a object stream\n palette_obj = document.ref!({})\n palette_obj << palette\n\n # build the color space array for the image\n obj.data[:ColorSpace] = [\n :Indexed,\n :DeviceRGB,\n (palette.size / 3) - 1,\n palette_obj\n ]\n end\n\n # *************************************\n # add transparency data if necessary\n # *************************************\n\n # For PNG color types 0, 2 and 3, the transparency data is stored in\n # a dedicated PNG chunk, and is exposed via the transparency attribute\n # of the PNG class.\n if transparency[:grayscale]\n # Use Color Key Masking (spec section 4.8.5)\n # - An array with N elements, where N is two times the number of color\n # components.\n val = transparency[:grayscale]\n obj.data[:Mask] = [val, val]\n elsif transparency[:rgb]\n # Use Color Key Masking (spec section 4.8.5)\n # - An array with N elements, where N is two times the number of color\n # components.\n rgb = transparency[:rgb]\n obj.data[:Mask] = rgb.collect { |x| [x, x] }.flatten\n end\n\n # For PNG color types 4 and 6, the transparency data is stored as\n # a alpha channel mixed in with the main image data. The PNG class\n # seperates it out for us and makes it available via the alpha_channel\n # attribute\n if alpha_channel?\n smask_obj = document.ref!(\n Type: :XObject,\n Subtype: :Image,\n Height: height,\n Width: width,\n BitsPerComponent: bits,\n ColorSpace: :DeviceGray,\n Decode: [0, 1]\n )\n smask_obj.stream << alpha_channel\n\n smask_obj.stream.filters << {\n FlateDecode: {\n Predictor: 15,\n Colors: 1,\n BitsPerComponent: bits,\n Columns: width\n }\n }\n obj.data[:SMask] = smask_obj\n end\n\n obj\n end", "def img_to_pdf(file, outdir)\n img = Magick::Image.read(file[:path]).first\n # resize the image if its too big (e.g., taken with a digital camera)\n if img.columns > 1000 || img.rows > 1000\n # resize such that it's 1000px in width\n scale = 1\n if img.columns > img.rows\n scale = 1000.0 / img.columns\n else\n scale = 1000.0 / img.rows\n end\n img = img.resize(scale)\n end\n img.write(\"pdf:#{outdir}\") { self.quality = 75 }\n end", "def to_pdf_file(filename = nil, background_type=:png)\n Prawn::Document.generate(filename, :background => File.dirname(__FILE__) + \"/../images/#{self.banco.downcase}.#{background_type}\") do |pdf|\n self.pdf_parameters(pdf)\n end\n end", "def to_pdf_data; end", "def pdf_to_pixel_pages(pdf_data)\n Magick::ImageList.new.\n from_blob(pdf_data).\n remap { |page| page.export_pixels }\n end", "def extraxt_images_from_pdf(pdf_link, pdf_name)\n\n # get data from pdf file_name\n resp = @a.get pdf_link\n\n # write to file_name\n\n File.open(\"#{@folder_pdfs}/#{pdf_name}.pdf\", 'w') do\n |f| f.write(resp.body)\n end\n\n # delete and create folder for saving images\n # TODO: backup old\n require 'fileutils'\n FileUtils.rm_rf \"#{@folder_images}/#{pdf_name}\"\n FileUtils.mkdir_p \"#{@folder_images}/#{pdf_name}\"\n\n # extract images\n require 'docsplit'\n Docsplit.extract_images \"#{@folder_pdfs}/#{pdf_name}.pdf\",\n :size => '500x',\n :format => :png,\n :output => \"#{@folder_images}/#{pdf_name}\"\n\nend", "def convert_to_pdf(file, outdir)\n case file[:type]\n when 'image'\n img_to_pdf(file, outdir)\n when 'code'\n code_to_pdf(file, outdir)\n when 'document'\n doc_to_pdf(file, outdir)\n when 'cover'\n cover_to_pdf(file, outdir)\n end\n end", "def convert(pdf, size, format)\n basename = File.basename(pdf, File.extname(pdf))\n subfolder = @sizes.length > 1 ? size.to_s : ''\n directory = File.join(@output, subfolder)\n FileUtils.mkdir_p(directory) unless File.exists?(directory)\n out_file = File.join(directory, \"#{basename}_%05d.#{format}\")\n cmd = \"gm convert +adjoin #{MEMORY_ARGS} #{DENSITY_ARG} #{resize_arg(size)} #{quality_arg(format)} \\\"#{pdf}#{pages_arg}\\\" \\\"#{out_file}\\\" 2>&1\"\n result = `#{cmd}`.chomp\n raise ExtractionFailed, result if $? != 0\n renumber_images(out_file, format)\n end", "def thumb_image_pdf(width, height)\n if pdf?(self)\n self.convert(:jpg)\n self.resize_and_pad(width, height)\n else\n self.resize_to_fill(width, height)\n end\n end", "def create_pdf(exam)\n exam_pdf_path = Rails.root.join('public', 'uploads', 'tmp', 'pdfs', \n exam.name + '.pdf')\n create_non_existing_dirs(exam_pdf_path)\n images_array = Array.new\n exam.pages.each do |p|\n images_array.push p.image.path()\n end\n image_list = Magick::ImageList.new(*images_array)\n image_list.write(exam_pdf_path)\n\n return exam_pdf_path\n end", "def to_pdf\n to_prawn.render\n end", "def find_page_image_format(pdf_file)\n output = `pdfimages -list #{pdf_file}`\n # The result from pdfimages should look like this:\n #\n # page num type width height color comp bpc enc interp object ID x-ppi y-ppi size ratio\n # --------------------------------------------------------------------------------------------\n # 1 0 image 2480 3507 gray 1 8 jpeg no 6 0 300 300 325K 3.8%\n # 2 1 image 2480 3507 gray 1 8 jpeg no 11 0 300 300 141K 1.7%\n # 3 2 image 2480 3507 gray 1 8 jpeg no 16 0 300 300 706K 8.3%\n #\n # So the image encoding should be in column [9] (where the page number is in column [0]).\n #\n # Run through the pages and ensure that they are all the same type.\n image_type = nil\n output.each_line() {\n |line|\n next if line =~ /^----/ || line =~ /^page/\n data = line.split(/\\s+/)\n image_type ||= data[9]\n image_type = \"inconsistent\" if image_type != data[9]\n }\n return image_type\nend", "def convertSVGtoImageOrPdf(svgString, exportFileName, exportFileFormat)\n \tcompleteFileName = SAVE_PATH+exportFileName+\".\"+exportFileFormat\n \t\n \tif exportFileFormat != \"svg\"\n\t \timg = Magick::Image.from_blob(svgString) {\n\t\t self.format = \"SVG\"\n\t\t}\n\t\tbegin\n\t\t\timg[0].write(completeFileName)\n\t\trescue\n\t\t\traiseError(\"403\") # raising error if image cannot be created\t\n\t\tend\t\n\telse\n\t\tbegin\n\t\t\tfile = File.open(completeFileName, \"w\")\n\t\t\tfile.write(svgString) \n\t\t\tfile.close()\n\t\trescue\n\t\t\traiseError(\"403\") # raising error if file cannot be created\t\n\t\tend\n\tend\n\tsendFileToDownload(completeFileName)\n\t\n end", "def build_pdf_object(document)\n color_space =\n case channels\n when 1\n :DeviceGray\n when 3\n :DeviceRGB\n when 4\n :DeviceCMYK\n else\n raise ArgumentError, 'JPG uses an unsupported number of channels'\n end\n\n obj = document.ref!(\n Type: :XObject,\n Subtype: :Image,\n ColorSpace: color_space,\n BitsPerComponent: bits,\n Width: width,\n Height: height\n )\n\n # add extra decode params for CMYK images. By swapping the\n # min and max values from the default, we invert the colours. See\n # section 4.8.4 of the spec.\n if color_space == :DeviceCMYK\n obj.data[:Decode] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]\n end\n\n obj.stream << @data\n obj.stream.filters << :DCTDecode\n obj\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adding QR and label to the PNG
def embed_info(input_file, qr, label, x_coord, y_coord) img_template = ChunkyPNG::Image.from_file(input_file) img_label = ChunkyPNG::Image.from_file(label) img_template.compose!(qr, x_coord, y_coord) img_template.compose!(img_label, x_coord + 255, y_coord) rename_file = input_file[5..-1] img_template.save("./out-pdf" + rename_file.gsub(".png", "-e.png"), :fast_rgba) end
[ "def customQRcode(inputStr) \n qrcode = RQRCode::QRCode.new(inputStr).as_png(fill: 'white', color: 'black', file: 'abc.png')\n avatar = ChunkyPNG::Image.from_file('abc.png')\n\n # alogo.png being the logo file\n badge = ChunkyPNG::Image.from_file('alogo.png')\n\n print(\"height of backgound:\")\n print(avatar.height)\n print(\"height of logo:\")\n print(badge.height)\n\n #Alpha Blending\n avatar.compose!(badge, avatar.height/2 - badge.height/2, avatar.height/2 - badge.height/2)\n avatar.save('composited.png', :fast_rgba)\nend", "def print_my_qrcode\n require 'rqrcode'\n\n qrcode = RQRCode::QRCode.new(\"http://api.paiemequick.com/u/p/#{self.authentication_token}/\")\n\n # NOTE: showing with default options specified explicitly\n svg = qrcode.as_svg(\n offset: 5,\n color: '000',\n shape_rendering: 'crispEdges',\n module_size: 6,\n standalone: true\n )\n\n # save SVG file to folder\n File.open(\"app/assets/images/#{self.phone}\", \"w\") do |line|\n line.puts svg\n end\n end", "def write_youtube_qr\n if $youtube\n qr = RQRCode::QRCode.new( 'my string to generate', :size => 4, :level => :h )\n png = qr.to_img # returns an instance of ChunkyPNG\n png.resize(90, 90).save(\"#{$title}_qr.png\")\n end\nend", "def generate_qr(qrcode)\n generate_qr = Barby::QrCode.new(qrcode, level: :q)\n base64_output = Base64.encode64(generate_qr.to_png({ xdim: 5 }))\n\t\"data:image/png;base64,#{base64_output}\"\nend", "def qr_code\n @patient = Patient.find(params[:id])\n @record_url = vacc_rec_patient_url(@patient)\n @qr = RQRCode::QRCode.new(@record_url, size: 10, level: :h)\n @png = @qr.as_png(\n bit_depth: 1,\n border_modules: 4,\n color_mode: ChunkyPNG::COLOR_GRAYSCALE,\n color: 'black',\n file: nil,\n fill: 'white',\n module_px_size: 6,\n resize_exactly_to: false,\n resize_gte_to: false,\n size: 400\n )\n end", "def qr_code_png\n data.qr_code_png\n end", "def barcode(text = 'http://hipscan.com', sz = 8, div = 'hipscan-qrcode')\r\n text = 'http://hipscan.com' if text.blank?\r\n capture_haml do\r\n haml_tag :div, :class => 'qr', :title => text do\r\n haml_concat raw qrcode(text, sz, 6, div)\r\n end\r\n end\r\n end", "def render_qr_code(qr_code, options = {})\n dot_w, dot_h = qrcode_dot_size(qr_code, options)\n if options[:at]\n pos_x, pos_y = options[:at]\n else\n pos_x, pos_y = qrcode_position(qr_code.modules.first.length * dot_w, qr_code.modules.length * dot_h, options)\n end\n\n qr_code.modules.each do |col|\n temp_x = pos_x\n col.each do |row|\n if row\n fill { rectangle([temp_x, pos_y], dot_w, dot_h) }\n end\n temp_x += dot_w\n end\n pos_y -= dot_h\n end\n end", "def render_qr_code(qr_code, *options)\n opt = options.extract_options!\n dot = opt[:dot] || DEFAULT_DOTSIZE\n extent= opt[:extent] || (8+qr_code.modules.length) * dot\n stroke = (opt.has_key?(:stroke) && opt[:stroke].nil?) || opt[:stroke]\n pos = opt[:pos] ||[0, cursor]\n\n align = opt[:align]\n case(align)\n when :center\n pos[0] = (@bounding_box.right / 2) - (extent / 2) \n when :right\n pos[0] = @bounding_box.right - extent\n when :left\n pos[0] = 0;\n end\n\n bounding_box pos, :width => extent, :height => extent do |box|\n if stroke\n stroke_bounds\n end\n\n pos_y = 4*dot +qr_code.modules.length * dot\n\n qr_code.modules.each_index do |row|\n pos_x = 4*dot\n dark_col = 0\n qr_code.modules.each_index do |col|\n move_to [pos_x, pos_y]\n if qr_code.dark?(row, col)\n dark_col = dark_col+1\n else\n if (dark_col>0)\n fill { rectangle([pos_x - dark_col*dot, pos_y], dot*dark_col, dot) }\n dark_col = 0\n end\n end\n pos_x = pos_x + dot\n end\n if (dark_col > 0)\n fill { rectangle([pos_x - dark_col*dot, pos_y], dot*dark_col, dot) }\n end\n pos_y = pos_y - dot\n end\n end\n end", "def generateQRCode\n id = params[:id]\n\n #on recherche l'enregistrement correspondant\n query = Qrmodel.find(id)\n query_string = query.to_s\n\n #on commence le processus de rendu du qrcode\n qrcode = RQRCode::QRCode.new(query_string)\n qrmodel.qrcode.attach(\n qrcode.as_png(\n resize_gte_to: false,\n resize_exactly_to: false,\n fill: 'white',\n color: 'black',\n size: 360,\n border_modules: 4,\n module_px_size: 6,\n file: Rails.root.join(\"tmp/#{SecureRandom.hex(2).parameterize}.png\")\n )\n )\n\n end", "def set_label(data,data_description,serie_name,value_name,caption,r=210,g=210,b=210)\n data_description = validate_data_description(\"set_label\",data_description)\n validate_data(\"set_label\",data)\n shadow_factor = 100\n c_label =allocate_color(@picture,r,g,b)\n c_shadow =allocate_color(@picture,r-shadow_factor,g-shadow_factor,b-shadow_factor)\n c_text_color =allocate_color(@picture,0,0,0)\n cp = 0\n found = false\n numerical_value = 0\n data.each do |key|\n if key[data_description[\"position\"]].to_s == value_name.to_s\n numerical_value = key[serie_name]\n found = true\n end\n cp +=1 if !found\n end\n\n xpos = @g_area_x1 + @g_area_x_offset + ( @division_width * cp ) + 2\n ypos = @g_area_y2 - (numerical_value - @vmin) *@division_ratio\n position = image_ftb_box(@font_size,0,@font_name,caption)\n text_height = position[3] - position[5]\n text_width = position[2]-position[0] + 2\n text_offset = (text_height/2).floor\n # Shadow\n poly = [xpos+1,ypos+1,xpos + 9,ypos - text_offset,xpos + 8,ypos + text_offset + 2]\n image_filled_polygon(@picture,poly,r-shadow_factor,g-shadow_factor,b-shadow_factor,3)\n draw_line(xpos,ypos+1,xpos + 9,ypos - text_offset - 0.2,r-shadow_factor,g-shadow_factor,b-shadow_factor)\n draw_line(xpos,ypos+1,xpos + 9,ypos + text_offset + 2.2,r-shadow_factor,g-shadow_factor,b-shadow_factor)\n draw_filled_rectangle(xpos + 9,ypos - text_offset-0.2,xpos + 13 + text_width,ypos + text_offset + 2.2,r-shadow_factor,g-shadow_factor,b-shadow_factor)\n\n #Label background\n poly = [xpos,ypos,xpos + 8,ypos - text_offset - 1,xpos + 8,ypos + text_offset + 1]\n image_filled_polygon(@picture,poly,r,g,b,3)\n draw_line(xpos-1,ypos,xpos + 8,ypos - text_offset - 1.2,r,g,b)\n draw_line(xpos-1,ypos,xpos + 8,ypos + text_offset + 1.2,r,g,b)\n draw_filled_rectangle(xpos + 8,ypos - text_offset - 1.2,xpos + 12 + text_width,ypos + text_offset + 1.2,r,g,b)\n\n image_ttf_text(@picture,@font_size,0,xpos + 10,ypos + text_offset,c_text_color,@font_name,caption)\n end", "def draw_barcode(x,y,r,barcode_kind,narrow_bar_width,wide_bar_width,h,print_code,data) \n @output << \"B#{x},#{y},#{r},#{barcode_kind},#{narrow_bar_width},#{wide_bar_width},#{h},#{print_code ? 'B' : 'N'},\\\"#{data}\\\"\\n\"\n end", "def svg text, options ={}\n size = options[:size] || QRCoder.minimum_qr_size_from_string(text)\n level = options[:level] || :h\n qrcode = RQRCode::QRCode.new(text, :size => size, :level => level)\n QRCoder::Renderers::SVG::render(qrcode, options)\n end", "def generate()\n @qrcode = @qr_generator.new(@url)\n @png = @qrcode.as_png(\n size: @size,\n border_modules: DEFAULT_BORDER_MODULES\n )\n end", "def qr\n require 'rqrcode'\n str = params[:str] || \"\"\n\n qr = RQRCode::QRCode.new(str)\n\n qr_img_stream = qr.as_png(\n border_modules: 2,\n color: \"24292e\"\n ).to_s\n\n send_data(qr_img_stream, type: 'image/png', disposition: 'inline')\n end", "def qrcode string, *args\n options = args.extract_options!\n level = (options[:level] || :h).to_sym\n size = options[:size] || 4\n qr = RQRCode::QRCode.new(string, :size => size, :level => level)\n render \"qrcode\" , :qr => qr\n end", "def to_qr( size=120 )\n RQRCode::QRCode.new( message )\n .as_png(\n resize_gte_to: false,\n resize_exactly_to: false,\n fill: 'white',\n color: 'black',\n size: size,\n border_modules: 2,\n module_px_size: 4\n ) \n end", "def set_label(data,data_description,serie_name,value_name,caption,r=210,g=210,b=210)\n\t\tdata_description = self.validate_data_description(\"set_label\",data_description)\n\t\tself.validate_data(\"set_label\",data)\n\t\tshadow_factor = 100\n\t\tc_label =allocate_color(@picture,r,g,b)\n\t\tc_shadow =allocate_color(@picture,r-shadow_factor,g-shadow_factor,b-shadow_factor)\n\t\tc_text_color =allocate_color(@picture,0,0,0)\n\t\tcp = 0\n\t\tfound = false\n\t\tnumerical_value = 0\n\t\tdata.each do |key|\n\t\t\tif key[data_description[\"position\"]].to_s == value_name.to_s\n\t\t\t\tnumerical_value = key[serie_name]\n\t\t\t\tfound = true\n\t\t\tend\n\t\t\tcp +=1 if !found\n\t\tend\n\n\t\txpos = @g_area_x1 + @g_area_x_offset + ( @division_width * cp ) + 2\n\t\typos = @g_area_y2 - (numerical_value - @vmin) *@division_ratio\n\t\tposition = image_ftb_box(@font_size,0,@font_name,caption)\n\t\ttext_height = position[3] - position[5]\n\t\ttext_width = position[2]-position[0] + 2\n\t\ttext_offset = (text_height/2).floor\n\t\t# Shadow\n\t\tpoly = [xpos+1,ypos+1,xpos + 9,ypos - text_offset,xpos + 8,ypos + text_offset + 2]\n\t\timage_filled_polygon(@picture,poly,r-shadow_factor,g-shadow_factor,b-shadow_factor,3)\n\t\tself.draw_line(xpos,ypos+1,xpos + 9,ypos - text_offset - 0.2,r-shadow_factor,g-shadow_factor,b-shadow_factor)\n\t\tself.draw_line(xpos,ypos+1,xpos + 9,ypos + text_offset + 2.2,r-shadow_factor,g-shadow_factor,b-shadow_factor)\n\t\tself.draw_filled_rectangle(xpos + 9,ypos - text_offset-0.2,xpos + 13 + text_width,ypos + text_offset + 2.2,r-shadow_factor,g-shadow_factor,b-shadow_factor)\n\n\t\t#Label background\n\t\tpoly = [xpos,ypos,xpos + 8,ypos - text_offset - 1,xpos + 8,ypos + text_offset + 1]\n\t\timage_filled_polygon(@picture,poly,r,g,b,3)\n\t\tself.draw_line(xpos-1,ypos,xpos + 8,ypos - text_offset - 1.2,r,g,b)\n\t\tself.draw_line(xpos-1,ypos,xpos + 8,ypos + text_offset + 1.2,r,g,b)\n\t\tself.draw_filled_rectangle(xpos + 8,ypos - text_offset - 1.2,xpos + 12 + text_width,ypos + text_offset + 1.2,r,g,b)\n\n\t\timage_ttf_text(@picture,@font_size,0,xpos + 10,ypos + text_offset,c_text_color,@font_name,caption)\n\tend", "def label_image_base64\n value_of(:shipment_results, :package_results, :shipping_label, :graphic_image)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method can be used to manually link an asset to an acts_as_asset_box object in tests or otherwise. The object needs to be saved afterward so that the Effective::Attachment is saved (and the association is saved). For example: class User < ActiveRecord::Base acts_as_asset_box :avatar end asset = Effective::Asset.new(...) user = User.new user.add_to_asset_box(:avatar, asset) user.save
def add_to_asset_box(box, *items) box = (box.present? ? box.to_s : 'assets') boxes = box.pluralize items = [items].flatten.compact if items.present? && items.any? { |obj| !obj.kind_of?(Effective::Asset) } raise ArgumentError.new('add_to_asset_box expects one or more Effective::Assets, or an Array of Effective::Assets') end if box == boxes # If we're adding to a pluralized box, we want to add our attachment onto the end pos = attachments.select { |attachment| attachment.box == boxes }.last.try(:position).to_i + 1 else # If we're adding to a singular box, we want our attachments to be on the front pos = attachments.to_a.find { |attachment| attachment.box == boxes }.try(:position).to_i # Push all the attachments forward attachments.each { |att| att.position = (att.position + items.length) if att.box == boxes } end # Build the attachments items.each_with_index do |item, x| attachment = self.attachments.build(:position => (pos+x), :box => boxes) attachment.attachable = self attachment.asset = item end attachments.to_a.sort_by! { |attachment| attachment.position } true end
[ "def add_asset\n asset = Asset.find_by_object_key(params[:asset])\n if asset.nil?\n notify_user(:alert, \"Unable to add asset. Record not found!\")\n return\n else\n @activity_line_item.assets << asset\n notify_user(:notice, \"Asset was successfully added to the ALI\")\n end\n redirect_back(fallback_location: root_path)\n end", "def add_asset src\n if src && !src.empty?\n e = {}.merge(src).delete_if {|k, v| v == nil || v.empty? }\n id = Digest::MD5.hexdigest(src[:url])\n if src[:type] == \"asset\"\n @yml[:assets][id] = e\n else\n @yml[:external_links][id] = e\n end\n end\n end", "def associate_file_asset_with_container(file_asset=nil, container_id=nil)\n if container_id.nil?\n container_id = params[:asset_id]\n end\n if file_asset.nil?\n file_asset = @file_asset\n end\n file_asset.add_relationship(:is_part_of, container_id)\n file_asset.save\n end", "def link_asset(path)\n asset = depend_on_asset(path)\n @links << asset.uri\n asset\n end", "def click_my_asset_link(driver, asset)\n logger.info \"Clicking thumbnail for My Asset ID #{asset.id}\"\n wait_for_update_and_click_js link_element(xpath: \"//h3[contains(.,'My Assets')]/../following-sibling::div/ul//a[contains(@href,'_id=#{asset.id}&')]\")\n switch_to_canvas_iframe driver\n end", "def store_asset(asset, unloaded); end", "def save_asset(asset)\n token = get_default_token(asset.drop)\n uri = URI::HTTP.build({:path => asset_path(asset.drop, asset)})\n form = create_form({ :token => token, \n :title => asset.title,\n :url => asset.url,\n :description => asset.description,\n :contents => asset.contents })\n req = Net::HTTP::Put.new(uri.request_uri, DEFAULT_HEADER)\n req.set_form_data(form)\n complete_request(req) { |body| asset = Mapper.map_assets(asset.drop, body)}\n asset\n end", "def add_asset(asset)\n @al_asset_group.addAsset(asset.al_asset)\n end", "def attach_asset\n @asset = Asset.find(params[:asset])\n @page = Page.find(params[:page])\n @page.assets << @asset unless @page.assets.include?(@asset)\n clear_model_cache\n render :partial => 'page_assets', :locals => { :page => @page }\n # render :update do |page|\n # page[:attachments].replace_html \"#{render :partial => 'page_assets', :locals => {:page => @page}}\"\n # end\n end", "def click_add_new_asset(asset)\n click_close_modal_button if close_modal_button?\n click_cancel_button if cancel_asset_button?\n if asset.type == 'File'\n wait_for_update_and_click_js add_asset_button_element unless upload_new_button?\n wait_for_update_and_click_js upload_new_button_element\n else\n wait_for_update_and_click_js add_asset_button_element unless add_link_button?\n wait_for_update_and_click_js add_link_button_element\n end\n end", "def before_create\n if self.asset.nil? && self.viewable\n self.asset = self.viewable.asset if self.viewable.respond_to? :asset\n end\n end", "def create_asset\n \t\timage_params = params[:blog_asset] || {}\n \t\t@image = BlogAsset.new(image_params)\n \t\t@image.blog_post_id = image_params[:blog_post_id] # Can't mass-assign attributes of attachment_fu, so we'll set it manually here\n \t\t@image.save!\n \t\trender :text => @image.public_filename\n \tend", "def create_asset\n\t\timage_params = params[:blog_asset] || {}\n\t\t@image = BlogAsset.new(image_params)\n\t\t@image.blog_post_id = image_params[:blog_post_id] # Can't mass-assign attributes of attachment_fu, so we'll set it manually here\n\t\t@image.save!\n\t\trender :text => @image.public_filename\n\tend", "def save\n Dropio::Resource.client.update_asset(self)\n end", "def link_asset(path); end", "def save\n Dropio::Client.instance.save_asset(self)\n end", "def click_asset_link_by_id(asset)\n logger.info \"Clicking thumbnail for asset ID #{asset.id}\"\n wait_for_update_and_click link_element(xpath: \"//a[contains(@href,'/assetlibrary/#{asset.id}')]\")\n end", "def upload_attachment(safebox, attachment)\n if attachment.guid.nil?\n result = @json_client.upload_file(safebox.upload_url, attachment.file_path || attachment.file, attachment.content_type, attachment.filename)\n attachment.guid = result[\"temporary_document\"][\"document_guid\"]\n end\n attachment\n end", "def create\n # Here we initialize an empty placeholder Asset, so we can reserve the ID\n @asset = Effective::Asset.new(user_id: ((current_user.try(:id) || 1) rescue 1), upload_file: 'placeholder')\n @asset.extra = params[:extra] if params[:extra].kind_of?(Hash)\n\n EffectiveAssets.authorized?(self, :create, @asset)\n\n begin\n @asset.save!\n render(body: {:id => @asset.id, :s3_key => asset_s3_key(@asset)}.to_json, :status => 200)\n rescue => e\n render(:body => e.message, :status => 500)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure there are conversation member objects for all users, if there is a converation associated with the availability
def ensure_conversation_members convo = Conversation.where(availability_id: id).first if convo convo.conversation_members.create(user: user, admin: admin) if convo.conversation_members.where(user: user).first.nil? end end
[ "def match_availability_message_to_convo\n if conversation_id.nil? && !availability_id.nil?\n conversation = Conversation.where(availability_id: availability_id).first\n if conversation.nil?\n conversation = Conversation.create(availability_id: availability_id, name: \"Teaching #{availability.start_time.strftime('%H:%M %d/%m/%Y')}\")\n availability.availability_users.each do |join|\n conversation.conversation_members.create!(user: join.user, admin: join.admin)\n end\n end\n self.conversation = conversation\n end\n end", "def has_user?(user)\r\n conversation_members.where(:user_id => user.id).any?\r\n end", "def all_users_ready?\n nr_members = members.size\n nr_ready = RoomUser.where(room_id: id, ready: true).count\n nr_members > 0 && nr_ready == nr_members\n end", "def is_in_conversation?(_user_id)\n conversation_members.where(user_id: _user_id).any?\n end", "def check_for_chat_room_member\n unless @chat_room.participants.include?(@whoami)\n flash[:notice] = \"You are not a member of this chat room\"\n redirect_to(chat_rooms_url)\n end\n end", "def check_conversation_member\n head :forbidden unless @member.id == current_user&.id\n end", "def engaged_users\n self.users.select { |u| u.ideas.count > 0 || u.comments.count > 0 || u.votes.count > 0 || u.support_messages.count > 0 }\n end", "def still_valid?\n return false if self.reply_type == 'conversation'\n participation_request = ParticipationRequest.find self.participation_request_id\n\n return false if participation_request.state != 'pending'\n return false if participation_request.date < Time.current\n\n !used\n end", "def create_missing_participants!\n members = group\n .members\n .joins(:person)\n members = members.where('people.id NOT IN (?)', self.people.ids) unless participants.empty?\n\n members.each do |m|\n Participant.create!(\n activity: self,\n member: m,\n person: m.person\n )\n end\n end", "def conversation_with?(user)\n if Conversation.between(self.id, user.id).exists?\n return true\n else\n return false\n end\n end", "def has_active_user?(user)\r\n conversation_members.where(\r\n :user_id => user.id,\r\n :parted => true\r\n ).any?\r\n end", "def check_no_associations\n unless self.friendships.empty? and self.mutual_friendships.empty? and self.activities.empty? and self.profile.nil?\n return false\n end\n end", "def ensure_personas_belong_to_users\n # Check to-side\n unless self.to_persona_ids.reject {|x| User.find(self.to_id).personas.find(x).nil? == false}.empty?\n errors.add(:base, I18n.t('connection.incongruent-user-persona'))\n return false\n end\n # Check from-side\n unless self.from_persona_ids.reject {|y| User.find(self.from_id).personas.find(y).nil? == false}.empty?\n errors.add(:base, I18n.t('connection.incongruent-user-persona'))\n return false\n end\n end", "def is_club_member(user)\n user && (self.active_club_members.find(:all, :conditions => [\"user_id = ?\",user.id]).length > 0) \n end", "def cannot_send_multiple_invitations\n\t\terrors.add :user_id, \"has already been invited\" unless Membership.where(started_at: nil, user_id: self.user_id, team_id: self.team_id).empty?\n\tend", "def check_remove_conversation\n Rails.logger.info \"----Removed conversation member: #{self.inspect}=======aso: #{destroyed_by_association}\"\n conversation.destroy! if !conversation.is_group_conversation? && destroyed_by_association.try(:active_record).try(:name) != 'Conversation' # if conversation is not being deleted\n end", "def adjust_user_invite_status\n if self.creator.respond_to?(:out_of_invites)\n self.creator.out_of_invites = (self.creator.invitations.unredeemed.count < 1)\n self.creator.save(:validate => false)\n end\n end", "def validate_membership\n errors.add(\"#{self.sadhak_profile.syid}\", \"is not active member to forum #{self.sy_club.name}.\") unless self.sy_club_member.approve?\n errors.empty?\n end", "def has_messages?\n # if the user has sent any or received any, then we return true\n 0 < Message.count_by_sql(%{\n SELECT COUNT(*)\n FROM messages m\n LEFT JOIN assignment_participations a_p\n ON a_p.id = m.assignment_participation_id\n LEFT JOIN assignment_submissions a_s\n ON a_s.id = a_p.assignment_submission_id\n WHERE (a_s.user_id = #{@user.id} OR a_p.user_id = #{@user.id}) AND a_s.assignment_id = #{@assignment.id}\n }) #, @user.id, @user.id, @assignment.id])\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Truncated project identifier (shortname & part of the description)
def project_identifier(p, length=26) truncate([p.shortname, p.description].join(" - "), :length => length) end
[ "def project_name\n project_tag_id = 'Project : '\n content_tag = AdministrativeTags.for(identifier: cocina_obj.externalIdentifier).select { |tag| tag.include?(project_tag_id) }\n content_tag.empty? ? '' : content_tag[0].gsub(project_tag_id, '').strip\n end", "def identifier\n [project.key, sequence].join('-')\n end", "def project_name\n\t\tcompany + project_type.to_s + client + store_num\n\tend", "def clean_project_name name\n\t\t name.\n\t\t\t# replace \"_\" by \"-\"\n\t\t\tgsub('_', '-')\n\t\tname\n\tend", "def string_project_title\n return self.project.title if self.project\n end", "def issue_project_key(issue_key)\n issue_key.split('-').length > 1 ? issue_key : [current_project, issue_key].join('-')\n end", "def long_name\n long.to_s.sub(/^(--.+?)(\\s+|\\=|\\[).*$/, \"\\\\1\")\n end", "def unique_name\n \"#{project.name} / #{name}\"\n end", "def project_id\n config_filename('.project_id', 'the Pivotal tracker project id')\n end", "def project_id; end", "def project_name\n workspace_name.split('.').first\n end", "def project_name\n name = self.plan.template.title\n name += \" - #{self.plan.title}\" if self.plan.template.phases.count > 1\n name\n end", "def project_name\n @project_name\n end", "def project_name\n \"$PROJECT_NAME v.$PROJECT_VERSION\"\n end", "def name_with_project \r\n if !!self.project \r\n \"#{self.name} - #{self.project.name}\"\r\n else\r\n \"#{self.name} - (unassigned)\" \r\n end \r\n end", "def full_project_name\n self.login\n \n @jira.getProject(self.project).name \n end", "def long_name\n n = name\n n += \" (\" if version.present? || language.present?\n n += \"rev#{ version }\" if version.present?\n n += \"-\" if version.present? && language.present?\n n += \"#{ language.upcase }\" if language.present?\n n += \")\" if version.present? || language.present?\n n\n end", "def project_number\n segments = @audience.split \"/\"\n idx = segments.index \"projects\"\n return nil if idx.nil? || idx + 1 == segments.size\n segments[idx + 1]\n end", "def get_project_name\n project_id = params[:project_id]\n name_from_repository = payload.fetch(\"repository\", {}).fetch(\"name\", nil)\n project_id || name_from_repository\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display an edit link if the entry belongs to the logged in user
def display_edit_link(entry) if entry.user == current_user link_to (image_tag 'edit.png'), edit_entry_path(entry) end end
[ "def show_edit_entry_link?\n user_signed_in? && @document.present? && (entry = @document.model_object).present? && can?(:edit, entry)\n end", "def edit\n return unless access?(:update, @author)\n end", "def user_edit\n if (user_signed_in? && (current_user.id == @book.user_id))\n @can_edit = true\n else \n @can_edit = false\n end \n end", "def edit?\n @blog.user == current_user\n end", "def edit\n @user = @current_user\n @page_title = \"Edit User Profile\"\n @editing = true\n end", "def link_edit(object)\n if admin? && object && object.id\n link_to content_tag(:span, \"Edit\"), edit_url(object), :style => \"float: left; margin-top: 20px; width: 100px;\", :class => \"button\"\n end\n end", "def editU\n @user = current_user\n end", "def edit\n\t\t@blog = Blog.find(params[:id])\n\n \t\tif current_user.id == @blog.user_id\n\n \t\telse \n \t\t\tflash[:notice] = \"Access Denied\"\n \t\t\tredirect_to root_path\n\n \t\tend\n\tend", "def show_edit_link?(quote)\n # Make sure there user property isn't nil to prevent anonymous users\n # from editing anonymous quotes, that was a really stupid bug\n if (quote.user != nil) and (quote.user == session.user)\n true\n else\n false\n end\n end", "def can_edit?(user)\n user && self.creator_id == user.id\n end", "def display_edit_button_for_user(user)\n if user.type.eql?'InstituteAdmin'\n link_to \"Edit\",edit_institute_admin_path(user), :class => \"button icon edit\"\n elsif user.type.eql?'CenterAdmin'\n link_to \"Edit\",edit_center_admin_path(user), :class => \"button icon edit\"\n else\n display_link(\"Edit\",edit_user_path(user),:update,User,\"button icon edit\")\n end\n end", "def edit\n # if @submission.user == current_user\n @submission = Submission.find(params[:id])\n # end\n\n end", "def can_edit?(user)\n user && id == user.profile_id\n end", "def authorized_to_edit?(post)\n post.user == current_user\n end", "def authorized_to_edit?(recipe)\n current_user == recipe.user\n end", "def edit\n authorize @project_link\n # render edit.html.haml\n end", "def edit?\n user and event.owner?(user)\n end", "def edit\n @author = find_author\n end", "def edit\n if @user.id != @application.user.id\n redirect_to application_path(@application), notice: \"Only the applicant can edit their application.\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /time_entries/1 DELETE /time_entries/1.json
def destroy @time_entry = TimeEntry.with_deleted.find(params[:id]) @time_entry.destroy respond_to do |format| format.html { redirect_to time_entries_url } format.json { head :no_content } end end
[ "def destroy\n @time_entry = TimeEntry.find(params[:id])\n @time_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to time_entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @time_entry = TimeEntry.find(params[:id])\n @time_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to time_entries_url }\n format.json { head :ok }\n end\n end", "def destroy\n @time_entry = TimeEntry.find(params[:id])\n @time_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to home_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @time_entry = TimeEntry.find(params[:id])\n @time_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(time_entries_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @timetable_entry.destroy\n respond_to do |format|\n format.html { redirect_to timetable_entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @big_time_entry.destroy\n respond_to do |format|\n format.html { redirect_to big_time_entries_url, notice: 'Big time entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @timesheet_entry = TimesheetEntry.find(params[:id])\n @timesheet_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to timesheet_entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @time_table_entry = TimeTableEntry.find(params[:id])\n @time_table_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(time_table_entries_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @archived_time_entry.destroy\n respond_to do |format|\n format.html { redirect_to archived_time_entries_url, notice: 'Archived time entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @daytime = Daytime.find(params[:id])\n @daytime.destroy\n\n respond_to do |format|\n format.html { redirect_to daytimes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @time_day.destroy\n respond_to do |format|\n format.html { redirect_to time_days_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @task_time = @task.task_times.find(params[:id])\n @task_time.destroy\n\n respond_to do |format|\n format.html { redirect_to task_times_url(@task) }\n format.json { head :no_content }\n end\n end", "def destroy\n @time_sheet_entry = TimeSheetEntry.find(params[:id])\n @time_sheet_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to time_sheet_entries_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @time_getter.destroy\n respond_to do |format|\n format.html { redirect_to time_getters_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @titletime.destroy\n respond_to do |format|\n format.html { redirect_to titletimes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @time_log = TimeLog.find(params[:id])\n @time_log.destroy\n\n respond_to do |format|\n format.html { redirect_to time_logs_url }\n format.json { head :ok }\n end\n end", "def destroy\n @event_time = EventTime.find(params[:id])\n @event_time.destroy\n\n respond_to do |format|\n format.html { redirect_to event_times_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @time_item.destroy\n respond_to do |format|\n format.html { redirect_to @time_item.timeline }\n format.json { head :no_content }\n end\n end", "def destroy\n @food_time = FoodTime.find(params[:id])\n @food_time.destroy\n\n respond_to do |format|\n format.html { redirect_to food_times_url }\n format.json { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs a string given in input as Ruby code or buffers it if the command is incomplete Test against level or input to check if the command has been executed
def run str @input ||= '' @level += str.scan(LEVEL_UP).length @level -= str.scan(/(^|\s)end($|\s)/).length # Will probably fail with a character chain @input += str + "\n" if @level <= 0 tmp = input reset eval tmp, context end end
[ "def pre_cmd(input); end", "def parseRunCommands\n didRun = false\n\n Dir.chdir($outputDir) {\n File.open($benchmarkDirectory + $benchmark) {\n | inp |\n inp.each_line {\n | line |\n begin\n doesMatch = line =~ /^\\/\\/@/\n rescue Exception => e\n # Apparently this happens in the case of some UTF8 stuff in some files, where\n # Ruby tries to be strict and throw exceptions.\n next\n end\n next unless doesMatch\n eval $~.post_match\n didRun = true\n }\n }\n }\n\n didRun\nend", "def run_rubylex\n\t\t\tline = \"\" \n\t\t\tcmd = \"\" \n\t\t\t@lexer = RubyLex.new \n\t\t\t@lexer.set_input(STDIN) do \n\t\t\t\t@indent_level = @lexer.indent\n\t\t\t\t@quoted = @lexer.quoted\n\t\t\t\tbegin\n\t\t\t\t\tcmd = Readline.readline(prompt())\n\t\t\t\t\tif cmd.nil?\n\t\t\t\t\t\t\"\"\n\t\t\t\t\telse\n\t\t\t\t\t\tReadline::HISTORY.push cmd if cmd != ''\n\t\t\t\t\t\texpand(cmd) + \"\\n\"\n\t\t\t\t\tend\n\t\t\t\trescue ::Interrupt => e\n\t\t\t\t\tputs\n\t\t\t\t\t''\n\t\t\t\tend\n\t\t\tend \n\n\t\t\t@lexer.each_top_level_statement do |cmd, i| \n\t\t\t\tbreak if cmd.chop == 'exit' \n\t\t\t\texecute cmd \n\t\t\tend \n\n\t\t\tfinish\n\t\tend", "def process_command(inp)\n @commands.each do |cmd|\n if inp =~ cmd.command_regexp\n begin\n output = cmd.execute self, $~\n puts output if output\n rescue StandardError => e\n handle_exception e\n end\n break\n end\n end\n end", "def execute(str)\n @parser.parse(str) do |to_call|\n if @dispatch.trace\n puts to_call\n c = ImmediateRead.new.getch\n throw :reset unless c == \"\\n\"\n puts\n end\n @dispatch.dispatch(to_call)\n end\n end", "def handle_command(code, activity, line_num, file_read)\n case code\n when 1\n doing_let(activity, line_num, file_read)\n when 2\n doing_print(activity, line_num, file_read)\n when 3\n doing_evaluate(activity, line_num, file_read)\n when -4..-1\n exit code.abs if file_read\n end\n end", "def parseRunCommands\n didRun = false\n $runCommandOptions = {}\n File.open($benchmarkDirectory + $benchmark) {\n | inp |\n inp.each_line {\n | line |\n begin\n doesMatch = line =~ /^\\/\\/@/\n rescue Exception => e\n # Apparently this happens in the case of some UTF8 stuff in some files, where\n # Ruby tries to be strict and throw exceptions.\n next\n end\n next unless doesMatch\n eval $~.post_match\n didRun = true\n }\n }\n didRun\nend", "def handle(buf)\n buf = buf.to_s\n buf.strip!\n\n return if buf.empty?\n\n parts = buf.split\n cmd_name = parts.shift\n\n if cmd_name == 'help'\n help(*parts)\n return\n end\n\n cmd = preloaded_commands[cmd_name]\n\n unless cmd\n error(\"Command `#{cmd_name}' not found!\")\n return\n end\n\n system(cmd, *parts)\n return $?.exitstatus\n end", "def run_command(cmd, options={})\n FudgeMatchers::Run.new cmd, options\nend", "def exec(cmd, *rest) end", "def run\n\n if @@mock\n\n @result = OpenStruct.new(:success? => true, :exitstatus => 0)\n @output = \"Command entered: #{self.cmd}\"\n @error = ''\n return true\n\n else\n\n @output = ''\n @error = ''\n @result = nil\n\n begin\n\n Open3.popen3(self.cmd) do |stdin, stdout, stderr, wait|\n stdin.puts self.input unless self.input.nil?\n stdin.close\n until stdout.eof?\n @output << stdout.gets\n end\n until stderr.eof?\n @error << stderr.gets\n end\n @result = wait.value\n end\n\n rescue Exception => e\n\n @result = OpenStruct.new(:success? => false, :exitstatus => -1)\n @error << \"#{cmd} raised an error: #{e.class}:#{e}\"\n\n end\n\n self.result.success?\n\n end\n\n end", "def process_command(dbg, inp)\n if @more_input and @last_command\n @more_input = false\n output = @last_command.execute(self, inp)\n else\n @more_input = false\n @commands.each do |cmd|\n if inp =~ cmd.command_regexp\n begin\n @last_command = cmd.multiline? ? cmd : nil\n output = cmd.execute(dbg, self, $~)\n rescue StandardError => e\n handle_exception e\n end\n break\n end\n end\n end\n output\n end", "def process_commands; end", "def execute(input)\n begin\n request_data = JSON.load(input)\n @rawjsonrpc_noti = if request_data[\"id\"] == nil then true\n else false\n end\n @rawjsonrpc_id = request_data[\"id\"]\n if @rawjsonrpc_funcs.has_key?(request_data[\"method\"])\n ret = @rawjsonrpc_funcs[request_data[\"method\"]].call(*request_data[\"params\"])\n elsif @rawjsonrpc_blocks.has_key?(request_data[\"method\"])\n ret = @rawjsonrpc_blocks[request_data[\"method\"]].call(*request_data[\"params\"])\n else\n @rawjsonrpc_back = request_data\n raise(\"No Methode\")\n end\n if request_data[\"id\"] != nil\n {\"result\" => ret, \"error\" => nil, \"id\" => request_data[\"id\"]}\n .to_json\n else nil\n end\n rescue => ex\n unless @rawjsonrpc_noti\n {\"result\" => nil, \"error\" => ex.message,\n \"id\" => @rawjsonrpc_id}.to_json\n end\n end\n end", "def run_cmd(actor, buf)\n name, arg = buf.split(/\\s+/, 2)\n return if name.nil?\n arg = nil if arg && arg.empty?\n name = name.strip.chomp.downcase\n\n cmds = Morrow.config.commands\n cmd = cmds[name] || begin\n cmds.values\n .select { |c| c.name.start_with?(name) }\n .max_by { |c| c.priority }\n end\n\n cmd ? cmd.handler.call(actor, arg) :\n send_to_char(char: actor, buf: \"unknown command: #{name}\")\n rescue Command::Error => ex\n send_to_char(char: actor, buf: ex.message)\n end", "def execute(input: $stdin, output: $stdout)\n loop do\n case @subcommand\n when :gui\n gui\n when :d3\n require_relative 'font_d3'\n subcmd = SampleCmdletPatterns::Commands::FontD3.new({})\n when :block\n require_relative 'font_block'\n subcmd = SampleCmdletPatterns::Commands::FontBlock.new({})\n when :doom\n require_relative 'font_doom'\n subcmd = SampleCmdletPatterns::Commands::FontDoom.new({})\n when :standard\n require_relative 'font_standard'\n subcmd = SampleCmdletPatterns::Commands::FontStandard.new({})\n when :starwars\n require_relative 'font_starwars'\n subcmd = SampleCmdletPatterns::Commands::FontStarwars.new({})\n when :straight\n require_relative 'font_straight'\n subcmd = SampleCmdletPatterns::Commands::FontStraight.new({})\n else\n break\n end\n @subcommand = subcmd&.execute(input: input, output: output)\n end\n end", "def run(input, options = {})\n command = Command.new(options: options)\n yield(command) if block_given?\n command.run(input)\n end", "def run(cmd)\n log cmd\n system(cmd) or fail \"Command Failed: [#{cmd}]\"\n end", "def run\n excode, offset = exact\n\n code = \"\\n\"\n# code << special_requirements\n code << \"require '#{file}'\\n\"\n code << \"eval(<<'_____#{handle}_____', TOPLEVEL_BINDING, '#{file}', #{offset})\\n\"\n code << excode\n code << \"\\n_____#{handle}_____\\n\\n\"\n\n cmd = ['ruby', *argv].join(' ')\n\n result = IO.popen(cmd,\"w+\") do |ruby|\n ruby.puts code\n ruby.close_write\n puts ruby.read\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return size, always 3.
def size return 3 end
[ "def size\n\t\treturn 3\n\tend", "def size(*) end", "def length\n 3\n end", "def size\n variables.size\n end", "def size\n @size ||= approximate_size\n end", "def size\n # atributo del objeto 1\n @size\n end", "def current_size; end", "def size\n items.size\n end", "def sz\n self.to_s.size\n end", "def size\n\tparts.size\nend", "def size\n @dynamic_entries\n .map(&:size)\n .reduce(0, :+)\n end", "def size\n return @cubes.size\n end", "def size\n if @object_data.key?('size')\n return @object_data['size']\n else\n return get.size\n end\n end", "def size\n @size ||= @original.size\n end", "def size() \n return @n_objects\n end", "def length; count end", "def nb_items\n return @contained.length\n end", "def size; '' end", "def byte_size(); @data.byte_size + 4; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the exterior product.
def exterior_product(vec) self.class.exterior_product(self, vec) end
[ "def exterior_product(vec)\n\t\tself.class.exterior_product(self, vec)\n\tend", "def base_product\n product_num\n end", "def product\n self.product_size.product\n end", "def product_version_operator\n return @product_version_operator\n end", "def product_set\n product_sets[0]\n end", "def currentProduct()\n @products[@current_product]\n end", "def product\n line_item.product unless line_item.nil?\n end", "def rq_prod_point\n return construction.rq_prod_point\n end", "def outer_extrema\n return Features.outer_extrema(@data)\n end", "def parts\n product.parts\n end", "def product_family\n return @product_family\n end", "def last_active_product\n if ct = self.last_active_premium_contact_transaction\n ct.active_product\n end\n end", "def current_epli_policy\n policies.where(business_product: Business::Product.find_by(name: 'EPLI')).order(policy_year: :desc).first\n end", "def get_productivity week\n productivity_curves.find_by(week_number: week).production\n end", "def product_version\n return @product_version\n end", "def ext_effective_price\n (effective_list_price || 0) * (qty || 0)\n end", "def relation_method\n :product\n end", "def product\n sale_product = Product.new(:id, :name, :vendor_id)\n Product.all.each do |pro_id, pro|\n if pro_id == product_id\n sale_product = pro\n break\n end\n end\n return sale_product\n end", "def product\n return FarMar::Product.find(@product_id)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finding instrument user clicked on and creating inctance of booking for form
def show @instrument = Instrument.find(params[:id]) @booking = Booking.new end
[ "def create\n @instrument =\n current_facility.instruments.find_by!(url_name: params[:instrument_id])\n @reservation = @instrument.admin_reservations.new\n @reservation_form = AdminReservationForm.new(@reservation)\n @reservation_form.assign_attributes(admin_reservation_params.merge(created_by: current_user))\n @reservation_form.assign_times_from_params(admin_reservation_params)\n\n if @reservation_form.save\n flash[:notice] = \"The reservation has been created successfully.\"\n redirect_to facility_instrument_schedule_url\n else\n render action: \"new\", layout: \"two_column\"\n end\n end", "def booking_info(distance, cab, user)\n puts \"Dear #{user.name}\"\n puts \"You have selected car of #{cab.class} class\"\n puts \"Car no. : #{cab.number_plate}\"\n puts \"Driver name : #{cab.driver}\"\n puts \"Total Fare : #{cab.calculate_fare(distance)} Rs\"\n puts \"Ride Time : #{cab.calculate_time(distance)} Hrs. \\n \"\n puts '1.start ride'\n puts '2.cancel ride'\n choice(1, 2)\n end", "def new_browse\n input = appointment_params\n @date = Date.parse(input[:date])\n @doctor = Doctor.find(input[:doctor_id])\n @open_times = @doctor.open_appointment_times(@date)\n @appointment = Appointment.new\n end", "def create_booking\n @userId = UserService.find_user session[:user]\n time_slot = params[:id]\n booking_details = time_slot.split(\":\")\n @room = Room.find(booking_details[0])\n @day = booking_details[1]\n @from = booking_details[2]\n @users = UserService.all_library_users\n @util = Util.new\n\n end", "def create_new_booking_business_event!\n BusinessEvents::BusinessEvent.fire_event(:new_booking, \n {:booking_id => id})\n end", "def interhome_booking_form\n @accommodation = InterhomeAccommodation.find(params[:id])\n @property = @accommodation.property\n\n arrival = Date.today\n @interhome_booking = Interhome::Booking.new(arrival.to_s[8..9], arrival.to_s[0..6], arrival, 7, 2, 0, 0)\n\n if @accommodation.interhome_vacancy\n render layout: false\n else\n render template: \"properties/interhome_no_vacancy_info\", layout: false\n end\n end", "def make_booking(fitness_class)\n Booking.new('member_id' => @id, 'fitness_class_id' => fitness_class.id).save()\n update()\n end", "def create\n @booking = Booking.new(booking_params)\n \n unless params[:subject_id].empty?\n @subject = Subject.find(params[:subject_id])\n end\n # TODO date and time validation\n begin\n date = (params['date_part'] + \" \" + params['time_part']).to_datetime\n rescue ArgumentError\n @booking.errors.add(:date, \"is invalid\")\n date = Date.new\n end\n @booking.booking_date = date\n # TODO: Refactor for admin booking creation\n @booking.shared = params[\"shared\"]\n @booking.subject = @subject\n # Add this customer as owner. \n @booking.creator = current_user.customer\n @booking.customers << current_user.customer\n @booking.booked_customers.first.number_students = params[:booking][:booked_customers][:number_students]\n @booking.period = 2\n \n # Create closed booking if customer came from searching or enquiring.\n if params[:presenter_id].present?\n presenter = Presenter.find(params[:presenter_id])\n if presenter.available? @booking.booking_date, @booking.duration_minutes\n @booking.chosen_presenter = Presenter.find(params[:presenter_id])\n @booking.rate = presenter.rate\n @booking.creator = current_user.customer\n else\n @booking.errors.add(:presenter, \"is not available at this time\")\n end\n end \n \n if @booking.save\n # Only send messages to customers if booking is shared\n @message = \"A new #{@booking.subject.name} booking has been created that you may be interested in.\"\n if @booking.shared?\n Notification.notify_applicable_users(current_user, @booking, \"customer\", booking_path(@booking), @message, :interested_booking)\n end\n # Only send messages to presenters if booking is open\n if @booking.chosen_presenter.nil?\n Notification.notify_applicable_users(current_user, @booking, \"presenter\", booking_path(@booking), @message, :interested_booking)\n end\n Notification.notify_admin(\"A new booking has been created\", booking_path(@booking), :booking)\n\n # Add booking to booked customers\n current_user.customer.created_bookings << @booking\n\n #clear search session \n session[:search_params] = nil\n redirect_to @booking\n else\n @date_part = params['date_part']\n @time_part = params['time_part']\n render :new\n end\n\n end", "def bookEvent\n end", "def create\n Appointment.isolated_transaction do\n @appointment = Appointment.new(create_params)\n @appointment.end = @appointment.start + @appointment.ubs.slot_interval_minutes.minutes\n vaccine = Vaccine.find_by id: params[:vaccine_id]\n patient = @appointment.patient\n\n if @appointment.patient.doses.exists? && @appointment.save\n last_dose = @appointment.patient.doses.order(:sequence_number).last\n create_booster_dose(@appointment, vaccine, patient, last_dose)\n\n redirect_to([:admin, @appointment])\n\n elsif vaccine && @appointment.save\n ReceptionService.new(@appointment).tap do |service|\n service.check_in(at: @appointment.start)\n service.check_out(vaccine, at: @appointment.start)\n end\n\n redirect_to([:admin, @appointment])\n else\n render :new\n end\n end\n end", "def invite_for_booking_process(booking)\n @booking = booking\n @user = booking.user\n email_with_name = %(\"#{@user.full_name}\" <#{@user.email}>)\n mail(to: email_with_name, subject: 'Stacey - coliving - booking process')\n end", "def insurance(table)\n table.raw.each do |row|\n case row[0].downcase\n when 'patient insurance?'\n health_insurance.each do |hi|\n hi.click if hi.text == row[1]\n end\n when 'insurance company'\n insurance_company_dropdown.click\n for i in insurance_company_select\n i.click if i.text == row[1]\n end\n when 'id'\n id.set row[1]\n when 'phone number'\n phone_number.set row[1]\n when 'group'\n group.set row[1]\n when 'seperate pharmacy card'\n seperate_card.each do |card|\n card.click if card.text == row[1]\n end\n when 'member services phone number'\n member_service_phone_number.set row[1]\n when 'pharmacy benefit manager'\n pharmacy_benefit_manager.set row[1]\n sleep 2\n when 'date of birth'\n sleep 2\n dob.click\n dob.set row[1]\n when 'relationship'\n relationship_dropdown.click\n relationship_select.each do |relation|\n relation.click if relation.text == row[1]\n end\n sleep 2\n when 'holder name'\n holder_name.set row[1]\n when 'insured ssn'\n insured_ssn.set row[1]\n end\n end\n end", "def booking(data)\n payload = safe_access(data)\n\n params = {\n property_id: payload.get(\"inquiry.room.property_id\"),\n inquiry_id: payload.get(\"inquiry.id\"),\n unit_id: payload.get(\"inquiry.room.unit_id\"),\n check_in: payload.get(\"inquiry.check_in\"),\n check_out: payload.get(\"inquiry.check_out\"),\n guests: payload.get(\"inquiry.num_guests\"),\n subtotal: payload.get(\"inquiry.subtotal\"),\n currency_code: payload.get(\"inquiry.currency_code\"),\n customer: {\n first_name: payload.get(\"inquiry.user.first_name\"),\n last_name: payload.get(\"inquiry.user.last_name\"),\n email: payload.get(\"inquiry.user.email\"),\n phone: payload.get(\"inquiry.user.phone_number\")\n }\n }\n\n env[\"rack.input\"] = StringIO.new(json_encode(params))\n true\n end", "def register_booking\n return unless booked_at\n\n self.booked_at = ClockIn.new.recorded_as booked_time: booked_at.to_date,\n add_time: true\n credits.register_booking(self)\n end", "def create_booking\n @userId = UserService.find_user session[:user]\n @BookingList = {}\n @room = Room.find(params[:id])\n bookings = BookingService.current_bookings_for_room(@room)\n bookings.each {|booking|\n @BookingList[\"#{@room.id}:#{booking.day}:#{booking.start_time}\"] = booking\n }\n @util = Util.new\n end", "def booking_email(reservation) #customer, host, reservtion_id\n @user = reservation.user #appoint reservation user id(email,name)\n @host = reservation.listing.user #appoint listing user(email,name)\n @listing = reservation.listing #appoint reservation. listing(which id)\n\n mail(to: @user.email, subject: \"Thank you for your booking.\") #after all info appointed, send an email to user(customer)\n end", "def booked_in\n message = I18n.t('notify.booking.booked_in', course_name: booking.course.name, booker: booking.booker.name)\n BookingMailer.delay.booking_confirmation_to_non_chalkler(booking)\n Chalkler.invite!({email: booking.pseudo_chalkler_email, name: booking.name}, booking.booker) if booking.invite_chalkler\n end", "def add_owner(owner)\n @user = User.find(owner)\n @owner = @user\n @app = @user.appointments.create(:booking_id => self.id, :owner => true, :confirmed => true, :status => 'booked')\n if @app.save\n BookingMailer.booking_email(@user, @app.booking, @owner).deliver\n end \n end", "def send_outbound_create_event\n # check for the therapist associated with this appointment\n send_outbound_event(\"created\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
now actually creating the new instrument with user params and saving it rendering new page if user did not input all params
def create @instrument = Instrument.new(instrument_params) @instrument.user = current_user if @instrument.save redirect_to instrument_path(@instrument), notice: 'Created new instrument.' else render :new end end
[ "def create\n p \"*******INST CREATE*********\"\n user = User.find_by(id: session[:user_id])\n instrument = user.instruments.build(instrument_params)\n if instrument.save\n render json: instrument, status: :created\n else\n render json: {error: \"Not Created\"}, status: :not_created\n end\n end", "def create\n @instrument = Instrument.new(instrument_params)\n \n respond_to do |format|\n if @instrument.save\n format.html { redirect_to @instrument, notice: t('.success') }\n format.json { render :show, status: :created, location: @instrument }\n else\n format.html { render :new }\n format.json { render json: @instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @breadcrumb = 'create'\n @currency_instrument = CurrencyInstrument.new(params[:currency_instrument])\n @currency_instrument.created_by = current_user.id if !current_user.nil?\n\n respond_to do |format|\n if @currency_instrument.save\n format.html { redirect_to @currency_instrument, notice: crud_notice('created', @currency_instrument) }\n format.json { render json: @currency_instrument, status: :created, location: @currency_instrument }\n else\n @minor_unit = 6\n format.html { render action: \"new\" }\n format.json { render json: @currency_instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def url_create\n\n # secure the creation of new measurements\n if @profile.secure_data_entry\n unless @profile.data_entry_key == params[:key]\n return\n end\n end\n \n\n save_ok = false\n \n # some CHORDS users had an extra '0' on the beginnig of their instrument_id.\n # cleans this dirty input so that the create still works \n cleansed_instrument_id = params[:instrument_id].to_i\n\n if Instrument.exists?(id: cleansed_instrument_id)\n \n # Are the data submitted in this query a test?\n is_test_value = false\n if params.key?(:test)\n is_test_value = true\n end\n \n # Save the url that invoked us\n Instrument.update(cleansed_instrument_id, :last_url => request.original_url)\n \n # Create an array containing the names of legitimate variable names\n measured_at_parameters = Array.new\n variable_shortnames = Array.new\n \n Instrument.find(cleansed_instrument_id).vars.each do |var|\n measured_at_parameters.push(var.measured_at_parameter)\n variable_shortnames.push(var.shortname)\n \n # see if the parameter was submitted\n \n if params.include? var.shortname\n \n if params.key?(var.measured_at_parameter)\n measured_at = params[var.measured_at_parameter]\n elsif params.key?(var.at_parameter)\n measured_at = params[var.at_parameter]\n elsif params[:at]\n measured_at = params[:at]\n else \n measured_at = Time.now.iso8601\n end\n \n instrument = Instrument.find(cleansed_instrument_id)\n \n\n timestamp = ConvertIsoToMs.call(measured_at)\n value = params[var.shortname].to_f\n\n tags = influxdb_tags = instrument.influxdb_tags_hash\n tags[:site] = instrument.site_id\n tags[:inst] = instrument.id\n tags[:var] = var.id\n tags[:test] = params.has_key?(:test)\n \n\n SaveTsPoint.call(timestamp, value, tags)\n \n end\n end\n \n save_ok = true\n \n end \n \n respond_to do |format|\n if save_ok\n format.json { render text: \"OK\" }\n format.html { render text: \"Measurement created\" }\n else\n format.json { render text: \"FAIL\" }\n format.html { render text: \"Measurement could not be created\" }\n end\n end\n end", "def create\n @instrument = Instrument.new(instrument_params)\n\n respond_to do |format|\n if @instrument.save\n format.html { redirect_to @instrument, notice: 'Instrument was successfully created.' }\n format.json { render :show, status: :created, location: @instrument }\n else\n format.html { render :new }\n format.json { render json: @instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @musical_instrument = MusicalInstrument.new(musical_instrument_params)\n\n respond_to do |format|\n if @musical_instrument.save\n format.html { redirect_to @musical_instrument, notice: 'Instrumento Musical criado com sucesso.' }\n format.json { render :show, status: :created, location: @musical_instrument }\n else\n format.html { render :new }\n format.json { render json: @musical_instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @instrumento = Instrumento.new(instrumento_params)\n\n respond_to do |format|\n if @instrumento.save\n format.html { redirect_to @instrumento, notice: 'Instrumento was successfully created.' }\n format.json { render :show, status: :created, location: @instrumento }\n else\n format.html { render :new }\n format.json { render json: @instrumento.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @instrument = Instrument.new(params[:instrument])\n\n respond_to do |format|\n if @instrument.save\n format.html { redirect_to @instrument, :notice => 'Instrument was successfully created.' }\n format.json { render :json => @instrument, :status => :created, :location => @instrument }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @instrument.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @instrument = Instrument.new(admin_instrument_params)\n\n respond_to do |format|\n if @admin_instrument.save\n format.html { redirect_to @admin_instrument, notice: 'Instrument was successfully created.' }\n format.json { render action: 'show', status: :created, location: @admin_instrument }\n else\n format.html { render action: 'new' }\n format.json { render json: @admin_instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @alunosinstrumento = Alunosinstrumento.new(alunosinstrumento_params)\n\n respond_to do |format|\n if @alunosinstrumento.save\n format.html { redirect_to @alunosinstrumento, notice: 'Alunosinstrumento was successfully created.' }\n format.json { render :show, status: :created, location: @alunosinstrumento }\n else\n format.html { render :new }\n format.json { render json: @alunosinstrumento.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @instrument_type = InstrumentType.new(instrument_type_params)\n\n respond_to do |format|\n if @instrument_type.save\n format.html { redirect_to @instrument_type, notice: 'Instrument type was successfully created.' }\n format.json { render :show, status: :created, location: @instrument_type }\n else\n format.html { render :new }\n format.json { render json: @instrument_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n params = profile_has_instrument_params\n params[:profile_id] = Profile.find_by_user_id(current_user.id).user_id\n @profile_has_instrument = ProfileHasInstrument.new(params)\n\n respond_to do |format|\n if @profile_has_instrument.save\n format.html { redirect_to root_path, notice: 'Instrument was successfully selected.' }\n format.json { render :show, status: :created, location: @profile_has_instrument }\n else\n format.html { render :new }\n format.json { render json: @profile_has_instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @instrument = Instrument.new(params[:instrument])\n\n respond_to do |format|\n if @instrument.save\n flash[:notice] = 'Instrument was successfully created.'\n format.html { redirect_to(@instrument) }\n format.xml { render :xml => @instrument, :status => :created, :location => @instrument }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @instrument.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @instrumento = Instrumento.new(params[:instrumento])\n\n if @instrumento.save\n render json: @instrumento, status: :created, location: @instrumento\n else\n render json: @instrumento.errors, status: :unprocessable_entity\n end\n end", "def create\n @insurance_session = InsuranceSession.new(params[:insurance_session])\n @insurance_session.created_user = current_user.login_name\n\n respond_to do |format|\n if @insurance_session.save\n session[:dos] = @insurance_session.dos.strftime(\"%m/%d/%Y\")\n if params[:commit] == \"Insurance Claim\"\n format.html { redirect_to insurance_session_insurance_billings_path(@insurance_session), notice: 'Session was successfully updated.' }\n else\n format.html { redirect_to_balance_bill 'Session was successfully updated.' }\n end\n format.json { render json: @insurance_session }\n else\n format.html {\n @patient = Patient.find(params[:insurance_session][:patient_id])\n setup_patient_related_dropdowns(@patient)\n setup_group_and_provider_dropdowns(@patient)\n setup_rates_and_offices\n setup_other_codes\n render action: \"new\" }\n format.json { render json: @insurance_session.errors, status: :unprocessable_entity }\n end\n end\n\n end", "def create_generated_invoice\r\n if !params[:invoice][\"invoice_id\"].blank?\r\n #Based on the selection of imported invoice from the user\r\n imported_invoice = ImportedInvoice.find(params[:invoice][:invoice_id])\r\n @invoice = GeneratedInvoice.new(imported_invoice.attributes.except!(\"file\"))\r\n if @invoice.save\r\n respond_to do |format|\r\n format.html { render :show, notice: 'Invoice was successfully generated.' }\r\n format.json { render :show, status: :created, location: @invoice }\r\n return\r\n end\r\n else\r\n respond_to do |format|\r\n format.html { render :generateNew }\r\n format.json { render json: @invoice.errors, status: :unprocessable_entity }\r\n return\r\n end\r\n end\r\n else\r\n flash[:error] = \"Some Fields Are Missing, Please Fill in All Required Items!\"\r\n redirect_to generateNew_invoices_path\r\n end\r\n end", "def create\n @instrument_in_shop = InstrumentInShop.new(instrument_in_shop_params)\n\n respond_to do |format|\n if @instrument_in_shop.save\n format.html { redirect_to @instrument_in_shop, notice: 'Instrument in shop was successfully created.' }\n format.json { render :show, status: :created, location: @instrument_in_shop }\n else\n format.html { render :new }\n format.json { render json: @instrument_in_shop.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n params[:asset_item_detail][:balance].gsub!(',','') # 去掉金钱的逗点\n @asset_item_detail = AssetItemDetail.new(params[:asset_item_detail])\n\n respond_to do |format|\n if @asset_item_detail.save\n # 当我的家庭流动资产变化的时候,自动更新Param中流动资产的总值,并自动加入一笔ParamChange以追踪变化记录\n update_my_assets_and_insert_change_record if @asset_item_detail.asset_item.asset_belongs_to_id == 1\n flash[:notice] = 'created!'\n format.html { redirect_to :controller => :asset_item_details, :action => :new, :asset_item_id => @asset_item_detail.asset_item_id }\n format.xml { render :xml => @asset_item_detail, :status => :created, :location => @asset_item_detail }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @asset_item_detail.errors, :status => :unprocessable_entity }\n end\n end\n end", "def url_create\n\n # secure the creation of new measurements\n if @profile.secure_data_entry\n unless @profile.data_entry_key == params[:key]\n return\n end\n end\n \n\n # Are the data submitted in this query a test?\n is_test_value = false\n if params.key?(:test)\n is_test_value = true\n end\n \n # Save the url that invoked us\n Instrument.update(params[:instrument_id], :last_url => request.original_url)\n\n # Create an array containing the names of legitimate variable names\n measured_at_parameters = Array.new\n variable_shortnames = Array.new\n \n Instrument.find(params[:instrument_id]).vars.each do |var|\n measured_at_parameters.push(var.measured_at_parameter)\n variable_shortnames.push(var.shortname)\n \n # see if the parameter was submitted\n \n if params.include? var.shortname\n\n if params.key?(var.measured_at_parameter)\n measured_at = params[var.measured_at_parameter]\n elsif params.key?(var.at_parameter)\n measured_at = params[var.at_parameter]\n elsif params[:at]\n measured_at = params[:at]\n else \n measured_at = Time.now \n end\n # Create a new measurement\n @measurement = Measurement.new(\n :measured_at => measured_at,\n :instrument_id => params[:instrument_id], \n :test => is_test_value,\n :parameter => var.shortname, \n :value => params[var.shortname])\n @measurement.save\n end\n end\n\n respond_to do |format|\n if @measurement.save\n format.json { render text: \"OK\" }\n format.html { render :show, status: :created, location: @measurement, message: \"Measurement created\" }\n else\n format.html { render :new }\n format.json { render json: @measurement.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finding instrument to destroy destroying the instrument redirecting to root_path
def destroy @instrument = Instrument.find(params[:id]) @instrument.destroy redirect_to root_path end
[ "def destroy\n @instrument = Instrument.find(params[:id])\n @instrument.destroy\n\n respond_to do |format|\n format.html { redirect_to(instruments_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @instrumento = Instrumento.find(params[:id])\n @instrumento.destroy\n\n head :no_content\n end", "def destroy\n @instrument.destroy\n respond_to do |format|\n format.html { redirect_to admin_instruments_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @instrument.destroy\n respond_to do |format|\n format.html { redirect_to instruments_url }\n format.json { head :no_content }\n end\n end", "def destroy_rest\n @instrument = Instrument.find(params[:id])\n @instrument.destroy\n\n respond_to do |format|\n format.html { redirect_to(instruments_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @instrument = Instrument.find(params[:id])\n @instrument.destroy\n\n respond_to do |format|\n format.html { redirect_to instruments_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @instrumento = Instrumento.find(params[:id])\n @instrumento.destroy\n\n respond_to do |format|\n format.html { redirect_to instrumentos_url }\n format.json { head :no_content }\n end\n end", "def destroy_rest\n @instrument_session = InstrumentSession.find(params[:id])\n @instrument_session.destroy\n\n respond_to do |format|\n format.html { redirect_to(instrument_sessions_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @instrument.destroy\n respond_to do |format|\n format.html { redirect_to instruments_url, notice: 'Instrument was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @instrument.destroy\n respond_to do |format|\n format.html { redirect_to instruments_url, notice: t('.success') }\n format.json { head :no_content }\n end\n end", "def destroy\n @instrumento.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_instrumentos_url, notice: 'Instrumento was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @spice.destroy\n\n head :no_content\n end", "def destroy\n revert_impersonate\n redirect_to root_path\n end", "def destroy_rest\n @entry_instrument = EntryInstrument.find(params[:id])\n @entry_instrument.destroy\n\n respond_to do |format|\n format.html { redirect_to(entry_instruments_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @payment_instrument.destroy\n respond_to do |format|\n format.html { redirect_to payment_instruments_url, notice: 'Payment instrument was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @v1_instrument_session = V1InstrumentSession.find(params[:id])\n @v1_instrument_session.destroy\n\n respond_to do |format|\n format.html { redirect_to(v1_instrument_sessions_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @game_instrument.destroy\n respond_to do |format|\n format.html { redirect_to action: :index, notice: 'Game instrument was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @virus_probe.destroy\n respond_to do |format|\n format.html { redirect_to virus_probes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @alunosinstrumento.destroy\n respond_to do |format|\n format.html { redirect_to alunosinstrumentos_url, notice: 'Alunosinstrumento was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
finding instrument to update updating instrument with user_params redirecting to instrument_path
def update @instrument = Instrument.find(params[:id]) @instrument.update(instrument_params) redirect_to instrument_path(@instrument) end
[ "def update\n params = profile_has_instrument_params\n params[:profile_id] = Profile.find_by_user_id(current_user.id).user_id\n respond_to do |format|\n if @profile_has_instrument.update(params)\n format.html { redirect_to root_path, notice: 'Instrument was successfully changed.' }\n format.json { render :show, status: :ok, location: @profile_has_instrument }\n else\n format.html { render :edit }\n format.json { render json: @profile_has_instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @instrument = Instrument.find(params[:id])\n @person = @instrument.person\n @participant = @person.participant\n\n respond_to do |format|\n if @instrument.update_attributes(params[:instrument])\n\n redirect_path = @participant ? participant_path(@participant) : person_path(@person)\n\n \tformat.html { redirect_to(redirect_path, :notice => 'Instrument was successfully updated.') }\n format.json { render :json => @instrument }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @instrument.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @instrument.update(instrument_params)\n format.html { redirect_to @instrument, notice: 'Instrument was successfully updated.' }\n format.json { render :show, status: :ok, location: @instrument }\n else\n format.html { render :edit }\n format.json { render json: @instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @instrument.update(admin_instrument_params)\n format.html { redirect_to @admin_instrument, notice: 'Instrument was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @admin_instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @insurance_payment = InsurancePayment.find(params[:id])\n\t@user_id = params[:user_id]\n respond_to do |format|\n if @insurance_payment.update_attributes(params[:insurance_payment])\n format.html { redirect_to(\"/insurance_payments/new\", :notice => 'InsurancePayment was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @insurance_payment.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @breadcrumb = 'update'\n @currency_instrument = CurrencyInstrument.find(params[:id])\n @currency_instrument.updated_by = current_user.id if !current_user.nil?\n\n respond_to do |format|\n if @currency_instrument.update_attributes(params[:currency_instrument])\n format.html { redirect_to @currency_instrument,\n notice: (crud_notice('updated', @currency_instrument) + \"#{undo_link(@currency_instrument)}\").html_safe }\n format.json { head :no_content }\n else\n @minor_unit = @currency_instrument.currency.minor_unit\n format.html { render action: \"edit\" }\n format.json { render json: @currency_instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @payment_instrument.update(payment_instrument_params)\n format.html { redirect_to @payment_instrument, notice: 'Payment instrument was successfully updated.' }\n format.json { render :show, status: :ok, location: @payment_instrument }\n else\n format.html { render :edit }\n format.json { render json: @payment_instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @instrument = Instrument.find(params[:id])\n\n respond_to do |format|\n if @instrument.update_attributes(params[:instrument])\n format.html { redirect_to @instrument, notice: 'Instrument was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @instrument = Instrument.find(params[:id])\n\n respond_to do |format|\n if @instrument.update_attributes(params[:instrument])\n flash[:notice] = 'Instrument was successfully updated.'\n format.html { redirect_to(@instrument) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @instrument.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @breadcrumb = 'update'\n @insurance = Insurance.find(params[:id])\n @insurance.updated_by = current_user.id if !current_user.nil?\n \n respond_to do |format|\n if @insurance.update_attributes(params[:insurance])\n format.html { redirect_to @insurance,\n notice: (crud_notice('updated', @insurance) + \"#{undo_link(@insurance)}\").html_safe }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @insurance.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @musical_instrument.update_attributes(musical_instrument_params)\n format.html { redirect_to @musical_instrument, notice: 'Instrumento Musical atualizado com sucesso.' }\n format.json { render :show, status: :ok, location: @musical_instrument }\n else\n format.html { render :edit }\n format.json { render json: @musical_instrument.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @user_insurance.update(user_insurance_params)\n format.html { redirect_to user_insurances_url, notice: 'Insurance was successfully updated.' }\n # format.json { render :show, status: :ok, location: @user_insurance }\n else\n format.html { render :edit }\n # format.json { render json: @user_insurance.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @patient = Patient.find(params[:patient_id])\n @patient_injury = @patient.patient_injuries.find(params[:id])\n @patient_injury.updated_user = current_user.login_name\n \n respond_to do |format|\n if @patient_injury.update_attributes(params[:patient_injury])\n format.html { redirect_back_or_default patient_patient_injuries_path(params[:patient_id]), notice: 'Patient history was successfully updated.' }\n format.json { head :no_content }\n else\n @accident_types = AccidentType.all\n format.html { render action: \"edit\" }\n format.json { render json: @patient_injury.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_rest\n @instrument = Instrument.find(params[:id])\n\n respond_to do |format|\n if @instrument.update_attributes(params[:instrument])\n flash[:notice] = 'Instrument was successfully updated.'\n format.html { redirect_to(@instrument) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @instrument.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @user_to_interest.update(user_to_interest_params)\n format.html { redirect_to @user_to_interest, notice: 'User to interest was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_to_interest }\n else\n format.html { render :edit }\n format.json { render json: @user_to_interest.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n forbidden unless current_account_user.update_recording_ipi? \n @recording = Recording.cached_find(params[:recording_id])\n @recording_ipi.update(recording_ipi_params)\n\n redirect_to account_account_recording_recording_ipis_path( @account, @recording)\n\n end", "def update\n respond_to do |format|\n if @alunosinstrumento.update(alunosinstrumento_params)\n format.html { redirect_to @alunosinstrumento, notice: 'Alunosinstrumento was successfully updated.' }\n format.json { render :show, status: :ok, location: @alunosinstrumento }\n else\n format.html { render :edit }\n format.json { render json: @alunosinstrumento.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if current_user && current_user.admin?\n @investment_asset = InvestmentAsset.find(params[:id])\n\n respond_to do |format|\n if @investment_asset.update_attributes(params[:investment_asset])\n format.html { redirect_to({:controller => :investment_assets, :action => :index}, :notice => 'Investment asset was successfully updated.') }\n else\n format.html { render :action => \"edit\" }\n end\n end\n else\n redirect_to accounts_path\n end \n end", "def update\n @insurance_master = InsuranceMaster.find(params[:id])\n\n respond_to do |format|\n if @insurance_master.update_attributes(params[:insurance_master])\n format.html { redirect_to(\"/insurance_masters/new?user_id=#{params[:user_id]}\", :notice => 'InsuranceMaster was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @insurance_master.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implicitly hints that a uniform exists.
def uniform_location(uniform_name) uniform_sym = uniform_name.to_sym @uniform_locations[uniform_sym] ||= Gl.glGetUniformLocation(@name, uniform_name.to_s) end
[ "def set_texture_uniform(name, uniform)\n \n end", "def bind_uniform(name, location)\n return if location == NO_UNIFORM\n value = self[name]\n return unless value\n\n type, length, address =\n if value.kind_of? PackedValue\n [value.type, value.length, value.value]\n elsif value.respond_to? :address\n [value.class, value.length, value.respond_to?(:to_p) ? value.to_p : value.address]\n else\n [value.class, 1, nil]\n end\n\n # Bind the value to the uniform location. Because you can't do\n # Class === Class, this basically turns into a long series of type == X\n # entries. Might be better to refactor it as a bunch if/elsif blocks.\n case\n\n when type == nil then return\n\n when type == Float ||\n type == :float\n if address\n glUniform1iv(location, length, address)\n else\n glUniform1i(location, value)\n end\n\n when type == Fixnum ||\n type == :int\n if address\n glUniform1iv(location, length, address)\n else\n glUniform1i(location, value)\n end\n\n when type == :int2\n if address\n glUniform2iv(location, length, address)\n else\n glUniform2i(location, *value)\n end\n\n when type == :int3\n if address\n glUniform3iv(location, length, address)\n else\n glUniform3i(location, *value)\n end\n\n when type == :int4\n if address\n glUniform4iv(location, length, address)\n else\n glUniform4i(location, *value)\n end\n\n when type == :uint\n if address\n glUniform1uiv(location, length, address)\n else\n glUniform1ui(location, value)\n end\n\n when type == :uint2\n if address\n glUniform2uiv(location, length, address)\n else\n glUniform2ui(location, *value)\n end\n\n when type == :uint3\n if address\n glUniform3uiv(location, length, address)\n else\n glUniform3ui(location, *value)\n end\n\n when type == :uint4\n if address\n glUniform4uiv(location, length, address)\n else\n glUniform4ui(location, *value)\n end\n\n when type == Snow::Vec2\n Gl::glUniform2fv(location, 1, address)\n\n when type == Snow::Vec3\n Gl::glUniform3fv(location, 1, address)\n\n when type == Snow::Vec4 ||\n type == Snow::Quat\n Gl::glUniform4fv(location, 1, address)\n\n when type == Snow::Mat3\n Gl::glUniformMatrix3fv(location, 1, Gl::GL_FALSE, address)\n\n when type == Snow::Mat4\n Gl::glUniformMatrix4fv(location, 1, Gl::GL_FALSE, address)\n\n when type == Snow::Vec2Array ||\n type == :float2\n Gl::glUniform2fv(location, value.length, address)\n\n when type == Snow::Vec3Array ||\n type == :float3\n Gl::glUniform3fv(location, value.length, address)\n\n when type == Snow::Vec4Array ||\n type == Snow::QuatArray ||\n type == :float4 ||\n type == :quat\n Gl::glUniform4fv(location, value.length, address)\n\n when type == Snow::Mat3Array ||\n type == :mat3 ||\n type == :float3x3\n Gl::glUniformMatrix3fv(location, value.length, Gl::GL_FALSE, address)\n\n when type == Snow::Mat4Array ||\n type == :mat4 ||\n type == :float4x4\n Gl::glUniformMatrix4fv(location, value.length, Gl::GL_FALSE, address)\n\n else\n raise \"Invalid value of type #{value.class} bound to uniform #{name}\"\n end\n\n nil\n end", "def set_bool_uniform(name, uniform)\n \n end", "def set_float_uniform(name, uniform)\n \n end", "def set_matrix_uniform(name, uniform)\n \n end", "def uniform_location(name)\n @uniform_locations[name.to_sym] ||= begin\n GL.glGetUniformLocation(self.name, name.to_s)\n end\n end", "def variable(variable)\n loc = glGetUniformLocation(@program, variable)\n if (loc == -1)\n puts \"Shader Error: Program \\\"#{@name}\\\" has no such uniform named \\\"#{variable}\\\"\", \" Is it used in the shader? GLSL may have optimized it out.\", \" Is it miss spelled?\" unless @variable_missing[variable]\n @variable_missing[variable] = true\n end\n return loc\n end", "def variable(variable)\n loc = glGetUniformLocation(@program, variable)\n if loc == -1\n unless @variable_missing[variable]\n puts \"Shader Error: Program \\\"#{@name}\\\" has no such uniform named \\\"#{variable}\\\"\",\n \" Is it used in the shader? GLSL may have optimized it out.\", \" Is it miss spelled?\"\n end\n @variable_missing[variable] = true\n end\n loc\n end", "def set_float_array_uniform(name, uniform)\n \n end", "def bind(program, *names)\n if names.empty?\n program.each_hinted_uniform do |name|\n location = program.uniform_location(name)\n next unless location != NO_UNIFORM && self.include?(name)\n bind_uniform(name, location)\n end\n else\n names.each do |name|\n name = name.to_sym\n next unless include? name\n location = program.uniform_location(name)\n next if location == NO_UNIFORM\n bind_uniform(name, location)\n end\n end\n\n self\n end", "def create\n @uniform = Uniform.new(uniform_params)\n\n respond_to do |format|\n if @uniform.save\n format.html { redirect_to @uniform, notice: 'Uniform was successfully created.' }\n format.json { render :show, status: :created, location: @uniform }\n else\n format.html { render :new }\n format.json { render json: @uniform.errors, status: :unprocessable_entity }\n end\n end\n end", "def valid_uniform_number\n unless uniform_number.blank?\n ones_digit = uniform_number % 10\n if ones_digit == 0\n ones_digit =1;\n end\n number = Team.search(:id_eq => team_id, \n :players_uniform_number_eq => uniform_number).result.to_a\n if !number.empty?\n errors.add(:uniform_number, \"is already taken\")\n end\n if uniform_number <= -1\n errors.add(:uniform_number, \"can't be negative\")\n end\n if uniform_number > 55\n errors.add(:uniform_number, \"can't be greater than 55\")\n end\n\n if 5 % ones_digit == 5\n errors.add(:uniform_number, \"AAU Regulation: no digit greater than 5 (use numbers 0-5,10-15,20-25...)\")\n end\n end\n end", "def glorot_uniform_initializer(seed: nil, dtype: nil)\n TensorStream::Initializer.new(-> { _op(:glorot_uniform, seed: seed, data_type: dtype) })\n end", "def uniform(data)\n Distribution.new :LISTS, data, mk_shape_fn {|x| 1}\n end", "def uniform(low=0, high=1, shape: nil, dtype: nil, ctx: nil, out: nil, **kwargs)\n _random_helper(:_random_uniform, :_sample_uniform, {low: low, high: high}, shape, dtype, ctx, out, kwargs)\n end", "def random_uniform_initializer(minval: 0, maxval: 1, seed: nil, dtype: nil)\n TensorStream::Initializer.new(-> { _op(:random_uniform, nil, nil, minval: 0, maxval: 1, seed: seed, data_type: dtype) })\n end", "def random_uniform_initializer(minval: 0, maxval: 1, seed: nil, dtype: nil)\n TensorStream::Initializer.new(-> { _op(:random_uniform, minval: 0, maxval: 1, seed: seed, data_type: dtype) })\n end", "def update\n respond_to do |format|\n if @uniform.update(uniform_params)\n format.html { redirect_to @uniform, notice: 'Uniform was successfully updated.' }\n format.json { render :show, status: :ok, location: @uniform }\n else\n format.html { render :edit }\n format.json { render json: @uniform.errors, status: :unprocessable_entity }\n end\n end\n end", "def uniform(a, b)\n a + rand()*(b-a)\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }