query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
Build a Blocks::Container object given the passed in arguments
def build_block_container(*args, &block) options = args.extract_options! anonymous = false if args.first name = args.shift else name = self.anonymous_block_name anonymous = true end block_container = Blocks::Container.new block_container.name = name.to...
[ "def build_block_container(*args, &block)\n options = args.extract_options!\n name = args.first ? args.shift : self.anonymous_block_name\n block_container = BuildingBlocks::Container.new\n block_container.name = name.to_sym\n block_container.options = options\n block_container.block = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a Blocks::Container object and add it to the global hash of blocks if a block by the same name is not already defined
def define_block_container(*args, &block) block_container = self.build_block_container(*args, &block) blocks[block_container.name] = block_container if blocks[block_container.name].nil? && block_given? block_container end
[ "def define(name, options={}, &block)\n # Check if a block by this name is already defined.\n if blocks[name.to_sym].nil?\n # Store the attributes of the defined block in a container for later use\n block_container = BuildingBlocks::Container.new\n block_container.name = name\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the X509 certificate. If it hasn't been passed in, return a selfsigned one
def to_x509() @cert end
[ "def x509\n begin\n OpenSSL::X509::Certificate.new crt\n rescue\n OpenSSL::X509::Certificate.new\n end\n end", "def certder\n if self.certificate\n @cert ||= OpenSSL::X509::Certificate.new(decode_pem(self.certificate))\n else\n @cert = \"\"\n end\n end", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluates the expression. Uses the postfix representation and integer arithmetic.
def evaluate() # operand stack opStack = [] # iterate over the tokens @postfix.split("").each do |c| # check if an operator if %w[+ - * / ^].include? c # pop the stack for the two operands where # a [operator] b b, a = opStack.pop, opStack.pop ...
[ "def e1311_postfix_evaluator(postfix_input)\n #puts \"Starting new postfix evaluation: #{postfix_input}\"\n stack = Utils::Stack.new\n # Iterate every token\n tokens = postfix_input.split(' ')\n tokens.each_with_index { |token, index|\n # Encounter operator\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
================================================================================= Create the thead process for the Jekyll server Params: +preview+:: the preview
def jekyll_thread preview terminal_add preview, terminal_info(I18n.t('preview.message.start')) Rails.application.executor.wrap do Thread.new do Rails.application.reloader.wrap do Rails.application.executor.wrap do start_jekyll preview end end end e...
[ "def preview_title_and_toc\n preview_path = \"#{PDF_PREVIEW_FOLDER}/preview_title_toc-#{current_cookbook.id}_#{Time.now.to_i}.pdf\"\n session[:preview_filename] = preview_path\n preview = CookbookPreviewWorker.new(\n cookbook: current_cookbook, \n filename: preview_path\n )\n preview.title_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
================================================================================= Start the Jekyll server for a preview Params: +preview+:: the preview
def start_jekyll preview path = get_dest_path preview Dir.chdir path Bundler.with_clean_env do ActiveSupport::Dependencies.interlock.permit_concurrent_loads do begin continue = true # Test if bundle was previously updated out, status = Open3.capture2e("bundle chec...
[ "def jekyll_thread preview\n terminal_add preview, terminal_info(I18n.t('preview.message.start'))\n Rails.application.executor.wrap do\n Thread.new do\n Rails.application.reloader.wrap do\n Rails.application.executor.wrap do\n start_jekyll preview\n end\n end\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /contract_doc_categories GET /contract_doc_categories.json
def index @contract_doc_categories = ContractDocCategory.all respond_to do |format| format.html # index.html.erb format.json { render json: @contract_doc_categories } end end
[ "def get_appcon_categories \n get(\"/appcon.json/categories\")\n end", "def get_appcon_categories \n get(\"/appcon.json/categories\")\nend", "def categories\n connection.get(\"/categories\").body.spot_categories\n end", "def index\n @contractor_categories = ContractorCategory.all\n end"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /contract_doc_categories/1 GET /contract_doc_categories/1.json
def show @contract_doc_category = ContractDocCategory.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @contract_doc_category } end end
[ "def index\n @contract_doc_categories = ContractDocCategory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @contract_doc_categories }\n end\n end", "def get_appcon_categories \n get(\"/appcon.json/categories\")\n end", "def get_appcon_ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /contract_doc_categories/new GET /contract_doc_categories/new.json
def new @contract_doc_category = ContractDocCategory.new respond_to do |format| format.html # new.html.erb format.json { render json: @contract_doc_category } end end
[ "def create\n @contract_doc_category = ContractDocCategory.new(params[:contract_doc_category])\n\n respond_to do |format|\n if @contract_doc_category.save\n format.html { redirect_to contract_doc_categories_path, notice: 'Contract doc category was successfully created.' }\n format.json { re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /contract_doc_categories POST /contract_doc_categories.json
def create @contract_doc_category = ContractDocCategory.new(params[:contract_doc_category]) respond_to do |format| if @contract_doc_category.save format.html { redirect_to contract_doc_categories_path, notice: 'Contract doc category was successfully created.' } format.json { render json: ...
[ "def create\n @doc_category = DocCategory.new(params[:doc_category])\n\n respond_to do |format|\n if @doc_category.save\n format.html { redirect_to doc_categories_path, notice: 'Doc category was successfully created.' }\n format.json { render json: @doc_category, status: :created, location:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /contract_doc_categories/1 PUT /contract_doc_categories/1.json
def update @contract_doc_category = ContractDocCategory.find(params[:id]) respond_to do |format| if @contract_doc_category.update_attributes(params[:contract_doc_category]) format.html { redirect_to @contract_doc_category, notice: 'Contract doc category was successfully updated.' } format...
[ "def update_categories(categories, options = {} )\n options.merge!(:docid => self.docid, :categories => categories)\n resp = @conn.put do |req|\n req.url \"categories\"\n req.body = options.to_json\n end\n\n resp.status \n end", "def create\n @contract_doc_cat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /contract_doc_categories/1 DELETE /contract_doc_categories/1.json
def destroy @contract_doc_category = ContractDocCategory.find(params[:id]) @contract_doc_category.destroy respond_to do |format| format.html { redirect_to contract_doc_categories_url } format.json { head :no_content } end end
[ "def destroy\n @doc_category = DocCategory.find(params[:id])\n @doc_category.destroy\n\n respond_to do |format|\n format.html { redirect_to doc_categories_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @document_category = DocumentCategory.find(params[:id])\n @d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method that checks if an object given to it is an album.
def isa? instance_of?(Album) end
[ "def isa?\n\t\tinstance_of?(Album)\n\tend", "def album_unique?(album_object, artist_object)\n\n albums = self.albums.select{|album| album.artist.present?}\n non_nil_albums = albums.select{|album| album.artist.name == artist_object.name} << album_object.name\n non_nil_albums.length == non_nil_albums.uniq....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create Logger from environment variables. The following environment variables are supported: WEATHER_SAGE_LOG_LEVEL: Log level. One of "fatal", "error", "warning", "info", or "debug". Defaults to "warn". WEATHER_SAGE_LOG_PATH: Path to log file. Defaults to standard error.
def initialize(env) # get log level (default to "warn" if unspecified) log_level = (env.get('LOG_LEVEL', DEFAULT_LEVEL)).upcase # create logger from log path (default to STDERR) super(env.get('LOG_PATH', STDERR)) # set log level (default to WARN) self.level = ::Logger.const_get(log_level) ...
[ "def set_log_level_from_environment\n env_log_level = ENV['LOG_LEVEL']\n\n if !env_log_level.nil? && Logger::Severity.const_defined?(env_log_level.upcase)\n @logger.level = Logger::Severity.const_get(env_log_level.upcase)\n true\n else\n false\n end\n end", "def create_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /organization_contacts POST /organization_contacts.json
def create @organization_contact = OrganizationContact.new(params[:organization_contact]) if params[:id][:org_id].empty? @organization_contact.organization_id = params[:organization_contact][:organization_id] else @organization_contact.organization_id = params[:id][:org_id] end respond...
[ "def create\n @organization_contact = @organization.contacts.new(params[:organization_contact])\n @organization_contact.person.require_validations = true\n\n respond_to do |format|\n if @organization_contact.save\n flash[:notice] = 'Contact was successfully created. '\n if params[:send_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /organization_contacts/1 PUT /organization_contacts/1.json
def update @organization_contact = OrganizationContact.find(params[:id]) org_id = Organization.find_by_company_name(params[:organization_contact][:organization_id]).id respond_to do |format| params[:organization_contact][:organization_id] = org_id if @organization_contact.update_attributes(param...
[ "def update\n @organization_contact = @organization.contacts.find(params[:id])\n @organization_contact.person.require_validations = true\n \n respond_to do |format|\n if @organization_contact.update_attributes(params[:organization_contact])\n flash[:notice] = 'Contact was successfully update...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /custom_workouts POST /custom_workouts.json
def create @custom_workout = @user.custom_workouts.new(params[:custom_workout]) respond_to do |format| if @custom_workout.save # TODO need to get a specific month in there . . . format.html { redirect_to my_fit_wit_fit_wit_workout_progress_path(month: params[:month]), notice: 'Custom work...
[ "def create\n @workout = Workout.new(workout_params)\n @workouts = Workout.all\n\n respond_to do |format|\n if @workout.save\n format.html { redirect_to workouts_url, notice: 'Workout was successfully created.' }\n format.json { render json: @workout.attributes }\n else\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PUT /custom_workouts/1 PUT /custom_workouts/1.json
def update @custom_workout = @user.custom_workouts.find(params[:id]) respond_to do |format| if @custom_workout.update_attributes(params[:custom_workout]) format.html { redirect_to my_fit_wit_fit_wit_workout_progress_path(month: params[:month]), notice: 'Custom workout was successfully updated.' }...
[ "def update\n respond_to do |format|\n if @workout.update(workout_params)\n format.json { render :show, status: :ok, location: @workout }\n else\n format.json { render json: @workout.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n @myworkout = Mywor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removing all odd numbers from an array
def remove_odd_numbers_from_array(a) a.each do |x| if x%2!=0 a.delete x end end return a end
[ "def remove_odd array\n\tarray.reduce [] do |evens, number|\n\t\tif number%2 == 1\n\t\t\tarray.delete number\n\t\tend\n\t\tarray\n\tend\n\n\t# arr.each do |index|\n\t# \tif index.odd? then\n\t# \t\tarr.delete index\n\t# \tend\n\t# end\n\n\n\t# arr.delete_if { |n| n%2 != 0}\nend", "def remove_odd(num_array)\n num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /evaluators GET /evaluators.xml
def index respond_to do |format| format.html # index.html.erb format.xml { render :xml => @evaluators } end end
[ "def index\n authorize Evaluator, :index?\n @evaluators = Evaluator.all.order(id: :asc)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @evaluators }\n end\n end", "def index\n @evaluators = Evaluator.all\n\n respond_to do |format|\n forma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /evaluators/1 DELETE /evaluators/1.xml
def destroy @evaluator.destroy respond_to do |format| format.html { redirect_to(evaluators_url) } format.xml { head :ok } end end
[ "def destroy\n @evaluator = Evaluator.find(params[:id])\n authorize @evaluator, :destroy?\n @evaluator.destroy\n\n respond_to do |format|\n format.html { redirect_to(evaluators_url) }\n format.xml { head :ok }\n end\n end", "def destroy\n @evaluacione = Evaluacione.find(params[:id])\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensures that storeconfigs is present before calling AbstractCollector's evaluate method
def evaluate if Puppet[:storeconfigs] != true return false end super end
[ "def collect_exists?; collect_data_exists? || collect_module_exists?; end", "def prepare\n @stores.each_value do |properties|\n properties[:store].from_hash(properties[:properties]).prepare\n end\n end", "def store_instances(enabled_stores, store_configs)\n fail \"No store...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collect exported resources as defined by an exported collection. Used with PuppetDB
def collect resources = [] time = Puppet::Util.thinmark do t = @type q = @cquery resources = scope.compiler.resources.find_all do |resource| resource.type == t && resource.exported? && (q.nil? || q.call(resource)) end found = Puppet::Resource.indirection. search(...
[ "def export_resources( output_dir )\n\t\t\t\t# No-op by default\n\t\t\tend", "def populate_collection resources\n res=[]\n resources.each do |r|\n res << populate(r)\n end\n return res\n end", "def collect_virtual(exported = false)\n scope.compiler.resources.find_all do |resourc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set an inclusion proc for this mixin. This block is evaluated in the tool class immediately after the mixin is included, and is passed any arguments provided to the `include` directive.
def on_include(&block) self.inclusion = block self end
[ "def include(mixin, *args, **kwargs)\n cur_tool = DSL::Internal.current_tool(self, true)\n return self if cur_tool.nil?\n mod = DSL::Internal.resolve_mixin(mixin, cur_tool, @__loader)\n cur_tool.include_mixin(mod, *args, **kwargs)\n self\n end", "def before_inclusion(&block...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes sure a user cant access the given action Example: assert_user_cant_access(:quentin, "destroy", :listing_id => 1)
def assert_user_cant_access(user, actions, params = {}) assert_user_access_check(false, user, actions, params) end
[ "def assert_admin_user_cant_access(admin_user, actions, params = {})\r\n assert_admin_user_access_check(false, admin_user, actions, params)\r\n end", "def test_edit_an_event_that_is_not_mine\n login_as(\"user_normal\")\n post :edit, :id=>40, :space_id => 'Public'\n assert_equal 'Action not allowed.',...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
upload_file(remote_filepath, remote_filename, local_filedata) remote_filepath: Remote filepath where the file will be uploaded remote_filename: Remote name of the file to be executed ie. boot.ini local_file: File containing the read data for the local file to be uploaded, actual open/read/close done in exploit()
def upload_file(remote_filepath, remote_filename, local_filedata = null) magic_code = "\xdd\xdd" opcode = [6].pack('L') # We create the filepath for the upload, for execution it should be \windows\system32\wbem\mof\<file with extension mof! file = "..\\..\\" << remote_filepath << remote_filename <...
[ "def upload_file(local, remote)\n write_file(remote, ::File.read(local))\n end", "def upload_file(remote, local)\n write_file(remote, ::File.read(local))\n end", "def upload_file!(local_path, remote_path)\n connection.upload(local_path, remote_path)\n nil\n end", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the workflow is completed If the workflow is completed, then we can return the results via rest api
def workflow_complete? return status == WORKFLOW_COMPLETE || status == UPLOADING_RESULTS_SCORE_RUNNING || status == UPLOADING_RESULTS_SCORE_COMPLETE || status == UPLOADING_RESULTS_VCF_RUNNING || status == UPLOADING_RESULTS_VCF_COMPLETE || status == COMPLETE e...
[ "def completed?\n @assessment.status == :complete\n end", "def complete()\n if @status.status == 'running'\n @logger.info \"Workflow #{self.class.name} has completed successfully\"\n @status.finished\n end\n end", "def wf_check_retrieved\n sid = record.submission_id\n data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check if the whole pedia service is complete
def pedia_complete? return status == COMPLETE end
[ "def complete?\n completed_at && response\n end", "def response_incomplete?\n end", "def crawling_complete?\n @completed\n end", "def scrape_finished?\n guidance_urls.for_scraping.all?(&:scrape_finished?)\n end", "def complete?\n xml = @client.get_request(\"/services/search/j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /candidates POST /candidates.json
def create @candidate = current_user.candidates.new(candidate_params) respond_to do |format| if @candidate.save format.html { redirect_to @candidate, notice: 'Candidate was successfully created.' } format.json { render :show, status: :created, location: @candidate } else form...
[ "def create\n @candidate = @election.candidates.build(candidate_params)\n\n respond_to do |format|\n if @candidate.save\n format.html { redirect_to election_candidate_url(@election, @candidate), notice: 'Candidate was successfully created.' }\n format.json { render :show, status: :created, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create empty database file (for new actions)
def create File.open(@db_file, "w" ) do |file| end end
[ "def create_database\n filename = get_database_name(\"Create a new database.\")\n AdapterMenu.new(filename).print_menu\n finish_database_initialization(filename)\n end", "def create_db\n delete_db\n create_tables\n end", "def create_db_cmd!\n # TODO:\n end", "def create_defaul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add new resonance to database (if not exists) body_number: number of new body resonance: array of resonance values type: type of resonance
def add(body_number, resonance, type = 1) if !self.check?(body_number) File.open(@db_file, 'a+') do |db| db.puts(body_number.to_s+';'+type.to_s+';'+resonance.inspect) end true else false end end
[ "def add_recurring_data(request, options)\r\n request.Set(RocketGate::GatewayRequest::REBILL_FREQUENCY, options[:rebill_frequency])\r\n request.Set(RocketGate::GatewayRequest::REBILL_AMOUNT, options[:rebill_amount])\r\n request.Set(RocketGate::GatewayRequest::REBILL_START, options[:rebill_start...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all asteroids in resonances for given interval [start, stop] in body numbers start: start of the interval stop: stop of the interval
def find_between(start, stop) asteroids = Array.new File.open(@db_file, 'r').each do |line| arr = line.split(';') tmp = arr[0].to_i if ((tmp >= start) && (tmp <= stop) ) resonance = arr[1].delete('[').delete(']').split(',').map{|x| x.to_f} asteroids.push(Asteroid.new(arr[0], re...
[ "def spiral_ranges\n Enumerator.new do |yielder|\n yielder << (1..1)\n\n start = 2\n range = 3\n\n loop do\n yielder << (start..(range**2))\n\n start = range**2 + 1\n range += 2\n end\n end\n end", "def extract_intervals(start_time=nil,end_time=nil, min_val=0.8...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all asteroids in given resonance resonance: resonance array
def find_asteroids_in_resonance(c_resonance) asteroids = Array.new File.open(CONFIG['resonance']['db_file'], 'r').each do |line| arr = line.split(';') resonance = arr[1].gsub!('[', '').gsub!(']', '').split(', ').map{|elem| elem.to_f} if ((resonance[0] == c_resonance[0]) && (resonance[1] == c_r...
[ "def find_elements(residues, objects = false)\n elements = Array.new\n \n residues.each do |currentRes|\n element = Array.new\n\n # look around (6 ang) for another related residums\n residues.each do |testRes|\n if not testRes == currentRes\n if currentRes[\"CA\"] and testRes[\"CA\"] and Bio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define the binary tree data by reading the contents of an array. Overwrites exisitng data if called on an existing tree. Considers an empty tree (root = nil) to not contain 'nil' Assumes all items in the data array are of similar, or compatible, data type.
def build_tree(data_array) @root = nil # overwrites tree, even if array is empty data_array.each_with_index do |data, index| if index == 0 @root = Node.new(data) else set_next_node(data) end end end
[ "def build_tree_2(data_array)\n root = nil\n \n data_array.each do |elem|\n node = insert_node(root, nil, elem) \n\troot ||= node\n end\n \n root\nend", "def build_tree(array)\n #Assign first value (at 0 index) as root node, shift removes the first element, so array is shorten by 1\n @root = Node.n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Same method as breadth_first_search, but with debugging output that lists the number nodes visited, and the actual order visited. Note: Handles case where data searched for and tree are not the same type
def breadth_first_search_with_debug(data) search_order = [] # For Debug output queue = [@root] node_match = nil match_found = false until queue.empty? || match_found || @root.nil? cur_node = queue.first next_node_value = cur_node.nil? ? "nil" : cur...
[ "def depth_first_search_pre_order_with_debug(data)\n search_order = [] # For Debug output\n stack = [@root]\n node_match = nil\n match_found = false\n until stack.empty? || match_found || @root.nil?\n cur_node = stack.pop\n next_node_value = cur_node.n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterative PreOrder depthfirst search (Parent > Left Child > Right Child) Returns, from the binary tree, the node which contains 'data' Returns 'nil' if no match is found, or if tree is empty (Root = nil). Note: Handles case where data searched for and tree are not the same type
def depth_first_search_pre_order(data) stack = [@root] node_match = nil match_found = false until stack.empty? || match_found || @root.nil? cur_node = stack.pop if cur_node.value == data match_found = true node_match = cur_node end right = cur_node.right_child ...
[ "def depth_first_search_pre_order_with_debug(data)\n search_order = [] # For Debug output\n stack = [@root]\n node_match = nil\n match_found = false\n until stack.empty? || match_found || @root.nil?\n cur_node = stack.pop\n next_node_value = cur_node.n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Same method as depth_first_search_pre_order (iterative), but with debugging output that lists the number nodes visited, and the actual order visited. Note: Handles case where data searched for and tree are not the same type
def depth_first_search_pre_order_with_debug(data) search_order = [] # For Debug output stack = [@root] node_match = nil match_found = false until stack.empty? || match_found || @root.nil? cur_node = stack.pop next_node_value = cur_node.nil? ? "nil" ...
[ "def test_dfs_pre(tree, data, expect_msg)\n puts \"__________________________________________________________\"\n puts \"__________________________________________________________\"\n puts \"\\nIterative Depth-first-search (pre-order) (with debug) for '#{data}':\"\n puts \"\\nExpected: '#{expect_msg}'\\n \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds an array of text to print binary tree. Each array position is a row of text that represents one level of the tree. Position 0 is level 0 (toplevel, or Root), Position 1 is level 1, etc... (Uses fact that there are 2^n nodes in each level "n", level 0 = root level) This really only works well for smaller trees. T...
def tree_levels_text_array text_rows = [] num_levels = num_tree_levels # set string size for spacing and "nil" nodes (with default if tree too big) max_length = (num_levels > 4) ? 2 : max_node_value_length blank_node = "_" * max_length # text for nil nodes cell_pad = " " * max_length # text ...
[ "def print_tree(node)\r\n return CATEGORY_NOT_FOUND unless node\r\n \r\n result, = print_rec(node) # grab the ASCII string from the array\r\n result.shift # remove the extra vertical bar\r\n puts result.join(\"\\n\") # print the result\r\n end", "def print_tree(lines)\n width = 1\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of all node values in breadthfirst search order. Includes 'nil' nodes, such that the array is a representation of the tree as a complete binary tree (even if the actual binary tree is NOT complete)
def all_node_values_with_nil tree_nodes = [] queue = [@root] queue_all_nil = false # continue adding all child nodes to queue until it contains only nil nodes until queue_all_nil cur_node = queue.first next_value = cur_node.nil? ? nil : cur_node.value tree_nodes << next_value ...
[ "def bfs_with_empty_nodes\n queue = [] # FIFO data structure\n traversal = []\n\n queue.push(self)\n while !queue.all? {|e| e == 'nil'}\n node = queue.shift\n if node != 'nil'\n if node.left\n queue.push(node.left)\n else\n queue.push('nil')\n end\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the number of levels in the binary tree
def num_tree_levels level = 0 num_nodes= all_node_values_with_nil.length # considers tree as 'complete num_nodes_in_full_tree = 2**level until num_nodes_in_full_tree >= num_nodes level += 1 num_nodes_in_full_tree += 2**level end num_tree_levels = level + 1 # (started count at 0)...
[ "def depth\n @levels.size\n end", "def tree_width\n num_branches = 0\n ancestry = self.steps.pluck(:ancestry)\n repeat_ancestry = ancestry.group_by {|e| e}.select { |k,v| v.size > 1}.keys\n repeat_ancestry.each do |value|\n num_branches = num_branches + ancestry.grep(value).size\n end\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sums the series: basem, base(m+1)...base(n1), base(n) Assumes exponents are positive integers, and first_exp 2^0 + 2^1 + 2^2 + 2^3 Returns base^exp, if first_exp = second_exp (trivial case) Returns 'nil' if first_exp > second_exp, or exponents not positivbe integers
def sum_base_to_exponent_series(base, first_exp, second_exp) sum = 0 if (first_exp.is_a?(Integer) && second_exp.is_a?(Integer) && first_exp <= second_exp && first_exp >= 0 && second_exp >= 0) if first_exp == second_exp sum = base**first_exp else ...
[ "def power_digit_sum(base, exponent)\n\t(2 ** 1000).to_s.split(\"\").inject(0) {|sum, n| sum + n.to_i}\nend", "def base_and_exponent( base )\n return [0, 0] if self == 0\n\n f = self.to_f\n exponent = (Math.log(f.abs) / Math.log(base)).floor\n if exponent > MAX_NREADABLE_EXP\n exponent = MAX_NREA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the array of letters, which are left to guess
def letters_to_guess @letters.map do |letter| if @user_guesses.include?(normalize_letter(letter)) letter else nil end end end
[ "def guess\n\t\tcollect_words_of_length\n\t\tputs \"Already guessed letters by computer: #{@guessed_letters}\"\n\t\t@guessing_letter = nil\n\t\twhile @guessing_letter == nil || invalid?(@guessing_letter)\n\t\t\t@guessing_letter = guessing_letter\n\t\tend\n\t\t@guessed_letters << @guessing_letter\n\t\t@guessing_lett...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method plays the letter, chosen by user it puts the letter into the array of user guesses
def play!(letter) if !over? && !@user_guesses.include?(letter) @user_guesses << normalize_letter(letter) end end
[ "def guess\n\t\tputs \"Already guessed letters: #{@guessed_letters.join(\", \")}\"\n\t\tguess = nil\n\t\twhile guess == nil || invalid?(guess)\n\t\t\tputs \"#{self.name}, please take a guess: \"\n\t\t\tguess = gets.chomp.downcase\n\t\t\tif invalid?(guess)\n\t\t\t\tputs \"Your guess is invalid. It must be one letter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the method merges the letters to the word
def word @letters.join end
[ "def merge_word word\n self << \" #{word}\" unless split.include? word\n self\n end", "def insertions\n new_words = []\n @words.each do |word|\n @word = word || '' \n (length + 1).times do |i|\n ('a'..'z').each { |c| new_words << \"#{@word[0...i]}#{c}#{@word[i..-1]}\" ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Task body for the :docs_debug task
def do_docs_debug( task, args ) self.prompt.say( "Docs are published to:", color: :bright_green ) if ( publish_url = self.publish_to ) self.prompt.say( self.indent(publish_url, 4) ) else self.prompt.say( self.indent("n/a"), color: :bright_yellow ) end self.prompt.say( "\n" ) end
[ "def doc_task; end", "def define_debug_tasks\n\t\ttask( :base_debug ) do\n\t\t\tself.output_documentation_debugging\n\t\t\tself.output_project_files_debugging\n\t\t\tself.output_dependency_debugging\n\t\tend\n\n\t\ttask :debug => :base_debug\n\tend", "def rdoc_task_description\n 'Build RDoc HTML files'\n en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets Socket options to allow for multicasting. If ENV["RUBY_TESTING_ENV"] is equal to "testing", then it doesn't turn off multicast looping.
def setup_multicast_socket set_membership(IPAddr.new(MULTICAST_IP).hton + IPAddr.new('0.0.0.0').hton) set_multicast_ttl(@ttl) set_ttl(@ttl) unless ENV["RUBY_TESTING_ENV"] == "testing" switch_multicast_loop :off end end
[ "def setup_multicast_socket\n set_membership(IPAddr.new(MULTICAST_IP).hton + IPAddr.new('0.0.0.0').hton)\n set_multicast_ttl(@ttl)\n set_ttl(@ttl)\n\n unless ENV[\"RUBY_UPNP_ENV\"] == \"testing\"\n switch_multicast_loop :off\n end\n end", "def setsockopt(*args)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The MD5 digest of the response body
def md5 headers['Content-MD5'] end
[ "def md5\n return self.body_data.md5\n end", "def md5_of_body\n data[:md5_of_body]\n end", "def digest(body)\n Digest::MD5.hexdigest body[9...35]\n end", "def content_md5\n headers['Content-MD5']\n end", "def md5\n reply.getMd5\n end", "def md5\n if @data_hash['m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all existing volumes that belong to this cluster and cram their metadata into the existing logical volume
def adopt_existing_volumes! Volume.all.each do |ec2_vol| next if ec2_vol.deleted? || ec2_vol.deleting? instance = Instance.find(ec2_vol.attached_instance_id) ; p instance ; next unless instance cluster_node_id = instance.get_cluster_node_id(self.name) ; next unless cluster_node_id ...
[ "def composite_volumes\n vols = {}\n facet.volumes.each do |vol_name, vol|\n self.volumes[vol_name] ||= Ironfan::Volume.new(:parent => self, :name => vol_name)\n vols[vol_name] ||= self.volumes[vol_name].dup\n vols[vol_name].reverse_merge!(vol)\n end\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Automatically embeds the RPXNow Javascript once.
def has_rpxnow return if defined?(@has_rpxnow) && @has_rpxnow rpxnow_js = "#{request.ssl? ? 'https://' : 'http://static.'}rpxnow.com/js/lib/rpx.js" has_js rpxnow_js @has_rpxnow = true end
[ "def inject_js; end", "def google_ajax_slideshow_scripts\n return '' if defined?(@google_ajax_slideshow_scripts_included)\n @google_ajax_slideshow_scripts_included = true\n '<script src=\"http://www.google.com/uds/solutions/slideshow/gfslideshow.js\" type=\"text/javascript\"></script>'.html_safe\n end",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies that product is a common multiple of every number up to num
def check_number(num, product) result = true (1..num).each do |number| if product % number != 0 result = false break end end return result end
[ "def check_product?(array, n)\n if array.length<3\n return false\n end\n for i in 0..array.length-3 do\n for j in i..array.length-2 do\n for k in j..array.length-1 do\n if (array[i]*array[j]*array[k])==n\n return true\n end\n end\n end\n end\n return false\nend", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the smallest common multiple of all numbers 1num
def find_smallest_common_multiple(num) primes = find_primes_under(num) product = factorial(num) counter = 0 while counter < primes.size while check_number(num, product) product = product / primes[counter] end product = product * primes[counter] counter += 1 end product end
[ "def smallest_multiple(num)\n array = 1.upto(num).map {|x| x}.reverse\n array.reduce(:lcm)\nend", "def smallest_common_multiple(n)\n\n\treturn 0\nend", "def smallest_multiple\n\tlcm = 1\n\n\t(2..20).each do |x|\n\t\tlcm *= x / gcd(lcm, x)\n\tend\n\n\tlcm\n\t\nend", "def smallest_multiple(input)\n placeho...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open the TDB file. Accepts a URI and list of open modes: db = TokyoModel::Adapters::File.new("file:///tmp/database.tdb", :read, :write, :create, :trunc)
def initialize(uri, *args) @db = TokyoCabinet::TDB::new @db.open(uri.path, args.empty? ? File.default_open_mode : File.open_mode(*args)) end
[ "def open\n close\n @db = SQLite3::Database.new(@options[:filename])\n self\n end", "def open(options)\n @db ||= options[:connection]\n return @db if @db\n\n if options[:path] && !File.exist?(options[:path])\n @db = SQLite3::Database.new(options[:path])\n setup\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an array of open mode symbols and returns the mode number: open_mode(:read, :write, :sync) 3 open_mode(:read, :write, :sync) 67
def open_mode(*modes) modes.inject(0) { |memo, obj| memo | OPEN_MODES[obj.to_sym].to_i } end
[ "def modes\n mode_codes.keys\n end", "def get_mode(path)\n return unless supports_acl?(path)\n\n owner_sid = get_owner(path)\n group_sid = get_group(path)\n well_known_world_sid = Win32::Security::SID::Everyone\n well_known_nobody_sid = Win32::Security::SID::Nobody\n\n with_privilege(SE_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
send a pdu, receives a pdu
def send(pdu) log { "sending request..." } log(level: 2) { pdu.to_hex } encoded_request = pdu.to_der log { Hexdump.dump(encoded_request) } encoded_response = @transport.send(encoded_request) log { "received response" } log { Hexdump.dump(encoded_response) } response_pdu =...
[ "def process_pdu(pdu)\n case pdu\n when Pdu::DeliverSm\n write_pdu(Pdu::DeliverSmResponse.new(pdu.sequence_number))\n logger.debug \"ESM CLASS #{pdu.esm_class}\"\n if pdu.esm_class != 4\n # MO message\n if @delegate.respond_to?(:mo_received)\n @delegate.mo_received(self, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deploys the given app_id on the given instance_id in the given stack_id Blocks until AWS confirms that the deploy was successful Returns a Aws::OpsWorks::Types::CreateDeploymentResult
def deploy(stack_id:, app_id:, instance_id:, revision:, deploy_timeout: 1800) # App IDs can be passed as a CSV to deploy multiple apps in the same stack app_ids = app_id.split(",") deploy_id = [] app_ids.each do |id| # Update the branch/revision to the given parameter, if any. unless revisi...
[ "def deploy_stack()\n\n\tmanifest = get_manifest()\n\tputs \"Deploying \" + manifest['StackName'] + \" to region \" + manifest['Region']\n\tcf_client = Aws::CloudFormation::Client.new(region: manifest['Region'], profile: ENV['AWS_DEFAULT_PROFILE'])\n\n\tstack = get_stack(manifest['StackName'], manifest['Region'], c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Polls Opsworks for timeout seconds until deployment_id has completed
def wait_until_deploy_completion(deployment_id, timeout) started_at = Time.now Timeout::timeout(timeout) do @opsworks_client.wait_until( :deployment_successful, deployment_ids: [deployment_id] ) do |w| # disable max attempts w.max_attempts = nil end end en...
[ "def _wait_until_deployed(deployment_id, timeout)\n opsworks_client.wait_until(:deployment_successful, deployment_ids: [deployment_id]) do |w|\n w.before_attempt do |attempt|\n puts \"Attempt #{attempt} to check deployment status\".light_black\n end\n w.interval = 10\n w.ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a Aws::OpsWorks::Types::Instance Detaches the provided instance from all of its load balancers Returns the detached load balancers as an array of Aws::ElasticLoadBalancing::Types::LoadBalancerDescription Blocks until AWS confirms that all instances successfully detached before returning Does not wait and instead ...
def detach_from_elbs(instance:) unless instance.is_a?(Aws::OpsWorks::Types::Instance) fail(ArgumentError, "instance must be a Aws::OpsWorks::Types::Instance struct") end all_load_balancers = @elb_client.describe_load_balancers .load_balancer_descriptions load_balancers...
[ "def detach_from(load_balancers, instance)\n check_arguments(instance: instance, load_balancers: load_balancers)\n\n load_balancers.select do |lb|\n matched_instance = lb.instances.any? do |lb_instance|\n instance.ec2_instance_id == lb_instance.instance_id\n end\n\n if matched_instance &...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts load_balancers as array of Aws::ElasticLoadBalancing::Types::LoadBalancerDescription and instances as a Aws::OpsWorks::Types::Instance Returns only the LoadBalancerDescription objects that have the instance attached and should be detached from Will not include a load balancer in the returned collection if the s...
def detach_from(load_balancers, instance) check_arguments(instance: instance, load_balancers: load_balancers) load_balancers.select do |lb| matched_instance = lb.instances.any? do |lb_instance| instance.ec2_instance_id == lb_instance.instance_id end if matched_instance && lb.instance...
[ "def detach_from_elbs(instance:)\n unless instance.is_a?(Aws::OpsWorks::Types::Instance)\n fail(ArgumentError, \"instance must be a Aws::OpsWorks::Types::Instance struct\")\n end\n\n all_load_balancers = @elb_client.describe_load_balancers\n .load_balancer_descriptions\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an instance as a Aws::OpsWorks::Types::Instance and load balancers as an array of Aws::ElasticLoadBalancing::Types::LoadBalancerDescription Attaches the provided instance to the supplied load balancers and blocks until AWS confirms that the instance is attached to all load balancers before returning Does nothing ...
def attach_to_elbs(instance:, load_balancers:) check_arguments(instance: instance, load_balancers: load_balancers) if load_balancers.empty? log("No load balancers to attach to") return {} end @lb_wait_params = [] registered_instances = {} # return this load_balancers.each do |lb| ...
[ "def attach_to_elb(instance, elb_name, subnet = nil)\n begin\n @log.info \"\"\n @log.info \"Adding to ELB: #{elb_name}\"\n elb = AWS::ELB.new\n AWS.memoize do\n unless subnet\n # Build list of availability zones for any existing instances\n zones = { }...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The value of the next element in the Sequence. The sequence goes back to the first element if there are no more elements.
def next if @elements and not @elements.empty? @index = (@index + 1) % @elements.length element = @elements[@index] value = value_of(element) @element, @value = element, value end @value end
[ "def next()\n result = current\n @index += 1\n @got_next_element = false\n @next_element = nil\n result\n end", "def next(val, options = {})\n i = self.index(val)\n return val if i.nil?\n\n i == self.size-1 ?\n (options[:cycle] == true ? self.first : val) : self[i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
def set_variant return unless params[:variant].in?(%w(phone tablet desktop)) request.variant = params[:variant].to_sym end o tambien se puede por medio del user_agent:
def set_variant # request.variant = :phone if request.user_agent.include?('iPhone') # o con la gema browser request.variant = :phone if browser.device.mobile? end
[ "def set_request_variant\n request.variant = :mobile if request.user_agent =~ /android|Android|blackberry|iphone|ipod|iemobile|mobile|webos/\n request.variant = :android_app if request.user_agent =~ /AndroidApp/\n puts \"--------------\"+request.variant.to_s+\"--------------\"\n end", "def set_variant\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new Recipe options Params for creating the recipe label label for the recipe description description for the recipe compatible_with recipe compatiblity (windows or unix) script_type specify script type for windows compatible (bat, vps, powershell) Returns a hash
def create(options = {}) optional = [:description, :compatible_with, :script_type ] params.required(:label).accepts(optional).validate!(options) response = request(:post, "/recipes.json", default_params(options)) response['recipe'] end
[ "def script_type\n case @script.type\n when :hash160\n 'pubkeyhash'\n when :pubkey\n 'pubkey'\n when :multisig\n 'multisig'\n when :p2sh\n 'scripthash'\n when :op_return\n 'nulldata'\n when :witness_v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Edit a Recipe id ID of the recipe options Params for creating recipe, see 'create' method Returns a Hash.
def edit(id, options = {}) optional = [:label, :description, :compatible_with, :script_type ] params.accepts(optional).validate! options request(:put, "/recipes/#{id}.json", default_params(options)) end
[ "def edit(id, recipe_step_id, options = {})\n \toptional = [:script,\n \t\t\t\t\t\t\t:result_source,\n :pass_anything_else,\n :pass_values,\n :on_success,\n :success_goto_step,\n :fail_anything_else,\n :fail_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete a Recipe id ID of the recipe Returns a Hash.
def delete(id) request(:delete, "/recipes/#{id}.json") end
[ "def delete(id, recipe_step_id)\n \trequest(:delete, \"/recipes/#{id}/recipe_steps/#{recipe_step_id}.json\")\n end", "def recipe_delete # /v1/user/:id/recipes/:recipe_id (DELETE)\n params[:recipes] = params[:recipe_id]\n recipes_delete\n end", "def delete(id)\n begin\n @db.execute...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets all rules that respond to a char in a given state.
def rules_for(state, char) rules.select { |rule| rule.applies_to?(state, char) } end
[ "def rule_for(state, character)\n self.rules.detect{ |rule| rule.applies_to?(state, character) } #detect == find\n end", "def get_transitions(state, char)\n transition = @transition_table[state][char]\n if transition\n return [transition]\n else\n return []\n end\n end", "def ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Support functions Run the jekyll command, with arguments (symbols are long options, hashes are long options with arguments)
def jekyll(*directives) directives.map! do |x| case x when Symbol "--#{x}" when Hash x.map { |k, v| "--#{k}=#{v}" }.join(' ') else x end end sh "jekyll #{directives.join(' ')}" end
[ "def jekyll(options = '')\n system(\"bin/jekyll #{options}\")\nend", "def jekyll\n\tfile_name_map = prepare_jekyll\n\tcreate_help_script(file_name_map)\n\trun_jekyll\nend", "def jekyll(opts = '')\n system 'rm -rf _site'\n system 'bundle exec jekyll ' + opts\nend", "def start_jekyll preview\n path = ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /passwordrecovery/recover/:token The page where the user lands coming from the password recovery email
def recover @user = User.find_by password_reset_digest: params[:token] if !@user flash[:alert] = 'Invalid link' redirect_to '/password-recovery/remind-password' return end @token = params[:token] end
[ "def recover\n account = Account.find_by_email_address(params[:email_address])\n if account\n account.is_pending_recovery!\n Mailer.deliver_recovery(:site => @authenticated_site, :account => account)\n head :ok\n else\n head :not_found\n end\n end", "def recovery_url(token_id)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if current recipient able to receive freeform text
def able_to_send_freeform_text? last_inbound_message = messages.inbound.last return false unless last_inbound_message last_inbound_message.created_at + 24.hours >= Time.zone.now end
[ "def appellant_is_recipient?\n virtual_hearing_updates.key?(:appellant_email_sent)\n end", "def verify_banned_message\n if sender.banned?\n self.body = \"This user’s messages have been removed because #{sender.the_sex_prefix} activities violates the LoveRealm community standards. Do not correspond wit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks for messaging platform based on their `number` column whatsapp 'whatsapp:+60123456789' sms '+60123456789' messenger 'messenger:123456789'
def platform case number when /whatsapp/ 'whatsapp' when /messenger/ 'messenger' else 'sms' end end
[ "def read_extension_phone_number_detect_sms_feature()\n begin\n endpoint = \"/restapi/v1.0/account/~/extension/~/phone-number\"\n resp = $platform.get(endpoint)\n for record in resp.body['records'] do\n for feature in record['features'] do\n if feature == \"SmsSender\"\n # If user has...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /stuk_todo_tasks POST /stuk_todo_tasks.json
def create @stuk_todo_task = current_user.stuk_todo_tasks.new(stuk_todo_task_params) respond_to do |format| if @stuk_todo_task.save format.html { redirect_to @stuk_todo_task, notice: 'Stuk todo task was successfully created.' } format.json { render :show, status: :created, location: @stuk...
[ "def create\n #@task = Task.new(task_params)\n task = @task_list.tasks.create!(task_params)\n render json: task\n end", "def create\n @todo_task = TodoTask.new(params[:todo_task])\n\n respond_to do |format|\n if @todo_task.save\n format.html { redirect_to @todo_task, notice: 'Todo task...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks the passedin password against the saved admin salt and hash.
def admin_authenticate?(password) salt = get_setting(:admin_pass_salt, "") hash = get_setting(:admin_pass_hash, "") hash == BCrypt::Engine.hash_secret(password, salt) end
[ "def check_password(password)\n @password = password\n @hsh == get_hash\n end", "def check_password(pass, hash)\n DjangoHash.parse(hash).check_password(pass)\n end", "def check(password, store)\n hash = get_hash(store)\n salt = get_salt(store)\n self.hash(password, salt) == hash\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves all of the settings using the passedin params.
def save(params) save_admin_pass(params[:admin_pass]) save_setting(:site_name, params[:site_name]) save_setting(:navbar_bg_color, params[:navbar_bg_color]) save_setting(:navbar_font_color, params[:navbar_font_color]) save_setting(:navbar_border_color, params[:navbar_border_color]) save_set...
[ "def save_settings\n (params[:setting] || []).each do |key, val|\n setting = Setting.find_by_key(key)\n setting = Setting.create!(key: key) unless setting\n if val.is_a?(ActionDispatch::Http::UploadedFile) # image setting value\n setting.update(image: val)\n else # text set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the value of the setting with the passedin key, otherwise, default.
def get_setting(key, default) setting = Setting.where(key: key).first setting && !setting.value.blank? ? setting.value : default end
[ "def get_or_default(key)\n fetch_and_store(key, SettingAccessors.setting_class.get_or_default(key, @record))\n end", "def [](key)\n setting_obj = setting(key)\n setting_obj ? setting_obj.value : nil\n end", "def get(key, default: nil)\n data[key.to_s] || default\n end", "def get(key...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the settings with the passedin key and val.
def save_setting(key, val) # Check for nil, since unchecked checkboxes don't send a value. # Check for whether a boolean, since .blank? returns true for false. # Check for a blank string. if val == nil || !!val == val || !val.blank? setting = Setting.where(key: key).first_or_create set...
[ "def save_setting(key_name, value)\n ini = Rex::Parser::Ini.new(self.config_file)\n ini.add_group(self.group_name) if ini[self.group_name].nil?\n ini[self.group_name][key_name] = value\n ini.to_file(self.config_file)\n end", "def []=(key, value)\n # Let's play nice with strings and non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves the admin password salt, hash, and whether the password exists.
def save_admin_pass(val) if val != ADMIN_PASS pass_salt = BCrypt::Engine.generate_salt pass_hash = BCrypt::Engine.hash_secret(val, pass_salt) save_setting(:admin_pass_salt, pass_salt) save_setting(:admin_pass_hash, pass_hash) save_setting(:is_admin_pass, true) end end
[ "def save_password(pw)\n pw_hash = pw.to_h\n existing = db.execute('SELECT bcrypt_salt FROM master_password WHERE id = 1')\n if existing.empty?\n db.execute('INSERT INTO master_password (id, bcrypt_salt, pbkdf2_salt, test_encryption) VALUES ( 1, ?, ?, ? )',\n hash_to_array(pw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the recommendations made by some user
def user recommendations 'user' end
[ "def recommendations\n if is_user?\n @recommendations ||= Hashie::Mash.new(self.class.get(\"/recommendations/#{@username}/#{@api_key}.json\")).recommendations\n end\n end", "def recommendations_for(active_user)\n recommend_by_user_based active_user\n end", "def recommendations\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
the recommendations made about some location
def location recommendations 'location' end
[ "def recommendations\n check_preference_setup \n check_last_played_time\n add_personality_recommendations\n\n @recommendations\n end", "def recommendation\n return @recommendation\n end", "def process_restaurants_search_result(doc, (prefecture, area1, area2), source_url, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The cached formatter instance. If there's none, one will be created.
def formatter @formatter ||= Formatters::Default.new end
[ "def formatter\r\n @formatter ||= SimpleFormatter.new\r\n end", "def initialize\n @formatter = method(:default_formatter)\n end", "def formatter\n\t\treturn ( @formatter || @default_formatter )\n\tend", "def get_formatter(sym, options)\n cls_name = sym.to_s.gsub(/_(\\w)/) {|m| m[1].upcase }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /gigapans GET /gigapans.json
def index @gigapans = Gigapan.all end
[ "def show\n @gig = Gig.find(params[:id])\n\n render json: @gig\n end", "def show\n @gig = Gig.find(params[:id])\n\n respond_to do |format|\n format.html {render json: @gig, status: :ok}\n format.json { render json: @gig, status: :ok }\n end\n end", "def show\n\n @gig = Gig.find(par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /gigapans POST /gigapans.json
def create @gigapan = Gigapan.new(gigapan_params) respond_to do |format| if @gigapan.save format.html { redirect_to @gigapan, notice: 'Gigapan was successfully created.' } format.json { render :show, status: :created, location: @gigapan } else format.html { render :new } ...
[ "def create\n @gig = Gig.new(params[:gig])\n\n if @gig.save\n render json: @gig, status: :created, location: @gig\n else\n render json: @gig.errors, status: :unprocessable_entity\n end\n end", "def create\n @gig = Gig.new(params[:gig])\n\n respond_to do |format|\n if @gig.save\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the value of the resource placeholder has been set yet.
def set_yet? !!@resource_lock.synchronize { defined? @resource } end
[ "def placeholder?(value)\n value == PLACEHOLDER\n end", "def verify_if_root_template_is_set!\n raise IncompleteResource, 'Must set a valid root template' if self['rootTemplateUri'].nil? || self['properties'].nil?\n end", "def is_placeholder?(fieldname)\n self.class.placeholders.includ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the attempt to read the resource has been terminated.
def terminated? !!@resource_lock.synchronize { @terminated } end
[ "def closed_read?\n !@readable\n end", "def closed_read?() end", "def ready_for_read?\n begin\n connected? && IO.select([socket], nil, nil, 0.1)\n rescue Exception\n triggered_close $!.message, :terminated\n raise\n end\n end", "def finished_reading?; @finished_read; end", "def ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A peak is an array element which is larger than its neighbours. More precisely, it is an index P such that 0 A[P + 1]. For example, the following array A: ``` A[0] = 1 A[1] = 5 A[2] = 3 A[3] = 4 A[4] = 3 A[5] = 4 A[6] = 1 A[7] = 2 A[8] = 3 A[9] = 4 A[10] = 6 A[11] = 2 ``` has exactly four peaks: elements 1, 3, 5 and 10...
def solution(a) peaks = find_peaks(a) return 0 if peaks.empty? min_flags = 1 max_flags = Math.sqrt(a.length).ceil + 1 while min_flags != max_flags mid_flags = min_flags + ((max_flags-min_flags)/2.0).ceil if check(peaks, mid_flags) min_flags = mid_flags else max_flags = mid_flags-1 ...
[ "def solution(a)\n nexxt = next_peak(a)\n f = 1 # can we set f flags?\n max_flags = 0\n # (f-1) * f = max distance between first and last flags\n while (f - 1) * f <= a.size\n pos = 0\n flags_so_far = 0\n while pos < a.size && flags_so_far < f\n pos = nexxt[pos]\n break if pos == -1\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
callseq: File.mime( string ) > string or array See also: File::magic and File::type
def mime(path) magic(path, Magic::MIME) end
[ "def mime_type(filename, mime_tab); end", "def mime_exts; end", "def magic_mime_type\n return if new_record?\n return unless File.exists? io_stream.path\n FileMagic.mime.file(io_stream.path).split(/;\\s*/).first\n end", "def mime_type\n Mime::Type.lookup(file_content_type)\n end", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if two points are equal with some degree of variance
def bbpFuzzyEqual(first_point, second_point, variance) if first_point.x - variance <= second_point.x and second_point.x <= first_point.x + variance if first_point.y - variance <= second_point.y and second_point.y <= first_point.y + variance return true end end ...
[ "def jbpFuzzyEqual(first_point, second_point, variance)\n if first_point.x - variance <= second_point.x and second_point.x <= first_point.x + variance\n if first_point.y - variance <= second_point.y and second_point.y <= first_point.y + variance\n return true\n end\n end\n\n fa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rotates a point counterclockwise by the angle around the pivot
def bbpRotateByAngle(first_point, pivot_point, angle) rotation_point = bbpSub(first_point, pivot_point) cosine = Math.cos(angle) sine = Math.sin(angle) rotation_point.x = rotation_point.x * cosine - rotation_point.y * sine + pivot_point.x rotation_point.y = rotation_point.y * ...
[ "def jbpRotateByAngle(first_point, pivot_point, angle)\n rotation_point = jbpSub(first_point, pivot_point)\n cosine = Math.cos(angle)\n sine = Math.sin(angle)\n\n rotation_point.x = rotation_point.x * cosine - rotation_point.y * sine + pivot_point.x\n rotation_point.y = rotation_point.y * s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The defaults for the params according to GEOS are as found in Geos::Constants::BUFFER_PARAMS_DEFAULTS. Note that when setting the :quad_segs value that you should set it before setting other values like :join and :mitre_limit, as GEOS contains logic concerning how the :quad_segs value affects these parameters and vice ...
def initialize(params = {}) params = Geos::Constants::BUFFER_PARAM_DEFAULTS.merge(params) ptr = FFIGeos.GEOSBufferParams_create_r(Geos.current_handle_pointer) @ptr = FFI::AutoPointer.new( ptr, self.class.method(:release) ) @params = {} VALID_PARAMETE...
[ "def add_spatial_params(solr_params)\n if blacklight_params[:bbox]\n solr_params[:bq] ||= []\n solr_params[:bq] << \"#{Settings.FIELDS.GEOMETRY}:\\\"IsWithin(#{envelope_bounds})\\\"#{boost}\"\n solr_params[:fq] ||= []\n solr_params[:fq] << \"#{Settings.FIELDS.GEOMETRY}:\\\"Intersect...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array of system page settings for a given page, or nil if the page is not a system page.
def system_pages(pageid) pages = Array.new if self.site_default_page_id == pageid pages << "Site default page" end if self.not_found_page_id == pageid pages << "Not found page" end if self.permission_denied_page_id == pageid pages << "Permission denied page" end if...
[ "def system_pages(pageid)\n pages = []\n\n pages << \"Site default page\" if self.site_default_page_id == pageid\n pages << \"Not found page\" if self.not_found_page_id == pageid\n pages << \"Permission denied page\" if self.permission_denied_page_id == pageid\n pages << \"Session expired page\" if s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /bet_events GET /bet_events.json
def index @bet_events = BetEvent.all end
[ "def events\n response = self.class.get('/v1/events.json')\n response.code == 200 ? JSON.parse(response.body) : nil\n end", "def get_events\n Resources::Event.parse(request(:get, \"Events\"))\n end", "def get_events()\n @client.make_request(:get, @client.concat_user_path(\"#{CALL_PATH}...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /bet_events POST /bet_events.json
def create @bet_event = BetEvent.new(bet_event_params) respond_to do |format| if @bet_event.save format.html { redirect_to @bet_event, notice: 'Bet event was successfully created.' } format.json { render :show, status: :created, location: @bet_event } else format.html { rend...
[ "def create\n @xbet_event = Xbet::Event.new(xbet_event_params)\n\n respond_to do |format|\n if @xbet_event.save\n format.html { redirect_to @xbet_event, notice: 'Event was successfully created.' }\n format.json { render :show, status: :created, location: @xbet_event }\n else\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /bet_events/1 PATCH/PUT /bet_events/1.json
def update respond_to do |format| if @bet_event.update(bet_event_params) format.html { redirect_to @bet_event, notice: 'Bet event was successfully updated.' } format.json { render :show, status: :ok, location: @bet_event } else format.html { render :edit } format.json { r...
[ "def update\n #TODO params -> strong_params\n if @event.update(params)\n head :no_content\n else\n render json: @event.errors, status: :unprocessable_entity\n end\n end", "def update\n respond_to do |format|\n if @event.update(event_params)\n format.json { head :no_content }\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /bet_events/1 DELETE /bet_events/1.json
def destroy @bet_event.destroy respond_to do |format| format.html { redirect_to bet_events_url, notice: 'Bet event was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @xbet_event.destroy\n respond_to do |format|\n format.html { redirect_to xbet_events_url, notice: 'Event was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @event.destroy\n respond_to do |format|\n format.json { head :no_con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load all sound files, bailing if any are invalid
def load_raw_sounds(kit_items) raw_sounds = {} kit_items.values.flatten.each do |sound_file_name| begin wavefile = WaveFile.open(sound_file_name) rescue Errno::ENOENT raise SoundFileNotFoundError, "Sound file #{sound_file_name} not found." rescue StandardError raise Inv...
[ "def load_sounds\n @sounds = Dir.new(\"databases/\"+@short+\"/sounds\").to_a-[\".\",\"..\"]\n end", "def load_sounds \n @minim = Minim.new self\n @s_beep = @minim.load_file @root_path + \"/sounds/beeep.wav\", 2048\n @s_peep = @minim.load_file @root_path + \"/sounds/peeeeeep.w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /bizowners_reviews POST /bizowners_reviews.json
def create @bizowners_review = BizownersReview.new(bizowners_review_params) @bizowners_review.update(jobseeker_id: current_user.id) @bizowners_review.update(status: true) respond_to do |format| if @bizowners_review.save format.html { redirect_to @bizowners_review, notice: 'Bizowners revie...
[ "def reviews_of_a_book\n resp=get_access_token().get(\"/#{params[:type]}/subject/#{params[:id]}/reviews\")\n doc=REXML::Document.new(resp.body)\n @reviews=[]\n REXML::XPath.each(doc,\"//entry\") do |entry|\n @reviews << Douban::Review.new(entry.to_s)\n end\n \n render :json => @reviews.to_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /bizowners_reviews/1 PATCH/PUT /bizowners_reviews/1.json
def update respond_to do |format| if @bizowners_review.update(bizowners_review_params) format.html { redirect_to @bizowners_review, notice: 'Bizowners review was successfully updated.' } format.json { render :show, status: :ok, location: @bizowners_review } else format.html { ren...
[ "def update\n @review.update!(review_params)\n\n render json: @review\n end", "def update\n respond_to do |format|\n if @boo_k_review.update(boo_k_review_params)\n format.html { redirect_to @boo_k_review, notice: 'Boo k review was successfully updated.' }\n format.json { render :show,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /bizowners_reviews/1 DELETE /bizowners_reviews/1.json
def destroy @bizowners_review.destroy respond_to do |format| format.html { redirect_to bizowners_reviews_url, notice: 'Bizowners review was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @review = reviewable.reviews.find(params[:id])\n @review.destroy\n\n respond_to do |format|\n format.html { redirect_to reviewable_reviews_url(reviewable) }\n format.json { head :no_content }\n end\n end", "def destroy\n @personal_review.destroy\n respond_to do |format|...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Overrides getter method to return the creators in the correct order.
def creator return super if ordered_creators.blank? JSON.parse(ordered_creators) end
[ "def creators\n # if_DC_exists_strict { self.DC.creator }\n c = []\n c.concat personal_creators.map { |hsh| \"#{hsh[:first]} #{hsh[:last]}\" }\n c.concat corporate_creators\n c.reject { |c| c.empty? }\n end", "def creator_names\n creators.map { |c| c&.creator_name&.v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obsoleting a mapping means some rpmdiff runs might have become obsolete. This is processed after commit, rather than after save, because the result is affected by whether additional mappings have been added or rpmdiff runs scheduled. Therefore we should not obsolete runs until all modifications for the current transact...
def after_commit(mapping) if obsoleted?(mapping) RpmdiffRun.invalidate_obsolete_runs(mapping.errata) end end
[ "def completeMap()\n\t\t@aventureDB.execute(\"UPDATE aventure SET state = 'DONE' WHERE idMap = '#{@currentMap}' AND idSave = '#{@idSave}'\")\n\t\t@aventureDB.execute(\"UPDATE aventure SET historic = '' WHERE idMap = '#{@currentMap}' AND idSave = '#{@idSave}'\")\n\t\tnextMap = getNextMap()\n\t\tif(isLocked(nextMap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
calculate the last possible reservation date based on all current price policies associated with this instrument
def last_reserve_date (Time.zone.now.to_date + max_reservation_window.days).to_date end
[ "def calculate_next_entitlement_period_end_date()\n latest_entitlement = find_latest_entitlement\n if latest_entitlement.nil?\n Date.new(Date.today.next_year.year, Date.today.next_month.month, 1)\n else\n latest_entitlement.end_date.next_year\n end\n end", "def calculate_overage(reservation...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the most recent show created for a user
def current_show shows.order('created_at DESC').first end
[ "def most_recent_user\n \tuser = User.find(last_poster_id)\n \treturn user\n end", "def set_most_recent\n @recent = User.order(\"created_at\").last\n end", "def last\r\n user = params[:user] || nil\r\n streams = user.nil? ? Stream.last(10) : Stream.where(user_id: user).last(10)\r\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }