query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
End of is_plural? Method: walk_association Purpose: Walks the association into the object passed to it Arguments: object_string : friendly text string name for the object association : friendly text string name for the association associated_objects : the list of objects in the association Returns: None
def walk_association(object_string, association, associated_objects) begin # # Assemble some fake code to make it look like we're iterating though associations (plural) # number_of_associated_objects = associated_objects.length if is_plural?(association) assignment_string = "#{object_string}...
[ "def dump_association(object_string, association, associated_objects, indent_string)\n begin\n #\n # Assemble some fake code to make it look like we're iterating though associations (plural)\n #\n number_of_associated_objects = associated_objects.length\n if is_plural?(associ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of walk_association Method: print_associations Purpose: Prints the associations (if any) of the object passed to it Arguments: object_string : friendly text string name for the object this_object : the Ruby object whose associations are to be dumped this_object_class : the class of the object whose associations are...
def print_associations(object_string, this_object, this_object_class) begin # # Only dump the associations of an MiqAeMethodService::* class # if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/ # # Print the associations of this object according to the # $walk_asso...
[ "def dump_association(object_string, association, associated_objects, indent_string)\n begin\n #\n # Assemble some fake code to make it look like we're iterating though associations (plural)\n #\n number_of_associated_objects = associated_objects.length\n if is_plural?(associ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of print_associations Method: print_methods Purpose: Prints the methods (if any) of the object class passed to it Arguments: object_string : friendly text string name for the object this_object : the Ruby object whose methods are to be dumped Returns: None
def print_methods(object_string, this_object) begin # # Only dump the methods of an MiqAeMethodService::* class # if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/ print_line($recursion_level, "Class of remote DRb::DRbObject is: #{this_object.method_missing(:c...
[ "def print_associations(object_string, this_object, this_object_class)\n begin\n #\n # Only dump the associations of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n #\n # Print the associations of this object according to the\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of print_methods Method: print_tags Purpose: Prints the tags (if any) of the object class passed to it Arguments: this_object : the Ruby object whose tags are to be printed this_object_class : the class of the object whose associations are to be dumped Returns: None
def print_tags(this_object, this_object_class) begin if this_object.respond_to?(:taggable?) if this_object.taggable? tags = Array.wrap(this_object.tags) if tags.length.zero? print_line($recursion_level, "--- no tags ---") else print_line($recursion_level, "--- tag...
[ "def print_associations(object_string, this_object, this_object_class)\n begin\n #\n # Only dump the associations of an MiqAeMethodService::* class\n #\n if this_object.method_missing(:class).to_s =~ /^MiqAeMethodService.*/\n #\n # Print the associations of this object according to the\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of print_tags Method: print_custom_attributes Purpose: Prints the custom attributes (if any) of the object class passed to it Arguments: object_string : friendly text string name for the object this_object : the Ruby object whose tags are to be printed Returns: None
def print_custom_attributes(object_string, this_object) begin if this_object.respond_to?(:custom_keys) custom_attribute_keys = Array.wrap(this_object.custom_keys) if custom_attribute_keys.length.zero? print_line($recursion_level, "--- no custom attributes ---") else print_line($r...
[ "def dump_attributes(object_string, this_object, indent_string)\n begin\n #\n # Print the attributes of this object\n #\n if this_object.respond_to?(:attributes)\n log(:info, \"#{indent_string}#{@method}: Debug: this_object.inspected = #{this_object.inspect}\") if @debug\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
End of print_custom_attributes Method: walk_object Purpose: Prints the details of the object passed to it Arguments: indent_level : the numeric value to use to indicate output indent (represents recursion depth) object_string : friendly text string name for the object this_object : the Ruby object to be dumped Returns:...
def walk_object(object_string, this_object) begin # # Make sure that we don't exceed our maximum recursion level # $recursion_level += 1 if $recursion_level > $max_recursion_level print_line($recursion_level, "*** exceeded maximum recursion level ***") $recursion_level -= 1 retur...
[ "def print_custom_attributes(object_string, this_object)\n begin\n if this_object.respond_to?(:custom_keys)\n custom_attribute_keys = Array.wrap(this_object.custom_keys)\n if custom_attribute_keys.length.zero?\n print_line($recursion_level, \"--- no custom attributes ---\")\n else\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the "official" name for the 7600B form, comprised of the GTC number, the order number , and the mod number, both padded to 4 digits and all separated by dashes.
def name "#{gtc_number}-#{name_str(order_number)}-#{name_str(mod_number)}" end
[ "def name\n \"#{gtc_number}-0000-#{mod_number.to_s.rjust(4, '0')}\"\n end", "def generate_name_with_digit (digit)\n char_array = ('a'..'z').to_a + ('0'..'9').to_a + ['_'] # char_array.length is 37\n\n quotient = digit\n queue = []\n while true do\n queue.push quotient % N_CHAR\n quotient...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /mercadoria/1 DELETE /mercadoria/1.json
def destroy @mercadorium.destroy respond_to do |format| format.html { redirect_to mercadoria_url } format.json { head :no_content } end end
[ "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @asignatura.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @prueba_json.destroy\n respond_to do |format|\n format.html { redirect_to prueba_jsons_url }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /permits POST /permits.json
def create @permit = Permit.new(permit_params) @permit.category_id = params[:category_id] @permit.employee_id = params[:employee_id] @permit.site_id = params[:site_id] respond_to do |format| if @permit.save format.html { redirect_to @permit, notice: 'Permit was successfully created.'...
[ "def create\n @permit = Permit.new(permit_params)\n @permit.service_type = @service_type\n @permit.trusted_app = @current_app\n\n # Determine the permitable object\n @permit.permitable = permitable\n\n respond_to do |format|\n if @permit.save\n format.json { render action: 'show', stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /permits/1 PATCH/PUT /permits/1.json
def update @permit.category_id = params[:category_id] @permit.employee_id = params[:employee_id] @permit.site_id = params[:site_id] respond_to do |format| if @permit.update(permit_params) format.html { redirect_to @permit, notice: 'Permit was successfully updated.' } format.j...
[ "def update\n @permit.permitable = permitable \n respond_to do |format|\n if @permit.update(permit_params)\n format.json { head :no_content }\n else\n format.json { render json: @permit.errors, status: :unprocessable_entity }\n end\n end\n end", "def update\n respond_to d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /permits/1 DELETE /permits/1.json
def destroy @permit.destroy respond_to do |format| format.html { redirect_to permits_url, notice: 'Permit was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @permit.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end", "def destroy\n @permit.destroy\n respond_to do |format|\n format.html { redirect_to permits_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @bldg_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checkse if devfile has any user added observers and sends notification to those nodes
def checkForObservers(devfile) begin path = "/user/" + params[:username] + "/device/" + params[:devicename] + "/files" + devfile.path + devfile.name devfile.file_observers.each do |fo| begin if fo XmppHelper::notificationToNode(fo, devfile, "Content updated!") end...
[ "def checkForObservers(devfile, username, devicename)\n begin\n path = \"/user/\" + username + \"/device/\" + devicename + \"/files\" + devfile.path + devfile.name\n devfile.file_observers.each do |fo|\n begin\n if fo\n XmppHelper::notificationToNode(fo, devfile, \"Content up...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates file's metadata to db parameters: f filehash commit the commit the file belongs to
def updateDevfile(f, commit) #:doc: dev_file = nil begin # Checks if there is any changes in files. f_filedate = DateTime.strptime(f['filedate'], "%T %F") f_filedate = f_filedate.strftime('%F %T').to_s now = DateTime.now.strftime('%F %T') puts "name: #{f['name']}...
[ "def update_metadata\n # @todo db - refactor to use an update\n metadata = files_doc\n metadata[:length] = @file_position\n metadata[:md5] = @local_md5\n @files.save(metadata)\n end", "def update_file_metadata(data)\n update_attributes!( :file_size => data.bytesize, :fil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates metadata of a new file to db parameters: f file commit the commit the file belongs to
def createDevfile(f, commit) #:doc: dev_file = nil blob = nil b_in_c = nil # If file already exists, raises an error but nothing needs to be deleted (except the commit is cancelled) begin dev_file = Devfile.find_by_name_and_path_and_device_id(f['name'], f['path'], @device.id) ...
[ "def createDevfile(f, commit) #:doc:\n \n dev_file = nil\n blob = nil\n b_in_c = nil\n \n # If file already exists, raises an error but nothing needs to be deleted (except the commit is cancelled)\n begin \n dev_file = Devfile.find_by_name_and_path_and_device_id(f['name'], f['path'], @d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add blobs from prev_commit to commit ignoring blobs in changed_files parameters: prev_commit The previous commit commit new commit changed_files list of files to ignore
def addUnchangedFilesToCommit(prev_commit, commit, changed_files) #:doc: # sql = "select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits.commit_id=#{prev_commit.id};" # devfiles_of_p...
[ "def addUnchangedFilesToCommit(prev_commit, commit, changed_files) #:doc:\n\n devfiles_of_prev_commit = Devfile.find_by_sql(\"select devfiles.path, devfiles.name, devfiles.blob_id from devfiles, blobs, blobs_in_commits where blobs.devfile_id=devfiles.id and blobs_in_commits.blob_id=blobs.id and blobs_in_commits....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if commit is missing (some of) it's thumbnails. Sends xmppmessages to the device for the missing thumbnails. parameters: commit the commit in question
def checkForThumbs(commit) #:doc: prev_commit_blob_ids = Array.new prev_commit = Commit.find(:first, :conditions => ["id = ?", commit.previous_commit_id]) if prev_commit prev_commit.blobs.find_each(:batch_size => 1500) do |pb| prev_commit_blob_ids.push(pb.id) end end blobs_w...
[ "def general_comment?() commit_file_id.nil? end", "def check_row\n err_arr = []\n begin\n if @row_hash[\"ao_ref_id\"].nil? && @row_hash[\"ao_uri\"].nil?\n err_arr.push I18n.t(\"bulk_import.error.no_uri_or_ref\")\n end\n end\n normalize_publish_column(@row_hash)\n normalize_publish_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that all necessary http parameters are given. parameters: username, password, devicename and dev_type. port is optionla, but if given must be a number. Returns false is some of the parameters is missing or is in wrong form. Returns true if parameters are fine. register uses this method.
def check_params #:doc: if params[:username] !~ /.{1,}/ or params[:password] !~ /.{1,}/ or params[:devicename] !~ /.{1,}/ or params[:dev_type] !~ /.{1,}/ or (params[:port] != nil and params[:port] !~ /\d{1,10}/) return false else return true end end
[ "def check_params\n # For each key,value in GLOBAL VAR **PARAMS**.\n PARAMS.each do |param, method|\n # Next if there isn't param in the request of client\n next unless params[param]\n # Check the *param* with *method*\n unless send(method, params[param])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Executes queries using the replica database. Fails over to primary if no replica is found. if you want to execute a block of code on the replica you can go: Account.on_replica do Account.first end the first account will be found on the replica DB For oneliners you can simply do Account.on_replica.first
def on_replica(&block) on_primary_or_replica(:replica, &block) end
[ "def on_replica(&block)\n on_master_or_replica(:replica, &block)\n end", "def enable_replica\n begin\n ActiveRecord::Base.connection.enable_replica\n yield\n rescue Makara::Errors::AllConnectionsBlacklisted => e\n yield\n ensure\n ActiveRecord::Base.connection.disable_replica\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enable saving of unknown barewords. With this, the only way to terminate parsing is to hit the end of the parse or with . You can retrieve the saved words from saved.
def save_unknown! @saved = [] end
[ "def preload\n !words_list.empty?\n end", "def save\n blowup_keywords\n super\n end", "def save_unmatched_words # :nodoc:\n tokens = phrase_without_matches.split(' ')\n unmatched_db = Corpus.new(\"unmatched-#{program_name}.db\")\n tokens.each do |token|\n if !complex_token_matc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns either the banner set with banner= or a simple banner like "Usage: $0 [arguments]"
def banner @banner || "Usage: #{program_prefix} [arguments]" end
[ "def banner(banner, options)\n if banner\n puts banner\n else\n # Usage needs to know about the defined options.\n usage(options)\n end\n end", "def help_banner\n output = ''\n if command_parser.main_options.banner?\n output << format(command_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check the follower common event call
def check_follower_trigger_there(new_x, new_y) if @follower.x == new_x && @follower.y == new_y if @follower.is_a?(Game_Event) @follower.start else @follower.turn_toward_player $game_temp.common_event_id = Game_CommonEvent::FOLLOWER_SPEECH end return true end r...
[ "def check_self_follow\n if helpers.am_i_owner?\n flash[:notice] = \"You can't follow your own event!\"\n redirect_to @event\n end\n end", "def following?(event)\n following.include?(event)\n end", "def on_follow(user)\n end", "def following? subject\n has_event? 'follow...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a contentEditable command
def edit(command, value=nil) command = command.gsub(/_./) { |i| i[1].upcase } focus if value `#{document}.native.execCommand(#{command}, false, #{value})` else `#{document}.native.execCommand(#{command}, false)` end end
[ "def command_mode(s) \n\t\t@command_editor.set_text(s)\n\t\t@command_editor.set_focus()\n\tend", "def execute_command(cmd, options = {})\n context = options[:in] || active_tab\n context.write :text => cmd\n end", "def execEditorScript _obj, _args\n \"_obj execEditorScript _args;\" \n end", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an instance of SeriesIndex for each series page, renders it, and writes the output to a file. +series_prefix+ is the String path to the series folder. +series+ is the series currently being processed.
def write_series_index(series_prefix, series, posts, authors) index = SeriesIndex.new(self, source, series_prefix, series, posts, authors) index.render(layouts, site_payload) index.write(dest) # Record the fact that this page has been added, otherwise Site::cleanup will remove it. pages <...
[ "def write_series(series) # :nodoc:\n write_ser(series)\n end", "def generate_indexes\n @indexes.each do |index|\n html_out = File.open \"#{@sitepath}/#{index}.html\",\"w\"\n layout_engine = Haml::Engine.new(\n File.read(\"#{@basepath}/_layouts/#{index}.haml\"))\n payload = layout...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets a series name, and pulls out a markdown header file returning either the rendered markdown, or an empty string
def series_bio(series) bio_path = "_includes/_series_bio/#{to_series_id(series)}.md" return "" unless File.exist?(bio_path) markdownify(File.read(bio_path)) end
[ "def extract_md_title(item)\n\t\tif (item[:extension] != 'md')\n\t\t\treturn nil\n\t\tend\n\n\t\tcontent = item.raw_content.lines.each{|l|\n\t\t\tif (l.start_with?('# '))\n\t\t\t\treturn l[2..-1].strip()\n\t\t\tend\n\t\t}\n\t\tnil\n\tend", "def slide_title\n title = @line[/^ *## (.*)/, 1]\n title.nil? ?...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the G of the memory_used
def memory_used_with_g self.memory_memused.map { |i| i / 1000000000.0} end
[ "def memused\n @memtotal - @memfree\n end", "def memory_used\n %x[free -ot].split[19]\n end", "def memory_total\n %x[free -ot].split[18]\n end", "def mem_used\n mem_total - mem_available\n end", "def ram_used\n %x[free -ot].split[8]\n end", "def memory_bytes_used\n get_d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get IPv6 addresses for given network interface
def ip6addr(iface=nil) @ip6addr[iface || default_iface] end
[ "def ipv_6_addresses\n data.ipv_6_addresses\n end", "def ipv_6_addresses\n data[:ipv_6_addresses]\n end", "def ipv6_addresses\n addresses.select { |address| address.match /:/ }\n end", "def ipv6\n @ipv6\n end", "def parse_ip6(ip_output, scope)\n cidr_ip = parse_ip_output(ip_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /vertices_scene3s GET /vertices_scene3s.json
def index @vertices_scene3s = VerticesScene3.all end
[ "def index\n @scene3s = Scene3.all\n end", "def index\n @space_scene3s = SpaceScene3.all\n end", "def index\n @vertices_scenes = VerticesScene.all\n end", "def index\n @position_scene3s = PositionScene3.all\n end", "def index\n @vertices_scene1s = VerticesScene1.all\n end", "def create...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /vertices_scene3s POST /vertices_scene3s.json
def create @vertices_scene3 = VerticesScene3.new(vertices_scene3_params) respond_to do |format| if @vertices_scene3.save format.html { redirect_to @vertices_scene3, notice: 'Vertices scene3 was successfully created.' } format.json { render :show, status: :created, location: @vertices_scen...
[ "def create\n @vertices_scene = VerticesScene.new(vertices_scene_params)\n\n respond_to do |format|\n if @vertices_scene.save\n format.html { redirect_to @vertices_scene, notice: 'Vertices scene was successfully created.' }\n format.json { render :show, status: :created, location: @vertices...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /vertices_scene3s/1 PATCH/PUT /vertices_scene3s/1.json
def update respond_to do |format| if @vertices_scene3.update(vertices_scene3_params) format.html { redirect_to @vertices_scene3, notice: 'Vertices scene3 was successfully updated.' } format.json { render :show, status: :ok, location: @vertices_scene3 } else format.html { render :...
[ "def update\n respond_to do |format|\n if @vertices_scene.update(vertices_scene_params)\n format.html { redirect_to @vertices_scene, notice: 'Vertices scene was successfully updated.' }\n format.json { render :show, status: :ok, location: @vertices_scene }\n else\n format.html { re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /vertices_scene3s/1 DELETE /vertices_scene3s/1.json
def destroy @vertices_scene3.destroy respond_to do |format| format.html { redirect_to vertices_scene3s_url, notice: 'Vertices scene3 was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @vertices_scene.destroy\n respond_to do |format|\n format.html { redirect_to vertices_scenes_url, notice: 'Vertices scene was successfully destroyed.' }\n format.json { head :no_content }\n end\n end", "def destroy\n @vertices_scene1.destroy\n respond_to do |format|\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a read operation with retrying. This method performs server selection for the specified server selector and yields to the provided block, which should execute the initial query operation and return its result. The block will be passed the server selected for the operation. If the block raises an exception, and ...
def read_with_retry(session = nil, server_selector = nil, &block) if session.nil? && server_selector.nil? # Older versions of Mongoid call read_with_retry without arguments. # This is already not correct in a MongoDB 3.6+ environment with # sessions. For compatibility we emulate the legacy...
[ "def read_with_retry(session = nil, server_selector = nil, &block)\n if session.nil? && server_selector.nil?\n deprecated_legacy_read_with_retry(&block)\n elsif session&.retry_reads?\n modern_read_with_retry(session, server_selector, &block)\n elsif client.max_read_retries > 0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Execute a read operation with a single retry on network errors. This method is used by the driver for some of the internal housekeeping operations. Applicationrequested reads should use read_with_retry rather than this method.
def read_with_one_retry(options = nil) yield rescue Error::SocketError, Error::SocketTimeoutError => e retry_message = options && options[:retry_message] log_retry(e, message: retry_message) yield end
[ "def read_with_one_retry\n yield\n rescue Error::SocketError, Error::SocketTimeoutError\n yield\n end", "def read_with_one_retry(options = nil)\n yield\n rescue *retryable_exceptions, Error::PoolError => e\n raise e unless e.write_retryable?\n\n retry_message = options &&...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retryable writes wrapper for operations not supporting modern retryable writes. If the driver is configured to use modern retryable writes, this method yields to the passed block exactly once, thus not retrying any writes. If the driver is configured to use legacy retryable writes, this method delegates to legacy_write...
def nro_write_with_retry(session, write_concern, &block) if session && session.client.options[:retry_writes] server = select_server(cluster, ServerSelector.primary, session) yield server else legacy_write_with_retry(nil, session, &block) end end
[ "def nro_write_with_retry(write_concern, context:, &block)\n session = context.session\n server = select_server(cluster, ServerSelector.primary, session)\n \n if session&.client.options[:retry_writes]\n begin\n server.with_connection(connection_global_id: context.conn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Implements legacy write retrying functionality by yielding to the passed block one or more times. This method is used for operations which are not supported by modern retryable writes, such as delete_many and update_many.
def legacy_write_with_retry(server = nil, session = nil) # This is the pre-session retry logic, and is not subject to # current retryable write specifications. # In particular it does not retry on SocketError and SocketTimeoutError. attempt = 0 begin attempt += 1 server ||=...
[ "def write_with_retry\n attempt = 0\n begin\n attempt += 1\n yield\n rescue Error::OperationFailure => e\n raise(e) if attempt > Cluster::MAX_WRITE_RETRIES\n if e.write_retryable?\n log_retry(e)\n cluster.scan!\n retry\n else\n ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
You are writing the user registration page for a secure web site. On the registration page, the user has to enter a user ID and a password, which has to adhere to the to following criteria: User ID and password cannot be the same User ID and password have to be at least six characters long Password has to contain at le...
def same (user_id, password) if user_id.downcase == password.downcase puts "User ID and password cannot be the same" else puts "Acceptable" end end
[ "def user_registration\n\n puts \"Enter a user ID.\"\n user_id = gets.chomp\n\n puts \"Enter a password\"\n password = gets.chomp\n\n if !same?(user_id, password) && long_enough(user_id) && long_enough(password) && contains_special(password) && does_not_contain_special(user_id) && password != \"password\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that accepts a password and determins if it is the word "password." If so, inform the user that the password cannot be the word "password." Else, return acceptable.
def is_password(password) if password.downcase == "password" puts "Password cannot be the word password" else puts "Acceptable" end end
[ "def valid_password?(password); end", "def check_for_password_string?(password)\n !password.downcase.include?(\"password\")\nend", "def valid_password?(password)\n true\n end", "def valid_password?(password)\n compare(password)\n end", "def password\n password = @prompt.mask(\"Enter ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Challenge Write a method that inputs user ID and password from the user, and then tells the user if the they are acceptable. Write a main method called validate_password that: First lets a user input both user ID and password, Then use the methods above to evaluate if the user ID and password combination is acceptable ...
def validate_password puts "Enter your User ID and Password here." user_id = gets.chomp password = gets.chomp same(user_id, password) long_enough(user_id) long_enough(password) does_not_contain_special(user_id) contains_special(password) is_password(password) end
[ "def validate_password()\n puts 'Enter your User ID'\n user_id = gets\n puts 'Enter your password'\n password = gets\n if same(user_id,password) == 'True'\n p 'user ID and password cannot match'\n elsif long_enough(user_id, password) == 'False'\n p 'user ID and password must ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Nokogiri XML DOM for the current Brominet XML representation of the GUI
def dom_for_gui @dom = Nokogiri::XML self.dump end
[ "def dom\r\n @dom = Nokogiri::XML @gui.dump\r\nend", "def get_xml_document\n Nokogiri::XML(self.body)\n end", "def document\n @doc ||= Nokogiri::XML(@xml)\n end", "def read_inner_xml()\n #This is a stub, used for indexing\n end", "def root_element\n root.xml \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
method will get the availability set using the resource group and availability set name will return whether or not the availability set exists.
def get(resource_group, availability_set) begin promise = @client.availability_sets.get(resource_group, availability_set).value! promise.body rescue MsRestAzure::AzureOperationError => e # if the error is that the availability set doe...
[ "def get\n begin\n promise = @client.availability_sets.get(@rg_name,@as_name).value!\n return promise\n rescue MsRestAzure::AzureOperationError => e\n # if the error is that the availability set doesn't exist,\n # just return a nil\n if e.response.status == 404\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this method will add the availability set if needed. it first checks to make sure the availability set exists, if not, it will create it.
def add(resource_group, availability_set, location) # check if it exists existance_promise = get(resource_group, availability_set) if !existance_promise.nil? OOLog.info("Availability Set #{existance_promise.name} exists in the #{existance_promise.location} region.") ...
[ "def add\n # check if it exists\n as_exist = @compute_client.availability_sets.check_availability_set_exists(@rg_name, @as_name)\n if as_exist\n OOLog.info(\"Availability Set #{@as_name} exists in the #{@location} region.\")\n else\n # need to create the availability set\n O...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
create the properties object for creating availability sets
def get_avail_set_props(location) avail_set_props = Azure::ARM::Compute::Models::AvailabilitySetProperties.new # At least two domain faults avail_set_props.platform_fault_domain_count = 2 avail_set_props.platform_update_domain_count = 2 # At this point we do not have virtual machin...
[ "def get_availability_set_properties(location, fault_domain_count, update_domain_count, use_managed_disk, tags)\n avail_set = Azure::ARM::Compute::Models::AvailabilitySet.new\n avail_set.location = location\n avail_set.sku = create_availability_set_sku(use_managed_disk)\n avail_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Marks the current model as a canhaz subject for authorizations
def acts_as_canhaz_object include Canhaz::Mongoid::ObjectExtensions class_eval do has_many :permissions_subjects, :class_name => 'Canhaz::Mongoid::Permission', :inverse_of => 'cobject' end end
[ "def acts_as_canhaz_subject\n include CanHaz::ModelExtensions::Subject\n extend CanHaz::ModelExtensions::Subject::ClassMethods\n before_destroy :can_do_nothing # Removes permission before deleting the subject\n end", "def acts_as_authorization_subject?\n acts_as_authorization_model? :subj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /ingresos GET /ingresos.xml
def index @ingresos = Ingreso.all respond_to do |format| format.html # index.html.erb format.xml { render :xml => @ingresos } end end
[ "def show\n @ingreso = Ingreso.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @ingreso }\n end\n end", "def index\n @pings = Ping.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /ingresos/1 GET /ingresos/1.xml
def show @ingreso = Ingreso.find(params[:id]) respond_to do |format| format.html # show.html.erb format.xml { render :xml => @ingreso } end end
[ "def index\n @ingresos = Ingreso.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @ingresos }\n end\n end", "def xml(id)\n http.get(\"/nfse/#{id}/xml\") do |response|\n response.headers.fetch(\"Location\") { \"\" }\n end\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /ingresos/new GET /ingresos/new.xml
def new @ingreso = Ingreso.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @ingreso } end 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 @newstuff = Newstuff.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @newstuff }\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /ingresos POST /ingresos.xml
def create @ingreso = Ingreso.new(params[:ingreso]) respond_to do |format| if @ingreso.save format.html { redirect_to(@ingreso, :notice => 'Ingreso was successfully created.') } format.xml { render :xml => @ingreso, :status => :created, :location => @ingreso } else format.h...
[ "def do_POST(request, response)\n content_type, params = parse_content_type(request)\n\n # In SOAP 1.1, the action is sent in the SOAPAction header. In\n # SOAP 1.2, it's sent as a parameter to the Content-Type header.\n # Savon sends SOAPAction (even though it's SOAP 1.2), so we need to\n # accept ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /ingresos/1 DELETE /ingresos/1.xml
def destroy @ingreso = Ingreso.find(params[:id]) @ingreso.destroy respond_to do |format| format.html { redirect_to(ingresos_url) } format.xml { head :ok } end 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|\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
RESTful DELETE of the node resource
def destroy n = Node.find_key(params[:id] || params[:name]) render api_delete Node end
[ "def destroy\n @node = Node.find(params[:id])\n @node.destroy\n\n respond_to do |format|\n format.html { redirect_to \"/\" }\n format.json { head :ok }\n end\n end", "def destroy\n @node = Node.find(params[:id])\n @node.destroy\n\n respond_to do |format|\n format.html { redire...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formula for side (2 cos[((n2) pi)/ (2 n)]
def side_length top = (@num_sides - 2) * Math::PI angle = top / (2 * @num_sides) @side_length = 2 * Math.cos(angle) end
[ "def calculate_two_sides\n calculate_last_angle\n v, r = first(sides.known)\n\n each sides.unknown(r) do |v2|\n side[v2] = sin(angle(v2)) * side(v) / sin(angle(v))\n equation('$2=\\frac{\\sin(@2) * $1}{\\sin(@1)}', v, v2)\n end\n end", "def side_from_sas(side1, a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Agent filters are always present no matter what, so we cant raise an error if the capabilities suggest the discovery method cant do agents we just have to rely on the discovery plugin to not do stupid things in the presense of a agent filter
def check_capabilities(filter) capabilities = ddl.discovery_interface[:capabilities] unless capabilities.include?(:classes) raise "Cannot use class filters while using the '%s' discovery method" % discovery_method unless filter["cf_class"].empty? end unless capabilities.include?(:facts...
[ "def set_filter(agent, filters, vars)\n agent.reset\n if filters[:discovery]\n agent.discover({:nodes => filters[:discovery]})\n else\n ['identity', 'fact', 'class', 'compound'].each do |kind|\n next unless filters[kind]\n add_filter = agent.method(\"#{kind}_filter\".to_sym)\n if filters[kin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks if compound filters are used and then forces the 'mc' discovery plugin
def force_discovery_method_by_filter(filter) unless discovery_method == "mc" unless filter["compound"].empty? Log.info "Switching to mc discovery method because compound filters are used" @client.options[:discovery_method] = "mc" return true end end retu...
[ "def force_discovery_method_by_filter(filter)\n false\n end", "def initialize_filter_set_if_needed\n helper = \"#{controller.controller_name.singularize}_filters\"\n send(helper) unless @filter_set\n end", "def global_filter; end", "def identity_filter_discovery_optimization\n if !...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
if a compound filter is specified and it has any function then we read the DDL for each of those plugins and sum up the timeout declared in the DDL
def timeout_for_compound_filter(compound_filter) return 0 if compound_filter.nil? || compound_filter.empty? timeout = 0 compound_filter.each do |filter| filter.each do |statement| if statement["fstatement"] pluginname = Data.pluginname(statement["fstatement"]["name"]) ...
[ "def ts_apply_filters\n # TODO: Make filters for Thinking Sphinx\n end", "def initialize_available_filters\n add_available_filter \"spent_on\", :type => :date_past\n\n add_available_filter(\"project_id\",\n :type => :list, :values => lambda { project_values }\n ) ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This should be called if you cannot find a paper through other means.
def fallback_to_first_possible_paper_reference model = @model_hash.values.detect { |model| model.try(:paper) } model.try(:paper) end
[ "def for_paper(paper)\n where(paper_id: paper.id)\n end", "def double_review\n @paper = Paper.find(params[:paper_id])\n @paper.reviews.each do |r|\n if r.user == current_user\n redirect_to paper_path(@paper)\n flash[:error] = \"You have already made a review for this pap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read a yaml file containing a menu
def read_yml_menu(filename) # Load the yaml file into a hash settings = YAML::load_file filename # These are now hashes with ingredient name as key # with hashes representing ingredients, that contain metadata such as prices meats = settings[:ingredients][:meats] vegetables = settings[:ingredi...
[ "def yaml\n File.read(@name)\n end", "def read file=STDIN\n\n yaml = case file\n when String\n raise \"Input file not defined\" unless file\n raise \"Input file does not exist\" unless File.exist? file\n raise \"Input file is not readable \" unles...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a hash of ingredients with metadata to a list of Ingredient objects
def hash_to_ingredient(dict) ingredients = Array.new # Each ingredient has name as key, and metadata as a dictionary. # At this point, we just extract the price, but we can expand this later dict.each do |name,ingr| ingredients.push(Salads::Ingredient.new(name, ingr["price"])) end return...
[ "def ingredients\n recipe_ingredients.map do |r|\n r.ingredient\n end\n end", "def ingredients\n recipeingredient.map {|ri| ri.ingredient}\n end", "def ingredients\n self.recipe_ingredients.map do |recipe_ingredient|\n recipe_ingredient.ingredient\n end\n end", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /stock_medicas POST /stock_medicas.json
def create @stock_medica = StockMedica.new(stock_medica_params) respond_to do |format| if @stock_medica.save format.html { redirect_to @stock_medica, notice: 'Fue Crado stock' } format.json { render :show, status: :created, location: @stock_medica } else format.html { ren...
[ "def create\n @stock = Stock.create!(stock_params)\n json_response(@stock, :created)\n\n end", "def create\n @stock = Stock.new(stock_params)\n\n if @stock.save\n render json: @stock, status: :created, location: @stock\n else\n render json: @stock.errors, status: :unprocessable_entity\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /stock_medicas/1 PATCH/PUT /stock_medicas/1.json
def update respond_to do |format| if @stock_medica.update(stock_medica_params) format.html { redirect_to @stock_medica, notice: 'Stock medica was successfully updated.' } format.json { render :show, status: :ok, location: @stock_medica } else format.html { render :edit } ...
[ "def update\n respond_to do |format|\n if @mouvement_stock.update(mouvement_stock_params)\n format.html { redirect_to @mouvement_stock, notice: 'Mouvement stock was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /stock_medicas/1 DELETE /stock_medicas/1.json
def destroy @stock_medica.destroy respond_to do |format| format.html { redirect_to stock_medicas_url, notice: 'Stock medica was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @stock.destroy\n respond_to do |format|\n format.html { redirect_to api_stocks_url }\n format.json { head :no_content }\n end\n end", "def destroy\n @mouvement_stock.destroy\n respond_to do |format|\n format.html { redirect_to mouvement_stocks_url }\n format.json...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The number of rotational degrees required to display this image as upright
def required_rotation_for_upright_display required_rotation_orientation_in_degrees = (360 - self.orientation) % 360 return required_rotation_orientation_in_degrees end
[ "def image_rotation\n @rotation\n end", "def total_rotation\n rotation + rotation_offset\n end", "def max_tilt_angle; end", "def rotation\n @rotation ||= 0\n end", "def rotation\n @rotation || -Math::PI/2\n end", "def rotated_height\n case self.rotate_to\n when 90, 270 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts an UID (room, grouping or app) from an URL/path.
def uid_from_path(url, base_store_url) return [:main, 0] if url.include?(base_store_url) return [:category, url.match(/viewGenre\?id\=(\d+)/)[1]] if url.include?("viewGenre?id=") return [:category, url.match(/viewGrouping\?id\=(\d+)/)[1]] if url.include?("viewGrouping?id=") return [:roo...
[ "def id_from_url(url)\n url.split(\"/\")[-1]\n end", "def extract_pid(uri)\n URI(uri).path.split('/').last\n end", "def find_id(uri)\n Addressable::URI.parse(uri).basename\n end", "def parse_attachment_reference_uuid_from_url(url)\n result = url&.match(ATTACHMENT_ID_REGEX)\n result ?...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
certinfos should be a hashlike where each entry describes a certificate. defaulthostname should be a string that will be inserted into %HOSTNAME% in certificate subject lines.
def initialize(certinfos, defaulthostname, config={}) @config = config @defaulthostname = defaulthostname @parenthostname = defaulthostname.sub(/^[\w-]+\./, '') # remove left-most label @certinfos = certinfos @certificates = {} end
[ "def warning_subjectaltname(cert, warning_messages, required_san_array, service_name)\n cent_san_hash = get_san_hash(cert)\n altnames = cent_san_hash[:altnames] || []\n ip_altnames = cent_san_hash[:ip_altnames] || []\n cert_san_array = altnames + ip_altnames\n missing_hostnames = []\n\n # Convert ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
FUNCTIONS a_anno 0:chr 1:pos 3:oldBase 4:newBase 5:quality 10:gene 11:/+ 12:exon/intron/promotor a_gen 1:gene 2:chr 3:+/ 4:start 5:stop 6:start_coding 7:end_coding 8:ofExons 9:ExonStarts 10:exonEnds
def mutations_effect(a_anno, a_gen) if $locus[a_anno[10]] && a_anno[3].length == a_anno[4].length $cdna.pos = $locus[a_anno[10]] transcript = original() exon_starts = a_gen[9].split(',') exon_ends = a_gen[10].split(',') mutation_position,exon_num = position_on_transcript(a_anno[1],a_gen[3],exon_s...
[ "def write_fasta_annotation (file_list)\n file_list.each do |f|\n abort(\"Couldn't open the file #{f}\") unless File.exists?(f)\n f_basename = File.basename(f, \".gbk\")\n outfile = File.open(\"fasta_with_annotations/\" + f_basename + \".fasta\", 'w')\n bio_gbk = Bio::GenBank.open(f)\n count = 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /slow_things GET /slow_things.json
def index @slow_things = SlowThing.all respond_with @slow_things if stale? @slow_things, public: true end
[ "def find\n @thing = Thing.where(:thing, url[:thing]).where(:tid, url[:id]).last\n render json: @thing.object\n end", "def index\n @things = Thing.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @things }\n end\n end", "def show\n respond_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /slow_things/1 GET /slow_things/1.json
def show respond_with @slow_thing if stale? @slow_thing, public: true end
[ "def index\n @slow_things = SlowThing.all\n respond_with @slow_things if stale? @slow_things, public: true\n end", "def find\n @thing = Thing.where(:thing, url[:thing]).where(:tid, url[:id]).last\n render json: @thing.object\n end", "def index\n @things = Thing.all\n\n respond_to do |format|...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /slow_things POST /slow_things.json
def create @slow_thing = SlowThing.new(slow_thing_params) respond_to do |format| if @slow_thing.save domain = URI(root_url) Net::HTTP.start(domain.host, domain.port) do |http| Rails.logger.debug "purging #{domain}" http.request( Purge.new(domain) ) Rails.lo...
[ "def long_slow_post(host, rate_limit, keep_alive) \r\n\trequest = \"POST /\" + (Digest::MD5.hexdigest(srand.to_s)) + \" HTTP/1.1\\r\\n\";\r\n request += \"Host: #{$host}\\r\\n\"\r\n request += \"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0\\r\\n\"\r\n request += \"Keep-Alive: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
PATCH/PUT /slow_things/1 PATCH/PUT /slow_things/1.json
def update respond_to do |format| if @slow_thing.update(slow_thing_params) domain = URI(root_url) Net::HTTP.start(domain.host, domain.port) do |http| Rails.logger.debug "purging #{domain}" http.request( Purge.new(domain) ) Rails.logger.debug "purging #{slow_thin...
[ "def patch *args\n make_request :patch, *args\n end", "def update\n @thing = Thing.find(params[:id])\n\n respond_to do |format|\n if @thing.update_attributes(params[:thing])\n format.html { redirect_to things_path, notice: 'Your thing was successfully updated!' }\n format.json { head ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /slow_things/1 DELETE /slow_things/1.json
def destroy @slow_thing.destroy respond_to do |format| format.html { redirect_to slow_things_url, notice: 'Slow thing was successfully destroyed.' } format.json { head :no_content } end 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 # delete a specific thing\n end", "def destroy\n @thing = Thing.find(params[:id])\n @thing.destroy\n\n respond_to do |format|\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes an array of strings, each representing a line Draws a box around the lines, and returns a new array padding may be provided
def box_it(array_of_lines, padding = 1, _box_colour = :bc_cyan) max_length = max_box_line_length(array_of_lines) pad_string = "\s" * padding box_lines = [ # Set the top box line "#{BOX_TOP_LEFT}#{BOX_HORIZONTAL_LINE * (max_length + (padding + 1))}#{BOX_TOP_RIGHT}" ] array...
[ "def pad_line(text)\n return text if text.empty? || padding.empty?\n\n padding_left = ' ' * padding[3].to_i\n padding_right = ' ' * padding[1].to_i\n text.map! do |part|\n part.insert(0, padding_left).insert(-1, padding_right)\n end\n end", "def pad_multi_line(tex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MUST BE CALLED BY User.deliver_inactive_notification!
def inactive_notification(user) setup_email(user) @subject += subject_from_sym :inactive_notification @body[:name] = user.full_name || 'Eternos user' @body[:link] = account_setup_url(:id => user.perishable_token) add_category_header "Inactive Account Notice" end
[ "def inactive\n\t\t# Pick a random user and temporary set his status to 'inactive'\n\t\tuser = User.first\n\t\tuser.status = 'inactive'\n\t\tUserStatusMailer.set_mail(user)\n\tend", "def atest_ID_25861_suspended_user_notification()\n # Need suspended account\n end", "def inactive_message\n self.status =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
MUST BE CALLED BY User.deliver_account_setup_reminder!
def account_setup_reminder(user) setup_email(user) @subject = subject_from_sym :account_setup_reminder @body[:name] = user.full_name @body[:setup_url] = account_setup_url(:id => user.perishable_token, :ref => 'asr1') add_category_header "Account Setup Reminder" end
[ "def handle_password_reminder_setup\n Users::Reminders.password_expiration(self) if @set_reminder && is_a?(User)\n end", "def deliver_signup_notification\n if !self.email.blank?\n Mailers::User.deliver_signup_notification(self) if self.recently_activated?\n end\n end", "def send_signup_notification\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current status of the state. This includes: Player status Room description Room's treasure Room's monster
def status output = StringIO.new output << @game.player.to_s output << "\n" output << "#{@game.current_room_model.description}\n" treasure = @game.current_room_model.treasure output << "\nThere is treasure here worth $#{treasure}.\n" if treasure && treasure > 0 monster = @game.current_roo...
[ "def status\n monster = @game.current_room_model.monster\n return unless monster\n\n weapons = @game.player.weapons\n output = \"With a ferocious sight the Wild #{monster.name} wants to fight! \\n\"\n output << \"Be careful it's ferocity level is #{monster.ferocity}\\n\"\n weapons.each_with_index ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles a command for this state. +command+ must be a symbol Possible commands: :north : Moves you to north :south : Moves you to south :east : Moves you to east :west : Moves you to west :up : Moves you to up :down : Moves you to down :tally : Shows you the current score and number of monsters killed :run : Tries to r...
def handle(command) puts "Doing #{command}..." method = command case command when :north then method = :move when :south then method = :move when :east then method = :move when :west then method = :move when :up then method = :move when :down then method = :move end ou...
[ "def handle(command)\n\n output = \"\"\n if @eating_food\n food_quantities = {:zero => 0, :one => 1, :two => 2, :three => 3, :four => 4, :five => 5, :six => 6,\n :seven => 7, :eight => 8, :nine => 9, :ten => 10}\n units_of_food = food_quantities[command]\n food = @game.player.food\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pickup the treasure in the room if there is any
def pick_up treasure = @game.current_room_model.treasure has_torch = @game.player.has_torch? return "There is no treasure to pick up\n" unless treasure && treasure > 0 return "You cannot see where it is\n" unless has_torch @game.player.wealth += treasure return "You picked-up gems worth $#{tr...
[ "def pickup_treasure\n contents = get_room_items\n if contents == 0\n puts \"THERE IS NO TREASURE TO PICK UP\"\n else\n @wealth += contents\n puts \"PICKED UP $#{contents}!\"\n set_to_room(@room, 0)\n end\n \n end", "def pick_up(item)\n if (item.is_a?Weapon)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transitions to the buying state
def inventory @game.state = BuyingState.new @game @game.state.handle end
[ "def next_state (delivery)\n\t\tif self.state == \"Box it\" && delivery then self.state = \"Delivery\" end\n\t\tif self.state == \"Box it\" && !delivery then self.state = \"Dispatched\" end\n\t\tif self.state == \"Cut it\" then self.state = \"Box it\" end\n\t\tif self.state == \"Bake it\" then self.state = \"Cut it...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts +sexp+ into a Compiler::Node.
def sexp_to_node(sexp) return nil if sexp.nil? if node_class = Node::Mapping[sexp.first] node_class.create(self, sexp) else raise Error, "Unable to resolve '#{sexp.first.inspect}'" end end
[ "def sexp_to_ast(sexp)\n eval sexp\n end", "def process(sexp, level = :expr)\n return fragment('', scope) if sexp.nil?\n\n if handler = handlers[sexp.type]\n return handler.new(sexp, level, self).compile_to_fragments\n else\n error \"Unsupported sexp: #{sexp.type}\"\n end...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Everything should have the same album tag
def all_same_album?(tags) all_same_tag?(tags, :album) end
[ "def fix_album_tags\n file_list = []\n file_list = select_files(\"#{@library_root}/**/D[0-9][0-9]_*.mp3\")\n\n album_name = \"\"\n temp_hash = {}\n\n # create album_name from file name \n # \"D09_0855_GS_10d.mp3\" gets album \"D09_10d\"\n file_list.each do |name|\n w = (File.basename(name)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Everything should have the same year tag
def all_same_year?(tags) all_same_tag?(tags, :year) end
[ "def year() end", "def match_year?(doc, date)\n return true unless year\n\n idate = RelatonBib.parse_date doc[\"issued-date\"], false\n idate.between? date, date.next_year.prev_day\n end", "def year? = unit == 'year'", "def store_years_encompassed(doc)\n raw_values = [:date, :date_associa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
And probably of the same genre. (Who cares, really, about the genre tag anyway?)
def all_same_genre?(tags) all_same_tag?(tags, :genre) end
[ "def genres\n songs.collect do |song|\n song.genre\n end\n .uniq #does not return duplicate genres if the artist has more than one song of a particular genre (artist has many genres through songs)\n end", "def has_genre?(genre)\n map(&:genre).flatten.uniq.include? genre\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the relevant tags for all files.
def all_tags(files) supported(files).map { |f| Aur::FileInfo.new(f).our_tags } end
[ "def tag_files\n Dir[File.join(@bag_dir, '*')].select { |f| File.file? f }\n end", "def tags_used\n s = Set.new\n @selected_files.each do |file|\n s.merge file.tags\n end\n s.to_a.map { |v| v.downcase }\n end", "def tags\n return @tags if @tags\n return @t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a Hash of only the rakefiles that have tasks to be run. key = rakefile name, value = EvaluatedRakeFile Add the tasks to run for each EvaluatedRakeFile
def rakefiles_with_tasks_to_run rakefiles_with_tasks = new_hash_of_eval_rakefiles # This isn't efficient, but it's clear: all_tasks_to_run.each do |task_to_run| rakefilename = task_to_run.filename ev_rakefile_to_run = self.all_rakefiles[rakefilename] ev_rakefile_to_run.tasks_...
[ "def all_evaluated_tasks_in_files(given_dir)\n eval_tasks = []\n\n [SOMETASK1, SOMETASK2, SOMETASK3, SOMETASK4, SOMETASK5].each do |sometask|\n eval_tasks << OneTimeTasker::EvaluatedRakeTask.new(scoped(sometask), File.join(q1_dir(given_dir), SOME_TASKS_RAKEFILE))\n end\n\n eval_tasks << OneTimeTask...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If there are tasks with the same name, mark them as duplicates and log them.
def set_and_log_duplicate_tasks(evaluated_tasks) return [] if evaluated_tasks.empty? # get all of the task_names that are duplicates (TODO ruby 2.7: replace this with .tally) duplicated_names = evaluated_tasks.group_by(&:name).select { |_name, tasks | tasks.size > 1 }.keys # Guard condition: ...
[ "def set_and_log_task_as_duplicate(duplicated_task, tasks_with_same_name)\n\n dup_filname = duplicated_task.filename\n\n # Get all of the other tasks that have this task name and set them as being a duplicate of this one\n the_other_dup_tasks = tasks_with_same_name.reject { |other_task| other_task ==...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return all of the tasks that should be run: No duplicates, no tasks that have previously been run successfully.
def all_tasks_to_run self.all_tasks - all_tasks_previously_run - all_tasks_duplicates end
[ "def complete_tasks\n tasks.select { |t| t.done? }\n end", "def successful_tasks\n @successful_tasks ||= @tasks_results.select(&:success?)\n end", "def all_completed\n completed_tasks = []\n @task_list.each do |task|\n if task.done?\n completed_tasks << task\n end\n end\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
All .rake files in the onetime_tasks_path
def onetime_rake_files tasks_dir = self.tasks_directory return [] unless Dir.exist?(tasks_dir) && !Dir.empty?(tasks_dir) Dir.glob(File.join('**', '*.rake'), base: tasks_dir) end
[ "def task_files\r\n Dir.chdir(Rails.root.join('lib', 'tasks')) do |dir|\r\n @task_files = Dir[\"*.rake\"]\r\n end\r\n @task_files = @task_files.reject{|task|\r\n task !~ /\\Abg_worker_/}.map{|task|\r\n task.sub('bg_worker_', '')\r\n }\r\n end", "def rakefiles\n @rakefiles ||= []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a new EvaluatedRakeFile for the rakefilename if we don't already have it. Add all task names to the EvalutedRakeFile that it doesn't already have.
def add_rakefile_and_tasks(rakefilename, task_names) # creates a new EvaluatedRakeFile entry if needed ev_rakefile = self.all_rakefiles[rakefilename] ev_rakefile.add_task_names(task_names) self.all_tasks.concat(ev_rakefile.all_tasks) ev_rakefile end
[ "def add_eval_task_named(task_name)\n new_ev_task = EvaluatedRakeTask.new(task_name, self.filename)\n add_eval_task(new_ev_task)\n\n new_ev_task\n end", "def rakefiles_with_tasks_to_run\n\n rakefiles_with_tasks = new_hash_of_eval_rakefiles\n\n # This isn't efficient, but it's clear:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find a SuccessfulAttempt for the EvaluatedTask. if a SuccessfulAttempt is found, return the first one found. else return nil if none found
def find_successful_attempt_for_task(evaluated_task) self.successful_task_attempts.detect { |already_ran_task| already_ran_task.task_name == evaluated_task.name } end
[ "def get_attempt(problem)\n\t\tif problem\n\t\t\treturn self.attempts.where(problem_id: problem.id).first\n\t\tend\n\tend", "def get_first_failed_job()\n # the first failed job if any, nil otherwise\n return (@retry_jobs_queue.size() > 0)? @retry_jobs_queue.deq() : nil\n end", "def find_task\n ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new element on any method missing calls. Returns self, so you can chain calls (eg html.div('foo').span('bar') )
def method_missing(method, *args, &block) parts = method.to_s.match(/^([a-z]+[0-9]?)$/) if parts # Assume it's a new element, create the tag tag(parts[1], *args, &block) else # There really is no method... super end end
[ "def method_missing(method, *args, &block)\n super(method, *args) unless block_given?\n options, attrs, element = (args.detect { |arg| arg.is_a?(Hash) } || {}), {}, nil\n\n # handle methods separately if they match the pre-defined elements\n if ELEMENTS.include?(method.to_sym)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /public_repositories GET /public_repositories.json
def index @public_repositories = PublicRepository.all end
[ "def repositories\n response = self.class.get('/repositories').body\n JSON.parse(response)\n end", "def list_repositories\n JSON.parse(request(:get, ''))\n end", "def repositories\n get_request(\"/1.0/user/repositories\")\n end", "def public_repositories\n raw_repos = GitHub::API.j...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /public_repositories POST /public_repositories.json
def create @public_repository = PublicRepository.new(public_repository_params) respond_to do |format| if @public_repository.save format.html { redirect_to @public_repository, notice: 'Public repository was successfully created.' } format.json { render :show, status: :created, location: @p...
[ "def index\n @public_repositories = PublicRepository.all\n end", "def create\n #@repo = Repo.new(repo_params)\n\n user= params[:user]\n repo= params[:repos]\n\n url = BASE_URL + \"repos/\" + user + \"/\" + repo + \"/collaborators\"\n # url = BASE_URL + \"repos/rails/rails/collaborators\"\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /public_repositories/1 DELETE /public_repositories/1.json
def destroy @public_repository.destroy respond_to do |format| format.html { redirect_to public_repositories_url, notice: 'Public repository was successfully destroyed.' } format.json { head :no_content } end end
[ "def destroy\n @repository = Repository.find(params[:id])\n @repository.destroy\n\n respond_to do |format|\n format.html { redirect_to repositories_path }\n format.json { head :no_content }\n end\n end", "def destroy\n @repo = Repo.find(params[:id])\n @repo.destroy\n\n respond_to d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use this method in DSL methods to add a file pattern to config
def add_file_pattern(name, pattern_string) if name.to_s !~ FILE_PATTERN_NAME_REGEX raise ArgumentError.new("A file pattern name must match this regex: #{ FILE_PATTERN_NAME_REGEX.inspect }") end @file_patterns[name.to_sym] = pattern_string.to_s end
[ "def file_pattern(name, pattern_string = nil, &pattern_block)\n if block_given?\n config.add_file_pattern(name, pattern_block.call)\n elsif pattern_string\n config.add_file_pattern(name, pattern_string)\n else\n raise(RtfileError, \"You must provide either pattern_str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use this method in DSL methods to add a kramdown converter method to config
def add_kramdown_converter_method(name, method_name) @kramdown_converter_methods[name.to_sym] = method_name.to_sym end
[ "def kramdown_converter_method(name, method_name)\n config.add_kramdown_converter_method(name, method_name)\n end", "def kramdown_converter_method(name)\n get_config_val(@kramdown_converter_methods, name)\n end", "def kramdown_conversion_method_name\n :to_kramdown_repositext\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a kramdown converter method
def kramdown_converter_method(name) get_config_val(@kramdown_converter_methods, name) end
[ "def kramdown_conversion_method_name\n :to_kramdown_repositext\n end", "def kramdown_converter_method(name, method_name)\n config.add_kramdown_converter_method(name, method_name)\n end", "def add_kramdown_converter_method(name, method_name)\n @kramdown_converter_methods[name.to_sy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes a glob pattern from file spec
def compute_glob_pattern(file_spec) segments = file_spec.split(Repositext::Cli::FILE_SPEC_DELIMITER) r = '' if segments.all? { |e| e =~ BASE_DIR_NAME_REGEX || e =~ FILE_PATTERN_NAME_REGEX } # file_spec consists of named base_dir and/or file_pattern bd = segments.detect { |e| ...
[ "def glob(path); end", "def private_glob_expression\n \"#{base_path}/*_spec.rb\"\n end", "def pattern_with_glob_pattern(*pattern, **options)\n options[:uri_decode] ||= false\n pattern = Mustermann.new(*pattern.flatten, **options)\n @glob_patterns ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes a hash with validation file specs from input_file_specs
def compute_validation_file_specs(input_file_specs) input_file_specs.inject({}) { |m,(fs_name, fs_string)| base_dir, file_pattern = fs_string.split(Repositext::Cli::FILE_SPEC_DELIMITER).compact if base_dir.nil? || file_pattern.nil? raise ArgumentError.new("file_spec requires both...
[ "def compute_validation_file_specs(input_file_specs)\n input_file_specs.inject({}) { |m,(fs_name, fs_attrs)|\n a_base_dir, a_file_selector, a_file_extension = fs_attrs\n m[fs_name] = [\n compute_base_dir(a_base_dir),\n compute_file_selector(a_file_selector),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the absolute path of primary_repo with a guaranteed trailing slash at the end
def primary_repo_base_dir File.expand_path( setting(:relative_path_to_primary_repo), base_dir(:rtfile_dir) ).sub(/\/?\z/, '') + '/' end
[ "def get_repo_abs_path( dirname )\n\t\t\tif dirname == nil then\n\t\t\t\t@repo\n\t\t\telse\n\t\t\t\tFile.join( @repo, dirname )\n\t\t\tend\n\t\tend", "def repo_path\n @config.get_value('GIT_REPO_ROOT')\n end", "def abspath\n \"#{repo_base_path}/#{self.git_repo_path}\"\n end", "def repository_path ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a key's value from container. Raises if an unknown key is requested.
def get_config_val(container, key, raise_on_unknown_key = true) key = key.to_sym if raise_on_unknown_key && !container.keys.include?(key) raise RtfileError.new("You requested an unknown key: #{ key.inspect }") end container[key] end
[ "def get(key)\n position = find(key)\n if position != nil\n @values[position]\n else\n nil\n end\n end", "def fetch(key)\n return @keys[key] ? @keys[key] : \"value not found\"\n end", "def get_value(collection, key)\n @data[collection][key]\n end", "def get(key)\n get_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
title:legend: xAxis: yAxis: tooltip: credits: :plotOptions
def defaults_options self.title({ :text=>"example test title from highcharts gem"}) self.legend({ :layout=>"vertical", :style=>{} }) self.xAxis({}) self.yAxis({ :title=> {:text=> nil}, :labels=>{} }) self.tooltip({ :enabled=>true }) self.credits({ :enabled => false}) self.plot...
[ "def legend; end", "def show_legend; end", "def legend_position; end", "def defaults_options\n self.title({:text => nil})\n self.legend({:layout => \"vertical\", :style => {}})\n self.xAxis({})\n self.yAxis({:title => {:text => nil}, :labels => {}})\n self.tooltip({:enabled => true})\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method will generate the options as a string suitable for straight use. This is required because of the addition of the datetime capability put in. The dates need to be formatted in a JS specific way.
def options_string options_collection = [] options.keys.each do |key| k = key.to_s.camelize.gsub!(/\b\w/) { $&.downcase } options_collection << "\"#{k}\": #{options[key].to_json}" end # This check is put in to catch for those graphs that are time series charts. In that event th...
[ "def to_s\n @options.join(' ')\n end", "def format_options\n return \"\" if @parameters.options.empty?\n\n longest_option = @parameters.options.map(&:long)\n .compact.max_by(&:length).length\n any_short = @parameters.options.map(&:short).compact.any?...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a test which tests authorization code. It assumes a method called access_denied? on the test case. The access_denied? method should return true when access is denied (ie. a 403 status code) and false in other cases. Example: should.allow.get :index
def allow Test::Spec::Rails::Macros::Authorization::TestGenerator.new(test_case, :access_denied?, false, 'Expected access to be allowed' ) end
[ "def test_index_authorized\n authorize @valid_user\n get :index\n assert_response :success\n assert_template \"index\"\n end", "def generate_authorization_testcase(testplan)\n fail \"nil\" if testplan.nil?\n id = testplan[\"id\"]\n\n tc = \"Feature: CWE-285: Improper Authorization\\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a test which tests authorization code. It assumes a method called access_denied? on the test case. The login_required? method should return true when the visitor was asked for credentials (ie. a 401 status code or a redirect to a login page) and false in other cases. Example: should.require_login.get :index
def require_login Test::Spec::Rails::Macros::Authorization::TestGenerator.new(test_case, :login_required?, true, 'Expected login to be required' ) end
[ "def allow\n Test::Spec::Rails::Macros::Authorization::TestGenerator.new(test_case,\n :access_denied?, false,\n 'Expected access to be allowed'\n )\n end", "def test_index_authorized\n authorize @valid_user\n get :index\n assert_response :success\n assert_template ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }