query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
sequencelengths
19
19
metadata
dict
GET /book_pages GET /book_pages.json
def index @book_pages = @book.book_pages respond_to do |format| format.html # index.html.erb format.json { render json: @book_pages } end end
[ "def show\n @book_page = @book.book_pages.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @book_page }\n end\n end", "def index\n @pages = Page.page params[:page]\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pages }\n end\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 index\n @pages = Page.all\n render json: @pages, status: 200\n end", "def index\n @books = Book.all\n render json: @books\n end", "def index\n @pages = current_site.pages\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pages }\n end\n end", "def show\n @pages = Pages.find(params[:id])\n\n render json: @pages\n end", "def index\n @pages = Page.all\n\n respond_to do |format|\n format.json { render json: @pages }\n format.xml { render xml: @pages }\n end\n end", "def show\n @page = Page.find(params[:id])\n @pages = Page.find(params[:id]).pages\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @page }\n end\n end", "def pages\n get(\"v1/event/#{@id}/pages\")\n end", "def index\n @biblebooks = Biblebook.all\n\n respond_to do |format|\n format.html\n format.json{ render json: @biblebooks, root: false}\n end\n end", "def index\n @about_pages = AboutPage.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @about_pages }\n end\n end", "def index\n @chapters = @book.chapters\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @chapters }\n end\n end", "def get_pages(options = nil)\n @client.raw('get', '/content/pages', options)\n end", "def new\n @book_page = @book.book_pages.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book_page }\n end\n end", "def pages\n self.list(:pages)\n end", "def index\n @collection_pages = @collection.collection_pages\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @collection_pages }\n end\n end", "def booking\n page = @site.pages.where(order: 2).first\n unless page\n head 404\n else\n render json: { content: Content.where(page_id: page.id, order: 0).first }\n end\n end", "def pages\n get(\"v1/account/#{@email}/pages\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /book_pages/1 GET /book_pages/1.json
def show @book_page = @book.book_pages.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @book_page } end end
[ "def index\n @book_pages = @book.book_pages\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @book_pages }\n end\n end", "def index\n @pages = Page.page params[:page]\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pages }\n end\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 @page = Page.find(params[:id])\n @pages = Page.find(params[:id]).pages\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @page }\n end\n end", "def show\n @pages = Pages.find(params[:id])\n\n render json: @pages\n end", "def new\n @book_page = @book.book_pages.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book_page }\n end\n end", "def new\n @scrapbook = Scrapbook.new\n @page = @scrapbook.pages.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @scrapbook }\n end\n end", "def booking\n page = @site.pages.where(order: 2).first\n unless page\n head 404\n else\n render json: { content: Content.where(page_id: page.id, order: 0).first }\n end\n end", "def index\n @books = Book.all\n render json: @books\n end", "def index\n @pages = Page.all\n render json: @pages, status: 200\n end", "def index\n @pages = current_site.pages\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pages }\n end\n end", "def index\n @biblebooks = Biblebook.all\n\n respond_to do |format|\n format.html\n format.json{ render json: @biblebooks, root: false}\n end\n end", "def index\n @pages = Page.all\n\n respond_to do |format|\n format.json { render json: @pages }\n format.xml { render xml: @pages }\n end\n end", "def index\n @chapters = @book.chapters\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @chapters }\n end\n end", "def index\n @about_pages = AboutPage.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @about_pages }\n end\n end", "def show\n @book_url = BookUrl.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @book_url }\n end\n end", "def index\n @firstpages = Firstpage.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @firstpages }\n end\n end", "def show\n @document_page = DocumentPage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @document_page }\n end\n end", "def index\n @memos = @book.memos.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @memos }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /book_pages/new GET /book_pages/new.json
def new @book_page = @book.book_pages.build respond_to do |format| format.html # new.html.erb format.json { render json: @book_page } end end
[ "def new\n @scrapbook = Scrapbook.new\n @page = @scrapbook.pages.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @scrapbook }\n end\n end", "def new\n @page = current_site.pages.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @page }\n end\n end", "def new\n @page = Page.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @page }\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 @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 @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 @book_url = BookUrl.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book_url }\n end\n end", "def new\n @newspage = Newspage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @newspage }\n end\n end", "def new\n @page_version = PageVersion.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @page_version }\n end\n end", "def new\n @page_type = PageType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @page_type }\n end\n end", "def new\n @page = Page.new\n\n respond_to do |format|\n format.json { render json: @page }\n format.xml { render xml: @page }\n end\n end", "def new\n @document_page = DocumentPage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @document_page }\n end\n end", "def new\n @page_template = PageTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @page_template }\n end\n end", "def new\n @book_link = BookLink.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book_link }\n end\n end", "def new\n @page_view = PageView.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @page_view }\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.json { render json: @book_type }\n end\n end", "def new\n @doc_page = DocPage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @doc_page }\n end\n end", "def new\n @yellowpage = Yellowpage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @yellowpage }\n end\n end", "def new\n @book_collection = BookCollection.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book_collection }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /book_pages POST /book_pages.json
def create @book_page = @book.book_pages.build(params[:book_page]) respond_to do |format| if @book_page.save format.html { redirect_to book_series_collection_book_book_pages_url(@book_series, @collection, @book), notice: 'Book page was successfully created.' } format.json { render json: @book_page, status: :created, location: @book_page } else format.html { render action: "new" } format.json { render json: @book_page.errors, status: :unprocessable_entity } end end end
[ "def new\n @book_page = @book.book_pages.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book_page }\n end\n end", "def create\n @scrapbook = Scrapbook.new(params[:scrapbook])\n @page = @scrapbook.pages.new\n\n respond_to do |format|\n if @scrapbook.save\n format.html { redirect_to new_scrapbook_page_url(@scrapbook), notice: 'Scrapbook was successfully created.' }\n format.json { render json: @scrapbook, status: :created, location: @scrapbook }\n else\n format.html { render action: \"new\" }\n format.json { render json: @scrapbook.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @scrapbook = Scrapbook.new\n @page = @scrapbook.pages.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @scrapbook }\n end\n end", "def index\n @book_pages = @book.book_pages\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @book_pages }\n end\n end", "def create\n @nested_page = Nested::Page.new(params[:nested_page])\n\n respond_to do |format|\n if @nested_page.save\n format.html { redirect_to @nested_page, notice: 'Page was successfully created.' }\n format.json { render json: @nested_page, status: :created, location: @nested_page }\n else\n format.html { render action: \"new\" }\n format.json { render json: @nested_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @page = Page.new(page_params)\n respond_to do |format|\n if @page.save\n format.html { render json: @page }\n format.json { render json: @page, status: :created}\n else\n format.html { render :new }\n format.json { render json: @page.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n begin\n @page = Page.create_page!\n format.html { redirect_to \"/#{@page.request_id}/inspect\", notice: t('pages.create.success') }\n format.json { render action: 'show', status: :created, location: @page }\n rescue => e\n format.html { render action: 'index' }\n format.json { render json: {:message => \"create page error\"}, status: :unprocessable_entity }\n end\n end\n end", "def create\n @page = Page.new(params[:page])\n\n respond_to do |format|\n if @page.save\n format.json { render json: @page, status: :created, location: [:api, @page] }\n format.xml { render xml: @page, status: :created, location: [:api, @page] }\n else\n format.json { render json: @page.errors, status: :unprocessable_entity }\n format.xml { render xml: @page.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @page = Page.new(params[:page])\n \n if @page.save\n respond_to do |format|\n format.json { render :json => @page, :status => :created }\n format.xml { render :xml => @page, :status => :created }\n end\n else\n respond_to do |format|\n format.json { raise Palani::Api::InvalidRecordJSONException }\n format.xml { raise Palani::Api::InvalidRecordXMLException }\n end\n end\n end", "def create\n\n #Can also be created with:\n # => curl -X POST -H \"Content-Type: application/json; charset=UTF-8\" -d '{\"page\": {\"ppm\": \"400\",\"device_id\": \"1\"}}' localhost:3000/pages.json\n # => curl -X POST -H \"Content-Type: application/json; charset=UTF-8\" -d '{\"page\": {\"ppm\": \"400\", \"device_address\": \"42\"}}' localhost:3000/pages.json\n\n @page = Page.new(page_params)\n authorize @page\n\n respond_to do |format|\n if @page.save\n format.html { redirect_to @page, notice: 'Page was successfully created.' }\n format.json { render :show, status: :created, location: @page }\n else\n format.html { render :new }\n format.json { render json: @page.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @document_page = DocumentPage.new(params[:document_page])\n\n respond_to do |format|\n if @document_page.save\n format.html { redirect_to @document_page, notice: 'Document page was successfully created.' }\n format.json { render json: @document_page, status: :created, location: @document_page }\n else\n format.html { render action: \"new\" }\n format.json { render json: @document_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @student_post_page = StudentPostPage.new(params[:student_post_page])\n\n respond_to do |format|\n if @student_post_page.save\n format.html { redirect_to @student_post_page, notice: 'Student post page was successfully created.' }\n format.json { render json: @student_post_page, status: :created, location: @student_post_page }\n else\n format.html { render action: \"new\" }\n format.json { render json: @student_post_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @document_page = DocumentPage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @document_page }\n end\n end", "def create\n @book = Book.new(book_params)\n\n if @book.save\n render json: @book, status: :created, location: @book\n else\n render json: @book.errors, status: :unprocessable_entity\n end\n end", "def page title, story\n page = {'title' => title, 'story' => story, 'journal' => [create(title)]}\n File.open(\"../pages/#{slug(title)}\", 'w') do |file| \n file.write JSON.pretty_generate(page)\n end\nend", "def create\n @collection_page = @collection.collection_pages.build(params[:collection_page])\n\n respond_to do |format|\n if @collection_page.save\n format.html { redirect_to [@book_series, @collection, @collection_page], notice: 'CollectionPage was successfully created.' }\n format.json { render json: @collection_page, status: :created, location: @collection_page }\n else\n format.html { render action: \"new\" }\n format.json { render json: @collection_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @doc_page = DocPage.new(params[:doc_page])\n\n respond_to do |format|\n if @doc_page.save\n format.html { redirect_to @doc_page, notice: 'Doc page was successfully created.' }\n format.json { render json: @doc_page, status: :created, location: @doc_page }\n else\n format.html { render action: \"new\" }\n format.json { render json: @doc_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @nested_page = Nested::Page.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @nested_page }\n end\n end", "def index\n @pages = Page.page params[:page]\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pages }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /book_pages/1 PUT /book_pages/1.json
def update @book_page = @book.book_pages.find(params[:id]) respond_to do |format| if @book_page.update_attributes(params[:book_page]) format.html { redirect_to book_series_collection_book_book_page_url(@book_series, @collection, @book, @book_page), notice: 'Book page was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @book_page.errors, status: :unprocessable_entity } end end 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 book_update\n if params[:token] != ENV['UPDATE_TOKEN']\n return render :text => 'nope'\n end\n\n lang = params[:lang]\n chapter = params[:chapter].to_i\n section = params[:section].to_i\n chapter_title = params[:chapter_title]\n section_title = params[:section_title]\n content = params[:content].force_encoding(\"UTF-8\")\n\n # create book (if needed)\n book = Book.where(:code => lang).first_or_create\n\n # create chapter (if needed)\n chapter = book.chapters.where(:number => chapter).first_or_create\n chapter.title = chapter_title\n chapter.save\n\n # create/update section\n section = chapter.sections.where(:number => section).first_or_create\n section.title = section_title\n section.html = content\n section.save\n\n render :text => 'ok'\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 @document_page = DocumentPage.find(params[:id])\n\n respond_to do |format|\n if @document_page.update_attributes(params[:document_page])\n format.html { redirect_to @document_page, notice: 'Document page was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @document_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @page = Page.find(params[:id])\n\n respond_to do |format|\n if @page.update_attributes(params[:page])\n format.json { head :no_content }\n format.xml { head :no_content }\n else\n format.json { render json: @page.errors, status: :unprocessable_entity }\n format.xml { render xml: @page.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @page = current_user.pages.with_slug!(params[:id])\n @page.attributes = params[:page]\n\n respond_to do |format|\n if @page.valid?\n @page.sections.destroy_all\n @page.update_attributes(params[:page])\n format.html { redirect_to @page, :notice => 'Page was successfully updated.' }\n format.json { render :json => {} }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @page.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @shelf_page = @shelf.shelf_pages.find(params[:id])\n\n respond_to do |format|\n if @shelf_page.update_attributes(params[:shelf_page])\n format.html { redirect_to shelf_shelf_pages_path, notice: 'Shelf page was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @shelf_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @collection_page = @collection.collection_pages.find(params[:id])\n\n respond_to do |format|\n if @collection_page.update_attributes(params[:collection_page])\n format.html { redirect_to [@book_series, @collection, @collection_page], notice: 'CollectionPage was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @collection_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_page(page_id, content, version: nil)\n info = page_info(page_id)\n version = info['version']['number'] + 1 if version.nil?\n log_debug \"Update Confluence page #{page_id}...\"\n call_api(\"rest/api/content/#{page_id}\", :put) do |request|\n request['Content-Type'] = 'application/json'\n request.body = {\n type: 'page',\n title: info['title'],\n body: {\n storage: {\n value: content,\n representation: 'storage'\n }\n },\n version: { number: version }\n }.to_json\n end\n end", "def update\n respond_to do |format|\n if @document_page.update(document_page_params)\n format.html { redirect_to @document_page, notice: 'Document page was successfully updated.' }\n format.json { render :show, status: :ok, location: @document_page }\n else\n format.html { render :edit }\n format.json { render json: @document_page.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 index\n @book_pages = @book.book_pages\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @book_pages }\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 @doc_page = DocPage.find(params[:id])\n\n respond_to do |format|\n if @doc_page.update_attributes(params[:doc_page])\n format.html { redirect_to @doc_page, notice: 'Doc page was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @doc_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @pages = Page.find(params[:id])\n\n respond_to do |format|\n if @pages.update_attributes(params[:pages])\n flash[:notice] = 'Admin::Pages was successfully updated.'\n format.html { redirect_to(@pages) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @pages.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @book_page = @book.book_pages.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book_page }\n end\n end", "def update\n @nested_page = Nested::Page.find(params[:id])\n\n respond_to do |format|\n if @nested_page.update_attributes(params[:nested_page])\n format.html { redirect_to @nested_page, notice: 'Page was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @nested_page.errors, status: :unprocessable_entity }\n end\n end\n end", "def changeBook\n getBook(params[:book_id])\n if @book.blank? \n return false;\n end\n @playdate.page_num = params[:page_num]\n @playdate.save\n Pusher[@playdate.pusher_channel_name].trigger('change_book', {\n :data => @book.to_json(:include => :pages),\n :book => @book.id,\n :player => current_user.id,\n :page => params[:page_num]\n })\n end", "def create\n @book_page = @book.book_pages.build(params[:book_page])\n\n respond_to do |format|\n if @book_page.save\n format.html { redirect_to book_series_collection_book_book_pages_url(@book_series, @collection, @book), \n notice: 'Book page was successfully created.' }\n format.json { render json: @book_page, status: :created, location: @book_page }\n else\n format.html { render action: \"new\" }\n format.json { render json: @book_page.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /book_pages/1 DELETE /book_pages/1.json
def destroy @book_page = @book.book_pages.find(params[:id]) @book_page.destroy respond_to do |format| format.html { redirect_to book_series_collection_book_book_pages_url(@book_series, @collection, @book) } format.json { head :no_content } end end
[ "def destroy\n @api_book.destroy\n\n head :no_content\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 @book = Book.find(params[:id])\n @book.destroy\n \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 @book_whole.destroy\n respond_to do |format|\n format.html { redirect_to book_wholes_url }\n format.json { head :no_content }\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 deleted_books_path }\n format.json { head :no_content }\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.json { head :ok }\n end\n end", "def destroy\n @book_detail.destroy\n respond_to do |format|\n format.html { redirect_to book_details_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @book_url = BookUrl.find(params[:id])\n @book_url.destroy\n\n respond_to do |format|\n format.html { redirect_to book_urls_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @book_detail = BookDetail.find(params[:id])\n @book_detail.destroy\n\n respond_to do |format|\n format.html { redirect_to book_details_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @document_page = DocumentPage.find(params[:id])\n @document_page.destroy\n\n respond_to do |format|\n format.html { redirect_to document_pages_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mybook = Mybook.find(params[:id])\n @mybook.destroy\n\n respond_to do |format|\n format.html { redirect_to mybooks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @biblebook.destroy\n respond_to do |format|\n format.html { redirect_to biblebooks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @add_book.destroy\n respond_to do |format|\n format.html { redirect_to add_books_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @doc_page = DocPage.find(params[:id])\n @doc_page.destroy\n\n respond_to do |format|\n format.html { redirect_to doc_pages_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @book_link = BookLink.find(params[:id])\n @book_link.destroy\n\n respond_to do |format|\n format.html { redirect_to book_links_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @book_version.destroy\n respond_to do |format|\n format.html { redirect_to book_versions_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @book_det = BookDet.find(params[:id])\n @book_det.destroy\n\n respond_to do |format|\n format.html { redirect_to book_dets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @book_doc.destroy\n respond_to do |format|\n format.html { redirect_to book_docs_url, notice: 'Book doc was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @scrapbook = Scrapbook.find(params[:id])\n @scrapbook.destroy\n\n respond_to do |format|\n format.html { redirect_to scrapbooks_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove comment from GitHub and then remove from database if successful. comment_id is unique identifier within repo scope.
def remove_comment repo, comment_id response = @@connection.delete do | request | request.url "repos/#{repo}/issues/comments/#{comment_id}" request.headers['Authorization'] = "token #{@@token}" end # look for Status: 204 No Content return if response.env[:status] != 204 # Comment successfully deleted from GitHub so remove from comment.db @@db.execute "delete from comment where id == #{comment_id}" end
[ "def delete_pull_comment(repo, comment_id, options = T.unsafe(nil)); end", "def delete_pull_request_comment(repo, comment_id, options = T.unsafe(nil)); end", "def delete_pull_request_comment(repo, comment_id, options = {})\n boolean_from_response(:delete, \"#{Repository.path repo}/pulls/comments/#{comment_id}\", options)\n end", "def delete(user_name, repo_name, comment_id, params={})\n _update_user_repo_params(user_name, repo_name)\n _validate_user_repo_params(user, repo) unless user? && repo?\n _validate_presence_of comment_id\n\n normalize! params\n # _merge_mime_type(:issue_comment, params)\n\n delete_request(\"/1.0/repositories/#{user}/#{repo.downcase}/issues/comments/#{comment_id}\", params)\n end", "def delete_review_comment(repo, comment_id, options = {})\n boolean_from_response :delete, \"#{Repository.path repo}/pulls/comments/#{comment_id}\", options\n end", "def delete_commit_comment(repo, id, options = T.unsafe(nil)); end", "def remove_comment(xid,comment_id)\n post('facebook.comments.remove', :xid=>xid, :comment_id =>comment_id)\n end", "def delete_gist_comment(gist_id, gist_comment_id, options = T.unsafe(nil)); end", "def delete_comment(comment)\r\n self.comments.delete(comment)\r\n comment.delete\r\n end", "def delete_gist_comment(id, comment_id)\n boolean_request :delete, \"/gists/#{id}/comments/#{comment_id}\"\n end", "def del_comment\n @comment = ''\n end", "def delete_comment(comment_id)\n \n deleted_ones = comments.select{|c| c.id.to_s == comment_id.to_s}\n \n comments.delete_if{|c| c.id.to_s == comment_id.to_s}\n recalc_comment_count()\n\n \n deleted_ones.first()\n end", "def remove_comments\n todos = parse_todos\n write_todos(todos)\n commit('Remove comments') unless clean?\n end", "def remove_comment\n\t\t@comment = Comment.find(params[:id])\n\t\tif @comment.user_id != session[:current_user_id]\n\t\t\tredirect_to user_path(session[:current_user_id])\n\t\telse\n\t\t\t@comment.destroy\n\t\t\tredirect_to gif_path(@comment.gif_id)\n\t\tend\n\tend", "def destroy\n Dropio::Client.instance.destroy_comment(self)\n end", "def delete(comment_id, params={})\n normalize! params\n _validate_presence_of(comment_id)\n # _merge_mime_type(:gist_comment, params)\n\n delete_request(\"/gists/comments/#{comment_id}\", params)\n end", "def delete_comment(comment_id, params = nil, headers = nil)\n delete(\"/api/v2/comments/#{comment_id}\", params, headers)\n end", "def remove_highlighted_comment_id_from_commentable\n if commentable and commentable.highlighted_comment_id == id\n commentable.highlighted_comment_id = nil\n commentable.save\n end\n nil\n end", "def remove_comment comment\n return if @comments.empty?\n\n case @comments\n when Array then\n @comments.delete_if do |my_comment|\n my_comment.file == comment.file\n end\n when RDoc::Markup::Document then\n @comments.parts.delete_if do |document|\n document.file == comment.file.name\n end\n else\n raise RDoc::Error, \"BUG: unknown comment class #{@comments.class}\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2. I can find a list of exercises I did on a day
def exercise_on_a_day(date) #iterate through workouts and find workouts.user_id == self my_workouts = Workout.all.select do |workout| workout["user_id"] == self["id"] end # find where date == workout date workouts_for_date = my_workouts.find_all do |workouts| workouts["date"] == date end.map {|workout_instance| workout_instance.exercise_id} exercise_array = [] exercise_list = workouts_for_date.each do |exercise_id| Exercise.all.each do |exercise_instances| exercise_array << exercise_instances.name if (exercise_instances.id == exercise_id) end end if exercise_array == [] return "Sorry. Doesn't look like you worked out on #{date}.".colorize(:light_cyan) else return exercise_array end end
[ "def get_exercises_list\n exercises_list = []\n inst_sections.each do |inst_section|\n exercises_ids = inst_section.inst_book_section_exercises.collect(&:inst_exercise_id).compact\n exercises_objs = InstExercise.where(id: exercises_ids)\n exercises_list.concat exercises_objs.collect(&:short_name)\n end\n return exercises_list\n end", "def list_exhibits\n puts \" 1) Vangogh - Through July 2017\"\n puts \" 2) Monet - Through Oct 2018\"\n puts \" 3) Warhol- Through Nov 2018\"\n end", "def todays_exercises(user)\n todays_exercises = []\n @exercises.each do |exercise|\n if exercise.session_type == todays_session_type(user)\n todays_exercises << exercise\n end\n end\n todays_exercises.uniq\n end", "def index\n @daily_exercises = DailyExercise.all\n end", "def get_all_exercises(query: nil, page: 1, exercises: [])\n search_params = \"name=#{query}&\" if query\n query_string = \"#{search_params}page=#{page}\"\n response = get(\"exercises?#{query_string}\")\n\n return PhysitrackApi::Response.from(response) unless response.success?\n\n exercises += response['exercises']\n\n if response['exercises'].try(:size) == 200\n get_all_exercises(query: query, page: page + 1, exercises: exercises)\n else\n PhysitrackApi::Response.from(response, payload: { 'exercises' => exercises })\n end\n end", "def index\n @oncourse_exercises = OncourseExercise.all\n\n\n\n end", "def exercise_list_param\n return params[:exercises].to_a\n end", "def index\n @completed_exercises = CompletedExercise.all\n end", "def initialize\n @date = Time.now\n @exercises = Array.new\n end", "def index\n @workouts_exercises = WorkoutsExercise.all\n end", "def fetch_type name\n exercises = []\n data.exercises.each do |exe|\n if exe.target === name\n exercises.push(exe.name)\n end\n end\n exercises\n end", "def index\n @workout_exercises = WorkoutExercise.all\n end", "def select_exercise()\n #Selects the valid exercises for the user by seaching through exercises file\n valid_exercises = []\n $exercises.each do | exercise |\n if exercise[\"limited_space\"] == $settings[:space].to_s && exercise[\"difficulty\"].include?($settings[:difficulty].downcase)\n valid_exercises.push(exercise)\n end\n end\n chosen = valid_exercises.sample\n\n #Displays exercise title and instructions\n puts chosen.fetch_values(\"title\")[0].upcase\n puts $emoji_list[2] * 6\n instructions = chosen.fetch_values(\"instructions\")\n instructions[0].each_with_index do | value, index |\n puts \"#{index + 1}: #{value.to_s}\"\n end\n \n # Are you ready to start exercising?\n start = $prompt.select(\"Are you ready to start exercising?\", [\"Yes\", \"No\"])\n\n if start == \"Yes\"\n puts \"Start exercising\".upcase\n puts $emoji_list[3]\n sleep 3\n timer($settings[:exercise_time] * 60)\n interval_timer\n else\n main_menu()\n end\nend", "def randomly_select_exercise_from_todays_exercises_list(user, compound)\n subarray_to_get = 1\n if compound\n subarray_to_get = 0 #the first array is compound exercises\n end \n random_exercises = split_todays_exercises_into_compound_noncompound_arrays(user)[subarray_to_get]\n return random_exercises.sample(@number_of_exercises_to_demand) \nend", "def relevant_exercise_logs\n ExerciseLog.joins(:user).where(user_id: current_user.id, exercise_date: 1.week.ago.beginning_of_day..Time.zone.now)\n end", "def index\n @api_v1_exercises = Api::V1::Exercise.all\n end", "def index\n @assigned_exercises = AssignedExercise.where(\"user_id = ?\", current_user.id).order(\"exercise_id\")\n end", "def index\n @superset_exercises = SupersetExercise.all\n end", "def index\n @regiment_exercises = RegimentExercise.all\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
3. I can see what muscle_groups I'm working on, ON a specific day
def muscle_groups_on_given_day(date) # exercise_name = self.exercise_on_a_day(date) my_workouts = Workout.all.select do |workout| workout["user_id"] == self["id"] end # find where date == workout date workouts_for_date = my_workouts.find_all do |workouts| workouts["date"] == date end.map {|workout_instance| workout_instance.exercise_id} exercise_array = [] muscle_groups = workouts_for_date.each do |exercise| Exercise.all.each do |exercise_instances| exercise_array << exercise_instances.muscle_group if (exercise_instances.id == exercise) end end if exercise_array == [] return "Sorry. Doesn't look like you worked out on #{date}.".colorize(:light_cyan) else exercise_array end end
[ "def date_group_items; end", "def all_scheduled(db)\r\n\t\tall_array=[]\r\n\t\tall_array = db.execute(\"SELECT * FROM playgroups\")\r\n\t\tall_array.each do |i|\r\n\t\t\tputs \"Host:#{i[1]}, Location:#{i[3]}, Kids attending:#{i[2]}\"\r\n\t\tend\t\t\r\n\tend", "def scsb_edd_patron_groups\n %w[EDD]\nend", "def view_symptoms_specific_date(day)\n day_symptoms = $db.execute( <<-SQL\n SELECT * FROM symptoms\n WHERE date=\"#{day}\";\n SQL\n )\n puts \"_____________________________\"\n puts \"Symptoms that occurred on #{day}:\"\n day_symptoms.each do | symptom |\n puts \"#{symptom['symptom']}\"\n end\n puts \"_____________________________\"\nend", "def local_edd_patron_groups\n %w[PULEDD]\nend", "def update_muscle_groups groups\n groups = {} unless groups.is_a?(Hash)\n groups.symbolize_keys\n self.muscle_groups = \"\"\n Activity::MUSCLE_GROUP_VALUES.each do |name|\n bit = groups[name] == \"1\" ? \"1\" : \"0\"\n self.muscle_groups = self.muscle_groups + bit\n end\n end", "def get_group racer\n if racer && racer.birth_year && racer.gender\n #determin age as of Jan 1 on year of race; put racer in group rounded down to nearest 10 and up\n #to nearest9s; masters is 60+\n quotient=(date.year-racer.birth_year)/10\n min_age=quotient*10\n max_age=((quotient+1)*10)-1\n gender=racer.gender\n name=min_age >= 60 ? \"masters #{gender}\" : \"#{min_age} to #{max_age} (#{gender})\" #text format of groups\n Placing.demongoize(:name=>name)\n end\nend", "def week_moods(array)\n array.each do |day|\n date = day[0..4]\n puts \"#{date} #{analyze_mood(day)}\"\n end\nend", "def upcoming_musicals\n\n current_date = Time.now.strftime(\"%m/%d/%Y\")\n current_year = Time.now.strftime(\"%m/%d/%Y\")[-2,4].to_i \n\n # performances.\n upcoming_perf = performances.select { |performance| performance.date[-2,2].to_i > current_year }\n musicals = upcoming_perf.map {|performance| performance.musical}.uniq\n # binding.pry\n end", "def index\n @muscle_groups = MuscleGroup.all\n end", "def gym_day?\n if day_of_week == 'monday' || day_of_week == 'thursday'\n #add gym shoes to items\n @items << 'gym shoes'\n end\n end", "def week_of_first_visit_2\n\n @cases = Encounter.find_by_sql(['SELECT patient_id, MAX(o.value_numeric) wk FROM encounter\n INNER JOIN obs o ON o.encounter_id = encounter.encounter_id\n AND o.concept_id = ? AND encounter.voided = 0\n WHERE DATE(encounter_datetime) BETWEEN\n (select DATE(MIN(lmp)) from last_menstraul_period_date\n where person_id in (?) and obs_datetime between ? and ?)\n AND (?) AND patient_id IN (?)\n GROUP BY patient_id HAVING wk >= 13',\n WEEK_OF_FIRST_VISIT_CONCEPT.concept_id,\n @monthly_patients,\n @today.to_date.beginning_of_month.strftime(\"%Y-%m-%d 00:00:00\"),\n @today.to_date.end_of_month.strftime(\"%Y-%m-%d 23:59:59\"),\n @today.to_date, @monthly_patients]\n ).collect { |e| e.patient_id }.uniq\n @cases\n end", "def exercise_on_a_day(date)\n #iterate through workouts and find workouts.user_id == self\n my_workouts = Workout.all.select do |workout|\n workout[\"user_id\"] == self[\"id\"]\n end\n # find where date == workout date\n workouts_for_date = my_workouts.find_all do |workouts|\n workouts[\"date\"] == date\n end.map {|workout_instance| workout_instance.exercise_id}\n \n exercise_array = []\n exercise_list = workouts_for_date.each do |exercise_id|\n Exercise.all.each do |exercise_instances|\n exercise_array << exercise_instances.name if (exercise_instances.id == exercise_id)\n end\n end\n \n if exercise_array == []\n return \"Sorry. Doesn't look like you worked out on #{date}.\".colorize(:light_cyan)\n else\n return exercise_array\n end\n end", "def get_report_by_date(date, group)\n if group\n self.reports.find(:first, :conditions => [\"group_id = ? and created_date like ?\" , group.id, date.to_s + \"%\"])\n else\n self.reports.find(:first, :conditions => [\"group_id is ? and created_date like ?\" , nil, date.to_s + \"%\"])\n end\n end", "def find_show_for_today(db, day)\n\tshow_on_today = db.execute(\"SELECT show, time FROM tvshows WHERE day=?\", [day])\n\ti = 0\n\twhile i < show_on_today.length\n\t\tputs \"#{show_on_today[i][0]} is on at #{show_on_today[i][1]} on #{day}.\"\n\ti +=1\n\tend\t\nend", "def week_of_first_visit_1\n\n @cases = Encounter.find_by_sql(['SELECT patient_id, MAX(o.value_numeric) wk FROM encounter\n INNER JOIN obs o ON o.encounter_id = encounter.encounter_id\n AND o.concept_id = ? AND encounter.voided = 0\n WHERE DATE(encounter_datetime) BETWEEN\n (select DATE(MIN(lmp)) from last_menstraul_period_date\n where person_id in (?) and obs_datetime between ? and ?)\n AND (?) AND patient_id IN (?)\n GROUP BY patient_id HAVING wk < 13',\n WEEK_OF_FIRST_VISIT_CONCEPT.concept_id,\n @monthly_patients,\n @today.to_date.beginning_of_month.strftime(\"%Y-%m-%d 00:00:00\"),\n @today.to_date.end_of_month.strftime(\"%Y-%m-%d 23:59:59\"),\n @today.to_date, @monthly_patients]\n ).collect { |e| e.patient_id }.uniq\n\n @cases\n end", "def print_shows()\n\t\tputs 'SHOWS:'\n\t\t@config.get_groups.each_with_index do |group, index|\n\t\t\tputs \"#{index+1}) [#{@config[group.to_s]['finished'] == 'true' ? \"\\u2713\".encode('utf-8') : \"\\u2717\".encode('utf-8')}] #{group} #{\"\\u2799\".encode('utf-8')} s.#{@config[group.to_s]['season']} ep.#{@config[group.to_s]['episode']}\"\n\t\tend\n\tend", "def append_daily_info \r\n\t\t#date \r\n\t\t#habit(s) 1/0 \r\n\t\t#mood (1-10)\r\n\tend", "def print_daily_list(db, day)\r\n\tputs \"Chores for #{day}\"\r\n\tprint_chores = db.execute(\"SELECT chores.name, family.name FROM chores, family WHERE chores.complete_by_day = ? AND chores.family_id = family.id\", [day])\r\n\tprint_chores.each do |x|\r\n\t\tputs \"#{x[1]} : #{x[0]}\"\r\n\tend\r\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
5. I can log my weight at the end of the week
def log_my_weight(weight) self.current_weight = weight self.save puts "Current weight #{weight}" end
[ "def log_weight(weight, date, opts={})\n opts[:time] = format_time(opts[:time]) if opts[:time]\n post(\"/user/#{@user_id}/body/log/weight.json\", opts.merge(:weight => weight, :date => format_date(date)))\n end", "def weight_recently_launched(data, max_weight, equalization_period_data)\n max_weight = 1 if data.empty?\n equalization_period_data.each do |x|\n days_ago = (Date.today - x.activity_date).to_f\n handicap = (days_ago.to_f / Conductor.equalization_period).to_f\n launch_window = (Conductor.equalization_period - days_ago).to_f \n\n Conductor.log(\"Handicap for #{x.alternative} is #{handicap} (#{days_ago} days ago)\")\n data << {:name => x.alternative, :weight => max_weight * MAX_WEIGHTING_FACTOR * (1 - handicap), :launch_window => launch_window}\n end\n end", "def add_demand(date, kwh)\n return 0 unless level(date) != :off_peak\n\n if kwh > 20\n p [kwh, date, level(date)]\n end\n\n super\n end", "def log_weight(weight, date, time = nil, options = {})\n params = key_value_date_time_params('weight', weight, date, time)\n post_json(path_user_version('/body/log/weight', options), params)\n end", "def log_weight(params)\n post_call(\"user/#{user_id}/body/log/weight.json\", params)\n end", "def wday() end", "def week \n\n\t\tshortened = {\"s\"=>\"squat\", \"b\"=>\"bench\",\"d\"=>\"dead\",\"p\"=>\"press\"}\n\n\t\tputs \"Which lift you doing brah? squat, press, dead, or bench?\"\n\t\tlift = gets.chomp!\n\t\tputs \"which week brah? 1, 2, 3, or 4?\"\n\t\tweek_num = (gets.chomp!).to_i\n\n\t\tshortened.has_key?(lift) ? lift = shortened[lift] : lift = lift\n\t\t\t\n\t\tlifts_hash = open_read \n\t\tweight = (lifts_hash[lift]*0.9)\n\n\n\t\tputs \" \"\n\t\tputs \" You're doing week #{week_num} #{lift} which is currently set @ #{weight.round_to(5)}lb\"\n\n\t\tif week_num == 1\n\t\t\tputs \"************* Week #{week_num} ***********\"\n\n\t\t\t(0.45..0.85).step(0.10).each do |val|\n\t\t\t\tputs \"5 reps @ #{ (weight*val).round_to(5) } with #{ plate_calc (weight*val)} on each side\"\n\t\t\tend\n\t\t\tputs \"***********************************\"\n\n\t\telsif week_num == 2\n\t\t\tputs \" \"\n\t\t\tputs \"************* Week #{week_num} ***********\"\n\t\t\tputs \"5 reps @ #{(weight*0.5).round_to(5)} with #{plate_calc (weight*0.5)} on each side\"\n\t\t\tputs \"5 reps @ #{(weight*0.6).round_to(5)} with #{plate_calc (weight*0.6)} on each side\"\n\t\t\t(0.7..0.9).step(0.1).each do |val|\n\t\t\t\tputs \"3 reps @ #{(weight*val).round_to(5)} with #{plate_calc ((weight*val))} on each side\"\n\t\t\tend\n\t\t\tputs \"***********************************\"\n\t\t\tputs \" \"\n\n\t\telsif week_num == 3\n\t\t\tputs \" \"\n\t\t\tputs \"************* Week #{week_num} ***********\"\n\t\t\t(0.55..0.75).step(0.1).each do |val| \n\t\t\t\tputs \"5 reps @ #{(weight*val).round_to(5)} with #{plate_calc (weight*val)} on each side\" \n\t\t\tend\n\t\t\tputs \"3 reps @ #{(weight*0.85).round_to(5)} with #{plate_calc (weight*0.85)} on each side\"\n\t\t\tputs \"1 reps @ #{(weight*0.95).round_to(5)} with #{plate_calc (weight*0.95)} on each side\"\n\t\t\tputs \"***********************************\"\n\t\t\tputs \" \"\n\n\t\telsif week_num == 4\n\t\t\tputs \" \"\n\t\t\tputs \"************* Week #{week_num} ***********\"\n\t\t\t(0.2..0.6).step(0.1).each do |val|\n\t\t\t\tputs \"5 reps @ #{ (weight*val).round_to(5) } with #{ plate_calc (weight*val)} on each side\"\n\t\t\tend\n\t\t\tputs \"***********************************\"\n\t\t\tputs \" \"\n\n\n\t\t\tif lift==\"press\"\n\t\t\tupdate lifts_hash\n\t\t\tend\n\n\t\telse\n\n\t\t\tputs \"Week not provided you said #{week_num}\"\n\t\tend\n\tend", "def add_demand(date, kwh)\n return 0 unless level(date) != :off_peak\n super\n end", "def front_page_weight\n weight = 50 - 4 * ((start_time - Time.current) / 1.day).to_i\n\n case event_type\n when 'concert'\n weight += 7\n when 'theme_party'\n weight += 9\n when 'football_match', 'dj', 'quiz'\n weight += -4 * 60 # two month's worth of ban\n else\n weight += 0\n end\n\n weight += 6 if area.name == 'Storsalen'\n\n case purchase_status\n when TICKETS_SOLD_OUT\n weight += -4 * 30 # one month's worth of ban\n end\n\n case few_tickets_left?\n when true\n weight += 3\n end\n\n weight\n end", "def visit_weight visits\n Math::log(visits)\n end", "def current_week_kwh_usage\n total_week_kwh_usage_until(Time.now.utc.to_date).round(2)\n end", "def append_daily_info \r\n\t\t#date \r\n\t\t#habit(s) 1/0 \r\n\t\t#mood (1-10)\r\n\tend", "def fortnights ; self * 2.weeks ; end", "def weight_loss(db, member_id, time_frame)\n total_pounds= []\n t = DateTime.now\n past_week = ((t-6)..t).map{ |date| date.strftime(\"%m-%d\") }\n this_month = Time.now.strftime(\"%m\") \n if time_frame == \"week\"\n past_week.each do |x|\n updated_weight = db.execute(\"SELECT * FROM weight WHERE member_id='#{member_id}' AND day='#{x}' \")\n updated_weight.each do |pounds|\n total_pounds << pounds['current_weight']\n end \n end\n else \n updated_weight = db.execute(\"SELECT * FROM weight WHERE member_id='#{member_id}' AND month='#{this_month}' \")\n updated_weight.each do |pounds|\n total_pounds << pounds['current_weight']\n end \n end \n weight_loss= total_pounds.max - total_pounds.min \nend", "def calculate_calories_burned\n type = activity.activity_type\n user_weight = user.recent_most_weight.value\n user_weight = user_weight < 1 || user_weight.nil? ? 0 : user_weight\n # Our global intensity multipler\n intensity = 1 + (activity.intensity / 10)\n\n case type\n\n when 0 # Weight lifting\n self.calories = 0 and return true if work == 0\n # Calculate the joules expended\n joules = (self.work / 1000) * 9.81 * 0.75\n # Calories per rep\n per_rep = (joules * 0.000239006) * 5 # Times 5 here because 5 * 20 = 100; Muscles are roughly 20% efficient\n # Multiplier for heart rate elevation and work intensity. Default is 1.5\n # if we don't know their weight\n multiplier = user_weight == 0 ? 1.5 : 3.5 * (self.work / user_weight)\n # The full formula\n calories_burned = per_rep * reps * multiplier * intensity\n self.calories = calories_burned.round(2)\n\n when 1 # Timed things\n # Altering our intensity to work in the formula at\n # http://ask.metafilter.com/48652/Walking-formula\n intensity = intensity / 100\n intensity = intensity < 0.015 ? 0.015 : intensity\n # Convert user_weight to pounds from grams\n user_weight = user_weight * 0.00220462\n # Work here will be time in seconds\n self.calories = (intensity * user_weight * (work / 60)).round(2)\n\n when 2 # Distance\n # Credit: NET calories burned per miles as listed at\n # https://www.checkyourmath.com/convert/length/miles_mm.php\n #\n # Find our intensity. Basic running is .65, walking is .3, sprinting is\n # all the way at .8\n intensity = intensity - 1\n intensity = intensity < 0.2 ? 0.2 : intensity\n intensity = intensity > 0.8 ? 0.8 : intensity\n # Convert their weight to pounds\n user_weight = user_weight * 0.00220462\n # Convert the unit of work from mm to miles\n work_in_miles = self.work * 0.00000062\n # And finally\n self.calories = (intensity * user_weight * work_in_miles).round(2)\n\n when 3 # Repetitions\n # A VERY simple and dirty calculation here. Basically, any of these reps\n # are going to be bodyweight, ranging from ridiculously easy for even the\n # most out of shape people (like a simple crunch), to something difficult\n # for even professional athletes (dragon flags). So we'll have a baseline\n # of 1 calorie, and range up to 6 per repetition depending on the exercise's\n # intensity\n intensity = (activity.intensity / 2).round\n intensity = intensity < 1 ? 1 : intensity\n self.calories = intensity * self.reps\n else\n\n self.calories = 0\n end\n end", "def fte\n lp = learning_plans.current\n return lp ? lp.weekly_hours : 0\n end", "def battery_weight; end", "def current_day_kwh_usage\n total_day_kwh_usage_on(Time.now.utc.to_date).round(2)\n end", "def document_progress(new_weight, old_weight)\n if self.goal == \"Lose Weight\"\n self.weight_histories.create(weight_recording: (old_weight - new_weight))\n elsif self.goal == \"Gain Weight\"\n self.weight_histories.create(weight_recording: (new_weight - old_weight))\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
6. I can also find out how much I lost compared to my starting weight
def weight_lost weight_fluctuate = current_weight - start_weight if current_weight < start_weight return "Down #{weight_fluctuate}. We are making progress!" else return "Up #{weight_fluctuate}. We are making gains!" end end
[ "def remaining_pints\n ((current_weight-14.25)/0.45).to_i > 0 ? ((current_weight-14.25)/0.45).to_i : 0\n end", "def weight_until_goal\n if weigh_ins.count > 0 && goal_weight > 0\n weigh_ins.first.current_weight - goal_weight\n elsif goal_weight > 0\n start_weight - goal_weight\n end\n end", "def calc_total_weight\n 0\n end", "def currentWeight() weighins.last.weight end", "def total_weight\n @total_weight ||= hypotheses.inject( 0 ) { |sum,h| sum + h.weight }\n end", "def covered_strength; end", "def wilksMensKG(bodyweight,total)\n wilks = total * 500 / (-216.0475144 + 16.2606339 * bodyweight - 0.002388645 * bodyweight**2 - 0.00113732 * bodyweight**3 + 0.00000701863 * bodyweight**4 - 0.00000001291 * bodyweight**5)\n puts wilks\nend", "def cost_of_stay\n num_of_nights * 200.00\n end", "def wilksWomensKG(bodyweight, total):\n wilks = total * 500 / (594.31747775582 - 27.23842536447 * bodyweight - 0.82112226871 * bodyweight**2 - 0.00930733913 * bodyweight**3 + 0.00004731582 * bodyweight**4 - 0.00000009054 * bodyweight**5)\n puts wilks\nend", "def calculate_weight_diffs\n weight_diff = 0.0\n rebin_weight = self.pool_graded_rebins.sum('graded_weight') || 0.0\n carton_weight = self.pool_graded_cartons.sum('schedule_weight') || 0.0\n\n weight_diff = self.bin_mass - (rebin_weight + carton_weight)\n weight_diff = 0.0 if (weight_diff.abs < 1.0)\n\n return weight_diff, rebin_weight, carton_weight\n end", "def weight\n if @weight\n @weight\n else\n @confines.length\n end\n end", "def wins\n need + greed\n end", "def battery_weight; end", "def losses_points\n pts = ( ( unit.amount - unit.remains ) * unit.massacre_points ).ceil.to_i\n\n if unit.remains == 0\n pts += unit.legendary ? 4 : 1\n end\n\n pts\n end", "def bmi\n (weight/(height*height).to_f)*703\n end", "def total_weight\n\t\tcargo_weight = 0\n\t\t@inventory.each do |object, location|\n\n\t\t\tcargo_weight += item_weight(object)\n\n\t\tend\n\t\tputs \"\\n\\n **Your cargo weighs #{cargo_weight} roddenberries!**\"\n\t\tcargo_weight\n\tend", "def ballsbowled\n 6 * overs.floor(0) + (overs - overs.floor(0)) * 10\n end", "def calc_weight(mod, acc)\n fuel = calc_fuel(mod)\n fuel <= 0 ? acc : calc_weight(fuel, acc + fuel)\nend", "def weight\n decay_conversation # fade the conversation since the last time we spoke\n incoming_weight + outgoing_weight\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
8. A user can create a new exercise to add to the database
def create_new_exercise(exercise, muscle_group) Exercise.create(name: exercise, muscle_group: muscle_group) puts "Thank you for sharing!" end
[ "def add_exercise(name, description)\n sql = \"INSERT INTO exercises (name, description) VALUES ($1, $2);\"\n query(sql, name, description)\n end", "def create_exercise()\n\n #Gets all the information from the user\n message(\"Please enter a name for this new exercise: \")\n name = gets.chomp\n message(\"Please enter a description for \" + name)\n description = gets.chomp\n message(\"Please enter a duration (in seconds) for \" + name)\n duration = gets.chomp\n\n #Creates the exercise object and places it in last_built temporarily\n @last_built = Exercise.new(name,description,duration)\n\n #Outputs the details of the object\n message(\"Please confirm that this information is correct:\")\n puts \"Name: \" + name\n puts \"Description: \" + description\n puts \"Duration (sec): \" + duration\n\n #Confirmation dialog\n continue = confirm(\"Would you like to add this exercise to the database? (Y/N)\")\n if continue == true\n #Places the built object into the database\n $database.add_new(\"exercise\", @last_built)\n return\n elsif continue == false\n #Discards the built object\n return\n end\n end", "def add_exercise(db)\n puts \"What is the name of the exercise you want to add?\"\n exercise = gets.chomp\n if is_existing_exercise(db, exercise)\n puts \"#{exercise} is already in the database.\"\n else\n db.execute(\"INSERT INTO exercises (name) VALUES (?)\", [name])\n puts \"#{exercise} was added to the database.\"\n end\nend", "def add_an_exercise\n p \"What body part is this exercise for? enter: 1 for arms, 2 for legs, 3 for shoulders, 4 for back\"\n x = gets.chomp.to_i\n p \"What is the exercise?\"\n name = gets.chomp\n p \"What about the reps?\"\n reps = gets.chomp\n if x == 1\n @db.execute(\"INSERT INTO arm_exercises (name, reps) VALUES (?, ?)\", [name, reps])\n elsif x == 2\n @db.execute(\"INSERT INTO leg_exercises (name, reps) VALUES (?, ?)\", [name, reps])\n elsif x == 3\n @db.execute(\"INSERT INTO shoulder_exercises (name, reps) VALUES (?, ?)\", [name, reps])\n elsif x == 4\n @db.execute(\"INSERT INTO shoulder_exercises (name, reps) VALUES (?, ?)\", [name, reps])\n else\n p \"invalid entry\"\n end\nend", "def add_exercises(exercise)\n @exercises << exercise\n end", "def create\n @exercise = Exercise.new(params[:exercise])\n\n respond_to do |format|\n if @exercise.save\n format.html { redirect_to @exercise, :notice => 'exercise was successfully created.' }\n format.json { render :json => @exercise, :status => :created, :location => @exercise }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @exercise.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @exercise = Exercise.new(params[:exercise])\n\n respond_to do |format|\n if @exercise.save\n format.html { redirect_to @exercise, notice: 'Exercise was successfully created.' }\n format.json { render json: @exercise, status: :created, location: @exercise }\n else\n format.html { render action: \"new\" }\n format.json { render json: @exercise.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @title = 'Add Exercise'\n @exercise = Exercise.new\n @exercise.exercise_category = ExerciseCategory.new\n end", "def create\n @exercise = Exercise.new(params[:exercise])\n\n respond_to do |format|\n if @exercise.save\n format.html { redirect_to(@exercise, :notice => 'Exercise was successfully created.') }\n format.xml { render :xml => @exercise, :status => :created, :location => @exercise }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @exercise.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @exercise = Exercise.new(params[:exercise])\n\n respond_to do |format|\n if @exercise.save\n flash[:notice] = 'Exercise was successfully created.'\n format.html { redirect_to(exercises_url) }\n format.xml { render :xml => @exercise, :status => :created, :location => @exercise }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @exercise.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @exercise = Exercise.new\n end", "def addExistingExercise\n @workout_day = WorkoutDay.find(params[:id])\n exerciseId = params[:exercise][:id]\n\n exercise = Exercise.find(exerciseId)\n\n if !exercise.nil?\n @workout_day.exercises << exercise\n end\n\n @workout_day.save\n\n respond_to do |format|\n format.html { redirect_to @workout_day, notice: 'Exercise successfully added' }\n format.json { render json: @workout_day, status: :created, location: @workout_day }\n end\n end", "def create\n @exercise = Exercise.new(exercise_params)\n\n if @exercise.save\n render :show, status: :created\n else\n render json: @exercise.errors, status: :unprocessable_entity\n end\n end", "def create\n @my_exercise = MyExercise.new(params[:my_exercise])\n\n respond_to do |format|\n if @my_exercise.save\n flash[:notice] = 'MyExercise was successfully created.'\n format.html { redirect_to(@my_exercise) }\n format.xml { render :xml => @my_exercise, :status => :created, :location => @my_exercise }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @my_exercise.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @exercise_entry = ExerciseEntry.new(params[:exercise_entry])\n\n respond_to do |format|\n if @exercise_entry.save\n format.html { redirect_to @exercise_entry, notice: 'Exercise entry was successfully created.' }\n format.json { render json: @exercise_entry, status: :created, location: @exercise_entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @exercise_entry.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_question\n @event.respond('Enter a new question: ')\n ques = @event.user.await!(timeout: 60)\n return open_channel if ques.nil?\n\n ques = ques.content\n @event.respond('Enter the answer: ')\n ans = @event.user.await!(timeout: 60)\n return open_channel if ans.nil?\n\n ans = ans.content.gsub(/\\W/, '').downcase # Clean up the answer by removing caps and non [a-z] [0-9] chars\n @event.respond('Commit to database? (y/n): ')\n prompt = @event.user.await!(timeout: 60)\n unless prompt.nil? || prompt.content != 'y'\n begin\n @@trivia_db.prepare('INSERT INTO trivia(question, answer, addedby) VALUES(?, ?, ?)').execute(ques, ans, @event.user.id)\n rescue SQLite3::Exception\n @event.respond('Unable to write to database!')\n else\n @event.respond('Changes saved')\n end\n end\n open_channel\n end", "def create\n @exercise_instruction = ExerciseInstruction.new(params[:exercise_instruction])\n @exercise_instruction.user_id = current_user.id\n\n respond_to do |format|\n if @exercise_instruction.save\n format.html { redirect_to @exercise_instruction.exercise, notice: 'Note was successfully created.' }\n format.json { render json: @exercise_instruction, status: :created, location: @exercise_instruction }\n else\n format.html { render action: \"new\" }\n format.json { render json: @exercise_instruction.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @api_v1_exercise = Api::V1::Exercise.new(api_v1_exercise_params)\n\n respond_to do |format|\n if @api_v1_exercise.save\n format.html { redirect_to @api_v1_exercise, notice: 'Exercise was successfully created.' }\n format.json { render :show, status: :created, location: @api_v1_exercise }\n else\n format.html { render :new }\n format.json { render json: @api_v1_exercise.errors, status: :unprocessable_entity }\n end\n end\n end", "def add_input (db, user_input)\r\n db.execute(\"INSERT INTO strength (date, exercise, weight, reps, minutes, difficult) VALUES (?, ?, ?, ?, ?, ?)\", [user_input])\r\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
7. a user can log a new workout
def log_new_workout(exercise, date) exercise_check = Exercise.search_exercise_by_name(exercise) exercise_instance = Exercise.all.find{|exercises| exercises.name == exercise} if exercise_check == "Sorry. We don't have any workouts called #{exercise}. Please return to the main menu to create this new exercise and share with the rest of our FitMePan crew." return exercise_check else Workout.create(user_id: self.id, exercise_id: exercise_instance.id, date: date) end puts "Thanks for logging your workout!" end
[ "def create\n @logged_workout = LoggedWorkout.new(logged_workout_params)\n @logged_workout.user = current_user\n\n respond_to do |format|\n if @logged_workout.save\n format.html { redirect_to @logged_workout, notice: \"Logged workout was successfully created.\" }\n format.json { render :show, status: :created, location: @logged_workout }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @logged_workout.errors, status: :unprocessable_entity }\n end\n end\n end", "def checkin\n if self.current_user == nil\n redirect_to \"/account/login\"\n end\n @workout = Workout.new\n @workout.workout_date = Time.now.to_date #.strftime(\"%x\")\n end", "def after_save workout_session\r\n Rails.logger.debug \"User #{workout_session.user} created session #{workout_session.attributes.inspect}\"\r\n end", "def check_work_user\n owner = Work.friendly.find(params[:id]).user\n unless owner == current_user || current_user.is_admin?\n store_location\n flash[:error] = 'You are not authorized to perform this action.'\n redirect_to login_path\n end\n end", "def save\n @workout = Workout.new(params[:workout])\n #@workout.user_profile_id = self.current_user.id\n if @workout.save\n redirect_to \"/myworkouts/#{@workout.id}\"\n else\n render :action => 'checkin' #{@workout.id}\"\n end\n end", "def check_my_work\n if (!is_admin? && (Work.find(params[:id]).user != current_user))\n flash[:notice] = \"Not your work\"\n redirect_to tasks_url()\n end\n end", "def create\n @user_workout = UserWorkout.new(user_workout_params)\n @user_workout.user_id = current_user.id\n\n respond_to do |format|\n if @user_workout.save\n current_user.userworkouts << @user_workout\n format.html { redirect_to @user_workout, notice: 'User workout was successfully created.' }\n format.json { render action: 'show', status: :created, location: @user_workout }\n else\n format.html { render action: 'new' }\n format.json { render json: @user_workout.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\tputs \"Creating workout with '#{params[:workout]}'\"\n\t\t\t\n\t\t# Make sure the workout name passed to the controller is valid\n\t\tif params[:workout][:name].length > 20 || params[:workout][:name].length < 5 || params[:workout][:name].index(/[^\\w\\s]/)\n\t\t\tflash[:notice] = \"Workout Name Invalid\"\n\t\t\tredirect_to :action => \"new\"\n\t\tend\n\n\t\t# Create new workout with specified name and then assign the new\n\t\t# workout to the current user\n\t\tw = Workout.new(:name => params[:workout][:name])\n\t\tw.user = User.find(session[:user_id])\n\t\tw.save\n\n\t\tif w.save\n\t\t\tredirect_to :action => \"edit\", :id => w.id\n\t\telse\n\t\t\tputs \"Error while saving workout\"\n\t\t\tredirect_to :controller => \"home\", :action => \"index\"\n\t\tend\n \tend", "def record_work_edit_history(work, user)\n history = work.histories.create()\n history.user = user\n history.save\n end", "def create\n @workoutlog = current_client.workoutlogs.create(workoutlog_params)\n respond_to do |format|\n if @workoutlog.save\n format.html { redirect_to clients_path, notice: 'Workoutlog was successfully created.' }\n format.json { render :show, status: :created, location: @workoutlog }\n else\n format.html { render :new }\n format.json { render json: @workoutlog.errors, status: :unprocessable_entity }\n end\n end\n end", "def log_workout(db, name, duration, calories, type)\n db.execute(\"INSERT INTO workout_log (name, workout_duration, calories_burned, workout_type) VALUES (?,?,?,?)\",[name, duration, calories, type])\nend", "def check_workstation_head\n redirect_to appointments_path, alert: \"Workstation heads may not modify appointments.\" unless current_user.admin || current_user.house.name != 'Workstations'\n end", "def log_in\n end", "def create\n @workout_logging = WorkoutLogging.new(workout_logging_params)\n\n respond_to do |format|\n if @workout_logging.save\n format.html { redirect_to @workout_logging, notice: 'Workout logging was successfully created.' }\n format.json { render :show, status: :created, location: @workout_logging }\n else\n format.html { render :new }\n format.json { render json: @workout_logging.errors, status: :unprocessable_entity }\n end\n end\n end", "def login_instructions\n end", "def workout_program(user)\n return workout_summary(user) if user.started?\n start_workout(user)\n end", "def log_edits_on = self", "def update_workouts_and_new_workoutpoint\n if logged_in?\n correct_workout_nil\n @user.workouts += 1\n @user.save\n @workoutpoint = @user.workoutpoints.build(workout_point: 1)\n @workoutpoint.save\n render(json: { message: \"Workouts increased\" }, status: :ok) and return\n else \n render(json: { message: \"Workouts increased\" }, status: :ok) and return\n end\n end", "def new\n #@workout = Workout.new\n @workout = current_user.workouts.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @workout }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /internships/1 GET /internships/1.json
def show @internship = Internship.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @internship } end end
[ "def index\n @internships = Internship.all\n end", "def index\n @internships = Internship.all\n @current_user = User.find(current_user.id)\n respond_with(@internships)\n end", "def show\n @internships_user = InternshipsUser.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @internships_user }\n end\n end", "def index\n @active_internships = Internship.active\n @expired_internships = Internship.expired\n @my_internships = current_user.internships\n end", "def internships\n respond_to do |format|\n format.html # internships.html.erb\n format.xml { render :xml => nil }\n end\n end", "def create\n @internship = current_user.internships.new(internship_params)\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to internships_url, notice: 'Internship was successfully created.' }\n else\n format.html { render action: 'new' }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @interns = Intern.all\n render_json_serializer(@interns)\n end", "def index\n @clientships = current_user.clientships.all \n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @clientships }\n end\n end", "def new\n @internship = Internship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @internship }\n end\n end", "def show\n @internships_task = InternshipsTask.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @internships_task }\n end\n end", "def show\n @internship = Internship.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @internship }\n end\n end", "def show\n @clientship = current_user.clientships.find(params[:id]) \n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @clientship }\n end\n end", "def index\n @assigned_ships = AssignedShip.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @assigned_ships }\n end\n end", "def show\r\n @intern_request = InternRequest.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @intern_request }\r\n end\r\n end", "def create\n @user = current_user\n @internship = @user.internships.build(params[:internship])\n #@internship = Internship.new(params[:internship])\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to @internship, notice: 'Internship was successfully created.' }\n format.json { render json: @internship, status: :created, location: @internship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @internships_user = InternshipsUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @internships_user }\n end\n end", "def show\r\n @internship_location = InternshipLocation.find(params[:id])\r\n\r\n respond_to do |format|\r\n format.html # show.html.erb\r\n format.json { render json: @internship_location }\r\n end\r\n end", "def new\n @internship = Internship.new\n @companies = Company.all\n @situations = Situation.all\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @internship }\n end\n end", "def index\n @fellowships = Fellowship.all\n\n render json: @fellowships\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /internships/new GET /internships/new.json
def new @internship = Internship.new respond_to do |format| format.html # new.html.erb format.json { render json: @internship } end end
[ "def create\n @internship = current_user.internships.new(internship_params)\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to internships_url, notice: 'Internship was successfully created.' }\n else\n format.html { render action: 'new' }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @internships_user = InternshipsUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @internships_user }\n end\n end", "def new\n @internship = Internship.new\n @companies = Company.all\n @situations = Situation.all\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @internship }\n end\n end", "def create\n @user = current_user\n @internship = @user.internships.build(params[:internship])\n #@internship = Internship.new(params[:internship])\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to @internship, notice: 'Internship was successfully created.' }\n format.json { render json: @internship, status: :created, location: @internship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to @internship, notice: 'Internship was successfully created.' }\n format.json { render json: @internship, status: :created, location: @internship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\r\n @intern_request = InternRequest.new\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @intern_request }\r\n end\r\n end", "def new\n @internships_task = InternshipsTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @internships_task }\n end\n end", "def new\n @assigned_ship = AssignedShip.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @assigned_ship }\n end\n end", "def new\r\n @internship_location = InternshipLocation.new\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @internship_location }\r\n end\r\n end", "def new\n @internship_instance = InternshipInstance.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @internship_instance }\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n @companies = Company.all\n @situations = Situation.all\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to @internship, :notice => 'Internship was successfully created.' }\n format.json { render :json => @internship, :status => :created, :location => @internship }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @internship = Internship.new\n @user = current_user if current_user\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @internship }\n end\n end", "def new\n \n @ship = Ship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ship }\n end\n end", "def new\n \t@internship_position = InternshipPosition.new\n\n \trespond_to do |format|\n \t\tformat.html #new.html.erb\n \t\tformat.json { render json: @internship_position }\n \tend\n end", "def create\n @internship = Internship.new(params[:internship])\n \n respond_to do |format|\n if @internship.save\n format.html { redirect_to(@internship, :notice => 'Internship was successfully created.') }\n format.xml { render :xml => @internship, :status => :created, :location => @internship }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @ship = Ship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ship }\n end\n end", "def new\n @spaceship = Spaceship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @spaceship }\n end\n end", "def create\n @intern = Intern.new(intern_params)\n\n respond_to do |format|\n if @intern.save\n format.html { redirect_to @intern, notice: 'Intern was successfully created.' }\n format.json { render :show, status: :created, location: @intern }\n else\n format.html { render :new }\n format.json { render json: @intern.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n @internship.user_id = current_user.id\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to(internships_path, :notice => 'Internship was successfully created.') }\n format.xml { render :xml => @internship, :status => :created, :location => @internship }\n else\n flash[:error] = @internship.errors.full_messages.join(\"<br>\")\n format.html { render :action => \"new\" }\n format.xml { render :xml => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /internships POST /internships.json
def create @internship = Internship.new(params[:internship]) respond_to do |format| if @internship.save format.html { redirect_to @internship, notice: 'Internship was successfully created.' } format.json { render json: @internship, status: :created, location: @internship } else format.html { render action: "new" } format.json { render json: @internship.errors, status: :unprocessable_entity } end end end
[ "def create\n @internship = current_user.internships.new(internship_params)\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to internships_url, notice: 'Internship was successfully created.' }\n else\n format.html { render action: 'new' }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user = current_user\n @internship = @user.internships.build(params[:internship])\n #@internship = Internship.new(params[:internship])\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to @internship, notice: 'Internship was successfully created.' }\n format.json { render json: @internship, status: :created, location: @internship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n @companies = Company.all\n @situations = Situation.all\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to @internship, :notice => 'Internship was successfully created.' }\n format.json { render :json => @internship, :status => :created, :location => @internship }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n \n respond_to do |format|\n if @internship.save\n format.html { redirect_to(@internship, :notice => 'Internship was successfully created.') }\n format.xml { render :xml => @internship, :status => :created, :location => @internship }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n @internship.user_id = current_user.id\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to(internships_path, :notice => 'Internship was successfully created.') }\n format.xml { render :xml => @internship, :status => :created, :location => @internship }\n else\n flash[:error] = @internship.errors.full_messages.join(\"<br>\")\n format.html { render :action => \"new\" }\n format.xml { render :xml => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @intern = Intern.new(intern_params)\n\n if @intern.save\n render_json_message({:success => t('.success')}, 201, {id: @intern.id})\n else\n render_json_message({:errors => @intern.errors.messages}, 422)\n end\n\n end", "def create\n @intern = Intern.new(intern_params)\n\n respond_to do |format|\n if @intern.save\n format.html { redirect_to @intern, notice: 'Intern was successfully created.' }\n format.json { render :show, status: :created, location: @intern }\n else\n format.html { render :new }\n format.json { render json: @intern.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @internships_user = InternshipsUser.new(params[:internships_user])\n\n respond_to do |format|\n if @internships_user.save\n format.html { redirect_to @internships_user, :notice => 'Internships user was successfully created.' }\n format.json { render :json => @internships_user, :status => :created, :location => @internships_user }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @internships_user.errors, :status => :unprocessable_entity }\n end\n end\n end", "def index\n @internships = Internship.all\n end", "def index\n @internships = Internship.all\n @current_user = User.find(current_user.id)\n respond_with(@internships)\n end", "def new\n @internship = Internship.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @internship }\n end\n end", "def internships\n respond_to do |format|\n format.html # internships.html.erb\n format.xml { render :xml => nil }\n end\n end", "def new\n @internships_user = InternshipsUser.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @internships_user }\n end\n end", "def create\n @internship_instance = InternshipInstance.new(params[:internship_instance])\n\n respond_to do |format|\n if @internship_instance.save\n format.html { redirect_to(@internship_instance, :notice => 'Internship instance was successfully created.') }\n format.xml { render :xml => @internship_instance, :status => :created, :location => @internship_instance }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @internship_instance.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @game = Game.find(params[:game_id])\n @game.authorships.create_from_names(params[:authorship])\n respond_to do |format|\n flash[:notice] = 'Les autheurs sont enregistres'\n format.html { redirect_to game_path(@game) }\n format.xml { head :created, :location => authorship_url(@authorship) }\n end\n end", "def create\r\n @intern_request = InternRequest.new(params[:intern_request])\r\n\r\n respond_to do |format|\r\n if @intern_request.save\r\n format.html { redirect_to @intern_request, notice: 'Intern request was successfully created.' }\r\n format.json { render json: @intern_request, status: :created, location: @intern_request }\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @intern_request.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def new\n @internship = Internship.new\n @companies = Company.all\n @situations = Situation.all\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @internship }\n end\n end", "def create\n @internships_task = InternshipsTask.new(params[:internships_task])\n\n respond_to do |format|\n if @internships_task.save\n format.html { redirect_to @internships_task, :notice => 'Internships task was successfully created.' }\n format.json { render :json => @internships_task, :status => :created, :location => @internships_task }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @internships_task.errors, :status => :unprocessable_entity }\n end\n end\n end", "def index\n @active_internships = Internship.active\n @expired_internships = Internship.expired\n @my_internships = current_user.internships\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /internships/1 PUT /internships/1.json
def update @internship = Internship.find(params[:id]) respond_to do |format| if @internship.update_attributes(params[:internship]) format.html { redirect_to @internship, notice: 'Internship was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @internship.errors, status: :unprocessable_entity } end end end
[ "def update\n respond_to do |format|\n if @internship.update(internship_params)\n format.html { redirect_to internships_url, notice: 'Internship was successfully updated.' }\n else\n format.html { render action: 'edit' }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @internship = current_user.internships.new(internship_params)\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to internships_url, notice: 'Internship was successfully created.' }\n else\n format.html { render action: 'new' }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @internship = Internship.find(params[:id])\n respond_to do |format|\n if @internship.update_attributes(params[:internship])\n format.html { redirect_to(@internship, :notice => 'Internship was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @intern = Intern.find(params[:id])\n\n respond_to do |format|\n if @intern.update_attributes(params[:intern])\n format.html { redirect_to @intern, notice: 'Intern was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @intern.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @user = current_user\n @internship = @user.internships.build(params[:internship])\n #@internship = Internship.new(params[:internship])\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to @internship, notice: 'Internship was successfully created.' }\n format.json { render json: @internship, status: :created, location: @internship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n if @intern.update(intern_params)\n render_json_message({success: t('.success')}, 200)\n else\n render_json_message({errors: @intern.errors.messages}, 422)\n end\n end", "def update\n respond_to do |format|\n if @intern.update(intern_params)\n format.html { redirect_to @intern, notice: 'Intern was successfully updated.' }\n format.json { render :show, status: :ok, location: @intern }\n else\n format.html { render :edit }\n format.json { render json: @intern.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @internships_user = InternshipsUser.find(params[:id])\n\n respond_to do |format|\n if @internships_user.update_attributes(params[:internships_user])\n format.html { redirect_to @internships_user, :notice => 'Internships user was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @internships_user.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to @internship, notice: 'Internship was successfully created.' }\n format.json { render json: @internship, status: :created, location: @internship }\n else\n format.html { render action: \"new\" }\n format.json { render json: @internship.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @internship_instance = InternshipInstance.find(params[:id])\n\n respond_to do |format|\n if @internship_instance.update_attributes(params[:internship_instance])\n format.html { redirect_to(@internship_instance, :notice => 'Internship instance was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @internship_instance.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\r\n @intern_request = InternRequest.find(params[:id])\r\n\r\n respond_to do |format|\r\n if @intern_request.update_attributes(params[:intern_request])\r\n format.html { redirect_to @intern_request, notice: 'Intern request 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: @intern_request.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def update\n @internships_task = InternshipsTask.find(params[:id])\n\n respond_to do |format|\n if @internships_task.update_attributes(params[:internships_task])\n format.html { redirect_to @internships_task, :notice => 'Internships task was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @internships_task.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @internship_committee.update(internship_committee_params)\n format.html { redirect_to @internship_committee, notice: 'Internship committee was successfully updated.' }\n format.json { render :show, status: :ok, location: @internship_committee }\n else\n format.html { render :edit }\n format.json { render json: @internship_committee.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @clientship = current_user.clientships.find(params[:id])\n\n respond_to do |format|\n if @clientship.update_attributes(params[:clientship])\n format.html { redirect_to @clientship, notice: 'Clientship was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @clientship.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n @companies = Company.all\n @situations = Situation.all\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to @internship, :notice => 'Internship was successfully created.' }\n format.json { render :json => @internship, :status => :created, :location => @internship }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n \n respond_to do |format|\n if @internship.save\n format.html { redirect_to(@internship, :notice => 'Internship was successfully created.') }\n format.xml { render :xml => @internship, :status => :created, :location => @internship }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def destroy\n @internship = Internship.find(params[:id])\n @internship.destroy\n\n respond_to do |format|\n format.html { redirect_to internships_url }\n format.json { head :no_content }\n end\n end", "def create\n @internship = Internship.new(params[:internship])\n @internship.user_id = current_user.id\n\n respond_to do |format|\n if @internship.save\n format.html { redirect_to(internships_path, :notice => 'Internship was successfully created.') }\n format.xml { render :xml => @internship, :status => :created, :location => @internship }\n else\n flash[:error] = @internship.errors.full_messages.join(\"<br>\")\n format.html { render :action => \"new\" }\n format.xml { render :xml => @internship.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @assigned_ship = AssignedShip.find(params[:id])\n\n respond_to do |format|\n if @assigned_ship.update_attributes(params[:assigned_ship])\n format.html { redirect_to @assigned_ship, notice: 'Assigned ship was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @assigned_ship.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns an array with coordinates of the 1's
def find_ones ones_arr = [] @image.each_index do |row| @image[row].each_index do |column| if @image[row][column] == 1 ones_arr << { :x => column, :y => row } end end end return ones_arr end
[ "def find_ones\n # @image.each { |row| row.each { |pixel| ... } }\n cords = []\n\n\n @image.each_with_index do |row, row_index|\n # row = [0, 1, 0, 0]\n # puts \"#{row_index} - ROW\"\n row.each_with_index do |pixel, column_index|\n # pixel = 0\n # puts \"#{column_index} - COLUMN\"\n if pixel == 1\n # save the coordinates\n cords << [row_index, column_index]\n end\n end\n end\n\n #puts cords.inspect\n cords\n end", "def coord_to_array(coordinates)\n x = coordinates[1]\n y = coordinates[0]\n conversion = ((x-1) * @size) + (y -1)\n end", "def find_ones\n ones_locations = []\n # => finding index of ROW and COL for each 1 in grid and storing as row/col array pairs\n @image_array.each_index do |row|\n @image_array[row].each_index do |col|\n if @image_array[row][col] == 1\n puts \"#{row}, #{col}\" # <---this is just to display that it's working, can be removed\n ones_locations << [row, col]\n end\n end\n end\n return ones_locations\n end", "def find_ones\n # => Establish an empty array to hold the index positions of all the 1s\n ones_ary = []\n # => Finding the index of ROW and COL for each 1 in the grid and storing\n # => them as row/col array pairs\n\n # => |row| denotes the top-level array (could be named anything)\n @image_array.each_index do |row|\n # => |col| is the chosen variable name for the inner array\n @image_array[row].each_index do |col|\n if @image_array[row][col] == 1\n puts \"#{row}, #{col}\"\n ones_ary << [row, col]\n end\n end\n end \n return ones_ary\n end", "def pos_to_a\r\n [ pos.x, pos.y ]\r\n end", "def to_array\n @points.collect { |p| [p.x, p.y] }\n end", "def get_pixels\r\n\t\tpixels_on = []\r\n\t\t@image.each.with_index do |row, row_index|\r\n\t\t\trow.each.with_index do |pixel, col_index|\r\n\t\t\t\tif pixel == 1\r\n\t\t\t\t\tpixels_on.push [row_index, col_index]\r\n\t\t\t\tend\r\n\t\t\tend\r\n\t\tend\r\n\t\tpixels_on\t\r\n\tend", "def coordinates\n [@x, @y]\n end", "def coords\n coord_list = []\n (@x..(@x + @size_x - 1)).each do |i|\n (@y..(@y + @size_y - 1)).each do |j|\n coord = [i, j]\n coord_list << coord\n end\n end\n\n return coord_list\n end", "def pos\n return [@x, @y]\n end", "def coordinates_to_indices(x, y)\n [x - 1, y - 1]\n end", "def coordinates(image)\n image.each_with_index.flat_map do |row,x|\n (0...row.length).find_all{|i| row[i] == @char }.map{|y| [x,y] }\n end\n end", "def neighbours point\n [\n [-1, 0],\n [1, 0],\n [0, 1],\n [0, -1]\n ].map do |(dx, dy)|\n [\n (point[0] + dx + @map.length) % @map.length,\n (point[1] + dy + @map.length) % @map.length\n ]\n end\n end", "def as_array\n region.rings.first.points.map {|p| [p.lat, p.lng]}\n end", "def initial_coordinates\n return 10, -28\n end", "def mineLocation field\n coords = []\n field.each_index do | i |\n field[i].each_index do | j |\n if field[i][j] == 1\n coords << i\n coords << j\n end\n end\n end\n coords\nend", "def y_points\n points = []\n (0...width).each do |x|\n (0...height).reverse_each do |y|\n if (array[y][x]).nonzero? && (y + 1 >= height || (array[y + 1][x]).zero?)\n points << Point.new(x, y + 1) + @position\n end\n end\n end\n\n points\n end", "def get_single_coord\n Matrix.two_to_one(@x_location, @y_location, @x_size)\n end", "def coords\n [x, y]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if pixel to set within bounds and sets to 1
def set_to_one(coords) if (0..@max_x).include?(coords[:x]) && (0..@max_y).include?(coords[:y]) @image[coords[:y]][coords[:x]] = 1 end end
[ "def set_pixel_if_within_bounds(x, y, color); end", "def set_pixel_if_within_bounds(x, y, color)\n return unless include_xy?(x, y)\n @pixels[y * width + x] = color\n end", "def restricted?(x, y)\n out_of_bounds?(x, y) || @image.color(x, y) == 0\n end", "def outside_curr_image_bounds?(row, col)\n if row <= 0 or row > @rows\n true\n elsif col <= 0 or col > @cols\n true\n else\n false\n end\n end", "def check_bounds\n\t\tif @x + SUB_TILE_WIDTH > @game_state.width\n\t\t\tupdate_x( -(@x + SUB_TILE_WIDTH - @game_state.width) )\n\t\telsif @x < 0\n\t\t\tupdate_x( @x.abs )\n\t\tend\n\t\tif @y + SUB_TILE_HEIGHT > @game_state.height\n\t\t\tupdate_y( -(@y + SUB_TILE_HEIGHT - @game_state.height) )\n\t\telsif @y < 0\n\t\t\tupdate_y( @y.abs )\n\t\tend\n\tend", "def check_limits_on_x_and_y\n\t\tself.x = self.window.limit_max_x if x > self.window.limit_max_x \n\t\tself.y = self.window.limit_min_y if y > self.window.limit_max_y \n\tend", "def coordinate_within_bounds?(x, y)\n x < @width && x >= 0 && y < @height && y >= 0\n end", "def _inbounds(val,rowCol,board)\n if rowCol\n return (val >=0 and val < board.getWidth)\n end\n return (val >= 0 and val < board.getHeight)\n end", "def in_bounds?\n @to[:x] >= 0 &&\n @to[:y] >= 0 &&\n @to[:x] < Constants.board_size &&\n @to[:y] < Constants.board_size\n end", "def pixel_range?(px,py)\n #puts \"#{@cx} #{@cy}\"\n #puts \"#{@x},#{@y};#{px},#{py}; #{(@px - px).abs <= @cx && (@py - py).abs <= @cy}\"\n #puts \"#{@x},#{@y};#{px/4},#{py/4}; #{(@x - px/4).abs <= 1 && (@py - py/4).abs <= 1}\"\n #return (@x - px/4).abs <= 1 && (@py - py/4).abs <= 1\n return (@px - px).abs <= @cx && (@py - py).abs <= @cy\n end", "def skip_bounds?(x,y)\n\t\tx> 513 && y < 50 \n\tend", "def pixel? = unit == 'pixel'", "def in_bounds?(x, y)\n return false if x.to_i < 0\n return false if y.to_i < 0\n\n x.to_i < cols && y.to_i < rows\n end", "def check_grid_coordinates(x, y)\n (x >= 0) && (x < @height) && (y >= 0) && (y < @width)\n end", "def outofBounds\n\t\tif @x > @window.width || @y > @window.height || @x < 0 || @y < 0 then\n\t\t\treturn true\n\t\tend\n\t\treturn false\n\tend", "def outside_x_bounds?(x, w)\n\t\tx + w < 0 || x > @width\n\tend", "def outofbounds?(box)\n box[0] < 0 || box[0] >= CHECKERS_HEIGHT || box[1] < 0 || box[1] >= CHECKERS_WIDTH\n end", "def contains_x(x)\n\t\t@x <= x && x <= (@x + @bg_width)\n\tend", "def bound_in_rect(rect)\n result = rect\n if rect.x < 0\n result.width = rect.width - rect.x\n result.x = 0\n end\n if rect.y < 0\n result.height = result.height - rect.y\n result.y = 0\n end\n if rect.width > xsize\n result.width = xsize\n end\n if rect.height > ysize\n result.height = ysize\n end\n return result\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
randomly generates an image from template (random values are normally distributed with mean = characetristic , deviation = sigma)
def create_sample_image_from_template(image_template, sigma) random_characteristics = image_template.ideal_characteristics.map do |val| deviated = RandomGaussian.new(val, sigma).rand deviated = 0.0 if deviated < 0 deviated = 1 if deviated > 1 deviated end # values = image_template.ideal_characteristics.each { |val| values << val + 5*rand(sigma) } ImageSample.new(image_template.image_class, random_characteristics) end
[ "def random_header_image\n header_images.sample\n end", "def random_image_old(horizontal=600,vertical=600)\n image_categories = ['abstract','city','people','transport','animals','food','nature','business', 'nightlife', 'sports','cats','fashion','technics']\n image_category = image_categories[Random.rand(image_categories.length)]\n #append a random id to trick the cache\n return \"http://lorempixel.com/\" + horizontal.to_s + \"/\" + vertical.to_s + \"/\" + image_category + \"/\" + random_id()[0,5]\n end", "def random_default_image\n Random.new.rand(1..6).to_s + '.jpg'\n end", "def random_image(query = 'safe, cute', nsfw = false)\n img = get(url: 'search/images', query: \"q=#{query.present? ? query : 'safe, cute'}&sf=random&per_page=1\", nsfw: nsfw)\n\n if img\n img_data = img['images'][0]\n image img_data.id, nsfw if img_data\n end\n end", "def generate_noise_gif_for_char(char)\n image = @reference_image_hash[char]\n\n #image = image.wave(10, 100)\n image = image.add_noise(Magick::PoissonNoise)\n #image = image.rotate(5)\n #image = image.resize_to_fit(@config.char_width, @config.char_height)\n\n image\n end", "def get_noise_table(size)\n (0 ... size).collect { |x| (0 ... size).collect { |y| rand(1000) }}\n end", "def random_student_art\n # fill array with all student art, return one at random\n images = Dir.glob(\"app/assets/images/student_art/*.jpg\").to_a\n images[rand(images.size)]\n end", "def gen_std_breqd_instance(n, c, wmax, pmax, seed)\n r = pmax/wmax # integer division\n r_2 = r**2\n pmax_2 = pmax**2\n rng = Random.new(seed)\n s = \"# bottom right ellipse quadrant distribution-- n: #{n}; c: #{c}; wmax: #{wmax}; pmax: #{pmax}; seed: #{seed}\\n\"\n s << \"n: #{n}\\nc: #{c}\\nbegin data\\n\"\n (1..wmax).to_a.sample(n, random: rng).each do | w |\n p = pmax - Math.sqrt(pmax_2 - (w**2 * r_2)).to_i\n s << \"#{w} #{p}\\n\"\n end\n s << \"end data\\n\"\n s\nend", "def random(tg,faulty,replacements,n)\n get_mappings(faulty,replacements).sample\nend", "def standard_normal_sample\n rho = Math.sqrt(-2.0 * Math.log(rng.rand))\n theta = 2 * Math::PI * rng.rand\n tfn = rng.rand > 0.5 ? :cos : :sin\n rho * Math.send(tfn, theta)\n end", "def apply(template_image)\n self.scale\n\n image = Magick::ImageList.new(self.artwork.image.path)\n\n image[0].rotate!(rotation) unless rotation.nil?\n image.resize!(self.width, self.height)\n\n center_x = template_image.columns / 2\n crop_image!(image, center_x)\n\n self.image_x += template_image.columns / 2 if self.leg == 'right'\n\n # x_copies = (image[0].columns / template[0].columns).ceil\n # y_copies = (image[0].rows / template[0].rows).ceil\n\n # To be tiling, see http://www.imagemagick.org/RMagick/doc/ilist.html#mosaic\n # tiled = Magick::ImageList.new\n # page = Magick::Rectangle.new(0,0,0,0)\n # x_copies.times do |x|\n # y_copies.times do |y|\n\n # end\n # end\n\n design_image = template_image[0].composite(image, self.image_x, self.image_y, Magick::DstOverCompositeOp)\n\n if mirror\n design_image.flop!\n design_image.composite!(image, self.image_x, self.image_y, Magick::DstOverCompositeOp)\n design_image.flop!\n end\n\n intermediate_location = \"#{Dir.tmpdir}/#{SecureRandom.hex}.png\"\n design_image.write(intermediate_location)\n intermediate_location\n end", "def demoRandom2(t)\n demoRandom(t)\n\n init_pics('mac-*')\n\n t.configure(:openbuttonimage=>@images['mac-collapse'],\n :closedbuttonimage=>@images['mac-expand'],\n :showlines=>false)\nend", "def rand_exp below_linear =[true,false].sample\n self.exp = below_linear ? 0.1 + 0.9 * rand : 1+rand(20)\nend", "def rng(mean=0,sigma=1,seed=nil)\n returned,y1,y2=0,0,0\n lambda {\n if returned==0\n begin\n x1 = 2.0 * rand - 1.0\n x2 = 2.0 * rand - 1.0\n w = x1 * x1 + x2 * x2\n end while ( w >= 1.0 )\n w = Math::sqrt( (-2.0 * Math::log( w ) ) / w )\n y1 = x1 * w\n y2 = x2 * w\n returned=1\n y1*sigma + mean\n else\n returned=0\n y2 * sigma + mean\n end\n }\n \n end", "def create_random_world\n randomize_terrain\n randomize_entities\n end", "def gaussian_rand\n u1 = u2 = w = g1 = g2 = 0 # declare\n begin\n u1 = 2 * rand - 1\n u2 = 2 * rand - 1\n w = u1 * u1 + u2 * u2\n end while w >= 1\n\n w = Math::sqrt( ( -2 * Math::log(w)) / w )\n g2 = u1 * w;\n g1 = u2 * w;\n # g1 is returned\nend", "def generate\n (0..30).sort{ rand() } .take(@conf)\n end", "def rand_banner_img\n [\n 'http://song-dev.qiniudn.com/g0.jpg',\n 'http://song-dev.qiniudn.com/g1.jpg',\n 'http://song-dev.qiniudn.com/g2.jpg',\n 'http://song-dev.qiniudn.com/g3.jpg',\n 'http://song-dev.qiniudn.com/g4.jpg',\n 'http://song-dev.qiniudn.com/g5.jpg',\n 'http://song-dev.qiniudn.com/g6.jpg'\n ].sample\n end", "def sample_from_gaussian\n # Compute product of hidden units and weights.\n product_of_units_and_weights = NMatrix::BLAS.gemm(@weights[0], @units[1].transpose)\n\n # Compute mean of Gaussian distribution.\n mean_of_gaussian_distribution = product_of_units_and_weights.transpose + @biases[1]\n\n # Sample visible units from Gaussian distribution.\n mean_of_gaussian_distribution.each_with_index do |mean,i|\n @units[0][i] = RandomBell.new(mu: mean, sigma: 1, range: -Float::INFINITY..Float::INFINITY).rand\n end\n\n # Compute Gaussian distribution.\n difference_of_units_and_mean = @units[0] - mean_of_gaussian_distribution\n @probability[1] = (-(difference_of_units_and_mean ** 2) / 2.0).exp / Math.sqrt(2.0 * Math::PI)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restarts the SSH service
def ssh_service_restart exec(Beaker::Command.new("stopsrc -g ssh")) exec(Beaker::Command.new("startsrc -g ssh")) end
[ "def restartIpService\n %x(ssh root@#{nodeRealName} \"echo \\'service networking restart\\' | at now + 1 minute\")\n end", "def ssh_service_restart\n case self['platform']\n when /debian|ubuntu|cumulus|huaweios/\n exec(Beaker::Command.new(\"service ssh restart\"))\n when /(el|centos|redhat|oracle|scientific)-[7-9]|eos-7|fedora-(1[4-9]|2[0-9]|3[0-9])|archlinux-/\n exec(Beaker::Command.new(\"systemctl restart sshd.service\"))\n when /el-|centos|fedora|redhat|oracle|scientific|eos/\n exec(Beaker::Command.new(\"/sbin/service sshd restart\"))\n when /opensuse|sles/\n exec(Beaker::Command.new(\"/usr/sbin/rcsshd restart\"))\n when /solaris/\n exec(Beaker::Command.new(\"svcadm restart svc:/network/ssh:default\"))\n when /(free|open)bsd/\n exec(Beaker::Command.new(\"sudo /etc/rc.d/sshd restart\"))\n else\n raise ArgumentError, \"Unsupported Platform: '#{self['platform']}'\"\n end\n end", "def ssh_service_restart\n launch_daemons_plist = '/System/Library/LaunchDaemons/ssh.plist'\n exec(Beaker::Command.new(\"launchctl unload #{launch_daemons_plist}\"))\n exec(Beaker::Command.new(\"launchctl load #{launch_daemons_plist}\"))\n end", "def restartApache (ip,username,password)\n\tNet::SSH.start(ip, username, :password => password) do |ssh|\n\t# capture all stderr and stdout output from a remote process\n\toutput = ssh.exec!(\"service httpd restart\")\n\t#puts output\n\tend\nend", "def restartApache (ip,username,password)\n\tNet::SSH.start(ip, username, :password => password) do |ssh|\n\t # capture all stderr and stdout output from a remote process\n\t output = ssh.exec!(\"service httpd restart\")\n\t puts output\n\tend\nend", "def restart()\n shutdown()\n start()\n end", "def reset_ssh\n if !ssh_state\n host(resource[:name]).configManager.serviceSystem.StopService(:id=>'TSM-SSH')\n end\n end", "def restart\n do_for_each_service { |service| service.restart }\n end", "def reset\n `ssh root@#{ip} \"reboot\"`\n end", "def restart\n request(:restart)\n end", "def restart!\n Kernel.exec(*@restart_cmdline)\n end", "def restart\n if @restart_command\n run_command(@restart_command)\n else\n stop\n start\n end\n end", "def restart_soon\n @restart = true\n @shutdown = true\n end", "def restart\n execute(make_xml('RestartRequest', {})).success\n end", "def restart_cmd\n @restart_cmd\n end", "def restart_linux_service(service)\n message = \"Information:\\tRestarting Service \"+service\n command = \"service #{service} restart\"\n output = execute_command(message,command)\n return output\nend", "def restart\n\t\t# puts \"Restarting #{@ip} ...\"\n\t\tsystem ipmi_command + \" chassis power cycle\"\n\tend", "def restartservice(service)\n do_request 'restartservice', :service => service\n end", "def restart\n if @resource[:configvalidator]\n ucommand(:configvalidator)\n unless $CHILD_STATUS.exitstatus == 0\n raise Puppet::Error,\n \"Configuration validation failed. Cannot start service.\"\n end\n end\n if @resource[:restart] or restartcmd\n ucommand(:restart)\n else\n self.stop\n self.start\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The maximum slack_before such that there is no collision with (the slack of) another reservation before the begins_at time This value could be negative, indicating that the begins_at value always collides with (the slack of) another reservation
def max_slack_before(begins_at) previous_reservation = Reservation.new(entity: self, begins_at: begins_at).previous (begins_at - previous_reservation.ends_at - previous_reservation.slack_after.minutes) / 1.minute if previous_reservation.present? end
[ "def max_slack_after(ends_at)\n next_reservation = Reservation.new(entity: self, ends_at: ends_at).next\n (next_reservation.begins_at - next_reservation.slack_before.minutes - ends_at) / 1.minute if next_reservation.present?\n end", "def slack_before_overlapping?\n previous_reservation = self.previous\n return false if previous_reservation.nil?\n\n total_slack = self.slack_before + previous_reservation.slack_after\n\n self.begins_at - previous_reservation.ends_at < total_slack.minutes\n end", "def slack_after_overlapping?\n next_reservation = self.next\n return false if next_reservation.nil?\n\n total_slack = self.slack_after + next_reservation.slack_before\n\n next_reservation.begins_at - self.ends_at < total_slack.minutes\n end", "def get_overtime_start\n return nil if self.start.nil? or self.end.nil? or self.get_overtime <= 0\n\n standard_wktime = Timecard.get_standard_wktime\n\n return nil if standard_wktime <= 0\n\n overtime_start = self.start + standard_wktime * 60\n\n self.get_breaks_a.each do |span|\n span_start = span.first\n span_end = span.last\n\n next if span_start > span_end or span_start > self.end\n\n if overtime_start > span_end\n overtime_start += (span_end - span_start)\n end\n end\n\n return overtime_start\n end", "def down_boundary\n Time.new - down_interval\n end", "def down_boundary\n Time.new - down_interval\n end", "def oldest_meaningful_end_time(top_event, max_event)\n\n #if they're the same, then no reason to do complicated math\n if top_event == max_event\n return top_event.end_time\n end\n \n min_ratio = top_event.score.to_f / max_event.score.to_f\n time_between = Math.log(min_ratio, 0.5) * Event::SCORE_HALF_LIFE\n min_end_time = [top_event.end_time - time_between, max_event.end_time.to_f].max\n\n return min_end_time\n end", "def previous(time, base)\n current = time\n until match?(current, base) && current < time\n pot_prev = align(potential_previous(current, base), base)\n pot_prev -= min_step if pot_prev == current\n\n current = pot_prev\n end\n\n current\n end", "def time\n [self.game_begins, [self.game_ends, Time.now].min].max\n end", "def findMinimumTimeDiff()\n pre = nil ;\n diff = nil ;\n @timeNameTable.values.sort.each{|time|\n if(pre.nil?) then\n pre = time ;\n else\n d = time - pre ;\n if(diff.nil? || diff > d) then\n diff = d ;\n end\n end\n }\n return diff ;\n end", "def not_before_time\n Time.now.to_i - configuration.not_before_time\n end", "def check_course_times\n self.end = start if start > self.end\n end", "def remaining\n limits.map(&:remaining).min\n end", "def get_overtime\n return 0 if self.start.nil? or self.end.nil?\n\n if self.off_am?\n standard_wktime = Timecard.get_standard_wktime_when_off_am\n elsif self.off_pm?\n standard_wktime = Timecard.get_standard_wktime_when_off_pm\n else\n standard_wktime = Timecard.get_standard_wktime\n end\n\n return 0 if standard_wktime <= 0\n\n return self.get_actual_wktime - standard_wktime\n\n# overtime = self.get_actual_wktime - standard_wktime\n#\n# if overtime >= 0\n# return overtime\n# else\n# return 0\n# end\n end", "def attempting_times_left\n @times_left ||= begin\n return MAX_ATTEMPTING_TIMES unless question.actable.attempt_limit\n\n times = question.actable.attempt_limit - submission.evaluated_or_graded_answers(question).size\n times = 0 if times < 0\n times\n end\n end", "def work_time\n [0.0, duration - waiting_time - blocked_time].max\n end", "def earliest_time\n Time.now.to_i - @sec\n end", "def minimum_lead_time\n return @minimum_lead_time\n end", "def calc_slack(k)\n if @tight_edge[k]\n nil\n else\n kslack = slack(k)\n if kslack <= 0\n @tight_edge[k] = true\n end\n kslack\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The maximum slack_after such that there is no collision with (the slack of) another reservation after the ends_at time This value could be negative, indicating that the ends_at value always collides with (the slack of) another reservation
def max_slack_after(ends_at) next_reservation = Reservation.new(entity: self, ends_at: ends_at).next (next_reservation.begins_at - next_reservation.slack_before.minutes - ends_at) / 1.minute if next_reservation.present? end
[ "def max_slack_before(begins_at)\n previous_reservation = Reservation.new(entity: self, begins_at: begins_at).previous\n (begins_at - previous_reservation.ends_at - previous_reservation.slack_after.minutes) / 1.minute if previous_reservation.present?\n end", "def slack_after_overlapping?\n next_reservation = self.next\n return false if next_reservation.nil?\n\n total_slack = self.slack_after + next_reservation.slack_before\n\n next_reservation.begins_at - self.ends_at < total_slack.minutes\n end", "def slack_before_overlapping?\n previous_reservation = self.previous\n return false if previous_reservation.nil?\n\n total_slack = self.slack_before + previous_reservation.slack_after\n\n self.begins_at - previous_reservation.ends_at < total_slack.minutes\n end", "def down_boundary\n Time.new - down_interval\n end", "def down_boundary\n Time.new - down_interval\n end", "def max_reserved_time\n @max_reserved_time_s && ( @max_reserved_time_s * 1000.0 ).round\n end", "def max_time\n @max_time ||= 0.2\n end", "def oldest_meaningful_end_time(top_event, max_event)\n\n #if they're the same, then no reason to do complicated math\n if top_event == max_event\n return top_event.end_time\n end\n \n min_ratio = top_event.score.to_f / max_event.score.to_f\n time_between = Math.log(min_ratio, 0.5) * Event::SCORE_HALF_LIFE\n min_end_time = [top_event.end_time - time_between, max_event.end_time.to_f].max\n\n return min_end_time\n end", "def max_time_ms\n spec[MAX_TIME_MS]\n end", "def last_yolo_exit_for(player)\n (player * leg_perimeter - (@leg_height * 2 - 2)) % num_normal_holes\n end", "def down_boundary\n Time.now - down_interval\n end", "def max_time_last\n max = 0\n i = 0\n while i < @children.size\n tl = @children[i].time_last\n max = tl if tl > max\n i += 1\n end\n max\n end", "def max_ball(v0)\n current_h = Float::INFINITY\n prev_h = calculate_height(v0, 0)\n t = 0\n \n loop do\n current_h = calculate_height(v0, t)\n return t - 1 if current_h < prev_h\n prev_h = current_h\n t += 1\n end \nend", "def work_time\n [0.0, duration - waiting_time - blocked_time].max\n end", "def largest_interval\r\n (0..5).detect {|idx| INTERVALS[idx] <= period} || 5\r\n end", "def y_end(y)\n [y_position, y].max\n end", "def deadline_does_not_exceed_max_deadline?\n @kase.try(:deadline_extendable?)\n end", "def time\n [self.game_begins, [self.game_ends, Time.now].min].max\n end", "def longest_time(h, m, s)\n\tnormalized_time = [h * 60 * 60, m * 60, s]\n [h, m, s][normalized_time.index(normalized_time.max)]\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set property values by an list/array (matching array index on property index) or hash (matching hash key on property name or index depending on key type)
def set_properties(*values) if values.size == 1 && values.first.is_a?(Hash) # We are dealing with a hash values.first.each do |key, index| self.set_property(key, value) end else # We are dealing with a list/array values.flatten.each_with_index do |value, index| self.set_property(index, value) end end end
[ "def set_properties_from_array(properties)\n @property_names_to_types.keys.zip(properties).each do |name, value|\n set_value(name, value)\n end\n end", "def []=(key, value)\n k = key.to_s\n if value.nil?\n remove_property(k)\n elsif (Array === value)\n case value[0]\n when NilClass\n set_property(k, [].to_java(:string))\n when String\n set_property(k, value.to_java(:string))\n when Float\n set_property(k, value.to_java(:double))\n when FalseClass, TrueClass\n set_property(k, value.to_java(:boolean))\n when Fixnum\n set_property(k, value.to_java(:long))\n else\n raise \"Not allowed to store array with value #{value[0]} type #{value[0].class}\"\n end\n else\n set_property(k, value)\n end\n end", "def []=(key, value)\n raise \"Not valid OrientDB Property value #{value.class}, valid: #{VALID_PROPERTY_VALUE_CLASSES.to_a.join(', ')}\" unless valid_property?(value)\n \n k = key.to_s\n if value.nil?\n remove_property(k)\n elsif (Array === value)\n case value[0]\n when NilClass\n set_property(k, [].to_java(:string))\n when String\n set_property(k, value.to_java(:string))\n when Float\n set_property(k, value.to_java(:double))\n when FalseClass, TrueClass\n set_property(k, value.to_java(:boolean))\n when Fixnum\n set_property(k, value.to_java(:long))\n else\n raise \"Not allowed to store array with value #{value[0]} type #{value[0].class}\"\n end\n else\n set_property(k, value)\n end\n end", "def set_kv (*kvlist)\n\tkvlist.each_slice(2) { |kv| self.[]=(*kv) }\n\tself\n end", "def set_list_value(key, index, value)\n @kvs_instance.lset(safe_key(key), index, value)\n end", "def set_list_value(key, index, value)\n raise NoMethodError\n end", "def set_property_at_index(propertyIndex,value,exception = nil)\n value = JS::Value.from_ruby(context,value)\n res = super(context,self,propertyIndex,value,exception)\n return res\n end", "def []=(*properties, values)\n # Flattent the values to 1 level. This creates an arrray of values in the case only a single value is provided.\n values = [values].flatten(1)\n properties = properties.map(&:to_s)\n run_in_transaction(:[]=, *properties, values) do\n node_properties = props\n Hash[properties.zip(values)].each { |k, v| node_properties[k] = v unless k.nil? }\n self.props = node_properties # Reset all the properties - write simple inefficient code until it proves inefficient\n end\n rescue NoMethodError => e\n _raise_doesnt_exist_anymore_error(e)\n end", "def set(index, val)\n \n end", "def set_property_at_index(ctx,object,propertyIndex,value,exception)\n JS::Lib.JSObjectSetPropertyAtIndex(ctx,object,propertyIndex,value,exception)\n end", "def setElementByList(l, v, m)\n l = deep_copy(l)\n v = deep_copy(v)\n m = deep_copy(m)\n m = setMValue(l, v, m)\n deep_copy(m)\n end", "def update_properties(hash)\n hash.each do |key, value|\n setter_method = \"#{key}=\"\n if self.respond_to?(setter_method)\n self.send(setter_method, value)\n end\n end\n end", "def from_arrays!(props, values)\n raise \"the properties array and the values array must be the same length\" unless\n props.length == values.length\n props.each_with_index do |p, index|\n writer = :\"#{p}=\"\n if self.respond_to? writer\n self.send writer, values[index]\n else\n self.instance_variable_set(:\"@#{p}\", values[index])\n end\n end\n self.to_integers!\n end", "def []=(*key_list, value)\n store_with_init(Array(key_list).flatten, value)\n end", "def update_field_property(source, property, fields=Hamster::Set[])\n field = source[property]\n # collect previous fields if present\n field.each do |value|\n # add previous fields\n fields = fields.add(value)\n end unless field.nil?\n # reassign fields\n source[property] = fields.to_a\n source\n end", "def set_properties(properties, overwrite)\n check_properties_type(properties)\n for name in properties.keys\n expression = properties[name]\n set_property(name, expression, overwrite)\n end\n end", "def custom_properties=(list)\n if list.class == Array\n list = List.new(list)\n list.each_with_index do |value, index|\n if value.is_a?(Hash)\n list[index] = CustomProperty.new(value)\n end\n end\n end\n @custom_properties = list\n end", "def assign_array_indexes(definitions, values)\n values.each_with_index do |value, index|\n assign_variable(\n definitions,\n Node.new(:integer, [index.to_s]),\n value,\n :member\n )\n end\n end", "def update_properties(hash)\n hash.each do |key, value|\n self.send(\"#{key}=\", value)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array 'board' of rows Each row is an array with randomly assigned values from 'colours' array
def get_board(width, height) # Create a new 2D array board = Array.new($board_height) {Array.new($board_width)} # Each element will be assigned a random value from 'colours' # That is done by choosing a random index of the 'colours' array (0...$board_height).each do |row| (0...$board_width).each do |cell| board[row][cell] = $colours[rand(6)] end end # Return board return board end
[ "def get_board(width, height)\n board = Array.new(height) {Array.new(width)}\n colours = [:red, :blue, :green, :yellow, :cyan, :magenta]\n (0...board.length).each do |i|\n (0...board[i].length).each do |j|\n random = rand colours.length\n board[i][j] = colours[random]\n end\n end\n return board\nend", "def get_board(width, height)\n # Create a 2d array the size of the board\n board = Array.new(height) { Array.new(width) }\n colors = [:red, :blue, :green, :yellow, :cyan, :magenta]\n\n # Loop through each square of the board\n (0...height).each do |row|\n (0...width).each do |column|\n # Get a random color symbol\n random_color = colors[rand 0...colors.length]\n\n # Set the value of the square to the random color symbol\n board[row][column] = random_color\n end\n end\n\n # Return the 2d array of random color symbols\n return board\nend", "def colors_array\n [[33, 150, 243],\n [250, 176, 51],\n [0, 128, 0],\n [24, 255, 2],\n [208, 24, 30],\n [236, 64, 122],\n [171, 71, 188],\n [94, 53, 177],\n [57, 73, 171],\n [30, 136, 229],\n [3, 155, 229],\n [0, 172, 193],\n [0, 255, 0],\n [0, 128, 0],\n [0, 255, 255],\n [0, 128, 128]] + (1..1000).map {|c| [rand(255), rand(255), rand(255)]}\n end", "def randomboard(width, height)\n board = newboard(width, height)\n for i in 1..height\n for j in 1..width\n board[i][j] = rand(0..1)\n end\n end\n board\nend", "def change_to_color(user_guess, feedback_array)\n feedback_colors = []\n feedback_array[0].times do |n|\n feedback_colors << \"black\"\n end\n feedback_array[1].times do |n|\n feedback_colors << \"black\"\n end\n feedback_array[2].times do |n|\n feedback_colors << \"white\"\n end\n @board.push(user_guess).push(feedback_colors)\n end", "def create_board\n (1..(@width * @width).to_i).each do |i|\n values = i <= @amount_mines ? @bomb : @empty\n @board.push({\n value: values,\n revealed?: false\n })\n end\n @board.shuffle!\n @board\n end", "def computer_color\n\t valid_colors = [\"r\", \"y\", \"b\", \"w\", \"c\", \"g\"] \n\t return [valid_colors[rand(0..5)],valid_colors[rand(0..5)], valid_colors[rand(0..5)], valid_colors[rand(0..5)]]\n\tend", "def make_board_array\n array = []\n 6.times do\n array.append([])\n end\n array\n end", "def random_black_piece\n pieces = @data.flatten(1).compact\n black_pieces = pieces.select do |piece|\n next unless piece.color == :black\n\n piece.moves.size.positive? || piece.captures.size.positive?\n end\n location = black_pieces.sample.location\n { row: location[0], column: location[1] }\n end", "def random_chess_board_square\n\t# chessboard_array =[]\n\t# \"a\".upto(\"h\") do |letter|\n\t# 1.upto(8) do |number|\n\t# chessboard_array << \"#{letter}#{number}\"\n\t# end\n\t# end\n\t chessboard_array = [\"a1\", \"a2\", \"a3\", \"a4\", \"a5\", \"a6\", \"a7\", \"a8\", \"b1\", \"b2\", \"b3\", \"b4\", \"b5\", \"b6\", \"b7\", \"b8\", \"c1\", \"c2\", \"c3\", \"c4\", \"c5\", \"c6\", \"c7\", \"c8\", \"d1\", \"d2\", \"d3\", \"d4\", \"d5\", \"d6\", \"d7\", \"d8\", \"e1\", \"e2\", \"e3\", \"e4\", \"e5\", \"e6\", \"e7\", \"e8\", \"f1\", \"f2\", \"f3\", \"f4\", \"f5\", \"f6\", \"f7\", \"f8\", \"g1\", \"g2\", \"g3\", \"g4\", \"g5\", \"g6\", \"g7\", \"g8\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\", \"h7\", \"h8\"]\n\t # p chessboard_array.sample\n\t # print \"\\n\"\n\tchessboard_array.sample\n end", "def generate_boogle_board_random(dim=4)\n chars = (\"A\"..\"Z\").to_a # to array\n (0...dim).map{\n (0...dim).map {\n chars[rand(chars.length - 1)] # will append the alphabet in matrix\n # rand_alpha = chars[rand(chars.length - 1)]\n # if rand_alpha == 'Q'\n # 'Qu'\n # else\n # rand_alpha\n # end\n }\n }\n end", "def board_generator\n ref_array = ref_array_generator().shuffle(random: Random.new(self.seed))\n board = []\n count = 0\n row = -1\n area = self.height * self.width\n \n while count < area do\n if count % self.width == 0\n board.push([0,ref_array.pop(),0])\n row += 1\n else\n board[row].insert(1,ref_array.pop())\n end\n count += 1\n end\n \n border = [0,0]\n self.width.times do\n border.push(0)\n end\n board.unshift(border)\n board.push(border)\n\n board = border_slicer(tile_number_generator(board))\n \n return board\n end", "def create_legal_board\n board = []\n 5.times do\n mini = []\n mini << rand(1..15)\n mini << rand(16..30)\n mini << rand(31..45)\n mini << rand(46..60)\n mini << rand(61..75)\n board << mini\n end\n p 'B I N G O'\n board.each {|sub| p sub}\nend", "def makeboard(legal_bingo_board)\n 5.times do\n legal_bingo_board.push([])\n end\n for y in 0..4\n for x in 0..4\n legal_bingo_board[x][y]=rand(15)+1+y*15\n end\n end\n legal_bingo_board[2][2] = \"F\"\n return legal_bingo_board\nend", "def setup_random\n @blocks = Array.new(ROWS) do\n Array.new(COLUMNS) { rand(COLOR_TABLE.size) }\n end\n end", "def display\n board.flatten.map { |stone| stone&.color }\n end", "def gen_board\n\n (\"A\"..\"I\").each do |row|\n (0..8).each_with_index { |column, value| @board.merge!( { \"#{row}#{column}\".to_sym => @board_array.shift.to_i } ) }\n end\n return @board\n end", "def colour_random!\n loop do\n col, row = rand(columns), rand(rows)\n cell = self[row, col]\n if cell.empty?\n cell.should_be_filled? ? cell.colour!(1) : cell.colour!(0)\n break\n end\n end\n end", "def show_board\n puts \"\"\n (1..12).each do |row|\n board_row = \"\"\n (1..4).each do |column|\n key = \"#{row},#{column}\"\n board_row += \"#{guesses[key]} \"\n end\n board_row += \"#{@pick_report[row].split(//).sort_by{rand}.join}\"\n puts board_row\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update_board method used to update the board after the user choose a new colours First the top left field is updated to the new colour For each neighbour field that has the same colour as the first field had before changing it, recursively update that field as well
def update_board(board,new_colour,old_colour,i,j) # Update field colour board[i][j]= new_colour # Check if there is a neighbour on top and if that neighbour has the same colour as the previous colour # If yes, then that neighbour is chosen to be updated in turn if (i-1) >=0 && board[i-1][j] == old_colour board = update_board(board,new_colour,old_colour,i-1,j) end # Check if there is a neighbour on the right and if that neighbour has the same colour as the previous colour # If yes, then that neighbour is chosen to be updated in turn if (j+1) < $board_width && board[i][j+1] == old_colour board = update_board(board,new_colour,old_colour,i,j+1) end # Check if there is a neighbour on the buttom and if that neighbour has the same colour as the previous colour # If yes, then that neighbour is chosen to be updated in turn if (i+1) <$board_height && board[i+1][j] == old_colour board = update_board(board,new_colour,old_colour,i+1,j) end # Check if there is a neighbour on the left and if that neighbour has the same colour as the previous colour # If yes, then that neighbour is chosen to be updated in turn if (j-1) >=0 && board[i][j-1] == old_colour board = update_board(board,new_colour,old_colour,i,j-1) end # return board return board end
[ "def update_board(row, column, board, current_colour, new_colour)\n if (current_colour != new_colour) then\n if (board[row][column] == current_colour) then\n board[row][column] = new_colour\n if (row == 0 && column == 0) then\n update_board(row+1, column, board, current_colour, new_colour)\n update_board(row, column+1, board, current_colour, new_colour)\n elsif (row == 0 && column == board[row].length-1) then\n update_board(row+1, column, board, current_colour, new_colour)\n update_board(row, column-1, board, current_colour, new_colour)\n elsif (row == board.length-1 && column == 0) then\n update_board(row-1, column, board, current_colour, new_colour)\n update_board(row, column+1, board, current_colour, new_colour)\n elsif (row == board.length-1 && column == board[row].length-1) then\n update_board(row, column-1, board, current_colour, new_colour)\n update_board(row-1, column, board, current_colour, new_colour)\n elsif (row == 0) then\n update_board(row+1, column, board, current_colour, new_colour)\n update_board(row, column-1, board, current_colour, new_colour)\n update_board(row, column+1, board, current_colour, new_colour)\n elsif (row == board.length-1) then\n update_board(row, column-1, board, current_colour, new_colour)\n update_board(row-1, column, board, current_colour, new_colour)\n update_board(row, column+1, board, current_colour, new_colour)\n elsif (column == 0) then\n update_board(row+1, column, board, current_colour, new_colour)\n update_board(row-1, column, board, current_colour, new_colour)\n update_board(row, column+1, board, current_colour, new_colour)\n elsif (column == board[row].length-1) then\n update_board(row+1, column, board, current_colour, new_colour)\n update_board(row, column-1, board, current_colour, new_colour)\n update_board(row-1, column, board, current_colour, new_colour)\n else\n update_board(row+1, column, board, current_colour, new_colour)\n update_board(row-1, column, board, current_colour, new_colour)\n update_board(row, column+1, board, current_colour, new_colour)\n update_board(row, column-1, board, current_colour, new_colour)\n end\n end\n end\n return board \nend", "def update_adjacent(board, column, row, new_color)\n # Get current color of square\n old_color = board[row][column]\n\n # Update color of square\n board[row][column] = new_color\n\n # Check is square ABOVE was the same color\n if row - 1 >= 0 && old_color == board[row-1][column]\n update_adjacent board, column, row - 1, new_color\n end\n\n # Check if the square to the RIGHT was the same color\n if column + 1 < board[0].length && old_color == board[row][column+1]\n update_adjacent board, column + 1, row, new_color\n end\n\n # Check if the square BELOW was the same color\n if row + 1 < board.length && old_color == board[row+1][column]\n update_adjacent board, column, row + 1, new_color\n end\n\n # Check if the square to the LEFT was the same color\n if column - 1 >= 0 && old_color == board[row][column-1]\n update_adjacent board, column - 1, row, new_color\n end\n\nend", "def update(board, player_color, input_color, x, y)\n board[x][y] = input_color\n # Recursively call the function for all nearby positions\n if x < board.length - 1 && board[x + 1][y] == player_color\n update(board, player_color, input_color, x + 1, y)\n end\n if y < board[x].length - 1 && board[x][y + 1] == player_color\n update(board, player_color, input_color, x, y + 1)\n end\n if x > 0 && board[x - 1][y] == player_color\n update(board, player_color, input_color, x - 1, y)\n end\n if y > 0 && board[x][y - 1] == player_color\n update(board, player_color, input_color, x, y - 1)\n end\n\n return board\nend", "def updateboard\n #scan through \n board_temp = []\n (0...@board.length).each do |iy|\n new_row = []\n (0...@board[iy].length).each do |ix|\n\n ## Following rules of Conway's GOL\n val = case neighbors([iy,ix])\n when 0, 1\n 0\n when 2\n @board[iy][ix]\n when 3 \n 1\n when 4,5,6,7,8\n 0 \n end\n new_row << val\n end\n board_temp << new_row\n end\n ## Replace board with new board, decided to use a new board because its \n ## confusing to update the existing board when considering neighbors\n @board = board_temp\n end", "def update_game_board(board, progressBoard, width, height, colour)\n (0..height - 1).each do |i|\n (0..width - 1).each do |j|\n if progressBoard[i][j] == 1 then\n if colour == \"r\" then\n board[i][j] = :red\n elsif colour == \"b\" then\n board[i][j] = :blue\n elsif colour == \"g\" then\n board[i][j] = :green\n elsif colour == \"y\" then\n board[i][j] = :yellow\n elsif colour == \"c\" then\n board[i][j] = :cyan\n elsif colour == \"m\" then\n board[i][j] = :magenta\n end\n end\n end\n end\nend", "def update\n @all_rows = @board.each_slice(9).to_a\n\n @all_cols = []\n @cols.each do |col|\n @all_cols << col.map { |i| @board[i] }\n end\n\n @all_boxes = []\n @boxes.each do |box|\n @all_boxes << box.map { |i| @board[i] }\n end\n end", "def update_board(affected_pieces)\n for position in affected_pieces\n # position[0] is the x coord \n # position[1] is the y coord\n # position[2] is the changed value at the position x,y\n position_as_str = \"#{position[0]},#{position[1]}\"\n @board_hash[position_as_str] = position[2]\n end\n end", "def set_on_board\n @piece.each_with_index do |row, x|\n row.each_with_index do |val, y|\n @board[@posx + x][@posy + y] = @color if val == 1\n end\n end\n end", "def replace_color #:doc:\n until @adjacent_cells.empty?\n cell = @adjacent_cells.pop\n @image[cell[0]][cell[1]] = @replace_color\n @visited_cells.push(cell)\n\n # Add cells to the fill stack\n BORDERCELLS.each do |border_cell|\n @next_cell = [cell[0] + border_cell[0], cell[1] + border_cell[1]]\n next if check_cell_for_filling\n @adjacent_cells.push(@next_cell)\n end\n end\n end", "def board_update(pawn_pos, cur_player)\n\t\t# Same split as earlier\n\t\tpawn_line = pawn_pos.split[0]\n\t\tpawn_col = pawn_pos.split[1].to_i - 1\n\t\tcase cur_player\n\t\twhen 0\n\t\t\tpawn_style = @player_1_case\n\t\twhen 1\n\t\t\tpawn_style = @player_2_case\n\t\tend\n\t\tcase pawn_line\n\t\twhen 'A'\n\t\t\t@A_line[pawn_col] = pawn_style\n\t\twhen 'B'\n\t\t\t@B_line[pawn_col] = pawn_style\n\t\twhen 'C'\n\t\t\t@C_line[pawn_col] = pawn_style\n\t\tend\n\t\t@board = [@A_line, @B_line, @C_line]\n\tend", "def update_chain_list_with(color, row, column)\n neighbors = self.chains.neighbors_of(color, row, column)\n \n if neighbors.size == 0\n self.chains.add(color, row, column)\n \n elsif neighbors.size == 1\n neighbors.first.add_stone(row, column)\n \n else\n new_chain = self.chains.add(color, row, column)\n neighbors.each {|c| new_chain.stones += c.stones }\n neighbors.each {|c| self.chains.remove(c) }\n new_chain.stones_updated!\n \n end\n end", "def update_board(user_input)\n combined_array = check_vertical(user_input)\n .concat(check_horizontal(user_input))\n .concat(check_diagonal(user_input))\n\n combined_array.each do |coords|\n make_move(coords)\n end\n end", "def image_board(color_board) ; @board = color_board ; end", "def draw_changes(screen)\n @updated_cells.each { |cell| cell.draw(screen) }\n @updated_cells.clear\n end", "def update(board, input)\n\told_colour = board[0][0]\n\tnew_colour = nil\n\tcase input\n\t\twhen \"r\"\n\t\t\tnew_colour = :red\n\t\twhen \"b\"\n\t\t\tnew_colour = :blue\n\t\twhen \"g\"\n\t\t\tnew_colour = :green\n\t\twhen \"c\"\n\t\t\tnew_colour = :cyan\n\t\twhen \"m\"\n\t\t\tnew_colour = :magenta\n\t\twhen \"y\"\n\t\t\tnew_colour = :yellow\n\t\telse\n\t\t\treturn\n\t\tend\n\tif old_colour == new_colour\n\t\treturn\n\tend\n\tupdate_cell(board, old_colour, new_colour, 0, 0)\nend", "def update_board\n\t\t@board.spots.each do |spot|\n\t\t\tspot[1] = @empty\n\t\tend\n\t\t@board.spots.map do |spot|\n\t\t\t@player1.tokens.each do |pieces|\n\t\t\t\tpieces.each do |piece| # should update board with token positions\n\t\t\t\t\tspot[1] = piece if spot[0] == piece.position\n\t\t\t\tend\n\t\t\tend\n\t\t\t@player2.tokens.each do |pieces|\n\t\t\t\tpieces.each do |piece| # should update board with token positions\n\t\t\t\t\tspot[1] = piece if spot[0] == piece.position\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend", "def update_cells(top_row, left_col, darray)\n darray.each_with_index do |array, y|\n array.each_with_index do |value, x|\n self[top_row + y, left_col + x] = value\n end\n end\n end", "def update\n @rovers.each {|rover|\n rover.make_moves\n @grid[rover.xcoord][rover.ycoord] = rover\n }\n end", "def change_to_color(user_guess, feedback_array)\n feedback_colors = []\n feedback_array[0].times do |n|\n feedback_colors << \"black\"\n end\n feedback_array[1].times do |n|\n feedback_colors << \"black\"\n end\n feedback_array[2].times do |n|\n feedback_colors << \"white\"\n end\n @board.push(user_guess).push(feedback_colors)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /bingos or /bingos.json
def create @bingo = Bingo.new(bingo_params) respond_to do |format| if @bingo.save format.html { redirect_to @bingo, notice: "Bingo was successfully created." } format.json { render :show, status: :created, location: @bingo } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @bingo.errors, status: :unprocessable_entity } end end end
[ "def create\n @bingo = Bingo.new(params[:bingo])\n\n respond_to do |format|\n if @bingo.save\n format.html { redirect_to @bingo, notice: 'Bingo was successfully created.' }\n format.json { render json: @bingo, status: :created, location: @bingo }\n else\n format.html { render action: \"new\" }\n format.json { render json: @bingo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_branding(params)\n request :post,\n '/v3/brandings.json',\n params\n end", "def create(bin_params)\n @rest.post('save', bin_params)\n end", "def api_gateway_post(path, params)\n api_gateway_body_fwd = params.to_json\n rack_input = StringIO.new(api_gateway_body_fwd)\n\n post path, real_params = {}, 'rack.input' => rack_input\nend", "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 api_gateway_post(path, params)\n api_gateway_body_fwd = params.to_json\n rack_input = StringIO.new(api_gateway_body_fwd)\n\n post path, real_params = {}, {\"rack.input\" => rack_input}\nend", "def create\n megam_rest.post_billings(to_hash)\n end", "def add_aos_version_box(args = {}) \n post(\"/aosversions.json/aosversionbox\", args)\nend", "def create\n @bof = Bof.new(params[:bof])\n\n respond_to do |format|\n if @bof.save\n format.html { redirect_to @bof, notice: 'Bof was successfully created.' }\n format.json { render json: @bof, status: :created, location: @bof }\n else\n format.html { render action: \"new\" }\n format.json { render json: @bof.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_branding(params)\n request :post, \"/v3/brandings.json\", params\n end", "def add_aos_version(args = {}) \n post(\"/aosversions.json/\", args)\nend", "def create\n @boook = Boook.new(params[:boook])\n\n respond_to do |format|\n if @boook.save\n format.html { redirect_to @boook, notice: 'Boook was successfully created.' }\n format.json { render json: @boook, status: :created, location: @boook }\n else\n format.html { render action: \"new\" }\n format.json { render json: @boook.errors, status: :unprocessable_entity }\n end\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 post *args\n make_request :post, *args\n end", "def create\n @bobot = Bobot.new(bobot_params)\n\n respond_to do |format|\n if @bobot.save\n format.html { redirect_to @bobot, notice: 'Bobot was successfully created.' }\n format.json { render :show, status: :created, location: @bobot }\n else\n format.html { render :new }\n format.json { render json: @bobot.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @boc = Boc.new(boc_params)\n\n respond_to do |format|\n if @boc.save\n format.html { redirect_to new_boc_path, notice: 'Boc was successfully created.' }\n format.json { render :show, status: :created, location: @boc }\n else\n format.html { render :new }\n format.json { render json: @boc.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @baoming = Baoming.new(params[:baoming])\n\n respond_to do |format|\n if @baoming.save\n format.html { redirect_to @baoming, notice: 'Baoming was successfully created.' }\n format.json { render json: @baoming, status: :created, location: @baoming }\n else\n format.html { render action: \"new\" }\n format.json { render json: @baoming.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @api_bottle = Api::Bottle.new(api_bottle_params)\n\n respond_to do |format|\n if @api_bottle.save\n format.html { redirect_to @api_bottle, notice: 'Bottle was successfully created.' }\n format.json { render :show, status: :created, location: @api_bottle }\n else\n format.html { render :new }\n format.json { render json: @api_bottle.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @boook = Boook.new(boook_params)\n\n respond_to do |format|\n if @boook.save\n format.html { redirect_to @boook, notice: 'Boook was successfully created.' }\n format.json { render :show, status: :created, location: @boook }\n else\n format.html { render :new }\n format.json { render json: @boook.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /bingos/1 or /bingos/1.json
def update respond_to do |format| if @bingo.update(bingo_params) format.html { redirect_to @bingo, notice: "Bingo was successfully updated." } format.json { render :show, status: :ok, location: @bingo } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @bingo.errors, status: :unprocessable_entity } end end end
[ "def update\n if @boat.update(boat_params)\n head :no_content\n else\n render json: @boat.errors, status: :unprocessable_entity\n end\n end", "def update_aos_version(args = {}) \n put(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def update\n @bof = Bof.find(params[:id])\n\n respond_to do |format|\n if @bof.update_attributes(params[:bof])\n format.html { redirect_to @bof, notice: 'Bof was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @bof.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @boook = Boook.find(params[:id])\n\n respond_to do |format|\n if @boook.update_attributes(params[:boook])\n format.html { redirect_to @boook, notice: 'Boook was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @boook.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_bottle.update(api_bottle_params)\n format.html { redirect_to @api_bottle, notice: 'Bottle was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_bottle }\n else\n format.html { render :edit }\n format.json { render json: @api_bottle.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @boc.update(boc_params)\n format.html { redirect_to @boc, notice: 'Boc was successfully updated.' }\n format.json { render :show, status: :ok, location: @boc }\n else\n format.html { render :edit }\n format.json { render json: @boc.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @boolio.update( boolio_params )\n format.html { redirect_to @boolio, notice: 'Boolio was successfully updated.' }\n format.json { render :show, status: :ok, location: @boolio }\n else\n format.html { render :edit }\n format.json { render json: @boolio.errors, status: :unprocessable_entity }\n end\n end\n end", "def put\n request_method('PUT')\n end", "def update_mobile_carrier(args = {}) \n put(\"/mobile.json/#{args[:carrierId]}\", args)\nend", "def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end", "def update\n respond_to do |format|\n if @boook.update(boook_params)\n format.html { redirect_to @boook, notice: 'Boook was successfully updated.' }\n format.json { render :show, status: :ok, location: @boook }\n else\n format.html { render :edit }\n format.json { render json: @boook.errors, status: :unprocessable_entity }\n end\n end\n 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_aos_version(args = {}) \n id = args['id']\n temp_path = \"/aosversions.json/{aosVersionId}\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"aosversionId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend", "def restobooking\n @buchung = Buchung.find(params[:id])\n @buchung.status='B' \n \n respond_to do |format|\n if @buchung.update_attributes(params[:buchung])\n format.html { redirect_to @buchung, notice: 'Buchung wurde erfolgreich geaendert.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @buchung.errors, status: :unprocessable_entity }\n end\n end \n end", "def update\n respond_to do |format|\n if @bounty.update(bounty_params)\n format.html { redirect_to @bounty, notice: 'Bounty was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @bounty.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @lob = Lob.find(params[:id])\n\n if @lob.update(lob_params)\n head :no_content\n else\n render json: @lob.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @blivot.update(blivot_params)\n format.html { redirect_to @blivot, notice: 'Blivot was successfully updated.' }\n format.json { render :show, status: :ok, location: @blivot }\n else\n format.html { render :edit }\n format.json { render json: @blivot.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @my_boice.update(my_boice_params)\n format.html { redirect_to @my_boice, notice: 'My boice was successfully updated.' }\n format.json { render :show, status: :ok, location: @my_boice }\n else\n format.html { render :edit }\n format.json { render json: @my_boice.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @boilerplate.update(boilerplate_params)\n format.json { render :show, status: :ok, location: @api_v1_boilerplate }\n else\n format.json { render json: @boilerplate.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return bool indicating if spec file satisfies any file in gem
def has_file_satisfied_by?(spec_file) file_paths.any? { |gem_file| RPM::Spec.file_satisfies?(spec_file, gem_file) } end
[ "def has_file_satisfied_by?(spec_file)\n file_paths.any? { |gem_file| RPM::Spec.file_satisfies?(spec_file, gem_file) }\n end", "def gemspec?\n File.extname(self) == \".gemspec\"\n end", "def gemspec?\n !gemspecs.empty?\n end", "def gem?\n #return true if Dir[File.join(location, '*.gemspec')].first\n pkgname = File.basename(location)\n gemsdir = File.dirname(location)\n specdir = File.join(File.dirname(gemsdir), 'specifications')\n Dir[File.join(specdir, \"#{pkgname}.gemspec\")].first\n end", "def valid_gemspec?\n gemspec_helper.valid?\n end", "def satisfied_by?(puppetfile)\n @specs.all? do |spec|\n puppetfile.modules.any? do |mod|\n spec.satisfied_by?(mod)\n end\n end\n end", "def inspected_file_is_gemspec?\n @file_path.end_with?(\"gemspec\")\n end", "def includes_gem?(file_name, gem_name)\n puts \"TEST = #{file_name}\"\n File.foreach(file_name) do |line|\n text = line.strip.split(' ')\n if (text.first.start_with?('require') && text.include?(\"'#{gem_name}'\")) \n return true\n end\n end\n return false\n end", "def inspected_file_is_gemspec?; end", "def installed?\n results = target_files.map {|f| is_my_file?(f) }\n return false if results.include? false\n return true\n end", "def use_rspec?\n File.exists?('spec')\n end", "def rspec_installed?\n raise 'you haven\\'t installed anything yet' if @installed_gems.nil?\n @installed_gems.any? { |s| s.name == 'rspec' }\n end", "def gem_listed?(gem)\n lockfile_specs.map(&:name).include? gem\n end", "def gem_path?(file); end", "def gem?(*args)\n options = args.last.is_a?(Hash) ? args.pop : {}\n name, requirement_string = args\n if options[:gemfile] && !process_gemfile?(options[:gemfile])\n gem_in_gemfile?(options[:gemfile], name, requirement_string)\n else\n gem_activated?(name, requirement_string)\n end\n end", "def installed?(name, req = Gem::Requirement.default)\n Gem::Specification.any? { |s| s.name =~ name and req =~ s.version }\n end", "def current_spec_is?(spec)\n return false unless file_name_spec_set?\n spec = [spec] unless spec.is_a? Array\n spec = spec.flatten\n spec = spec.map do |spec|\n Noop::Utils.convert_to_spec spec\n end\n spec.any? do |spec|\n file_name_spec == spec\n end\n end", "def gem_path?(file)\n # rubygems 1.8\n if Gem::Specification.respond_to?(:any?)\n Gem::Specification.any?{ |gem| file.start_with?(gem.full_gem_path) }\n # rubygems 1.6\n else\n Gem.all_load_paths.any?{ |path| file.start_with?(path) }\n end\n end", "def matches_spec? spec\n name == spec.name and requirement.satisfied_by? spec.version\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Download the local gem and return it as a string
def download_gem self.class.download_gem @name, @version end
[ "def download_gem\n gem_path = \"https://rubygems.org/gems/#{@name}-#{@version}.gem\"\n curl = Curl::Easy.new(gem_path)\n curl.follow_location = true\n curl.http_get\n gemf = curl.body_str\n end", "def download_gem\n self.class.download_gem @name, @version\n end", "def get(local_path)\n check_config(require_destination: true)\n local_path = Pathname(local_path)\n cartage.display \"Downloading from #{name} to #{local_path}...\"\n get_file local_path, cartage.final_release_metadata_json\n cartage.plugins.request_map(:build_package, :package_name).each do |name|\n get_file local_path, name\n end\n end", "def gem_path\n @path || downloaded_gem_path\n end", "def package_url\n \"https://github.com/arduino/arduino-cli/releases/download/#{@desired_version}/#{package_file}\"\n end", "def downloaded_gem_path\n self.class.downloaded_gem_path @name, @version\n end", "def fetch_gem(name, version)\n http_get(host + \"/gems/#{name}-#{version}.gem\").body\n end", "def gem_path\n @path || downloaded_gem_path\n end", "def download\n puts repo_get_url\n system(\"curl -o #{app}-repo.tgz '#{repo_get_url}'\")\n end", "def fetch_package(pkg, path = '.')\n download(fetch_package_path(pkg), path)\n end", "def get_package_file(name, ver)\n @package_name, @version = name, ver\n response = get_request build_package_url\n open(temp_package_file_path, \"wb\") do |file|\n file.write(response.body)\n end\n File.open(temp_package_file_path)\n end", "def download(spec, source_uri)\n gem_file_name = \"#{spec.full_name}.gem\"\n local_gem_path = File.join @install_dir, 'cache', gem_file_name\n\n Gem.ensure_gem_subdirectories @install_dir\n\n source_uri = URI.parse source_uri unless URI::Generic === source_uri\n scheme = source_uri.scheme\n\n # URI.parse gets confused by MS Windows paths with forward slashes.\n scheme = nil if scheme =~ /^[a-z]$/i\n\n case scheme\n when 'http' then\n unless File.exist? local_gem_path then\n begin\n say \"Downloading gem #{gem_file_name}\" if\n Gem.configuration.really_verbose\n\n remote_gem_path = source_uri + \"gems/#{gem_file_name}\"\n\n gem = Gem::RemoteFetcher.fetcher.fetch_path remote_gem_path\n rescue Gem::RemoteFetcher::FetchError\n raise if spec.original_platform == spec.platform\n\n alternate_name = \"#{spec.name}-#{spec.version}-#{spec.original_platform}.gem\"\n\n say \"Failed, downloading gem #{alternate_name}\" if\n Gem.configuration.really_verbose\n\n remote_gem_path = source_uri + \"gems/#{alternate_name}\"\n\n gem = Gem::RemoteFetcher.fetcher.fetch_path remote_gem_path\n end\n\n File.open local_gem_path, 'wb' do |fp|\n fp.write gem\n end\n end\n when nil, 'file' then # TODO test for local overriding cache\n begin\n FileUtils.cp source_uri.to_s, local_gem_path\n rescue Errno::EACCES\n local_gem_path = source_uri.to_s\n end\n\n say \"Using local gem #{local_gem_path}\" if\n Gem.configuration.really_verbose\n else\n raise Gem::InstallError, \"unsupported URI scheme #{source_uri.scheme}\"\n end\n\n local_gem_path\n end", "def download(path)\n Gem.ensure_gem_subdirectories path\n\n if @spec.respond_to? :sources\n exception = nil\n path = @spec.sources.find do |source|\n begin\n source.download full_spec, path\n rescue exception\n end\n end\n return path if path\n raise exception if exception\n\n elsif @spec.respond_to? :source\n source = @spec.source\n source.download full_spec, path\n\n else\n source = Gem.sources.first\n source.download full_spec, path\n end\n end", "def fetch_package_file(package)\n cache = cache_file(package)\n if cache\n Util.log \"Using a cached version of #{package.title} ...\"\n\n [cache, File.read(cache)]\n else\n Util.log \"The package is found at #{package.url}.\"\n Util.log \"Finding the download URL ...\"\n\n download_uri = resolve_download_url(package)\n\n Util.log \"Found it. Downloading from #{download_uri} ...\"\n [download_uri, HTTParty.get(download_uri)]\n end\n end", "def rubyforge_download_uri(project, gem_name = project, extension = \".gem\")\n frs_uri = URI.parse google_lucky_uri(\"#{project} download page\")\n frs_contents = Net::HTTP.get frs_uri\n frs_links = frs_contents.scan(/\\<a.+href=\\\"(.+?)\\\"\\>/).flatten.\n select { |link| link.index('.tgz') && link.index(\"#{gem_name}-\") }\n latest_link = frs_links.sort_by { |n| n.match(/#{gem_name}-(.*)\\.#{extension}/)[1] }.last\n return frs_uri.merge(latest_link)\n end", "def fetch(spec, save_path)\n uri = AllGems.db[:specs].filter(:full_name => spec.full_name).select(:uri).first[:uri]\n AllGems.logger.info \"Fetching gem from: #{uri}/gems/#{spec.full_name}.gem\"\n return save_path if File.exists?(save_path) # don't fetch if gem already exists\n FileUtils.touch(save_path)\n begin\n remote_path = \"#{uri}/gems/#{spec.full_name}.gem\"\n remote_uri = URI.parse(remote_path)\n file = File.open(save_path, 'wb')\n file.write(AllGems.fetch_remote(remote_uri))\n file.close\n save_path\n rescue StandardError => boom\n raise FetchError.new(spec.name, spec.version, remote_path, boom)\n end\n end", "def tailor_package_resource_to_platform\n @package.source(download_path)\n end", "def download_prog(repo_hash)\n if (repo_hash[:source] == \"github\")\n clone_repo(repo_hash)\n elsif (repo_hash[:source] == \"rubygems\")\n puts \"Unpacking gem #{repo_hash[:name]}...\"\n system \"gem unpack #{repo_hash[:name]} --version #{repo_hash[:version]}\"\n else\n raise \"Unexpected source of repo #{repo_hash[:name]}: #{repo_hash[:source]}\"\n end\nend", "def gem_string\n @gem_string ||= `gem list #{repo} --exact --remote --all`.chomp.split(\"\\n\").last.to_s\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns path to gem, either specified one of downloaded one
def gem_path @path || downloaded_gem_path end
[ "def gem_path\n @path || downloaded_gem_path\n end", "def downloaded_gem_path\n self.class.downloaded_gem_path @name, @version\n end", "def get_path(gemname, version_req)\n return gemname if gemname =~ /\\.gem$/i\n\n specs = Gem::source_index.find_name gemname, version_req\n\n selected = specs.sort_by { |s| s.version }.last\n\n return nil if selected.nil?\n\n # We expect to find (basename).gem in the 'cache' directory.\n # Furthermore, the name match must be exact (ignoring case).\n if gemname =~ /^#{selected.name}$/i\n filename = selected.full_name\n path = nil\n\n Gem.path.find do |gem_dir|\n path = File.join gem_dir, 'gems', filename\n File.exist? path\n end\n\n path\n else\n nil\n end\n end", "def full_gem_path\n File.join(installation_path, \"gems\", full_name)\n end", "def find_gem_based_path(gemspec, path)\n gemspec.full_require_paths.each do |p|\n full_path = check_path(File.join(p, path))\n return full_path if full_path\n end\n nil\n end", "def get_path(gemname, version_req)\n return gemname if gemname =~ /\\.gem$/i\n specs = SourceIndex.from_installed_gems.search(gemname, version_req)\n selected = specs.sort_by { |s| s.version }.last\n return nil if selected.nil?\n # We expect to find (basename).gem in the 'cache' directory.\n # Furthermore, the name match must be exact (ignoring case).\n if gemname =~ /^#{selected.name}$/i\n filename = selected.full_name + '.gem'\n return File.join(Gem.dir, 'cache', filename)\n else\n return nil\n end\n end", "def lookup_gem_path(name)\n gem = name[GEM_NAME_RE, 1] || name\n spec = Gem::Specification.find_by_name(gem)\n\n if gem_uses_modulation?(spec)\n find_gem_based_path(spec, name)\n else\n :require_gem\n end\n rescue Gem::MissingSpecError\n nil\n end", "def find_gem_wrapper(base)\n wrapper = File.join @gem_bin, base\n return wrapper if File.exists? wrapper\n return nil\n end", "def get_path(gemname, version_req)\n return gemname if gemname =~ /\\.gem$/i\n specs = SourceIndex.from_installed_gems.search(gemname, version_req)\n selected = specs.sort_by { |s| s.version }.last\n return nil if selected.nil?\n # We expect to find (basename).gem in the 'cache' directory.\n # Furthermore, the name match must be exact (ignoring case).\n if gemname =~ /^#{selected.name}$/i\n filename = selected.full_name + '.gem'\n return File.join(Gem.dir, 'cache', filename)\n else\n return nil\n end\n end", "def gemspec_path\n Pathname.glob('*.gemspec').first\n end", "def find_requirable_file(file)\n root = full_gem_path\n\n require_paths.each do |lib|\n base = \"#{root}/#{lib}/#{file}\"\n Gem.suffixes.each do |suf|\n path = \"#{base}#{suf}\"\n return path if File.file? path\n end\n end\n\n return nil\n end", "def gem_path?(file); end", "def gem_filename\n \"#{gem_dirname}.gem\"\n end", "def full_gem_path\n # TODO: This is a heavily used method by gems, so we'll need\n # to aleast just alias it to #gem_dir rather than remove it.\n @full_gem_path ||= find_full_gem_path\n end", "def gem_name\n @gem_name ||= @source_path.sub_ext(\"\").basename.to_s\n end", "def latest\n latest = Dir['*.gem'].first\n raise \"Can't find gem file!\" if latest.nil?\n File.basename(latest) \nend", "def gem_file(spec, package_name)\n\t\tif spec.platform == Gem::Platform::RUBY then\n\t\t\t\"#{package_name}.gem\"\n\t\telse\n\t\t\t\"#{package_name}-#{spec.platform}.gem\"\n\t\tend\n\tend", "def gemfile_for gemspec\n Pathname(gemspec.gems_dir).parent / 'cache' / gemspec.file_name\n end", "def gem_file(spec, package_name)\n if spec.platform == Gem::Platform::RUBY then\n \"#{package_name}.gem\"\n else\n \"#{package_name}-#{spec.platform}.gem\"\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return diff of content in this gem against other
def diff(other) require_cmd! diff_cmd out = nil begin this_dir = unpack other_dir = other.is_a?(Polisher::Gem) ? other.unpack : (other.is_a?(Polisher::Git::Repo) ? other.path : other) result = AwesomeSpawn.run("#{diff_cmd} -r #{this_dir} #{other_dir}") out = result.output.gsub("#{this_dir}", 'a').gsub("#{other_dir}", 'b') rescue ensure FileUtils.rm_rf this_dir unless this_dir.nil? FileUtils.rm_rf other_dir unless other_dir.nil? || !other.is_a?(Polisher::Gem) end out end
[ "def diff(other_version, format=:unified)\n Diff.cs_diff(content_html, other_version.content_html, :unified, 0) unless other_version.nil?\n end", "def display_diff(version1, version2)\n version1_text = render_wiki_content(:content => version1)\n version2_text = render_wiki_content(:content => version2)\n diff(version1_text, version2_text)\n end", "def content_difference\n nokogiri_doc = Algo.new(url: url)\n updated_content = nokogiri_doc.selected_content(selector: selector)\n \n difference = ''\n if updated_content != original_content\n difference = updated_content.mask('.') - original_content.mask('.')\n end\n difference\n end", "def diff\n result = manifest.diff\n report_difference(result)\n end", "def diff_to_compare; end", "def diff(other)\n if engine != other.engine && @input_engine\n [:engine, engine, other.engine]\n elsif version != other.version\n [:version, version, other.version]\n elsif engine_version != other.engine_version && @input_engine\n [:engine_version, engine_version, other.engine_version]\n elsif patchlevel != other.patchlevel && @patchlevel\n [:patchlevel, patchlevel, other.patchlevel]\n end\n end", "def line_diff(old, new)\n RailsDiff.diff(old,new)\n end", "def diff(other, options = {})\n DiffLCS.diff(self.split(''), other.split(''), options)\n end", "def diff(file1, file2)\n `diff #{file1} #{file2}`.strip\n end", "def do_diff(a, b)\r\n DiffBuilder.new(a, b).build\r\n end", "def diff\n original_proposal_version.changeset\n end", "def content_diff\n if params[:version] && !params[:version].match?(/^[1-9]\\d*$/)\n render(plain: '400 Bad Request: version parameter must be positive integer', status: :bad_request)\n return\n end\n obj_version = params[:version].to_i if params[:version]&.match?(/^[1-9]\\d*$/)\n subset = params[:subset] ||= 'all'\n render(xml: MoabOnStorage::StorageServicesWrapper.content_diff(druid, params[:content_metadata], subset, obj_version).to_xml)\n rescue Moab::MoabRuntimeError => e\n render(plain: \"500 Unable to get content diff: #{e}\", status: :internal_server_error)\n Honeybadger.notify(e)\n end", "def html_diff\n HgHtmlDiff.new(@git_change, @changeset_index).content\n end", "def diff(aVersion, field)\n version = get_version(aVersion)\n if !version.nil? \n Diffy::Diff.new(version[field], self[field], :include_plus_and_minus_in_html => true)\n else \n nil\n end\n end", "def calculate_diff(other_apk_filepath:)\n ensure_apk_filepath!\n\n base_apk_info = Apkstats::Entity::ApkInfo.new(command: apkanalyzer_command, apk_filepath: apk_filepath)\n other_apk_info = Apkstats::Entity::ApkInfo.new(command: apkanalyzer_command, apk_filepath: other_apk_filepath)\n diff_apk_info = Apkstats::Entity::ApkInfoDiff.new(base: base_apk_info, other: other_apk_info)\n\n {\n base: base_apk_info.to_h,\n other: other_apk_info.to_h,\n diff: diff_apk_info.to_h\n }\n end", "def content_diff\n if params[:version] && !params[:version].match?(/^[1-9]\\d*$/)\n render(plain: \"400 Bad Request: version parameter must be positive integer\", status: :bad_request)\n return\n end\n obj_version = params[:version].to_i if params[:version]&.match?(/^[1-9]\\d*$/)\n subset = params[:subset] ||= 'all'\n render(xml: MoabStorageService.content_diff(druid, params[:content_metadata], subset, obj_version).to_xml)\n rescue ArgumentError => e\n render(plain: \"400 Bad Request: #{e}\", status: :bad_request)\n rescue Moab::MoabRuntimeError => e\n render(plain: \"500 Unable to get content diff: #{e}\", status: :internal_server_error)\n Honeybadger.notify(e)\n end", "def diff(other)\n Distance.diff_total(self, other, true)\n end", "def diff_page\n wiki_content = remove_page_creation_date(@mw_client.get_page_content(@page_name)).strip # .strip removes potential '\\n' at end of file\n generated_content = remove_page_creation_date(@generated_content).strip\n diff = Diffy::Diff.new(wiki_content, generated_content, :context => 3)\n if (diff.to_s.empty?)\n puts \"No differences found between generated and current wiki content for page #{@page_name}.\"\n return true\n end\n puts \"Differences between generated and current wiki content for page #{@page_name}:\"\n puts '------------ PAGE DIFF BEGIN ------------'\n puts \"#{diff.to_s(:text)}\"\n puts '------------- PAGE DIFF END -------------'\n return false\n end", "def diff\n @diff ||= begin\n commit.diffs.collect{|diff| diff.diff}.join(\"\\n\")\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The plane method is used to retrieve the plane of the arc. Refer to the Geom module for instructions to create a plane.
def plane end
[ "def plane\n return nil if @vertices.length < 3\n Plane.three_points(*@vertices[0..2])\n end", "def get_plane\n end", "def get_plane\n Plane.construct_with_three_points(point_a, point_b, point_c)\n end", "def project_to_plane(plane)\n end", "def distance_to_plane(plane)\n end", "def distance_to_plane(plane)\n end", "def set_plane(plane)\n end", "def add_plane()\n planes << Plane.new(\n gen_location,\n 0,\n width,\n height,\n gen_speed(),\n true\n )\n end", "def draw_plane(plane, lineLoop, pickid)\n\n glPushName(pickid | PICK_ID_PLANE) if self.picking\n \n # if is_picked?(:plane, pickid)\n # Material.black.apply\n # glLineWidth(3.0)\n # glEdgeFlag(GL_TRUE)\n # end\n glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)\n\n Material.new(0.9, 0.9, 0.0, 0.5).apply\n glBegin(GL_TRIANGLE_FAN)\n glNormal3f(plane.a, plane.b, plane.c)\n lineLoop.each{|p| \n glVertex3f(p[0], p[1], p[2])\n }\n glEnd()\n \n glEdgeFlag(GL_FALSE)\n glPopName() if picking\n \n if (is_picked?(:plane, pickid))\n Material.black.apply\n glLineWidth(3.0)\n glBegin(GL_LINE_LOOP)\n lineLoop.each{|p|\n glVertex3f(p[0], p[1], p[2])\n }\n glEnd()\n glLineWidth(1.0)\n end\n \n end", "def find_plane(init_phi, init_theta, delta_deg)\n\n phi = init_phi\n theta = init_theta\n\n @arduino.move(phi, theta)\n r = @leica.measure\n p1 = Point.new({r: r, phi: phi, theta: theta})\n\n phi = init_phi + delta_deg\n theta = init_theta\n\n @arduino.move(phi, theta)\n r = @leica.measure\n p2 = Point.new({r: r, phi: phi, theta: theta})\n\n phi = init_phi\n theta = init_theta + delta_deg\n\n @arduino.move(phi, theta)\n r = @leica.measure\n p3 = Point.new({r: r, phi: phi, theta: theta})\n\n plane = Plane.new(p1, p2, p3)\n\n return plane\n end", "def add_section_plane(plane)\n end", "def land_plane plane\n\t\traise \"Aiport is full\" if full?\n\t\tif ok_to_land? == WEATHER_GOOD\n\t\t\tplane.land!\n\t\t\tpark_plane plane\n\t\tend\n\tend", "def add_plane(aPlane, recache = true)\n self.clip_planes << aPlane\n recache_visible_atoms if recache\n aPlane\n end", "def find_angle_with_plane(plane)\n if (intersect_plane? plane)\n numer = (vector.scalar_product(plane.find_normal_vector)).abs\n denom = (vector.length * plane.find_normal_vector.length)\n Math.asin(numer / denom) * (180 / Math::PI)\n end\n end", "def plane_for_display(plane)\n\t\t\"#{plane.tail_number} (#{plane.model})\"\n\tend", "def any_point_on_plane\n \n unless (@c == 0)\n return Vector[0, 0, @d/@c]\n end\n \n unless (@b == 0)\n return Vector[0, @d/@b, 0]\n end\n \n unless (@a == 0)\n return Vector[@d/@a, 0, 0]\n end\n \n # Actually if we get to this point, the plane undetermined and all of R3 satisfies the definition\n return Vector[0,0,0]\n end", "def screen_to_plane\n corners = plane_corners\n origin = corners[0]\n xaxis = corners[1] - corners[0]\n yaxis = corners[2] - corners[0]\n zaxis = (xaxis * yaxis).normalize\n\n # REVIEW: Is this logical pixels or physical pixels? I want logical!\n xaxis.length /= Sketchup.active_model.active_view.vpwidth\n yaxis.length /= Sketchup.active_model.active_view.vpheight\n\n new_transformation(origin, xaxis, yaxis, zaxis)\n end", "def distance_to_plane(plane)\n plane.substitute(self).abs / (plane.find_normal_vector.length)\n end", "def show\n @plane = Plane.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @plane }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The start_angle method is used to retrieve the angle of the start of the arc, measured from the X axis in radians.
def start_angle end
[ "def start_angle\n MSPhysics::Newton::Hinge.get_start_angle(@address)\n end", "def start_angle=(angle)\n MSPhysics::Newton::Hinge.set_start_angle(@address, angle)\n end", "def arc(x, y, radius, start_angle, end_angle)\n start_angle = radians(90 - start_angle)\n end_angle = radians(90 - end_angle)\n clockwise = 1 # 1 = clockwise, 0 = counterclockwise\n CGPathAddArc(@path, @transform, x, y, radius, start_angle, end_angle, clockwise)\n self\n end", "def arc(x, y, r, start_angle, end_angle, move_to0=false)\n cur_page.arc(x, y, r, start_angle, end_angle, move_to0)\n end", "def test_start_angle_negative_stays_negative\n start_angle = nil\n assert_nothing_raised do\n # Create a 1/2 circle perpendicular to the normal or Z axis\n center = Geom::Point3d.new 0,0,40\n normal = Geom::Vector3d.new 0,0,1\n xaxis = Geom::Vector3d.new 1,0,0\n start_a = -Math::PI/2\n end_a = Math::PI\n model = Sketchup.active_model\n entities = model.active_entities\n edgearray = entities.add_arc center, xaxis, normal, 5, start_a, end_a\n edge = edgearray[0]\n arccurve = edge.curve\n start_angle = arccurve.start_angle\n end\n assert_equal(-Math::PI/2, start_angle,\n 'Failed: start_angle != -Math::PI/2' )\n end", "def start_lat_rad\n unless @start_lat_rad\n # Take the point at (start_clat, 0) and rotate it around (0, 0) by the declination.\n # The resulting point is where the orbit crossing (0, 0) starts. The latitude of\n # this point is the geographic start latitude\n transform = Transformation.new\n transform.rotate_x(declination_rad)\n coordinate = transform.apply(Coordinate.phi_theta(start_clat_rad, 0.0))\n @start_lat_rad = coordinate.phi\n end\n @start_lat_rad\n end", "def test_start_angle_on_circle\n start_angle = nil\n assert_nothing_raised do\n centerpoint = Geom::Point3d.new\n # Create a circle perpendicular to the normal or Z axis\n vector = Geom::Vector3d.new 0,0,1\n vector2 = vector.normalize!\n model = Sketchup.active_model\n entities = model.active_entities\n edgearray = entities.add_circle centerpoint, vector2, 11\n edge = edgearray[0]\n arccurve = edge.curve\n start_angle = arccurve.start_angle\n end\n assert_equal(0.0, start_angle,\n 'Failed: start_angle != PI*2' )\n end", "def arc(x, y, radius, start_angle, end_angle)\n start_angle = radians(90-start_angle)\n end_angle = radians(90-end_angle)\n clockwise = 1 # 1 = clockwise, 0 = counterclockwise\n CGContextAddArc(@ctx, x, y, radius, start_angle, end_angle, clockwise)\n CGContextDrawPath(@ctx, KCGPathStroke)\n end", "def angle\n @angle\n end", "def arrow_start\n as = nil\n if has_value?(self.calibrate_coords)\n m = self.calibrate_coords.match /^(.*)\\-/\n as = m[1] if (m)\n end\n as\n end", "def calculate_angle(change)\n\t\t(@angle + change) % 360\n\tend", "def create_arc(x,y,z,radius,start_angle, end_angle, degrees_or_radians, normal=nil)\n \tbegin\n \t\tnormal ||= Ag::Vector3d.ZAxis\n \t\tstart_angle, end_angle = start_angle.to_radians, end_angle.to_radians if degrees_or_radians == :D\n \tarc = Ads::Arc.new(Ag::Point3d.new(x, y, z), normal, radius, start_angle, end_angle)\n rescue Exception => e\n puts_ex e\n end\t\n arc\n end", "def calculate_radians\n if x_length == 0 || y_length == 0\n angle_to_start_of_quadrant\n else\n case angle_to_end_of_quadrant\n when DEGREES_90\n angle_ignoring_quadrant\n when DEGREES_180\n DEGREES_180 - angle_ignoring_quadrant\n when DEGREES_270\n DEGREES_180 + angle_ignoring_quadrant\n else\n DEGREES_360 - angle_ignoring_quadrant\n end\n end\n end", "def angle=(value)\r\n if value < 0\r\n value = 360+value\r\n elsif value > 360\r\n value = value-360\r\n end\r\n @angle = value\r\n end", "def get_arc_points(cx,cy,radius, beg_angle, end_angle, degree_inc = 1.0)\r\n# - - - - - - - - - - - - - - - - - - - -\r\n deg = beg_angle\r\n degree_inc = degree_inc.abs\r\n ares = Array.new\r\n while (deg < end_angle)\r\n #print \"(deg = \", deg, \")\\n\"\r\n cp = calc_point_from_angle(cx,cy, deg, tradius)\r\n ares.append(cp)\r\n deg += degree_inc\r\n end #while\r\nend", "def add_arc(centerPoint: { x: 0.0, y: 0.0 }, radius: 1.0, \n startAngle: 0.0, endAngle: Math::PI * 0.25,\n isClockwise: false)\n pathElement = { elementtype: :patharc,\n centerpoint: centerPoint,\n radius: radius,\n startangle: startAngle,\n endangle: endAngle,\n clockwise: isClockwise }\n @pathArray.push(pathElement)\n @pathArray\n end", "def angle=(value)\r\n if value < 0\r\n value = 360+value\r\n elsif value > 360\r\n value = value-360\r\n end\r\n @angle = value\r\n end", "def arc_around(center, options)\n open_curve(arc_vertices(center, options))\n end", "def angle_from_arc(arc_length, offset_angle=0.0, precision=1.0)\n index = cumulative_distances(precision, offset_angle).closest_index(arc_length)\n @cumulative_distance_angles[index]\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The xaxis method is used to retrieve the X axis of the coordinate system for the curve. Note that the length of the returned vector is equal to the radius of the underlying curve.
def xaxis end
[ "def x_axis_coords\n current_x_coord = self.current_pos[0]\n [current_x_coord, (current_x_coord + self.width)]\n end", "def xaxis\n end", "def x\n x_value = bounds.x\n x_value -= parent.absolute_x if parent.is_a?(Shape)\n x_value\n end", "def set_x_axis(params = {})\n @x_axis = convert_axis_args(@x_axis, params)\n end", "def x_val_axis; end", "def x\n x_value = bounds.x\n x_value -= parent.absolute_x if parent.is_a?(Shape) && parent.class != Shape\n x_value\n end", "def x\n if (@@x.nil?)\n raise \"Cannot determine X coordinate\"\n end\n return @@x\n end", "def axis\n axes = Sketchup.active_model.axes\n\n axes.axes.find do |axis|\n position.on_line?([axes.origin, axis])\n end\n end", "def get_x_axis_labels\n 5\n end", "def x\n @x ||= Vedeu::Geometry::GenericCoordinate.new(name: name,\n offset: ox,\n type: :x)\n end", "def x\r\n @ax - @centerx\r\n end", "def axes\n return @axes\n end", "def axis \n\t\t\tvlen = self.vec.mag\n\t\t\tif vlen > 0.0 \n\t\t\t\treturn self.vec/vlen\n\t\t\telse\n\t\t\t\treturn ODE::Vector::new( 0.0, 0.0, 0.0 )\n\t\t\tend\n\t\tend", "def print_x_axis_init(domain_x)\n (@max_y_indentation).times { print \" \"}\n value = \"#{domain_x.get_coordinate_to_index(0).round(3)}\"\n print \"%#{value.length}s\" % \"#{value}\"\n end", "def set_x_axis(params)\n name, encoding = encode_utf16(params[:name], params[:name_encoding])\n formula = parse_series_formula(params[:name_formula])\n\n @x_axis_name = name\n @x_axis_encoding = encoding\n @x_axis_formula = formula\n end", "def graph_x_axis_for(x_axis, date)\n case @conditions[:breakdown_type]\n when \"Quarterly\"\n x_axis.match(/-Q(.)/)\n x_axis.sub(/-Q.$/, \".\" + (($1.to_i - 1) * 25).to_s)\n when \"Weekly\"\n date = Date.parse(x_axis.sub(/Week of /, \"\"))\n other_thing = (date.cweek / 52.0)\n if other_thing >= 1.0\n other_thing = 0.999\n end\n date.cwyear.to_s + \".\" + other_thing.to_s.gsub(/0\\./, \"\")\n when \"Daily\"\n date.year + (date.yday / 365.0)\n when \"Yearly\"\n x_axis\n when \"Monthly\"\n (date.year * 12) + date.month\n else\n raise NoMethodError\n end\n end", "def draw_x_axis(canvas)\n x_labels = initialize_labels\n x_labels.gravity(Magick::NorthGravity)\n x_labels.text_align(Magick::CenterAlign)\n\n range = (0..X_MAX)\n range.step(100) do |x|\n x_labels.text(convert_x_to_width(x),\n convert_y_to_height(0) + 30,\n x.to_s)\n end\n x_labels.draw(canvas)\n end", "def scale_x\n @scale[0]\n end", "def print_x_axis\n print \"%#{@entry_size}s |\" % [\"portion in %\"]\n\n axis_numbers = initialize_axis_numbers\n counter = 0.1;\n 1.upto(@width) do |i|\n if ( i % (counter * @width).round == 0)\n print \"|\"\n axis_numbers = axis_numbers[0...-1].concat((counter * 100).round.to_s)\n counter += 0.1\n else\n print \"-\"\n axis_numbers.concat(\" \")\n end\n end\n\n puts \"\\n#{axis_numbers}\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The yaxis method is used to retrieve the Y axis of the coordinate system for the curve. Note that the length of the returned vector is equal to the radius of the underlying curve.
def yaxis end
[ "def y_axis_coords\n current_y_coord = self.current_pos[1]\n [current_y_coord, (current_y_coord + self.height)]\n end", "def set_y_axis(params = {})\n @y_axis = convert_axis_args(@y_axis, params)\n end", "def vector_y max_value = 1\n max_value * Math.sin(self.to_radians)\n end", "def createYAxisCanvas\r\n\t\t##\r\n\t\t# Create y-axis label canvas\r\n\t\t##\r\n\t\tyAxisCanvas = GraphCanvas.new @seriesSet.longestYAxisLabelLength + 2, @canvas.height - 8\r\n\t\tyAxisCanvas.draw GraphLine.new(\t\r\n\t\t\t\t\t\t\tCanvasCoordinate.new(yAxisCanvas.width - 1, 0),\r\n\t\t\t\t\t\t\tCanvasCoordinate.new(yAxisCanvas.width - 1, @canvas.height - 8),\r\n\t\t\t\t\t\t\t:blue,\r\n\t\t\t\t\t\t\t\"|\")\r\n\t\t# Do label numbers\r\n\t\tincrementY\t\t= (@seriesSet.maxY.to_f - @seriesSet.minY) / (@canvas.width - yAxisCanvas.width)\r\n\t\t(0...yAxisCanvas.height/ 2).each{|idx|\r\n\t\t\tyAxisCanvas.draw GraphText.new (@seriesSet.maxY - idx * incrementY * 2).round.to_i.to_s, CanvasCoordinate.new(0, idx * 2), :blue\r\n \t\t}\r\n\t\tyAxisCanvas\r\n\tend", "def draw_y_axis(canvas)\n y_labels = initialize_labels\n y_labels.gravity(Magick::EastGravity)\n y_labels.text_align(Magick::RightAlign)\n\n range = (0..Y_MAX)\n range.step(50) do |y|\n y_labels.text(convert_x_to_width(0) - 10,\n convert_y_to_height(y),\n y.to_s)\n end\n y_labels.draw(canvas)\n end", "def set_y2_axis(params = {})\n @y2_axis = convert_axis_args(@y2_axis, params)\n end", "def y\n @y ||= Vedeu::Geometry::GenericCoordinate.new(name: name,\n offset: oy,\n type: :y)\n end", "def y\n y_value = bounds.y\n y_value -= parent.absolute_y if parent.is_a?(Shape)\n y_value\n end", "def get_y_axis_labels\n 5\n end", "def y_val_axis; end", "def y\n origin.y\n end", "def y\n y_value = bounds.y\n y_value -= parent.absolute_y if parent.is_a?(Shape) && parent.class != Shape\n y_value\n end", "def set_y_axis(params)\n name, encoding = encode_utf16(params[:name], params[:name_encoding])\n formula = parse_series_formula(params[:name_formula])\n\n @y_axis_name = name\n @y_axis_encoding = encoding\n @y_axis_formula = formula\n end", "def pos_y=(new_y)\n @pos_y = new_y\n dim[:sy] = new_y\n dim[:ey] = new_y + 96\n end", "def transform_y y\n @origin_y + y * SCREEN_Y_DIRECTION\n end", "def get_y coords\n coords.last\n end", "def scale_y\n @scale[1]\n end", "def y_axis_position(num)\n 100.0 * (num - y_min) / (y_max - y_min).to_f\n end", "def get_y\n if DEBUG_COORDS\n logger.debug \"get_y(), %s %s ## %s\" % [get_class(), get_id(), get_unique_id()]\n end\n y = 0\n if @use_uiautomator\n y = @attributes['bounds'][0][1]\n else\n begin\n if @attributes.has_key?(GET_VISIBILITY_PROPERTY) and @attributes[GET_VISIBILITY_PROPERTY] == 'VISIBLIE'\n top = @attributes[@top_property].to_i\n x += top\n if DEBUG_COORDS\n logger.debug \"get_y(), VISIBLE adding #{top}\"\n end\n end\n end\n end\n if DEBUG_COORDS\n logger.debug \"get_y() return #{y}\"\n end\n return y\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the needed paths. install_dir: The gems will be temporarily installed into this directory. Caution: Before installing the directory will be delete. jar_dir: The directory where the JAR files will be put.
def setup(install_dir, jar_dir) @install_dir = install_dir @jar_dir = jar_dir end
[ "def bundle\n raise \"Paths not given! Call setup first.\" if @install_dir.nil? || @jar_dir.nil?\n gems_jar = File.join(jar_dir, 'gems.jar')\n default_options = { :generate_rdoc => false, \n :generate_ri => false,\n :install_dir => install_dir }\n FileUtils.rm_rf install_dir if File.exists? install_dir\n FileUtils.mkdir_p install_dir\n installer = Gem::DependencyInstaller.new(default_options)\n @gems.each do |name, version|\n puts \"Installing #{name} (#{version})\"\n installer.install(name, version || Gem::Requirement.default) \n end\n Dir.glob(\"#{install_dir}/**/*.jar\").each do |jar|\n FileUtils.mv jar, File.join(jar_dir, jar.split(\"/\").last)\n end\n FileUtils.rm gems_jar if File.exists? gems_jar\n `jar cf #{gems_jar} -C #{install_dir} .`\n end", "def install_path\n @install_path ||= gem_install_dir.join(bucket).join(path)\n end", "def addJars(dir)\n fileset :dir =>dir do\n include :name => \"**/*.jar\"\n end \nend", "def install_path\n File.join(Config.gems_path, @gem_spec.gem_dirname)\n end", "def setup_bundle\n ENV['GEM_HOME'] = Noop::Config.dir_path_gem_home.to_s\n bundle_install_and_update Noop::Config.dir_path_root\n bundle_install_and_update Noop::Config.dir_path_deployment\n Dir.chdir Noop::Config.dir_path_root\n end", "def install installable\n [bindir, cachedir, docdir, gemdir, specdir].each do |dir|\n FileUtils.mkdir_p dir\n end\n\n installable.install self\n end", "def add_bundler_files(jar)\n pwd = Pathname.new(Dir.pwd)\n gemfile = config.bundler[:gemfile].relative_path_from(pwd).to_s\n lockfile = config.bundler[:lockfile].relative_path_from(pwd).to_s\n jar.files[jar.apply_pathmaps(config, gemfile, :application)] = config.bundler[:gemfile].to_s\n if File.exist?(lockfile)\n jar.files[jar.apply_pathmaps(config, lockfile, :application)] = config.bundler[:lockfile].to_s\n end\n end", "def inject_jar(jar_path)\n jar_dir = tmp_app_path.join('Contents/Java')\n jar_dir.rmtree\n jar_dir.mkdir\n cp Pathname.new(jar_path), jar_dir\n end", "def additional_classpath\r\n list = super\r\n\r\n if FileTest.exist? ext=File.join(@lib, 'ext')\r\n current = Dir.getwd\r\n Dir.chdir ext\r\n\r\n list += Dir['*.jar'].collect { |jar| File.join(ext, jar) }\r\n\r\n Dir.chdir current\r\n end\r\n list\r\n end", "def gem_install(jruby, basedir, gemname, quiet = false)\n if gemname.include?(\",\")\n g, v = gemname.split(\",\",2)\n cmd(\"#{jruby} -S gem install -i #{basedir} #{g} -v=#{v}\", quiet)\n else\n cmd(\"#{jruby} -S gem install -i #{basedir} #{gemname}\", quiet)\n end\n end", "def set_gem_paths!\n ENV[\"GEM_PATH\"] = ENV[\"BUNDLE_PATH\"] = logstash_gem_home\n ENV[\"BUNDLE_GEMFILE\"] = GEMFILE_PATH unless ENV['BUNDLE_GEMFILE']\n\n require 'bundler'\n require 'logstash/bundler_patch'\n\n Bundler.setup\n ENV[\"GEM_HOME\"] = ENV[\"GEM_PATH\"] = logstash_gem_home\n\n # Bundler.setup will wipe the existing $LOAD_PATH.\n # Since we are using gems not declared in the gemfile we need to\n # recalculate the $LOAD_PATH with all the available gems.\n load_paths = Gem::Specification\n .collect(&:load_paths)\n .flatten\n .reject { |path| $LOAD_PATH.include?(path) }\n\n $LOAD_PATH.unshift(*load_paths)\n end", "def add_gem_paths; end", "def install\n cd_and_sh( pkg_dir, install_commands )\n end", "def install!\n install_dependencies!\n \n if !Config.force? && File.exist?(install_path)\n log(:debug, \"Already installed `#{@gem_spec}'\")\n else\n log(:info, \"Installing `#{@gem_spec}'\")\n download\n unpack\n \n load_full_spec!\n \n replace(data_dir, install_path)\n replace(gem_file, gem_cache_file)\n \n create_bin_wrappers!\n create_ruby_gemspec!\n end\n end", "def jruby_install_gemrc\n sudo \"mkdir -p #{jruby_gemrc_path}\"\n rput( 'etc/gemrc', jruby_gemrc_path, :user => 'root' )\n end", "def install_dir\n @install_dir ||= default_install_dirs[package][node['os'].to_sym]\n raise \"Unsupported Combination: #{package} + #{node['os']}\" unless @install_dir\n @install_dir\n end", "def gems_directory\n @fs.path_to(path, \"__resources/gems/gems\")\n end", "def jruby_install\n\n root = \"#{local_root}/lib/jruby\"\n distro = \"/tmp/jruby-bin-#{jruby_version}.tar.gz\"\n\n dist_install( 'curl', minimal: true, check_install: true )\n\n sudo <<-SH\n if [ ! -d #{jruby_dist_path} ]; then\n mkdir -p #{root}\n mkdir -p #{root}/gems\n curl -sSL -o #{distro} #{jruby_bin_url}\n SH\n\n hash_verify( hash, distro, user: :root ) if hash\n\n sudo <<-SH\n tar -C #{root} -zxf #{distro}\n rm -f #{distro}\n mkdir -p #{gemrc_path}\n cd #{root} && ln -sfn jruby-#{jruby_version} jruby\n cd #{local_root}/bin && ln -sf ../lib/jruby/jruby/bin/jirb .\n fi\n SH\n\n rput( 'jruby/bin/', \"#{local_root}/bin/\", excludes: :dev, user: :root )\n end", "def install_dependencies_to_local_repo(install_jars, naether_jars, opts = {})\n require \"#{File.dirname(__FILE__)}/../naether\"\n\n @naether = Naether.create_from_jars(naether_jars)\n\n if opts[:local_repo]\n @naether.local_repo_path = opts[:local_repo]\n end\n\n install_jars.each do |dep|\n notation, path = dep.to_a.first\n @naether.install(notation, nil, path)\n end\n\n @naether\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Bundles the required gems into a JAR file. Before the gems are packed into the JAR, all JARs inside the gems are moved to the jar_dir.
def bundle raise "Paths not given! Call setup first." if @install_dir.nil? || @jar_dir.nil? gems_jar = File.join(jar_dir, 'gems.jar') default_options = { :generate_rdoc => false, :generate_ri => false, :install_dir => install_dir } FileUtils.rm_rf install_dir if File.exists? install_dir FileUtils.mkdir_p install_dir installer = Gem::DependencyInstaller.new(default_options) @gems.each do |name, version| puts "Installing #{name} (#{version})" installer.install(name, version || Gem::Requirement.default) end Dir.glob("#{install_dir}/**/*.jar").each do |jar| FileUtils.mv jar, File.join(jar_dir, jar.split("/").last) end FileUtils.rm gems_jar if File.exists? gems_jar `jar cf #{gems_jar} -C #{install_dir} .` end
[ "def add_bundled_gems\n return unless bundle_gems\n\n if bundle_local\n logger.trace 'Adding bundler filer to jar locally...'\n else\n logger.trace 'Adding bundler files to jar...'\n end\n\n require 'bundler'\n begin\n gemfile_path, lockfile_path = nil\n\n # Execute Bundler commands in the app_path, not in the Dir.pwd\n Bundler::SharedHelpers.chdir app_path do\n # No need to check ENV['BUNDLE_GEMFILE'], because Bundler will\n # take care of that\n gemfile_path = Bundler.default_gemfile\n lockfile_path = Bundler.default_lockfile\n end\n rescue Bundler::GemfileNotFound\n logger.warn 'No Gemfile found - skipping gem dependencies'\n return {}\n end\n\n # We need gemfile_root to properly locate the `vendor/bundle`\n gemfile_root = gemfile_path.parent\n vendor_cache_path = gemfile_root.join('vendor/cache')\n vendor_bundle_path = gemfile_root.join('vendor/bundle')\n\n unless lockfile_path.exist?\n logger.warn 'No Gemfile.lock found — this might lead to unexpected \\\n dependency tree, please consider running `bundle install` to resolve \\\n and lock dependencies.'\n end\n\n exclude_registed_jars = TorqueBox::Jars.list.map { |j| File.basename(j) }\n bundle_source = temp_dir\n\n # No need to run bundler at all. Just copy the contents of the\n # `vendor/bundle` to the jar\n if vendor_bundle_path.exist?\n logger.info 'Using existing `vendor/bundle`. Make sure that your \\\n dependencies is up to date.'\n\n bundle_source = vendor_bundle_path\n else\n vendor_bundle_gems :lockfile_exist => lockfile_path.exist?\n end\n\n add_files :source => bundle_source.to_s,\n :destination => 'app/vendor/bundle',\n :pattern => '/{**/*,.bundle/**/*}',\n :exclude => exclude_registed_jars\n\n copy_bundler_gem\n end", "def create!\n FileUtils.mkdir_p(@configuration[:build_dir])\n\n Dir.mktmpdir do |tmp_dir|\n output_path = File.join(@configuration[:build_dir], @configuration[:jar_name])\n project_dir = Pathname.new(@configuration[:app_dir])\n extra_files = @configuration[:extra_files] || []\n jruby_complete_path = @configuration[:jruby_complete]\n\n if !(defined? JRubyJars) && !(jruby_complete_path && File.exists?(jruby_complete_path))\n raise PuckError, 'Cannot build Jar: jruby-jars must be installed, or :jruby_complete must be specified'\n end\n\n gem_dependencies = resolve_gem_dependencies\n create_jar_bootstrap!(tmp_dir, gem_dependencies)\n\n ant = Ant.new(output_level: 1)\n ant.jar(destfile: output_path) do\n manifest do\n attribute name: 'Main-Class', value: 'org.jruby.JarBootstrapMain'\n attribute name: 'Created-By', value: \"Puck v#{Puck::VERSION}\"\n end\n\n zipfileset dir: tmp_dir, includes: 'jar-bootstrap.rb'\n\n if jruby_complete_path\n zipfileset src: jruby_complete_path\n else\n zipfileset src: JRubyJars.core_jar_path\n zipfileset src: JRubyJars.stdlib_jar_path\n end\n\n %w[bin lib].each do |sub_dir|\n zipfileset dir: project_dir + sub_dir, prefix: File.join(JAR_APP_HOME, sub_dir)\n end\n\n extra_files.each do |ef|\n path = Pathname.new(ef).expand_path.cleanpath\n prefix = File.join(JAR_APP_HOME, path.relative_path_from(project_dir).dirname.to_s)\n zipfileset dir: path.dirname, prefix: prefix, includes: path.basename\n end\n\n gem_dependencies.each do |spec|\n zipfileset dir: spec[:base_path], prefix: spec[:jar_path]\n end\n end\n end\n end", "def jar(src_folder, src_manifest, target_jar)\n sh \"jar cvfm #{target_jar} #{src_manifest} -C #{src_folder} .\"\nend", "def make_jar(jarname, dirname, quiet = false)\n cmd(\"jar cf #{jarname} -C #{dirname} .\", quiet)\n end", "def add_bundler_files(jar)\n pwd = Pathname.new(Dir.pwd)\n gemfile = config.bundler[:gemfile].relative_path_from(pwd).to_s\n lockfile = config.bundler[:lockfile].relative_path_from(pwd).to_s\n jar.files[jar.apply_pathmaps(config, gemfile, :application)] = config.bundler[:gemfile].to_s\n if File.exist?(lockfile)\n jar.files[jar.apply_pathmaps(config, lockfile, :application)] = config.bundler[:lockfile].to_s\n end\n end", "def add_bundler_files(jar)\n gemfile = relative_from_pwd(config.bundler[:gemfile])\n lockfile = relative_from_pwd(config.bundler[:lockfile])\n jar.files[apply_pathmaps(config, gemfile, :application)] = config.bundler[:gemfile].to_s\n if File.exist?(lockfile)\n jar.files[apply_pathmaps(config, lockfile, :application)] = config.bundler[:lockfile].to_s\n end\n if config.bundler[:git_specs]\n pathmap = \"#{config.relative_gem_path}/bundler/gems/%p\"\n pathmap.sub!(%r{^/+}, '')\n config.pathmaps.git = [pathmap]\n config.bundler[:git_specs].each do |spec|\n full_gem_path = Pathname.new(spec.full_gem_path)\n\n gem_relative_path = full_gem_path.relative_path_from(::Bundler.install_path)\n filenames = []\n gem_relative_path.each_filename { |f| filenames << f }\n\n exclude_gems = true\n unless filenames.empty?\n full_gem_path = Pathname.new(::Bundler.install_path) + filenames.first\n exclude_gems = false\n end\n\n if spec.groups.include?(:warbler_excluded)\n pattern = \"#{full_gem_path.to_s}/**/#{spec.name}.gemspec\" # #42: gemspec only to avert Bundler error\n else\n pattern = \"#{full_gem_path.to_s}/**/*\"\n end\n\n FileList[pattern].each do |src|\n f = Pathname.new(src).relative_path_from(full_gem_path).to_s\n next if exclude_gems && config.gem_excludes && config.gem_excludes.any? {|rx| f =~ rx }\n jar.files[apply_pathmaps(config, File.join(full_gem_path.basename, f), :git)] = src\n end\n end\n end\n end", "def create\n FileUtils.mkdir_p(@configuration[:build_dir])\n\n Dir.mktmpdir do |tmp_dir|\n output_path = File.join(@configuration[:build_dir], @configuration[:jar_name])\n temporary_output_path = File.join(Dir.mktmpdir, @configuration[:jar_name])\n project_dir = Pathname.new(@configuration[:app_dir]).expand_path.cleanpath\n extra_files = @configuration[:extra_files] || []\n jruby_complete_path = @configuration[:jruby_complete]\n\n if !(defined? JRubyJars) && !(jruby_complete_path && File.exists?(jruby_complete_path))\n raise PuckError, 'Cannot build Jar: jruby-jars must be installed, or :jruby_complete must be specified'\n end\n\n merge_archives = (@configuration[:merge_archives] || []).to_a\n if jruby_complete_path\n merge_archives << jruby_complete_path\n else\n merge_archives.push(JRubyJars.core_jar_path, JRubyJars.stdlib_jar_path)\n end\n\n gem_dependencies = @dependency_resolver.resolve_gem_dependencies(@configuration)\n create_jar_bootstrap!(tmp_dir, gem_dependencies)\n\n ant = Ant.new(output_level: 1)\n begin\n ant.jar(destfile: temporary_output_path) do\n manifest do\n attribute name: 'Main-Class', value: 'org.jruby.JarBootstrapMain'\n attribute name: 'Created-By', value: \"Puck v#{Puck::VERSION}\"\n end\n\n zipfileset dir: tmp_dir, includes: 'jar-bootstrap.rb'\n\n %w[bin lib].each do |sub_dir|\n path = project_dir + sub_dir\n if File.exists?(path)\n zipfileset dir: path, prefix: File.join(JAR_APP_HOME, sub_dir)\n end\n end\n\n extra_files.each do |file, target_path|\n path = Pathname.new(file).expand_path.cleanpath\n if target_path\n zipfileset file: path, fullpath: target_path\n else\n prefix = File.join(JAR_APP_HOME, path.relative_path_from(project_dir).dirname.to_s)\n zipfileset dir: path.dirname, prefix: prefix, includes: path.basename\n end\n end\n\n gem_dependencies.each do |spec|\n base_path = Pathname.new(spec[:base_path]).expand_path.cleanpath\n unless project_dir == base_path\n zipfileset dir: spec[:base_path], prefix: File.join(JAR_GEM_HOME, 'gems', spec[:versioned_name])\n zipfileset file: spec[:spec_file], fullpath: File.join(JAR_GEM_HOME, 'specifications', File.basename(spec[:spec_file]))\n end\n end\n\n merge_archives.each do |archive, target_path|\n if target_path\n zipfileset src: archive, prefix: target_path, excludes: SIGNATURE_FILES\n else\n zipfileset src: archive, excludes: SIGNATURE_FILES\n end\n end\n end\n\n FileUtils.mv(temporary_output_path, output_path)\n rescue Java::OrgApacheToolsAnt::BuildException => e\n raise PuckError, sprintf('Error when building JAR: %s (%s)', e.message, e.class), e.backtrace\n ensure\n FileUtils.rm_rf(File.dirname(temporary_output_path))\n end\n output_path\n end\n end", "def inject_jar(jar_path)\n jar_dir = tmp_app_path.join('Contents/Java')\n jar_dir.rmtree\n jar_dir.mkdir\n cp Pathname.new(jar_path), jar_dir\n end", "def native_bundles(base_dir=Dir.pwd, output_jar, verbosity, app_name)\n # Currently only JDK8 will package up JRuby apps. In the near\n # future the necessary tools will be in maven central and\n # we can download them as needed, so this can be changed then.\n # this is in format \"1.7.0_11-b21\", check for all jdk's less than 8\n if ENV_JAVA[\"java.runtime.version\"].match(/^1\\.[0-7]{1}\\..*/)\n raise \"You must install JDK 8 to use the native-bundle packaging tools. You can still create an executable jar, though.\"\n end\n\n # the native bundling uses ant\n require \"ant\"\n\n output_jar = Pathname.new(output_jar)\n dist_dir = output_jar.parent\n jar_name = File.basename(output_jar)\n out_name = File.basename(output_jar, '.*')\n\n # Can't access the \"fx\" xml namespace directly, so we get it via __send__.\n ant do\n taskdef(resource: \"com/sun/javafx/tools/ant/antlib.xml\",\n uri: \"javafx:com.sun.javafx.tools.ant\",\n classpath: \".:${java.home}/../lib/ant-javafx.jar\")\n __send__(\"javafx:com.sun.javafx.tools.ant:deploy\", nativeBundles: \"all\",\n width: \"100\", height: \"100\", outdir: \"#{base_dir}/build/\",\n outfile: out_name, verbose: verbosity) do\n application(mainClass: \"org.jruby.JarBootstrapMain\", name: app_name)\n resources do\n fileset(dir: dist_dir) do\n include name: jar_name\n end\n end\n end\n end\n\n # These webstart files don't work, and the packager doesn't have an option to\n # disable them, so remove them so the user isn't confused.\n # FIXME: jnlp webstart\n full_build_dir = \"#{base_dir}/build/\"\n rm FileList[\"#{full_build_dir}*.html\",\"#{full_build_dir}*.jnlp\"]\n end", "def fast_merge_jar(target_jar, merge_jar)\n info \"merging #{merge_jar}\"\n tmp = _(:target, \"tmp\")\n sh \"rm -rf #{tmp}\"\n sh \"mkdir -p #{tmp}; cd #{tmp}; jar -xf #{merge_jar}; jar -uf #{target_jar} *\"\n sh \"rm -rf #{tmp}\"\n end", "def all_in_one_jar(options)\n name = options[:id] || fail(\"Missing :id\")\n libs = options[:libs] || fail(\"Missing :id\")\n package(:jar, :id => fakesdb(name)).tap do |pkg|\n pkg.enhance [task(:retrieve)]\n # double-enhance so merge happens after base jar is created\n pkg.enhance do\n pkg.enhance do\n libs.each do |prefix|\n Dir[_(\"lib\") + \"/#{prefix}-*.jar\"].each do |dep|\n fast_merge_jar pkg, dep if dep !~ /-sources/\n end\n end\n end\n end\n end\n end", "def connectorj_jar\n ::File.basename(new_resource.url, '.tar.gz') + if connectorj_ver.split('.')[0].to_i >= 8\n '.jar'\n else\n '-bin.jar'\n end\n end", "def pack(dir = nil)\n logger.info \"packing the Jimfile for this project\"\n vendor(dir)\n bundle\n compress\n end", "def generate_jar(opts={})\n\t\traise if not respond_to? :config\n\t\t# Allow changing the jar's Main Class in the manifest so wrappers\n\t\t# around metasploit.Payload will work.\n\t\tmain_class = opts[:main_class] || \"metasploit.Payload\"\n\n\t\tpaths = [\n\t\t\t[ \"metasploit\", \"Payload.class\" ],\n\t\t] + @class_files\n\n\t\tjar = Rex::Zip::Jar.new\n\t\tjar.add_files(paths, File.join(Msf::Config.data_directory, \"java\"))\n\t\tjar.build_manifest(:main_class => main_class)\n\t\tjar.add_file(\"metasploit.dat\", config)\n\n\t\tjar\n\tend", "def dest_jars\n if maven_strategy == :jars_from_assembly\n\n # For manifest, map destination jars from available jars in\n # (jar_from) target/assembly. These are available since mvn\n # package will be run first for the :manifest target.\n Dir[ File.join( jar_from, \"*.jar\" ) ].\n map { |j| File.basename( j ) }.\n sort.\n map { |j| File.join( jar_dest, j ) }\n else\n Util::clean_list( jars ).\n sort.\n map { |j| File.join( jar_dest, j ) }\n end\n end", "def create_boot_jar(jvm_spec)\n depends :init, :compile\n\n jvm = @jvm_set[jvm_spec]\n output_path = @build_results.tools_home\n output_path = FilePath.new(config_source['dest']) unless config_source['dest'].nil?\n boot_jar = BootJar.new(jvm, output_path, @module_set, @static_resources.dso_boot_jar_config_file)\n boot_jar.ensure_created(:delete_existing => true)\n puts \"\"\n puts \"Boot JAR for JVM '%s' successfully created at '%s'.\" % [ jvm.to_s, boot_jar.path.to_s ]\n end", "def shared_boot_jar_directory\n FilePath.new(@build_dir, \"boot-jars\")\n end", "def jar_from\n dirs = [ 'target' ]\n\n unless maven_strategy == :no_assembly\n dirs << [ assembly_name,\n assembly_version,\n 'bin.dir' ].join( '-' )\n end\n\n File.join( dirs )\n end", "def package_as_bundle_spec(spec)\n spec.merge(:type => :jar)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /daties POST /daties.json
def create @daty = current_user.daties.build(daty_params) respond_to do |format| if @daty.save format.html { redirect_to @daty, notice: 'Daty was successfully created.' } format.json { render :show, status: :created, location: @daty } else format.html { render :new } format.json { render json: @daty.errors, status: :unprocessable_entity } end end end
[ "def create\n @meteo_datum = MeteoDatum.new(meteodatum_params)\n @meteo_datum.weather_station_id = params[:weather_station_id]\n\n if @meteo_datum.save\n render json: @meteo_datum, status: :created\n else\n render json: @meteo_datum.errors, status: :unprocessable_entity\n end\n end", "def create\n @deep_datum = DeepDatum.new(deep_datum_params)\n\n respond_to do |format|\n if @deep_datum.save\n format.html { redirect_to @deep_datum, notice: 'Deep datum was successfully created.' }\n format.json { render :show, status: :created, location: @deep_datum }\n else\n format.html { render :new }\n format.json { render json: @deep_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @weather_datum = WeatherDatum.new(weather_datum_params)\n\n respond_to do |format|\n if @weather_datum.save\n format.html { redirect_to @weather_datum, notice: 'Weather datum was successfully created.' }\n format.json { render :show, status: :created, location: @weather_datum }\n else\n format.html { render :new }\n format.json { render json: @weather_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @skydatum = Skydatum.new(params[:skydatum])\n\n respond_to do |format|\n if @skydatum.save\n format.html { redirect_to @skydatum, notice: 'Skydatum was successfully created.' }\n format.json { render json: @skydatum, status: :created, location: @skydatum }\n else\n format.html { render action: \"new\" }\n format.json { render json: @skydatum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @daily_datum = DailyDatum.new(params[:daily_datum])\n\n respond_to do |format|\n if @daily_datum.save\n format.html { redirect_to @daily_datum, notice: 'Daily datum was successfully created.' }\n format.json { render json: @daily_datum, status: :created, location: @daily_datum }\n else\n format.html { render action: \"new\" }\n format.json { render json: @daily_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @dino = Dino.new(dino_params)\n\n if @dino.save\n render json: @dino, status: :created, location: @dino\n else\n render json: @dino.errors, status: :unprocessable_entity\n end\n end", "def create\n @ride_datum = RideDatum.new(params[:ride_datum])\n\n respond_to do |format|\n if @ride_datum.save\n format.html { redirect_to @ride_datum, notice: 'Ride datum was successfully created.' }\n format.json { render json: @ride_datum, status: :created, location: @ride_datum }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ride_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @diocese = Diocese.new(diocese_params)\n\n if @diocese.save\n render json: @diocese, status: :created, location: @diocese\n else\n render json: @diocese.errors, status: :unprocessable_entity\n end\n end", "def create\n @data_table_datum = DataTableDatum.new(data_table_datum_params)\n\n respond_to do |format|\n if @data_table_datum.save\n format.html { redirect_to @data_table_datum, notice: 'Data table datum was successfully created.' }\n format.json { render :show, status: :created, location: @data_table_datum }\n else\n format.html { render :new }\n format.json { render json: @data_table_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n @tracked_datum = TrackedDatum.new(tracked_datum_params)\n\n respond_to do |format|\n if @tracked_datum.save\n format.html { redirect_to @tracked_datum, notice: 'Tracked datum was successfully created.' }\n format.json { render :show, status: :created, location: @tracked_datum }\n else\n format.html { render :new }\n format.json { render json: @tracked_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\t\tdata_set = DataSet.find(params[:data_set_id])\n\t\t\n\t\t#if data are send in batch\n\t\tif params[:_json].kind_of?(Array)\n\t\t\tdata_arr = params[:_json]\n\t\t\tdata = Array.new\n\t\t\tall_valid = true\n\t\t\t\n\t\t\t#save all data in one transaction\n\t\t\tDatum.transaction do\n\t\t\t\tdata_arr.each do |item|\n\t\t\t\t\tdata.push(data_set.data.new(item))\n\t\t\t\t\tdata.last.save\n\t\t\t\t\tif !data.last.valid?\n\t\t\t\t\t\tall_valid = false\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\trespond_with(data) do |format|\n \tif all_valid\n \tformat.json { render json: { success: true, data: data } }\n \telse\n \tformat.json { render json: { success: false, errors: 'Data werent created' } }\n \tend\n \tend\n \t\n\t\t#if there is only one datum\n\t\telse\n\t\t\tdatum = data_set.data.new(params[:datum])\n\t\t\tdatum.save\n\t\t\t\n\t\t\trespond_with(datum) do |format|\n \tif datum.valid?\n \tformat.json { render json: { success: true, data: datum } }\n \telse\n \tformat.json { render json: { success: false, errors: datum.errors } }\n \tend\n \tend\n\t\tend\n end", "def create\n @drumy = Drumy.new(params[:drumy])\n\n respond_to do |format|\n if @drumy.save\n format.html { redirect_to @drumy, notice: 'Drumy was successfully created.' }\n format.json { render json: @drumy, status: :created, location: @drumy }\n else\n format.html { render action: \"new\" }\n format.json { render json: @drumy.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @scrapping_datum = ScrappingDatum.new(scrapping_datum_params)\n\n respond_to do |format|\n if @scrapping_datum.save\n format.html { redirect_to @scrapping_datum, notice: 'Scrapping datum was successfully created.' }\n format.json { render :show, status: :created, location: @scrapping_datum }\n else\n format.html { render :new }\n format.json { render json: @scrapping_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n\n #Can also be created with:\n # => curl -X POST -H \"Content-Type: application/json; charset=UTF-8\" -d '{\"sensor_datum\": {\"ppm\": \"400\",\"device_id\": \"1\"}}' localhost:3000/sensor_data.json\n # => curl -X POST -H \"Content-Type: application/json; charset=UTF-8\" -d '{\"sensor_datum\": {\"ppm\": \"400\", \"device_address\": \"42\"}}' localhost:3000/sensor_data.json\n\n @sensor_datum = SensorDatum.new(sensor_datum_params)\n authorize @sensor_datum\n\n @sensor_datum.resolve_device_id\n @sensor_datum.resolve_experiment_id\n\n respond_to do |format|\n if @sensor_datum.save\n format.html { redirect_to @sensor_datum, notice: 'Sensor datum was successfully created.' }\n format.json { render :show, status: :created, location: @sensor_datum }\n else\n format.html { render :new }\n format.json { render json: @sensor_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @energy_datum = EnergyDatum.new(params[:energy_datum])\n\n respond_to do |format|\n if @energy_datum.save\n format.html { redirect_to @energy_datum, notice: 'Energy datum was successfully created.' }\n format.json { render json: @energy_datum, status: :created, location: @energy_datum }\n else\n format.html { render action: \"new\" }\n format.json { render json: @energy_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n respond_to do |format|\n if @input_datum.update(params[:input_data].keys, params[:input_data].values)\n format.html { redirect_to @input_datum, notice: 'Input datum was successfully created.' }\n format.json { render :show, status: :created, location: @input_datum }\n else\n format.html { render :new }\n format.json { render json: @input_datum.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @dataslate = Dataslate.new(dataslate_params)\n\n respond_to do |format|\n if @dataslate.save\n format.html { redirect_to @dataslate, notice: 'Dataslate was successfully created.' }\n format.json { render :show, status: :created, location: @dataslate }\n else\n format.html { render :new }\n format.json { render json: @dataslate.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @deanery = Deanery.new(deanery_params)\n\n if @deanery.save\n render json: @deanery, status: :created, location: @deanery\n else\n render json: @deanery.errors, status: :unprocessable_entity\n end\n end", "def create\n @dynasty = Dynasty.new(dynasty_params)\n\n respond_to do |format|\n if @dynasty.save\n format.html { redirect_to @dynasty, notice: 'Dynasty was successfully created.' }\n format.json { render :show, status: :created, location: @dynasty }\n else\n format.html { render :new }\n format.json { render json: @dynasty.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /daties/1 DELETE /daties/1.json
def destroy @daty.destroy respond_to do |format| format.html { redirect_to daties_url, notice: 'Daty was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @json_datum.destroy\n respond_to do |format|\n format.html { redirect_to json_data_url }\n format.json { head :no_content }\n end\n end", "def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end", "def destroy\n @drumy = Drumy.find(params[:id])\n @drumy.destroy\n\n respond_to do |format|\n format.html { redirect_to drumies_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @dataset_datum.destroy\n respond_to do |format|\n format.html { redirect_to dataset_data_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @getdatum = Getdatum.find(params[:id])\n @getdatum.destroy\n\n respond_to do |format|\n format.html { redirect_to getdata_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @datashows = Datashow.find(params[:id])\n @datashows.destroy\n\n respond_to do |format|\n format.html { redirect_to(datashows_url) }\n format.xml { head :ok }\n end\n end", "def delete datapoints\n datapoints = [*datapoints]\n datapoints.each do |dp|\n @user.delete \"/users/me/goals/#{@slug}/datapoints/#{dp.id}.json\"\n end\n end", "def destroy\n @daily_datum = DailyDatum.find(params[:id])\n @daily_datum.destroy\n\n respond_to do |format|\n format.html { redirect_to daily_data_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @ride_datum = RideDatum.find(params[:id])\n @ride_datum.destroy\n\n @ride_datum = RideDatum.delete_all\n\n respond_to do |format|\n format.html { redirect_to ride_data_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @dato = Dato.find(params[:id])\n @dato.destroy\n\n respond_to do |format|\n format.html { redirect_to datos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @deep_datum.destroy\n respond_to do |format|\n format.html { redirect_to deep_data_url, notice: 'Deep datum was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @dataset = Dataset.find(params[:id])\n @dataset.destroy\n\n respond_to do |format|\n format.html { redirect_to datasets_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @jsonfile = Jsonfile.find(params[:id])\n @jsonfile.destroy\n\n respond_to do |format|\n format.html { redirect_to(jsonfiles_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @datapoint = Datapoint.find(params[:id])\n @datapoint.destroy\n\n respond_to do |format|\n format.html { redirect_to datapoints_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @skydatum = Skydatum.find(params[:id])\n @skydatum.destroy\n\n respond_to do |format|\n format.html { redirect_to skydata_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @crowd_datum = CrowdDatum.find(params[:id])\n @crowd_datum.destroy\n\n respond_to do |format|\n format.html { redirect_to crowd_data_url }\n format.json { head :ok }\n end\n end", "def destroy\n @datoscontacto = Datoscontacto.find(params[:id])\n @datoscontacto.destroy\n\n respond_to do |format|\n format.html { redirect_to datoscontactos_url }\n format.json { head :no_content }\n end\n end", "def destroy\n AccDatum.find(params[:id]).destroy\n respond_to do |format|\n format.html { redirect_to acc_data_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints out the coin attributes for the Coin object with terminaltable gem
def attributes table = terminal_table do |t| t.title = name.upcase t.add_row ["Price USD:", "$#{price_usd}"] t.add_row ["Price BTC:", "#{price_btc}"] t.add_row ["Market Cap USD:", "$#{market_cap_usd}"] t.add_row ["Change Last 24h:", "#{percent_change_24h}%"] t.add_row ["Last Updated:", "#{Time.at(last_updated_unix.to_i)}"] t.style = { all_separators: true, width: 60 } end puts table end
[ "def coin_attributes\n table = terminal_table do |t|\n t.title = name.upcase\n t.add_row [\"Change:\", \"#{change}%\"]\n price.each do |currency, price|\n t.add_row [currency.upcase, price.to_f.round(2)]\n end\n t.style = { all_separators: true, width: 30 }\n end\n puts table\n end", "def print_coin_names\n coins.each_with_index do |coin, index|\n table = terminal_table do |t|\n t.add_row [index + 1, coin.name]\n t.style = { all_separators: true, width: 15 }\n end\n puts table\n end\n end", "def print_coins(coins_array)\n puts 'COINS'\n coins_array.each { |c| puts \"\\t#{c.amount}\\t#{c.type}\" }\n end", "def print_coin_names\n coin_names_arrays.each do |coin|\n coin.each do |name|\n index = name.slice!(/\\d+\\s/).strip\n table = terminal_table do |t|\n t.add_row [index, name]\n t.style = { all_separators: true, width: 60 }\n end\n puts table\n end\n yield\n end\n end", "def details\n\n puts \"\"\n puts \"Todays crypto update:\"\n puts \"Volume is the amount of the coin that has been traded with in a certain time frame...fyi\"\n puts \"----------------------------------------------------------------------\"\n puts \"| Coin (Symbol) | Volume (1 day) | Volume (7 day) | Volume (30 day) |\"\n puts \"----------------------------------------------------------------------\"\n puts \"\"\n\n @coins = TheCryptoUpdate::Coin.all[0..99]\n\n @coins.find do |coin|\n puts \" #{coin.name} (#{coin.symbol}) | $#{coin.volume_1d} | $#{coin.volume_7d} | $#{coin.volume_30d} |\"\n end\n\n end", "def print_sorted_prices\n sort_by_price.each do |coin|\n table = terminal_table do |t|\n t.add_row [coin.name, \"$#{coin.price['usd'].to_f.round(4)}\"]\n t.style = { all_separators: true, width: 40 }\n end\n puts table\n end\n end", "def display_coins\n end", "def print_sorted_prices\n sort_by_price_usd.each do |coin|\n unless coin.price_usd == 0\n table = terminal_table do |t|\n t.add_row [coin.name, \"$#{coin.price_usd}\"]\n t.style = { all_separators: true, width: 60 }\n end\n puts table\n end\n end\n end", "def print_billcoins\r\n\t\t@billcoins.each_pair {|k, v| puts \"#{k}: #{v} billcoins\" unless k==\"SYSTEM\"}\t# don't print SYSTEM billcoin count\r\n\tend", "def print_fields\r\n\t\tputs \"name: #{@name}\"\r\n\t\tputs \"num_billcoins: #{@num_billcoins}\"\r\n\t\tputs \"\"\r\n\tend", "def list_top_coins\n # here doc - http://blog.jayfields.com/2006/12/ruby-multiline-strings-here-doc-or.html\n puts <<-DOC.colorize(:cyan)\n ____ ____ ____ _________ ____ ____ ____ ____ ____ ____ _________ ____ ____ ____ ____ ____ ____\n ||T |||h |||e ||| |||C |||r |||y |||p |||t |||o ||| |||U |||p |||d |||a |||t |||e ||\n ||__|||__|||__|||_______|||__|||__|||__|||__|||__|||__|||_______|||__|||__|||__|||__|||__|||__||\n |/__\\|/__\\|/__\\|/_______\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/_______\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\|/__\\||\n\n DOC\n\n puts \"Top 100 Cryptocurrencies By Market Capitalization\"\n puts \"\"\n puts \"Todays crypto update:\"\n puts \"-----------------\"\n puts \"| Coin (Symbol) |\"\n puts \"-----------------\"\n\n @coins = TheCryptoUpdate::Coin.all[0..99]\n\n @coins.each.with_index(1) do |coin, i|\n # puts \"#{i}. #{coin.name} (#{coin.symbol}) | $#{coin.volume_1d} | #{coin.volume_7d}% | #{coin.volume_30d}% |\"\n puts \"#{i}. #{coin.name} (#{coin.symbol})\"\n end\n\n end", "def print_sorted_changes(input = nil)\n sort_by_change(input).each do |coin|\n table = terminal_table do |t|\n t.add_row [coin.name, \"#{coin.change}%\"]\n t.style = { all_separators: true, width: 40 }\n end\n puts table\n end\n end", "def print_table\n\t\t\theadings =[' '] + @collection\n\t\t\trows=[]\n\t\t\t@collection.each do |prime|\n\t\t\t\trows.push [prime] + @collection.map { |a| prime * a}\n\t\t\tend\n\t\t\ttable = Terminal::Table.new :headings => headings, :rows => rows\n\t\t\tputs table\n\t\tend", "def print_sorted_changes(input = nil)\n sort_by_change(input).each do |coin|\n table = terminal_table do |t|\n t.add_row [coin.name, \"#{coin.percent_change_24h}%\"]\n t.style = { all_separators: true, width: 60 }\n end\n puts table\n end\n end", "def table_print\n @table.each do |row|\n p row\n end\n end", "def print_node_attributes(node)\n @client = Helper.setup(parent_options)\n node_attributes = Client::Node::NODE_ATTRIBUTES\n rows = []\n node_attributes.each do |attr|\n rows << [attr, @client.node.method(\"get_node_#{attr}\").call(node)]\n end\n table = Table.new :headings => ['Attribute', 'Value'], :rows => rows\n puts \"Node: #{node}\"\n puts table\n end", "def display_table\n # TODO: This should loop over the models\n # The Blinky::XXX.attributes finds the models field names.\n rows = [\n [context.users_name, context.users.size, field_names(Blinky::User.attributes(:full))],\n [context.organizations_name, context.organizations.size, field_names(Blinky::Organization.attributes(:full))],\n [context.tickets_name, context.tickets.size, field_names(Blinky::Ticket.attributes(:full))]\n ]\n puts Terminal::Table.new headings: %w(Group Count Fields), rows: rows\n end", "def bin_status\n rows = []\n\n # loop through to find all available bin space\n self.bins.each do |bin|\n rows << [bin.type, \"#{bin.bin_level}%\"]\n end\n # Drawing and styling the table\n table = Terminal::Table.new :rows => rows\n table = Terminal::Table.new :title => ' Your available bin space '.light_white.on_light_red, :headings => ['Bin type'.light_white, 'How much used'.light_white], :rows => rows, :style => {:width => 100, :padding_left => 1, :border_x => \"=\"}\n\n puts table\n end", "def profile_print\n puts \"Client ID: \\t#{@id}\\nName: \\t\\t#{@name}\\nPhone Number: \\t#{@phone}\\nEmail Address: \\t#{@email}\"\n charges = ''\n bigtotal = 0\n @pendingcharges.each do |charge|\n total = charge[:flatfee] + (charge[:hours] * charge[:chargeperhour])\n bigtotal += total\n charges.concat(\" #{charge[:description]} - \\t\\t$#{total} \\n\\t$#{charge[:flatfee]} fee + #{charge[:hours].to_s} hours at $#{charge[:chargeperhour].to_s} per hour.\\n\\n\")\n end\n puts \"\\nPending charges:\\t\\t\\t$#{bigtotal}\\n\\n\"\n puts charges\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Using the options build when the commandline was parsed, instantiate a new Capistrano configuration, initialize it, and execute the requested actions. Returns the Configuration instance used, if successful.
def execute! config = instantiate_configuration(options) config.debug = options[:debug] config.dry_run = options[:dry_run] config.preserve_roles = options[:preserve_roles] config.logger.level = options[:verbose] set_pre_vars(config) load_recipes(config) config.trigger(:load) execute_requested_actions(config) config.trigger(:exit) config rescue Exception => error handle_error(error) end
[ "def execute!\n config = instantiate_configuration\n config.logger.level = options[:verbose]\n config.load 'deploy'\n\n status = catch(:abort_called_by_capistrano){\n set_webistrano_logger(config)\n \n set_up_config(config)\n \n exchange_real_revision(config) unless (config.fetch(:scm).to_s == 'git') # git cannot do a local query by default\n save_revision(config)\n save_pid\n \n config.trigger(:load)\n execute_requested_actions(config)\n config.trigger(:exit)\n }\n \n if status == :capistrano_abort\n false\n else\n config\n end\n rescue Exception => error\n handle_error(error) \n return false\n end", "def create_config \n @config = ::Capistrano::Configuration.new\n if @cloud.debug || @cloud.verbose \n @config.logger.level = @cloud.debug ? ::Capistrano::Logger::MAX_LEVEL : ::Capistrano::Logger::INFO\n else\n @config.logger.level = ::Capistrano::Logger::IMPORTANT\n end\n \n capfile = returning Array.new do |arr|\n Dir[\"#{::File.dirname(__FILE__)}/recipies/*.rb\"].each {|a| arr << \"require '#{a}'\" }\n arr << \"ssh_options[:keys] = '#{@cloud.full_keypair_basename_path}'\"\n \n arr << set_poolparty_roles\n end.join(\"\\n\")\n \n @config.provisioner = self\n @config.cloud = @cloud\n \n @config.load(:string => capfile)\n \n @cloud.deploy_file ? @config.load(@cloud.deploy_file) : @config.set(:user, @cloud.user)\n end", "def create_config\n @config = ::Capistrano::Configuration.new\n @config.logger = ::Capistrano::Logger.new\n @config.logger.level = ::Capistrano::Logger::MAX_LEVEL\n\n capfile = returning Array.new do |arr|\n Dir[\"#{::File.dirname(__FILE__)}/recipies/*.rb\"].each {|a| arr << \"require '#{a}'\" }\n #arr << \"ssh_options[:keys] = '#{@cloud.full_keypair_basename_path}'\"\n\n arr << \"role :apps, \\\"toy.local\\\"\"\n end.join(\"\\n\")\n\n @config.load(:string => capfile)\n @config.set(:user, \"root\")\n end", "def new_capistrano_config(opts=@opts)\n c = Capistrano::Configuration.new(opts)\n # NOTE: Capistrano::Logger constant values are opposite of Logger ....goofy\n c.logger.level = opts[:log_level] || Capistrano::Logger::DEBUG\n @@load_paths.each {|d| c.load_paths << d }\n Array(opts[:load_paths]).flatten.each {|d| c.load_paths << d } if opts[:load_paths]\n return c\n end", "def create_capistrano_config\n \n capistrano_config_file = @settings['local']['application_root']+\"/config/deploy.rb\"\n \n puts \"===== Initializing capistrano\"\n if !File.exist?(capistrano_config_file) || force? || confirmation(\"overwrite #{capistrano_config_file}\")\n run \"capify #{@settings['local']['application_root']}\"\n\n File.open(File.expand_path(File.dirname(__FILE__)+'/capistrano_template'), \"r\") do |input|\n File.open(capistrano_config_file, \"w\") do |output|\n input.each_line do |line|\n line.gsub!(\"APPLICATION_HOST\", @settings['server']['host'])\n line.gsub!(\"APPLICATION_USER\", @settings['application']['user'])\n line.gsub!(\"APPLICATION_REPOSITORY\", @settings['application']['repository'])\n line.gsub!(\"APPLICATION_NAME\", @settings['application']['name']) \n line.gsub!(\"APPLICATION_ROOT\", @settings['server']['webserver_root'] + \"/\" + @settings['application']['name'])\n output.print(line)\n puts line\n end\n end\n end\n end\n \n create_maintenance_html\n end", "def remote_deploy(options={})\n @cartridge_model.do_control('update-configuration',\n @cartridge_model.primary_cartridge,\n pre_action_hooks_enabled: false,\n post_action_hooks_enabled: false,\n out: options[:out],\n err: options[:err])\n\n deploy(options)\n\n if options[:init]\n primary_cart_env_dir = File.join(@user.homedir, @cartridge_model.primary_cartridge.directory, 'env')\n primary_cart_env = Utils::Environ.load(primary_cart_env_dir)\n ident = primary_cart_env.keys.grep(/^OPENSHIFT_.*_IDENT/)\n _, _, version, _ = Runtime::Manifest.parse_ident(primary_cart_env[ident.first])\n\n @cartridge_model.post_install(@cartridge_model.primary_cartridge,\n version,\n out: options[:out],\n err: options[:err])\n\n end\n end", "def configure\n run_with_failure_handler(\"cd #{@extracted_path} ; ./configure #{options[:config_options] || ''}\", 'configure')\n end", "def remote_deploy(options={})\n @cartridge_model.do_control('update-configuration',\n @cartridge_model.primary_cartridge,\n pre_action_hooks_enabled: false,\n post_action_hooks_enabled: false,\n out: options[:out],\n err: options[:err])\n\n deploy(options)\n\n if options[:init]\n primary_cart_env_dir = PathUtils.join(@container_dir, @cartridge_model.primary_cartridge.directory, 'env')\n primary_cart_env = ::OpenShift::Runtime::Utils::Environ.load(primary_cart_env_dir)\n ident = primary_cart_env.keys.grep(/^OPENSHIFT_.*_IDENT/)\n _, _, version, _ = Runtime::Manifest.parse_ident(primary_cart_env[ident.first])\n\n @cartridge_model.post_install(@cartridge_model.primary_cartridge,\n version,\n out: options[:out],\n err: options[:err])\n\n end\n end", "def parse\n options = {}\n options.merge(parse_config_file(CONFIG_LOCATION))\n\n argv = parse_argv\n if argv[:config_file].kind_of?(String)\n options.merge(parse_config_file(argv[:config_file]))\n end\n\n options.merge(argv)\n end", "def execute\n config_options= {\n :config_file => config\n }\n config = load_config(options = config_options)\n symlink_options = {\n :mode => mode,\n }\n if defined?(hosts)\n symlink_options[:hosts] = hosts\n end\n manage_symlinks(config, options = symlink_options)\n end", "def execute_recipes!\n config = SwitchTower::Configuration.new\n config.logger.level = options[:verbose]\n config.set :password, options[:password]\n config.set :pretend, options[:pretend]\n\n options[:pre_vars].each { |name, value| config.set(name, value) }\n\n # load the standard recipe definition\n config.load \"standard\"\n\n options[:recipes].each { |recipe| config.load(recipe) }\n options[:vars].each { |name, value| config.set(name, value) }\n\n actor = config.actor\n options[:actions].each { |action| actor.send action }\n end", "def cap_config\n @cap_config ||= Sauce.instance.new_capistrano_config()\n end", "def parse_options\n @options = {\n :environment => 'production',\n :config_path => ENV['CLOUD_CROWD_CONFIG'] || '.',\n :daemonize => false\n }\n @option_parser = OptionParser.new do |opts|\n opts.on('-c', '--config PATH', 'path to configuration directory') do |conf_path|\n @options[:config_path] = conf_path\n end\n opts.on('-p', '--port PORT', 'port number for server (central or node)') do |port_num|\n @options[:port] = port_num\n end\n opts.on('-e', '--environment ENV', 'server environment (defaults to production)') do |env|\n @options[:environment] = env\n end\n opts.on('-d', '--daemonize', 'run as a background daemon') do |daemonize|\n @options[:daemonize] = daemonize\n end\n opts.on('--days NUM_DAYS', 'grace period before cleanup (7 by default)') do |days|\n @options[:days] = days.to_i if days.match(/\\A\\d+\\Z/)\n end\n opts.on_tail('-v', '--version', 'show version') do\n require \"#{CC_ROOT}/lib/cloud-crowd\"\n puts \"CloudCrowd version #{VERSION}\"\n exit\n end\n end\n @option_parser.banner = BANNER\n @option_parser.parse!(ARGV)\n end", "def initialize(args = [], options = {}, config = {})\n self.behavior = case config[:behavior].to_s\n when \"force\", \"skip\"\n _cleanup_options_and_set(options, config[:behavior])\n :invoke\n when \"revoke\"\n :revoke\n else\n :invoke\n end\n\n super\n self.destination_root = config[:destination_root]\n end", "def command(_arguments = nil, _options = nil)\n config_file = settings.config_file\n if File.exist?(config_file)\n warn HighLine.color(\"Aborting, config file #{config_file} already exists\", :red)\n else\n FileUtils.mkdir_p(settings.root)\n IO.write(config_file, settings.default_config)\n raise IOError, \"Failed to create settings file #{config_file}\" unless File.exist? config_file\n\n puts \"Initializing MT, created #{config_file}\"\n end\n end", "def initialize(capistrano)\n @capistrano = capistrano\n end", "def initialize(config = {}, &block)\n @config = DEFAULT_OPTIONS.merge(config)\n @options = []\n @commands = {}\n @trash = []\n @triggered_options = []\n @unknown_options = []\n @callbacks = {}\n @separators = {}\n @runner = nil\n @command = config.delete(:command)\n\n if block_given?\n block.arity == 1 ? yield(self) : instance_eval(&block)\n end\n\n if config[:help]\n on('-h', '--help', 'Display this help message.', :tail => true) do\n puts help\n exit\n end\n end\n end", "def build_ansible_aws_config(options)\n exists = check_aws_image_exists(options)\n if exists == true\n handle_output(options,\"Warning:\\tAWS image already exists for '#{options['name']}'\")\n quit(options)\n end\n options['clientdir'] = options['clientdir']+\"/ansible/aws/\"+options['name']\n yaml_file = options['clientdir']+\"/\"+options['name']+\".yaml\"\n if not File.exist?(yaml_file)\n handle_output(options,\"Warning:\\tAnsible AWS config file '#{yaml_file}' does not exist\")\n quit(options)\n end\n message = \"Information:\\tBuilding Ansible AWS instance using AMI name '#{options['name']}' using '#{yaml_file}'\"\n command = \"cd #{options['clientdir']} ; ansible-playbook -i hosts #{yaml_file}\"\n execute_command(options,message,command)\n get_ansible_instance_info(options['name'])\n return\nend", "def configure\n # make sure there's a zonecfg from some source\n if @resource[:zonecfg_archive].nil? && @resource[:zonecfg_export].nil?\n fail \"No configuration resource is defined.\"\n end\n\n # open zonecfg_export as a file if possible or treat it like a string\n unless @resource[:zonecfg_export].nil? || @resource[:zonecfg_export].empty?\n begin\n file = File.open(@resource[:zonecfg_export], \"rb\")\n exported_cfg = file.read.gsub(/[\\n]\\n*\\s*/, \"; \")\n rescue\n exported_cfg = @resource[:zonecfg_export].gsub(/[\\n]\\n*\\s*/, \"; \")\n ensure\n file.close unless file.nil?\n end\n end\n\n # start building a command line\n command = \"#{command(:cfg)} -z #{@resource[:name]}\"\n\n # start building the subcommands\n command << \" '\"\n\n # use an archive if specified\n if !@resource[:zonecfg_archive].nil?\n # use the config from the archive\n command << \"create -a #{@resource[:zonecfg_archive]}\"\n\n # use an archived zone if specified\n if !@resource[:archived_zonename].nil?\n command << \" -z #{@resource[:archived_zonename]}\"\n end\n\n command << \";\"\n end\n\n # use the exported zonecfg if specified\n if !@resource[:zonecfg_export].nil? and !exported_cfg.nil?\n command << \" #{exported_cfg}\"\n end\n\n # end the subcommands\n command << \"'\"\n\n # execute the command to configure the zone\n if command\n exec_cmd(:cmd => command)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The current_user can be found in the JWT payload; eagerly load the user's roles so they can be discriminated against
def current_user @current_user ||= User.includes(:roles).find_by(id: payload['user_id']) end
[ "def current_user\n @current_user ||= CurrentUser.includes(:roles).find_by(email: id_token[:email])\n end", "def current_user\n if decoded_payload\n # Can't use symbol for hash key, JWT parses it as string\n @current_user ||= User.find_by(id: decoded_payload['user_id'])\n end\n end", "def fetch_roles\n @current_user.nil? ? [] : @current_user.roles\n end", "def current_roles\n return [] unless defined? current_user\n return [] if current_user.empty?\n\n current_user.roles\n end", "def current_jwt_user\n #\n @jwt_user ||= (defined? session and session[:jwt_user]) ? JwtUser.where(id: session[:jwt_user]).first : nil\n end", "def current_jwt_user\n @jwt_user ||= session[:jwt_user] ? JwtUser.where(id: session[:jwt_user]).first : nil\n end", "def current_user\n token_locations = [cookies[:auth_token], ENV['DANGEROUS_AUTH_HACK'], params[:auth_token]]\n token = token_locations.find{|x| !x.blank? }\n if token\n Identity.includes(:person).find_by(token: token).try(:person)\n else\n nil\n end\n end", "def current_user!\n @current_user = current_user || User.create!(token_subject: @authz_jwt[:sub])\n rescue ActiveRecord::ActiveRecordError => ex\n raise UserNotFound.new(ex.message)\n end", "def select\n @users ||= User.role_wise_users(params[:user][:role])\n authorize! :read, @user\n end", "def current_jwt_auth\n #\n @jwt_auth ||= (defined? session and session[:jwt_auth]) ? JwtToken.where(id: session[:jwt_auth]).first : nil\n end", "def current_user\n decoded_hash = decoded_token(token)\n if !decoded_hash.empty?\n user_id = decoded_hash[0][\"user_id\"]\n\t\t\tuser = User.find(user_id)\n\t\telse\n\t\t\treturn \"hello from current User\"\n end\n end", "def get_curr_user\n render json: current_user\n end", "def user_role\n current_user.role if current_user\n end", "def current_role\n self.roles[0].toString\n end", "def current_jwt_token\n @jwt_auth ||= session[:jwt_auth] ? JwtToken.where(id: session[:jwt_auth]).first : nil\n end", "def current_user\n restrict(native.user_profiles, id: user_id)\n end", "def hubssolib_get_user_roles\n user = self.hubssolib_current_user\n user ? user.user_roles.to_authenticated_roles : nil\n end", "def current_user_has_any_role?(node)\n current_user.present? && current_user.has_any_role?(node)\n end", "def check_user_allowed_to_view_roles\n raise NotAllowed unless @client.associated_users_readable_by(current_user).include?(@user)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
called after the user has been destroyed delete all user maps
def delete_maps own_maps.each do | map | logger.debug "deleting map #{map.inspect}" map.destroy end end
[ "def clear_users\n @users = {}\n end", "def clear_users\n @users = {}\n end", "def delete_user_machine_mapping\n output = IO.popen(\"mozybfstcli user show\").readlines\n data = JSON.parse(output[1])\n data = data['items']\n data.each do |item|\n if (item['data']['deleted']).to_s == 'false'\n user = item['data']['username']\n system(\"mozybfstcli user remove -u #{user}\")\n break\n end\n end\n end", "def destroy\n @usermap.destroy\n respond_to do |format|\n format.html { redirect_to usermaps_url, notice: 'Usermap was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def unload!\n @versions = nil\n @version_json = {}\n @last_update = {}\n @maps = {}\n @mappings = nil\n end", "def destroy\n super()\n self.users.map { |u| u.destroy(deep_destroy: true) }\n return nil\n end", "def delete\n\t\tcurrent_user\n\t\tcurrent_user.regexpressions.destroy_all\n\t\tcurrent_user.tasks.destroy_all\n\t\tcurrent_user.clouds.destroy_all\n\t\tcurrent_user.platforms.destroy_all\n\t\tcurrent_user.demos.destroy_all\n\t\tcurrent_user.favorites.destroy_all\n\tend", "def destroy\n @usermap = Usermap.find(params[:id])\n @usermap.destroy\n\n respond_to do |format|\n format.html { redirect_to(usermaps_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @mapuser.destroy\n respond_to do |format|\n format.html { redirect_to mapusers_url, notice: 'Mapuser was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_mapping.destroy\n respond_to do |format|\n format.html { redirect_to user_mappings_url, notice: 'User mapping was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def cleanup_locations\n Location.all.each do |location|\n location.destroy unless @uf2_location_uids.include?(location.uid)\n end\n end", "def cleanup_locations\n Location.all.each do |location|\n location.destroy if has_different_location_uid?(location)\n end\n end", "def delete\n Modeles::User.delete @userInTable.id\n @userInTable = nil\n @name = nil\n @groups = nil\n @mail = nil\n @website = nil\n @isAdmin = nil\n @files = nil\n @errors = nil\n end", "def destroy\n @user_tracker.destroy\n \n end", "def clear_map(handle)\n map_group_keys = storage.map_keys_get(keys_key(handle))\n map_group_keys.each do |group_key|\n storage.delete(data_key(handle, group_key))\n end\n storage.delete(keys_key(handle))\n storage.delete(map_total_count_key(handle))\n storage.delete(map_finished_count_key(handle))\n end", "def cdb_destroy\n couchdb.delete(\"webui_user\", @name, @couchdb_rev)\n end", "def cdb_destroy\n couchdb.delete(\"webui_user\", @name, @couchdb_rev)\n end", "def clear_user_and_mark_purged\n random_suffix = (('0'..'9').to_a + ('a'..'z').to_a).sample(8).join\n\n self.studio_person_id = nil\n self.name = nil\n self.username = \"#{SYSTEM_DELETED_USERNAME}_#{random_suffix}\"\n self.current_sign_in_ip = nil\n self.last_sign_in_ip = nil\n self.email = ''\n self.hashed_email = ''\n self.parent_email = nil\n self.encrypted_password = nil\n self.uid = nil\n self.reset_password_token = nil\n self.full_address = nil\n self.properties = {}\n\n self.purged_at = Time.zone.now\n\n save!\n end", "def destroy_user_preferences\r\n block_name = \"gr#{id}_block\".underscore\r\n userpref_list = UserPreference.select{|u| u.others[:graph_alloc]}\r\n userpref_list.each do |up|\r\n upref = up.others[:graph_alloc]\r\n %w(top left right).each{|k| (upref[k] ||=[] ).delete block_name}\r\n user = up.user\r\n user.pref[:graph_alloc] = upref\r\n user.pref.save\r\n end\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set meta tags for the page. See MetaTags::ViewHelperset_meta_tags for details.
def set_meta_tags(meta_tags) self.meta_tags.update(meta_tags) end
[ "def set_page_meta_tags\n req = self.request\n set_meta_tags_for_url_path(req.base_url, req.fullpath)\n end", "def page_meta_tags\n set_meta_tags title: seo_data[:title]\n set_meta_tags description: seo_data[:description]\n set_meta_tags keywords: seo_data[:keywords]\n set_meta_tags canonical: current_url\n set_meta_tags charset: 'utf-8'\n set_meta_tags icon: [{href: '/favicon.png', type: 'image/png' },\n {href: '/apple-touch-favicon.png', rel: 'apple-touch-icon-precomposed', type: 'image/png'}]\n set_meta_tags og: social_network_params\n set_meta_tags twitter: social_network_params.merge({card: 'summary'})\n end", "def page_meta_tags\n if block_given?\n set_page_meta_tags(yield)\n else\n emit_page_meta_tags\n end\n end", "def set_page_meta_tags(pairs = nil)\n @page_meta_tags = {}\n merge_meta_tags!(pairs) if pairs.present?\n merge_meta_tags!(yield) if block_given?\n @page_meta_tags\n end", "def setExtractMetaTags(value)\n @fields['extract_meta_tags'] = value\n self\n end", "def set_meta_tags\n @meta_tags ||= Hash.new\n\n return unless @cms_page.respond_to?(:meta_information)\n\n request_uri = request.env['PATH_INFO']\n\n if @cms_page\n @meta_tags = @cms_page.meta_information\n elsif @cms_page = get_cms_page_for(request_uri)\n @meta_tags = @cms_page.meta_information\n elsif @cms_page = OpenGraphTags.config[:cms_page].try(:root)\n @meta_tags = @cms_page.meta_information\n @meta_tags[:url] = request_uri if @meta_tags\n end\n end", "def []=(name, value)\n @meta_tags[name] = value\n end", "def meta_tags\n\t\toutput = ''\n\n\t\toutput << content_tag('title', meta_title)\n\t\toutput << \"\\n\"\n\t\toutput << tag('meta', name: 'description', content: meta_description)\n\t\toutput << \"\\n\"\n\t\toutput << tag('meta', name: 'keywords', content: meta_keywords)\n\t\toutput << \"\\n\"\n\n\t\tfor link in @meta[:links]\n\t\t\toutput << tag('link', link[:options])\n\t\t\toutput << \"\\n\"\n\t\tend\n\n\t\tfor extra_params in @meta[:extra]\n\t\t\toutput << tag('meta', name: extra_params[:name], content: extra_params[:content])\n\t\t\toutput << \"\\n\"\n\t\tend\n\n\t\toutput.html_safe\n\tend", "def set_meta_tags_title\n set_meta_tags site: 'benradler.com'\n end", "def prepare_meta_tags(options={})\n site_name = I18n.t('meta_tag.site_name')\n title = I18n.t('meta_tag.title')\n description = I18n.t('meta_tag.description')\n image = options[:image] || ActionController::Base.helpers.image_url('/homepage/teaser_bg.jpg')\n current_url = request.url\n\n # Let's prepare a nice set of defaults\n defaults = {\n site: site_name,\n title: title,\n image: image,\n description: description,\n keywords: %w[bookmarks web mobile free application],\n twitter: {\n site_name: site_name,\n site: '@wundermarks',\n card: 'summary',\n description: :description,\n image: image\n },\n og: {\n url: current_url,\n site_name: site_name,\n title: :title,\n image: image,\n description: :description,\n type: 'website'\n }\n }\n\n options.reverse_merge!(defaults)\n\n set_meta_tags options\n end", "def update_meta_tag(key, value)\n set_meta_tags({key => value})\n end", "def set_Meta(value)\n set_input(\"Meta\", value)\n end", "def replace_page_meta_tags(pairs = nil)\n @page_meta_tags ||= DEFAULT_PAGE_META_TAGS.dup\n @page_meta_tags.merge!(pairs) if pairs.present?\n @page_meta_tags.merge!(yield) if block_given?\n @page_meta_tags\n end", "def set_meta_tags_for_url_path(base_url, request_fullpath)\n\n page_title = t(LOCALE_TITLE_KEY, default: SiteMetaInfoDefaults.title)\n page_desc = t(LOCALE_DESCRIPTION_KEY, default: SiteMetaInfoDefaults.description)\n\n set_meta_tags site: SiteMetaInfoDefaults.site_name,\n title: page_title,\n description: page_desc,\n keywords: create_keywords\n\n set_page_meta_images\n\n set_og_meta_tags(site_name: SiteMetaInfoDefaults.site_name,\n title: helpers.full_page_title(page_title: page_title),\n description: page_desc,\n type: t(LOCALE_TYPE_KEY, default: SiteMetaInfoDefaults.og_type),\n base_url: base_url,\n fullpath: request_fullpath)\n\n set_facebook_meta_tags\n\n set_twitter_meta_tags(card: t(LOCALE_TWITTER_CARD_KEY, default: SiteMetaInfoDefaults.twitter_card_type))\n\n end", "def set_meta\n title = \"Are You Ready To Take The Ideal Me 'Dream Life' Challenge?\"\n description = \"12 Goals, One A Month, The Best Celeb Experts, Info & Products & Testing It For Max Results In Minimal Time To See What Works, What Doesn't And How To Become Your Ideal Me\"\n image = ''\n set_meta_tags(og: { site_name: 'Ideal Me', title: title, description: description, type: :website, url: 'https://www.idealme.com', image: image },\n fb: { admins: %w(100004702779319 278115168965598 470201106346280).join(',') },\n twitter: { card: 'summary', title: title, description: description, image: image },\n server: IM_HOSTNAME\n\n )\n end", "def default_meta_tags\r\n # set main site title\r\n set_meta_tags :site => I18n.t('meta_tags.defaults.site', :default => '')\r\n\r\n # set keywords\r\n c = I18n.t \"meta_tags.#{controller_name}.#{action_name}.keywords\", :default => ''\r\n b = I18n.t \"meta_tags.#{controller_name}.defaults.keywords\", :default => ''\r\n r = I18n.t \"meta_tags.defaults.keywords\", :default => ''\r\n [b, c].each do |t|\r\n r = \"#{r}, #{t}\" unless t.blank?\r\n end\r\n set_meta_tags :keywords => r.split(', ')\r\n\r\n # set other tags\r\n [:title, :description].each do |tag|\r\n result = I18n.t \"meta_tags.#{controller_name}.#{action_name}.#{tag}\", :default => ''\r\n result = I18n.t \"meta_tags.#{controller_name}.defaults.#{tag}\", :default => '' if result.blank?\r\n result = I18n.t \"meta_tags.defaults.#{tag}\", :default => '' if result.blank?\r\n\r\n set_meta_tags tag => result unless result.blank?\r\n end\r\n end", "def default_meta_tags\n # set main site title\n set_meta_tags :site => I18n.t('meta_tags.defaults.site', :default => '')\n\n # set keywords\n c = I18n.t \"meta_tags.#{controller_name}.#{action_name}.keywords\", :default => ''\n b = I18n.t \"meta_tags.#{controller_name}.defaults.keywords\", :default => ''\n r = I18n.t 'meta_tags.defaults.keywords', :default => ''\n [b, c].each do |t|\n r = \"#{r}, #{t}\" unless t.blank?\n end\n set_meta_tags :keywords => r.split(', ')\n\n # set other tags\n [:title, :description].each do |tag|\n result = I18n.t \"meta_tags.#{controller_name}.#{action_name}.#{tag}\", :default => ''\n result = I18n.t \"meta_tags.#{controller_name}.defaults.#{tag}\", :default => '' if result.blank?\n result = I18n.t \"meta_tags.defaults.#{tag}\", :default => '' if result.blank?\n\n set_meta_tags tag => result unless result.blank?\n end\n end", "def render_custom(tags)\n meta_tags.meta_tags.each do |name, data|\n Array(data).each do |val|\n tags << Tag.new(:meta, :name => name, :content => val)\n end\n meta_tags.extract(name)\n end\n end", "def set_seo_meta(title, options = {})\n keywords = options[:keywords] || \"\"\n description = options[:description] || \"\"\n\n if title.length > 0\n @page_title = \"#{title} &raquo; \"\n end\n @meta_keywords = keywords\n @meta_description = description\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
routines to add: is mysql even installed? is mysql process started? is mysql listening at all on remote node? check the cluster status on a remote node start the mysql service with the given address restart the mysql service cos the cluster is complete
def create # this routine creates the cluster - if this runs, exists? has exited false # first we check all the nodes to ensure mysql is listening, and if the # wsrep_cluster_status is primary. If one is, we'll join it. # array cluster_servers is the list of hosts to check first_node = true gcomm_address = "gcomm://" @resource[:cluster_servers].each { | node | if @resource[:hostname] != node # not this host, so do the check puts "checking host #{node} for Primary" #TODO - refactor this to simplify, it's ugly like this begin cluster_check_result = mysql([defaults_file, "-h", node, '-NBe', "show status like 'wsrep_cluster_status'"].compact) puts "Result of check on #{node} was #{cluster_check_result}" rescue => e debug(e.message) cluster_check_result = "someerror" end if cluster_check_result.match(/Primary/) first_node = false gcomm_address = "gcomm://#{node}" puts "Node #{node} matched Primary, first_node is #{first_node}, address is now #{gcomm_address}" # TODO what happens when mysql isn't listening on node? # that node is a primary, we can connect to it # we should end the loop here, but it probably doesn't hurt if we don't #break else puts "host #{node} is not a primary" end end } # after that loop, we'll have a boolean first_node that tells if this is the first node. if first_node == true puts "This is the first node of the cluster, so we will create the cluster now, address: #{gcomm_address}" # this is the first node, and it's not yet a cluster else puts "first node is #{first_node}, address: #{gcomm_address}" end # stop the service mysqladmin([defaults_file, "shutdown"].compact) service([@resource[:servicename], "stop"].compact) # start it special with the address as set above # TODO if this is the first node, do another check after some random sleep time, just in case... mysql_startup = fork do exec "/usr/bin/mysqld_safe --wsrep_cluster_address=#{gcomm_address}" end Process.detach(mysql_startup) end
[ "def check_for_mysql_presence(host,user,system_user)\n Net::SSH.start(host,system_user, {auth_methods: %w( publickey )}) do |ssh|\n output = ssh.exec!(\"ps -U #{user} -u #{user} u\")\n if output =~ /mysql/\n $results += 1\n # Grab the port number. This requires ruby 1.9.2+\n /port=(?<port>\\d+)/ =~ output\n puts \"MySQL Match on #{host}:#{port} for #{user}\".blue\n end\n end\n end", "def start_mysql(*options)\n if @master\n @repl_paused = options.include?('--skip-slave-start')\n end\n running = ssh_cmd \"netstat -ln | grep ':#{@port}' | wc -l\"\n raise \"[#{@ip}] Failed to start MySQL: Something is already listening on port #{@port}\" unless running.chomp == '0'\n if options.size == 0\n output \"Attempting to start MySQL, no option overrides supplied\"\n else\n output \"Attempting to start MySQL with options #{options.join(' ')}\"\n end\n output service(:start, 'mysql', options.join(' '))\n @options = options\n confirm_listening\n @running = true\n if role == :master && ! @options.include?('--skip-networking')\n disable_read_only!\n end\n end", "def wait_for_mysql_server\n if !is_mapr_mysql_server\n run_in_ruby_block('wait_for_mysql_server') do\n wait_for_service(node['mapr']['mysql_service_name'])\n end\n end\n end", "def check_mysql\n key = \"HKLM\\\\SOFTWARE\"\n if registry_enumkeys(key).include?(\"MySQL AB\")\n print_status(\"\\tMySQL Server found.\")\n return true\n end\n return false\n rescue\n return false\n end", "def probe_running\n if @host.available?\n status = service(:status, 'mysql').downcase\n # mysql is running if the output of \"service mysql status\" doesn't include any of these strings\n not_running_strings = ['not running', 'stop/waiting']\n @running = not_running_strings.none? {|str| status.include? str}\n else\n @running = false\n end\n end", "def mysqlHealth(envid)\n now = Time.now\n env = $envManager.getEnv(envid)\n vmList = env.getVMList()\n vmList.each { |vm|\n cmd = \"ssh carina@#{vm.ipaddress} mysqladmin ping\"\n lineread = false\n IO.popen(cmd) { |f|\n if f.eof\n if !lineread\n $Logger.debug \"MySqlHealthPlugin: mysqld is not alive - no output from mysqladmin ping\"\n vm.status = \"SICK\"\n return 0\n end\n break\n end\n v = f.readline\n puts \"MySqlHealthPlugin: Processing line: #{v}\"\n lineread=true\n if !v.include? 'is alive'\n $Logger.debug \"MySqlHealthPlugin: mysqld is not alive\"\n vm.status = \"SICK\"\n return 0\n end\n }\n }\n $Logger.debug \"MySqlHealthPlugin: mysqld is alive\"\n return 1\n end", "def db_server_started?\n #if deleted it doesn't exist anymore\n if not File.exists?(@shm_db)\n false\n elsif \n Dir.chdir(@shm_db) \n resp = `derby/bin/NetworkServerControl ping`\n Dir.chdir(@admin_folder)\n not (resp =~ /Connection\\sobtained/).nil?\n end\n \n end", "def dbserver_up?(_server)\n if (self.is_ubuntu)\n my_cnf_path = '/etc/mysql/my.cnf'\n else\n my_cnf_path = '/etc/my.cnf'\n end\n\n server_up = true\n state = Acquia::FieldsStatus.new()\n ssh(_server){|s|\n Log.logger.info(\"Verifying mysqld running\")\n cmd = 'ps -ef'\n pattern = 'mysqld'\n if (!action_complete?(s, cmd,pattern))\n state.add_fail('No mysqld process')\n end\n Log.logger.info(\"Verifying mysqld my.cnf\")\n cmd = 'test -f '+ my_cnf_path +' -a -s '+ my_cnf_path+' && echo '+ my_cnf_path + ' ok'\n pattern = my_cnf_path.gsub(/\\//,'\\/') + ' ok'\n if (!action_complete?(s, cmd,pattern))\n state.add_fail('Bad dbserver my.cnf')\n end\n Log.logger.info(\"Verifying mysqld fields config php\")\n config_bin_path = '/usr/local/sbin/'\n config_bin = 'fields-config-db.php'\n # config_bin = 'fields-config-hosts.php'\n config_full_path = config_bin_path+config_bin\n cmd = 'test -f '+ config_full_path +' -a -s '+ config_full_path+' && echo '+ config_bin + ' script ok'\n pattern = config_bin + ' script ok'\n if (!action_complete?(s, cmd,pattern))\n state.add_fail(config_bin +' not ok')\n end\n # We used to run fields-config-db.php here to make sure /root/.my.cnf was\n # set up before connecting to mysqld. However, puppet runs ah-set-db-root\n # now, and we've already verified puppet has succeeded.\n Log.logger.info(\"Verifying mysqld/puppet crontab\")\n cmd = 'crontab -l'\n pattern = config_full_path.gsub(/\\//, '\\/')\n if (!action_complete?(s, cmd,pattern))\n state.add_fail(config_bin +' crontab not ok')\n end\n Log.logger.info(\"Verifying mysqld connection\")\n cmd = 'mysql -e \\'show databases;\\''\n pattern = '\\s+mysql\\s+'\n if (!action_complete?(s, cmd,pattern))\n state.add_fail('Cannot connect to mysqld')\n end\n }\n unless (state.passed)\n Log.logger.warn(\"Problem with dbserver configuration: #{state.get_fail_message}\")\n end\n return state\n end", "def activate_service(modified=false)\n service = \"mysql\"\n modified |= interpreter.service_manager.enable(service)\n modified |= interpreter.service_manager.start(service)\n return modified\n end", "def probe(force=false)\n return if probed? && !force\n output \"Probing MySQL installation\"\n probe_running\n probe_master\n probe_slaves\n self\n end", "def calculate_manage_cassandra\n hosts = [cassandra_hosts].flatten\n hosts = hosts.map { |x| x.split(':', 2).first }\n !(hosts & %w(localhost 127.0.0.1)).empty?\n end", "def karaf_started?\n on roles(:esb) do\n as \"smx-fuse\" do\n n = capture('netstat -ao | grep 8101 | wc -l')\n n.to_i > 0\n end\n end\nend", "def mysql_installed?\n !which('mysql').nil?\n end", "def manage_cassandra\n calculate_management('cassandra')\n end", "def status\n return true unless managed?\n\n out = exec_solr('status').read\n out =~ /running on port #{port}/\n end", "def cluster_exists?\n not (search(:node, 'recipes:ceph\\:\\:mon').empty?)\n end", "def is_service_installed?(service, platform_families = node['platform_family'])\n if platform_family?(platform_families)\n # Add chkconfig for alinux2 and centos platform, because they do not generate systemd unit file automatically from init script\n # Ubuntu platform generate systemd unit file from init script automatically, if the service is not found by systemd the check will fail because chkconfig does not exist\n shell_out(\"systemctl daemon-reload; systemctl list-unit-files --all | grep #{service} || chkconfig --list #{service}\").exitstatus.to_i.zero?\n else\n # in case of different platform return false\n false\n end\nend", "def start_memcached\n exec [\"service\", \"memcached\", \"start\"]\nend", "def mw_mysql_replication_server(instance_name, template, options)\n mw_mysql_server instance_name, options\n\n node.set['mw_mysql']['instances']||= {}\n node.set['mw_mysql']['instances'][instance_name]['log_dir'] = \"/var/log/mysql-#{instance_name}\"\n\n mysql_config \"Replication #{instance_name}\" do\n config_name 'replication'\n instance instance_name\n source template\n cookbook 'mw_mysql'\n variables(server_id: options[:server_id], mysql_instance: instance_name, logs: node['mw_mysql']['instances'][instance_name]['log_dir'])\n notifies :restart, \"mysql_service[#{instance_name}]\", :immediately\n action :create\n end\n\n mw_replication_create_user options\nend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /report_orders_by_users GET /report_orders_by_users.json
def index @report_orders_by_users = ReportOrdersByUser.all end
[ "def show_user_reports\n reports = User.find(params[:id]).reports\n render :json => reports\n end", "def orders_report(start_date, end_date, status, format, offset=0)\n rest_url = \"#{@api}/report/orders/detail/#{format}?startDate=#{start_date}&endDate=#{end_date}&status=#{status}&offset=#{offset}\"\n RestClient.get rest_url, @header\n end", "def orders\r\n\t\t@current_area = 'orders_report'\r\n\t\t@current_menu = 'reports'\r\n\r\n\t\tif request.post? || (request.get? && params[:page])\r\n\t\t\t@report_title = 'Orders'\r\n\t\t\tfilename = 'reports/orders'\r\n\t\t\t@criteria = [\"status='completed'\"]\r\n\r\n\t\t\t@page = (params[:page] || 1).to_i\r\n\t\t\t@items_per_page = 20\r\n\t\t\t@offset = (@page - 1) * @items_per_page\r\n\r\n\t\t\tif params[:start_date]\r\n\t\t\t\t@start_date = ffs_parse_date(params[:start_date])\r\n\r\n\t\t\t\t@criteria << \"(created_at >= '\" + @start_date.strftime('%Y-%m-%d') + \"')\"\r\n\t\t\t\tfilename += '-' + @start_date.strftime('%Y-%m-%d')\r\n\t\t\t\t@report_title += ': ' + @start_date.strftime('%d/%m/%Y')\r\n\t\t\tend\r\n\r\n\t\t\tif params[:end_date]\r\n\t\t\t\t# We want to show records that fall before the day after the end date\r\n\t\t\t\t@end_date = ffs_parse_date(params[:end_date])\r\n\t\t\t\tquery_end_date = @end_date + 1\r\n\r\n\t\t\t\t@criteria << \"(created_at <= '\" + query_end_date.strftime('%Y-%m-%d') + \"')\"\r\n\t\t\t\tfilename += '-to-' + @end_date.strftime('%Y-%m-%d')\r\n\t\t\t\t@report_title += ' to ' + @end_date.strftime('%d/%m/%Y')\r\n\t\t\telse\r\n\t\t\t\t@report_title += ' to present'\r\n\t\t\tend\r\n\r\n\t\t\t@order_count = Order.count(@criteria.join(' AND '))\r\n\t\t\t@pages = Paginator.new(self, @order_count, @items_per_page, @page)\r\n\t\t\t@orders = Order.find(\r\n\t\t\t\t:all,\r\n\t\t\t\t:conditions => @criteria.join(' AND '),\r\n\t\t\t\t:order => 'created_at DESC',\r\n\t\t\t\t:offset => params[:download] ? 0 : @offset,\r\n\t\t\t\t:limit => params[:download] ? nil : @items_per_page\r\n\t\t\t)\r\n\r\n\t\t\t# make Excel file if download is selected - otherwise render in page\r\n\t\t\tif params[:download]\r\n\t\t\t\t@rows = @orders.collect { |x| [ x.id, [x.created_at, :date], x.user.to_s, x.delivery_address ? x.delivery_address.country : x.billing_address.country, x.items.count, [x.total, :price] ] }\r\n\r\n\t\t\t\t@report_title += ' ' + Date.today.strftime('%d/%m/%Y')\r\n\t\t\t\tfilename += '.xls'\r\n\r\n\t\t\t\treport = Report.new filename\r\n\t\t\t\treport.write 0, 0, @report_title, :title\r\n\t\t\t\treport.write 1, 0, [ 'ID', 'Date', 'User', 'Country', 'Items', 'Total' ], :heading\r\n\t\t\t\treport.write_rows @rows\r\n\t\t\t\treport.close\r\n\r\n\t\t\t\t@headers['Expires'] = '0'\r\n\t\t\t\t@headers['Cache-Control'] = 'must-revalidate,post-check=0,pre-check=0'\r\n\t\t\t\t@headers['Pragma'] = 'public'\r\n\r\n\t\t\t\tsend_file filename, :type => 'application/vnd.ms-excel', :stream => false\r\n\t\t\t\tFile.delete filename\r\n\t\t\tend\r\n\t\telse\r\n\t\t\t@start_date = @end_date = Date.today\r\n\t\tend\r\n\tend", "def index\n @planned_orders = PlannedOrder.where(:user => current_user.email).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @planned_orders }\n end\n end", "def my_reports\n @reports ||= Report.user(current_user).all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @reports }\n end\n end", "def user_report\n user = User.find_by_username(params[:username])\n raise Discourse::InvalidParameters.new(:username) if !user\n\n ignored_ids = DiscourseFingerprint.get_ignores(user)\n\n fingerprints =\n Fingerprint\n .where(user: user)\n .where.not(value: FlaggedFingerprint.select(:value).where(hidden: true))\n .order(updated_at: :desc)\n\n user_ids =\n Fingerprint\n .matches\n .where(value: fingerprints.pluck(:value))\n .to_h { |match| [match.value, match.user_ids - [user.id]] }\n\n users = User.where(id: user_ids.values.flatten.uniq).or(User.where(id: ignored_ids))\n\n render json: {\n user: BasicUserSerializer.new(user, root: false),\n ignored_ids: ignored_ids,\n fingerprints:\n serialize_data(fingerprints, FingerprintSerializer, scope: { user_ids: user_ids }),\n users: users.map { |u| [u.id, BasicUserSerializer.new(u, root: false)] }.to_h,\n }\n end", "def index_by_user\n # find the user by username\n user = User.find_by(username: params[:user_id])\n # find the fills by user.id\n @fills = Fill.where(user_id: user.id)\n render json: @fills, include: ['user', 'prompt', 'comments.user', 'comments.user.id', 'comments.user.username']\n end", "def orders\n params = { command: 'account_orders' }\n get('/json.php', params)\n end", "def index\n @user_orders = Order.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @user_orders }\n end\n end", "def show\n @users_report = UsersReport.find(params[:id])\n\n render json: @users_report\n end", "def index\n @mpi_statistics_reports = MpiStatisticsReport.includes({:batch => [:client, :facility]}, :user, {:eob => :check_information}).limit(20).order(\"id desc\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @mpi_statistics_reports }\n end\n end", "def index\n @users = user_list(true)\n @users = page(@users)\n respond_to do |format|\n format.html\n format.json\n format.csv { send_data @users.to_csv, filename: \"users-#{Date.today}.csv\" }\n end\n end", "def company_all_orders_by_users_company\n @user = User.find(session[:user_id]) \n @orders = Order.where(user_id: @user.id, company_id: @user.company_id)\n end", "def employee_repair_orders_index\n\n @employee = current_employee_user.id\n\n @employee_repair_orders = current_business_user.employee_users_repair_orders.where(\n employee_user_id: @employee )\n if @employee_repair_orders\n render json: { employee_repair_orders: @employee_repair_orders.as_json(include: [\n :repair_order,\n :client,\n :vehicle]) },\n status: :ok\n else\n render json: { employee_repair_orders: @employee_repair_orders.errors.full_messages },\n status: :unprocessable_entity\n end\n end", "def all\n @hour_reports = HourReport.find(:all, :conditions => {:user_id => current_user.id })\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @hour_reports }\n end\n end", "def user_orders\n @order_status = {\n 'paid' => 'Objets payés',\n 'being_shipped' => 'En cours de livraison',\n 'shipped' => 'Objets reçus'\n }\n\n @user_orders = @user.orders.order('created_at DESC')\n end", "def export_user_request\n @user = User.find(params[:id])\n @user_requests = @user.pto_requests\n\n respond_to do |format|\n format.csv { send_data @user_requests.to_csv }\n end\n end", "def fetch\n credit_histories = CreditHistory.where(user_id: params[:user_id])\n .order('created_at DESC')\n paginate json: credit_histories\n end", "def index\n @orders = current_user.orders\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /report_orders_by_users POST /report_orders_by_users.json
def create @report_orders_by_user = ReportOrdersByUser.new(report_orders_by_user_params) respond_to do |format| if @report_orders_by_user.save format.html { redirect_to @report_orders_by_user, notice: 'Report orders by user was successfully created.' } format.json { render :show, status: :created, location: @report_orders_by_user } else format.html { render :new } format.json { render json: @report_orders_by_user.errors, status: :unprocessable_entity } end end end
[ "def index\n @report_orders_by_users = ReportOrdersByUser.all\n end", "def export_user_request\n @user = User.find(params[:id])\n @user_requests = @user.pto_requests\n\n respond_to do |format|\n format.csv { send_data @user_requests.to_csv }\n end\n end", "def user_report\n user = User.find_by_username(params[:username])\n raise Discourse::InvalidParameters.new(:username) if !user\n\n ignored_ids = DiscourseFingerprint.get_ignores(user)\n\n fingerprints =\n Fingerprint\n .where(user: user)\n .where.not(value: FlaggedFingerprint.select(:value).where(hidden: true))\n .order(updated_at: :desc)\n\n user_ids =\n Fingerprint\n .matches\n .where(value: fingerprints.pluck(:value))\n .to_h { |match| [match.value, match.user_ids - [user.id]] }\n\n users = User.where(id: user_ids.values.flatten.uniq).or(User.where(id: ignored_ids))\n\n render json: {\n user: BasicUserSerializer.new(user, root: false),\n ignored_ids: ignored_ids,\n fingerprints:\n serialize_data(fingerprints, FingerprintSerializer, scope: { user_ids: user_ids }),\n users: users.map { |u| [u.id, BasicUserSerializer.new(u, root: false)] }.to_h,\n }\n end", "def user_orders\n @order_status = {\n 'paid' => 'Objets payés',\n 'being_shipped' => 'En cours de livraison',\n 'shipped' => 'Objets reçus'\n }\n\n @user_orders = @user.orders.order('created_at DESC')\n end", "def questionnaire_report_by_users\r\n\r\n range = @when_start .. @when_end\r\n activity_id = Activity.get_activity('submit questionnaire_answer').id\r\n\r\n user_activities = UserActivity.where(:activity_id => activity_id).where(:created_at => range).joins(:user).all\r\n users = {}\r\n user_activities.each do |au|\r\n unless users[au.user.email]\r\n users[au.user.email] = {:user => \"#{au.user.email} #{au.user.first_name} #{au.user.last_name}\", attendance: {}}\r\n end\r\n users[au.user.email][:attendance][au.created_at.to_date] = true\r\n end\r\n\r\n users\r\n end", "def create\n @report = Report.find(params[:report_id])\n @users_report = @report.users_reports.create!(:user_id => params[:user_id])\n respond_to do |format|\n format.js\n end\n end", "def create\n user = User.find_by_id(params[:user])\n format_response({ success: false, message: \"User ##{params[:user_id]} not found\" }) and return if user.blank?\n\n order = Order.new(\n user_id: user.id\n )\n\n order.order_date = Date.parse(params[:order_date]) unless params[:order_date].blank?\n order.vat_percentage = params[:vat_percentage].to_d unless params[:vat_percentage].blank?\n\n if order.save\n format_response({ success: true, message: \"Order #{order.id} created\" }) and return\n else\n format_response({ success: false, message: order.errors.full_messages.to_sentence }) and return\n end\n end", "def add_export_users(order, except = [])\n @fixed_export.each do |region_code, load_curve|\n next if except.include?(region_code)\n\n order.add(Merit::User.create(\n key: :\"export_to_#{ region_code }\",\n load_curve: load_curve\n ))\n end\n end", "def export\n send_data current_user.records.select(:json).order('updated_at desc').collect(&:json).to_json, filename: 'records.json'\n end", "def student_all_report\n @user = User.find(params[:id])\n report = StringIO.new\n CSV::Writer.generate(report, ',') do |csv|\n #Get Words\n @words = @user.word_answers.find(:all, :order => \"question_id ASC\")\n csv << %w(question answer date)\n @words.each do |answer|\n csv << [answer.word.value, answer.value, answer.created_at]\n end\n #Get Situations\n @situation_answers = @user.completion_answers.find(:all, :order => \"question_id ASC\")\n @situation_answers.each do |answer|\n csv << [answer.completion.value, answer.value, answer.created_at]\n end\n #Get Scenarios\n @scenario_answers = @user.scenario_answers.find(:all, :order => \"question_id ASC\")\n @scenario_answers.each do |answer|\n csv << [answer.scenario.value, answer.value, answer.created_at]\n end\n \n #Get posts\n @posts = @user.posts.find(:all, :order => \"created_at DESC\")\n @posts.each do |post|\n csv << [post.topic.title, post.body, post.created_at]\n end\n end\n export_as_csv(report,@user.whole_name+\"-all\")\n end", "def orders\r\n\t\t@current_area = 'orders_report'\r\n\t\t@current_menu = 'reports'\r\n\r\n\t\tif request.post? || (request.get? && params[:page])\r\n\t\t\t@report_title = 'Orders'\r\n\t\t\tfilename = 'reports/orders'\r\n\t\t\t@criteria = [\"status='completed'\"]\r\n\r\n\t\t\t@page = (params[:page] || 1).to_i\r\n\t\t\t@items_per_page = 20\r\n\t\t\t@offset = (@page - 1) * @items_per_page\r\n\r\n\t\t\tif params[:start_date]\r\n\t\t\t\t@start_date = ffs_parse_date(params[:start_date])\r\n\r\n\t\t\t\t@criteria << \"(created_at >= '\" + @start_date.strftime('%Y-%m-%d') + \"')\"\r\n\t\t\t\tfilename += '-' + @start_date.strftime('%Y-%m-%d')\r\n\t\t\t\t@report_title += ': ' + @start_date.strftime('%d/%m/%Y')\r\n\t\t\tend\r\n\r\n\t\t\tif params[:end_date]\r\n\t\t\t\t# We want to show records that fall before the day after the end date\r\n\t\t\t\t@end_date = ffs_parse_date(params[:end_date])\r\n\t\t\t\tquery_end_date = @end_date + 1\r\n\r\n\t\t\t\t@criteria << \"(created_at <= '\" + query_end_date.strftime('%Y-%m-%d') + \"')\"\r\n\t\t\t\tfilename += '-to-' + @end_date.strftime('%Y-%m-%d')\r\n\t\t\t\t@report_title += ' to ' + @end_date.strftime('%d/%m/%Y')\r\n\t\t\telse\r\n\t\t\t\t@report_title += ' to present'\r\n\t\t\tend\r\n\r\n\t\t\t@order_count = Order.count(@criteria.join(' AND '))\r\n\t\t\t@pages = Paginator.new(self, @order_count, @items_per_page, @page)\r\n\t\t\t@orders = Order.find(\r\n\t\t\t\t:all,\r\n\t\t\t\t:conditions => @criteria.join(' AND '),\r\n\t\t\t\t:order => 'created_at DESC',\r\n\t\t\t\t:offset => params[:download] ? 0 : @offset,\r\n\t\t\t\t:limit => params[:download] ? nil : @items_per_page\r\n\t\t\t)\r\n\r\n\t\t\t# make Excel file if download is selected - otherwise render in page\r\n\t\t\tif params[:download]\r\n\t\t\t\t@rows = @orders.collect { |x| [ x.id, [x.created_at, :date], x.user.to_s, x.delivery_address ? x.delivery_address.country : x.billing_address.country, x.items.count, [x.total, :price] ] }\r\n\r\n\t\t\t\t@report_title += ' ' + Date.today.strftime('%d/%m/%Y')\r\n\t\t\t\tfilename += '.xls'\r\n\r\n\t\t\t\treport = Report.new filename\r\n\t\t\t\treport.write 0, 0, @report_title, :title\r\n\t\t\t\treport.write 1, 0, [ 'ID', 'Date', 'User', 'Country', 'Items', 'Total' ], :heading\r\n\t\t\t\treport.write_rows @rows\r\n\t\t\t\treport.close\r\n\r\n\t\t\t\t@headers['Expires'] = '0'\r\n\t\t\t\t@headers['Cache-Control'] = 'must-revalidate,post-check=0,pre-check=0'\r\n\t\t\t\t@headers['Pragma'] = 'public'\r\n\r\n\t\t\t\tsend_file filename, :type => 'application/vnd.ms-excel', :stream => false\r\n\t\t\t\tFile.delete filename\r\n\t\t\tend\r\n\t\telse\r\n\t\t\t@start_date = @end_date = Date.today\r\n\t\tend\r\n\tend", "def create\n @users_report = UsersReport.new(users_report_params)\n\n respond_to do |format|\n if @users_report.save\n format.html { redirect_to @users_report, notice: 'Users report was successfully created.' }\n format.json { render :show, status: :created, location: @users_report }\n else\n format.html { render :new }\n format.json { render json: @users_report.errors, status: :unprocessable_entity }\n end\n end\n end", "def destroy\n @report_orders_by_user.destroy\n respond_to do |format|\n format.html { redirect_to report_orders_by_users_url, notice: 'Report orders by user was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def update\n respond_to do |format|\n if @report_orders_by_user.update(report_orders_by_user_params)\n format.html { redirect_to @report_orders_by_user, notice: 'Report orders by user was successfully updated.' }\n format.json { render :show, status: :ok, location: @report_orders_by_user }\n else\n format.html { render :edit }\n format.json { render json: @report_orders_by_user.errors, status: :unprocessable_entity }\n end\n end\n end", "def charts_data_for(user)\n charts_data = {}\n\n ### chart user hours ### \n\n # time period\n from = user.registered_at.to_date\n to = Time.now.to_date + 1.week\n charts_data[:user_hours_from] = from \n charts_data[:user_hours_to] = to\n\n # prepare data \n charts_data[:user_hours] = groups_total_hours(current_user.records, from, to, 30) \n\n ### chart user submission ###\n\n # time period\n from = Time.now.to_date.prev_month\n to = Time.now.to_date \n charts_data[:user_submission_from] = from \n charts_data[:user_submission_to] = to\n\n # prepare data \n user_submission = []\n user.projects.each do |project|\n # records are grouped with project\n records = project.records.where(\"records.created_at >= ? and user_id = ?\", from, user.id)\n records.each do |record|\n user_submission << {project: project.name, date: record.created_at.to_date, \n time: record.created_at.strftime(\"%H-%M-%S\"), hours: record.hours}\n end\n end\n charts_data[:user_submission] = user_submission\n \n charts_data.to_json\n end", "def employee_repair_orders_index\n\n @employee = current_employee_user.id\n\n @employee_repair_orders = current_business_user.employee_users_repair_orders.where(\n employee_user_id: @employee )\n if @employee_repair_orders\n render json: { employee_repair_orders: @employee_repair_orders.as_json(include: [\n :repair_order,\n :client,\n :vehicle]) },\n status: :ok\n else\n render json: { employee_repair_orders: @employee_repair_orders.errors.full_messages },\n status: :unprocessable_entity\n end\n end", "def index_by_user\n # find the user by username\n user = User.find_by(username: params[:user_id])\n # find the fills by user.id\n @fills = Fill.where(user_id: user.id)\n render json: @fills, include: ['user', 'prompt', 'comments.user', 'comments.user.id', 'comments.user.username']\n end", "def create_two_orders_with_different_users\n order = Order.new\n order.order_status_id = 1\n order.pickup_date = Date.today\n order.order_date = Date.today\n order.user_id = users(:user).id\n order_product = order.order_products.new\n order_product.product_id = products(:whiskey).id\n order_product.quantity = 1\n order.save\n order = Order.new\n order.order_status_id = 1\n order.pickup_date = Date.today\n order.order_date = Date.today\n order.user_id = users(:admin).id\n order_product = order.order_products.new\n order_product.product_id = products(:whiskey).id\n order_product.quantity = 1\n order.save\n end", "def create\n @users_xorder = UsersXorder.new(users_xorder_params)\n\n respond_to do |format|\n if @users_xorder.save\n format.html { redirect_to @users_xorder, notice: 'Users xorder was successfully created.' }\n format.json { render :show, status: :created, location: @users_xorder }\n else\n format.html { render :new }\n format.json { render json: @users_xorder.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /report_orders_by_users/1 PATCH/PUT /report_orders_by_users/1.json
def update respond_to do |format| if @report_orders_by_user.update(report_orders_by_user_params) format.html { redirect_to @report_orders_by_user, notice: 'Report orders by user was successfully updated.' } format.json { render :show, status: :ok, location: @report_orders_by_user } else format.html { render :edit } format.json { render json: @report_orders_by_user.errors, status: :unprocessable_entity } end end end
[ "def update\n @users_report = UsersReport.find(params[:id])\n\n if @users_report.update(params[:users_report])\n head :no_content\n else\n render json: @users_report.errors, status: :unprocessable_entity\n end\n end", "def update #only patch owned reports, do not edit client/user since their ids are in the routing\n @report = Report.find_by(id: params[:id])\n if current_user == @report.user\n #reset bool values that have n/a option\n @report.positive = nil\n @report.appointment = nil\n @report.payment = nil\n @report.update(report_params)\n @report.client_id = report_params[:client_id] if report_params[:client_id]\n redirect_to user_report_path(current_user, @report), notice: \"Report updated\"\n else\n redirect_to user_reports_path(current_user), alert: \"That's not your report\"\n end\n end", "def update\n @api_v1_report = Api::V1::Report.find(params[:id])\n\n if @api_v1_report.user_id == @current_user.id && @api_v1_report.update(api_v1_report_params)\n head :no_content\n else\n render json: @api_v1_report.errors, status: :unprocessable_entity\n end\n end", "def update\n @users_order = Order.find(params[:id])\n\n respond_to do |format|\n if @users_order.update_attributes(params[:order])\n format.html { redirect_to [:users, @users_order], notice: 'Order was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n end\n end\n end", "def update_report_template(args = {}) \n put(\"/reports.json/template/#{args[:templateId]}\", args)\nend", "def update\n @user_reports = UserReport.find(params[:id])\n\n respond_to do |format|\n if @user_reports.update_attributes(params[:user_report])\n flash[:notice] = 'UserReport was successfully updated.'\n format.html { redirect_to(@user_reports) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user_reports.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n json_response(@order.update!(order_params))\n end", "def update\n @user_report = UserReport.find(params[:id])\n\n respond_to do |format|\n if @user_report.update_attributes(params[:user_report])\n flash[:notice] = 'UserReport was successfully updated.'\n format.html { redirect_to(@user_report) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user_report.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @users_xorder.update(users_xorder_params)\n format.html { redirect_to @users_xorder, notice: 'Users xorder was successfully updated.' }\n format.json { render :show, status: :ok, location: @users_xorder }\n else\n format.html { render :edit }\n format.json { render json: @users_xorder.errors, status: :unprocessable_entity }\n end\n end\n end", "def edit #only edit owned reports\n @report = Report.find_by(id: params[:id])\n\n @clients = Client.all\n end", "def update\n @progress_report_user = ProgressReportUser.find(params[:id])\n\n respond_to do |format|\n if @progress_report_user.update_attributes(params[:progress_report_user])\n format.html { redirect_to @progress_report_user, notice: 'Progress report user was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @progress_report_user.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @generated_report.update(generated_report_params)\n format.html { redirect_to @generated_report, notice: \"Generated report was successfully updated.\" }\n format.json { render :show, status: :ok, location: @generated_report }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @generated_report.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @power_order.update(power_order_params)\n render json: @power_order\n end", "def update\n @stage_order.update(stage_order_params)\n render json: @stage_order \n end", "def update\n @api_v1_report_comment = Api::V1::ReportComment.find(params[:id])\n\n if @api_v1_report_comment.user_id == @current_user.id && @api_v1_report_comment.update(api_v1_report_comment_params)\n head :no_content\n else\n render json: @api_v1_report_comment.errors, status: :unprocessable_entity\n end\n end", "def update\n @custom_report = CustomReport.find(params[:id])\n\n if @custom_report.update(params[:custom_report])\n head :no_content\n else\n render json: @custom_report.errors, status: :unprocessable_entity\n end\n end", "def update\n @user_order = UserOrder.find(params[:id])\n\n respond_to do |format|\n if @user_order.update_attributes(params[:user_order])\n format.html { redirect_to(@user_order, :notice => 'User order was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @user_order.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @bulk_order = BulkOrder.find_by_token(params[:id])\n @user = User.find_by_id(session[:user_id]) if session[:user_id]\n @users = @bulk_order.users\n @item = @bulk_order.item\n @buyer_email = params[:stripeEmail]\n if params[:quantity]\n\n @user_order = UserOrder.new()\n @user_order = UserOrder.create_user_order(params,@user,@bulk_order)\n\n @shipping_address = Address.create_shipping_address(params,@user_order)\n @billing_address = Address.create_billing_address(params,@user_order)\n\n if @user\n @bulk_order.users.push(@user)\n end\n @bulk_order.user_orders.push(@user_order)\n @bulk_order.percent_filled = (@bulk_order.percent_filled + params[:quantity].to_i)\n @bulk_order.buyer_count +=1\n\n if @bulk_order.percent_filled >= @bulk_order.max_amount\n @bulk_order.completed = true\n BulkOrder.email_bulk_order_users(@bulk_order)\n ShippoService.create_shipments_bulk_order_fill(@bulk_order)\n end\n # PUT THIS IN ABOVE STATEMENT IN CASE THEY FILL ORDER ON JOING\n if !@user\n NotifMailer.no_user_bulk_order_email(@bulk_order,@user_order).deliver\n end\n\n respond_to do |format|\n if @bulk_order.save\n if @user\n format.html { redirect_to user_path(@user)}\n else\n format.html { redirect_to user_order_path(@user_order)}\n end\n else\n format.html { render :edit }\n format.json { render json: @bulk_order.errors, status: :unprocessable_entity }\n end\n end\n\n StripeService::update_bulk_order_payment(params,@user_order,@bulk_order)\n\n else #IF USER IS EDITING BATCH BEFORE PUBLISH\n @bulk_order.update(bulk_order_params)\n @bulk_order.save\n redirect_to user_supplier_path_url(@user)\n\n end\n end", "def update\n @api_report = Report.find(params[:id])\n if @api_report.update(params[:api_report])\n render json: @api_report, status: :success\n else\n render json: @api_report.errors, status: :unprocessable_entity\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /report_orders_by_users/1 DELETE /report_orders_by_users/1.json
def destroy @report_orders_by_user.destroy respond_to do |format| format.html { redirect_to report_orders_by_users_url, notice: 'Report orders by user was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @users_report = UsersReport.find(params[:id])\n @users_report.destroy\n\n head :no_content\n end", "def destroy\n @user_reports = UserReport.find(params[:id])\n @user_reports.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_reports_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @user_report = UserReport.find(params[:id])\n @user_report.destroy\n\n respond_to do |format|\n format.html { redirect_to(user_reports_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @report.destroy!\n render json: {status: :ok}\n end", "def destroy\n @backend_user_content_report = Backend::UserContentReport.find(params[:id])\n @backend_user_content_report.destroy\n\n respond_to do |format|\n format.html { redirect_to backend_user_content_reports_url }\n format.json { head :ok }\n end\n end", "def destroy\n @progress_report_user = ProgressReportUser.find(params[:id])\n @progress_report_user.destroy\n\n respond_to do |format|\n format.html { redirect_to progress_report_users_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @statusreport = current_user.organization.statusreports.find(params[:id])\n @statusreport.destroy\n respond_to do |format|\n format.html { redirect_to statusreports_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @generated_report.destroy\n respond_to do |format|\n format.html { redirect_to generated_reports_url, notice: \"Generated report was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def delete_report_template(args = {}) \n body_delete(\"/reports.json/template\", args[:array_of_ids])\nend", "def destroy\n @report.destroy\n\n respond_to do |format|\n format.html { redirect_to reports_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @report = Report.find(params[:id])\n @report.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_reports_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @user_reported_statistic = UserReportedStatistic.find(params[:id])\n @user_reported_statistic.destroy\n\n respond_to do |format|\n format.html { redirect_to user_reported_statistics_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @report.destroy\n respond_to do |format|\n format.html { redirect_to reports_url }\n format.json { head :no_content }\n end\n end", "def destroy\n if @customer_report.destroy\n render :json => @customer_report\n else \n render :json => @customer_report.errors.full_messages\n end\n end", "def destroy\n @client_report.destroy\n respond_to do |format|\n format.html { redirect_to client_reports_url, notice: 'Report was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @api_report = Report.find(params[:id])\n @api_report.destroy\n\n head :no_content\n end", "def destroy\n @user_order = UserOrder.find(params[:id])\n @user_order.destroy\n\n respond_to do |format|\n format.html { redirect_to user_orders_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @last_report.destroy\n respond_to do |format|\n format.html { redirect_to last_reports_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @status_report.destroy\n respond_to do |format|\n format.html { redirect_to status_reports_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the point offset in a 3D space
def view_offset @position + Moon::Vector3[@view.position, 0] end
[ "def origin\r\n Point3.origin\r\n end", "def dot(point3)\n (@x*point3.x)+(@y*point3.y)+(@z*point3.z)\n end", "def distance_to(point3)\n Math.sqrt(((@x-point3.x)**2)+((@y-point3.y)**2)+((@z-point3.z)**2))\n end", "def ll_to_point3d(flatten)\n #puts \"x: \" + @x.to_s\n #puts \"y: \" + @y.to_s\n #we are assuming points in latlon\n lla = LLAtude.new([@y.degrees, @x.degrees, 0])\n if flatten\n @z = 0\n else\n @z = lla.position.z\n end\n p = [lla.position.x, lla.position.y, @z]\n return p\n #return lla.position\n #return Geom::Point3d.new(@x, @y, z)\n end", "def point3(x=0, y=0, z=0)\r\n Point3.new(x,y,z)\r\n end", "def to_ole_point3d(pt)\n case pt\n when ole_point3d?(pt)\n pt\n when Point3d\n create_ole_point(pt.x, pt.y, pt.z)\n when Array\n pt1 = pt.map(&:to_f)\n x, y, z = pt1\n z ||= 0.0\n create_ole_point(x, y, z)\n end\n end", "def to_point3d(pt)\n case pt\n when Array\n pt_a = pt.map(&:to_f)\n x, y, z = pt_a\n z ||= 0.0\n Point3d.new(x, y, z)\n when Point3d\n pt\n when WIN32OLE_RECORD\n Point3d.from_ole(pt) if pt.typename == \"Point3d\"\n end\n end", "def test_offset_all_axes\n point2 = nil\n assert_nothing_raised do\n a = [10,10,10]\n vector = Geom::Vector3d.new(2.123,4.567,7.890)\n point2 = a.offset! vector\n end\n expected_point = Geom::Point3d.new 12.123,14.567,17.890\n assert_equal(expected_point, point2,\n 'Failed with 3-axes offset' )\n end", "def physical_position(axis)\n position[axis] + offset[axis]\n end", "def x\n return @x - @map_data.offset_x\n end", "def internal_coordinates\n result = @position.map{ |coord| coord - coord.floor }\n return Vector3DInternal[ *result ]\n end", "def x_offset; end", "def content_offset(offset, dimension)\n if offset >= dimension\n offset - dimension\n\n else\n 0\n\n end\n end", "def point_on_the_line3d(c)\n c2=c.gsub(' ','').insert(c.length,'=')\n m=Array.new() #line has point\n\n if c2.include?('x')\n before=c2.index('x')+1\n after=c2.index('/')\n m[0]=c2.slice(before..after).gsub('/','').to_f*(-1)\n c2=c2.slice(c2.index('='),c2.length).sub('=','')\n else m[0]=0.0\n end\n if c2.include?('y')\n before=c2.index('y')+1\n after=c2.index('/')\n m[1]=c2.slice(before..after).gsub('/','').to_f*(-1)\n c2=c2.slice(c2.index('='),c2.length).sub('=','')\n else m[1]=0.0\n end\n if c2.include?('z')\n before=c2.index('z')+1\n after=c2.index('/')\n m[2]=c2.slice(before..after).gsub('/','').to_f*(-1)\n c2=c2.slice(c2.index('='),c2.length).sub('=','')\n else m[2]=0.0\n end\n return m\n end", "def distance_to_point(x, y, z)\n a*x + b*y + c*z - d\n end", "def offset()\n (@centered ? @step/2.0 : 0.0) ;\n end", "def front_offset_y\n return data.front_offset_y\n end", "def Segment3dClosestPointXY(arg0, arg1, arg2, arg3)\n ret = _invoke(1610744258, [arg0, arg1, arg2, arg3], [VT_BYREF | VT_DISPATCH, VT_BYREF | VT_DISPATCH, VT_BYREF | VT_DISPATCH, VT_BYREF | VT_R8])\n @lastargs = WIN32OLE::ARGV\n ret\n end", "def find_point(arg_z)\n vx = vector[:x]\n vy = vector[:y]\n vz = vector[:z]\n\n ox = origin_node.x\n oy = origin_node.y\n oz = origin_node.z\n\n if (vx == 0 && vy == 0 )\n return { x: 0, y: 0, z: arg_z }\n end\n\n if (vx == 0)\n # to do\n end\n\n y = ((((arg_z - oz) / vz) * vy)) + oy\n x = ((((arg_z - oz) / vz) * vx)) + ox\n\n return { x: x, y: y, z: arg_z }\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a response from the Solr endpoint for a faceted query
def get_fq_solr_response(fq) solr_url = @blacklight_context.connection_config[:url] conn = Faraday.new(url: solr_url) do |faraday| faraday.request :url_encoded # form-encode POST params faraday.adapter Faraday.default_adapter # make requests with Net::HTTP end facet_request = \ "#{core_url}select?fq=#{fq}&fl=id,title_display,author_display,\ isbn_display,issn_display,lccn_display,oclc_s,holdings_1display,electronic_portfolio_s\ &rows=#{@rows}&wt=json" conn.get facet_request end
[ "def get_facet_field_response(facet_field, user_params = params || {}, extra_controller_params = {})\n solr_params = solr_facet_params(facet_field, user_params, extra_controller_params)\n # Make the solr call\n find(solr_params)\n end", "def get_facet_field_response(facet_field, user_params = params || {}, extra_controller_params = {})\n solr_params = solr_facet_params(facet_field, user_params, extra_controller_params)\n query_solr(user_params, extra_controller_params.merge(solr_facet_params(facet_field, user_params, extra_controller_params)))\n end", "def facet_field_response(facet_field, req_params = nil, eds_params = nil)\n query =\n search_builder\n .with(user_params)\n .facet(facet_field)\n .merge(req_params || {})\n eds_params = service_params.merge(eds_params || {})\n repository.search(query, eds_params)\n end", "def solrize_search_response(req_params, response)\n response.deep_symbolize_keys!\n\n facet_fields = (response[:facets] || []).inject({}) do |facet_fields, facet|\n facet_fields[facet[:name]] = facet[:fields].collect { |field| [ field[:label], field[:count] ] }.flatten\n facet_fields\n end\n \n h = {\n 'response' => {\n 'numFound' => response[:totalResults],\n 'start' => (response[:params][:start] || 0) - 1,\n 'docs' => response[:items],\n },\n 'facet_counts' => {\n 'facet_fields' => facet_fields\n }\n }\n\n blacklight_config.solr_response_model.new(h, req_params, solr_document_model: blacklight_config.solr_document_model)\n end", "def facet_field_response(facet_field, extra_controller_params = {})\n query = search_builder.with(search_state).facet(facet_field)\n repository.search(query.merge(extra_controller_params))\n end", "def get_facet_field_response(facet_field, req_params = nil, eds_params = nil)\n search_service.get_facet_field_response(\n facet_field,\n (req_params || params),\n eds_params\n )\n end", "def get_facet_field_response(facet_field, req_params = nil, eds_params = nil)\n query =\n search_builder\n .with(@user_params)\n .facet(facet_field)\n .merge(req_params || {})\n @repository.search(query, @eds_params.merge(eds_params || {}))\n end", "def index\n @response = get_advanced_search_facets unless request.post?\n end", "def facet\n @facet = blacklight_config.facet_fields[params[:id]]\n raise ActionController::RoutingError, 'Not Found' unless @facet\n\n @response = search_service.facet_field_response(@facet.key)\n @display_facet = @response.aggregations[@facet.field]\n\n @presenter = @facet.presenter.new(@facet, @display_facet, view_context)\n @pagination = @presenter.paginator\n respond_to do |format|\n format.html do\n # Draw the partial for the \"more\" facet modal window:\n return render layout: false if request.xhr?\n # Otherwise draw the facet selector for users who have javascript disabled.\n end\n format.json\n end\n end", "def get_facet_field_response(facet_field, user_params = params || {}, extra_controller_params = {})\n xfacet = get_xfacet_for_search_field\n if xfacet\n params_without_q = user_params.dup\n params_without_q.delete(:q)\n\n query_params = xfacet_query_params(xfacet, user_params)\n\n query = search_builder.with(params_without_q).merge(query_params).facet(facet_field)\n repository.search(query.merge(extra_controller_params))\n else\n super(facet_field, user_params, extra_controller_params)\n end\n end", "def facets\n @solr_data[:facets]\n end", "def get_search_results(user_query, facets=nil, num_per_page=nil, page=1)\n \n num_per_page ||= DisplayFields.index_view[:num_per_page] rescue 10\n \n mapper = RSolr::Ext::Request::Standard.new\n \n solr_params = mapper.map({\n :q=>user_query,\n :phrase_filters => facets,\n :qt=>:search,\n :per_page=>num_per_page,\n :page=>page\n })\n raw_response = Blacklight.solr.select(solr_params)\n \n RSolr::Ext::Response::Standard.new(raw_response)\n end", "def solr_get(query, args = {})\n response = ActiveFedora::SolrService.get(query, args)\n logger.debug(\"Solr params: #{response['responseHeader']['params']}\")\n response\n end", "def results\n filter = params[:filter] || {}\n \n if stale?(base.facet_cache_key)\n\n @results = base.refine(filter).to_a\n\n respond_to do |format|\n format.html { render @results, :layout => false }\n format.json { render :json => @results }\n end\n end\n end", "def people_facet_query(the_login, search_term, facet_options_provided)\n options = {\n :page => 1,\n :rows => 10,\n :facet => true,\n :facet_zeroes => false,\n :fq => [],\n :facet_fields => [:role_type_id_for_solr_t, \n :fully_represented_for_solr_s,\n :inside_nz_for_solr_s,\n :outside_nz_for_solr_s,\n :countries_facet_for_solr_s,\n :nz_regions_facet_for_solr_t,\n :role_type_group_for_solr_s,\n :year_of_creation_range_for_solr_s,\n :last_name_range_for_solr_s,\n :role_type_id_for_solr_t,\n\t\t\t\t\t\t :awards_received_for_solr_t\n ],\n :facet_queries => []\n }\n \n #default facet options are expressed here - this ensures the key exists. In effect nil means ALL\n default_options = {\n :born_key => nil,\n :last_name_key => nil,\n :person_organisation_key => nil,\n :fully_represented_key => nil,\n :inside_nz_key => nil,\n :outside_nz_key => nil,\n :country_facet_key => nil,\n :region_facet_key => nil,\n :role_group_key => nil,\n :role_type_key => nil, # an individual role, e.g. funder,\n :status => nil,\n\t :distinction_type_key => nil\n }\n \n \n \n #techinque from http://wiki.rubyonrails.com/rails/pages/RailsBestPractices\n facet_options = options.merge facet_options_provided\n \n #log\n #RAILS_DEFAULT_LOGGER.debug facet_options.to_yaml\n \n \n fields = [\n {:name => 'known_as_for_solr_t', :boost => 4},\n {:name => 'description_for_solr_t', :boost => 2.5},\n {:name => 'profile_for_solr_t', :boost => 0.6},\n {:name => 'pull_quote_for_solr_t'}\n ]\n \n query=''\n # lucene_query = FinderHelper.build_query(RoleContactinfo, query, fields)\n #Note OR is needed here as we are searching for the same text in several fields\n #OLD BROKEN lucene_query = FinderHelper.build_advanced_query(Contributor, fields,search_term,query_param_boolean='OR')\n \n if search_term == \"\"\n lucene_query = \"type_t:Contributor\"\n else\n lucene_query = FinderHelper.build_query(Contributor, search_term, fields)\n end\n \n lucene_query = FinderHelper.make_query_more_exact(lucene_query)\n \n #As per WR50270, filter to only include those contributors with known_as\n #You can check those affected by doing this in a Ruby console\n #Contributor.find_all_by_known_as(nil).map{|c|c.description}\n lucene_query << \" has_known_as_for_solr_t:1\"\n \n #Do we have a virginal query? Check for no search text, no restrictions in fq, no facet keys chosen\n st_blank = search_term.blank?\n fq_len_is_zero = (options[:fq].length == 0)\n option_keys_blank = check_if_star_key_all_blank(facet_options) \n virgin_query = ((st_blank) && (fq_len_is_zero) && option_keys_blank) #and option_keys_blank\n \n\n # gq = generate_contributor_born_facet_query(facet_options[:born_key])\n last_name_opts = generate_contributor_last_name_facet_query(facet_options[:last_name_key])\n creation_year_opts = generate_contributor_born_facet_query(facet_options[:born_key])\n person_org_opts = generate_contributor_person_org_query(facet_options[:person_organisation_key])\n fully_rep_opts = generate_facet_query(FULL_REPRESENTED_DETAILS,facet_options[:fully_represented_key])\n inside_nz_opts = generate_facet_query(INSIDE_NZ_DETAILS,facet_options[:inside_nz_key])\n outside_nz_opts = generate_facet_query(OUTSIDE_NZ_DETAILS,facet_options[:outside_nz_key])\n country_opts = generate_facet_query(COUNTRY_DETAILS,facet_options[:country_facet_key])\n nz_region_opts = generate_facet_query(REGION_DETAILS,facet_options[:region_facet_key])\n role_group_opts = generate_facet_query(ROLE_TYPE_GROUP_DETAILS, facet_options[:role_group_key])\n role_opts = generate_facet_query(ALL_ROLE_TYPES_FACET, facet_options[:role_type_key])\n status_opts = generate_facet_query(FULL_REPRESENTED_DETAILS, facet_options[:status])\n distinction_type_opts = generate_facet_query(ALL_DISTINCTION_TYPES_FACET, facet_options[:distinction_type_key])\n \n gq =concatentate_facet_hashes([last_name_opts,\n creation_year_opts,\n person_org_opts,\n fully_rep_opts,\n inside_nz_opts,\n outside_nz_opts,\n country_opts,\n nz_region_opts,\n role_group_opts,\n role_opts,\n status_opts,\n\t\t\t\t\t\t\t\t\tdistinction_type_opts\n ])\n #RAILS_DEFAULT_LOGGER.debug \"****MREGED:#{gq.class}, #{gq.to_yaml}\"\n \n facet_query = gq[:facet_queries]\n #RAILS_DEFAULT_LOGGER.debug \"FACET QUERY VALUES ARE #{facet_query}\"\n #RAILS_DEFAULT_LOGGER.debug \"FACET QUERY VALUES CLASS ARE #{facet_query.class}\"\n #RAILS_DEFAULT_LOGGER.debug \"FACET QUERY VALUES LENGTH ARE #{facet_query.length}\"\n facet_options[:facet_queries] = facet_query\n facet_options[:fq] = gq[:fq]\n \n facet_options[:sort]= 'facet_sort_field_for_solr_s asc' if search_term.blank?\n \n #RAILS_DEFAULT_LOGGER.debug \"facet queries of class #{ options[:facet_queries].length}, #{ options[:facet_queries][0].class}\"\n\n \n #RAILS_DEFAULT_LOGGER.debug \"LUC QUERY:\"+lucene_query\n # @results, @paginator = solr_query(lucene_query, facet_queries)\n \n #RAILS_DEFAULT_LOGGER.debug \"GQ:#{gq.to_yaml}\"\n # #RAILS_DEFAULT_LOGGER.debug \"FACET QUERIES:#{facet_queries.to_yaml}\"\n #RAILS_DEFAULT_LOGGER.debug \"FACET OPTIONS:#{facet_options.to_yaml}\"\n #\n\n lucene_query = append_status_filter_if_required(the_login, lucene_query)\n logger.debug \"LUCENE QUERY:#{lucene_query}\"\n \n \n @results, @paginator = solr_query(lucene_query, facet_options)\n #RAILS_DEFAULT_LOGGER.debug \"FACET OPTIONS SELECTED:\" + facet_options[:fq].to_yaml\n #RAILS_DEFAULT_LOGGER.debug \"FACET OPTIONS PROVIDED:\" + facet_options_provided.to_yaml\n \n @lq = lucene_query\n \n if virgin_query\n @results[:docs] = []\n \n end\n [@results, @paginator]\n end", "def facets_parser(solr_facets)\n facets = []\n if solr_facets && solr_facets['facet_queries']\n solr_facets['facet_queries'].each do | facet_query, facet_query_count |\n field = facet_query.split(':')[0]\n results = facets.find{|result | result.field == field }\n unless results\n results = SolrHelper::FacetResults.new\n results.field = field\n results.label = label_for_facet(field)\n facets << results\n end\n query = SolrHelper::FacetQuery.new\n query.field = field\n query.value = facet_query.split(':')[1]\n query.query = facet_query\n query.count = facet_query_count\n query.label = label_for_facet(facet_query)\n results << query\n end\n end\n\n if solr_facets && solr_facets['facet_fields']\n solr_facets['facet_fields'].each do | facet_field_name, facet_field_contents |\n facet_results = SolrHelper::FacetResults.new\n facet_results.field = facet_field_name\n facet_results.label = label_for_facet(facet_field_name)\n if facet_field_contents.is_a?(Array)\n facet_field_contents.each_index do | index |\n if index%2 == 0\n result = SolrHelper::FacetResult.new\n result.count = facet_field_contents[index+1]\n result.label = label_for_facet(facet_field_name)\n result.field = facet_field_name\n result.value = facet_field_contents[index]\n result.display_value = facet_field_contents[index]\n facet_results << result\n end\n end\n elsif facet_field_contents.is_a?(Hash)\n facet_field_contents.each do | facet_field_value, facet_field_count |\n result = SolrHelper::FacetResult.new\n result.count = facet_field_count\n result.label = label_for_facet(facet_field_name)\n result.field = facet_field_name\n result.value = facet_field_value\n result.display_value = facet_field_value\n facet_results << result\n end\n end\n facets << facet_results\n end\n end\n return facets\n end", "def facets\n facet_name = request.params[\"f_name\"]\n if facet_name == nil\n render :json => nil\n return\n end\n @presenter = execute_search(-1)\n facet_data = @presenter.facets.find {|f| f.name == facet_name }\n render :json => facet_data.values\n rescue => ex\n backtrace = ex.backtrace.join(\"\\r\\n\")\n Rails.logger.error(\"Could not render facets as JSON. Exception: #{ex} \\r\\n #{backtrace}\")\n render :json => nil, status: 500\n end", "def get_multiselect_facet_field_response(facet_field, user_params = params || {}, extra_controller_params = {})\n solr_params = solr_facet_params(facet_field, user_params, extra_controller_params)\n # Delete facet query for selected facet items\n solr_params[:fq].delete_if { |item| item =~ /^#{facet_field}:/ } if solr_params.has_key? :fq\n # Make the solr call\n find(solr_params)\n end", "def index\n xfacet = get_xfacet_for_search_field\n if xfacet\n @facet = xfacet\n\n template = case xfacet.xfacet_view_type\n when 'rbrowse'\n 'catalog/rbrowse'\n when 'xbrowse'\n 'catalog/xbrowse'\n end\n\n (@response, @document_list) = search_results(params)\n\n @display_facet = @response.aggregations[xfacet.key]\n @display_facet_window =\n BlacklightSolrplugins::FacetFieldWindow.new(@display_facet, per_page, calc_offset_and_expected_pos(params[:dir])[1])\n\n respond_to do |format|\n format.html { render :template => template }\n format.rss { render :layout => false }\n format.atom { render :layout => false }\n format.json do\n @presenter = Blacklight::JsonPresenter.new(@response,\n @document_list,\n facets_from_request,\n blacklight_config)\n end\n additional_response_formats(format)\n document_export_formats(format)\n end\n\n else\n super\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the URL for the current Blacklight Solr core
def core_url @blacklight_context.default_index.connection.uri.to_s.gsub(%r{^.*\/solr}, '/solr') end
[ "def blacklight_url\n blacklight_connection.base_uri\n rescue StandardError\n ENV[\"SOLR_URL\"] || \"http://127.0.0.1:8983/solr/blacklight-core\"\n end", "def url\n \"http://#{host}:#{port}/solr/\"\n end", "def url\n \"http://127.0.0.1:#{port}/solr/\"\n end", "def solr_url\n @solr_url ||= endpoint_url.gsub(/\\/select$/, '')\n end", "def render_solr_core\n unless request.host == 'search.library.cornell.edu' or request.host == 'catalog.library.cornell.edu'\n core = Blacklight.connection_config[:url]\n # Remove http protocol string\n start = core.rindex(/:\\/\\//) + 3\n display = '<p class=\"solr-core\">Solr core: ' + core[start..-1] + '</p>'\n display.html_safe\n end\n end", "def solr_base_url\n DatastaxRails::Base.establish_connection unless connection\n port = DatastaxRails::Base.config[:solr][:port]\n path = DatastaxRails::Base.config[:solr][:path]\n protocol = ssl_type ? 'https' : 'http'\n \"#{protocol}://#{current_server}:#{port}#{path}\"\n end", "def solr\n @solr ||= RSolr.connect(url: solr_url)\n end", "def solr_server\n self.class.solr_server\n end", "def GetBaseSearchURL\n @base_url\n end", "def path\n unless defined?(@path)\n @path = solr_url.path if solr_url\n @path ||= user_configuration_from_key('solr', 'path')\n @path ||= default_path\n end\n @path\n end", "def solr_home\n File.join(configuration.solr_home)\n end", "def getSolrDescription\n uri = URI.parse(\"http://#{@host}:#{@port}/solr/admin/cores\")\n out = Net::HTTP.get_response(uri)\n if out.code.to_i == 200 \n return out.body\n else \n STDERR.puts \"Error reaching Solr: \" + \n \"#{out.header.code} -- #{out.header.message}\"\n return nil\n end \n end", "def connect\n \n if index_full_text == true\n \n url = Blacklight.solr_config['fulltext']['url']\n else\n url = Blacklight.solr_config['default']['url']\n end\n @connection = Solr::Connection.new(url, :autocommit => :on )\n end", "def url\n site.url\n end", "def initialize url = nil\n @solr = url.nil? ? RSolr.connect(:url => RH_CONFIG[\"solr_discovery\"]) : RSolr.connect(:url => url)\n end", "def url\n @conf.url\n end", "def path\n unless defined?(@path)\n @path = solr_url.path if solr_url\n @path ||= configuration_from_key('solr', @path_key)\n @path ||= default_path\n end\n @path\n end", "def solr_url=(v)\n @solr_url = v\n writer_settings[\"solr.url\"] = v if writer_settings\n end", "def solr_home\n @solr_home ||= configuration_from_key('solr', 'solr_home')\n @solr_home ||= File.join(::Rails.root, 'solr')\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /nostros/1 GET /nostros/1.xml
def show @nostro = Nostro.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @nostro } end end
[ "def show\n @nossos_servico = NossosServico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def xml(id)\n http.get(\"/nfse/#{id}/xml\") do |response|\n response.headers.fetch(\"Location\") { \"\" }\n end\n end", "def index\n @nonces = Nonce.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @nonces }\n end\n end", "def index\n @notas = @solicitud.notas.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @notas }\n end\n end", "def index\n @cuentas = Cuenta.all\n\n @cadena = getcuentasxml\n \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @cadena }\n end\n end", "def show\n @carro_som = CarroSom.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @carro_som }\n end\n end", "def index\n @nanos = Nano.find(:all)\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @nanos.to_xml }\n end\n end", "def show\n\n @puntuacione = Puntuacione.find(params[:id])\n respond_to do |format| \n format.xml { render xml: @puntuacione }\n end\n end", "def index\n @objetivo_negocios = ObjetivoNegocio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @objetivo_negocios }\n end\n end", "def show\n @roteiro = Roteiro.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @roteiro }\n end\n end", "def show\n @objetivo_negocio = ObjetivoNegocio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @objetivo_negocio }\n end\n end", "def index\n @novidades = Novidade.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @novidades }\n end\n end", "def new\n @nossos_servico = NossosServico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def show\n @tipo_osexterna = TipoOsexterna.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tipo_osexterna }\n end\n end", "def index\n retrieve_vtodos\n\n respond_to do |format|\n format.html # index.html.erb\n format.rdf { render :xml => ICAL::Vtodo.to_xml }\n end\n end", "def index\n @tipo_notas = TipoNota.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @tipo_notas }\n end\n end", "def index\n @tipo_lancamentos = TipoLancamento.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @tipo_lancamentos }\n end\n end", "def show\n @notacredito = Notacredito.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @notacredito }\n end\n end", "def index\n @clienteles = @paramun.clienteles\n\n respond_to do |format|\n if @clienteles.empty?\n format.xml { render request.format.to_sym => \"ccliErreurA\" } ## Aucune Clientele\n else \n format.xml { render xml: @clienteles }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /nostros/new GET /nostros/new.xml
def new @nostro = Nostro.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @nostro } end end
[ "def new\n @nossos_servico = NossosServico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def new\n @node = Node.scopied.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @node }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nomina }\n end\n end", "def create\n @nostro = Nostro.new(params[:nostro])\n\n respond_to do |format|\n if @nostro.save\n flash[:notice] = 'Nostro was successfully created.'\n format.html { redirect_to(@nostro) }\n format.xml { render :xml => @nostro, :status => :created, :location => @nostro }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @nostro.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @registro = Registro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @registro }\n end\n end", "def new\n @revista = Revista.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @revista }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end", "def new\n @servico = Servico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @servico }\n end\n end", "def new\n @recurso = Recurso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @recurso }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @instituto }\n end\n end", "def new\n @node = Node.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @node }\n end\n end", "def new\n @domino = Domino.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @domino }\n end\n end", "def new\n @roteiro = Roteiro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @roteiro }\n end\n end", "def new\n @nome = Nome.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nome }\n end\n end", "def new\n @nsar = Nsar.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nsar }\n end\n end", "def new\n @societe = Societe.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @societe }\n end\n end", "def new\n @tiposproceso = Tiposproceso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tiposproceso }\n end\n end", "def new\n @proceso = Proceso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @proceso }\n end\n end", "def new\n @solicitud = Solicitud.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @solicitud }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /nostros POST /nostros.xml
def create @nostro = Nostro.new(params[:nostro]) respond_to do |format| if @nostro.save flash[:notice] = 'Nostro was successfully created.' format.html { redirect_to(@nostro) } format.xml { render :xml => @nostro, :status => :created, :location => @nostro } else format.html { render :action => "new" } format.xml { render :xml => @nostro.errors, :status => :unprocessable_entity } end end end
[ "def create\n @nossos_servico = NossosServico.new(params[:nossos_servico])\n\n respond_to do |format|\n if @nossos_servico.save\n format.html { redirect_to(@nossos_servico, :notice => 'Nossos servico was successfully created.') }\n format.xml { render :xml => @nossos_servico, :status => :created, :location => @nossos_servico }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @nossos_servico.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @nsar = Nsar.new(params[:nsar])\n\n respond_to do |format|\n if @nsar.save\n format.html { redirect_to(nsars_path) }\n format.xml { render :xml => @nsar, :status => :created, :location => @nsar }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @nsar.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @noot = Noot.new(noot_params)\n\n respond_to do |format|\n if @noot.save\n format.html { redirect_to @noot, notice: 'Noot was successfully created.' }\n format.json { render :show, status: :created, location: @noot }\n else\n format.html { render :new }\n format.json { render json: @noot.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\r\n @noot = Noot.new(noot_params)\r\n\r\n respond_to do |format|\r\n if @noot.save\r\n format.html { redirect_to @noot, notice: 'Noot was successfully created.' }\r\n format.json { render :show, status: :created, location: @noot }\r\n else\r\n format.html { render :new }\r\n format.json { render json: @noot.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end", "def create\n @neuro = Neuro.new(neuro_params)\n\n respond_to do |format|\n if @neuro.save\n format.html { redirect_to @neuro, notice: 'Neuro was successfully created.' }\n format.json { render :show, status: :created, location: @neuro }\n else\n format.html { render :new }\n format.json { render json: @neuro.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @nitrou = Nitrou.new(nitrou_params)\n\n respond_to do |format|\n if @nitrou.save\n format.html { redirect_to @nitrou, notice: 'Nitrou was successfully created.' }\n format.json { render :show, status: :created, location: @nitrou }\n else\n format.html { render :new }\n format.json { render json: @nitrou.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @nostro = Nostro.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nostro }\n end\n end", "def novo\n @disciplina = Disciplina.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @disciplina }\n end\n end", "def create\n doc = Nokogiri::XML(request.body.read)\n cvNode = doc.xpath('elwak/checklisten_vorlage')\n cv = ChecklistenVorlage.new({\n objekt_id: cvNode.xpath('objekt_id').text.to_s, \n bezeichner: cvNode.xpath('bezeichner').text.to_s, \n version: cvNode.xpath('version').text.to_s.to_i, \n inaktiv: cvNode.xpath('inaktiv').text.to_s.to_bool \n })\n cv.save\n\n cvNode.xpath('checklisten_eintrags/checklisten_eintrag').each do |ceNode|\n ce = ChecklistenEintrag.new({\n checklisten_vorlage_id: cv.id,\n bezeichner: ceNode.xpath('bezeichner').text.to_s,\n was: ceNode.xpath('was').text.to_s,\n wann: ceNode.xpath('wann').text.to_s,\n typ: ceNode.xpath('typ').text.to_s.to_i,\n position: ceNode.xpath('position').text.to_s.to_i\n })\n ce.save\n end\n\n respond_to do |format|\n format.xml {render :xml => '<?xml version=\"1.0\" encoding=\"UTF-8\"?><success />'}\n end\n end", "def create\n @niveis_ensino = NiveisEnsino.new(params[:niveis_ensino])\n\n respond_to do |format|\n if @niveis_ensino.save\n format.html { redirect_to(@niveis_ensino, :notice => 'Niveis ensino cadastrado com sucesso.') }\n format.xml { render :xml => @niveis_ensino, :status => :created, :location => @niveis_ensino }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @niveis_ensino.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @ngo = Ngo.new(params[:ngo])\n\n respond_to do |format|\n if @ngo.save\n flash[:notice] = 'Ngo was successfully created.'\n format.html { redirect_to(@ngo) }\n format.xml { render :xml => @ngo, :status => :created, :location => @ngo }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @ngo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @nave_nodriza = NaveNodriza.new(nave_nodriza_params)\n\n respond_to do |format|\n if @nave_nodriza.save\n format.html { redirect_to nave_nodrizas_path, notice: 'Nave nodriza was successfully created.' }\n format.json { render action: 'show', status: :created, location: @nave_nodriza }\n else\n format.html { render action: 'new' }\n format.json { render json: @nave_nodriza.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n params[:nota][:usuario_id] = usuario_actual.id\n @nota = @solicitud.notas.new(params[:nota])\n\n respond_to do |format|\n if @nota.save\n format.html { redirect_to( solicitud_notas_path(@solicitud), :notice => 'Seguimiento agregado con exito.') }\n format.xml { render :xml => @nota, :status => :created, :location => @nota }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @nota.errors, :status => :unprocessable_entity }\n end\n end\n end", "def new\n @nossos_servico = NossosServico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def create\n @nippou = Nippou.new(nippou_params)\n\n respond_to do |format|\n if @nippou.save\n format.html { redirect_to @nippou, notice: 'Nippou was successfully created.' }\n format.json { render action: 'show', status: :created, location: @nippou }\n else\n format.html { render action: 'new' }\n format.json { render json: @nippou.errors, status: :unprocessable_entity }\n end\n end\n end", "def post_nodes_with_root\n serialize_service.post_nodes_serialized\n end", "def create\n @noddle = Noddle.new(noddle_params)\n\n respond_to do |format|\n if @noddle.save\n format.html { redirect_to @noddle, notice: 'Noddle was successfully created.' }\n format.json { render :show, status: :created, location: @noddle }\n else\n format.html { render :new }\n format.json { render json: @noddle.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @nodo = Nodo.new(nodo_params)\n\n respond_to do |format|\n if @nodo.save\n #format.html { redirect_to @nodo, notice: 'Nodo was successfully created.' }\n #format.json { render action: 'show', status: :created, location: @nodo }\n format.html { redirect_to nodos_url }\n format.json { head :no_content }\n else\n format.html { render action: 'new' }\n format.json { render json: @nodo.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @noc = Noc.new(params[:noc])\n\n respond_to do |format|\n if @noc.save\n format.html { redirect_to @noc, :notice => 'Noc was successfully created.' }\n format.json { render :json => @noc, :status => :created, :location => @noc }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @noc.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /nostros/1 DELETE /nostros/1.xml
def destroy @nostro = Nostro.find(params[:id]) @nostro.destroy respond_to do |format| format.html { redirect_to(nostros_url) } format.xml { head :ok } end end
[ "def destroy\n @domino = Domino.find(params[:id])\n @domino.destroy\n\n respond_to do |format|\n format.html { redirect_to(dominos_url) }\n format.xml { head :ok }\n end\n end", "def del\n @status1 = Status1.find(params[:id])\n @status1.destroy\n\n respond_to do |format|\n format.html { redirect_to(status1s_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @scrap_xml = ScrapXml.find(params[:id])\n @scrap_xml.destroy\n\n respond_to do |format|\n format.html { redirect_to(scrap_xmls_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @l1_node = L1Node.find(params[:id])\n @l1_node.destroy\n\n respond_to do |format|\n format.html { redirect_to(l1_nodes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @dependencia = Dependencia.find(params[:id])\n @dependencia.destroy\n\n respond_to do |format|\n format.html { redirect_to(dependencias_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @relatestagiario = Relatestagiario.find(params[:id])\n @relatestagiario.destroy\n\n respond_to do |format|\n format.html { redirect_to(relatestagiarios_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @roteiro = Roteiro.find(params[:id])\n @roteiro.destroy\n\n respond_to do |format|\n format.html { redirect_to(roteiros_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @suministro = Suministro.find(params[:id])\n @suministro.destroy\n\n respond_to do |format|\n format.html { redirect_to(suministros_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @obrasproyecto = Obrasproyecto.find(params[:id])\n @obrasproyecto.destroy\n\n respond_to do |format|\n format.html { redirect_to(obrasproyectos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @nomina.destroy\n\n respond_to do |format|\n format.html { redirect_to(nominas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @nossos_servico = NossosServico.find(params[:id])\n @nossos_servico.destroy\n\n respond_to do |format|\n format.html { redirect_to(nossos_servicos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @nom = Nom.find(params[:id])\n @nom.destroy\n\n respond_to do |format|\n format.html { redirect_to(noms_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @carro_som = CarroSom.find(params[:id])\n @carro_som.destroy\n\n respond_to do |format|\n format.html { redirect_to(carro_soms_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @registro = Registro.find(params[:id])\n @registro.destroy\n\n respond_to do |format|\n format.html { redirect_to(home_path) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tconexion = Tconexion.find(params[:id])\n @tconexion.destroy\n\n respond_to do |format|\n format.html { redirect_to(tconexions_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @documento = @externo.documentos.find(params[:id])\n @documento.destroy\n\n respond_to do |format|\n format.html { redirect_to(documentos_url(@externo)) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tipo_documento = TipoDocumento.find(params[:id])\n @tipo_documento.destroy\n\n respond_to do |format|\n format.html { redirect_to(tipo_documentos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @dossier = Dossier.find(params[:id])\n @dossier.destroy\n\n respond_to do |format|\n format.html { redirect_to(\"/\") }\n format.xml { head :ok }\n end\n end", "def destroy\n @distribuidora = Distribuidora.find(params[:id])\n @distribuidora.destroy\n\n respond_to do |format|\n format.html { redirect_to(distribuidoras_url) }\n format.xml { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If children need to do anything special on apply, now's their chance.
def apply_children end
[ "def apply_to_children(&block)\n self.entities.each do |entity|\n block.call(entity)\n entity.apply_to_children(&block)\n end\n end", "def ignore_children!\n @ignoring_children += 1\n end", "def measure_children()\n children.each do |child|\n child.measure()\n end\n end", "def child_check\n if @children.nil? or @children.empty?\n get_children unless @already_fetched_children\n @already_fetched_children = true\n end\n end", "def children_approved?\n needed = self.min_children_needed || self.child_approvals.count\n self.child_approvals.approved.count >= needed\n end", "def allowed_children; end", "def calculated_amount\n #use the real score if we have one, otherwise assume zero\n #could make this more sophistocated later (e.g. use #N/A)\n\n #if we don't have child goals, use the current manual score\n #if there isn't a manually entered score, use zero\n #if we DO have children, average up the child scores\n #this should recursively follow all children to the bottom...\n #could be VERY slow with lots of kids... might want to make this an offline process and save the score inside the Goal model... TODO\n if(children.empty?)\n #return the score if there is one.\n score_amount = score ? score.amount : 0\n else\n score_amount = children.map{|c| c.calculated_amount}.inject(:+).to_f / children.count\n end\n #save!\n #score_amount #dumb, but I need to return this value. Not the \"true\" from the save above\n end", "def update_children_moderation_flag\n if self.changed.include?('moderation_flag') and self.content.has_children?\n self.content.children.each do |child|\n similiar_submissions = Submission.where(:content_id => child.id, :feed_id => self.feed_id, :moderation_flag => self.moderation_flag_was)\n similiar_submissions.each do |child_submission|\n child_submission.update_attributes({:moderation_flag => self.moderation_flag, :moderator_id => self.moderator_id})\n end\n end\n end\n end", "def apply_effectto_all_allies\n \n # apply effect to all battle menbers actors\n if @user.battler.is_a?(Game_Actor)\n $game_player.followers.each {|i|\n next unless i.visible?\n next if i.battler.dead? and @item.scope == 8\n apply_self_effect(i, pop=true)}\n apply_self_effect($game_player, pop=true)\n \n # Apply effect to all enemies allies\n elsif @user.battler.is_a?(Game_Enemy)\n for event in $game_map.event_enemies\n if event.on_battle_screen?\n next if event.battler.object || event.page.nil?\n next if @item.scope == 8 and event.battler.dead?\n if event.battler.dead?\n @item.scope == 10 ? event.apply_respawn : next\n end\n event.battler.item_apply(event.battler, @item)\n $game_player.damage_pop.push(DamagePop_Obj.new(event))\n event.animation_id = animation\n end\n end\n apply_self_effect(@user, true)\n end\n end", "def processed_children node, &block\n # Recursively examine the node, returning an array of valid descendants or, if they are all valid, the node itself\n def do_children node, &block\n return [ node ] if node.text?\n all_good = true\n collected = node.children.collect do |child|\n subcollection = do_children child, &block\n all_good &&= (subcollection == [ child ])\n subcollection\n end\n # Keep the node whole if all its children are good and the block approves\n return [ node ] if all_good && block_given? && block.call(node)\n collected.flatten\n end\n # For each potential new child, look into expanding it and/or approving it by calling the block\n do_children node, &block\nend", "def update_child_moderation\n if self.changed.include?('moderation_flag') and self.content.has_children?\n self.content.children.each do |child|\n similiar_submissions = Submission.where(content_id: child.id, feed_id: self.feed_id, moderation_flag: self.moderation_flag_was)\n similiar_submissions.each do |child_submission|\n child_submission.update_attributes({moderation_flag: self.moderation_flag, moderator_id: self.moderator_id})\n end\n end\n end\n end", "def children_time=(_arg0); end", "def evaluate_children(mode)\n children.collect { |c| c.evaluate mode }\n end", "def trigger_children(state)\n children.each do |child|\n if child.send(\"on_#{state}?\")\n Rails.logger.info \"Queuing #{child.type} ##{child.id}\"\n child.failure! unless TaskJob.set(queue: child.queue_name).perform_later(child)\n end\n end\n end", "def override_probability_if_won_or_lost\n unless self.stage.blank?\n self.probability = 100 if self.stage.won?\n self.probability = 0 if self.stage.lost?\n end\n end", "def ensure_none_or_self_only_sync\n return if @child_types.nil? || @affects.nil?\n return if @child_types == :none && @affects == :self_only\n return unless @child_types == :none || @affects == :self_only\n\n if @child_types == :none && (@affects != :all && @affects != :self_only)\n Puppet.warning(\"If child_types => 'none', affects => value will be ignored. Please remove affects or set affects => 'self_only' to remove this warning. Reference: #{inspect}\")\n end\n @affects = :self_only if @child_types == :none\n\n if @affects == :self_only && (@child_types != :all && @child_types != :none)\n Puppet.warning(\"If affects => 'self_only', child_types => value will be ignored. Please remove child_types or set child_types => 'none' to remove this warning. Reference: #{inspect}\")\n end\n @child_types = :none if @affects == :self_only\n end", "def children_completed?\n needed = min_children_needed || child_steps.count\n child_steps.completed.count >= needed\n end", "def children_duration=(_arg0); end", "def percent_chance( &block )\n result = !!( rand( 100 ) < self )\n block_given? ? ( result ? yield : nil ) : result\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If our object has a blueprint and a max_field equivalent of a field, offer a 'max' button. field is a sym of the field in question, input is the input field to populate.
def check_max_button(field,input) if @object.respond_to?(:blueprint) max = ("max_" + field.to_s ).to_sym if @object.blueprint.respond_to?(max) num_max = @object.send(max) maxButton = Button.new("Max") do input.text = num_max.to_s end maxButton.rect.x = input.rect.right + @spacing maxButton.rect.y = input.rect.y self << maxButton end end end
[ "def max\n read_attribute(:max) or ( input and input.max )\n end", "def set_max(fields)\n view.update_many(\"$max\" => collect_operations(fields))\n end", "def set_Max(value)\n set_input(\"Max\", value)\n end", "def max(action)\n limits(action)[:max]\n end", "def max(field = nil)\n block_given? ? super() : aggregates(field)[\"max\"]\n end", "def max(field)\n grouped(:max, field.to_s, Javascript.max, Javascript.max_finalize)\n end", "def max(field)\n grouped(:max, field.to_s, Javascript.max)\n end", "def max(field = nil)\n return super() if block_given?\n\n aggregate_by(field, :max)\n end", "def set_MaxID(value)\n set_input(\"MaxID\", value)\n end", "def max(field, opts={})\n opts = ::Hashie::Mash.new(opts)\n all(opts).inject(nil) do |max, item|\n val = item.send(field)\n max = val if !val.nil? && (max.nil? || val > max)\n max\n end\n end", "def set_MaxBid(value)\n set_input(\"MaxBid\", value)\n end", "def set_MaxID(value)\n set_input(\"MaxID\", value)\n end", "def max(field)\n Criteria.new(self).max(field)\n end", "def set_MaxId(value)\n set_input(\"MaxId\", value)\n end", "def set_MaxCount(value)\n set_input(\"MaxCount\", value)\n end", "def max_number_confirm_button\n\t\t$tracer.trace(format_method(__method__))\n\t\treturn ToolTag.new(@tag.find.button.className(create_ats_regex_string(\"ats-maxnumconfirmbtn\")), format_method(__method__))\n\tend", "def max=(value)\n @max = value\n end", "def set_max(max)\n self[:max] = (max > 0 ? max : 1)\n end", "def set_MaxCount(value)\n set_input(\"MaxCount\", value)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the maximum number of times to retry sending the request to the API. (Default is 5) Returns self to accommodate method chaining.
def retry_at_most(max_retries) @max_retries = max_retries self end
[ "def max_retry\n 5\n end", "def send_maximum_retry\n super\n end", "def set_send_maximum_retry(opts)\n opts = check_params(opts,[:retries])\n super(opts)\n end", "def max_retry_delay\n @max_retry_delay ||= DEFAULT_MAX_RETRY_DELAY\n end", "def retry_limit\n @retry_limit ||= backoff_strategy.length\n end", "def number_of_retries(num)\n raise ArgumentError, 'Must be positive Integer' unless num.is_a?(Integer) && num.positive?\n self.retries = num\n end", "def set_connect_maximum_retry(opts)\n opts = check_params(opts,[:retries])\n super(opts)\n end", "def max_retry_count\n\t\t2\n\tend", "def num_retries\n 1\n end", "def setRetryCount(count)\n @helper.setRetryCount(count)\n self\n end", "def retry_max_wait=(val)\n @retry_max_wait = val\n end", "def nretries\n options[:nretries]\n end", "def retry(count=nil)\n if count\n skip if @counter >= count\n end\n raise Pioneer::HttpRetryRequest\n end", "def poll_max_retries\n 3\n end", "def retry_max_wait\n @retry_max_wait ||= Vault::Defaults::RETRY_MAX_WAIT\n end", "def with_retry #block\n num_attempts = 0\n begin\n num_attempts += 1\n yield\n rescue Twitter::Error::TooManyRequests => error\n if num_attempts <= MAX_RETRIES\n # NOTE: Your process could go to sleep for up to 15 minutes but if you\n # retry any sooner, it will almost certainly fail with the same exception.\n puts \"RETRY in #{error.rate_limit.reset_in}\"\n sleep error.rate_limit.reset_in\n retry\n else\n raise\n end\n end\n end", "def max_retries_import\n @max_retries_import || 5\n end", "def connect_maximum_retry\n super\n end", "def queue_retry_limit(limit=nil)\n if limit\n @queue_retry_limit = limit\n else #accessor\n @queue_retry_limit\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the Serializer from the default. Returns self to accommodate method chaining.
def with_serializer(serializer) @serializer = serializer self end
[ "def freeze!\n serializers.freeze\n\n self\n end", "def set_root_serializer(name); root_serializer_options[:serializer_class] ||= name; end", "def set_serializer(self_class, serializer_class)\n self_class.instance_variable_set(SERIALIZER_CLASS, serializer_class)\n end", "def serializer\n @serializer ||=\n begin\n @serializer = serializer_opts.delete(:serializer)\n @serializer ||= ActiveModel::Serializer.serializer_for(resource, serializer_opts)\n\n if serializer_opts.key?(:each_serializer)\n serializer_opts[:serializer] = serializer_opts.delete(:each_serializer)\n end\n @serializer\n end\n end", "def serializer=(value)\n PaperTrail.config.serializer = value\n end", "def freeze\n @original_deserialized_values ||= {}\n @original_deserialized_values.freeze\n super\n end", "def default_serializer_options\n {\n include: ['*.*'], # By default, serialize 2 levels of nesting\n scope: {locale: @locale } # By default, pass locale to serializer scope\n }\n end", "def freeze\n deserialized_values.freeze\n super\n end", "def <<(serializer)\n case\n when serializers.frozen?\n raise SerializersFrozenError\n when serializers.length >= SERIALIZER_LIMIT\n raise SerializersLimitError\n else\n @serializers[serializer] = flags.max.succ\n @inverted = @serializers.invert\n end\n\n self\n end", "def serializers\n @serializers ||= Readthis::Serializers.new\n end", "def serializer(klass)\n @objects_serializer = klass\n end", "def serialization_options\n @serialization_options || self.class.serialization_options || self.class.superclass.serialization_options\n end", "def serialize_default(object); object; end", "def to_json(options = {}, *args)\n return options[:serializer].new(self, options, *args).serialized_json if options[:serializer]\n\n super\n end", "def use_active_resource_deserialization\n use_active_record_deserialization # Same for now\n end", "def initialize(column_serializer: shrine_class.opts[:column][:serializer], **options)\n super(**options)\n @column_serializer = column_serializer\n end", "def serializer_from_resource(resource, serializer_context_class, options)\n serializer_class =\n options.fetch(:serializer) { serializer_context_class.serializer_for(resource) }\n\n if serializer_class.nil? # rubocop:disable Style/GuardClause\n DefaultSerializer.new(resource, options)\n else\n serializer_class.new(resource, options.except(:serializer))\n end\n end", "def refresh\n @deserialized_values = {}\n super\n end", "def serializer(type = nil)\n type ||= serializer_type\n if type == serializer_type\n @serializer ||= self.class.serializers[type].new(self)\n else\n self.class.serializers[type].new(self)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This may be useful when using a local installation of the SmartyStreets APIs. base_url is a string that defaults to the URL for the API corresponding to the Client object being built. Returns self to accommodate method chaining.
def with_base_url(base_url) @url_prefix = base_url self end
[ "def initialize base_url\n @base_url = base_url\n end", "def initialize(base_uri= \"http://localhost:8080\")\n @base_uri = base_uri\n @version = \"v1\"\n end", "def initialize base_url, api_key\n\t\t\t\t\t@connection = Freshdesk::Api::Client::Request.new base_url, api_key\n\t\t\t\tend", "def initialize(api_key, version = 'v1', base_url = 'http://api.digitalnz.org')\n @api_key = api_key\n @base_url = base_url\n @version = version\n \n if @base_url =~ /^(.*)\\/$/\n @base_url = $1\n end\n end", "def initialize(baseServiceUrl)\n $LOG.info \"Initializing client with #{@baseServiceUrl}\"\n @baseServiceUrl = baseServiceUrl\n @use_format_param = false\n @default_format = FHIR::Formats::ResourceFormat::RESOURCE_XML\n @default_format_bundle = FHIR::Formats::FeedFormat::FEED_XML\n set_no_auth\n end", "def base_url\n BASE_URL.dup % [\"%s\", \"%s\", @api_key, \"%s\"] \n end", "def build(base_url, &block)\n operation_manager = AFHTTPRequestOperationManager.alloc.initWithBaseURL(base_url.to_url)\n if block\n dsl = AFMotion::ClientDSL.new(operation_manager)\n case block.arity\n when 0\n dsl.instance_eval(&block)\n when 1\n block.call(dsl)\n end\n end\n if !operation_manager.operationQueue\n operation_manager.operationQueue = NSOperationQueue.mainQueue\n end\n operation_manager\n end", "def api_base_url=(url)\n version = Apipie.configuration.default_version\n @api_base_url[version] = url\n end", "def get(base_url, options)\n Builds.new(\"#{base_url}/api/build\", options)\n end", "def base_url\n @base_url ||= File.join(JsonApiServer.configuration.base_url, request.path)\n end", "def base_url\n @base_url || self.class.base_url\n end", "def base_url\n \"#{site_url}/api/#{Wrike3.api_version}\"\n end", "def base_url\n @base_url || DEFAULT_BASE_URL\n end", "def initialize(url_or_port, api_key_or_file, api_version=nil)\n @client = Client.new(url_or_port, api_key_or_file, api_version)\n end", "def set_base_url(url)\n base_url = url\n end", "def base_url=(url)\n @base_url = url\n end", "def base_url\n \"https://api.beezup.com/\"\n end", "def initialize(version, base_url)\n @version = version\n @base_url = base_url \n @logger = Logger.new(STDERR)\n @endpoint_url = \"#{@base_url}/rpc/soap/jirasoapservice-v#{version}\"\n end", "def base_url\n self.mode == 'production' ? Ebay::Search::Api::PRODUCTION_URL : Ebay::Search::Api::SANDBOX_URL\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enables debug mode, which will print information about the HTTP request and response to $stdout. Returns self to accommodate method chaining.
def with_debug @debug = true self end
[ "def set_debug_flag\n if @http_log_debug\n @httparty_log_level = :debug\n @httparty_log_format = :curl\n end\n end", "def enable_debug\n self.class.enable_debug\n self\n end", "def debug enable\n @debug_mode = enable\n end", "def debug!\n self.log_level = Logger::DEBUG\n end", "def enable_debug_mode!\n self.level = Enceladus::Logger::DEBUG\n end", "def debug(options={})\n return unless @debug\n\n error = options[:error]\n req = options[:req]\n\n string_block = []\n string_block << title(options)\n string_block << request_dump(req) if request_parsed?(req)\n string_block << error.backtrace if error\n\n internal_write string_block.join(\"\\n\")\n end", "def http_debug(http_debug_bool)\n Facter::Options[:http_debug] = http_debug_bool\n end", "def http_debug?\n Options[:http_debug]\n end", "def logging_http_on\n logging_on(Logger::DEBUG)\n end", "def debug!(options = {})\n options = debug_options_defaults.merge options\n logger.level = options[:enabled] ? options[:level] : Log4r::OFF\n\n if options[:enabled]\n logger.add stderr unless logger.outputters.include? stderr\n logger.info \"enabling debug mode\"\n else\n logger.info \"disabling debug mode\"\n logger.remove \"stderr\"\n end\n\n self\n end", "def debug!\n self.severity = :DEBUG\n end", "def debug_api\n response.content_type = 'text/plain' if params[:debug]\n end", "def nice_debugging_for(json)\n if @options[:debug] && !(DONT_SHOW_DEBUG_FOR.include? @request.method)\n puts \"#{@request.method}: JSON Response:\"\n pp json\n puts \"\\n\"\n end\n end", "def debug_mode\n @configuration[:debug_mode] = true\n end", "def debug_on\n @debug_socket = true\n end", "def print_request(options)\n return unless enabled\n\n puts \"#{options[:method].to_s.upcase} #{options[:url]}\"\n\n print_request_headers options[:headers]\n print_request_body options[:body]\n end", "def debug\n d = @debug\n @debug = true\n yield\n @debug = d\n end", "def toggle_debug\n @debug = @debug == false ? true : false\n end", "def set_debug_output\n debug_output unless Rails.env.production?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Call given request and create matching response object
def call(request) begin response = RestClient.post(URI.escape(Config.api_url + request.operation), request.data) rescue RestClient::Unauthorized, Exception return nil end # Check response if response.code != 200 return nil end # Parse response parsed_response = JSON.parse(response.to_s) # Check format if parsed_response["api"].nil? || parsed_response["api"]["response"].nil? return nil end # Fill matching response object with parsed response response = request.response_factory(parsed_response["api"]["response"]) return response end
[ "def call(request, response_class)\n request.valid?\n uri = @endpoint.clone\n uri.query = query(request).to_s\n response = request(uri)\n puts \"Response:\\n#{response.body}\\n\\n\" if $DEBUG\n response_class.new(response.body)\n end", "def request\n Response.new(make_request)\n end", "def _process_request(request)\n _error!(Errors::NotFoundError) unless request.valid?\n _validate_version(request)\n retval = _call_method(request)\n _response(request.post? ? 201 : 200, _prepare_response(retval))\n end", "def lookup_response(request, entries); end", "def service(request, response)\n process(request, response)\n end", "def perform_request\n ## Perform request\n @request.send(method, action, params)\n\n ## Set response\n @response = @request.response\n end", "def make_request\n response = @http.request(@request)\n end", "def call()\n json = do_request()\n parse(json)\n end", "def request\n url1 = url\n return false unless valid?\n http_response = HTTParty.post(url, :format => :plain,\n :query => @params.merge({ :cmd => @cmd }),\n :headers => {\n 'ZooZ-Unique-ID' => @unique_id,\n 'ZooZ-App-Key' => @app_key,\n 'ZooZ-Response-Type' => @response_type,\n }) if @response_type.eql?('NVP')\n\n\n\n http_response = HTTParty.post(url, :format => :json,\n :body => @params.merge({ :cmd => @cmd }),\n :headers => {\n 'ZooZDeveloperId' => @developer_id,\n 'ZooZServerAPIKey' => CGI::escape(@app_key)\n }) if @response_type.eql?('JSON')\n\n response = Response.new\n response.request = self\n response.http_response = http_response\n unless response.success?\n @errors = response.errors\n return false\n end\n response\n end", "def response_for(request)\n expectation = find_by(request)\n return nil if expectation.nil?\n\n expectation.response(request)\n end", "def call(request); end", "def lookup_response(request, entries)\n if entries\n entries = entries.map { |entry| deserialize_entry(*entry) }\n _, response = entries.find { |req, res| response_matches?(request, req, res) }\n response\n end\n end", "def build_response(connection, request)\n app.call(build_env(connection, request))\n end", "def make_request(http, request)\n response = http.request(request)\n Response.new(response)\n end", "def get_api_response(request)\n api = Api::ApiResponse.new(request, DATABASE_NAME)\n response_from_api = api.respond(request)\n\n response_from_api\n end", "def call_handler(handler:, request:)\n t0 = Time.now\n\n begin\n id = request['id']\n\n self.validate_request request\n\n result = handler.call id: id,\n method: request['method'],\n params: request['params'],\n meta: {}\n rescue => err\n log_error(err) if Fluffle.logger.error?\n\n error = self.build_error_response err\n end\n\n response = {\n 'jsonrpc' => '2.0',\n 'id' => id,\n 'meta' => {\n 'handler_duration' => (Time.now - t0)\n }\n }\n\n if error\n response['error'] = error\n else\n response['result'] = result\n end\n\n response\n end", "def create_response(*args)\n Response.new(*args)\n end", "def process_request req, res\n req_headers = req.header\n req_query = req.query\n req_body = Oaf::HTTPServer.get_request_body req\n file = Oaf::Util.get_request_file(@options[:path], req.path,\n req.request_method, @options[:default_response])\n out = Oaf::Util.get_output(file, req.path, req_headers, req_body,\n req_query)\n res_headers, res_status, res_body = Oaf::HTTPServer.parse_response out\n Oaf::HTTPServer.set_response! res, res_headers, res_body, res_status\n end", "def manage_request(*arguments)\n require \"json\"\n begin\n content_type_included = false\n path = \"\"\n data = \"\"\n\n @response = Hash.new()\n headers_t = @headers.dup()\n cookies_to_set_str = \"\"\n if arguments.size == 3\n path = arguments[0]\n elsif arguments.size == 1 and arguments[0].kind_of?(Hash)\n path = arguments[0][:path]\n elsif arguments.size == 1 and arguments[0].kind_of?(String)\n path = arguments[0].to_s()\n end\n @cookies.each { |cookie_path, cookies_hash|\n cookie_path = \"\" if cookie_path == \"/\"\n path_to_check = path\n if path == \"/\" or path[-1] != \"/\"\n path_to_check += \"/\"\n end\n if path_to_check.scan(/^#{cookie_path}\\//).size > 0\n cookies_hash.each { |key, value|\n cookies_to_set_str += \"#{key}=#{value}; \"\n }\n end\n }\n headers_t[\"Cookie\"] = cookies_to_set_str\n\n method_s = caller[0].to_s().scan(/:in `(.*)'/).join\n\n if arguments.size == 3\n data = arguments[1]\n if arguments[2].kind_of?(Hash)\n headers_t.merge!(arguments[2])\n end\n elsif arguments.size == 1 and arguments[0].kind_of?(Hash)\n if arguments[0][:data].nil?\n if arguments[0].keys.include?(:data)\n data = \"\"\n elsif arguments[0].keys.include?(:data_examples) and\n arguments[0][:data_examples].kind_of?(Array)\n data = arguments[0][:data_examples][0] #the first example by default\n else\n data = \"\"\n end\n else\n data = arguments[0][:data]\n end\n if arguments[0].include?(:headers)\n headers_t.merge!(arguments[0][:headers])\n end\n\n if headers_t[\"Content-Type\"].to_s() == \"\" and headers_t[\"content-type\"].to_s() == \"\" and\n headers_t[:\"content-type\"].to_s() == \"\" and headers_t[:\"Content-Type\"].to_s() == \"\"\n content_type_included = false\n elsif headers_t[\"content-type\"].to_s() != \"\"\n content_type_included = true\n headers_t[\"Content-Type\"] = headers_t[\"content-type\"]\n elsif headers_t[:\"content-type\"].to_s() != \"\"\n content_type_included = true\n headers_t[\"Content-Type\"] = headers_t[:\"content-type\"]\n headers_t.delete(:\"content-type\")\n elsif headers_t[:\"Content-Type\"].to_s() != \"\"\n content_type_included = true\n headers_t[\"Content-Type\"] = headers_t[:\"Content-Type\"]\n headers_t.delete(:\"Content-Type\")\n elsif headers_t[\"Content-Type\"].to_s() != \"\"\n content_type_included = true\n end\n\n if !content_type_included and data.kind_of?(Hash)\n headers_t[\"Content-Type\"] = \"application/json\"\n content_type_included = true\n end\n # to be backwards compatible since before was :values\n if arguments[0].include?(:values) and !arguments[0].include?(:values_for)\n arguments[0][:values_for] = arguments[0][:values]\n end\n if content_type_included and (!headers_t[\"Content-Type\"][/text\\/xml/].nil? or\n !headers_t[\"Content-Type\"][\"application/soap+xml\"].nil? or\n !headers_t[\"Content-Type\"][/application\\/jxml/].nil?)\n if arguments[0].include?(:values_for)\n arguments[0][:values_for].each { |key, value|\n data = NiceHttpUtils.set_value_xml_tag(key.to_s(), data, value.to_s(), true)\n }\n end\n elsif content_type_included and !headers_t[\"Content-Type\"][/application\\/json/].nil? and data.to_s() != \"\"\n require \"json\"\n if data.kind_of?(String)\n if arguments[0].include?(:values_for)\n arguments[0][:values_for].each { |key, value|\n data.gsub!(/(( *|^)\"?#{key.to_s()}\"? *: *\")(.*)(\" *, *$)/, '\\1' + value + '\\4') # \"key\":\"value\", or key:\"value\",\n data.gsub!(/(( *|^)\"?#{key.to_s()}\"? *: *\")(.*)(\" *$)/, '\\1' + value + '\\4') # \"key\":\"value\" or key:\"value\"\n data.gsub!(/(( *|^)\"?#{key.to_s()}\"? *: *[^\"])([^\"].*)([^\"] *, *$)/, '\\1' + value + '\\4') # \"key\":456, or key:456,\n data.gsub!(/(( *|^)\"?#{key.to_s()}\"? *: *[^\"])([^\"].*)([^\"] * *$)/, '\\1' + value + '\\4') # \"key\":456 or key:456\n }\n end\n elsif data.kind_of?(Hash)\n data_n = Hash.new()\n data.each { |key, value|\n data_n[key.to_s()] = value\n }\n if arguments[0].include?(:values_for)\n #req[:values_for][:loginName] or req[:values_for][\"loginName\"]\n new_values_hash = Hash.new()\n arguments[0][:values_for].each { |kv, vv|\n if data_n.keys.include?(kv.to_s())\n new_values_hash[kv.to_s()] = vv\n end\n }\n data_n.merge!(new_values_hash)\n end\n data = data_n.to_json()\n elsif data.kind_of?(Array)\n data_arr = Array.new()\n data.each_with_index { |row, indx|\n unless row.kind_of?(Hash)\n @logger.fatal(\"Wrong format on request application/json, be sure is a Hash, Array of Hashes or JSON string\")\n return :error, :error, :error\n end\n data_n = Hash.new()\n row.each { |key, value|\n data_n[key.to_s()] = value\n }\n if arguments[0].include?(:values_for)\n #req[:values_for][:loginName] or req[:values_for][\"loginName\"]\n new_values_hash = Hash.new()\n if arguments[0][:values_for].kind_of?(Hash) #values[:mykey][3]\n arguments[0][:values_for].each { |kv, vv|\n if data_n.keys.include?(kv.to_s()) and !vv[indx].nil?\n new_values_hash[kv.to_s()] = vv[indx]\n end\n }\n elsif arguments[0][:values_for].kind_of?(Array) #values[5][:mykey]\n if !arguments[0][:values_for][indx].nil?\n arguments[0][:values_for][indx].each { |kv, vv|\n if data_n.keys.include?(kv.to_s())\n new_values_hash[kv.to_s()] = vv\n end\n }\n end\n else\n @logger.fatal(\"Wrong format on request application/json when supplying values, the data is an array of Hashes but the values supplied are not\")\n return :error, :error, :error\n end\n data_n.merge!(new_values_hash)\n end\n data_arr.push(data_n)\n }\n data = data_arr.to_json()\n else\n @logger.fatal(\"Wrong format on request application/json, be sure is a Hash, Array of Hashes or JSON string\")\n return :error, :error, :error\n end\n elsif content_type_included and arguments[0].include?(:values_for)\n if arguments[0][:values_for].kind_of?(Hash) and arguments[0][:values_for].keys.size > 0\n if !headers_t.nil? and headers_t.kind_of?(Hash) and headers_t[\"Content-Type\"] != \"application/x-www-form-urlencoded\" and headers_t[\"content-type\"] != \"application/x-www-form-urlencoded\"\n @logger.warn(\":values_for key given without a valid content-type or data for request. No values modified on the request\")\n end\n end\n end\n elsif arguments.size == 1 and arguments[0].kind_of?(String)\n #path=arguments[0].to_s()\n data = \"\"\n else\n @logger.fatal(\"Invalid number of arguments or wrong arguments in #{method_s}\")\n return :error, :error, :error\n end\n if headers_t.keys.include?(\"Content-Type\") and !headers_t[\"Content-Type\"][\"multipart/form-data\"].nil? and headers_t[\"Content-Type\"] != [\"multipart/form-data\"] #only for the case raw multipart request\n encoding = \"UTF-8\"\n data_s = \"\"\n else\n encoding = data.to_s().scan(/encoding='(.*)'/i).join\n if encoding.to_s() == \"\"\n encoding = data.to_s().scan(/charset='(.*)'/i).join\n end\n if encoding.to_s() == \"\" and headers_t.include?(\"Content-Type\")\n encoding = headers_t[\"Content-Type\"].scan(/charset='?(.*)'?/i).join\n if encoding.to_s() == \"\"\n encoding = headers_t[\"Content-Type\"].scan(/encoding='?(.*)'?/i).join\n end\n end\n\n begin\n data_s = JSON.pretty_generate(JSON.parse(data))\n rescue\n data_s = data\n end\n data_s = data_s.to_s().gsub(\"<\", \"&lt;\")\n end\n if headers_t.keys.include?(\"Accept-Encoding\")\n headers_t[\"Accept-Encoding\"].gsub!(\"gzip\", \"\") #removed so the response is in plain text\n end\n\n headers_ts = \"\"\n headers_t.each { |key, val| headers_ts += key.to_s + \":\" + val.to_s() + \", \" }\n message = \"#{method_s} REQUEST: \\npath= \" + path.to_s() + \"\\n\"\n message += \"headers= \" + headers_ts.to_s() + \"\\n\"\n message += \"data= \" + data_s.to_s() + \"\\n\"\n message = @message_server + \"\\n\" + message\n if path.to_s().scan(/^https?:\\/\\//).size > 0 and path.to_s().scan(/^https?:\\/\\/#{@host}/).size == 0\n # the path is for another server than the current\n else\n self.class.last_request = message\n @logger.info(message)\n end\n\n if data.to_s() != \"\" and encoding.to_s().upcase != \"UTF-8\" and encoding != \"\"\n data = data.to_s().encode(encoding, \"UTF-8\")\n end\n return path, data, headers_t\n rescue Exception => stack\n @logger.fatal(stack)\n @logger.fatal(\"manage_request Error on method #{method_s} . path:#{path.to_s()}. data:#{data.to_s()}. headers:#{headers_t.to_s()}\")\n return :error\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /sofas/1 GET /sofas/1.xml
def show #@sofa = Sofa.find(params[:title]) @sofa = Sofa.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @sofa } end end
[ "def new\n @sofa = Sofa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @sofa }\n end\n end", "def show\n @soon = Soon.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @soon }\n end\n end", "def show\n @servicosindex = Servicosindice.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @servicosindex }\n end\n end", "def show\n @servicios = Servicio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @servicios }\n end\n end", "def show\n @sitio = Sitio.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @sitio }\n end\n end", "def show\n @sitio = Sitio.find(params[:id])\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @sitio }\n end\n end", "def show\n @soap = Soap.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @soap }\n end\n end", "def show\n @solicitud = Solicitud.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @solicitud }\n end\n end", "def show\n @sifi = Sifi.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @sifi }\n end\n end", "def show\n @nossos_servico = NossosServico.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def show\n @tso = Tso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tso.to_xml(:except => [ :created_at, :updated_at ]) }\n end\n end", "def show\n @solexame = Solexame.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @solexame }\n end\n end", "def show\n @silo = Silo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @silo }\n end\n end", "def xml(id)\n http.get(\"/nfse/#{id}/xml\") do |response|\n response.headers.fetch(\"Location\") { \"\" }\n end\n end", "def index\n @sitios = Sitio.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @sitios }\n end\n end", "def index\n @sofas = Sofa.all\n end", "def show\n @solicitante = Solicitante.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @solicitante }\n end\n end", "def show\n @tah = Tah.find(params[:id])\n @tah_tsos = @tah.tsos.paginate(:page => params[:page])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @tah.to_xml(:except => [ :created_at, :updated_at ], :include => :tsos) }\n end\n end", "def show\n @selo = Selo.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @selo }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /sofas/new GET /sofas/new.xml
def new @sofa = Sofa.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @sofa } end end
[ "def new\n @tso = Tso.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @tso }\n end\n end", "def new\n @soon = Soon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @soon }\n end\n end", "def new\n @sitio = Sitio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @sitio }\n end\n end", "def new\n @nossos_servico = NossosServico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @nossos_servico }\n end\n end", "def new\n @spiga = Spiga.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @spiga }\n end\n end", "def new\n @sitio = Sitio.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @sitio }\n end\n end", "def new\n @softdb = Softdb.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @softdb }\n end\n end", "def new\n @servicios = Servicio.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @servicios }\n end\n end", "def new\n @sifi = Sifi.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @sifi }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end", "def new\n @solicitud = Solicitud.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @solicitud }\n end\n end", "def new\n @silo = Silo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @silo }\n end\n end", "def new\n @servico = Servico.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @servico }\n end\n end", "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @asesoria }\n end\n end", "def new\n @st_pi = StPi.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @st_pi }\n end\n end", "def new\n @spiel = Spiel.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @spiel }\n end\n end", "def new\n @soap = Soap.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @soap }\n end\n end", "def new\n @servicosindex = Servicosindice.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @servicosindex }\n end\n end", "def new\n @sitio=Sitio.find(params[:id])\n @foro = @sitio.foros.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @foro }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /sofas POST /sofas.xml
def create @sofa = Sofa.new(params[:sofa]) respond_to do |format| if @sofa.save flash[:notice] = 'Sofa was successfully created.' format.html { redirect_to(@sofa) } format.xml { render :xml => @sofa, :status => :created, :location => @sofa } else format.html { render :action => "new" } format.xml { render :xml => @sofa.errors, :status => :unprocessable_entity } end end end
[ "def create\n @sofa = Sofa.new(sofa_params)\n\n respond_to do |format|\n if @sofa.save\n format.html { redirect_to @sofa, notice: 'Sofa was successfully created.' }\n format.json { render :show, status: :created, location: @sofa }\n else\n format.html { render :new }\n format.json { render json: @sofa.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @sofa = Sofa.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @sofa }\n end\n end", "def create\n @director = Director.find(params[:director_id])\n @soaps = @director.soaps.create(soap_params)\n redirect_to director_path(@director)\n\n\n end", "def create\n @tso = Tso.new(params[:tso])\n\n respond_to do |format|\n if @tso.save\n flash[:notice] = 'Tso was successfully created.'\n format.html { redirect_to(@tso) }\n format.xml { render :xml => @tso, :status => :created, :location => @tso }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @tso.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 @solicitante = Solicitante.new(params[:solicitante])\n\n respond_to do |format|\n if @solicitante.save\n format.html { redirect_to(@solicitante, :notice => 'Solicitante was successfully created.') }\n format.xml { render :xml => @solicitante, :status => :created, :location => @solicitante }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @solicitante.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @sigesp_solicitud = Sigesp::Solicitud.new(sigesp_solicitud_params)\n\n respond_to do |format|\n if @sigesp_solicitud.save\n format.html { redirect_to @sigesp_solicitud, notice: 'Solicitud was successfully created.' }\n format.json { render action: 'show', status: :created, location: @sigesp_solicitud }\n else\n format.html { render action: 'new' }\n format.json { render json: @sigesp_solicitud.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @servicios = Servicio.new(params[:servicios])\n \n\n respond_to do |format|\n if @servicios.save\n flash[:notice] = 'Servicios was successfully created.'\n format.html { redirect_to(@servicios) }\n format.xml { render :xml => @servicios, :status => :created, :location => @servicios }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @servicios.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @solexame = Solexame.new(params[:solexame])\n\n respond_to do |format|\n if @solexame.save\n flash[:notice] = 'Solexame was successfully created.'\n format.html { redirect_to(@solexame) }\n format.xml { render :xml => @solexame, :status => :created, :location => @solexame }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @solexame.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @espacio = Espacio.new(params[:espacio])\n\n respond_to do |format|\n if @espacio.save\n flash[:notice] = 'Se creo el espacio satisfactoriamente.'\n format.html { redirect_to(@espacio) }\n format.xml { render :xml => @espacio, :status => :created, :location => @espacio }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @espacio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @soon = Soon.new(params[:soon])\n\n respond_to do |format|\n if @soon.save\n format.html { redirect_to(admin_magazine_soons_path(@magazine), :notice => 'Wkrótce zostało prawidłowo dodane.') }\n format.xml { render :xml => @soon, :status => :created, :location => @soon }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @soon.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @solicitation = Solicitation.new(params[:solicitation])\n\n respond_to do |format|\n if @solicitation.save\n format.html { redirect_to(@solicitation, :notice => 'Solicitation was successfully created.') }\n format.xml { render :xml => @solicitation, :status => :created, :location => @solicitation }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @solicitation.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @solexame = Solexame.new(solexame_params)\n\n respond_to do |format|\n if @solexame.save\n flash[:notice] = 'Solicitação foi criado com sucesso.'\n format.html { redirect_to(@solexame) }\n format.xml { render :xml => @solexame, :status => :created, :location => @solexame }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @solexame.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @siswa = Siswa.new(params[:siswa])\n\n respond_to do |format|\n if @siswa.save\n format.html { redirect_to @siswa, notice: 'Siswa was successfully created.' }\n format.json { render json: @siswa, status: :created, location: @siswa }\n else\n format.html { render action: \"new\" }\n format.json { render json: @siswa.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @socio_serasa = SocioSerasa.new(socio_serasa_params)\n\n respond_to do |format|\n if @socio_serasa.save\n format.html { redirect_to @socio_serasa, notice: 'Socio serasa was successfully created.' }\n format.json { render action: 'show', status: :created, location: @socio_serasa }\n else\n format.html { render action: 'new' }\n format.json { render json: @socio_serasa.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @sitio = Sitio.new(params[:sitio])\n\n respond_to do |format|\n if @sitio.save\n format.html { redirect_to(@sitio, :notice => 'Sitio was successfully created.') }\n format.xml { render :xml => @sitio, :status => :created, :location => @sitio }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @sitio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @nossos_servico = NossosServico.new(params[:nossos_servico])\n\n respond_to do |format|\n if @nossos_servico.save\n format.html { redirect_to(@nossos_servico, :notice => 'Nossos servico was successfully created.') }\n format.xml { render :xml => @nossos_servico, :status => :created, :location => @nossos_servico }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @nossos_servico.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @sapat = Sapat.new(sapat_params)\n\n respond_to do |format|\n if @sapat.save\n format.html { redirect_to @sapat, notice: 'Sapat was successfully created.' }\n format.json { render :show, status: :created, location: @sapat }\n else\n format.html { render :new }\n format.json { render json: @sapat.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @estagio = Estagio.new(params[:estagio])\n\n respond_to do |format|\n if @estagio.save\n flash[:notice] = 'Estagio was successfully created.'\n format.html { redirect_to(@estagio) }\n format.xml { render :xml => @estagio, :status => :created, :location => @estagio }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @estagio.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /sofas/1 PUT /sofas/1.xml
def update @sofa = Sofa.find(params[:id]) respond_to do |format| if @sofa.update_attributes(params[:sofa]) flash[:notice] = 'Sofa was successfully updated.' format.html { redirect_to(@sofa) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @sofa.errors, :status => :unprocessable_entity } end end 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_to do |format|\n if @sofa.update(sofa_params)\n format.html { redirect_to @sofa, notice: 'Sofa was successfully updated.' }\n format.json { render :show, status: :ok, location: @sofa }\n else\n format.html { render :edit }\n format.json { render json: @sofa.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 test_put_existing\n request = Http::Request.new('PUT', '/file1', {}, 'bar')\n\n response = self.request(request)\n\n assert_equal(204, response.status)\n\n assert_equal(\n 'bar',\n @server.tree.node_for_path('file1').get\n )\n\n assert_equal(\n {\n 'X-Sabre-Version' => [Version::VERSION],\n 'Content-Length' => ['0'],\n 'ETag' => [\"\\\"#{Digest::MD5.hexdigest('bar')}\\\"\"]\n },\n response.headers\n )\n end", "def update\n @solexame = Solexame.find(params[:id])\n\n respond_to do |format|\n if @solexame.update_attributes(params[:solexame])\n flash[:notice] = 'Solexame was successfully updated.'\n format.html { redirect_to(@solexame) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @solexame.errors, :status => :unprocessable_entity }\n end\n end\n end", "def put(*a) route 'PUT', *a end", "def put_datastream(pid, dsID, xml)\n uri = URI.parse(@fedora + '/objects/' + pid + '/datastreams/' + dsID ) \n RestClient.put(uri.to_s, xml, :content_type => \"application/xml\")\n rescue => e\n e.response \n end", "def update\n @xoso = Xoso.find(params[:id])\n\n respond_to do |format|\n if @xoso.update_attributes(params[:xoso])\n format.html { redirect_to @xoso, notice: 'Xoso was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @xoso.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @sitio = Sitio.find(params[:id])\n\n respond_to do |format|\n if @sitio.update_attributes(params[:sitio])\n format.html { redirect_to(@sitio, :notice => 'Sitio was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @sitio.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @soon = Soon.find(params[:id])\n\n respond_to do |format|\n if @soon.update_attributes(params[:soon])\n format.html { redirect_to @soon, notice: 'Soon was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @soon.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @servicosindex = Servicosindice.find(params[:id])\n\n respond_to do |format|\n if @servicosindex.update_attributes(params[:servicosindex])\n format.html { redirect_to(@servicosindex, :notice => 'Servicosindice was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @servicosindex.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @nossos_servico = NossosServico.find(params[:id])\n\n respond_to do |format|\n if @nossos_servico.update_attributes(params[:nossos_servico])\n format.html { redirect_to(@nossos_servico, :notice => 'Nossos servico was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @nossos_servico.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @sofa = Sofa.new(params[:sofa])\n\n respond_to do |format|\n if @sofa.save\n flash[:notice] = 'Sofa was successfully created.'\n format.html { redirect_to(@sofa) }\n format.xml { render :xml => @sofa, :status => :created, :location => @sofa }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @sofa.errors, :status => :unprocessable_entity }\n end\n end\n end", "def put *args\n make_request :put, *args\n end", "def do_PUT(req, res)\n domain, resource, id, format = parse_request_path(req.path_info)\n attributes = from_xml(resource, req.body)\n attributes['updated-at'] = Time.now.iso8601\n logger.debug \"Updating item with attributes: #{attributes.inspect}\"\n sdb_put_item(domain, attributes, true)\n raise WEBrick::HTTPStatus::OK\n end", "def update\n @soon = Soon.find(params[:id])\n\n respond_to do |format|\n if @soon.update_attributes(params[:soon])\n format.html { redirect_to( admin_magazine_soons_path(@magazine), :notice => 'Wkrótce zostala prawidłowo zaktualizowane.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @soon.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @oase = Oasis.find(params[:id])\n\n respond_to do |format|\n if @oase.update_attributes(params[:oase])\n format.html { redirect_to @oase, notice: 'Oasis was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @oase.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @servicios = Servicios.find(params[:id])\n\n respond_to do |format|\n if @servicios.update_attributes(params[:servicios])\n flash[:notice] = 'Servicios was successfully updated.'\n format.html { redirect_to(@servicios) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @servicios.errors, :status => :unprocessable_entity }\n end\n end\n end", "def put(path, params={}); make_request(:put, host, port, path, params); end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /sofas/1 DELETE /sofas/1.xml
def destroy @sofa = Sofa.find(params[:id]) @sofa.destroy respond_to do |format| format.html { redirect_to(sofas_url) } format.xml { head :ok } end end
[ "def destroy\n @softdb = Softdb.find(params[:id])\n @softdb.destroy\n\n respond_to do |format|\n format.html { redirect_to(softdbs_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @sa = Sa.find(params[:id])\n @sa.destroy\n\n respond_to do |format|\n format.html { redirect_to(sas_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @estatu = Estatu.find(params[:id])\n @estatu.destroy\n\n respond_to do |format|\n format.html { redirect_to(estatus_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @scrap_xml = ScrapXml.find(params[:id])\n @scrap_xml.destroy\n\n respond_to do |format|\n format.html { redirect_to(scrap_xmls_url) }\n format.xml { head :ok }\n end\n end", "def del\n @status1 = Status1.find(params[:id])\n @status1.destroy\n\n respond_to do |format|\n format.html { redirect_to(status1s_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @senhas = Senha.find(params[:id])\n @senhas.destroy\n\n respond_to do |format|\n format.html { redirect_to(homes_path) }\n format.xml { head :ok }\n end\n end", "def destroy\n @estacion = Estacion.find(params[:id])\n @estacion.destroy\n\n respond_to do |format|\n format.html { redirect_to(estaciones_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @segmento = Segmento.find(params[:id])\n @segmento.destroy\n\n respond_to do |format|\n format.html { redirect_to(segmentos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @sisben = Sisben.find(params[:id])\n @sisben.destroy\n\n respond_to do |format|\n format.html { redirect_to(sisbenes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @dependencia = Dependencia.find(params[:id])\n @dependencia.destroy\n\n respond_to do |format|\n format.html { redirect_to(dependencias_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @tso = Tso.find(params[:id])\n @tso.destroy\n\n respond_to do |format|\n format.html { redirect_to(tsos_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @solicitante = Solicitante.find(params[:id])\n @solicitante.destroy\n\n respond_to do |format|\n format.html { redirect_to(solicitantes_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @solicitud_documento = SolicitudDocumento.find(params[:id])\n @solicitud_documento.destroy\n\n respond_to do |format|\n format.html { redirect_to(solicitudes_documento_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @sifi = Sifi.find(params[:id])\n @sifi.destroy\n\n respond_to do |format|\n format.html { redirect_to(sifis_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @satelite = Satelite.find(params[:id])\n @satelite.destroy\n\n respond_to do |format|\n format.html { redirect_to(satelites_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @feria2010observacion = Feria2010observacion.find(params[:id])\n @feria2010observacion.destroy\n\n respond_to do |format|\n format.html { redirect_to(feria2010observaciones_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @xsd.destroy\n\n respond_to do |format|\n format.html { redirect_to '/wsdl/' }\n format.xml { head :ok }\n end\n end", "def destroy\n @saidas = Saida.find(params[:id])\n @saidas.destroy\n\n respond_to do |format|\n format.html { redirect_to(homes_path) }\n format.xml { head :ok }\n end\n end", "def destroy\n @nossos_servico = NossosServico.find(params[:id])\n @nossos_servico.destroy\n\n respond_to do |format|\n format.html { redirect_to(nossos_servicos_url) }\n format.xml { head :ok }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests to see if specified dropdown group should be highlighted or not
def highlight?(dropdown_group) if dropdown_group == 'home' ["/", "/dashboard/network"].any? do | route | current_page?(route) end elsif dropdown_group == 'manage' ["/dashboard/visualconfig", "/dashboard/manage", "/dashboard/instances"].any? do | route | current_page?(route) end elsif dropdown_group == 'admin' ["/admin/users", "/admin/settings"].any? do | route | current_page?(route) end elsif dropdown_group == 'configures' ["/configures", "/configures/new"].any? do | route | current_page?(route) end end end
[ "def group_choosen?\n !current_group.nil?\n end", "def selected_group?(group_name)\n @selected_path[1].to_s == group_name.to_s\n end", "def group?\n return self.selector == Selector::GROUP\n end", "def is_option_from_radio_button_group_selected(access_type, by, option, access_name, should_be_selected=true)\n radio_button_group = WAIT.until{$driver.find_elements(:\"#{access_type}\" => \"#{access_name}\")}\n \n getter = ->(rb, by) { by == 'value' ? rb.attribute('value') : rb.text }\t\n \n ele = radio_button_group.find { |rb| getter.call(rb, by) == option }\n \n if !ele.selected? && should_be_selected\n raise TestCaseFailed ,'Radio button is not selected'\n elsif ele.selected? && !should_be_selected\n raise TestCaseFailed ,'Radio button is selected'\n end\nend", "def select_according_to_group\n garr = []\n self.grouptables.each do |x| garr << x.table_attribute.split('.').last end\n self.selecttables.each do |x| \n if (!(x.table_attribute.include?(\"(\")) and !(garr.include?(x.table_attribute.split('.').last)) and !garr.empty?)\n errors.add(:grouptables,\"group and select string is not compatible\")\n end \n end\n end", "def valid_group_title?(group)\n PrometheusMetricEnums\n .custom_group_details\n .map { |_, details| details[:group_title] }\n .include?(group)\n end", "def is_default_group?\n self.name==\"Default\"\n end", "def group_assignment?\n invalid_override || group_max > 1\n end", "def option_selected?(i)\n @selected == i\n end", "def check_group(name)\n self.checkbox(:title=>\"Select #{name}\").set\n end", "def is_option_from_radio_button_group_selected(access_type, by, option, access_name, should_be_selected = true)\n radio_button_group = $driver.find_elements(:\"#{access_type}\" => \"#{access_name}\")\n\n getter = ->(rb, by) { by == 'value' ? rb.attribute('value') : rb.text }\n\n ele = radio_button_group.find { |rb| getter.call(rb, by) == option }\n\n expect(ele.selected?).to be should_be_selected\nend", "def is_selected?\r\n return @cd_selected\r\n end", "def check_group(group_name)\n frm.table(:id=>\"groupTable\").row(:text=>/#{Regexp.escape(group_name)}/).checkbox(:name=>\"selectedGroups\").set\n end", "def valid_dropdown?(dropdown)\n return false unless dropdown.position\n return false unless %W(left right).include? dropdown.position.to_s\n return false unless dropdown.caption \n return false unless valid_subitems?(dropdown.subitems)\n true\n end", "def check_for_groupings(groupings)\n if groupings.blank?\n raise I18n.t('groups.select_a_group')\n end\n end", "def groupIconSelectable \n \"groupIconSelectable\" \n end", "def validate_groups\n true\n end", "def is_ebook_options_selected?(option)\n return true if option == \"2\" || option == \"3\"\n\tend", "def selected\r\n assert_exists\r\n #@option.selected\r\n option_selected\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current page number of the manga. This will not make any api calls and only looks at (url, referer_url).
def manga_page # http://i2.pixiv.net/img04/img/syounen_no_uta/46170939_p0.jpg # http://i1.pixiv.net/c/600x600/img-master/img/2014/09/24/23/25/08/46168376_p0_master1200.jpg # http://i1.pixiv.net/img-original/img/2014/09/25/23/09/29/46183440_p0.jpg if url =~ %r{/\d+_p(\d+)(?:_\w+)?\.#{EXT}}i return $1.to_i end # http://www.pixiv.net/member_illust.php?mode=manga_big&illust_id=46170939&page=0 [url, referer_url].each do |x| if x =~ /page=(\d+)/i return $1.to_i end end nil end
[ "def page_number\n @page_number ||= full_response[\"PageNumber\"]&&full_response[\"PageNumber\"].to_i\n end", "def current_page_number\n return 1 if page_is_first_page?\n page_number\n end", "def page_number\n from_meta(:page_number, 1)\n end", "def PageNo()\n\t\t#Get current page number\n\t\treturn @page;\n\tend", "def page_number_for(name, response)\n response.result['meta']['links'][name.to_s].split('=').last.to_i\n rescue NoMethodError\n nil\n end", "def page_number\n @page_number || 1\n end", "def current_page\n params[:page] && params[:page].match(/\\d+/) ? params[:page].to_i : 1\n end", "def page\n return 1 if !params[page_param] || params[page_param].empty?\n params[page_param].to_i\n end", "def current_page\n return 1 unless self.paginated?\n return 1 if @conditions[:page].to_i < 1\n return @conditions[:page].to_i\n end", "def current_page_number\n @pageset.size\n end", "def page_number\n (params[:page] || 1).to_i\n end", "def page\n page = @page.to_i\n page > 1 ? page : 1\n end", "def page_num_getter\n\t\t##Nokogiri\n\t\t# doc = Nokogiri::HTML(open(@page_name))\n\t\t# puts doc.css('result custom-right-inner')\n\t\t##Mechanize\n\t\t##new agent\n\t\t@agent = Mechanize.new\n\t\tstr = @agent.get(@page_name).search('span.custom-right-inner')[0].text\n\t\t@total_page = str.scan(/\\d+/)[0].to_i\n\tend", "def parse_page() # :doc:\n result = nil\n if x = parse_arg(:page)\n result = x.to_i\n raise error(102, \"invalid page: '#{x}'\") if result < 1\n else\n result = 1\n end\n return result\n end", "def page\n\t\t\t@page ||= request.headers[\"page\"] || 1\n\t\tend", "def get_last_page\n query = URI.parse(request.referrer).query\n @last_page = query.nil? ? 0 : CGI.parse(query)[\"page\"].first.to_i\n end", "def get_page_number\n # this is the normal case; masterfile and unit share same metadata record\n # so page number will match the numbering sequence of the filename\n page = filename.split(\"_\")[1].split(\".\")[0].to_i\n # if metadata_id == unit.metadata_id\n if is_clone?\n mf_id = original_mf_id\n page = MasterFile.find(mf_id).filename.split(\"_\")[1].split(\".\")[0].to_i\n end\n # else\n # # this master file has been assigned to a separate metadata record. the\n # # page number in the filename does not reflect the actual page num. Count\n # # masterfiles owned by metadata record to determine\n # page = 1\n # metadata.master_files.each do |mf|\n # if mf.id == id\n # break\n # else\n # page += 1\n # end\n # end\n # end\n return page\n end", "def next_page_number\n last_page? ? nil : current_page_number + 1\n end", "def page\n (params[:page] || 0).to_i\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TEST CASE: CONSTANT OPERATORS. IT SHOULD CONTAIN ALL VALID OPERATORS
def test_operator_array assert_equal(OPERATORS, RomanMathmaticalOperation::OPERATORS) assert_not_equal(WRONG_OPERATORS, RomanMathmaticalOperation::OPERATORS ) end
[ "def test_operator_valid\n assert @rpn.operator?('+')\n assert @rpn.operator?('-')\n assert @rpn.operator?('/')\n assert @rpn.operator?('*')\n end", "def test_valid_input\n assert_equal(nil, RomanMathmaticalOperation.new(\"X\", \"+\",\"V\").send(:valid_input))\n exception = assert_raise(\"RomanMathmaticalOperationError\") {RomanMathmaticalOperation.new(\"X\", \"+\",nil).send(:valid_input)}\n assert_equal(\"This X or is not valid\", exception.message)\n exception = assert_raise(\"RomanMathmaticalOperationError\") {RomanMathmaticalOperation.new(\"X\", \"%\",\"V\").send(:valid_input)}\n assert_equal(\"Operator missmatch\", exception.message)\n end", "def test_read_operands\n test = Struct.new(:op, :operands, :bytes_read)\n tests = [\n test.new(Opcode::CONSTANT, [65_535], 2)\n ]\n tests.each do |tt|\n instruction = make(tt.op, tt.operands)\n definition = lookup(tt.op.ord)\n assert_not_nil(definition)\n operands_read, n = read_operands(definition, instruction[1...instruction.length])\n assert_equal(tt.bytes_read, n)\n assert_equal(tt.operands, operands_read)\n end\n end", "def test_op_op_sequences\n ops = [AddOpToken.instance, SubtractOpToken.instance,\n MultiplyOpToken.instance, DivideOpToken.instance,\n ExponentOpToken.instance,\n LeftParenthesisToken.instance, RightParenthesisToken.instance]\n ops.each do |op1|\n ops.each do |op2|\n source = op1.lexeme.to_s + op2.lexeme.to_s\n assert_tokenises_as source, op1, op2\n end\n end\n end", "def test_required_class_constants\n @cmds.each do |cmd_name, cmd|\n if cmd.is_a?(Trepan::SubcommandMgr)\n cmd.subcmds.subcmds.each do |subcmd_name, subcmd|\n where = \"of subcommand #{subcmd_name} in command #{cmd_name}\"\n %w(HELP NAME SHORT_HELP).each do\n |const|\n value = subcmd.my_const(const)\n assert_equal(true, value.is_a?(String),\n \"#{const} #{where} should be a String; got #{value}.\")\n end\n value = subcmd.my_const('MIN_ABBREV')\n assert(value.is_a?(Fixnum),\n \"MIN_ABBREV #{where} should be a Fixnum; got #{value}.\")\n\n if 'show' == cmd_name\n short_help = subcmd.my_const('SHORT_HELP')\n needed_start = 'Show '\n assert_equal(needed_start, short_help[0..needed_start.size-1],\n \"Short help #{where} should start: \\\"#{needed_start}\\\"; got #{short_help}\")\n end\n end\n end\n end\n end", "def DISABLED_test_op_op_sequences\n ops = [AddOpToken.instance, SubtractOpToken.instance,\n MultiplyOpToken.instance, DivideOpToken.instance,\n ExponentOpToken.instance,\n LeftParenthesisToken.instance, RightParenthesisToken.instance]\n ops.each do |op1|\n ops.each do |op2|\n source = op1.lexeme.to_s + op2.lexeme.to_s\n assert_tokenises_as source, op1, op2\n end\n end\n end", "def test_static\n assert_equal('1', Examples::KeywordBarBaz.check(1))\n assert_equal('Bar', Examples::KeywordBarBaz.check(3))\n assert_equal('Baz', Examples::KeywordBarBaz.check(5))\n assert_equal('BarBaz', Examples::KeywordBarBaz.check(15))\n assert_equal(3, Examples::KeywordBarBaz.bar)\n assert_equal(5, Examples::KeywordBarBaz.baz)\n assert_equal(%w[1 2 Bar], Examples::KeywordBarBaz.check_range(1..3))\n\n assert_equal('Bar', Examples::KeywordBarBaz.bar_string)\n assert_equal('Baz', Examples::KeywordBarBaz.baz_string)\n end", "def test_do_math_middle_keyword\r\n input = [\"1\", \"PRINT\", \"+\"]\r\n val = 0\r\n assert_output(\"Line 0: Could not evaluate expression\\n\") {val = @arg_checker.do_math(input)}\r\n assert_equal [], val\r\n end", "def test_let_op_valid_expression\n value = @rpn.let_op(['a', '1'])\n assert_equal value, 1\n value = @rpn.let_op(['a', '1', '1', '+'])\n assert_equal value, 2\n end", "def test_static_foo\n assert_equal('FizzFooBar', Examples::FizzBuzzFooBarBazBang.check(63))\n assert_equal('FooBaz', Examples::FizzBuzzFooBarBazBang.check(77))\n assert_equal('FooBang', Examples::FizzBuzzFooBarBazBang.check(91))\n end", "def test_add_token\n assert_tokenises_as '+', AddOpToken.instance\n assert_tokenises_as ' +', AddOpToken.instance\n assert_tokenises_as ' + ', AddOpToken.instance\n end", "def test_handle_operators_multiply_valid\r\n @arg_checker.stack = [\"3\", \"6\"]\r\n input = '*'\r\n val = 0\r\n assert_output(\"\") {val = @arg_checker.handle_operators(input)}\r\n assert_equal val, true\r\n assert_equal [18], @arg_checker.stack\r\n end", "def test_constants_mode_symbols\n 7.times.each do |i|\n mode_name = ::Malody::Mode.constants\n if i.zero? then\n mode_sel = Set.new(mode_name)\n mode_value = -1\n else\n mode_sel = Set.new(mode_name.sample(rand((mode_name.size / 3)...(mode_name.size))))\n mode_value = ::Malody::Mode.get_mode_value(*mode_sel)\n end\n mode_sel2 = Set.new(::Malody::Mode.get_modes(mode_value))\n assert_equal mode_sel, mode_sel2, \"Given mode value should return back to its own\"\n end\n end", "def test_operand_var\n @rpn.add_var(\"X\", 10)\n assert @rpn.operand?(\"X\")\n end", "def test_Arithmetic_Sample04\n assert_equal(16, 2**2**2)\n assert_equal(81, 3**2**2)\n end", "def test_handle_operators_add_valid\r\n @arg_checker.stack = [\"1\", \"1\"]\r\n input = '+'\r\n val = 0\r\n assert_output(\"\") {val = @arg_checker.handle_operators(input)}\r\n assert_equal val, true\r\n assert_equal [2], @arg_checker.stack\r\n end", "def constants() end", "def test_value_of\n test1 = nil\n test2 = ''\n\n assert_equal('', value_of(test1, 0))\n assert_equal('', value_of(test2, 0))\n end", "def test_static\n assert_equal('1', Examples::KeyBuzz.check(1))\n assert_equal('Key', Examples::KeyBuzz.check(3))\n assert_equal('Buzz', Examples::KeyBuzz.check(5))\n assert_equal('KeyBuzz', Examples::KeyBuzz.check(15))\n assert_equal(3, Examples::KeyBuzz.Key)\n assert_equal(5, Examples::KeyBuzz.Buzz)\n assert_equal(%w[1 2 Key], Examples::KeyBuzz.check_range(1..3))\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TEST CASE: to_num METHOD. IT SHOULD RETURN INTEGER VALUE IF VALID INPUT (ROMAN LETTER) PASSED ELSE RETURN 0
def test_to_num assert_equal(11, RomanMathmaticalOperation.new.send(:to_num,"XI")) assert_equal(0, RomanMathmaticalOperation.new.send(:to_num,"wrong")) assert_not_equal(11, RomanMathmaticalOperation.new.send(:to_num,"X")) end
[ "def to_num\n if token == \"i\"\n return token.to_c\n elsif token.include? \".\"\n return token.to_f\n elsif (token =~ /[a-zA-Z]/) == 0\n return token\n else\n return token.to_i\n end\n end", "def charToNum(letter)\n return letter.upcase.ord-65 #ensure this is uppercase???\nend", "def isNumber(character)\n return character.to_i.to_s == character.to_s\nend", "def to_number( word )\n begin\n return Integer( word )\n rescue\n puts $!\n end\n begin\n return Float( word )\n rescue\n puts $!\n end\n nil\n end", "def convert_string_to_number(str); end", "def isnum(char)\r\n\treturn char[0] >= 48 && char[0] <= 57\r\nend", "def to_numeric(num)\n if num.nil?\n 0\n elsif num.kind_of? Integer\n num\n else\n 1 # We count each instance of a string this way\n end\n end", "def string_to_number(s)\n s.to_i\nend", "def to_digit\n return NUMBER[self] if self <= 9 && self >= 0\n NUMBER[0]\n end", "def binary_to_num(s); end", "def test_can_convert_numbers\n\t\tassert_equal(11, arabic_converter(\"XI\"))\n\t\tassert_equal(14, arabic_converter(\"XIV\"))\n\t\tassert_equal(19, arabic_converter(\"XIX\"))\n\t\tassert_equal(16, arabic_converter(\"XVI\"))\n\t\tassert_equal(18, arabic_converter(\"XVIII\"))\n\tend", "def convert_string_input_to_integer(str)\n is_string_a_valid_integer?(str) ? str.to_i : nil\nend", "def replaceCharToNumber(char)\n case char\n when 'T'\n then\n char = 10\n when 'J'\n then\n char = 11\n when 'Q'\n then\n char = 12\n when 'K'\n then\n char = 13\n when 'A'\n then\n char = 14\n end\n char.to_i\nend", "def is_number?(tok)\n #check number format: correct types of digits\n if tok[0] == 36 # $\n return nil if( (tok.sub(\"$\",\"\") =~ /[^A-Fa-f0-9]/) != nil)\n elsif tok[0] == 67 # C\n return nil if ( (tok.sub(\"C\",\"\") =~ /[^0-7]/) != nil)\n elsif tok[0] == 66 # B\n return nil if ( (tok.sub(\"B\",\"\") =~ /[^01]/) != nil) \n elsif tok[0] >= 48 and tok[0] <= 57\n return nil if ( (tok =~ /[^0-9]/) != nil) \n else\n #can raise exceptions here:\n return nil\n end\n \n return get_number_system(tok)\n end", "def number\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 1 )\n value = nil\n __DEC_NUMBER1__ = nil\n __HEX_NUMBER2__ = nil\n\n begin\n # at line 22:2: ( DEC_NUMBER | HEX_NUMBER )\n alt_1 = 2\n look_1_0 = @input.peek( 1 )\n\n if ( look_1_0 == DEC_NUMBER )\n alt_1 = 1\n elsif ( look_1_0 == HEX_NUMBER )\n alt_1 = 2\n else\n raise NoViableAlternative( \"\", 1, 0 )\n end\n case alt_1\n when 1\n # at line 22:4: DEC_NUMBER\n __DEC_NUMBER1__ = match( DEC_NUMBER, TOKENS_FOLLOWING_DEC_NUMBER_IN_number_180 )\n # --> action\n value = __DEC_NUMBER1__.text.to_i \n # <-- action\n\n when 2\n # at line 23:4: HEX_NUMBER\n __HEX_NUMBER2__ = match( HEX_NUMBER, TOKENS_FOLLOWING_HEX_NUMBER_IN_number_187 )\n # --> action\n value = __HEX_NUMBER2__.text[2..-1].to_i(16) \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__, 1 )\n\n end\n \n return value\n end", "def to_integer(input); end", "def scanAsNumber(str)\n if(str =~ /^[0-9]*$/)\n return str.to_i ;\n else\n return str.to_f ;\n end\n end", "def getOneLetter digit\n case digit\n when 1\n return 'I'\n when 2\n return 'X'\n when 3\n return 'C'\n when 4\n return 'M'\n else\n puts \"\\nError: invald digit place\"\n return nil\n end\nend", "def test_to_char\n onum = OraNumber.new(123.45)\n assert_equal(' 123.4500', onum.to_char('99999.9999'))\n assert_equal(' 0123.4500', onum.to_char('90000.0009'))\n assert_equal(' 00123.4500', onum.to_char('00000.0000'))\n assert_equal('123.45', onum.to_char('FM99999.9999'))\n assert_equal('0123.450', onum.to_char('FM90000.0009'))\n assert_equal('00123.4500', onum.to_char('FM00000.0000'))\n assert_equal(' -123.4500',(-onum).to_char('99999.9999'))\n assert_equal(' -0123.4500',(-onum).to_char('90000.0009'))\n assert_equal('-00123.4500',(-onum).to_char('00000.0000'))\n assert_equal('-123.45', (-onum).to_char('FM99999.9999'))\n assert_equal('-0123.450', (-onum).to_char('FM90000.0009'))\n assert_equal('-00123.4500',(-onum).to_char('FM00000.0000'))\n assert_equal(' 0,123.4500', onum.to_char('0G000D0000', \"NLS_NUMERIC_CHARACTERS = '.,'\"))\n assert_equal(' 0.123,4500', onum.to_char('0G000D0000', \"NLS_NUMERIC_CHARACTERS = ',.'\"))\n assert_equal('Ducat123.45', onum.to_char('FML9999.999', \"NLS_CURRENCY = 'Ducat'\"))\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TEST CASE: valid_input METHOD. IT SHOULD RETURN nil IF VALID(ROMAN LETTERS AND OPERATORS) INPUT PASSED ELSE RAISE EXCEPTION
def test_valid_input assert_equal(nil, RomanMathmaticalOperation.new("X", "+","V").send(:valid_input)) exception = assert_raise("RomanMathmaticalOperationError") {RomanMathmaticalOperation.new("X", "+",nil).send(:valid_input)} assert_equal("This X or is not valid", exception.message) exception = assert_raise("RomanMathmaticalOperationError") {RomanMathmaticalOperation.new("X", "%","V").send(:valid_input)} assert_equal("Operator missmatch", exception.message) end
[ "def test_accepting_vaild_input\n input = ''\n end", "def test_handle_input_valid\r\n input = '1 1 +'\r\n assert_output(\"2\\n\") {@arg_checker.handle_input(input)}\r\n end", "def get_and_validate_input\n result = gets.chomp.strip\n case\n when result.length < 2\n return FALSE\n when result == 'NO'\n return :quit\n else\n return result\n end\n end", "def test_handle_input_unkown_keyword\r\n input = 'LET CDD 27'\r\n assert_output(\"Line 1: Unknown keyword CDD\\n\") {@arg_checker.handle_input(input)}\r\n end", "def input_reader_test\n include Input_reader\n if !verify_single_input(\"FFgt\") && verify_single_input(\"F2\") && !verify_single_input(\"BB\") && verify_single_input(\"B\") && !verify_single_input(\"C2\")\n puts \"Successfully verify the single input\"\n else puts \"Fail to verify the single input\"\n end\n\n split_result = split_single_input(\"F2\")\n if (split_result[:direction] == \"F\") && (split_result[:length] == 2)\n puts \"Successfully split the single input\"\n else puts \"Fail to split the single input\"\n end\n\n if verify_user_input(\"F2,F3,B3,R2,L\") && verify_user_input(\"F2\") && !verify_user_input(\"F2,F33,B3,R2,L\")\n puts \"Successfully verify the user input\"\n else puts \"Fail to verify the user input\"\n end\n\n puts \"Successfully split the user input\" if split_user_input(\"F2,F3,B3,R2,L\")[2] == {:direction=>\"B\", :length=>3}\nend", "def validate_input_letter(input)\n until !input.match(/[^a-z]/)\n puts \"\\nPlease return a valid letters from A to Z.\\n\"\n input = gets.chomp.downcase\n end\n end", "def test_that_will_return_invalid_if_too_many_letters_or_wrong_characters\n assert_equal(\"Invalid Input\", arabic_converter(\"IIII\"))\n assert_equal(\"Invalid Input\", arabic_converter(\"1\"))\n assert_equal(\"Invalid Input\", arabic_converter(\"xV\"))\n assert_equal(\"Invalid Input\", arabic_converter(\"a.]\"))\n end", "def get_input\n input = params[\"input\"]\n valid_input(input)\nend", "def test_name_generator_with_invalid_input\nresult = name_generator(\"89&6\\n 5.,?<\")\nassert_equal(\"Inavalid ID. Please enter new ID with only lower case letters.\", result)\nend", "def test_empty_str(empty_str, exp_result)\n actual_result = Validator.string_of_nums?(empty_str)\n if(actual_result == exp_result)\n puts(\"PASS\")\n else\n puts(\"FAIL\")\n end\n return actual_result\nend", "def test_7_rejects_only_alphnumeric\n result = is_alphanumeric?(\"1Abjilsa2\")\n refute(result, \"1Abjilsa2 has no alphanumeric, should be valid\")\n end", "def acceptInput( instruction, creationStep, acceptableValues, error, numerical = false )\n goodInput = false\n input = \"\"\n\n while goodInput == false\n puts instruction\n if numerical == false\n # String-based input\n input = gets.chomp.downcase\n else\n # Integer-based input\n input = gets.chomp.to_i\n end\n\n # Accept any input unless received explicit selectable values\n return input unless acceptableValues != \"all\" || input == \"help\"\n\n if acceptableValues.include?( input )\n return input\n elsif input == \"help\" || input == \"help\".to_i\n puts HelpText::HELP[ creationStep ]\n else\n error.call( input )\n end\n\n end\n\nend", "def test_example_4_bad_input\n begin\n Pricer::Calculator.run(price: 12_456.95, people: 0, material: :books)\n assert false\n rescue Pricer::Errors::BadInput\n assert true\n end\n end", "def valid_input(input)\n valid = false\n parsed_input = downcase_camelcase_input(input)\n while valid == false\n #accepts uppercase or lowercase Y/N\n if parsed_input == \"Y\" || parsed_input ==\"N\"\n valid = true\n else\n puts \"\\nPlease enter Y or N:\\n\"\n print \"⚡️ \"\n input = gets.chomp.strip\n parsed_input = downcase_camelcase_input(input)\n end\n end\n parsed_input\n end", "def valid?(input)\n OPERATORS.include?(input) || numeric?(input)\n end", "def test_valid_choice_false_5\n user_input = \"3a\"\n assert_equal false, valid_choice?(user_input)\n end", "def check_input(num)\n if num.match(/\\A\\d+\\Z/) #regex check of string having a number\n return \"number\"\n elsif num == \"sort\" # if user types calculate then they are done entering numbers\n return \"exit\"\n else\n return \"error\" # if user didn't type calculate or a number then they didn't type in acceptable entry\n end\nend", "def test_rejects_password_with_no_na_char\n result = at_least_one_na_character?(\"1Abjilsa\")\n refute(result, \"'1Abjilsa should be invalid because it does not contain non-alphanumeric characters\")\n end", "def test_it_recognizes_if_guess_has_invalid_characters\n attempt = Guess.new('rngy')\n attempt.valid_characters?\n\n refute attempt.valid_characters?\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TEST is_roman METHOD IT SHOULD RETURN TRUE IF VALID(ROMAN LETTER) INPUT PASSED ELSE RAISE EXCEPTION
def test_is_roman assert_equal(true, RomanMathmaticalOperation.is_roman("V")) exception = assert_raise("RomanMathmaticalOperationError") {RomanMathmaticalOperation.is_roman(1)} assert_equal("Not valid input", exception.message) exception = assert_raise("RomanMathmaticalOperationError") {RomanMathmaticalOperation.is_roman("WRONG")} assert_equal("Not valid input", exception.message) end
[ "def is_roman?\n @input.is_a? String\n end", "def validate_roman roman_str\n\tif roman_str.scan(/^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/).empty?\n\t\tabort(\"Invalid Roman Language\")\n\tend\nend", "def roman?\r\n # Liberal definition: all Roman numeral letters\r\n self.upcase =~ ROMAN_REGEXP\r\n # ALT: Stolen from O'Reilly's Perl Cookbook 6.23. Regular Expression Grabbag\r\n #self =~ /^M*(D?C{0,3}|C[DM])(L?X{0,3}|X[LC])(V?I{0,3}|I[VX])$/i\r\n # ALT: Catch all non-arabic numbers\r\n # not self.arabic?\r\n end", "def is_valid_roman?(number)\n return false if number.match(/(IIII|XXXX|CCCC|MMMM)+/)\n return false if number.match(/(VV|LL|DD)+/)\n numarr = number.split(\"\")\n response = true\n numarr.each_with_index do |num, id|\n response = case num\n when \"I\"\n return false if numarr[id+1] and roman_measures[numarr[id+1]] > 10\n true\n when \"V\"\n return false if numarr[id+1] and roman_measures[numarr[id+1]] > 5\n true\n when \"X\"\n return false if numarr[id+1] and roman_measures[numarr[id+1]] > 100\n true\n when \"L\"\n return false if numarr[id+1] and roman_measures[numarr[id+1]] > 50\n true\n when \"C\"\n true\n when \"D\"\n return false if numarr[id+1] and roman_measures[numarr[id+1]] > 500\n true\n when \"M\"\n true\n else\n return false\n end\n end\n response\n end", "def is_roman_numeral?\n RomanNumeral.is_roman_numeral?(self)\n end", "def is_roman_numeral?\n RomanNumerals.is_roman_numeral?(self)\n end", "def test_valid_input\n assert_equal(nil, RomanMathmaticalOperation.new(\"X\", \"+\",\"V\").send(:valid_input))\n exception = assert_raise(\"RomanMathmaticalOperationError\") {RomanMathmaticalOperation.new(\"X\", \"+\",nil).send(:valid_input)}\n assert_equal(\"This X or is not valid\", exception.message)\n exception = assert_raise(\"RomanMathmaticalOperationError\") {RomanMathmaticalOperation.new(\"X\", \"%\",\"V\").send(:valid_input)}\n assert_equal(\"Operator missmatch\", exception.message)\n end", "def test_that_will_return_invalid_if_too_many_letters_or_wrong_characters\n assert_equal(\"Invalid Input\", arabic_converter(\"IIII\"))\n assert_equal(\"Invalid Input\", arabic_converter(\"1\"))\n assert_equal(\"Invalid Input\", arabic_converter(\"xV\"))\n assert_equal(\"Invalid Input\", arabic_converter(\"a.]\"))\n end", "def roman_method_logic(arabic_cmd, roman_cmd)\n return handle_arabic_cmd(arabic_cmd) unless arabic_cmd.nil?\n return handle_roman_cmd(roman_cmd) unless roman_cmd.nil?\n rescue ArgumentError => e\n e.message\n end", "def test_convert_roman_one_to_arabic_one\n generic_fn_roman_numerals( 'I', '1' )\n end", "def romanOf strNum\n\n intNum = strNum.to_i\n # if the parameter is not an int, empty, or out of range\n if strNum[/[0-9]+/] != strNum || intNum > 4999 || intNum == 0\n return nil\n end\n\n # the unfinished Roman numeral\n numeral = ''\n numDigits = strNum.length\n\n i = 0\n while i < numDigits\n\n # the (numDigits - i)th digit from the right\n digit = strNum[i].to_i\n if digit.to_i >= 5 # add five-letter\n numeral += getFiveLetter(numDigits - i)\n digit -= 5\n end\n numeral += getOneLetter(numDigits - i) * digit # add one-letter\n i += 1\n\n end\n\n return numeral\n\nend", "def from_roman(num)\nend", "def roman_numbers num\n case num\n when 'CM'\n return 900\n when 'CD'\n return 400\n when 'XC'\n return 90\n when 'XL'\n return 40\n when 'IX'\n return 9\n when 'IV'\n return 4\n else\n return false\n end\nend", "def romanize(number)\n raise ArgumentError, 'can not encode zero' if number == 0\n raise ArgumentError, 'can not encode negative number' if number < 0\n\n # String to handle the roman output.\n roman = \"\"\n\n # Hash to handle to roman numbers next to Integers.\n roman_numbers = {\n 1000 => \"M\",\n 900 => \"CM\",\n 500 => \"D\",\n 400 => \"CD\",\n 100 => \"C\",\n 90 => \"XC\",\n 50 => \"L\",\n 40 => \"XL\",\n 10 => \"X\",\n 9 => \"IX\",\n 5 => \"V\",\n 4 => \"IV\",\n 1 => \"I\",\n }\n\n roman_numbers.each do |value, letter|\n\n # Inserts current roman letter x times.\n roman << letter*(number / value)\n\n # Decreases the input_number via modulo value.\n # Modulo divides input_number/value evenly, the rest of the numbers that can't be evenly divided gets pushed into input_number.\n number = number % value\n end\n\n # Returns roman version.\n return roman\n\nend", "def roman_to_integer roman\r\n digit_vals = {'i' => 1,\r\n 'v' => 5,\r\n 'x' => 10,\r\n 'l' => 50,\r\n 'c' => 100,\r\n 'd' => 500,\r\n 'm' => 1000}\r\n total = 0\r\n prev = 0\r\n roman.reverse.each_char do |c_or_C|\r\n c = c_or_C.downcase\r\n val = digit_vals[c]\r\n if !val\r\n puts 'this is not a valid roman numeral!'\r\n return\r\n end\r\n if val < prev\r\n val *= -1\r\n else\r\n prev = val\r\n end\r\n\r\n total += val\r\n end\r\n\r\n total\r\nend", "def convert_to_roman_numeral(input_array)\n\tnumber_map = {1 => 'I', \n\t\t2 => 'II', \n\t\t3 => 'III', \n\t\t4 => 'IV', \n\t\t5 => 'V', \n\t\t6 => 'VI', \n\t\t7 => 'VII', \n\t\t8 => 'VIII', \n\t\t9 => 'IX', \n\t\t10 => 'X'}\n\n\tif input_array != nil && input_array.length > 0 \n\t\ti = 0\n\t\twhile i < input_array.length do \n\t\t\tif input_array[i].to_i > 0 && input_array[i].to_i < 11 \n\t\t\t\tputs input_array[i].to_s + \" maps to: \" + number_map[input_array[i].to_i]\n\t\t\tend\t\n\t\t\ti += 1\n\t\tend\n\tend\n\tputs \"True or false: number_map[9] == 'IX' ?\"\n\tputs number_map[9] == 'IX'\nend", "def roman_to_integer roman\n roman_lookup = {'i' => 1,\n 'v' => 5,\n 'x' => 10,\n 'l' => 50,\n 'c' => 100,\n 'd' => 500,\n 'm' => 1000}\n\n # Initialize total integer value (updates as we process the string)\n total = 0\n\n # Prev is used to track the numeral character one over\n prev = 0\n \n # Look at the string in reverse order, we will add to a running total\n # for each numeral character.\n roman.reverse.each_char do |character|\n # Look up the current numeral character in the roman_lookup table\n numeral = roman_lookup[character]\n \n # If not found in roman_lookup, it's invalid,\n # break and tell the user in loop.\n if !numeral\n puts 'This is not a valid roman numeral!'\n break\n end\n\n # If the current character is less than the one to its left\n # Subtract one from numeral\n if numeral < prev\n numeral *= -1\n else # Otherwise, equal\n prev = numeral\n end\n\n # Add to running total\n total += numeral\n end\n\n total\nend", "def roman (x)\n num = x.to_s.scan(/\\d/).map {|i| i.to_i}\n num = num.reverse\n \n ones = num[0]\n tens = num[1]\n hundreds = num [2]\n thousands = num [3]\n roman_num = \"\"\n \n #create result for ones digit\n if ones >= 5 \n result = (\"I\" * (ones-5)) + \"V\"\n roman_num += result\n else\n result = \"I\" * ones\n roman_num += result\n end\n \n #create result for tens digit\n if tens != nil #skips this loop if number is not >= 10\n if tens >= 5\n result = (\"X\" * (tens-5)) + \"L\"\n roman_num += result\n else\n result = \"X\" * tens\n roman_num += result\n end\n end\n \n #create result for hundreds digit\n if hundreds != nil #skips this loop if number is not >= 100\n if hundreds >= 5\n result = (\"C\" * (hundreds-5)) + \"D\"\n roman_num += result\n else\n result = \"C\" * hundreds\n roman_num += result\n end\n end\n \n #create result for thousands digit\n if thousands != nil #skips this loop if number is not >= 1000\n if thousands < 5\n result = \"M\" * thousands\n roman_num += result\n end\n end\n \n puts roman_num.reverse\nend", "def verify\n\t\t@ascii_string.each do |value|\n\t\t\traise ArgumentError, \"#{value} is not an ASCII representation of number character with in the range 0-9\" unless NILTO9.key?(value) \n\t\tend\n\t\tself\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TEST OUTPUT OF THE EXPRESSION PASSED TO THE execute_expression IF VALID INPUT(ROMAN LETTERS) GIVEN IT SHOULD RETURN VALID OUTPUT(ROMAN LETTERS) ELSE RAISE EXCEPTION
def test_execute_expression assert_equal("L", RomanMathmaticalOperation.new("XL","+","X").execute_expression) assert_equal("XCIX", RomanMathmaticalOperation.new("C","-","I").execute_expression) assert_equal("X", RomanMathmaticalOperation.new("C","/","X").execute_expression) assert_equal("C", RomanMathmaticalOperation.new("X","*","X").execute_expression) exception = assert_raise("RomanMathmaticalOperationError") {RomanMathmaticalOperation.new("Y","*","X").execute_expression} assert_equal("Not valid input", exception.message) exception = assert_raise("RomanMathmaticalOperationError") {RomanMathmaticalOperation.new("X","*",0).execute_expression} assert_equal("Not valid input", exception.message) exception = assert_raise("RomanMathmaticalOperationError") {RomanMathmaticalOperation.new("X", "+").execute_expression} assert_equal("This X or is not valid", exception.message) exception = assert_raise("RomanMathmaticalOperationError") {RomanMathmaticalOperation.new("X", "%","V").execute_expression} assert_equal("Operator missmatch", exception.message) end
[ "def test_empty_str(empty_str, exp_result)\n actual_result = Validator.string_of_nums?(empty_str)\n if(actual_result == exp_result)\n puts(\"PASS\")\n else\n puts(\"FAIL\")\n end\n return actual_result\nend", "def test_valid_input\n assert_equal(nil, RomanMathmaticalOperation.new(\"X\", \"+\",\"V\").send(:valid_input))\n exception = assert_raise(\"RomanMathmaticalOperationError\") {RomanMathmaticalOperation.new(\"X\", \"+\",nil).send(:valid_input)}\n assert_equal(\"This X or is not valid\", exception.message)\n exception = assert_raise(\"RomanMathmaticalOperationError\") {RomanMathmaticalOperation.new(\"X\", \"%\",\"V\").send(:valid_input)}\n assert_equal(\"Operator missmatch\", exception.message)\n end", "def test_handle_input_valid\r\n input = '1 1 +'\r\n assert_output(\"2\\n\") {@arg_checker.handle_input(input)}\r\n end", "def test_zero_int(zero_int, exp_result)\n actual_result = Validator.string_of_nums?(zero_int)\n if(actual_result == exp_result)\n puts(\"PASS\")\n else\n puts(\"FAIL\")\n end\n return actual_result\nend", "def operation_should_evaluate\n result = check_eval_syntax operation\n errors.add(:operation, \"should be proper ruby code. #{result[:exception]}\") unless result[:exception].blank? || result[:result] == 0\n end", "def test_name_generator_with_invalid_input\nresult = name_generator(\"89&6\\n 5.,?<\")\nassert_equal(\"Inavalid ID. Please enter new ID with only lower case letters.\", result)\nend", "def test_7_rejects_only_alphnumeric\n result = is_alphanumeric?(\"1Abjilsa2\")\n refute(result, \"1Abjilsa2 has no alphanumeric, should be valid\")\n end", "def test_valid_eval\n assert_equal [11, 'valid'], @eval.evaluate([5, 6, '+'])\n end", "def test_do_math_middle_keyword\r\n input = [\"1\", \"PRINT\", \"+\"]\r\n val = 0\r\n assert_output(\"Line 0: Could not evaluate expression\\n\") {val = @arg_checker.do_math(input)}\r\n assert_equal [], val\r\n end", "def test_13_return_good_job_prompt_if_letter_in_word\n $word = \"test\"\n letter = \"e\"\n results = letter_test(letter)\n assert_equal(\"Good job - that letter was in the word. Please guess again!\", results)\n end", "def test_do_more_math_invalid\r\n input = \"a\"\r\n val=0\r\n assert_output(\"\") {val = @arg_checker.do_more_math(input)}\r\n assert_equal [1, \"a\", 0], @arg_checker.error_data\r\n assert_equal false, val\r\n assert_equal [], @arg_checker.stack\r\n end", "def test_let_syntax_err_check_value_missing\r\n assert_output(/Value missing/){ let_syntax_err_check 'a'.split, 1}\r\n end", "def test_check_capital_non_alpha\r\n assert_equal true, @g.check_capital('?!.(3')\r\n end", "def test_error_5\n val = @rpn.print_line \"LET - -\"\n assert_equal val, [5, \"Line 0: Could not evaluate expression\"]\n end", "def eval(input)\n return false\n end", "def check_expression\n count_ops\n fail \"EmptyError\" if @exp.empty?\n fail \"OpsAmountError\" if @num - @ops != 1 || @num + @ops < 3\n end", "def complete_expression?(str); end", "def validate\n # @expression && !@expression.blank?\n if !@expression || @expression.blank?\n return\n elsif !Calculator.valid?(@expression)\n @expression = nil\n @mode = :invalid\n end\n end", "def test_8_return_false_if_letter_not_in_word\r\n $word = \"test\"\r\n letter = \"d\"\r\n results = letter_test(letter)\r\n assert_equal(false, results)\r\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructor == Parameters: api_key The api_key of the partner (which may be found in the api_keys section of the console) id The account id of the partner (which may be found in the settings page of the console)
def initialize(api_key = Sift.api_key, id = Sift.account_id) @api_key = api_key @id = id end
[ "def initialize(api_key = Sift.api_key, id = Sift.account_id)\n raise(\"api_key must be a non-empty string\") unless valid_string?(api_key)\n raise(\"partner must be a non-empty string\") unless valid_string?(id)\n @api_key = api_key\n @id = id\n end", "def initialize(api_key, account_id, api_version = 'v1')\n @api_key = api_key\n @account_id = account_id\n @api_ver = api_version\n instance_variables.each do |variable|\n raise ArgumentError, \"#{variable} should not be nil or blank\" if instance_variable_get(variable.to_sym).to_s == \"\"\n end\n end", "def api_key; \"055a1100-a84d-4064-84d7-bce46f7b80c8\"; end", "def initialize(api_key, api_secret)\n @api_key = api_key\n @api_secret = api_secret\n end", "def initialize(api_key)\n @client = Juicer::Client.new(api_key)\n end", "def set_api_key(api_key)\n self.api_key = api_key\n end", "def initialize(api_key, secret_key)\n @api_key = api_key\n @secret_key = secret_key\n end", "def initialize(api_key)\n @api_key = api_key\n @data_api_url = 'https://www.altadata.io/data/api/'\n @subscription_api_url = \"https://www.altadata.io/subscription/api/subscriptions?api_key=#{@api_key}\"\n end", "def initialize(api_key, shared_secret)\n @api_key = api_key\n @shared_secret = shared_secret\n end", "def initialize(api_key)\n @api_key = api_key\n @client = Hurley::Client.new 'http://api.rottentomatoes.com/api/public/v1.0'\n self\n end", "def initialize(driver, api)\n @driver = driver\n @api = api\n @module = AdWords::V13::AccountService\n end", "def initialize(partner_id, partner_secret, options = nil)\n @partner_id = partner_id\n @partner_secret = partner_secret.strip\n\n if options.is_a?(::Hash)\n @api_url = options[:api_url] || API_URL\n end\n\n unless @api_url\n @api_url = API_URL\n end\n end", "def initialize(apiKey = '***REMOVED***', pid = '***REMOVED***')\n @options = {:apiKey => apiKey, :PID => pid}\n @debug = false\n end", "def initialize(api_obj)\n @api_obj = api_obj\n end", "def initialize(api_key = Payable.api_key, path = Payable.current_rest_api_path, timeout = API_TIMEOUT, company_id = Payable.company_id)\n raise(\"api_key must be a non-empty string\") if !api_key.is_a?(String) || api_key.empty?\n raise(\"path must be a non-empty string\") if !path.is_a?(String) || path.empty?\n @api_key = api_key\n @path = path\n @timeout = timeout\n @company_id = company_id\n end", "def initialize\n\t \n\t @apikey ='88b669eb-3431-4893-b75d-2e7e2c9f853e' # api Key value.. You should put your own api key.. Don't misuse it..\n @url = 'https://api.idolondemand.com/1/api/sync/' # partial url.. This is for synchronous .. \n\t\t\t\t\t\t\t# for one call I have used asyn and there, I have used the complete url \n\t @version = '/v1' # version number of api\n end", "def initialize(client, id, **options)\n super(client, { id: id }, options)\n end", "def initialize(api_key = nil)\n @api_key = api_key || ENV['KLOUT_API_KEY'] || raise(ArgumentError)\n end", "def initialize(api_key)\n @sg = SendGrid::API.new(api_key: api_key)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new merchant account under the given partner. == Parameters: site_url the url of the merchant site site_email an email address for the merchant analyst_email an email address which will be used to log in at the Sift Console password password (at least 10 chars) to be used to sign into the Console When successful, returns a including the new account id and credentials. When an error occurs, returns nil.
def new_account(site_url, site_email, analyst_email, password) reqBody = {:site_url => site_url, :site_email => site_email, :analyst_email => analyst_email, :password => password} begin http_post(accounts_url(), reqBody) rescue Exception => e puts e.message puts e.backtrace.inspect end end
[ "def new_account(site_url, site_email, analyst_email, password)\n\n raise(\"site url must be a non-empty string\") unless valid_string?(site_url)\n raise(\"site email must be a non-empty string\") unless valid_string?(site_email)\n raise(\"analyst email must be a non-empty string\") unless valid_string?(analyst_email)\n raise(\"password must be a non-empty string\") unless valid_string?(password)\n\n reqBody = {:site_url => site_url, :site_email => site_email,\n :analyst_email => analyst_email, :password => password}\n begin\n http_post(accounts_url(), reqBody)\n rescue Exception => e\n puts e.message\n puts e.backtrace.inspect\n end\n\n end", "def create_merchant email_address, merchant, bank_account_uri=nil, name=nil, meta={}\n account = Account.new(\n :uri => self.accounts_uri,\n :email_address => email_address,\n :merchant => merchant,\n :bank_account_uri => bank_account_uri,\n :name => name,\n :meta => meta,\n )\n account.save\n end", "def add_new_account(partner)\n fill_company_info(partner.company_info)\n fill_partner_admin_info(partner.partner_info, partner.admin_info)\n fill_account_detail(partner.account_detail)\n fill_billing_info(partner)\n\n # define master plan subscription period\n fill_subscription_period(partner.subscription_period)\n\n if partner.has_initial_purchase\n fill_initial_purchase(partner)\n set_pre_sub_total(partner)\n next_btn.click\n if !flash_errors[0].nil?\n Log.info \"Error when adding a new partner: \" + flash_errors[0].text\n return\n end\n wait_time = CONFIGS['global']['max_wait_time']\n wait_until(wait_time) do\n back_btn.visible? # wait for fill credit card info\n end\n if partner.net_term_payment\n net_term_payment_input.click\n if alert_present?\n partner.billing_info.alert = alert_text\n alert_accept\n end\n else\n cc_payment_input.click\n fill_credit_card_info(partner.credit_card)\n end\n set_order_summary(partner)\n if partner.credit_card.cvv2 == 'true'\n cvv2_what_is_this.click\n cvv2_help.text.should == 'What is the CVV2 code?'\n cvv2_close.click\n end\n\n wait_until { !locate(:css, \"div#cc-details input#submit_button\").nil? && create_partner_btn.visible? && create_partner_btn['disabled'] != 'true' }\n create_partner_btn.click\n wait_until { create_partner_btn['disabled'] == 'true' }\n wait_until { create_partner_btn['disabled'] != 'true' }\n else\n include_initial_purchase_cb.uncheck\n set_pre_sub_total(partner)\n next_btn.click\n end\n end", "def create_wepay_account\n\t\tif self.has_wepay_access_token? && !self.has_wepay_account?\n\t\t\tparams = {:name => self.farm, :description => \"Farm selling \" + self.produce }\n\t\t\tresponse = Wefarm::Application::WEPAY.call(\"/account/create\", self.wepay_access_token, params)\n\t\t\t\n\t\t\tif response[\"account_id\"]\n\t\t\t\tself.wepay_account_id = response[\"account_id\"]\n\t\t\t\treturn self.save\n\t\t\telse\n\t\t\t raise \"Error - \" + response[\"error_description\"]\n\t\t\tend\n\t \n\t\tend\t\t\n\t\traise \"Error - cannot create WePay account\"\n\tend", "def create_wepay_account\n \t\tif self.has_wepay_access_token? && !self.has_wepay_account?\n \t\tparams = { :name => self.company_name, :description => self.company_description }\t\t\t\n \t\tresponse = Shopketti::Application::WEPAY.call(\"/account/create\", self.wepay_access_token, params)\n\n \tif response[\"account_id\"]\n \tself.wepay_account_id = response[\"account_id\"]\n \treturn self.save\n \telse\n \traise \"Error - \" + response[\"error_description\"]\n \tend\n\n \tend\t\t\n \traise \"Error - cannot create WePay account\"\n end", "def create_wepay_account\n raise 'Error - cannot create WePay account' unless wepay_access_token? && !wepay_account?\n params = { name: farm, description: 'Farm selling ' + produce }\n response = Wefarm::Application::WEPAY.call('/account/create', wepay_access_token, params)\n\n raise 'Error - ' + response['error_description'] unless response['account_id']\n self.wepay_account_id = response['account_id']\n save\n end", "def create_wepay_account\n # if we don't have an access_token for this user, then we cannot make this call\n if self.has_wepay_account? then return false end\n # make the /account/create call\n response = WEPAY.call(\"/account/create\", self.wepay_access_token, {\n name: self.campaign.name,\n description: self.campaign.description,\n type: self.campaign.account_type,\n country: self.country,\n currencies: [ self.currency ],\n })\n if response['error'].present?\n raise response['error_description']\n end\n self.wepay_account_id = response['account_id']\n self.save\n end", "def create_wepay_account\n if self.has_wepay_access_token? && !self.has_wepay_account?\n params = { :name => self.name, :description => \"Member of the Trade Art Collective\"}\n response = TradeArtCollective::Application::WEPAY.call(\"/account/create\", self.wepay_access_token, params)\n\n if response[\"account_id\"]\n self.wepay_account_id = response[\"account_id\"]\n return self.save\n else\n raise \"Error - \" + response[\"error_description\"]\n end\n\n end\n raise \"Error - cannot create WePay account\"\n end", "def create_merchant email_address, merchant, bank_account_uri=nil, name=nil, meta={}\n account_attributes = {\n :uri => self.accounts_uri,\n :email_address => email_address,\n :bank_account_uri => bank_account_uri,\n :name => name,\n :meta => meta,\n }\n\n if merchant.respond_to? :keys\n account_attributes[:merchant] = merchant\n else\n account_attributes[:merchant_uri] = merchant\n end\n\n account = Account.new account_attributes\n account.save\n end", "def create_wepay_account\n\t if self.has_wepay_access_token? && !self.has_wepay_account?\n\t params = { :name => self.name, :description => \"Selling goods on Tradies \" }\t\t\t\n\t response = WEPAY.call(\"/account/create\", self.wepay_access_token, params)\n\n\t if response[\"account_id\"]\n\t \tputs \"need to get account_id\"\n\t \t\t# puts response['account_id']\n\t # self.wepay_account_id = response[\"account_id\"]\n\t return self.update_columns(wepay_account_id: response['account_id'])\n\t else\n\t raise \"Error - \" + response[\"error_description\"]\n\t end\n\n\t end\t\t\n\t raise \"Error - cannot create WePay account\"\n\tend", "def create_merchant *args\n options = args.last.is_a?(Hash) ? args.pop : {}\n email_address = args[0] || options.fetch(:email_address) { nil }\n merchant = args[1] || options.fetch(:merchant) { nil }\n bank_account_uri = args[2] || options.fetch(:bank_account_uri) { nil }\n name = args[3] || options.fetch(:name) { nil }\n meta = args[4] || options.fetch(:meta) { nil }\n\n account_attributes = {\n :uri => self.accounts_uri,\n :email_address => email_address,\n :bank_account_uri => bank_account_uri,\n :name => name,\n :meta => meta,\n }\n\n if merchant.respond_to? :keys\n account_attributes[:merchant] = merchant\n else\n account_attributes[:merchant_uri] = merchant\n end\n\n account = Account.new account_attributes\n account.save\n end", "def create\n @backend_partner_site = Backend::PartnerSite.new(params[:backend_partner_site])\n\n unless @backend_partner_site.nil?\n @backend_partner_site.referer.strip! unless @backend_partner_site.referer.nil?\n @backend_partner_site.r.strip! unless @backend_partner_site.r.nil?\n end\n \n respond_to do |format|\n if @backend_partner_site.save\n format.html { redirect_to @backend_partner_site, notice: 'Partner site was successfully created.' }\n format.json { render json: @backend_partner_site, status: :created, location: @backend_partner_site }\n else\n format.html { render action: \"new\" }\n format.json { render json: @backend_partner_site.errors, status: :unprocessable_entity }\n end\n end\n end", "def create_merchant *args\n warn_on_positional args\n\n options = args.last.is_a?(Hash) ? args.pop : {}\n email_address = args[0] || options.fetch(:email_address) { nil }\n merchant = args[1] || options.fetch(:merchant) { nil }\n bank_account_uri = args[2] || options.fetch(:bank_account_uri) { nil }\n name = args[3] || options.fetch(:name) { nil }\n meta = args[4] || options.fetch(:meta) { nil }\n bank_account = args[5] || options.fetch(:bank_account) { nil }\n\n account_attributes = {\n :uri => self.accounts_uri,\n :email_address => email_address,\n :bank_account_uri => bank_account_uri,\n :name => name,\n :meta => meta,\n :bank_account => bank_account\n }\n\n if merchant.respond_to? :keys\n account_attributes[:merchant] = merchant\n else\n account_attributes[:merchant_uri] = merchant\n end\n\n account = Account.new account_attributes\n account.save\n end", "def create_account\n set_user\n set_payer\n set_user_sport\n save_account\n end", "def create_account\n if params[:edress].blank?\n render(:json => {:errors => \"Please specify non-empty email\".t});\n return\n end\n if !@account_setting.current_monetary_processor_account.nil?\n render(:json => {:errors => \"You already has an attached account. Delete it first if you want to attach another one.\".t});\n return\n end\n\n @account = PaypalAccount.new(:account_identifier => params[:edress], :account_setting_id => @account_setting.id,\n :monetary_processor => MonetaryProcessor.paypal)\n begin\n @account.save!\n\n render :json => {:success => true}\n rescue Exception => e\n if e.is_a?(ActiveRecord::RecordInvalid) && @account.errors.on(:email)\n render :json => {:errors => \"The email address you've entered appears to be invalid. Maybe you've entered some non-latinic symbols?\".t}\n else\n just_notify(e)\n render :json => {:errors => \"Sorry, we encountered a problem with your request. {{errors}}\" / e.message}\n end\n end\n end", "def create_account(lead)\n Account.create({\n company_id: lead.company_id,\n user_id: lead.user_id\n })\n end", "def create\n params[:partner_user][:crypted_password] = convert_to_md5(params[:partner_user][:crypted_password]) unless params[:partner_user][:crypted_password].blank?\n @user = @partner_account.users.new(partner_user_params)\n raise CustomerlobbyErrors::UnprocessableEntityError.new @user.errors.full_messages unless @user.save\n end", "def create_buyer email_address, card_uri, name=nil, meta={}\n account = Account.new(\n :uri => self.accounts_uri,\n :email_address => email_address,\n :card_uri => card_uri,\n :name => name,\n :meta => meta,\n )\n account.save\n end", "def create_account(options = {})\n requires!(options, :username)\n \n\t data = get_xml(:url => \"createacct\", :params => options)\n\t check_for_cpanel_errors_on(data)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the configuration which controls http notifications for all merchant accounts under this partner. == Parameters cfg A Hash, with keys :http_notification_url and :http_notification_threshold The value of the notification_url will be a url containing the string '%s' exactly once. This allows the url to be used as a template, into which a merchant account id can be substituted. The notification threshold should be a floating point number between 0.0 and 1.0
def update_notification_config(cfg) http_put(notification_config_url(), cfg) end
[ "def update_notification_config(cfg = nil)\n\n raise(\"configuration must be a hash\") unless cfg.is_a? Hash\n\n http_put(notification_config_url(), cfg)\n end", "def notify_config\n { url: new_resource.notify_url }\n end", "def action_enable_web_push_rss_with_http_info(campaign_hash, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: WebpushApi.action_enable_web_push_rss ...'\n end\n # verify the required parameter 'campaign_hash' is set\n if @api_client.config.client_side_validation && campaign_hash.nil?\n fail ArgumentError, \"Missing the required parameter 'campaign_hash' when calling WebpushApi.action_enable_web_push_rss\"\n end\n pattern = Regexp.new(/[a-zA-Z0-9_-]*/)\n if @api_client.config.client_side_validation && campaign_hash !~ pattern\n fail ArgumentError, \"invalid value for 'campaign_hash' when calling WebpushApi.action_enable_web_push_rss, must conform to the pattern #{pattern}.\"\n end\n\n # resource path\n local_var_path = '/campaigns/webpush/rss/{campaign_hash}/actions/enable'.sub('{' + 'campaign_hash' + '}', CGI.escape(campaign_hash.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body]\n\n # return_type\n return_type = opts[:debug_return_type] || 'AcceptedResponse'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['Apikey']\n\n new_options = opts.merge(\n :operation => :\"WebpushApi.action_enable_web_push_rss\",\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: WebpushApi#action_enable_web_push_rss\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def update_notifications_with_http_info(factory_id, cloud_notification_settings_body, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: FlipApi.update_notifications ...\"\n end\n # verify the required parameter 'factory_id' is set\n if @api_client.config.client_side_validation && factory_id.nil?\n fail ArgumentError, \"Missing the required parameter 'factory_id' when calling FlipApi.update_notifications\"\n end\n # verify the required parameter 'cloud_notification_settings_body' is set\n if @api_client.config.client_side_validation && cloud_notification_settings_body.nil?\n fail ArgumentError, \"Missing the required parameter 'cloud_notification_settings_body' when calling FlipApi.update_notifications\"\n end\n # resource path\n local_var_path = \"/notifications.json\"\n\n # query parameters\n query_params = {}\n query_params[:'factory_id'] = factory_id\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 # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(cloud_notification_settings_body)\n auth_names = ['api_key']\n data, status_code, headers = @api_client.call_api(:PUT, 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 => 'CloudNotificationSettings')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: FlipApi#update_notifications\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def update_notifications(bucket_name, notifications)\n S3.client.put_bucket_notification_configuration({\n bucket: bucket_name,\n notification_configuration: {\n topic_configurations: notifications.values.select { |n| n.type == \"sns\" }.map(&:to_aws),\n queue_configurations: notifications.values.select { |n| n.type == \"sqs\" }.map(&:to_aws),\n lambda_function_configurations: notifications.values.select { |n| n.type == \"lambda\" }.map(&:to_aws)\n }\n })\n end", "def updateNotifications\r\n\t\tdataHash = {\r\n\t\t\tuser_id: params[:user].id,\r\n experience_p_status: params[:experience_p_status],\r\n experience_status: params[:experience_status],\r\n\t\t\tfeelike_status: params[:feelike_status],\r\n\t\t\tfollows_status: params[:follows_status],\r\n comment_status: 0\r\n\t\t}\r\n UsersSettings.byUser(params[:user].id).first.updateNotifications(dataHash)\r\n self.default_response\r\n\tend", "def update_config\n unless !@sender.adm.avlconn\n @sender.adm.reload_file\n end\n end", "def update_telemetry_configuration\n raise IncompleteResource, 'Please retrieve the Logical Interconnect before trying to update' unless @data['telemetryConfiguration']\n update_options = {\n 'If-Match' => @data['telemetryConfiguration'].delete('eTag'),\n 'body' => @data['telemetryConfiguration']\n }\n response = @client.rest_put(@data['telemetryConfiguration']['uri'], update_options, @api_version)\n body = @client.response_handler(response)\n set_all(body)\n end", "def put_notification_configuration(auto_scaling_group_name, notification_types, topic_arn)\n options = {}\n options.merge!(AWS.indexed_param('NotificationTypes.member.%d', [*notification_types]))\n request({\n 'Action' => 'PutNotificationConfiguration',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n 'TopicARN' => topic_arn,\n :parser => Fog::Parsers::AWS::AutoScaling::PutNotificationConfiguration.new\n }.merge!(options))\n end", "def merge_netconf(config)\n @client.set(values: config, mode: :merge)\n end", "def update(authorization, notification_url)\n url = test? ? STATUS_TEST_URL : STATUS_LIVE_URL\n parameters = [ authorization, account, notification_url ]\n data = PostData.new\n data[:requestparams] = parameters.join('|')\n \n response = ssl_get(\"#{url}?#{data.to_post_data}\")\n end", "def update_tls_config_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: TlsConfigurationsApi.update_tls_config ...'\n end\n # unbox the parameters from the hash\n tls_configuration_id = opts[:'tls_configuration_id']\n # verify the required parameter 'tls_configuration_id' is set\n if @api_client.config.client_side_validation && tls_configuration_id.nil?\n fail ArgumentError, \"Missing the required parameter 'tls_configuration_id' when calling TlsConfigurationsApi.update_tls_config\"\n end\n # resource path\n local_var_path = '/tls/configurations/{tls_configuration_id}'.sub('{' + 'tls_configuration_id' + '}', CGI.escape(tls_configuration_id.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/vnd.api+json'])\n # HTTP header 'Content-Type'\n content_type = @api_client.select_header_content_type(['application/vnd.api+json'])\n if !content_type.nil?\n header_params['Content-Type'] = content_type\n end\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'tls_configuration'])\n\n # return_type\n return_type = opts[:debug_return_type] || 'TlsConfigurationResponse'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || ['token']\n\n new_options = opts.merge(\n :operation => :\"TlsConfigurationsApi.update_tls_config\",\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:PATCH, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: TlsConfigurationsApi#update_tls_config\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end", "def update(authorization, notification_url)\n url = test? ? STATUS_TEST_URL : STATUS_LIVE_URL\n parameters = [ authorization, account, notification_url ]\n data = ActiveUtils::PostData.new\n data[:requestparams] = parameters.join('|')\n\n response = ssl_get(\"#{url}?#{data.to_post_data}\")\n end", "def put_notification_configuration(auto_scaling_group_name, notification_types, topic_arn)\n params = AWS.indexed_param('NotificationTypes.member.%d', [*notification_types])\n request({\n 'Action' => 'PutNotificationConfiguration',\n 'AutoScalingGroupName' => auto_scaling_group_name,\n 'TopicARN' => topic_arn,\n :parser => Fog::Parsers::AWS::AutoScaling::PutNotificationConfiguration.new\n }.merge!(params))\n end", "def apply_grip_config(config)\n if !config.is_a?(Array)\n config = [config]\n end\n config.each do |entry|\n if !entry.key?('control_uri')\n next\n end\n client = PubControlClient.new(entry['control_uri'])\n if entry.key?('control_iss')\n client.set_auth_jwt({'iss' => entry['control_iss']}, entry['key'])\n end\n super_add_client(client)\n end\n end", "def update_client_webhook_setting\n @client_webhook_setting.url = @url\n @client_webhook_setting.last_acted_by = @admin_id\n @client_webhook_setting.event_result_types = 0\n @client_webhook_setting.event_sources = 0\n\n @event_result_types.each do |event_result_type|\n @client_webhook_setting.send(\"set_\" + event_result_type)\n end\n\n @event_sources.each do |event_source|\n @client_webhook_setting.send(\"set_\" + event_source)\n end\n @client_webhook_setting.source = GlobalConstant::AdminActivityChangeLogger.web_source\n @client_webhook_setting.save! if @client_webhook_setting.changed?\n\n end", "def apply_config(config)\n if !config.is_a?(Array)\n config = [config]\n end\n config.each do |entry|\n pub = PubControlClient.new(entry['uri'])\n if entry.key?('iss')\n pub.set_auth_jwt({'iss' => entry['iss']}, entry['key'])\n end\n @clients.push(pub)\n end\n end", "def update_configuration(config)\n fsi = Vcloud::Core::Fog::ServiceInterface.new\n fsi.post_configure_edge_gateway_services(id, config)\n end", "def update_config(options = {})\n @logger.debug(\"config changed: #{options.inspect}\")\n @urlmapping = options[:urlmapping] || []\n @filters = options[:filters] || []\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
List of games where current_user is either black or white player
def my_games return unless user_signed_in? @my_games = Game.where('white_player_id = ? or black_player_id = ?', current_user.id, current_user.id).where(winning_player_id: nil).order(:created_at) end
[ "def white_players\n Player.joins(:player_games).where(player_games: { game_id: self.id, team_color: PlayerGame::WHITE_TEAM })\n end", "def games\n\t\tChessGame.where(\"black_player_id = ? OR white_player_id = ?\", self.id , self.id)\n\tend", "def active_games_by_user db, username\n sql = %q[SELECT * FROM games WHERE player1 = $1 OR player2 = $1 AND game_winner IS NULL]\n result = db.exec(sql, [username])\n result.entries\n end", "def tied_games\n Game.includes(:scores)\n .where(blue_team_id: self.id).or(Game.includes(:scores).where(white_team_id: self.id))\n .select do |game|\n (game.blue_team_id == self.id || game.white_team_id == self.id) &&\n (game.blue_goals == game.white_goals)\n end\n end", "def games(filters = {})\n filtered_games = filters[:game_state] ? Game.where(state: filters[:game_state]) : Game.all\n filtered_games.to_a.each_with_object([]) do |game, array|\n game.players.each do |player|\n if player.user == self &&\n (filters[:role].nil? || player.role == filters[:role]) && \n (filters[:host].nil? || player.host == filters[:host])\n array << game \n break\n end\n end\n end\n end", "def past_games_by_user db, username\n sql = %q[SELECT * FROM games WHERE player1 = $1 OR player2 = $1 AND game_winner IS NOT NULL]\n result = db.exec(sql, [username])\n result.entries\n end", "def blue_players\n Player.joins(:player_games).where(player_games: { game_id: self.id, team_color: PlayerGame::BLUE_TEAM })\n end", "def search_query(params)\n user = User.find_by(email: params)\n Game.where(white_player_id: user.id, black_player_id: nil).order(:created_at)\n end", "def color_of(current_user)\n return :white if white_player == current_user\n return :black if black_player == current_user\n nil\n end", "def player?(current_user)\n black_player == current_user or white_player == current_user\n end", "def opponent_of(current_user)\n return black_player if white_player == current_user\n return white_player if black_player == current_user\n nil\n end", "def team_players\n black_team_players = []\n red_team_players = []\n array_of_teams = []\n self.gameplayers.each do |game|\n if game.team == \"black\"\n black_team_players << game.user\n elsif game.team == \"red\"\n red_team_players << game.user\n end\n end\n array_of_teams << black_team_players\n array_of_teams << red_team_players\n return array_of_teams\n end", "def won_games\n Game.includes(:scores)\n .where(blue_team_id: self.id).or(Game.includes(:scores).where(white_team_id: self.id))\n .select do |game|\n (game.blue_team_id == self.id && game.blue_goals > game.white_goals) ||\n (game.white_team_id == self.id && game.white_goals > game.blue_goals)\n end\n end", "def in_progress_games(other_player)\n games.where(\n 'complete = ? AND (challenger_id = ? OR challenged_id = ?)',\n false,\n other_player.id,\n other_player.id\n )\n end", "def playing_users\n user_state.select { |user, state| state == :playing }.keys\n end", "def common_games(user)\n (self.games & user.games).map{|game| game.name}\n end", "def index\n # Using .includes(:board_game) reduces SQL to a single query instead of a separate query per instance of wished_games\n @wished_games = current_user.wished_games.includes(:board_game)\n end", "def players_near_me\n users = []\n\n my_courts.each do |court|\n users_near_court(court).each do |user|\n users << user unless user == current_user\n end\n end\n\n return users.uniq\n end", "def get_unplayed_games()\n return Game.where(\"winner is ?\", nil).order(:created_at)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find unstarted games where the white_player_id matches the searched email address
def search_query(params) user = User.find_by(email: params) Game.where(white_player_id: user.id, black_player_id: nil).order(:created_at) end
[ "def white_players\n Player.joins(:player_games).where(player_games: { game_id: self.id, team_color: PlayerGame::WHITE_TEAM })\n end", "def my_games\n return unless user_signed_in?\n @my_games = Game.where('white_player_id = ? or black_player_id = ?', current_user.id, current_user.id).where(winning_player_id: nil).order(:created_at)\n end", "def in_progress_games(other_player)\n games.where(\n 'complete = ? AND (challenger_id = ? OR challenged_id = ?)',\n false,\n other_player.id,\n other_player.id\n )\n end", "def get_unplayed_games()\n return Game.where(\"winner is ?\", nil).order(:created_at)\n end", "def find_dangling_cpu_players\n players = Player::CPU\n .joins(:matches)\n .where(matches: {\n id: Round.created_or_playing.with_cpu_players.pluck(:match_id),\n winner_id: nil\n })\n .where.not(id: cpu_players.keys)\n players.each(&method(:activate_player))\n\n set_next_player_check\n end", "def games\n\t\tChessGame.where(\"black_player_id = ? OR white_player_id = ?\", self.id , self.id)\n\tend", "def active_games_by_user db, username\n sql = %q[SELECT * FROM games WHERE player1 = $1 OR player2 = $1 AND game_winner IS NULL]\n result = db.exec(sql, [username])\n result.entries\n end", "def games(filters = {})\n filtered_games = filters[:game_state] ? Game.where(state: filters[:game_state]) : Game.all\n filtered_games.to_a.each_with_object([]) do |game, array|\n game.players.each do |player|\n if player.user == self &&\n (filters[:role].nil? || player.role == filters[:role]) && \n (filters[:host].nil? || player.host == filters[:host])\n array << game \n break\n end\n end\n end\n end", "def select_players\n players = @league.find_all_players do |pl|\n pl.status == \"game_waiting\" &&\n game_name?(pl.game_name) &&\n pl.sente == nil &&\n pl.rated? # Only players who have player ID can participate in Floodgate (rating match)\n end\n return players\n end", "def past_games_by_user db, username\n sql = %q[SELECT * FROM games WHERE player1 = $1 OR player2 = $1 AND game_winner IS NOT NULL]\n result = db.exec(sql, [username])\n result.entries\n end", "def still_to_play\n return self.game_players.where.not(\n id: self.current_hand.hand_players.where.not(bid: nil).select(:game_player_id)\n )\n end", "def tied_games\n Game.includes(:scores)\n .where(blue_team_id: self.id).or(Game.includes(:scores).where(white_team_id: self.id))\n .select do |game|\n (game.blue_team_id == self.id || game.white_team_id == self.id) &&\n (game.blue_goals == game.white_goals)\n end\n end", "def find_games(param_team, games)\n team_games = []\n games.each do |game|\n if game[:home_team] == param_team || game[:away_team] == param_team\n team_games << game\n end\n end\n team_games\nend", "def find_unregistered_guests(id)\r\n @unreg_guests = []\r\n PrivateInvite.find_all_by_private_event_id(@event.id).each do |g|\r\n if !User.find_by_email(g.email)\r\n @unreg_guests << g.email\r\n end\r\n end\r\n @unreg_guests \r\n end", "def check_for_broken_competitor(competitor_name)\n puts \"Broken game for #{competitor_name}\"\n games_competitor_played = Game.where(\"(teama = ? OR teamb = ?) AND winner is not ?\", competitor_name, competitor_name,nil)\n if games_competitor_played == 0 then\n Competitor.where(\"name = ?\", competitor_name).first.update_attributes(:active => false, :broken => true)\n Game.where(\"full_name_a = ? OR full_name_b = ?\", competitor_name, competitor_name).each {|pending_game| pending_game.destroy!}\n end\n end", "def check_games\n mysteam64id = \"76561198054201790\"\n\n usergames = JSON.parse(open(\"http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key=47759AFAA400BE100A45F20F9A918C3E&steamid=\" + @user.steam64id + \"&format=json&include_appinfo=1&include_played_free_games=1\").read)\n \n temp_user_game_v = usergames[\"response\"][\"games\"]\n\n num_steam_games = temp_user_game_v[\"game_count\"]\n\n temp_user_game_v.each do |g|\n temp_app_id = g['appid']\n temp_game_name = g['name']\n\n if !Game.exists?(steam_game_id: temp_app_id)\n newgame = Game.create(name: temp_game_name, steam_game_id: temp_app_id)\n end\n\n @user.games << newgame\n\n end\n end", "def blue_players\n Player.joins(:player_games).where(player_games: { game_id: self.id, team_color: PlayerGame::BLUE_TEAM })\n end", "def remove_bye_players(players, round)\n Player.joins(\n :round_statuses,\n ).where(\n round_statuses: { status: 1, round_id: round.id },\n ).where(id: players.map(&:id))\n end", "def players\n players_in_signup = []\n player_ids = self.signups.map {|sign| sign.player_id}\n User.all.select do |user|\n if player_ids.any?(user.id)\n players_in_signup << user\n end\n end\n players_in_signup.uniq\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
rubocop:disable Metrics/AbcSize Prevent access to games_controllershow if player is not a part of that game
def own_game? return unless @game.black_player_id return if @game.white_player_id == current_user.id || @game.black_player_id == current_user.id flash[:alert] = "Sorry, you're not a player in that game" redirect_to games_path end
[ "def player_of_game(game)\n game.player(self)\n end", "def owner\n playerships.first(:conditions => {:owner => true}).player\n rescue\n destroy\n end", "def computers_turn?\n self.current_player.class == Players::Computer ? true : false\n end", "def must_be_my_turn\n @game = Game.find(params[:game_id])\n @player = Player.find(params[:id])\n unless @game.turn_player == @player\n render nothing: true, status: :forbidden\n end\n end", "def find_opponent(player)\n self.player_id == player.id ? self.opponent : self.player\n end", "def player1\n if self.game_type == 'cvc'\n player1 = Computer.find(self.player1_id)\n else \n player1 = Human.find(self.player1_id)\n end\n return player1\n end", "def right_player?\n current_player == Player.find(@piece.owner)\n end", "def current_player\n Player.find(player_turn) unless player_turn.nil?\n end", "def won_game(player)\n if player.advantage\n player.win = true\n player.games_won += 1\n won_set(player)\n reset_scores\n elsif player.points > 3 and player.opponent.points < 3\n player.win = true\n player.games_won += 1\n won_set(player)\n reset_scores\n end\n end", "def player\n # Count total games, ignoring tiebreaks\n games_played = match.set_games.all.reduce(0) do |sum, game|\n sum + (game.tiebreak? ? 0 : 1)\n end\n if match.doubles\n next_doubles_server games_played\n else\n next_singles_server games_played\n end\n end", "def current_player\n current_turn.player\n end", "def players_allowed_to_play\n return if self.manager.nil? || self.players.nil?\n\n self.players.each do |p|\n unless p.tournaments.include? self.manager\n errors.add(:match, \"players must be in same tournament as match\")\n end\n end\n end", "def viewing_players_tab?\n ! viewing_scouts_tab?\n end", "def current_user_is_player1?(game)\n user_session.current_user.id == game.player1_id\n end", "def still_to_play\n return self.game_players.where.not(\n id: self.current_hand.hand_players.where.not(bid: nil).select(:game_player_id)\n )\n end", "def no_convocateds\n self.players.no_convocated\n end", "def burn_player_if_needed\n return if user.blank?\n return if match_played.blank?\n\n championship.freeze!(user) if match_played >= (championship.matches.size / 2.0)\n end", "def update_current_player\n\t @current_player = (@current_player == @human_player)? @ai_player : @human_player\n\t initialize_board_and_code(@current_player.ai?)\n\tend", "def filter_access_before_game_open\n return if current_user&.admin? || !@game.before_competition?\n\n redirect_to user_root_path, alert: I18n.t('game.not_available')\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if game is in checkmate If so, present message indicating winner
def checkmate? return unless @game.determine_checkmate if @game.turn_number.even? @game.update(winning_player_id: @game.black_player_id) elsif game.turn_number.odd? @game.update(winning_player_id: @game.white_player_id) end end
[ "def check_for_mate\n if @board.in_checkmate?( match.next_to_move )\n match.active = false\n match.winner = (match.next_to_move==:white ? match.player2 : match.player1)\n match.save\n end\n end", "def winner\n winning_conditions_met? == \"x\" ? \"#{@player_one} won!\" : \"#{@player_two} won!\"\n end", "def check_winner\r\n\t\tif board.winner?(p1.marker)\r\n\t\t\ttrue\r\n\t\telsif board.winner?(p2.marker)\r\n\t\t\ttrue\r\n\t\telse\r\n\t\t\tfalse\r\n\t\t\t\r\n\t\tend\r\n\tend", "def opponent_in_check?\n if demo_check?(color)\n if demo_checkmate?\n game.status = \"checkmate\"\n game.winner = color\n else\n game.status = \"check\"\n end\n else\n game.status = nil\n return false\n end\n end", "def someone_won?\n !!detect_winner\n end", "def check_winner\r\n if pawns_array.all? { |pawn| pawn.finished == true }\r\n puts \"Player #{self.name.to_s} has won!!! Congrats!!!\"\r\n exit\r\n end\r\n end", "def we_got_a_winner\r\n @remaining_players == 1\r\n end", "def check_win\n\t\t\tif win\n\t\t\t\tputs \"\\n You win!\" \n\t\t\telse\n\t\t\t\t# shows how many turns remain\n\t\t\t\tputs \"\\n You have #{TURNS - @turns} turns left\"\n\t\t\tend\n\t\tend", "def win_game\n @win.each do |m|\n if @board[m[0]].strip == @board[m[1]] && @board[m[1]] == @board[m[2]]\n @winner = true\n end\n end\n @winner\n end", "def check_for_winner\n winning_spaces_filled = WINNING_SPACES.map {|space| @active_spaces[space[0]] + @active_spaces[space[1]] + @active_spaces[space[2]]}\n if winning_spaces_filled.include?(\"OOO\")\n \"Computer\"\n elsif winning_spaces_filled.include?(\"XXX\")\n \"Player\"\n end\n end", "def game_result(completed_game)\n winner = completed_game.winner\n return 'Draw' unless winner\n winner.id == user_session.current_user.id ? 'You won!' : 'You lost'\n end", "def winner\n count1, count2 = @cups[6].count, @cups[13].count\n if count1 > count2\n @name1\n elsif count2 > count1\n @name2\n else\n :draw\n end\n end", "def win_check\n winner = TicTacToe.new(@game_board).winner\n if winner == \"x\" || winner == \"o\"\n @is_winner = true\n p \"Player \"+@current_player + \" wins!\"\n reset_game\n elsif winner == \"draw\"\n p \"Its a draw\"\n reset_game\n end\nend", "def checkmate\n get_out_of_check_moves.length == 0 && in_check?(your_king_position)\n end", "def winner_announcement\n \tif computer_winner?\n puts \"~ I'M SORRY! THE COMPUTER BEAT YOU... YOU LOST! ~\"\n play_again?\n elsif human_winner?\n puts \"~ CONGRATULATIONS! YOU WON!!! ~\"\n play_again?\n else\n puts \"~ CATS GAME... IT WAS A TIE! ~\"\n play_again?\n end\n end", "def won?\n criminal_lost?(@game.current_round)\n end", "def checkForWinner\r\n if(@num_anthills <= 1)\r\n puts\"*******! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! There's a winner ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! !******* \"\r\n printSummary()\r\n return false\r\n else\r\n return true\r\n end\r\n end", "def win\n\t\tif @@feedback == [\"B\", \"B\", \"B\", \"B\"]\n\t\t\t@winner = true\n\t\t\treturn\n\t\tend\n\tend", "def win_message\n puts \"Player #{@id.to_s} (#{@piece}) wins!\"\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /admin/buildings POST /admin/buildings.json
def create @admin_building = Admin::Building.new(admin_building_params) @admin_building.user = current_user respond_to do |format| if @admin_building.save @admin_buildings = buildings(current_user) create_default_service(@admin_building) format.html { redirect_to @admin_building, notice: t(:building_notice_created) } format.json { render :show, status: :created, location: @admin_building } format.js { render :layout => false } else format.html { render :new } format.json { render json: @admin_building.errors, status: :unprocessable_entity } format.js { render :layout => false } end end end
[ "def create\n @building = Building.new(admin_building_params)\n\n respond_to do |format|\n if @building.save\n format.html { redirect_to admin_building_path(@building), notice: 'Building was successfully created.' }\n format.json { render :show, status: :created, location: @building }\n else\n format.html { render 'new' }\n format.json { render json: @building.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @building = Building.new(building_params)\n\n if @building.save\n render json: @building, status: :created, location: @building\n else\n render json: @building.errors, status: :unprocessable_entity\n end\n end", "def create \n @building = Building.new(params[:building])\n\n respond_to do |format|\n if @building.save\n format.html { redirect_to @building, notice: 'Building was successfully created.' }\n format.json { render json: @building, status: :created, location: @building }\n else\n format.html { render action: \"new\" }\n format.json { render json: @building.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @building = Building.new(building_params)\n @building.building_levels.build(building_params[:building_levels_attributes]) if params[:floor]\n render json: @building.errors unless @building.save\n end", "def create\n @building_type = BuildingType.new(building_type_params)\n\n respond_to do |format|\n if @building_type.save\n format.html { redirect_to @building_type, notice: 'Building type was successfully created.' }\n format.json { render :show, status: :created, location: @building_type }\n else\n format.html { render :new }\n format.json { render json: @building_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @building_type = BuildingType.new(params[:building_type])\n\n respond_to do |format|\n if @building_type.save\n format.html { redirect_to @building_type, notice: 'Building type was successfully created.' }\n format.json { render json: @building_type, status: :created, location: @building_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @building_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @building = @site.buildings.build(params[:building])\n\n respond_to do |format|\n if @building.save\n flash[:notice] = 'Building was successfully created.'\n format.html { redirect_to([@site,@building]) }\n format.xml { render :xml => @building, :status => :created, :location => @building }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @building.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @other_building = OtherBuilding.new(other_building_params)\n\n respond_to do |format|\n if @other_building.save\n format.html { redirect_to @other_building, notice: 'Other building was successfully created.' }\n format.json { render :show, status: :created, location: @other_building }\n else\n format.html { render :new }\n format.json { render json: @other_building.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n @buildings = Building.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json :@buildings }\n end\n end", "def create\n @page_title = \"Buildings\"\n @building = Building.new(params[:building])\n add_crumb(\"Admin\", '/admin')\n add_crumb(\"Buildings\", '/buildings')\n add_crumb(\"Create\")\n respond_to do |format|\n if @building.save\n flash[:notice] = 'Building was successfully created.'\n format.html { redirect_to(@building) }\n format.xml { render :xml => @building, :status => :created, :location => @building }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @building.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @buildingdetail = Buildingdetail.new(buildingdetail_params)\n\n respond_to do |format|\n if @buildingdetail.save\n format.html { redirect_to @buildingdetail, notice: \"Buildingdetail was successfully created.\" }\n format.json { render :show, status: :created, location: @buildingdetail }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @buildingdetail.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n # @buildings = Building.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: Oj.dump(@buildings, mode: :compat) }\n end\n end", "def create\n @building_level = BuildingLevel.new(building_level_params)\n render json: @building_level.errors unless @building_level.save\n end", "def create\n @building_master = BuildingMaster.new(building_master_params)\n\n respond_to do |format|\n if @building_master.save\n format.html { redirect_to @building_master, notice: 'Building master was successfully created.' }\n format.json { render :show, status: :created, location: @building_master }\n else\n format.html { render :new }\n format.json { render json: @building_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @featured_building = FeaturedBuilding.new(featured_building_params)\n\n respond_to do |format|\n if @featured_building.save\n format.html { redirect_to redirect_path, notice: 'Featured building was successfully created.' }\n format.json { render :show, status: :created, location: @featured_building }\n else\n format.html { render :new }\n format.json { render json: @featured_building.errors, status: :unprocessable_entity }\n end\n end\n end", "def building_stories_params\n params.permit(:building_id, data: [:id, :name, :multiplier, :z, :floor_to_floor_height, :floor_to_ceiling_height, :building_id])\n end", "def get_building\n if params[:customer].present?\n @buildings = Customer.find(params[:customer]).buildings\n else\n @buildings = Customer.all\n end\n if request.xhr?\n respond_to do |format|\n format.json {\n render json: {buildings: @buildings}\n }\n end\n end\n end", "def new\n @building_type = BuildingType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @building_type }\n end\n end", "def create\n @building = Building.new(params[:building])\n\n respond_to do |format|\n if @building.save\n flash[:notice] = 'Building was successfully created.'\n format.html { redirect_to(@building) }\n format.xml { render :xml => @building, :status => :created, :location => @building }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @building.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /admin/buildings/1 PATCH/PUT /admin/buildings/1.json
def update respond_to do |format| if @admin_building.update(admin_building_params) @admin_buildings = buildings(current_user) format.html { redirect_to @admin_building, notice: t(:building_notice_updated) } format.json { render :show, status: :ok, location: @admin_building } format.js { render :layout => false } else format.html { render :edit } format.json { render json: @admin_building.errors, status: :unprocessable_entity } format.js { render :layout => false } end end end
[ "def update\n respond_to do |format|\n if @building.update(admin_building_params)\n format.html { redirect_to admin_building_path(@building), notice: 'Building was successfully updated.' }\n format.json { render :show, status: :ok, location: @building }\n else\n format.html { render :edit }\n format.json { render json: @building.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @building = Building.find(params[:id])\n\n if @building.update_attributes(building_params)\n head :no_content\n else\n render json: @building.errors, status: :unprocessable_entity\n end\n end", "def update\n @building = Building.find(params[:id])\n\n if @building.update(building_params)\n head :no_content\n else\n render json: @building.errors, status: :unprocessable_entity\n end\n end", "def update\n render json: @building.errors unless @building.update(building_params)\n end", "def update\n @building_type = BuildingType.find(params[:id])\n\n respond_to do |format|\n if @building_type.update_attributes(params[:building_type])\n format.html { redirect_to @building_type, notice: 'Building type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @building_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n render json: @building_level.errors unless @building_level.update(building_level_params)\n end", "def update\n respond_to do |format|\n if @featured_building.update(featured_building_params)\n format.html { redirect_to redirect_path, notice: 'Featured building was successfully updated.' }\n format.json { render :json => { success: true, data: @featured_building } }\n else\n format.html { render :edit }\n format.json { render json: @featured_building.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @other_building.update(other_building_params)\n format.html { redirect_to @other_building, notice: 'Other building was successfully updated.' }\n format.json { render :show, status: :ok, location: @other_building }\n else\n format.html { render :edit }\n format.json { render json: @other_building.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @building_master.update(building_master_params)\n format.html { redirect_to @building_master, notice: 'Building master was successfully updated.' }\n format.json { render :show, status: :ok, location: @building_master }\n else\n format.html { render :edit }\n format.json { render json: @building_master.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @building = @site.buildings.find(params[:id])\n\n respond_to do |format|\n if @building.update_attributes(params[:building])\n flash[:notice] = 'Building was successfully updated.'\n format.html { redirect_to([@site,@building]) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @building.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @buildingdetail.update(buildingdetail_params)\n format.html { redirect_to @buildingdetail, notice: \"Buildingdetail was successfully updated.\" }\n format.json { render :show, status: :ok, location: @buildingdetail }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @buildingdetail.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @buildingtype.update(buildingtype_params)\n format.html { redirect_to @buildingtype, notice: 'Buildingtype was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @buildingtype.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @page_title = \"Buildings\"\n @building = Building.find(params[:id])\n\n respond_to do |format|\n if @building.update_attributes(params[:building])\n flash[:notice] = 'Building was successfully updated.'\n format.html { redirect_to(@building) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @building.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @building_type.update(building_type_params)\n format.html { redirect_to @building_type, notice: 'Building type was successfully updated.' }\n format.json { render :show, status: :ok, location: @building_type }\n else\n format.html { render :edit }\n format.json { render json: @building_type.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @build_object = BuildObject.find(params[:id])\n\n respond_to do |format|\n if @build_object.update_attributes(params[:build_object])\n format.html { redirect_to @build_object, notice: 'Build object was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @build_object.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @building_stage.update(building_stage_params)\n format.html { redirect_to @building_stage, notice: 'Stage was successfully updated.' }\n format.json { render :show, status: :ok, location: @building_stage }\n else\n format.html { render :edit }\n format.json { render json: @building_stage.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @build = Build.find(params[:id])\n\n respond_to do |format|\n if @build.update_attributes(params[:build])\n format.html { redirect_to @build, notice: 'Build was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @build.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @building_type = BuildingType.find(params[:id])\n\n respond_to do |format|\n if @building_type.update_attributes(params[:building_type])\n flash[:notice] = 'BuildingType was successfully updated.'\n format.html { redirect_to(@building_type) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @building_type.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @building = Building.find(params[:id])\n\n respond_to do |format|\n if @building.update_attributes(params[:building])\n flash[:notice] = 'Building was successfully updated.'\n format.html { redirect_to(@building) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @building.errors, :status => :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /admin/buildings/1 DELETE /admin/buildings/1.json
def destroy @admin_building.destroy respond_to do |format| format.html { redirect_to admin_buildings_url, notice: t(:building_notice_destroyed) } format.json { head :no_content } end end
[ "def destroy\n @admin_building = Building.find params[:id]\n @admin_building.destroy\n respond_to do |format|\n format.html { redirect_to admin_buildings_url, notice: 'Building was successfully deleted.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @building = Building.find(params[:id])\n @building.destroy\n\n respond_to do |format|\n format.html { redirect_to buildings_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @building = Building.find(params[:id])\n @building.destroy\n\n respond_to do |format|\n format.html { redirect_to buildings_url }\n format.json { head :ok }\n end\n end", "def destroy\n @very_building.destroy\n respond_to do |format|\n format.html { redirect_to very_buildings_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @building = Building.find(params[:id])\n @building.destroy\n\n head :no_content\n end", "def destroy\n @building = Building.find(params[:id].to_i)\n @building.destroy\n respond_to do |format|\n format.html { redirect_to buildings_url, notice: 'Building destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @building_type = BuildingType.find(params[:id])\n @building_type.destroy\n\n respond_to do |format|\n format.html { redirect_to building_types_url }\n format.json { head :no_content }\n end\n end", "def destroy\n #@building = Building.find(params[:id])\n @building.destroy\n\n respond_to do |format|\n format.html { redirect_to(buildings_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @buildingtype.destroy\n respond_to do |format|\n format.html { redirect_to buildingtypes_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @build.destroy\n respond_to do |format|\n format.html { redirect_to builds_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @building = Building.find(params[:id])\n @building.destroy\n\n respond_to do |format|\n format.html { redirect_to(buildings_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @buildinglog = Buildinglog.find(params[:id])\n @buildinglog.destroy\n\n respond_to do |format|\n format.html { redirect_to buildinglogs_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @my_build.destroy\n respond_to do |format|\n format.html { redirect_to my_builds_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @build = Build.find(params[:id])\n @build.destroy\n\n respond_to do |format|\n format.html { redirect_to builds_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @build = Build.find(params[:id])\n @build.destroy\n\n respond_to do |format|\n format.html { redirect_to builds_url }\n format.json { head :ok }\n end\n end", "def delete(req)\n @building.delete(req)\n save\n end", "def destroy\n @buildingdetail.destroy\n respond_to do |format|\n format.html { redirect_to buildingdetails_url, notice: \"Buildingdetail was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end", "def destroy\n @built = Built.find(params[:id])\n @built.destroy\n\n respond_to do |format|\n format.html { redirect_to(builts_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @build_object = BuildObject.find(params[:id])\n @build_object.destroy\n\n respond_to do |format|\n format.html { redirect_to build_objects_url }\n format.json { head :no_content }\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
update this fetches the existing student by the id for editing in the view and updates changes to that id if there is an error preventing update, it renders the edit form again
def update set_student if @student.update_attributes(edit_params) redirect_to @student else render 'edit' end end
[ "def update\n\t\t#for each student, find the student using student id\n\t\t@student = Student.find(params[:id])\n\t\t#update the student using the student params\n\t\t@student.update(student_params)\n\t\t#go back to the student path when done\n\t\tredirect_to student_path(@student)\n\t#wraps up \"update\" action\n\tend", "def update\n @student = current_district.students.find(params[:id])\n\n respond_to do |format|\n if @student.update_attributes(params[:student])\n flash[:notice] = \"#{edit_obj_link(@student)} was successfully updated.\".html_safe\n format.html { redirect_to(index_url_with_page) }\n else\n format.html { render :action => \"edit\" }\n end\n end\n end", "def edit\n @student = Student.find(params[:id])\n end", "def edit\n @student = Student.find(params[:id])\n render :edit\n end", "def update\n if(session[:student_id] == nil)\n redirect_to signin_session_path\n end\n \n @student = Student.find(params[:id])\n \n if session[:student_id] == @student.id\n if @student.update(params[:student].permit(:name, :nickname, :email, :url, :password_digest))\n redirect_to students_path\n flash[:update] = 'Student updated'\n else\n render 'edit'\n end\n else\n flash[:error] = 'Not logged in as student'\n redirect_to students_path\n end\n end", "def update\n @student = Student.find(params[:id])\n\n respond_to do |format|\n if @student.update_attributes(params[:student])\n format.html { redirect_to [:admin, @student], :notice => 'Student was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @student.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n student_respond @student.update(student_params), :edit\n end", "def update\n @student = Student.find(params[:id])\n\n respond_to do |format|\n if @student.update_attributes(params[:student])\n flash[:success] = t('student.updated')\n format.html { redirect_to(students_path) }\n format.xml { head :ok }\n else\n flash[:error] = t('default_error_message')\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @student.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @student = Student.find(params[:id])\n\n respond_to do |format|\n if @student.update_attributes(params[:student])\n format.html { redirect_to student_url(@student) }\n format.xml { render :nothing => true }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @student.errors.to_xml }\n end\n end\n end", "def update\n @indexstudent = Indexstudent.find(params[:id])\n\n respond_to do |format|\n if @indexstudent.update_attributes(params[:indexstudent])\n format.html { redirect_to @indexstudent, notice: 'Indexstudent was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @indexstudent.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @student_detail.update(student_detail_params)\n format.html { redirect_to student_details_path, notice: 'Student detail was successfully updated.' }\n format.json { render :show, status: :ok, location: @student_detail }\n else\n format.html { render :edit }\n format.json { render json: @student_detail.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @student = User::Student.find(params[:id])\n respond_to do |format|\n if @student.update(student_params)\n format.html { redirect_to user_student_path(@user, @student), notice: 'Student was successfully updated.' }\n format.json { render :show, status: :ok, location: user_student_path(@user, @student) }\n else\n format.html { render :edit }\n format.json { render json: @student.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @stud.update(stud_params)\n format.html { redirect_to @stud, notice: 'Student was successfully updated.' }\n format.json { render :show, status: :ok, location: @stud }\n else\n format.html { render :edit }\n format.json { render json: @stud.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @student = Portal::Student.find(params[:id])\n\n respond_to do |format|\n if @student.update_attributes(params[:student])\n flash[:notice] = 'Portal::Student was successfully updated.'\n format.html { redirect_to(@student) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @student.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @leaveforstudent = Leaveforstudent.find(params[:id])\n\n respond_to do |format|\n if @leaveforstudent.update_attributes(params[:leaveforstudent])\n flash[:notice] = t('leaveforstudent.title2')+\" \"+t('updated')\n format.html { redirect_to(@leaveforstudent) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @leaveforstudent.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n # @student_taluka = StudentTaluka.find(params[:id])\n\n respond_to do |format|\n if @student_taluka.update_attributes(params[:student_taluka])\n format.html { redirect_to @student_taluka, notice: 'Student taluka was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @student_taluka.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @msstudent = Msstudent.find(params[:id])\n respond_to do |format|\n if @msstudent.update_attributes(params[:msstudent])\n format.html { redirect_to @msstudent, notice: ' Student was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @msstudent.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @studentinfo = Studentinfo.find(params[:id]) \n\n respond_to do |format|\n if @studentinfo.update_attributes(params[:studentinfo])\n format.html { redirect_to(@studentinfo, :notice => 'Studentinfo was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @studentinfo.errors, :status => :unprocessable_entity }\n end\n end\n end", "def update\n @dojo_student = DojoStudent.find(params[:id])\n\n respond_to do |format|\n if @dojo_student.update_attributes(params[:dojo_student])\n format.html { redirect_to @dojo_student, notice: 'Dojo student was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @dojo_student.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
supervisors for the student
def supervisor @supervisors = Allocation.all.order(created_at: :desc).where(student_id: current_student.id) end
[ "def supervisores\n @supervisor = User.all\n end", "def academics\n [supervisor] + examiners\n end", "def senior(students)\n students.select {|student| student.senior? }\nend", "def students\n self.course_person.all(:type => \"student\").persons\n end", "def get_student\n\t\tstudents_array = []\n\t\tstudents.each do |student|\n\t\t\tstudent.performances.each do |performance|\n\t\t\t\tstudents_array += [student] if performance.rate == 3\n\t\t\t\tstudents_array += [student, student] if performance.rate == 2\n\t\t\t\tstudents_array += [student, student, student] if performance.rate == 1\n\t\t\tend\n\t\tend\n\t\tstudents_array.sample\n\tend", "def supervision\n @supervisions = Allocation.all.order(created_at: :desc).where(staff_id: current_staff.id)\n end", "def cur_student\n student\n end", "def super_sector; end", "def students_advisor\n return nil if self.advisor? || self.provisional?\n\n self.current_sections.first.advisor\n end", "def give_superusers_managing_role\n AdminSet.all.each do |admin_set|\n admin_set.permission_template.available_workflows.each do |workflow| # .where(active: true) ?\n workflow.update_responsibilities(role: Sipity::Role.where(name: \"managing\").first, agents: superusers_as_sipity_agents)\n end\n end\n end", "def students\n Student.all.select{|student| student.cohort == self }\n end", "def all_students\n # binding.pry\n student_array = BoatingTest.all.select do |test_info|\n test_info.instructor == self \n end \n student_array.map(&:student)\n end", "def is_supervisor?\n not under_supervision_clinics.empty?\n end", "def supervisor\n crew_members.supervisors.first.user unless crew_members.supervisors.empty?\n end", "def student\n return @student\n end", "def former_student\n @batch = Batch.shod(params[:graduate][:batch_id])\n @batch.graduate(params[:students], params[:graduate][:status_description])\n former_student2\n authorize! :create, @batch\n end", "def student_names\n self.students.map do |student|\n student.name\n end\n end", "def allowSuperiorSubordinate()\n banner(\"Allow Superior/Subordinate\")\n @run.society.each_agent(true) do |agent|\n superior = agent.name\n debug \"superior = #{superior}\"\n subordinates = []\n directlyReportingAll(superior).each do |subordinate|\n if @allAgents.include?(subordinate) then\n subordinates.push(subordinate)\n end\n end\n debug \"subordinates = #{subordinates.join(',')}\"\n enclaves = [ agent.host.enclave ]\n subordinates.each do |subordinate|\n enclave = getEnclaveFromAgent(subordinate)\n if enclave == nil then\n next\n end\n if ! enclaves.include?(enclave) then\n enclaves.push(enclave)\n end\n end\n debug \"enclaves = [#{enclaves.join(\", \")}]\"\n if (! subordinates.empty?) then\n declareSet(namedAgent(superior), [superior])\n subordinatesName = \"SubordinatesOf#{superior}\"\n declareSet(subordinatesName, subordinates)\n permit(namedAgent(superior), subordinatesName,\n \"#{superior}TalksToSubordinates-I\",\n enclaves)\n permit(subordinatesName, namedAgent(superior),\n \"#{superior}TalksToSubordinates-II\",\n enclaves)\n end\n end\n end", "def students\n course_enrollments.where(course_role: CourseRole.student).map(&:user)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a named cluster by name
def named_cluster(name = context&.cluster) return nil if name.nil? clusters.find { |c| c.name == name } end
[ "def cluster(name)\n return nil unless cluster?(name)\n\n clusters.select { |x| x.name == name }.first\n end", "def has_cluster?( name )\n \n return @clusters.has_key?( name.to_sym )\n \n end", "def cluster_exists?(cluster_name)\n existing_clusters = self.get('/clusters')\n cluster_exists = false\n unless existing_clusters.nil?\n existing_clusters['items'].each do |cluster|\n if cluster['name'] == cluster_name.downcase\n cluster_exists = true\n end\n end\n end\n cluster_exists\n end", "def member_of_cluster?(serv_name, serv_node)\n clusters.each do |cluster|\n return cluster if member?(cluster, serv_name, serv_node)\n end\n nil\n end", "def cluster() node[:cluster_name] ; end", "def cluster name, &block\n subgraph \"cluster_#{name}\", &block\n end", "def has_cluster?( name )\n \n return ::Module::Cluster.instance_controller( self ).has_cluster?( name )\n \n end", "def name\n @cluster.name\n end", "def find_client(cl_name)\n chef_clients.find{|ccl| ccl.name == cl_name }\n end", "def cluster(name, options = {})\n sql = 'CLUSTER '\n sql << 'VERBOSE ' if options[:verbose]\n sql << quote_table_name(name)\n sql << \" USING #{quote_generic(options[:using])}\" if options[:using]\n\n execute \"#{sql};\"\n end", "def find_server(name)\n find_server_by(name: name)\n end", "def cluster_name\n return false if Cassandra.VERSION.to_f < 0.7\n\n @cluster_name ||= client.describe_cluster_name()\n end", "def cluster\n raw_match['cluster']\n end", "def client(name)\n client_to_find = name\n @clients.find {|key, value| key == client_to_find } \n end", "def find_node_by_name(name)\n @nodes[name]\n end", "def find_node(name)\n @nodes.each { |node| return node if node[:name] == name }\n end", "def find_cloud_by_name(name)\n cloud = nil\n cloud_list = @connection.clouds.index(:filter => [\"name==#{name}\"])\n raise \"More than one cloud with the name of '#{name}'. \" +\n \"Please fix via the RightScale dashboard and retry.\" if cloud_list.size > 1\n cloud = cloud_list.first unless cloud_list.empty?\n cloud\n end", "def find_server_index(name)\n find_server_index_by(name: name)\n end", "def get_cluster_name_for_host(host)\n return nil unless load_knife_config\n query = Chef::Search::Query.new\n # we're only expecting a single node to be returned --> make sure it's the case!\n chef_node = query.search('node', \"fqdn:#{host}\").first.first\n chef_node.ganglia.cluster_name\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /strategic_objectives POST /strategic_objectives.json
def create @strategic_objective = StrategicObjective.new(strategic_objective_params) if @strategic_objective.save flash[:success] = 'Strategic objective was successfully created.' redirect_to :back else flash[:danger] = 'Strategic objective was not created.' redirect_to :back end end
[ "def create\n @objective = @goal.objectives.create(objective_params)\n render json: @objective\n end", "def create\n @objective = current_user.objectives.create(params[:objective])\n\n respond_to do |format|\n if @objective.save\n format.html { redirect_to @objective, notice: 'Objective was successfully created.' }\n format.json { render json: @objective, status: :created, location: @objective }\n else\n format.html { render action: \"new\" }\n format.json { render json: @objective.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n #@objective = Objective.new(params[:objective])\n @objective = @task.objectives.new(params[:objective])\n @objective.user = current_user\n\n respond_to do |format|\n if @objective.save\n format.html { redirect_to tasks_path(current_user), notice: 'ubjective was successfully created.' }\n format.json { render json: @objective, status: :created, location: @objective }\n else\n format.html { render action: \"new\" }\n format.json { render json: @objective.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @criterion = Criterion.find(params[:criterion_id])\n @objective = @criterion.objectives.new(params[:objective])\n\n respond_to do |format|\n if @objective.save\n flash[:notice] = 'Objective was successfully created.'\n format.html { redirect_to(@criterion) }\n format.xml { render :xml => @objective, :status => :created, :location => @objective }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @objective.errors, :status => :unprocessable_entity }\n end\n end\n end", "def index\n @objectives = @goal.objectives.all \n render json: @objectives \n end", "def create\n @strategic_goal = StrategicGoal.new(strategic_goal_params)\n\n respond_to do |format|\n if @strategic_goal.save\n format.html { redirect_to @strategic_goal, notice: 'Strategic goal was successfully created.' }\n format.json { render :show, status: :created, location: @strategic_goal }\n else\n format.html { render :new }\n format.json { render json: @strategic_goal.errors, status: :unprocessable_entity }\n end\n end\n end", "def new\n @objective = @task.objectives.new\n #@objective = @tasks.objectives.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @objective }\n end\n end", "def create\n @objective_textual = ObjectiveTextual.new(objective_textual_params)\n\n respond_to do |format|\n if @objective_textual.save\n format.html { redirect_to @objective_textual, notice: 'Objective textual was successfully created.' }\n format.json { render :show, status: :created, location: @objective_textual }\n else\n format.html { render :new }\n format.json { render json: @objective_textual.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @project_objective = @project.project_objectives.new(params[:project_objective])\n\n respond_to do |format|\n if @project_objective.save\n format.html { redirect_to(edit_project_by_action_type_path(@project, \"objective\"), :notice => 'Project objective was successfully created.') }\n format.xml { render :xml => @project_objective, :status => :created, :location => @project_objective }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @project_objective.errors, :status => :unprocessable_entity }\n end\n end\n end", "def create\n @decision_object = DecisionObject.new(params[:decision_object])\n\n respond_to do |format|\n if @decision_object.save\n format.html { redirect_to @decision_object, notice: 'Decision object was successfully created.' }\n format.json { render json: @decision_object, status: :created, location: @decision_object }\n else\n format.html { render action: \"new\" }\n format.json { render json: @decision_object.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @adjective = Adjective.new(adjective_params)\n\n respond_to do |format|\n if @adjective.save\n format.html { redirect_to @adjective, notice: 'Adjective was successfully created.' }\n format.json { render action: 'show', status: :created, location: @adjective }\n else\n format.html { render action: 'new' }\n format.json { render json: @adjective.errors, status: :unprocessable_entity }\n end\n end\n end", "def index\n #@objectives = Objective.all\n @objectives = @task.objectives.order(\"position\")\n @objective ||= @task.objectives.new\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @objectives }\n end\n end", "def update\n\n if @strategic_objective.update(strategic_objective_params)\n flash[:success] = 'Strategic objective was successfully updated.'\n redirect_to :back\n else\n flash[:danger] = 'Strategic objective was not updated.'\n redirect_to :back\n end\n end", "def create\n @estrategia_promocional = EstrategiaPromocional.new(params[:estrategia_promocional])\n\n respond_to do |format|\n if @estrategia_promocional.save\n format.html { redirect_to @estrategia_promocional, notice: 'Estrategia promocional was successfully created.' }\n format.json { render json: @estrategia_promocional, status: :created, location: @estrategia_promocional }\n else\n format.html { render action: \"new\" }\n format.json { render json: @estrategia_promocional.errors, status: :unprocessable_entity }\n end\n end\n end", "def create\n @learning_objective = LearningObjective.new(learning_objective_params)\n @learning_objective.user = current_user\n\n respond_to do |format|\n if @learning_objective.save\n format.html { redirect_to @learning_objective, notice: 'Learning objective was successfully created.' }\n format.json { render json: @learning_objective, status: :created, location: @learning_objective }\n else\n format.html { render :new }\n format.json { render json: @learning_objective.errors, status: :unprocessable_entity }\n end\n end\n end", "def set_objective\n @objective = @goal.objectives.find_by(id: params[:id])\n end", "def index\n @strategic_goals = StrategicGoal.all\n end", "def create\n objective = params[:objective]\n status = CompanyObjective.new_company_objective(objective, current_user.id)\n respond_to do |format|\n if status == 200 \n format.json { render json: 'Company Objective is created successfully!', status: :ok }\n else\n format.json { render json: 'Fail to create company objective!', status: :unprocessable_entity }\n end\n end\n end", "def create\n @program_educational_objective = ProgramEducationalObjective.new(program_educational_objective_params)\n\n respond_to do |format|\n if @program_educational_objective.save\n format.html { redirect_to @program_educational_objective, notice: 'Program educational objective was successfully created.' }\n format.json { render :show, status: :created, location: @program_educational_objective }\n else\n format.html { render :new }\n format.json { render json: @program_educational_objective.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /strategic_objectives/1 PATCH/PUT /strategic_objectives/1.json
def update if @strategic_objective.update(strategic_objective_params) flash[:success] = 'Strategic objective was successfully updated.' redirect_to :back else flash[:danger] = 'Strategic objective was not updated.' redirect_to :back end end
[ "def update\n respond_to do |format|\n if @strategic_goal.update(strategic_goal_params)\n format.html { redirect_to @strategic_goal, notice: 'Strategic goal was successfully updated.' }\n format.json { render :show, status: :ok, location: @strategic_goal }\n else\n format.html { render :edit }\n format.json { render json: @strategic_goal.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @objective = Objective.find(params[:id])\n\n respond_to do |format|\n if @objective.update_attributes(params[:objective])\n format.html { redirect_to tasks_path(current_user), notice: 'ubjective was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @objective.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @objective = Objective.find(params[:id])\n\n respond_to do |format|\n if @objective.update_attributes(params[:objective])\n format.html { redirect_to @objective, notice: 'Objective was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @objective.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_initiative.update(api_v1_initiative_params)\n format.html { redirect_to @api_v1_initiative, notice: 'Initiative was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @narrative = Narrative.find(params[:id])\n\n respond_to do |format|\n if @narrative.update_attributes(params[:narrative])\n format.html { redirect_to @narrative, notice: 'Narrative was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @narrative.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @estrategia_promocional = EstrategiaPromocional.find(params[:id])\n\n respond_to do |format|\n if @estrategia_promocional.update_attributes(params[:estrategia_promocional])\n format.html { redirect_to @estrategia_promocional, notice: 'Estrategia promocional was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @estrategia_promocional.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @orderable_concept = OrderableConcept.find(params[:id])\n\n respond_to do |format|\n if @orderable_concept.update_attributes(params[:orderable_concept])\n format.html { redirect_to @orderable_concept, notice: 'Orderable concept was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @orderable_concept.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @ontology = Ontology.find(params[:id])\n\n respond_to do |format|\n if @ontology.update_attributes(params[:ontology])\n format.html { redirect_to @ontology, notice: 'Ontology was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :edit }\n format.json { render json: @ontology.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @concepto = Concepto.find(params[:id])\n\n respond_to do |format|\n if @concepto.update_attributes(params[:concepto])\n format.html { redirect_to @concepto, notice: 'Concepto was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @concepto.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n authorize_initiative\n respond_to do |format|\n if @initiative.update(initiative_params)\n format.html { redirect_to @initiative, notice: 'Initiative was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @initiative.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @api_v1_initiative_update.update(api_v1_initiative_update_params)\n format.html { redirect_to @api_v1_initiative_update, notice: 'Initiative update was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_initiative_update }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_initiative_update.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to do |format|\n if @tactic.update(tactic_params)\n format.html { redirect_to @tactic, notice: 'Tactic was successfully updated.' }\n format.json { render :show, status: :ok, location: @tactic }\n else\n format.html { render :edit }\n format.json { render json: @tactic.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @decision_object = DecisionObject.find(params[:id])\n\n respond_to do |format|\n if @decision_object.update_attributes(params[:decision_object])\n format.html { redirect_to @decision_object, notice: 'Decision object was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @decision_object.errors, status: :unprocessable_entity }\n end\n end\n end", "def update_suggested_course_pathway\n suggested_pathway = SuggestedPathway.find_by(id: params[:id])\n suggested_pathway.name = params[:name]\n suggested_pathway.year = params[:year]\n suggested_pathway.course_id = params[:course_id]\n suggested_pathway.data = params[:data]\n suggested_pathway.save\n render json: suggested_pathway\n end", "def update\n respond_to do |format|\n if @objective_textual.update(objective_textual_params)\n format.html { redirect_to @objective_textual, notice: 'Objective textual was successfully updated.' }\n format.json { render :show, status: :ok, location: @objective_textual }\n else\n format.html { render :edit }\n format.json { render json: @objective_textual.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @golf_cource = GolfCource.find(params[:id])\n\n respond_to do |format|\n if @golf_cource.update_attributes(params[:golf_cource])\n format.html { redirect_to scaffold_golf_cource_url(@golf_cource), notice: 'Golf cource was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @golf_cource.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @thief_talent = ThiefTalent.find(params[:id])\n\n if @thief_talent.update(thief_talent_params)\n head :no_content\n else\n render json: @thief_talent.errors, status: :unprocessable_entity\n end\n end", "def update\n @optin_contestant = OptinContestant.find(params[:id])\n\n respond_to do |format|\n if @optin_contestant.update_attributes(params[:optin_contestant])\n format.html { redirect_to @optin_contestant, notice: 'Optin contestant was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @optin_contestant.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @article_of_clothing = ArticleOfClothing.find(params[:id])\n\n respond_to do |format|\n if @article_of_clothing.update_attributes(params[:article_of_clothing])\n format.html { redirect_to @article_of_clothing, notice: 'Article of clothing was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @article_of_clothing.errors, status: :unprocessable_entity }\n end\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Mash uses convert_value to mashify values on input. We override it here to convert hash or array values to VividMash or AttrArray for consistency and to ensure that the added parts of the attribute tree will have the correct cache invalidation behavior.
def convert_value(value) case value when VividMash, AttrArray value when Hash VividMash.new(value, __root__, __node__, __precedence__) when Array AttrArray.new(value, __root__, __node__, __precedence__) else value end end
[ "def convert_value(value)\n case value\n when VividMash\n value\n when AttrArray\n value\n when Hash\n VividMash.new(value, __root__, __node__, __precedence__)\n when Array\n AttrArray.new(value, __root__, __node__, __precedence__)\n else\n value\n end\n end", "def convert_value(value)\n if value.class == ConfigMash\n value\n elsif value.class == Hash\n ConfigMash.new(value)\n else\n super\n end\n end", "def convert_value(val, duping=false) #:nodoc:\n return val.dup if val.is_a?(Hashie::Mash)\n super(val, duping)\n end", "def transform(value)\n return CustomHash.new(value) if value.kind_of?(Hash) || value.kind_of?(Array)\n value\n end", "def mashify(data)\n if data.is_a?(Array)\n data.map { |d| mashify(d) }\n elsif data.is_a?(Hash)\n Hashie::Mash.new(data)\n else\n data\n end\n end", "def prepare_value(attr, value)\n if attr.container == Array\n value = if value.is_a?(Hash)\n [value]\n else\n [*value].compact\n end\n end\n\n hook_name = prepare_hook_name(attr)\n if self.respond_to?(hook_name, true)\n send(hook_name, value)\n else\n value\n end\n end", "def __convert_value(value)\n case\n # Converts Hash to Bag instance\n when value.kind_of?(Hash)\n Bag.new(value, @__config)\n\n # Converts Array elements to Bag instances if needed\n when value.kind_of?(Array)\n value.map(&self.method(:__convert_value))\n\n # Keeps as-is other elements\n else\n value\n end\n end", "def normalize(object, attribute, value); normalize_value(value) end", "def process_value(value)\n case value\n when Hash then self.class.new(@_agent, value)\n when Array then value.map { |v| process_value(v) }\n else value\n end\n end", "def attr_converter(hash)\n jiak.data.attr_converter(hash)\n end", "def convert(attribute, v)\n clazz = attribute.clazz\n # either as it is already the correct (||nested_array) type\n if v == nil || v.is_a?(clazz) || (attribute.is_a?(Arrest::NestedCollection) && v.is_a?(Array))\n converted_v = v\n elsif attribute.is_a?(Arrest::NestedAttribute) && v.is_a?(Hash) # a nested attribute needs a parent and a hash\n converted_v = attribute.from_hash(self, v)\n elsif clazz.respond_to?(:convert) # or its clazz implements a convert method\n converted_v = clazz.convert(v)\n elsif CONVERTER[clazz] # or a converter has been registered in arrest\n converted_v = CONVERTER[clazz].convert(v)\n else # otherwise raise\n raise ArgumentError, \"Setting of attribute with type >#{clazz}< with value type >#{v.class}< failed.\"\n end\n converted_v\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 convert_attribute_value obj\n case obj\n when OpenCensus::Trace::TruncatableString\n TraceProtos::AttributeValue.new \\\n string_value: convert_truncatable_string(obj)\n when Integer\n TraceProtos::AttributeValue.new int_value: obj\n when true, false\n TraceProtos::AttributeValue.new bool_value: obj\n end\n end", "def to_marchash\n [@tag, @value]\n end", "def mass_assign(hash, pre_process: true)\n method = pre_process ? :[]= : :orig_set_value\n validate_hash(hash)\n hash.each do |key, value|\n send(method, key, value)\n end\n end", "def normalize( value )\n value\n end", "def coerce(value)\n hash = super(value)\n coerced_hash = {}\n\n hash.each do |k,v|\n k = @key_type.coerce(k) if @key_type\n v = @value_type.coerce(v) if @value_type\n\n coerced_hash[k] = v\n end\n\n return coerced_hash\n end", "def mass_assign(hash, pre_process: true)\n method = pre_process ? :[]= : :orig_set_value\n hash.each do |key, value|\n self.send(method, key, value)\n end\n end", "def to_mash\n ::Hashie::Mash.new(self)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates actual cost from the activities claiming this project as a parent. In the even there are no activities, sets this projects' cost to 0.
def update_actual_cost cost = BigDecimal(0.00, 10) self.activities.each do |activity| cost += activity.actualCost end self.actual_cost = cost end
[ "def update_target_cost\n cost = BigDecimal(0.00, 10)\n self.activities.each do |activity|\n cost += activity.targetCost\n end\n self.target_cost = cost\n end", "def total_cost\n @cost + @child_cost\n end", "def calculate_base_cost!\n result_obj = self.cost_matrix.reduction\n\n @base_cost = result_obj[:total_reduction]\n if(self.parent)\n @base_cost += self.parent.base_cost + self.parent.reduced_cost_matrix[self.parent.city_id, self.city_id]\n end\n\n @reduced_cost_matrix = result_obj[:matrix]\n end", "def updateCosts(children, costs, parent, unvisitedNodes) \n # If the cost from the parent to any of the children is less than\n # what is currently recorded, replace it\n children.each do |child,cost|\n if (cost < costs[child][:cost])\n costs[child] = {\n cost: cost,\n parent: parent\n }\n end\n end\n # when we're done, remove this node from the list of unvisited nodes\n unvisitedNodes.delete(parent)\n end", "def resources_total_cost\n\t\tif has_children?\n\t\t\tchildren.includes(:children).map(&:resources_total_cost).inject(:+)\n\t\telse\n\t\t\tresources_cost\n\t\tend\n\tend", "def costs\n @cost_payment_plan = @project.cost_payment_plan\n @budget = @project.budget\n end", "def total_payout\n # make sure we have rep_parent\n node = self\n if !self.rep_parent.nil?\n node = self.rep_parent\n end\n \n # get total payout of children\n child_payout = 0\n node.children.each do |child|\n child_payout = child_payout + child.total_payout\n end\n \n # multiply complete * reward and expired * penalty\n payout = node.repititions.\n where(:state => Activity::COMPLETE).size * node.reward\n payout = payout -\n node.repititions.\n where(:state => Activity::EXPIRED).size *\n node.penalty\n return payout + child_payout\n \n end", "def calculate_gcost(p, parent)\n\t\tif is_ortho?(p, parent)\n\t\t\tgcost = @gcosts[parent] + COST_ORT\n\t\telse\n\t\t\tgcost = @gcosts[parent] + COST_DIA\n\t\tend\n\tend", "def cost\n cost_from_shared_groups + cost_from_shared_meetings\n end", "def cost\n total = 0.0\n not_covered.each do |n|\n total += n.cost\n end\n total\n end", "def subcontract_cost\n subcontract_ids = line_items.find(:all,\n :select => 'DISTINCT subcontract_id AS ids').map { |x| x.ids }\n logger.debug subcontract_ids.inspect\n if subcontract_ids == [nil]\n @subcontract_cost = BigDecimal.new(\"0.0\")\n else\n @subcontract_cost = -Subcontract.find(subcontract_ids).sum { |subk| subk.nil? ? BigDecimal.new(\"0.0\") : BigDecimal.new(subk.cost.to_s) }\n end\n @subcontract_cost\n end", "def cost\n commission = [self.payment/10.0, MTURK_COMMISSION_MINIMUM].max\n return (self.payment + commission) * tasks.size\n end", "def total_payout\n # calculate children payout\n count = 0\n self.children.each do |child|\n count = count + child.total_payout\n end\n \n # calculate payout of this ativity\n if self.state == COMPLETE\n return count + self.reward\n elsif self.state == EXPIRED\n return count - self.penalty\n else \n return count\n end\n\n end", "def this_total_costs\n item_costs + worker_costs + tool_costs + vehicle_costs + subcontractor_costs\n end", "def cost\n cost = 0\n @solution.each { |route| cost += route.travel_time_and_cost[0] }\n return cost\n end", "def calculated_amount\n #use the real score if we have one, otherwise assume zero\n #could make this more sophistocated later (e.g. use #N/A)\n\n #if we don't have child goals, use the current manual score\n #if there isn't a manually entered score, use zero\n #if we DO have children, average up the child scores\n #this should recursively follow all children to the bottom...\n #could be VERY slow with lots of kids... might want to make this an offline process and save the score inside the Goal model... TODO\n if(children.empty?)\n #return the score if there is one.\n score_amount = score ? score.amount : 0\n else\n score_amount = children.map{|c| c.calculated_amount}.inject(:+).to_f / children.count\n end\n #save!\n #score_amount #dumb, but I need to return this value. Not the \"true\" from the save above\n end", "def set_project_amount\n if self.project\n self.net_project_amount_in_cents = self.net_amount_in_cents - self.current_project_fee_amount_in_cents\n if self.net_project_amount_in_cents < 0\n self.net_project_amount_in_cents = 0 #not allowed to have negative amount\n #above line is a problem - should be debiting this amount off of a stored ce value..\n end\n else\n self.net_project_amount_in_cents = 0\n end\n self.project_amount_in_cents = self.net_project_amount_in_cents if self.new_record? \n end", "def total_costs\n item_costs + worker_costs + tool_costs + vehicle_costs + subcontractor_costs + suborder_costs\n end", "def cost\n schedule.reduce(0) do |cost, day|\n cost + COSTS[day.city][day.cost]\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a hash of (year, zeroBigDecimal) with one year for each year this project spans.
def initialized_year_hash year_in_range = self.startDate.year year_hash = {} while year_in_range <= self.endDate.year year_hash[year_in_range] = BigDecimal(0.0, 10) year_in_range += 1 end year_hash end
[ "def hashCode\n @year * daysInYear + ordinalDate\n end", "def last_year_as_hash(offset = 1)\n data_klass.metrics.zip(aggregated_quarter(offset).metric_values).to_h\n end", "def activity_year_fractions_hash(activity)\n year_fractions = {}\n total_activity_days = activity.endDate - activity.startDate # Cannot be zero, by :validDate\n range_start = activity.startDate\n while range_start.year < activity.endDate.year\n range_end = Date.new(range_start.year + 1)\n year_fractions[range_start.year] = ((range_end - range_start) / total_activity_days)\n range_start = range_end\n end\n year_fractions[range_start.year] = ((activity.endDate - range_start) / total_activity_days)\n year_fractions\n end", "def map_year_of_birth\n @year_of_birth = Hash.new(0)\n\n @friends_info[\"year_of_birth\"].each do |value|\n @year_of_birth[value] += share_amounts[\"year_of_birth\"]\n end\n\n @year_of_birth\n end", "def hash_days_number year\n hash = { 1 => 31, 2 => 28, 3 => 31, 4 => 30, 5 => 31, 6 => 30,\n 7 => 31, 8 => 31, 9 => 30, 10 => 31, 11 => 30, 12 => 31 }\n\n hash[2] = 29 if leap? year\n hash\nend", "def hash\n\t\t\"#{@year}#{@month}\".to_i\n\tend", "def countries_reported_range(year)\n year = year.to_i\n years = case year\n when 2012\n [year, year + 1]\n when Date.today.year - 1\n [year - 1, year]\n else\n [year - 1, year, year + 1]\n end\n hash = {}\n years.map do |y|\n data = countries_reported(y)\n hash[year] ||= []\n hash[year] << data\n end\n hash\n end", "def yearly_occurrences; end", "def year_metrics(metrics = [])\n metric_hash = {}\n\n metrics.each do |metric|\n if metric_hash[metric[:year]].present?\n metric_hash[metric[:year]] += metric[:metric]\n else\n metric_hash[metric[:year]] = metric[:metric]\n end\n end\n\n metric_hash\n end", "def associated_years\n years = \"\"\n \n\t start_date = event_start\n\t start_date = entry_deadline if is_opportunity?\n\t \n years << start_date.year.to_s if !start_date.blank?\n years << ' '\n years << event_finish.year.to_s if !event_finish.blank?\n \n #remove duplicates and trim off spaces\n unique_years = years.strip.split(' ').uniq.sort\n result = unique_years\n if unique_years.length > 1\n result = []\n for y in unique_years[0]..unique_years[1]\n result << y\n end\n end\n result\n #now we have the 2004-2008 case to deal with, we wish to create [2004,2005,...2008]\n \n end", "def get_project_fiscal_years project\n if project.blank?\n []\n elsif project.multi_year?\n a = []\n (current_fiscal_year_year..current_fiscal_year_year + 49).map{ |y| [fiscal_year(y), y] }.each do |fy|\n if fy[1] < project.fy_year\n next\n else\n a << fy\n end\n end\n a\n else\n [[project.fiscal_year, project.fy_year]]\n end\n end", "def years_with_records\n query = get_sql_for(\"year\")\n records .select(\"#{query} as year\")\n .group(query)\n .order(\"#{query} DESC\").map do |record|\n record.year.to_i\n end\n end", "def registers_years\n years = []\n self.registers.dates_by_year.map do |register|\n years << register.date.year\n end\n logger.info \"The distinct years are #{ years }\"\n return years\n end", "def year\n raise ArgumentError, 'Timeframes that cross year boundaries are dangerous during Timeframe#year' unless start_date.year == end_date.yesterday.year\n Timeframe.new :year => start_date.year\n end", "def build_header_year\n \"#{begin_date.year}/#{end_date.year}\"\n end", "def years\n\n firstCoin = Coin.where([\"coin_value_id = :cv\", { :cv => id }]).order(\"coins.start_year ASC\").find(:first)\n lastCoin = Coin.where([\"coin_value_id = :cv\", { :cv => id }]).order(\"coins.start_year ASC\").find(:last)\n\n start_year = firstCoin.start_year\n end_year = lastCoin.end_year\n\n if end_year == 0\n require 'date'\n end_year_str = Date.today.strftime(\"%Y\")\n else\n end_year_str = end_year\n end\n \n return \"#{start_year} - #{end_year_str}\"\n\n end", "def years() 365 * days end", "def get_matching_students_count\n year_groups = Hash.new(0)\n get_matching_students.each do |user|\n year_groups[user.year] += 1\n end\n year_groups\n end", "def create_year_structures\n for y in 1..self.duration_in_years\n self.year_structures << YearStructure.create(year_of_study: y)\n end\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
given an activity, returns a hash of (year, fraction of activity's time) across the activity's start and end dates. Note this is inclusive of the startDate, exclusive of the endDate.
def activity_year_fractions_hash(activity) year_fractions = {} total_activity_days = activity.endDate - activity.startDate # Cannot be zero, by :validDate range_start = activity.startDate while range_start.year < activity.endDate.year range_end = Date.new(range_start.year + 1) year_fractions[range_start.year] = ((range_end - range_start) / total_activity_days) range_start = range_end end year_fractions[range_start.year] = ((activity.endDate - range_start) / total_activity_days) year_fractions end
[ "def activity\n activity = {}\n return activity if empty?\n\n commit_count = values.size\n\n active_days = {}\n each do |commit|\n date = commit.committed_date.utc\n day = Time.utc(date.year, date.month, date.day).send :to_date\n if active_days.key? day\n active_days[day] += 1\n else\n active_days[day] = 1\n end\n end\n\n most_active_day = active_days.sort_by { |day, count| count }.last.first\n\n activity[:first_commit_date] = last.committed_date\n activity[:last_commit_date] = first.committed_date\n\n age_in_days = (Time.now - activity[:first_commit_date]) / 86400.0\n\n activity[:active_days] = active_days\n activity[:most_active_day] = most_active_day\n activity[:commits_per_day] = commit_count / age_in_days\n activity[:commits_per_active_day] = commit_count.to_f / active_days.size\n\n activity\n end", "def scheduled_activity_attrs_from_activity(activity)\n result = Hash.new\n result[:study_segment] = activity['study_segment'].to_s\n result[:activity_id] = activity['id']\n result[:ideal_date] = activity['ideal_date']\n result[:labels] = activity['labels']\n result[:activity_name] = activity['activity']['name'] if activity['activity']\n result[:activity_type] = activity['activity']['type'] if activity['activity']\n result[:current_state] = activity['current_state']['name'] if activity['current_state']\n result[:date] = activity['current_state']['date'] if activity['current_state']\n result[:activity_time] = activity['current_state']['time'] if activity['current_state']['time']\n result[:person_id] = activity['assignment']['id'] if activity['assignment']\n result\n end", "def initialized_year_hash\n year_in_range = self.startDate.year\n year_hash = {}\n while year_in_range <= self.endDate.year\n year_hash[year_in_range] = BigDecimal(0.0, 10)\n year_in_range += 1\n end\n year_hash\n end", "def hours_per_day(entries)\n hours_per_day = Hash.new(0.0)\n entries.each do |entry|\n hours_per_day[entry[:start].to_date] += (entry[:end] - entry[:start]) / 3600.0\n end\n hours_per_day\nend", "def build_histogram(registration_dttms, &set_time_segment)\n histogram = Hash.new(0)\n registration_dttms.each{|dttm_str| \n dttm = DateTime.strptime(dttm_str, '%m/%d/%y %H:%M')\n time_seg = set_time_segment.call(dttm)\n\n histogram[time_seg]+=1\n }\n histogram.sort_by{|time_seg, freq| freq}.reverse\nend", "def daily_analysis filename\n # Retrieve activity log\n activities = retrieve_log_with_name filename\n\n if not activities then\n return {}\n end\n\n time_spent = {}\n \n # Process each activity\n activities.each do |activity|\n # Parse the activity log\n (name, start_time, end_time) = activity.split(\"\\t\")\n\n # Count the time (if it's a new activity, add it, else, add the times)\n if time_spent.member? name then\n time_spent[name] += Integer(end_time) - Integer(start_time)\n else\n time_spent[name] = Integer(end_time) - Integer(start_time)\n end\n end\n\n # Convert the time to minutes\n time_spent.map { |activity| [activity[0], activity[1]/60] }\nend", "def yearly_occurrences; end", "def commit_activity_score\n return 0 unless @gem_git\n commits_sum = @gem_git.commit_dates_year.reduce(0.0) do |acc, week|\n acc + week\n end\n commits_average = commits_sum / @gem_git.commit_dates_year.length\n score_calculation(commits_average, COMMIT_ACTIVITY_BANDS)\n end", "def daily_activity_duration(activity)\n self.timeblocks_today\n .where(activity_id: activity)\n .sum(:duration) +\n ((Time.now - self.timeblocks_today\n .where(activity_id: activity,\n endtime: nil)\n .first.starttime rescue 0)).to_i\n end", "def build_ics_time(booking)\n times = Hash.new\n start_date = booking.startdate\n end_date = booking.enddate\n start_time = booking.starttime\n end_time = booking.endtime\n\n dtstart = Time.new start_date.year,start_date.month,start_date.day,start_time.hour,start_time.min,start_time.sec\n dtend = Time.new start_date.year,start_date.month,start_date.day,end_time.hour,end_time.min,end_time.sec\n dtstamp = Time.now\n last_modified = Time.now\n\n times.store :dtstart,dtstart.getutc\n times.store :dtend,dtend.getutc\n times.store :dtstamp, dtstamp.getutc\n times.store :last_modified, last_modified.getutc\n\n return times\n\n end", "def calculate_start_and_finish_times!\n # Initialize distance matrix with negative infinity and 0 in the diagonal.\n n = @activities.size\n distance = Array.new(n) { |i| Array.new(n) { |j| i == j ? 0 : -Float::INFINITY } }\n # For all precedences (i,j) set the distance to the duration of i.\n @activities.each do |activity|\n activity.successors.each do |successor|\n distance[activity.id][successor.id] = activity.duration\n end\n end\n # For all activities (use IDs):\n activities = @activities.collect(&:id)\n activities.each do |a|\n # For all pairs (i,j) not including a ...\n ij = activities - [a]\n ij.each do |i|\n # ... and a cost d[i,a] > negative infinity:\n next if distance[i][a] == -Float::INFINITY\n # If the path i->a->j is longer than i->j until now, set i->a->j as new distance between i and j.\n ij.each { |j| distance[i][j] = [ distance[i][j], distance[i][a] + distance[a][j] ].max }\n end\n end\n # Set earliest/latest start/finish times of each activity.\n @activities.each do |a|\n a.earliest_start = distance[0][a.id]\n a.latest_start = -distance[a.id][0]\n a.earliest_finish = a.earliest_start + a.duration\n a.latest_finish = a.latest_start + a.duration\n end\n end", "def getPlayingActivityMap\n \n\n period = params[:period]\n\n case \n when period == \"today\" then\n startDate = endDate = Date.today.to_s\n when period == \"yesterday\" then\n startDate = endDate = (Date.today-1).to_s\n when period == \"pastweek\" then\n startDate = (Date.today-7).to_s\n endDate = Date.today.to_s\n when period == \"ever\" then\n startDate = STARTDATE\n endDate = Date.today.to_s\n else \n startDate = endDate = Date.today.to_s\n end\n\n \n @activity = Hash.new(0)\n \n (startDate..endDate).each do |date|\n (1..100).each do |square|\n @activity[\"#{square}\"] += EntrantLocationAudit.find(:first, :conditions => \"date = '#{date}' AND square_number = '#{square}'\").count \n end\n end\n \n \n # find highest activity key value\n # @highest = @activity.values.max\n \n # case \n # when @highest == 0 then @factor = 1 \n # when @highest > 100 then @factor = @highest.to_f / 100.0\n # when @highest <= 100 then @factor = 100.0 / @highest.to_f \n # end\n \n # unless @activity.empty?\n # (1..100).each do |square|\n # @activity[\"#{square}\"] = (@activity[\"#{square}\"].to_f * @factor).to_i\n # end\n # end\n \n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @activity.to_xml }\n format.amf { render :amf => @activity }\n end\n \n # puts \"Highest: \" + @highest.to_s\n # puts \"Factor: \" + @factor.to_s\n # puts @activity.inspect\n \n end", "def calculate_start_times\n duration_map = published_audio_members.collect do |audio_asset|\n [audio_asset.id, audio_asset.file&.metadata&.dig(\"duration_seconds\")]\n end.to_h\n\n sum = 0\n end_points = duration_map.values.map {|i| sum += i}.map { |i| i.round(3) }\n\n duration_map.keys.zip([0] + end_points)\n end", "def to_hash\n data = {}\n data[:start_date] = TimeUtil.serialize_time(start_time)\n data[:end_time] = end_time if end_time\n data[:duration] = duration if duration\n data[:rrules] = recurrence_rules.map(&:to_hash)\n data[:exrules] = exception_rules.map(&:to_hash)\n data[:rtimes] = recurrence_times.map do |rt|\n TimeUtil.serialize_time(rt)\n end\n data[:extimes] = exception_times.map do |et|\n TimeUtil.serialize_time(et)\n end\n data\n end", "def years_count\n ((@end_date - @start_date).to_f / 365).to_f.round(1)\n end", "def hash\n\t\t\"#{@year}#{@month}\".to_i\n\tend", "def hours_per_year\n hours_per_day * days_per_year\nend", "def hashCode\n @year * daysInYear + ordinalDate\n end", "def activity_on_date_range(activity, start, finish)\n get(\"/user/#{@user_id}/activities/#{activity}/date/#{format_date(start)}/#{format_date(finish)}.json\")\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
TODO decide if this should be calculated from yearly_target_cost
def update_target_cost cost = BigDecimal(0.00, 10) self.activities.each do |activity| cost += activity.targetCost end self.target_cost = cost end
[ "def future_cost(initial_cost, number_of_years, interest_rate)\n initial_cost * (1 + interest_rate) ** number_of_years\n end", "def total_cost_approx\n years_active = @bike_trips.reject { |t| t.end_time.nil? }\n .group_by { |t| t.end_time.year }.map { |y, _| y }\n annual_fees = years_active.map(&method(:annual_cost_for_year))\n annual_fees.reduce(0) { |a, e| a + e }\n end", "def intrinsic_cost()\n return 3\n end", "def annual_cost\n (number_of_positions * hourly_rate * hours_per_week * number_of_weeks)\n end", "def insurance_cost(years)\n years * MORTGAGE_INSURANCE_RATE * required_mortgage\n end", "def idea_cost(v)\n monthly_mixed_monarch_points 5 * -v\n end", "def plan_cost( years )\n\t\tcase years\n\t\twhen 1\n\t\t\tif self.plan_level == \"Small Institution\"\n\t\t\t\treturn 1500\n\t\t\telsif self.plan_level == \"Medium Institution\"\t\n\t\t\t\treturn 1800\n\t\t\telsif self.plan_level == \"Large Institution\"\t\n\t\t\t\treturn 200\n\t\t\tend\n\t\twhen 2\n\t\t\tif self.plan_level == \"Small Institution\"\n\t\t\t\treturn 2700\n\t\t\telsif self.plan_level == \"Medium Institution\"\t\n\t\t\t\treturn 3240\n\t\t\telsif self.plan_level == \"Large Institution\"\t\n\t\t\t\treturn 3600\n\t\t\tend\t\n\t\twhen 3\n\t\t\tif self.plan_level == \"Small Institution\"\n\t\t\t\treturn 3825\n\t\t\telsif self.plan_level == \"Medium Institution\"\t\n\t\t\t\treturn 4590\n\t\t\telsif self.plan_level == \"Large Institution\"\t\n\t\t\t\treturn 5100\n\t\t\tend\t\t\t\t\n\t\tend\t\t\n\tend", "def estimated_cost\n @h + cost\n end", "def standard_cost_code; end", "def insurance_cost(years)\n if pmi_required?\n years * 0.005 * required_mortgage\n else\n 0\n end\n end", "def adjusted_target_income\n (self.target_income * (years_to_retirement * self.avg_inflation_rate)) + self.target_income\n end", "def actual_cost\n self.cost/1000.to_f\n end", "def cost_difference\n cost - estimated_cost\n end", "def calculate_cost(feature_set, theta)\n cost_vectorized = 1.0/(2 * @number_of_training_examples) * (feature_set * theta - @output_set).transpose * (feature_set * theta - @output_set)\n cost_vectorized[0,0]\n end", "def development_cost(v)\n buttons_per_month = 28.0/(1820-1444)/12\n monthly_mixed_monarch_points (buttons_per_month * 65 * -v)\n end", "def cost\n total = 0.0\n not_covered.each do |n|\n total += n.cost\n end\n total\n end", "def marginal_cost\n raise NotImplementedError\n end", "def cost_performance_index\n project.actual_cost(self) != 0 ? project.earned_value(self).to_f / project.actual_cost(self) : 0\n end", "def churn_times_cost\n safe_churn = churn.positive? ? churn : 1\n @churn_times_cost ||= (safe_churn * cost).round(2)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It will fill the hash_record with data from the input file that matches the column_names
def fill_hash_record_from_line(column_names, headers, line) hash_record = {} fields = line.split(@sep) fields.each_with_index do |field, field_id| hash_record[headers[field_id]] = field if column_names.include?(headers[field_id]) end hash_record end
[ "def create_lookup_table\n File.open(source).each_with_index do |line|\n next if line.chomp.empty?\n\n values = unstring(line).chomp.split(';')\n\n next if values.empty?\n\n @joiners.each do |joiner|\n key = values[joiner.join[0]]\n joiner.lookup[:rows][key] = []\n\n joiner.cols.each do |i|\n joiner.lookup[:rows][key] << values[i]\n end\n end\n\n end\n end", "def from_csv old_csv, new_csv, split_string = ',', id_column_number = 0\n\t\t@old_hash = HashCompare::csv_to_hash old_csv, split_string, id_column_number\n\t\t@new_hash = HashCompare::csv_to_hash new_csv, split_string, id_column_number\n\tend", "def build_row_hashes()\r\n FasterCSV.parse(@data, :headers => self.has_header?(), :encoding => 'U') do |row|\r\n collection = @header_row.zip(row)\r\n @row_hashes << collection.inject({}) do |hash, value|\r\n hash[value.first] = value.last\r\n hash\r\n end\r\n end\r\n end", "def build_add_seed_hash(row, column_maps, lookups)\n hsh = {}\n column_maps.each do |db_column,infile_column|\n value = row[infile_column]\n if search_string = lookups[db_column]\n hsh[db_column] = build_lookup(search_string, value)\n else\n hsh[db_column] = value\n end\n end\n hsh\nend", "def load(file,options={})\n lines = CSV.read(file,options)\n header=lines.shift \n @data = lines.collect do |line|\n #convert the line to a record hash\n record = Hash[*header.each_with_index.collect {|h,i| [h,line[i]] }.flatten]\n end\n end", "def hash_creator(filepath)\n hash = Hash.new\n CSV.foreach(filepath, headers: true) do |row|\n student = Student.new(fname = row[0], lname = row[1], email = row[2], section = row[3], major1 = row[4], major2 = row[5], minor1 = row[6], minor2 = row[7])\n if hash.has_key?(student.section)\n array = hash[student.section]\n array.push(student)\n hash[student.section] = array\n else\n array = [student]\n hash[student.section] = array\n end\n end\n return hash\nend", "def set_data_from_hash(data)\n data[:columns].each_with_index do |column_name, index|\n sample_value = data[:rows].first[index]\n add_column(column_type_for_value(sample_value), :id => column_name, :label => column_name)\n end\n set_data_from_array(data[:rows])\n end", "def each_csv_record(filename)\n sheet = CSV.read(filename,liberal_parsing: true, col_sep: \", \")\n keys = sheet[0]\n 1.upto(sheet.size-1).each do |row_index|\n row = sheet[row_index]\n logger.debug \"#{row.inspect}\"\n record = Hash.new\n 0.upto(keys.size-1) do |column|\n record[keys[column]] = row[column]\n end\n logger.debug \"record #{record.inspect}\"\n yield record\n end\n end", "def import_files_into_hash(db, unique_files_hash)\n # get all the records from db\n sql = \"SELECT * FROM files\" \n rows = db.execute sql\n puts \"file records: #{rows.size}\"\n\n num_added = 0\n num_skipped = 0\n\n # process each row, insert into unique_files_hash hash unless the hash already contains that entry\n rows.each do |row|\n key_string = calculate_key_string_for_files_row(row)\n # key = StringHash.sha256(key_string)\n unless unique_files_hash.key? key_string\n # add row to hash\n unique_files_hash[key_string] = create_hash_for_files_row(row)\n num_added += 1\n else\n num_skipped += 1\n end\n end\n puts \"files added: #{num_added}\"\n puts \"files skipped: #{num_skipped}\"\n end", "def buildWeatherRelationHash ()\n\tputs \"Bulidng weather relation hash from weather relation file\"\n\t$weatherRelationHash = Hash.new\n\tjustWeather = File.open(\"WeatherRelationData.csv\", \"r\").each do |line|\n\t\ttemp = line.delete(\"\\n\").split(\",\")\n\t\t$weatherRelationHash[temp[0]] = temp.join(\",\")\n\tend\nend", "def assign_csv_values_to_genericfile(row, generic_file)\n field_mappings = @import.import_field_mappings.where('import_field_mappings.key != ?', 'image_filename')\n field_mappings.each do |field_mapping|\n\n key_column_number_arr = @import.import_field_mappings.where(key: field_mapping.key).first.value.reject!{|a| a.blank? } \n key_column_value_arr = []\n\n # For certain fields the values in the csv are comma delimeted and need to be parsed\n if field_mapping.key == 'subject'\n key_column_number_arr.each do |num|\n key_column_value_arr = key_column_value_arr + (row[num.to_i].try(:split, ',') || [])\n end\n elsif field_mapping.key == 'collection_identifier'\n # it's not a multivalue field so let's just get the first mapping\n key_column_number_arr.each do |num|\n generic_file.collection_identifier = row[num.to_i]\n break\n end\n\n elsif field_mapping.key == 'measurements'\n key_column_number_arr.each do |num|\n measurement_hash = measurement_format_for(row[num.to_i].try(:strip))\n unless measurement_hash.nil?\n #insert field as a measurement object\n measurement = Osul::VRA::Measurement.create(measurement: measurement_hash[:width], measurement_unit: measurement_hash[:unit], measurement_type: \"width\") \n \n generic_file.measurements << measurement\n measurement = Osul::VRA::Measurement.create(measurement: measurement_hash[:height], measurement_unit: measurement_hash[:unit], measurement_type: \"height\") \n generic_file.measurements << measurement\n end\n end\n\n elsif field_mapping.key == 'materials'\n key_column_number_arr.each do |num|\n material_hash = material_format_for(row[num.to_i].try(:strip))\n unless material_hash.nil?\n material = Osul::VRA::Material.create(material_hash)\n generic_file.materials << material\n end\n end\n\n else\n key_column_number_arr.each do |num|\n key_column_value_arr << row[num.to_i]\n end\n end\n\n # materials and measurements are associations so they are updated differently \n unless field_mapping.key == 'materials' or field_mapping.key == 'measurements' or field_mapping.key == 'collection_identifier'\n key_column_value_arr = key_column_value_arr.map.reject{|a| a.blank?}\n generic_file.send(\"#{field_mapping.key}=\".to_sym, key_column_value_arr)\n end\n end\n end", "def populate_fields\n @header = populate_hmap_header\n string_t = @raw_data[header.strings_offset..-1]\n @bucktes = populate_buckets do |bucket|\n bucket_s = bucket.to_a.map do |key|\n string_t[key..-1].match(/[^\\0]+/)[0]\n end\n HMapBucketStr.new(*bucket_s)\n end\n end", "def csv2hash(filename)\n hashes = Array.new\n CSV.foreach( filename, { :headers => true, :header_converters => :symbol } ) do |row|\n hash = Hash.new\n row.each do |key, val| \n hash[key.to_sym] = val\n end\n hashes.push hash \n end\n hashes\n end", "def initial_data_type(filename,chunk,delimiter)\n @headers = Array.new\n @header_datatype = Array.new\n get_keys = false\n @arr_unique = Array.new{hash.new}\n #hash_datatype = {\"int\" => 0, \"float\" => 0, \"date\" => 0, \"string\" => 0}\n @arr_details = Array.new(@no_of_columns){{\"int\" => 0, \"float\" => 0, \"date\" => 0, \"datetime\" => 0, \"string\" => 0}}\n total_chunks = SmarterCSV.process(filename, {:col_sep => delimiter, :chunk_size => chunk, :remove_empty_values => false, :remove_zero_values => false}) do |chunk|\n if(get_keys == false)\n chunk.each do |row| \n @headers = row.keys\n #puts headers[0].to_sym\n get_keys = true\n break\n end\n end\n for i in 0..@headers.length-1\n arr = chunk.map{|x| x[@headers[i].to_sym]}\n if(@arr_unique[i].to_a.empty?)\n @arr_unique[i] = arr\n arr.each do |field|\n field_type = get_datatype(field)\n count = @arr_details[i][field_type]\n @arr_details[i][field_type] = count+1\n\n end\n else\n @arr_unique[i] |= arr\n arr.each do |field|\n field_type = get_datatype(field)\n count = @arr_details[i][field_type]\n @arr_details[i][field_type] = count+1\n end\n end\n end\n break\n end\n #To prepare hash with datatypes of every column to decide on the intial datatypes\n #puts @arr_details.inspect\n @arr_details.each do |hash|\n max_value = 0\n max_value_key = String.new\n hash.each do |key, value|\n if(max_value <= value)\n max_value = value\n max_value_key = key\n end\n end\n if max_value_key == \"int\"\n if hash[\"float\"] != 0\n max_value_key = \"float\"\n end\n end\n max_value_key = \"string\" if hash[\"string\"] != 0\n @header_datatype.push(max_value_key)\n end\n #puts @header_datatype.inspect\n end", "def import_input_data(data)\n\n # clear all the old data\n #InputRecord.delete_all\n\n # grab the table out of the data file\n table = /<table.*?>(.*)<\\/table>/im.match(data.squish)\n # split into array rows based on <tr></tr> and do some cleanup\n tabledata = table[1].gsub(/\\&nbsp;/,\" \").gsub(/ </,\"<\").gsub(/> /,\">\").gsub(/<b>|<\\/b>|<img.*?>|<\\/img>|<span.*?>|<\\/span>|<td.*?>|<a .*?>|<\\/a>/,\"\").scan(/<tr.*?>.*?<\\/tr>/im)\n # split by columns and remove extraneous tags\n tabledata.map!{ |row| row.gsub(/<tr.*?>/,\"\").gsub(/<\\/td><\\/tr>/,\"\").force_encoding(\"UTF-8\").gsub(/\\u{a0}/,\"\").split(\"</td>\")}\n\n data_columns = {\n \"Acronym\" => :acronym,\n \"Title\" => :title,\n \"Organization\" => :organization,\n \"Department\" => :department,\n \"Agency\" => :agency,\n \"RFP #\" => :rfp_number,\n \"Solicitation #\" => :rfp_number,\n \"Program Value\" => :program_value,\n \"Value($k)\" => :program_value,\n \"RFP Date\" => :rfp_date,\n \"Solicitation Date\" => :rfp_date,\n \"Status\" => :status,\n \"User List\" => :user_list,\n \"Project Award Date\" => :project_award_date,\n \"Projected Award Date\" => :project_award_date,\n \"Opportunity Id\" => :input_opportunity_number,\n \"Opp Id\" => :input_opportunity_number,\n \"Contract Type\" => :contract_type,\n \"Contract Type (Combined List)\" => :contract_type_combined,\n \"Primary Service\" => :primary_service,\n \"Contract Duration\" => :contract_duration,\n \"Last Updated\" => :last_updated,\n \"Competition Type\" => :competition_type,\n \"NAICS\" => :naics,\n \"Primary State of Perf.\" => :primary_state_of_performance,\n \"Summary\" => :summary,\n \"Comments\" => :comments,\n \"Latest News\" => :comments,\n \"DOD/Civil\" => :dod_civil,\n \"Incumbent\" => :incumbent,\n \"Contractor\" => :incumbent,\n \"Contractor (Combined List)\" => :contractor_combined,\n \"Incumbent Value\" => :incumbent_value,\n \"Contract Value($k)\" => :incumbent_value,\n \"Incumbent Contract #\" => :incumbent_contract_number,\n \"Contract Number\" => :incumbent_contract_number,\n \"Incumbent Award Date\" => :incumbent_award_date,\n \"Contract Award Date\" => :incumbent_award_date,\n \"Incumbent Expire Date\" => :incumbent_expire_date,\n \"Contract Expire Date\" => :incumbent_expire_date,\n \"Priority\" => :priority,\n \"Vertical\" => :vertical,\n \"Vertical (Combined List)\" => :vertical_combined,\n \"Segment\" => :segment,\n \"Segment (Combined List)\" => :segment_combined,\n \"Key Contacts\" => :key_contacts\n }\n\n # figure out which input columns map to which data columns\n keys = []\n cols = {}\n tabledata[0].each_index do |column|\n keys[column] = data_columns[tabledata[0][column].strip]\n cols[data_columns[tabledata[0][column]]] = column\n# puts \"found #{keys[column]} in #{cols[data_columns[tabledata[0][column]]]}\"\n end\n\n record_count = 0\n\n # load the data\n for row in 1..(tabledata.length-1) # for each row (except the header row)\n# puts \"loading row #{row}\"\n opportunity_number_column = cols[:input_opportunity_number]\n opportunity_number = tabledata[row][opportunity_number_column]\n record = InputRecord.find_or_create_by_input_opportunity_number(opportunity_number) # get the record or make a new one\n keys.each_index do |column| # for each column in the input file, update the attribute\n case keys[column]\n when :title #need special processing for title to split URL from actual title\n if tabledata[row][column] =~ /<a/\n data = /<a href=\"(.*?)\">(.*?)<\\/a>/i.match(tabledata[row][column])\n record.input_url = data[1] unless data[1].nil?\n record.title = data[2] unless data[2].nil?\n else\n record.title = tabledata[row][column]\n end\n when :department\n @dept = tabledata[row][column]\n when :agency\n if tabledata[row][column].nil?\n record.send(\"organization=\", \"#{@dept}\")\n else\n record.send(\"organization=\", \"#{@dept}/#{tabledata[row][column]}\")\n end\n when :rfp_date, :project_award_date, :last_updated, :incumbent_award_date, :incumbent_expire_date\n record.send(\"#{keys[column]}=\",GovwinIQ.fix_input_date(tabledata[row][column]))\n else\n record.send(\"#{keys[column]}=\", tabledata[row][column]) unless keys[column].nil?\n end\n end\n record.save!\n record_count += 1\n end\n\n return record_count\n end", "def read_substitutions(mapfile)\n\n new_map = {}\n\n #for each row in the given mapfile\n CSV.foreach(mapfile, :headers => true, :header_converters => :symbol) do |row|\n\n id_number = row.fields[0]\n\n #parse the row into a new hash element\n new_map[id_number] = row.fields[1]\n \n end\n\n #return the new map\n new_map\n\nend", "def merge_into_hash(file)\n current_fh = open_file(file)\n current_fh.each_line { |line|\n parts = split_line(line)\n next unless parts.length == Mergeit::Config::SUPPORTED_PARTS[:size]\n\n ip = parts[0].strip\n next unless is_ip_addr?(ip)\n\n numbers = parts[1].strip\n next unless is_valid_csv?(numbers)\n\n process_to_hash(ip, numbers.split(Mergeit::Config::NUMBERS[:delimeter]))\n }\n ensure\n current_fh.close\n end", "def init_special_fusion_hash(filename)\n data = Array.new\n \n File.open(filename, \"r\") do |f|\n f.each_line do |line|\n data = line.strip.split(\",\")\n \n # We'll add the demon both ways to make sure we can fuse both ways.\n # Alternatively I could've wrote special_fusion to check both demons\n # for the first key, but I thought this might've been easier.\n add_to_special_hash(data[0], data[1], data[2], data[3], data[4].to_i)\n add_to_special_hash(data[1], data[0], data[2], data[3], data[4].to_i)\n end\n end\n end", "def load_csv(file) \n\t\thash = {}\n\t\tCSV.foreach(file) { |row| hash[row[0]] = row[1] } \n\t\thash\n\tend" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Actively searches for hubs by talking to publisher directly
def discover_hubs_for_topic @hubs = Nelumba.feed_from_url(self.topic_url).hubs end
[ "def get_hubs!\n # TODO\n end", "def ping_hubs\n feed_url = \"#{url}.atom\"\n OPub::Publisher.new(feed_url, hubs).ping_hubs\n end", "def search(q)\n rv = []\n Chef::Search::Query.new.search(:hubs, q) do |z|\n rv << Hub.new(z)\n end\n return rv\n end", "def ping_hubs\n @hubs.each do |hub_url|\n res = Net::HTTP.post_form(URI.parse(hub_url),\n { 'hub.mode' => 'publish',\n 'hub.url' => @topic_url })\n end\n end", "def broadcast_queries\n WebsocketRails[:query].trigger 'all_searches', Query.all.most_frequent\n end", "def subscribe_to_channel; end", "def ping_hubs(feed_url)\n OPub::Publisher.new(feed_url, hubs).ping_hubs\n end", "def search_public_chat(username)\n broadcast('@type' => 'searchPublicChat',\n 'username' => username)\n end", "def search_public_chats(query)\n broadcast('@type' => 'searchPublicChats',\n 'query' => query)\n end", "def hub\n @@message_hub\n end", "def hubs\n link(:hub).map { |link| link.href }\n end", "def broadcast_presence\n services = CouchModels::Service.find_all\n users = services.map {|service| service.users }.flatten.uniq\n nodes = users.map {|jid| available(@stream.jid, jid) }\n nodes << services.map do |service|\n service.users.map {|jid| available(service.jid, jid) }\n end\n nodes.flatten!\n @throttle.async_send(nodes)\n end", "def hubs\n link('hub').map { |link| link.href }\n end", "def publish_for search, data\n each_channels_of search do |channel|\n channel.transmit format(data)\n rescue Errno::ECONNREFUSED, Net::OpenTimeout, SocketError => e\n Rails.logger.info \"Establishing TCP connection to #{channel} failed. Error: #{e.inspect}\"\n end\n end", "def hubs\n if link(:hub)\n link(:hub).map do |link|\n link[:href]\n end\n else\n []\n end\n end", "def listen(m)\n nicks = @registry[:piesacken] || Array.new\n return unless m.address? and nicks.include?(m.sourcenick) \n \n @bot.say m.replyto, \"#{m.sourcenick}, #{insult}\"\n m.ignored = true\n end", "def devices\n @socket.send(search_message, 0, MULTICAST_ADDR, MULTICAST_PORT)\n listen_for_responses(first)\n end", "def broadcast(message)\n clients.matchAll().then do |clients|\n clients.each do |client|\n client.postMessage(message)\n end\n end\nend", "def subscribed\n # stream_from \"some_channel\"\n stream_from \"user_#{user_id}\"\n update_clusters user_id\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subscribe to the topic through the given hub.
def subscribe return unless self.hub.nil? # Discover hubs if none exist @hubs = discover_hubs_for_topic(self.topic_url) if self.hubs.empty? @hub = self.hubs.first change_subscription(:subscribe, token) # TODO: Check response, if failed, try a different hub end
[ "def subscribe(*args)\n params = arguments(args, required: [:topic, :callback]).params\n _merge_action!(\"subscribe\", arguments.topic, arguments.callback, params)\n params['headers'] = HEADERS\n\n post_request(\"/hub\", params)\n end", "def subscribe(_topic, **)\n raise 'not implemented'\n end", "def subscribe!\n @repository.callback_url = pubsubhubbub_callback_url\n\n if @repository.valid?\n begin\n client.subscribe(\n topic,\n @repository.callback_url,\n ENV['PUBSUBHUBBUB_SECRET']\n )\n\n @repository.save\n rescue Octokit::Error => e\n @repository.errors.add(:base, e.message)\n\n false\n end\n end\n end", "def subscribe(topic, url)\n # note: do NOT encode the URL, this is not decoded on the erlang side!\n # (only strings are allowed anyway)\n # url = @conn.class.encode_value(url)\n result = @conn.call(:subscribe, [topic, url])\n @conn.class.process_result_subscribe(result)\n end", "def subscribe(feed, callback)\n RestClient.post(hub, :headers => HEADER, 'hub.mode' => 'subscribe', 'hub.topic' => feed, 'hub.callback' => callback, 'hub.verify' => 'async')\n end", "def subscribe(topic, callback = nil, config = nil)\n\t\tend", "def subscribe!(websocket)\n @sid = channel.subscribe { |msg| websocket.send msg }\n ensure\n log.info(widget_name) { \"Subscribed #{sid} via #{channel}\" }\n end", "def subscribe_to_topic(topic, device)\n raise NotImplementedError.new\n end", "def subscribe(public_ip, public_port = 80)\n fetch if @hub_url.nil?\n hub = PubSubHubbub.new(@hub_url, public_ip, public_port)\n hub.subscribe(self)\n hub.client_thread.join\n end", "def subscribe(*args, &blk)\n (@client ||= connect).subscribe(*args, &blk)\n end", "def subscribe(*topics)\n # Defer subscribing until we are connected\n callback do\n send_packet(\n MQTT::Packet::Subscribe.new(\n :topics => topics,\n :message_id => @message_id.next\n )\n )\n end\n end", "def subscribe(*topics)\n # Defer subscribing until we are connected\n callback do\n send_packet(\n MQTT::Packet::Subscribe.new(\n :id => next_packet_id,\n :topics => topics\n )\n )\n end\n end", "def subscribe(*topics)\n # FIXME: make sure @connection isn't nil\n @connection.subscribe(*topics)\n end", "def subscribe(*topics)\n packet = MQTT::Packet::Subscribe.new(\n :id => next_packet_id,\n :topics => topics\n )\n send_packet(packet)\n end", "def subscribe\n @conn.send_data :opcode => SUBSCRIBE, :channel => @name\n @subscribe_sent = true\n end", "def subscribe(topic, symbol = nil, auth: false, &callback)\n raise 'callback block is required' unless block_given?\n\n @callbacks[topic.to_s] = callback\n\n payload = { op: :subscribe, args: [subscription(topic, symbol)] }\n @faye.send payload.to_json.to_s\n end", "def subscribe_to(topic)\n StreamUser.create(:user => self, :stream_message => topic.stream_messages.last, :source => 'followed') if topic.stream_messages.last\n subscriptions << Subscription.new(:topic => topic)\n end", "def subscribe(arn, endpoint, protocol)\n request({\n 'Action' => 'Subscribe',\n 'Endpoint' => endpoint,\n 'Protocol' => protocol,\n 'TopicArn' => arn.strip,\n :parser => Fog::Parsers::AWS::SNS::Subscribe.new\n })\n end", "def do_subscribe\n subscribe_to(@nodename)\n get_subscriptions\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change our subscription to this topic at a hub. mode: Either :subscribe or :unsubscribe hub_url: The url of the hub to negotiate with token: A token to verify the response from the hub.
def change_subscription(mode) token ||= SecureRandom.hex(32) @tokens << token.to_s # TODO: Set up HTTPS foo res = Net::HTTP.post_form(URI.parse(self.hub), { 'hub.mode' => mode.to_s, 'hub.callback' => @callback_url, 'hub.verify' => 'async', 'hub.verify_token' => token, 'hub.lease_seconds' => '', 'hub.secret' => @secret, 'hub.topic' => @topic_url }) end
[ "def subscribe\n return unless self.hub.nil?\n\n # Discover hubs if none exist\n @hubs = discover_hubs_for_topic(self.topic_url) if self.hubs.empty?\n @hub = self.hubs.first\n change_subscription(:subscribe, token)\n\n # TODO: Check response, if failed, try a different hub\n end", "def subscribe_mode?\n params['hub.mode'] == 'subscribe'\n end", "def subscribe!\n @repository.callback_url = pubsubhubbub_callback_url\n\n if @repository.valid?\n begin\n client.subscribe(\n topic,\n @repository.callback_url,\n ENV['PUBSUBHUBBUB_SECRET']\n )\n\n @repository.save\n rescue Octokit::Error => e\n @repository.errors.add(:base, e.message)\n\n false\n end\n end\n end", "def subscribe(feed, callback)\n RestClient.post(hub, :headers => HEADER, 'hub.mode' => 'subscribe', 'hub.topic' => feed, 'hub.callback' => callback, 'hub.verify' => 'async')\n end", "def subscribe_to_channel; end", "def subscribe(*args)\n params = arguments(args, required: [:topic, :callback]).params\n _merge_action!(\"subscribe\", arguments.topic, arguments.callback, params)\n params['headers'] = HEADERS\n\n post_request(\"/hub\", params)\n end", "def subscribe(topic, url)\n # note: do NOT encode the URL, this is not decoded on the erlang side!\n # (only strings are allowed anyway)\n # url = @conn.class.encode_value(url)\n result = @conn.call(:subscribe, [topic, url])\n @conn.class.process_result_subscribe(result)\n end", "def unsubscribe(topic, callback)\n options = {\n :\"hub.mode\" => \"unsubscribe\",\n :\"hub.topic\" => topic,\n :\"hub.callback\" => callback,\n }\n post(\"/hub\", options, 3, true, true, true)\n true\n end", "def toggle_subscription!\n self.unsubscribed = !unsubscribed\n save\n end", "def subscribe_to(topic)\n StreamUser.create(:user => self, :stream_message => topic.stream_messages.last, :source => 'followed') if topic.stream_messages.last\n subscriptions << Subscription.new(:topic => topic)\n end", "def subscribe(topic, symbol = nil, auth: false, &callback)\n raise 'callback block is required' unless block_given?\n\n @callbacks[topic.to_s] = callback\n\n payload = { op: :subscribe, args: [subscription(topic, symbol)] }\n @faye.send payload.to_json.to_s\n end", "def renew_subscription\n uri = URI(@event_sub_url)\n con = EM::HttpRequest.new(@event_sub_url)\n log :debug, 'Open connection for renewing subscription'\n http = con.setup_request(:subscribe, :head => {\n 'HOST' => \"#{uri.host}:#{uri.port}\",\n 'USER-AGENT' => RUPNP::USER_AGENT,\n 'SID' => @sid,\n 'TIMEOUT' => \"Second-#@timeout\"})\n http.errback do |client|\n log :warn, \"Cannot renew subscription to event: #{client.error}\"\n con.close\n end\n\n http.callback do\n log :debug, 'Close connection'\n con.close\n if http.response_header.status != 200\n log :warn, \"Cannot renew subscribtion to event #@event_sub_url:\" +\n \" #{http.response_header.http_reason}\"\n else\n @timeout = http.response_header['TIMEOUT'].match(/(\\d+)/)[1].to_i ||\n 1800\n set_timer\n log :info, \"Subscription to #@event_sub_url renewed\"\n self << :renewed\n end\n end\n end", "def subscribe(_topic, **)\n raise 'not implemented'\n end", "def subscribe(callback_url)\n @repository.callback_url = callback_url\n\n if @repository.valid?\n begin\n client.subscribe(\n topic,\n callback_url,\n ENV['PUBSUBHUBBUB_SECRET']\n )\n\n @repository.save\n rescue Octokit::Error => e\n @repository.errors.add(:base, e.message)\n\n false\n end\n end\n end", "def subscribe!(websocket)\n @sid = channel.subscribe { |msg| websocket.send msg }\n ensure\n log.info(widget_name) { \"Subscribed #{sid} via #{channel}\" }\n end", "def subscribe(topic, callback = nil, config = nil)\n\t\tend", "def push_subscription(object)\n local_server.subscribe(object)\n synchro_point\n end", "def push_subscription(object)\n\t\tlocal_server.subscribe(object)\n\t\tsynchro_point\n\t end", "def topic=(topic)\n raise 'Tried to set topic on voice channel' if voice?\n\n update_channel_data(topic: topic)\n end" ]
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }