query
stringlengths
7
9.5k
document
stringlengths
10
1.07M
negatives
listlengths
19
19
metadata
dict
PATCH/PUT /air_moistures/1 PATCH/PUT /air_moistures/1.json
def update respond_to do |format| if @air_moisture.update(air_moisture_params) format.html { redirect_to @air_moisture, notice: 'Air moisture was successfully updated.' } format.json { render :show, status: :ok, location: @air_moisture } else format.html { render :edit } ...
[ "def update\n spice = Spice.find_by(id: params[:id])\n spice.update(spice_params)\n render json: spice\nend", "def update_mobile_carrier(args = {}) \n put(\"/mobile.json/#{args[:carrierId]}\", args)\nend", "def update\n authorize! :update, Moon\n @moon = Moon.find(params[:id])\n\n respond_to d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /air_moistures/1 DELETE /air_moistures/1.json
def destroy @air_moisture.destroy respond_to do |format| format.html { redirect_to air_moistures_url, notice: 'Air moisture was successfully destroyed.' } format.json { head :no_content } end end
[ "def delete_floor_plan(args = {}) \n delete(\"/files.json/floorplan/images\", args)\nend", "def destroy\n @json.destroy\n\n head :no_content\n end", "def destroy\n @soil_moisture.destroy\n respond_to do |format|\n format.html { redirect_to soil_moistures_url, notice: 'Soil moisture was success...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
show stops for line
def show_stops(lines, line1) lines.each do |line| if line[:lines] == line1 puts line[:stops] end end end
[ "def draw_line\n print H_SEP * columns\n end", "def draw_alt_line\n @dim.times do |i|\n if i.even?\n print draw_x\n else\n if @type == \"allx\"\n print draw_x\n elsif @type == \"alt\"\n print draw_dot\n end\n end\n end\n end", "def get_line...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search through provided list of trips and filter optionally by service_id and route_id
def search_trips(trips, opts = {}) service_id = opts[:service_id] route_id = opts[:route_id] service_id ||= 'S1' valid_trips = trips.select { |trip| trip[:service_id].eql? service_id } trips_with_route = valid_trips.select{ |trip| if !route_id.nil? ...
[ "def trips_by_route_id(route_id)\n get \"/gtfs/trips/routeid/#{route_id}\"\n end", "def search\n #set @trips variable with all matched trips from DB\n\n #route to special view that lists all trips but for each respective river (unlike index, which lists all trips for 1 river)\n redirect_to \n en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Analyze the structure of the HTML document and score content blocks for likelihood of containing useful content
def analyze opt = DEFAULTS.clone opt.merge!(@options) @sections = [] factor = continuous = 1.0 body = '' score = 0 # The content is split into blocks of divs list = @raw_content.split(/<\/?(?:div)[^>]*>/) list.each do |block| n...
[ "def rate_content(content)\n contents = Hash.new\n for i in 0...content.size\n contents[\"#{i}\"] = 0.0\n\n # chceking if div does not contain whole document\n contents[\"#{i}\"] += -20 if content[i].to_s.lines.count > @@lines*0.95\n\n # rating contents for tags they contain\n content...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the given block has only tags without text.
def has_only_tags?(block) block.gsub(/<[^>]*>/im, '').strip.length == 0 end
[ "def is_block_tag(text)\n BlockPatterns::BLOCK_TAG_REGEX.match(text.strip).present?\n end", "def no_paragraph_tag?(text)\n text !~ /^\\<p/\n end", "def element_is_text?\n !self[:is_tag]\n end", "def first_tag_is_a_block_tag(html)\n blockelems = [\"P\", \"H1\", \"H2\", \"H3\", \"H4...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Eliminates link heavy blocks and blocks that are lists of links and then returns block stripped of tags
def clean_block(block) # Return empty block if it is a list of links return "" if is_link_list?(block) # Return empty block if it is a very link heavy block count = 0 no_links = block.gsub(/<a\s[^>]*>.*?<\/a\s*>/im){count+=1;''}.gsub(/<form\s[^>]*>.*?<\/form\s*>/im, '') ...
[ "def process_block_elements (out)\n re = '\\\\s+(<\\\\/?(?:area|base(?:font)?|blockquote|body' +\n '|caption|center|cite|col(?:group)?|dd|dir|div|dl|dt|fieldset|form' +\n '|frame(?:set)?|h[1-6]|head|hr|html|legend|li|link|map|menu|meta' +\n '|ol|opt(?:group|ion)|p|param|t(?:able|body|head|...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether a block is link list or not
def is_link_list?(st) if st =~ /<(?:ul|dl|ol)(.+?)<\/(?:ul|dl|ol)>/im listpart = $1 outside = st.gsub(/<(?:ul|dl)(.+?)<\/(?:ul|dl)>/imn, '').gsub(/<.+?>/mn, '').gsub(/\s+/, ' ') list = listpart.split(/<li[^>]*>/) list.shift rate = evaluate_list(list) o...
[ "def link?\n type == LINK_TYPE\n end", "def isLinktype\n @RecordType == LINKTYPE\n end", "def local_link?\n [1,2].include?(link_type)\n end", "def list?\n return @is_list if defined? @is_list\n @is_list = %w(ul ol).include?(node.name)\n end", "def is_linktype?(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We might have to remove certain characters, but for now we just CGI.escape it and remove any periods
def clean_name(name) CGI.escape(name).gsub('.', '') end
[ "def cgi_escape(input); end", "def remove_dots\n @username.gsub!('.', '')\n end", "def sanitize_param(p)\n CGI.escape(p.gsub(/ /, \"+\")).gsub(\"%2B\", \"+\")\n end", "def sanitize_dirty_string(str)\n str.to_s.strip.gsub('.', '')\n .gsub('-', '')\n .gsub('_', '')\n .g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
createsa minimal openurl to make a new request to umlaut
def create_openurl(request, wh) metadata = request.referent.metadata co = OpenURL::ContextObject.new cor = co.referent cor.set_format(wh['record_type']) cor.add_identifier("info:oclcnum/#{wh['oclcnum']}") cor.set_metadata('aulast', metadata['aulast'] ) if metadata['aulast'] cor.set_meta...
[ "def new_http(uri); end", "def get_url\n \"http://www.allabolag.se/#{self.identification_no.gsub(\"-\",\"\")}\"\n end", "def create_url\n\t\tif self.url.blank?\n\t\t\tself.url = self.title.downcase.gsub(/[^a-zA-Z0-9]+/, \"-\").chomp(\"-\")\n\t\tend\t\n\tend", "def fake_url\n return source.to_s + pub_da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We just link to worldcat using the oclc number provided FIXME this might need special partial if we incorporate a cover image
def create_worldcat_widely_held(request, xml) # try to prevent circular links top_holding_info = get_widely_held_info(xml) return nil if circular_link?(request, top_holding_info) # http://www.worldcat.org/links/ most = top_holding_info['most'] title = top_holding_info['title'] ...
[ "def generate_rdf_catlink(b,ty)\n ul = \"http://catalog.library.cornell.edu/catalog/#{id}\"\n # if no elect access data, 'description' field.\n b.dc(:description,ul)\n end", "def category\n path = @path_remote.split('/')\n return path[3] # Could require changes depending on the structure of the m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new csv differ, this differ can then be used to create a split and a unified view. The raw csv strings are decoded and the csv header is extracted. If the table has more than 100 rows, a simplified version of the table will be rendered this will limit the performance hit of a very long table.
def initialize(generated, expected) @generated = CSV.parse((generated || '').lstrip, nil_value: '') @expected = CSV.parse((expected || '').lstrip, nil_value: '') @gen_headers, *@generated = @generated @gen_headers ||= [] @exp_headers, *@expected = @expected @exp_headers ||= [] @simplified_...
[ "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render a unified table view based on the data passed when creating the CsvDiffer instance.
def unified builder = Builder::XmlMarkup.new builder.table(class: 'unified-diff diff csv-diff') do builder.colgroup do builder.col(class: 'line-nr') builder.col(class: 'line-nr') builder.col(span: @combined_headers.length) end builder.thead do builder.tr do ...
[ "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render a split table view based on the data passed when creating the CsvDiffer instance. The split view renders two tables, that individually have a horizontal scrollbar.
def split builder = Builder::XmlMarkup.new builder.div do split_build_table(builder, @gen_headers, true) split_build_table(builder, @exp_headers, false) end.html_safe end
[ "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build one of the two tables of the split table view (see function 'split')
def split_build_table(builder, headers, is_generated_output) builder.table(class: 'split-diff diff csv-diff') do builder.colgroup do builder.col(class: 'line-nr') builder.col(span: headers.length) end builder.thead do if is_generated_output icon_cls = 'mdi-file-ac...
[ "def split\n builder = Builder::XmlMarkup.new\n\n builder.div do\n split_build_table(builder, @gen_headers, true)\n split_build_table(builder, @exp_headers, false)\n end.html_safe\n end", "def get_table\n parts = @rest.split(TABLE_DIV_REGEXP)\n\n @table_name = parts.pop\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a simplified version of the unified table body This simplified view combines all rows in a column into 1 row with newlines. The columns are still separate, but the diff is less accurate.
def unified_simple_body(builder) gen_cols = @generated.transpose.map { |col| col.join("\n") } builder.tr do builder.td(class: 'line-nr') do builder << (1..@generated.length).to_a.join("\n") end builder.td(class: 'line-nr') builder << Array.new(@combined_headers.length) { |i| @ge...
[ "def unified\n builder = Builder::XmlMarkup.new\n builder.table(class: 'unified-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(class: 'line-nr')\n builder.col(span: @combined_headers.length)\n end\n builder.thead do\n buil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a simplified version of the split table body This simplified view combines all rows in a column into 1 row with newlines. The columns are still separate, but the diff is less accurate.
def split_simple_body(builder, data, cls) gen_cols = data.transpose.map { |col| col.join("\n") } builder.tr do builder.td(class: 'line-nr') do builder << (1..data.length).to_a.join("\n") end gen_cols.each do |col| builder.td(class: cls) do builder << CGI.escape_html(...
[ "def split_build_table(builder, headers, is_generated_output)\n builder.table(class: 'split-diff diff csv-diff') do\n builder.colgroup do\n builder.col(class: 'line-nr')\n builder.col(span: headers.length)\n end\n builder.thead do\n if is_generated_output\n icon_cls =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrap the row elements (cells) in html td tags. Determine what class to use based on the row chunk action. This way the row will be correctly formatted (eg. green background).
def new_row(chunk) new_class = { '-' => '', '+' => 'ins', '=' => 'unchanged', '!' => 'ins' }[chunk.action] [new_class.empty?, chunk.new_element.map { |el| %(<td class="#{new_class}">#{el}</td>) }] end
[ "def table_row_helper(cells, opts={})\n if cells[0] == :divider\n # this is not very nice..\n \"<tr><td colspan='#{cells[1]}' class='divider'><div></div></td></tr>\".html_safe\n else\n # Tried making this with content_tag but couldn't get the html_safe to work right... :S\n \"<tr>#{cells.c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compare the table headers of the generated and expected table. The combined headers is the minimal set of headers that include the generated and expected headers (including duplicates). The indices arrays can be used to map the original input headers to the correct headers in the combined header list.
def diff_header_indices(generated, expected) counter = 0 gen_indices = [] exp_indices = [] gen_headers = [] exp_headers = [] combined_headers = [] Diff::LCS.sdiff(generated, expected) do |chunk| case chunk.action when '-' gen_indices << counter counter += 1 ...
[ "def compare_header_array_order(array_to_compare)\n index = 0\n @header_array.each do |column|\n set_error_message(\"Columns are out of order #{array_to_compare[index][:name]}\") unless array_to_compare[index][:name] == column\n index += 1\n end\n end", "def compare_header(header, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
register a timeout listener that will be called in given seconds (aprox). Returns a listener object that can be used with clear_timeout to remove the listener
def set_timeout(seconds, block) listener = { seconds: seconds, block: block, time: @time, target: @time + seconds } @timeout_listeners.push listener listener end
[ "def set_timeout(seconds = @interval, block = nil, &proc_block)\n the_block = block == nil ? proc_block : block\n throw 'No block provided' if the_block == nil\n listener = { seconds: seconds, block: the_block, target: @time + seconds }\n @timeout_listeners.push listener\n listener\n end", "def _a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an array with two values, the first being a hash of edges with a number containing their class assignment, the second valud is a boolean which states whether or not the graph is a comparability graph Complexity in time O(d|E|) where d is the maximum degree of a vertex Complexity in space O(|V|+|E|)
def gamma_decomposition k = 0; comparability=true; classification={} edges.map {|edge| [edge.source,edge.target]}.each do |e| if classification[e].nil? k += 1 classification[e] = k; classification[e.reverse] = -k comparability &&= plexus_comparability_explore(e, k, clas...
[ "def gamma_decomposition\r\n k = 0; comparability=true; classification={}\r\n edges.map {|edge| [edge.source,edge.target]}.each do |e|\r\n if classification[e].nil?\r\n k += 1\r\n classification[e] = k; classification[e.reverse] = -k\r\n comparability &&= gratr_comparabil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns one of the possible transitive orientations of the UndirectedGraph as a Digraph
def transitive_orientation(digraph_class=Digraph) raise NotImplementError end
[ "def transitive_orientation(digraph_class=Digraph)\r\n raise NotImplementError\r\n end", "def to_rgl_oriented\n RGL::ImplicitGraph.new do |g|\n g.vertex_iterator do |block|\n self.each_segment do |segment|\n [:+, :-].each do |orient|\n block.call([segment, orie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
searches books.google.com for books by isbn. returns either a hash, or if given an object providing a from_hash(hash) method will fill it with the data. the object members must be named like the keys in the hash.
def search_by_isbn(isbn, object = nil) return nil if (isbn = isbn.gsub(/-/,"")).nil? @client = HTTPClient.new @book_hash = std_entry @isbn = isbn ol_hash = search_open_library isbndb_hash = search_isbndb gb_hash = search_google_books @book_hash.each {|k,v| @book_hash[k] = ol_has...
[ "def book_by_isbn(isbn)\n Hashie::Mash.new(request('/book/isbn', :isbn => isbn)['book'])\n end", "def book_by_isbn(isbn)\n\t\t\tresponse = request('/book/isbn', :isbn => isbn)\n\t\t\tHashie::Mash.new(response['book'])\t\t\t\t\n\t\tend", "def find_books(query, isbn)\n sparql = SPARQL::Client.new(\"h...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new AESPipe object with the given _options_. If a _block_ is given, it will be passed the newly created AESPipe object. _options_ may contain the following keys: :mode:: The mode of the cipher, either :encrypt or :decrypt. Defaults to :encrypt. :block_size:: The blocksize to use with the cipher. Defaults to 4...
def initialize(options={},&block) @mode = options.fetch(:mode,:encrypt).to_sym @block_size = options.fetch(:block_size,DEFAULT_BLOCK_SIZE).to_i @key_size = options.fetch(:key_size,DEFAULT_KEY_SIZE).to_i @iv = options.fetch(:iv,DEFAULT_IV).to_s @hash = options.fetch(:h...
[ "def cipher\n aes = OpenSSL::Cipher::Cipher.new(\"aes-#{@key_size}-cbc\")\n\n case @mode\n when :encrypt\n aes.encrypt\n when :decrypt\n aes.decrypt\n else\n raise(InvalidMode,\"invalid mode #{@mode}\")\n end\n\n aes.key = @key\n aes.iv = @iv\n\n yie...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a new AES cipher object. If a _block_ is given it will be passed the newly created cipher.
def cipher aes = OpenSSL::Cipher::Cipher.new("aes-#{@key_size}-cbc") case @mode when :encrypt aes.encrypt when :decrypt aes.decrypt else raise(InvalidMode,"invalid mode #{@mode}") end aes.key = @key aes.iv = @iv yield aes if block_given? ...
[ "def cipher\n OpenSSL::Cipher::AES.new(256, :CBC)\n end", "def create_cipher_simple(mode)\n iv,pwd,salt = parse_key(@key)\n\n cipher = OpenSSL::Cipher.new 'AES-128-CBC'\n cipher.send(mode)\n\n cipher.iv = iv\n cipher.key = pwd\n cipher\n end", "def create_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Processes an input stream of the given _file_ and the specified _block_. If _file_ is not given +STDIN+ will be used instead. The specified _block_ will be passed each block of data from the stream. Once the _block_ has returned the input stream will be closed.
def process_input(file=nil) input = if file File.new(file.to_s) else STDIN end loop do text = input.read(@block_size) break unless text yield text end input.close return nil end
[ "def with_io(&block)\n if self.input_file\n File.open(self.input_file, \"r\", &block)\n else\n block.call(environment.input_buffer)\n end\n end", "def read_file(block=0)\n Rula.log(Logger::DEBUG,\"Reading file #{filename} block #{block}\",self)\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select instances by role, with optional name constraints. Select the "master" app instance: select_instances(app_master: true) Select the "master" db instance on a solo or multiinstance env: select_instances(solo: true, db_master: true) Select app, app_master, or utils (only if they are named resque or redis): select_i...
def select_instances(options) instances_by_role(options.keys).select do |inst| # get the value of the string/symbol key that matches without losing nil/false values val = options.fetch(inst.role.to_sym) { options.fetch(inst.role.to_s, false) } case val when true, false t...
[ "def instances_by_role(*roles)\n roles = roles.flatten.map(&:to_s)\n instances.select { |inst| roles.include?(inst.role.to_s) }\n end", "def get_instances_by_role(group, role)\n get_instances(group).select do |instance|\n if not instance.tags['role'].nil? and instance.ready?\n in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple version of select_instances that only selects roles, not names instances_by_role(:app_master, :app) same instances_by_role(%w[app_master app]) same select_instances(app_master: true, app: true) same
def instances_by_role(*roles) roles = roles.flatten.map(&:to_s) instances.select { |inst| roles.include?(inst.role.to_s) } end
[ "def select_instances(options)\n instances_by_role(options.keys).select do |inst|\n # get the value of the string/symbol key that matches without losing nil/false values\n val = options.fetch(inst.role.to_sym) { options.fetch(inst.role.to_s, false) }\n\n case val\n when tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Throws a POST request at the API to /add_instances and adds one instance to this environment. Usage example: api = EY::CloudClient.new(token: 'your token here') env = api.environment_by_name('your_env_name') env.add_instance(role: "app") env.add_instance(role: "util", name: "foo") Note that the role for an instance MUS...
def add_instance(opts) unless %w[app util].include?(opts[:role].to_s) # Fail immediately because we don't have valid arguments. raise InvalidInstanceRole, "Instance role must be one of: app, util" end # Sanitize the name to remove whitespace if there is any if opts[:...
[ "def create_instance(body)\n headers = default_headers\n headers['Content-Type'] = 'application/x-www-form-urlencoded'\n JSON.parse(post('/instances', urlencode(body), headers))['instances']\n end", "def add_instance(instance)\n register_response = client.register_instances_with_load_balancer(load_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a request to the API to remove the instance specified by its "provisioned_id" (Amazon ID). Usage example: api = EY::CloudClient.new(token: 'token') env = api.environment_by_name('my_app_production') bad_instance = env.instance_by_id(12345) instance ID should be saved upon creation env.remove_instance(bad_instance...
def remove_instance(instance) unless instance raise ArgumentError, "A argument of type Instance was expected. Got #{instance.inspect}" end # Check to make sure that we have a valid instance role here first. unless %w[app util].include?(instance.role) raise InvalidIns...
[ "def remove_instance(remove_instance)\n request = {:body => { :request => {:role => role } } } if [:app,:util].include? remove_instance\n request = {:body => { :request => { :provisioned_id => remove_instance.amazon_id } }} unless [:app,:util].include? remove_instance\n EngineyardAPI::API.post(\"#{@...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get last weather update
def last_weather weathers.last end
[ "def last_updated\n self.dig_for_datetime(\"lastUpdateOn\")\n end", "def last_update_at\n connection.get_metric_last_update_at(@id)\n end", "def current_weather\n return @weather[2]\n end", "def last_updated\n @last_updated\n end", "def last_update\n @record.updated_at\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
User get read access to device ( owner or public device)
def get_read_access( u) return (u == self.user) || (self.public) end
[ "def readable?\n status_flag?(:kSecReadPermStatus)\n end", "def readable_by? user\n check_access(user, READABLE_BY_AUTH, READABLE)\n end", "def acl\n 'public-read'\n end", "def accountant_allow_read(permission)\n return accountant_right(permission) > 0\n end", "def dor_read...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /album_genres/1 GET /album_genres/1.json
def show @album_genre = AlbumGenre.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @album_genre } end end
[ "def index\n @genres = Genre.all\n\n render json: @genres\n end", "def genres( album )\n return get_metadata( album )[:genres]\n end", "def show\n @song_genre = SongGenre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @song_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /album_genres/new GET /album_genres/new.json
def new @album_genre = AlbumGenre.new respond_to do |format| format.html # new.html.erb format.json { render json: @album_genre } end end
[ "def new\n @genre = Genre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @genre }\n end\n end", "def new\n @album = Album.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album }\n end\n end"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /album_genres POST /album_genres.json
def create @album_genre = AlbumGenre.new(params[:album_genre]) respond_to do |format| if @album_genre.save format.html { redirect_to @album_genre, notice: 'Album genre was successfully created.' } format.json { render json: @album_genre, status: :created, location: @album_genre } el...
[ "def updategenres\n @album = Album.find(params[:id])\n album_param = params[:albums] \n album_param[:genres].each do |genre_id|\n genre = Genre.find(genre_id)\n @album.genres << genre \n end \n respond_to do |format|\n format.html { redirect_to(@album) }\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /album_genres/1 DELETE /album_genres/1.json
def destroy @album_genre = AlbumGenre.find(params[:id]) @album_genre.destroy respond_to do |format| format.html { redirect_to album_genres_url } format.json { head :no_content } end end
[ "def destroy\n @album.destroy\n render json: @album\n end", "def destroy\n json_destroy(genre)\n end", "def destroy\n\n @album = @user.albums.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :no_content }\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
crear un metodo initialize que inicialice las variables de instancia "revenue" y "costs" a cero
def initialize @revenue = 0 @costs = 0 end
[ "def initialize(employee_discount = 0)\n # initialization\n @total = 0\n @discount = employee_discount\n # creates items array and last_transaction hash to keep track of items and\n # the last purchase made\n @items = []\n @last_transaction = {}\n end", "def initialize(*params) \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
crear un metodo "credit" que reciba un parametro "amount" y se lo sume a la variable de instancia "revenue"
def credit(amount) @revenue += amount end
[ "def add_credit(transaction)\n if transaction.type == 'Expense'\n @credit -= transaction.quantity.to_f\n else\n @credit += transaction.quantity.to_f\n end\n self.update()\n\n end", "def attempt_credit_purchase (amount, description)\n\t if use_credit(amount)\n\t \t@purchases.push(description)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
has many clients through appointments
def clients Appointments.all.collect do |appointment| appointment.client end end
[ "def appointments\n Appointment.all.filter { |appointment| appointment.provider_id == self.id || appointment.user_id == self.id}\n end", "def my_appointments(user)\n Appointment.where(user_id: user.id)\n end", "def appointments\n Appointment.all.select{|appointment| appointment.stude...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
recursively crawls the parser rules and looks for elements that index values. Adds an empty index for each of these.
def setup_indexes rules if rules[:children] rules[:children].each_pair do |child_name,child_rules| if index = child_rules[:index] @indexes[index[:name]] = {} end setup_indexes(child_rules) end end end
[ "def parse_index_list\n self.seek(self.stat.size - 200)\n # parse the index offset\n tmp = self.read\n tmp =~ MzML::RGX::INDEX_OFFSET\n offset = $1\n # if I didn't match anything, compute the index and return\n unless (offset)\n return compute_index_list\n end\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
combo_changed event handlers for composite foreign key: carton_pack_type_id combo_changed event handlers for composite foreign key: basic_pack_id search combo_changed event handlers for the unique index on this table(carton_pack_products)
def carton_pack_product_type_code_search_combo_changed type_code = get_selected_combo_value(params) session[:carton_pack_product_search_form][:type_code_combo_selection] = type_code @basic_pack_codes = CartonPackProduct.find_by_sql("Select distinct basic_pack_code from carton_pack_products where type_code = '#{type_...
[ "def fg_product_item_pack_product_code_search_combo_changed\n\titem_pack_product_code = get_selected_combo_value(params)\n\tsession[:fg_product_search_form][:item_pack_product_code_combo_selection] = item_pack_product_code\n\t@unit_pack_product_codes = FgProduct.find_by_sql(\"Select distinct unit_pack_product_code ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render multiple boxes. Takes as argument a single array of Hash For the Hash options, please see render_box. The boxes are wrapped in a div with class "textboxes". You can pass individual styling using :textboxes_style => textboxes_style. You can specify a template Hash ( :template => template ) which will be merged wi...
def render_boxes(array = [], options = {}) boxes = "" template = {} if options[:template].class.to_s.eql?("Hash") template = options[:template] end array.each do |individual_options| box_options = template box_options = template.merge(individual_options) unless individual_option...
[ "def render_box(options = {})\n # list of classes for the outer div.\n outer_div_classes = [ \"textbox_container\" ]\n # inner div, same story\n inner_div_classes = [ \"textbox\" ]\n # heading\n heading_classes = [ \"heading\" ]\n\n content = yield if block_given?\n content ||= options[:cont...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render a box. options: content (string) heading (string) float_left (true/false) text_align_center (true/false) highlight (true/false) background_image (url) bigfont (true/false) heading_color (color name, e.g. 'red') background_color (color name, e.g. 'blue') inner_div_style (css style, e.g. "width: 382px; height: 281...
def render_box(options = {}) # list of classes for the outer div. outer_div_classes = [ "textbox_container" ] # inner div, same story inner_div_classes = [ "textbox" ] # heading heading_classes = [ "heading" ] content = yield if block_given? content ||= options[:content] return...
[ "def widget_box(title, options = {}, &block)\n raise \"Bad developer. No nested widget boxes for you!\" if @rendering_widget_box\n @rendering_widget_box = true\n\n # This is where we're going to drop any tabs generated in our block.\n @widget_options = {\n :tabs => [],\n :header_html ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the value of the Selection input for this Choreo.
def set_Selection(value) set_input("Selection", value) end
[ "def set_selection(*args)\n # Check for a cell reference in A1 notation and substitute row and column\n args = row_col_notation(args)\n\n @selection = args\n end", "def select=(value)\n @select = value\n end", "def selected=(selected)\n @selected = selected\n update_cur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the value of the Title input for this Choreo.
def set_Title(value) set_input("Title", value) end
[ "def set_title(title)\n @title = title\n end", "def title=(value)\n @title = value\n end", "def title=(value)\n @title = value\n end", "def setTitle(iTitle)\n @Title = iTitle\n end", "def SetTitle(title)\n\t\t#Title of document\n\t\t@title = title\n\tend", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the value of the URL input for this Choreo.
def set_URL(value) set_input("URL", value) end
[ "def url=(value)\n @url = value\n end", "def set_url(url)\n Utility::check_types({ url=>String }) if $DEBUG\n @url = url\n nil\n end", "def setURL(url)\r\n\t\t\t\t\t@url = url\r\n\t\t\t\tend", "def url=(url)\n @url = url.to_s.strip\n reset!\n end", "def url=(value)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Show logout instead of link to adminpage on adminpanel
def show_logout @show_logout = true end
[ "def admin_dashboard\n if current_user.class == User\n sign_out_and_redirect(current_user)\n end\n end", "def loggout_admin\n if current_admin\n sign_out current_admin \n end \n end", "def logout\n session.delete(:admin_password)\n redirect_to admin_login_path\n end", "def admin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Receiving messages from client and sending to other clients
def client_handler(client, all_clients) client.puts 'Welcome to server, stranger!' loop do msg = client.gets if msg.nil? puts 'Client disconnected' break end all_clients.each { |dest| send_msg(msg, dest) if dest != client } end end
[ "def listen_user_messages( client_ID, client )\n puts \"in listen_user_messages\"\n loop {\n msg = JSON.parse(client.gets.chomp)\n puts sprintf(\"msg.inpect : %s\\n\", msg.inspect)\n command = msg[0]\n if command == 'MSG'\n @clients.each do |other_name, other_client|\n if o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper for model classes. Allows for convenient instantiation of current athlete. This is completely agnostic to class type, it can be a DB model, a PORO, etc. Usage: class Account Strava::Athlete Can also perform lookup through another method: class User < ApplicationRecord has_one :account include Strava.model as: :a...
def model(as: :strava_athlete, via: :access_token, id: nil) Module.new.tap do |mod| str = <<~EOF def self.included(base) base.send(:define_method, :#{as}) { ::Strava::Athlete.new(#{id ? "{'id' => #{id}}" : '{}' }, token: #{via}, current: true) } end EOF mod....
[ "def associate_one(person, account_class)\n return unless person\n\n account = account_class.find_by_secdn(person.dn)\n\n new(person, account)\n end", "def acls\n build_acls acls_config\n end", "def model_class_name\n options[:model] ? options[:model].classify : ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reverse the word order of a given string =begin doctest: reverse word order of a string >> s = "This is test line one." >> reverse_word_order(s) => "one. line test is This" doctest: Lines are handled this way >> s = "This is test line one.\nThis is test line two." >> reverse_word_order(s) => "two. line test is This one...
def reverse_word_order string string.split.reverse.join(' ') end
[ "def reverse_word_order(lines)\n lines.split(' ').reverse.join(' ')\nend", "def word_reverse(str)\n p str.split(' ').reverse.join(' ')\nend", "def word_reverse(string)\n p string.split.reverse.join(' ')\nend", "def reverse_words(string)\n return string if string === \"\"\n sentence_array = string.spl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
define equality between two entities by iterating over instance variables and comparing each field for equality
def ==(entity) rval = true self.instance_variables.each { |variable| rval &= self.instance_variable_get(variable) == entity.instance_variable_get(variable) } rval end
[ "def equality_by_fields(o)\n equality_fields.reduce(true) do |result, property|\n result && o.respond_to?(property) && self.send(property) == o.send(property)\n end\n end", "def ==(other)\n attributes == other.attributes\n end", "def eql?(other)\n return true if equal?(other)\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
undesignate_package params is passed from 'form_nested_params_for_undesignate'
def undesignate(undesignate_package = nil) packages = undesignate_package ? undesignate_package : @params OrdersPackage.undesignate_partially_designated_item(packages) @package.reload.undesignate_from_stockit_order end
[ "def unparse_params\n @_unparse_params ? @_unparse_params.dup : nil\n end", "def untouchable_params_attributes #:nodoc:\n { :outfile_id => true }\n end", "def unpublish\n\t update_attributes! :draft => true\n\tend", "def remove_fields\n end", "def unapprove\n ag = AnnotationGroup.where({g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tell this track's channel to use the given instrument, and also set the track's instrument display name.
def instrument=(instrument) @events << MIDI::ProgramChange.new(@channel, instrument) super(GM_PATCH_NAMES[instrument]) end
[ "def instrument=(instrument)\n @events << \nMIDI::ProgramChange.new(@channel, instrument)\n super(MIDI::GM_PATCH_NAMES[instrument])\n end", "def instrument=(instrument)\n @events << MIDI::ProgramChange.new(@channel, instrument)\n super(MIDI::GM_PATCH_NAMES[instrument])\n end", "def instrument_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Configure Vedeu using a simple configuration DSL.
def configure(&block) fail InvalidSyntax, '`configure` requires a block.' unless block_given? Vedeu::Configuration.configure(&block) end
[ "def setup_basic_config(config, vm_config)\n # Vargrant Box\n config.vm.box = vm_config['base_box']\n \n if vm_config['base_box_version'] != 'latest'\n config.vm.box_version = vm_config['base_box_version']\n end\n\n \n # Vagrant box name\n config.vm.define vm_config['name']\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Register an interface by name which will display output from a event or command. This provides the means for you to define your application's views without their content.
def interface(name = '', &block) API::Interface.define({ name: name }, &block) end
[ "def add_interface(interface)\n @current_interface = interface\n add \"interface #{interface}\"\n end", "def register(interface)\n InvalidInterfaceError.check(interface)\n \n interfaces[interface.to_s.demodulize.underscore.to_sym] = interface\n end", "def reg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Trigger a registered or system event by name with arguments. If the event stored returns a value, that is returned. If multiple events are registered for a name, then the result of each event will be returned as part of a collection.
def trigger(name, *args) Events.use(name, *args) end
[ "def trigger event_name, *args\n event = @events.detect do |evnt|\n evnt.get_name == event_name\n end\n event.trigger *args if (event)\n return !!event\n end", "def trigger(name, *args)\n @eventable ||= Hash.new { |hash, key| hash[key] = [] }\n @eventable[name]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unregisters the event by name, effectively deleting the associated events bound with it also.
def unevent(name) Events.remove(name) end
[ "def unregister(name, handler)\n write(EVENT_UNREGISTER, name, nil)\n type, _label, _message = read_and_dispatch_events\n case type\n when EVENT_CONFIRM\n @events[name] -= [handler]\n when EVENT_UNKNOWN\n raise EventUnknownError, name\n else\n raise EventError, \"i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes all unnessesary data from the traces
def remove_useless_traces_data(params) convert_list_of_json_traces_to_objects(params[0]) create_new_traces @traces_json_string = '[' + @traces_json_string[0...-1] + ']' puts @traces_json_string end
[ "def untrace()\n #This is a stub, used for indexing\n end", "def clean_trace(trace)\n return unless trace\n trace.reject do |line|\n line =~ /(gems|vendor)\\/liquid-logging/\n end\n end", "def clear_transformed_data!\n @transformed_values = []\n end",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a trace string to JSON Object
def convert_json_trace_to_object(trace) JSON.parse(trace[1...-1].insert(0, '{'), object_class: OpenStruct) end
[ "def return_json_string\n @traces_json_string\n end", "def json() JSON.parse( text ); end", "def parse_json(string)\n JSON.parse string\n end", "def JSON(object, *args)\n if object.respond_to? :to_str\n JSON.parse(object.to_str, args.first)\n else\n JSON.generate(object, args.first)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the traces that will be used in the visualization process. This is done by 1 extract the variables names form the trace 2 extract the encoded locals from the trace 3 extract the heap values form the trace 4 extract the code from the trace
def create_new_traces @traces.each do |trace| trace_stack = trace.stack_to_render[0] unless(trace_stack.func_name.include? '<init>') trace_stack_ordered_variable_names = trace_stack.ordered_varnames trace_stack_encoded_locals = trace_stack.encoded_locals trace_heap = trace.heap t...
[ "def generate_tracing_configuration()\n result = \"\"\n\n if @tracing_vars\n @tracing_vars.each_with_index do |var_name, var_index|\n result += \"garbledwebpiratenlibraryname.add_traced_variable('#{var_name}', #{var_index})\\n\"\n end\n result += \"\\n\"\n end\n\n return result\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
getter method to return the new trace as JSON string
def return_json_string @traces_json_string end
[ "def serialize trace_context\n trace_context.trace_id.dup.tap do |ret|\n if trace_context.span_id\n ret << \"/\" << trace_context.span_id.to_i(16).to_s\n end\n if trace_context.trace_options\n ret << \";o=\" << trace_context.trace_options.to_s\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates the full execution trace for the complete source code by executing the command related to Java_Jail
def generate_backend_trace(junit_test_file, files_path, peruser_files_path, student_file_name) raw_code = junit_test_file raw_code.gsub! "\n", "\\n" + "\n" raw_code.gsub! "\t", "\\t" lines = raw_code.split("\n") jUnit_test = '' ...
[ "def go\n @vm = launchTarget()\n generateTrace()\n end", "def inspect_jobs(index = nil)\n return empty_msg if empty?\n desc = []\n puts \"\\n\"\n @jobs.each_with_index do |j, i|\n unless index.nil?\n next unless i == index\n end\n desc << '|...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the line number
def set_line(line_number) @line_number = line_number end
[ "def lineno=(line_number)\n ensure_open\n\n raise TypeError if line_number.nil?\n\n @lineno = Integer(line_number)\n end", "def lineno=(val)\n $. = @lineno = val\n end", "def lineno= integer\n #This is a stub, used for indexing\n end", "def update_line_numbers!\n each_with_index...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
gets the line number if the trace at the specified index
def get_line_number(index) if @list_of_events.length.zero? puts 'list is empty' else temp_event = @list_of_events[index] temp_event.line_number end end
[ "def line_number\n return unless backtrace and backtrace[0]\n\n backtrace[0].split(\":\")[1].to_i\n end", "def line_no\n backtrace[1][/:(\\d+):/][1...-1].to_i\n end", "def line_number\n @current_line\n end", "def from_line_index\n from_line - 1\n end", "def __caller_line_number__(ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds the event to the list of events
def add_event(event) @list_of_events << event end
[ "def add_event(event)\n @events.push event\n end", "def add_event event\n Helpers::Error.error(\n \"Passed `event' is not an instance of `Event'.\",\n \"Got `#{event.inspect}:#{event.class.name}'.\"\n ) unless (event.is_a? Event)\n @events << event\n end", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the events one by one
def print_events if @filtered_events.length.zero? puts 'List of events is empty' else (0..@filtered_events.length).each do |x| temp_event = @filtered_events[x] puts temp_event.trace end end end
[ "def print_events(events)\n events.each do |name, description|\n puts \"Event: #{name}\"\n puts \"Description: #{description} \\n\\n\"\n end\n end", "def print_events_captured \n @events_captured.each do |event|\n puts event\n end\n end", "def print_event\n clea...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract the execution trace for the student solution only. THis is done by finding the execution trace for the code that is surrounded by startTraceNow and endTraceNow function calls.
def exe_Point_Finder(trace) symbol_stack = [] other_list = [] top_symbol = '' exe = '' exe_point = ' ' on = false off = false trace.split('').each do |i| current_symbol = i exe_point += current_symbol if i == '{' or i == '[' or i == '(' symbol_stack << i e...
[ "def trace_step(&block)\n if @trace_execution_steps_counter > 0\n puts \"Trace: \" + yield.to_s\n end\n end", "def trace(begX, begY, endX, endY)\n solve(begX, begY, endX, endY)\n if @maze_trace.empty?\n return\n else\n @maze_trace.each do |i|\n print \"#{i} -> \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /podvals GET /podvals.xml
def index @podvals = Podval.find(:all) @podval = Podval.find_by_main(1) if @podval == nil @podvals = Podval.find_all_by_vis(1) @podval = @podvals.choice end respond_to do |format| format.html # index.html.erb format.xml { render :xml => @podvals } end end
[ "def new\n @podval = Podval.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @podval }\n end\n end", "def list\n http.get(\"/service-values\") do |response|\n respond_with_collection(response)\n end\n end", "def destroy\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /podvals/new GET /podvals/new.xml
def new @podval = Podval.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @podval } end end
[ "def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => new_vurl }\n end\n end", "def new\n @prop_value = PropValue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prop_value }\n end\n end", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
DELETE /podvals/1 DELETE /podvals/1.xml
def destroy @podval = Podval.find(params[:id]) @podval.destroy respond_to do |format| format.html { redirect_to(podvals_url) } format.xml { head :ok } end end
[ "def delete(path, params={}); make_request(:delete, host, port, path, params); end", "def delete(node, val)\nend", "def delete_aos_version(args = {}) \n delete(\"/aosversions.json/#{args[:aosVersionId]}\", args)\nend", "def delete_document(params)\n @client.delete(\"/evault\", params)\n end", "def d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /properties/new GET /properties/new.json
def new @property = Property.new respond_to do |format| format.html # new.html.erb format.json { render json: @property } end end
[ "def new\n @properties_path = PropertiesPath.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @properties_path }\n end\n end", "def new\n @property = current_customer.properties.new\n respond_to do |format|\n format.html # new.html.erb\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset all associated sheets total_response_count to nil to trigger refresh of sheet answer coverage
def reset_sheet_total_response_count sheets.where(missing: false).update_all(response_count: nil, total_response_count: nil, percent: nil) sheets.where(missing: true).update_all(response_count: 0, total_response_count: 0, percent: 100) SubjectEvent.where(id: sheets.select(:subject_event_id)).update_all( ...
[ "def clear_responses\n self.update_attribute(:response_count, 0)\n self.options.find(:all, :conditions => [\"response_count >= 1\"]).each do |option|\n option.update_attribute(:response_count, 0)\n end\n end", "def reset_responses!\n @responses.clear\n end", "def clear_all\n Response.w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
POST /api/favourites?key= curl X POST v u admin:admin
def create favourite=current_user.add_favourite(params[:key]) if favourite respond_to do |format| format.json { render :json => jsonp(favourites_to_json([favourite])) } format.xml { render :xml => favourites_to_xml([favourite]) } format.text { render :text => text_not_supported } ...
[ "def favorite(action, value)\n raise ArgumentError, \"Invalid favorite action provided: #{action}\" unless @@FAVORITES_URIS.keys.member?(action)\n value = value.to_i.to_s unless value.is_a?(String)\n uri = \"#{@@FAVORITES_URIS[action]}/#{value}.json\"\n case action\n when :add\n response = http_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Description Sets that the notification has been seen by the user (see Notificationhas_been_seen) Mode Ajax Specific filters NotificationsControllerinitialize_notification_with_owner
def seen if @ok @ok = @notification.has_been_seen end @new_notifications = current_user.number_notifications_not_seen end
[ "def notification_seen\n current_user.notice_seen\n end", "def saw_notification\n current_user.notice_seen = true\n current_user.save\n end", "def mark_notification_as_seen_and_read\n notifications.each{|n| n.update_attributes(:read => true, :seen => true)} if (status == Friendship::STATUS[:accept...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the notifications offset
def initialize_notification_offset @offset_notifications = (correct_integer?(params[:offset]) ? params[:offset].to_i : NOTIFICATIONS_LOADED_TOGETHER) end
[ "def default_note_off_offset\n 6 * mpt\n end", "def init_position\n @init_position\n end", "def send_offsets\n end", "def set_default_position\n if self.position.nil?\n self.position = newsletter.blocs.count + 1\n end\n end", "def set_default_offset(topic, default_offset)\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the last visited
def last_visited Deck.find(params[:id]).update_attribute(:last_visited, DateTime.now) end
[ "def last_visited!(t)\n update_attribute(:last_visited, t)\n end", "def update_times_visited\n if self.times_visited.nil? || self.times_visited < 1\n self.times_visited = 1\n else\n self.times_visited += 1\n end\n\n save\n end", "def visited\n self.visited_at = Time.now\n self.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the current user is the creator of the deck
def creator? unless current_user.id == Deck.find(params[:id]).user_id flash[:error] = "You do not have permission to modify this deck" redirect_to root_path end end
[ "def creator_user?(raffle)\n current_user == creator_user(raffle)\n end", "def users_card?\n @card.user == current_user\n end", "def created_by?(user)\n unless user.nil?\n userid = user.send(BigbluebuttonRails.configuration.user_attr_id)\n self.creator_id == userid\n else\n fals...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rails 5.2 moved from a unary Migrator class to MigrationContext, that can be scoped to a given path. Rails 6.0 requires the schema migration object as an argument.
def migration_context klass = ActiveRecord::MigrationContext case klass.instance_method(:initialize).arity when 1 klass.new(migration_path) else klass.new(migration_path, schema_migration) end end
[ "def schema_migration # :nodoc:\n ClickhouseActiverecord::SchemaMigration\n end", "def migrate(schema, to_version = nil)\n conn = ActiveRecord::Base.connection\n return false unless conn.schema_exists? schema\n current_search_path = conn.schema_search_path\n conn.schema_search_path...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a value array to multiple pwm ports (or a single port if the param is a hash)
def write(values) if values.is_a? Hash # TODO: hacky - refactor fail "wrong hash format, expected the keys 'port' and 'value'" unless values.key?(:port) && values.key?(:value) write_to_port(values[:port], values[:value]) elsif values.is_a? Array log.error('more values than configured...
[ "def write_to_port(port, value)\n value = value.to_i\n @values[port.to_i] = value\n # log.debug \"write bar #{port} value #{value}\"\n client.pwm_write(@ports[port.to_i], value)\n end", "def pwm_write_registers(options)\n start_at_register = options[:start_index]\n values = option...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write a value to a pwm port
def write_to_port(port, value) value = value.to_i @values[port.to_i] = value # log.debug "write bar #{port} value #{value}" client.pwm_write(@ports[port.to_i], value) end
[ "def pwm(value)\n GPIO.write \"gpio#{@number}/value\", value\n end", "def pwm(value)\n GPIO.write \"gpio#{@number}/value\", value\n end", "def pwm_write(number, value)\n pwm_write_registers(start_index: number, values: [value])\n end", "def pwm_write(value)\n @value = value\n\n # Cal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GET /days/new GET /days/new.xml
def new @trip = Trip.find(params[:trip_id]) @prev_day = @trip.days[-1] @day = Day.new respond_to do |format| format.html # new.html.erb format.xml { render :xml => @day } end end
[ "def new\n @day = current_account.days.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @day }\n end\n end", "def new\n @the_day = TheDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query the API server for the root device
def root_device begin @root_device = open('http://instance-data/latest/meta-data/block-device-mapping/root').read rescue message.fatal 'Could not get the root device!' end end
[ "def root_device\n @device.root_device\n end", "def root_device_name\n data[:root_device_name]\n end", "def root_device_name\n data.root_device_name\n end", "def root_device_name\n @instance.root_device_name\n end", "def root_device_type\n data[:root_device_type]...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Autodetect Devise scope using +Devise.default_scope+. Used to make the linkhelpers smart if like in most cases only one devise scope will be used, e.g. "user" or "account".
def auto_detect_scope(*args) options = args.extract_options! if options.key?(:for) options[:scope] = options[:for] ::ActiveSupport::Deprecation.warn("DEPRECATION: " << "Devise scope :for option is deprecated. " << "Use: facebook_*_link(:some_scope...
[ "def auto_detect_scope(*args)\n options = args.extract_options!\n\n if options.key?(:for)\n options[:scope] = options[:for]\n ::ActiveSupport::Deprecation.warn(\"DEPRECATION: \" <<\n \"Devise scope :for option is deprecated. \" <<\n \"Use: facebook_*...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate agnostic hidden sign in/out (connect) form for Facebook Connect.
def facebook_connect_form(scope, options = {}) sign_out_form = options.delete(:sign_out) options.reverse_merge!( :id => (sign_out_form ? 'fb_connect_sign_out_form' : 'fb_connect_sign_in_form'), :style => 'display:none;' ) scope = ::Devise::Mapping.fi...
[ "def facebook_sign_out_link(*args)\n scope = auto_detect_scope(*args)\n options = args.extract_options!\n options.except!(:scope, :for)\n options.reverse_merge!(\n :label => ::I18n.t(:sign_out, :scope => [:devise, :sessions, :facebook_actions]),\n :size => :large,\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test data: (;PB[Honinbo Shusaku]BR[6d]PW[Honinbo Shuwa]WR[8d])
def test_data_hash [{ 'PB' => 'Honinbo Shusaku', 'BR' => '6d', 'PW' => 'Honinbo Shuwa', 'WR' => '8d', 'GC' => 'game from Hikaru no Go chapter 2, this version only in the anime', 'RE' => 'W+4' }] end
[ "def test_example_b\r\n actual_test([\"PLACE 0,0,NORTH\",\r\n \"LEFT\",\r\n \"REPORT\"],\"0,0,WEST\")\r\n end", "def test_extract_orf()\n orf_hash_test = NpSearch::Translation.extract_orf(@expected_translation, 10)\n assert_equal(@expected_orf.to_s, orf_hash_test.to_s.gsu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append 'phrase' and 'translation'. If this 'phrase' already exists as key, then simply append 'translation' to the value array.
def append(phrase, translation) phrase.strip! translation.strip! if @value_hash[phrase].nil? @value_hash[phrase] = [translation] else @value_hash[phrase] << translation end end
[ "def add_necessary_words(search_array)\n @words_with.each do |k,v|\n if v.include?(search_array.last)\n puts \"Phrase requires \\\"#{k}\\\". Adding...\"\n \n case k\n when \"kakatteimasu\"\n @trans_array << \"にかかっています\"\n @say_it_array << \"ni kakatte imasu\"\n when \"hiki...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Imports the dict.cc file given in the constructor and builds/writes the database files.
def import read_dict_file(:langA) write_database(:langA) read_dict_file(:langB) write_database(:langB) end
[ "def initialize(file='corpus.db')\n @path = File.join(default_path, file)\n @filename = file\n FileUtils.mkdir_p(default_path) unless File.exists?(default_path)\n create_database\n end", "def initialize(database, file)\r\n end", "def build_database(filename)\n database = []\n lines = get_li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cause the CSVfile contains phrases we cannot be sure what is the most important word. This method strikes out everything between parenthesis, and if multiple words stay over, simply takes the longes one.
def extract_word( phrase ) w = phrase.gsub(/(\([^(]*\)|\{[^{]*\}|\[[^\[]*\])/, '').strip.downcase return nil if w.empty? # No empty strings # Now return the longest word, hoping that it's the most important, too ary = w.gsub(/[.,\-<>]/, ' ').strip.split do |i| i.strip! end ary.sort!{ |x,y| y.length ...
[ "def save_ambigious_words(file_name)\n File.open(file_name, 'w') do |f|\n sentences.each do |s|\n s.words.each do |w|\n tag_strings = w.get_correct_tags().collect { |t| t.clean_out_tag }\n f.puts w.string + \"\\t\" + tag_strings.sort.join(\"\\t\") if tag_strings.count > 1\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fulltext regexp lookup. Complexity: O(n)
def query_fulltext_regexp( query ) read_db do |dbm| dbm.each_value do |raw_val| val = RDictCcEntry.format_str(raw_val) match_line_found = false val.each_line do |line| if line =~ /^\s+/ if match_line_found puts line else # S...
[ "def regexp_matches(regexp); end", "def match(regexp); end", "def matched_text; end", "def word_pattern; end", "def deep_regexps; end", "def find_match(rules)\n regex, replacement = rules.find { |rule| !!(word =~ rule[0]) }\n\n return if regex.nil?\n\n word.sub(regex, replacement)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Public: Setup callback on headers parsing complete block Block the block of code Examples headers = HttpProxy::HeadersParser.new headers.process do |parsing_result| p parsing_result["UserAgent"] end Returns nothing
def process(&block) @parser.on_headers_complete = block end
[ "def on_headers_complete(&block)\n @settings[:on_headers_complete] = Callback.new(&block)\n end", "def parse_headers!(block)\n headers.each { |header| block.call(header.key, parse_value(header.value)) }\n end", "def on_headers_complete(&block)\n cb = Callback.new(&block)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Move the cursor to specified row. The main window and the headers will be updated reflecting the displayed files and directories. The row number can be out of range of the current page.
def move_cursor(row = nil) if row if (prev_item = items[current_row]) main.draw_item prev_item end page = row / max_items switch_page page if page != current_page main.activate_pane row / maxy @current_row = row else @current_row = 0 en...
[ "def goto_row(row)\n \n set RGhost::Cursor.goto_row(row) \n end", "def jump_rows(row)\n @rows+=row\n set RGhost::Cursor.jump_rows(row)\n end", "def move_to_row\n if @multibar\n CURSOR_LOCK.synchronize do\n if @first_render\n @row = @multibar.next_row\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort the whole files and directories in the current directory, then refresh the screen. ==== Parameters +direction+ Sort order in a String. nil : order by name r : reverse order by name s, S : order by file size sr, Sr: reverse order by file size t : order by mtime tr : reverse order by mtime c : order by ctime cr : re...
def sort(direction = nil) @direction, @current_page = direction, 0 sort_items_according_to_current_direction switch_page 0 move_cursor 0 end
[ "def sort_direction\n if ['asc', 'desc'].include?(params[:dir])\n params[:dir].to_sym\n else\n self.class.default_sort_dir\n end\n end", "def set_direction dir\n return 'ASC' unless dir\n dir == 'ASC' ? 'DESC' : 'ASC'\n end", "def sort_by key, reverse=false\n # remove...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the file permission of the selected files and directories. ==== Parameters +mode+ Unix chmod string (e.g. +w, gr, 755, 0644)
def chmod(mode = nil) return unless mode begin Integer mode mode = Integer mode.size == 3 ? "0#{mode}" : mode rescue ArgumentError end FileUtils.chmod mode, selected_items.map(&:path) ls end
[ "def chmod(mode, *files)\n verbose = if files[-1].is_a? String then false else files.pop end\n $stderr.printf \"chmod %04o %s\\n\", mode, files.join(\" \") if verbose\n o_chmod mode, *files\n end", "def chmod(mode)\n File.chmod(mode, @path)\n end", "def chmod(mode) File.chmod(mode, path) end", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the file owner of the selected files and directories. ==== Parameters +user_and_group+ user name and group name separated by : (e.g. alice, nobody:nobody, :admin)
def chown(user_and_group) return unless user_and_group user, group = user_and_group.split(':').map {|s| s == '' ? nil : s} FileUtils.chown user, group, selected_items.map(&:path) ls end
[ "def set_owner(path, owner, group)\n @fs.setOwner(_path(path), owner, group)\n end", "def change_owner(username, group, path)\n %x(sudo chown -R #{Shellwords.escape(username)}:#{Shellwords.escape(group)} #{path})\n\n $?.success?\n end", "def set_owner\n FileUtils.chown owner, group, destin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fetch files from current directory or current .zip file.
def fetch_items_from_filesystem_or_zip unless in_zip? @items = Dir.foreach(current_dir).map {|fn| load_item dir: current_dir, name: fn }.to_a.partition {|i| %w(. ..).include? i.name}.flatten else @items = [load_item(dir: current_dir, name: '.', stat: File.stat(current_dir))...
[ "def main_files\n retrieve_files_in_main_dir\n end", "def retrieve_files_in_main_dir\n ensure_file_open!\n @file.glob('*').map do |entry|\n next if entry.directory?\n\n entry_file_name = Pathname.new(entry.name)\n [entry_file_name, entry.get_input_stream(&:read)]\n end.compact.to_h\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Rename selected files and directories. ==== Parameters +pattern+ new filename, or a shash separated Regexp like string
def rename(pattern) from, to = pattern.sub(/^\//, '').sub(/\/$/, '').split '/' if to.nil? from, to = current_item.name, from else from = Regexp.new from end unless in_zip? selected_items.each do |item| name = item.name.gsub from, to FileUtils.mv ...
[ "def rename_command(new_match, search, options = T.unsafe(nil)); end", "def pattern=(pattern)\n @root, @wildcard = Wow::Package::FilePattern.split_pattern(pattern)\n end", "def file_sub(path, pattern, replacement = nil, &b)\n tmp_path = \"#{path}.tmp\"\n File.open(path) do |infile|\n File.open(tmp_path...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the timestamp of the selected files and directories. ==== Parameters +timestamp+ A string that can be parsed with `Time.parse`. Note that this parameter is not compatible with UNIX `touch t`.
def touch_t(timestamp) FileUtils.touch selected_items, mtime: Time.parse(timestamp) ls end
[ "def timestamp=(timestamp)\n @timestamp = _check_timestamp(timestamp)\n end", "def timestamp=(timestamp)\n @timestamp = _check_timestamp(timestamp)\n end", "def timestamp=(timestamp)\n @timestamp = _check_timestamp(timestamp)\n end", "def record_modification_timestamp(pat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Paste yanked files / directories here.
def paste if @yanked_items if current_item.directory? FileUtils.cp_r @yanked_items.map(&:path), current_item else @yanked_items.each do |item| if items.include? item i = 1 while i += 1 new_item = load_item dir: current_dir...
[ "def wheatpaste_directory(directory, pause_length, line_by_line)\n initial_directory = Dir.pwd\n Dir.chdir(directory)\n \n Dir[\"**/*\"].sort.each do |f|\n if File.file?(f)\n wheatpaste_file(f, pause_length, line_by_line)\n end\n end\n \n Dir.chdir(initial_directory)\n end", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copy selected files and directories' path into clipboard on OSX.
def clipboard IO.popen('pbcopy', 'w') {|f| f << selected_items.map(&:path).join(' ')} if osx? end
[ "def copy_command\n if darwin?\n 'pbcopy'\n elsif windows?\n 'clip'\n else\n 'xclip -selection clipboard'\n end\n end", "def copy\n case RUBY_PLATFORM\n when /linux/\n IO.popen('xclip -selection clipboard', 'r+') do |pipe|\n pipe.write(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Unarchive .zip and .tar.gz files within selected files and directories into current_directory.
def unarchive unless in_zip? zips, gzs = selected_items.partition(&:zip?).tap {|z, others| break [z, *others.partition(&:gz?)]} zips.each do |item| FileUtils.mkdir_p current_dir.join(item.basename) Zip::File.open(item) do |zip| zip.each do |entry| File...
[ "def unzip_files(target)\n Dir.glob(File.join(target, \"*.zip\")).each do |file|\n loginfo(\"Unzipping #{file}...\", 1)\n Zip::File.open(file) do |zipFile|\n zipFile.each do |zip|\n zipFile.extract(zip, File.join(target, zip.name))\n end\n end\n loginfo(\"Done.\\n\", 1)\n end\nend", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }