query
stringlengths 7
9.5k
| document
stringlengths 10
1.07M
| negatives
sequencelengths 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 }
format.json { render json: @air_moisture.errors, status: :unprocessable_entity }
end
end
end | [
"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 do |format|\n if @moon.update_attributes(params[:moon])\n format.html { redirect_to @moon, notice: 'Moon was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @moon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @airtime = Airtime.find(params[:id])\n\n respond_to do |format|\n if @airtime.update_attributes(params[:airtimes])\n format.html { redirect_to @airtime, notice: 'Airtime was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @airtime.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mile.update(mile_params)\n format.html { redirect_to @mile, notice: 'Mile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @ami = Ami.find(params[:id])\n\n respond_to do |format|\n if @ami.update_attributes(params[:ami])\n format.html { redirect_to @ami, notice: 'Ami was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ami.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @mosaic.update(mosaic_params)\n format.html { redirect_to @mosaic, notice: 'Mosaic was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mosaic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @plate = Plate.find(params[:id])\n\n if @plate.update(params[:plate])\n head :no_content\n else\n render json: @plate.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @aile.update(aile_params)\n format.html { redirect_to @aile, notice: 'Aile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @aile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n @minute_hand.manipulate_and_update(minute_hand_params)\n format.json { render :show, status: :ok, location: @minute_hand }\n end\n end",
"def update\n respond_to do |format|\n if @moon.update(moon_params)\n format.html { redirect_to @moon, notice: 'Moon was successfully updated.' }\n format.json { render :show, status: :ok, location: @moon }\n else\n format.html { render :edit }\n format.json { render json: @moon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @soil_moisture.update(soil_moisture_params)\n format.html { redirect_to @soil_moisture, notice: 'Soil moisture was successfully updated.' }\n format.json { render :show, status: :ok, location: @soil_moisture }\n else\n format.html { render :edit }\n format.json { render json: @soil_moisture.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @mi = Mi.find(params[:id])\n\n respond_to do |format|\n if @mi.update_attributes(params[:mi])\n format.html { redirect_to @mi, notice: 'Mi was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @mi.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @pelicula = Pelicula.find(params[:id])\n @pelicula.update(update_params)\n render json: @pelicula, status: :ok\n end",
"def update\n @precious_metal = PreciousMetal.find(params[:id])\n\n respond_to do |format|\n if @precious_metal.update_attributes(params[:precious_metal])\n format.html { redirect_to @precious_metal, :notice => 'Precious metal was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @precious_metal.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @species = Species.find(params[:id])\n\n if @species.update(species_params)\n head :no_content\n else\n render json: @species.errors, status: :unprocessable_entity\n end\n end",
"def update\n @mosaic = Mosaic.find(params[:id])\n\n respond_to do |format|\n if @mosaic.update_attributes(params[:mosaic])\n format.html { redirect_to @mosaic, notice: 'Mosaic was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @mosaic.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n authorize! :update, @water_fountain\n respond_to do |format|\n if @water_fountain.update(water_fountain_params)\n format.json { head :no_content }\n else\n format.json { render json: { error: @water_fountain.errors.full_messages }, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @machinery = Machinery.find(params[:id])\n\n respond_to do |format|\n if @machinery.update_attributes(params[:machinery])\n format.html { redirect_to @machinery, notice: 'Machinery was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @machinery.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"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 successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end",
"def destroy\n @agronomium = Agronomium.find(params[:id])\n @agronomium.destroy\n\n respond_to do |format|\n format.html { redirect_to agronomia_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ami = Ami.find(params[:id])\n @ami.destroy\n\n respond_to do |format|\n format.html { redirect_to amis_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @wi_mn_d_min_t_air.destroy\n respond_to do |format|\n format.html { redirect_to wi_mn_d_min_t_airs_url }\n format.json { head :no_content }\n end\n end",
"def delete_monster(monster_id)\n RESTful.delete(\"#{URL_MICROSERVICE_MONSTER}/monster/#{monster_id}\")\n end",
"def delete_mobile_carrier(args = {}) \n delete(\"/mobile.json/#{args[:carrierId]}\", args)\nend",
"def destroy\n @moonwalk.destroy\n respond_to do |format|\n format.html { redirect_to moonwalks_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mooch.destroy\n respond_to do |format|\n format.html { redirect_to mooches_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @demand.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n Idiom.where(id: @idiom[:id]).delete_all\n respond_to do |format|\n format.html { redirect_to '/media' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mile.destroy\n respond_to do |format|\n format.html { redirect_to miles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mi = Mi.find(params[:id])\n @mi.destroy\n\n respond_to do |format|\n format.html { redirect_to mis_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @wi_mn_d_ave_t_air.destroy\n respond_to do |format|\n format.html { redirect_to wi_mn_d_ave_t_airs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @hito.destroy\n respond_to do |format|\n format.html { redirect_to hitos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mob.destroy\n respond_to do |format|\n format.html { redirect_to mobs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @metal = Metal.find(params[:id])\n @metal.destroy\n\n respond_to do |format|\n format.html { redirect_to metals_url }\n format.json { head :no_content }\n end\n end"
] | {
"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_speed\n @line_show_fast = CP::CMS::TEXT_TYPE_OR_SKIP\n end",
"def plot_line; end",
"def calculate_line(stop1, stop2)\n if @purple_line.include?(stop1) && @purple_line.include?(stop2)\n \"either\"\n elsif @purple_line.include?(stop1) && @blue_line_west.include?(stop2)\n \"blue\"\n elsif @purple_line.include?(stop1) && @red_line_only.include?(stop2)\n \"red\"\n elsif @red_line_only.include?(stop1)\n \"red\"\n elsif @blue_line_west.include?(stop1)\n \"blue\"\n end\n end",
"def straight\n @line_type = '--'\n self\n end",
"def draw_vertical(start_line, end_line, start_char)\n start_line.upto(end_line) do |line_idx| \n @lines[line_idx][start_char] = PATH_CHAR \n end\n end",
"def draw_line(number)\n @dim.times do |i|\n if i+1 == number || @dim-i == number\n print draw_x\n else\n print draw_dot\n end\n end\n end",
"def timing_line(start, stop)\n\t\t@value = \"#{start.to_timing} --> #{stop.to_timing}\"\n\t\treturn self\n\tend",
"def interchange_and_stops(start_line,start,end_line,stop)\n interchange = find_interchange(start_line,end_line)[0]\n start_line = trim_lines(start_line, start, interchange, true) # check directions\n end_line = trim_lines(end_line, stop, interchange, false) # for both lines\n total_stops = start_line.length + end_line.length + 1\n return interchange, start_line, end_line, total_stops\nend",
"def available_stops(subway_line)\n\t$mta[subway_line.to_sym].join(\" | \")\nend",
"def get_stops (line, first_stop, last_stop)\n # puts \"line #{ line } stop #{ first_stop } -> stop #{ last_stop }\"\n first_index = lines[line.to_sym].index(first_stop)\n last_index = lines[line.to_sym].index(last_stop)\n if first_index <= last_index\n trip = lines[line.to_sym][first_index..last_index]\n else\n trip = lines[line.to_sym][last_index..first_index].reverse\n end\n trip.shift # remove first stop\n return trip\nend",
"def passed_stops(mta, start_index, end_index, line_name)\n line_stops = which_line(line_name)\n if (start_index < end_index)\n passed_stops_list = (Array(mta[line_stops.to_sym].invert.keys))[(start_index + 1)..end_index]\n else\n passed_stops_list = ((Array(mta[line_stops.to_sym].invert.keys))[end_index..(start_index - 1)]).reverse\n end\nend",
"def draw_lines\n @dim.times do |i|\n if @type.nil?\n draw_line(i+1)\n draw_edge\n puts\n elsif @type == \"allx\" || @type == \"alt\"\n draw_alt_line\n draw_edge\n puts\n end\n end\n end",
"def emitLines\n\t\tout=\"\"\n\t\tmax = @td.maxValue \n\t\t\n\t\tcoloridx = 0\n\t\tx=0\n\t\ty=0\n\t\tstyle = \"line0\"\n\t\tbarwidth = getXPoint(1) - getXPoint(0)\n\t\t\n\t\t\n\t\t@td.lines.each_pair{|name, line|\n\t\t\tstyle.succ!\n\t\t\tout += %Q(<path stroke-width=\"12\" style=\"#{@sty[style]}\" d=\")\n\t\t\t\n\t\t\tline.each_with_index{|count, i|\n\t\t\t\tx = getXPoint(i)\n\t\t\t\ty = getYPoint(count, max)\n\t\t\n\t\t\t\tif (i==0) then\n\t\t\t\t\tout += \"M\"\n\t\t\t\telse\n\t\t\t\t\tout += \"L\"\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tif (@linegraph) then\n\t\t\t\t\t#fudge for readability -- a single point in the middle\n\t\t\t\t\tout += \" #{x + barwidth/2} #{y} \"\n\t\t\t\telse\n\t\t\t\t\t#correct output -- left and right corners of bar top\n\t\t\t\t\tout += \" #{x} #{y} \"\n\t\t\t\t\tout += \" #{x + barwidth} #{y} \"\n\t\t\t\tend\t\t\n\t\t\t}\n\t\t\t\n\t\t\tout += \" #{rightEdge + 200} #{y} \" if @nicekey\n\t\t\t\n\t\t\tout += %Q(\" />\\n)\n\t\t\t\n\t\t\tout += %Q(<text x=\"#{rightEdge+30}\" y=\"#{y-30}\" style=\"#{@sty['keyLbl']}\">#{name}</text>) if @nicekey\n\t\t}\n\t\t\n\t\t\n\t\t\n\t\tout\n\tend",
"def lines\r\n prime_fact(@lines) << \" line\" << (\"s\" unless @lines == 1).to_s\r\n end",
"def show_lines\n puts TEXT_LINES_HEADLINE\n \n y = 0;\n while (y < @field.height)\n act_line = \"\"\n x = 0\n while (x < @field.width)\n active = @field.assignment[x][y]\n act_part = (active == nil) ? \" - \" : (active == true) ? \" X \" : \" O \";\n act_line += act_part\n x += 1;\n end\n puts act_line;\n y += 1\n end\n self.show_empty_row\n \n 1.upto(@field.width) { |x| print \" #{x} \" }\n \n self.show_empty_row\n end",
"def show_line_separator\n puts \"-----------------------------------------------------------------------\".white.on_red.bold\nend",
"def curved\n @line_type = '..'\n self\n end"
] | {
"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? then
trip[:route_id].eql? route_id
else
true
end
}
trips_with_route.map {|trip| trip[:trip_id]}
end | [
"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 end",
"def get_all_route_stops(id)\n get_call(\"stops?filter[route]=#{id}\")\n end",
"def matches(trip)\n if trip.to_work\n origin_dist = 8000\n destination_dist = 1000\n else\n origin_dist = 1000\n destination_dist = 8000\n end\n @matches = Trip.joins(:users).\n where(pools: { is_active: true}).\n where.not(users: { id: id}).\n where(\"users.driving_pref = 0 OR driving_pref != ?\", driving_pref).\n where(trips: {to_work: trip.to_work}).\n where(\"ST_NumGeometries(trips.waypoints) = 2\").\n where(\"ST_DWithin( ST_geometryN(trips.waypoints, 1)::geography , ?::geography, ? )\", trip.waypoints[0], origin_dist).\n where(\"ST_DWithin( ST_geometryN(trips.waypoints, 2)::geography , ?::geography, ? )\", trip.waypoints[1], destination_dist).\n limit(20)\n\n # This gets up to 20 trips where (in order):\n # - the match user is actively taking this trip\n # - the match user isn't the current user\n # - the match user is neutral driving_pref or opposite of current user\n # - the match trip has same \"to_work\" value as current trip\n # - the match trip is currently an individual trip (technically not checking this, just checking that trip only has 2 waypoints)\n # - the match trip's origin is within [origin_dist] of the current trip's origin (note the difference in indexing!)\n # - the match trip's destination is [destination_dist] 1km of the current trip's destination\n \n # ATM TIMES NEVER CONSIDERED ANYWHERE\n # SHOULD FILTER IN DB BASED ON TIME/LOCATIONS (POSSIBLY ORDER AND LIMIT), THEN ALSO COMPUTE COMPAT AND ORDER RESULTS SOMEHOW\n # SHOULD HAVE SOME WAY OF RELAXING IF NOT ENOUGH RESULTS / BEING MORE PICKY IF TOO MANY.\n # ALSO SHOULD PRIORITIZE EXISTING MATCHES SOMEWHERE SOMEHOW\n \n @matches = @matches.sort_by{|t| -compatibility(t.users.first)} #right now sorting by compatability with first user\n return @matches\n end",
"def get_updates(v, trips)\n vehicle_id = v.vehicle.vehicle.id\n route_id = v.vehicle.trip.route_id\n trip_id = v.vehicle.trip.trip_id\n\n trips[route_id].each { |t|\n if !t.trip_update.nil? && t.trip_update.vehicle && t.trip_update.vehicle.id == vehicle_id\n trip_count = 0\n\n t.trip_update.stop_time_update.each{|u|\n stop_id = u.stop_id\n puts \" Stop: #{schedule.get_stop_info_by_name(stop_id, \"\")[1]}\"\n puts \" Arrival: #{Time.at(u.arrival.time).strftime(\"%l:%M%p %m-%e-%y \")}\"\n trip_count += 1\n\n if trip_count >= 2\n break\n end\n }\n end\n }\n end",
"def filter_services(filter)\n # product a list of filtered ServiceEndpoint objects. filtered\n # will contain a list of nil or ServiceEnpoint (subclasses) objects.\n filtered = self.services.collect {|s| filter.call(s)}\n \n # return all object in filtered that are not nil\n return filtered.find_all {|s| s}\n end",
"def trips_by_trip_id(trip_id)\n get \"/gtfs/trips/tripId/#{trip_id}\"\n end",
"def trips\n arr = []\n Trips.all.each do |trip|\n if trip.listing == self\n arr << trip\n end\n end\n arr\n end",
"def find_by_route\n @result = Array.new\n @distancias = Array.new\n\n @ride = Ride.order('id')\n if params[:radio] != '0'\n @ride.each do |p|\n distancia1 =Geocoder::Calculations.distance_between([params[:destLatitud],params[:destLongitud]], [p.destPointLat,p.destPointLong])\n distancia2 =Geocoder::Calculations.distance_between([params[:startLatitud],params[:startLongitud]], [p.startPointLat,p.startPointLong])\n if distancia1 <params[:radio].to_f && distancia2 <params[:radio].to_f\n @result.push(p)\n #@distancias.push(distancia1)\n end\n end\n # json_response={\n # result: @result,\n # distancias: @distancias\n # } \n respond_with @result , location: nil\n end\n if params[:radio] == '0'\n respond_with @ride,location: nil\n end \n #Ride.find_by_destPointLat_and_destPointLong(params[:latitud],params[:longitud])\n \n end",
"def route_services\n generated_route = []\n route_list.each do |item|\n if(item.is_a?(Service) || item.is_a?(CustomService))\n generated_route.push(item)\n elsif(item.is_a?(ServiceGroup))\n item.services.each do |srv|\n generated_route.push(srv)\n end\n end\n end\n generated_route\n end",
"def trips_within(meters)\n f = distance(:from)\n t = distance(:to)\n trips_with_distance.where{(f + t <= meters)}.exclude(:id => self.id).all\n end",
"def filter_by_route\n array = []\n data.entry.arrivalsAndDepartures.each do |bus|\n time = OneBusAway::Utilities.convert_time bus.scheduledDepartureTime\n array << { bus.routeShortName => time }\n end\n array\n end",
"def trips\n Trip.find_for_driver(@driver_id)\n end",
"def search_passengers(search, academic_year_id)\n return [] unless search[:route_id].present?\n conditions = {:receiver_type => search[:passenger]}\n route_type = \"#{search[:route_type]}_route_id\".to_sym\n conditions[route_type] = search[:route_id]\n include = (search[:passenger] == \"Student\" ? {:receiver => {:batch => :course}} : {:receiver => :employee_department})\n stop_method = \"#{search[:route_type]}_stop\".to_sym\n Transport.in_academic_year(academic_year_id).all(:conditions => conditions, :include => [stop_method, include])\n end",
"def gettrips\n @employee = Employee.find(params[:employee_id])\n #@lovedone = Lovedone.find(params[:lovedone_id]) \n #filter only trips with state as active or \n #@trips = Trip.where(employee_id: @employee, lovedone_id: @lovedone)\n @trips = Trip.where(employee_id: @employee, state: \"active\")\n respond_to do |format|\n if @trips\n #format.json { render json: @trips}\n format.json { render :json => @trips.to_json(:include => [:lovedone, :employee])}\n else\n #format.html\n format.json { render json: @trips.errors, status: :unprocessable_entity }\n end \n end \n end",
"def stops_for_route(route_id)\n stop_ids = @db[:stop_times].\n select(:stop_id).\n where(:trip_id => trips_for_route_today(route_id))\n\n stops = @db[:stops].\n select(:stop_id, :stop_name).\n where(:stop_id => stop_ids).\n order(:stop_name).\n all\n\n stops.map { |stop| { :route_id => route_id}.merge(stop) }\n end",
"def services\n Service.where(agency: agencies)\n end",
"def match_rides(ride, first_result_at, last_result_at, search_by)\n # this is a little hack, will definitely require some tweaking\n if search_by == 'arrival'\n # user requested rides based on end/arrival time of ride\n results = Ride.find(:all, :conditions => {:end_time => first_result_at..last_result_at})\n else\n # user requested rides based on start time of ride or DEFAULT\n results = Ride.find(:all, :conditions => {:start_time => first_result_at..last_result_at})\n end\n #logger.debug \"################### \" + results.count.to_s\n results.delete_if { |r| get_surface_distance(r.start_lat, r.start_long, \n ride.start_lat, ride.start_long) > 1.0 || \n get_surface_distance(r.end_lat, r.end_long,\n ride.end_lat, ride.end_long) > 1.0 ||\n get_available_seats_count(r) == 0 ||\n ride_in_past?(r) }\n #logger.debug \"################### \" + results.count.to_s\n return results\n end",
"def get_arrival_times_by_uid\n\troutes_with_arrivals = []\n\t@routes.each do |route|\n\t\t# Get all uids for the stations listed in the route\n\t\tall_objects = check_stations_on_route route[:stations]\n\n\t\t# Get the train object for just the uid we want\n\t\tall_objects.each do |train|\n\t\t\tif (train[:uid] == route[:uid])\n\t\t\t\troutes_with_arrivals.push(train)\n\t\t\tend\n\t\tend\n\tend\n\treturn routes_with_arrivals\nend"
] | {
"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|
next unless block
block.gsub!(/\n/, '')
# Ignore blocks that have no text
next if has_only_tags?(block)
# Each new block iterated over makes it less likely for it to belong
# to the existing block
continuous /= opt[:continuous_factor] if body.length > 0
# Clean up and strip block of html tags for scoring
clean = clean_block(block)
#clean = strip_tags(block)
next if clean.length < opt[:min_length]
# Calculate scores for clustering of blocks
# c represents how probable it is for this block to be a content block
c = (clean.length + clean.scan(opt[:punctuations]).length * opt[:punctuation_weight]) * factor
# The further down the document we go (i.e. the more blocks we see),
# the less likely they are to be valid content blocks
factor *= opt[:decay_factor]
# The not body rate represents how likely this is to be a junk block
not_body_rate = block.scan(opt[:waste_expressions]).length
# The block score is reduced if there is a not_body_rate
c *= (opt[:no_body_factor] ** not_body_rate) if not_body_rate>0
# c1 represents how probable it is for this block to belong to the
# existing block or if it is a new one
c1 = c * continuous
puts "----- #{c}*#{continuous}=#{c1} #{clean.length} \n\n" if opt[:debug]
if c1 > opt[:threshold]
# Treat continuous blocks as cluster
body += block + "\n"
score += c1
continuous = opt[:continuous_factor]
elsif c > opt[:threshold]
# Continuous block end
@sections << { :body => body, :score => score }
body = block + "\n"
score = c
continuous = opt[:continuous_factor]
else
# We drop blocks that don't have a high enough c score
end
end
# Add the last block as we've finished iterating
@sections << { :body => body, :score => score } if body
# Sort the sections by score
sorted_sections = @sections.sort_by { |section| section[:score] }
# Convert to nokogiri representation for compatibility with the content method
@content_candidates = sorted_sections.reverse.map { |section| Nokogiri::HTML(section[:body], nil, 'utf-8') }
end | [
"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 contents[\"#{i}\"] += 0.3*content[i].xpath(\".//span\").size if content[i].xpath(\".//span\").size != 0\n contents[\"#{i}\"] += 2*content[i].xpath(\".//p\").size if content[i].xpath(\".//p\").size != 0\n contents[\"#{i}\"] += 0.5*content[i].xpath(\".//img\").size if content[i].xpath(\".//img\").size != 0\n contents[\"#{i}\"] += 1*content[i].xpath(\".//h3\").size if content[i].xpath(\".//h3\").size != 0\n contents[\"#{i}\"] += 0.6*content[i].xpath(\".//br\").size if content[i].xpath(\".//br\").size != 0\n contents[\"#{i}\"] += 0.4*content[i].xpath(\".//strong\").size if content[i].xpath(\".//strong\").size != 0\n contents[\"#{i}\"] += 0.4*content[i].xpath(\".//em\").size if content[i].xpath(\".//em\").size != 0\n contents[\"#{i}\"] += 0.5*content[i].xpath(\".//h2\").size if content[i].xpath(\".//h2\").size != 0\n contents[\"#{i}\"] += 0.4*content[i].xpath(\".//b\").size if content[i].xpath(\".//b\").size != 0\n contents[\"#{i}\"] += 0.2*content[i].xpath(\".//h1\").size if content[i].xpath(\".//h1\").size != 0\n contents[\"#{i}\"] += 2*content[i].xpath(\".//article\").size if content[i].xpath(\".//article\").size != 0\n\n #checking if div does not contain navigation links\n for j in 0...@@nav_links.size do\n contents[\"#{i}\"] += -2 if content[i].to_s.include? @@nav_links[j].to_s\n end\n\n end\n\n right_content = contents.max_by{|k,v| v}[0]\n\n cnt = content[right_content.to_i]\n clear(cnt)\n end",
"def fetch_content\n # Get text from given wiki URL\n @text = Nokogiri::HTML(open(@url)).css('#bodyContent p').text\n\n # Analyze readability of the wiki text\n @readability = Odyssey.analyze_multi(@text, ['FleschKincaidRe', 'FleschKincaidGl', 'Ari', 'ColemanLiau', 'GunningFog', 'Smog'], true)\n\n # Set the @loaded status to true\n @loaded = true\n end",
"def doc_block_analysis\n total = documents.size.to_f\n\n self.blocks = documents.each_with_index.map do |d, i|\n progress&.call((i.to_f / total * 40.0).to_i + 40)\n\n d.term_vectors.each_with_object({}) do |(k, v), ret|\n next unless word_list.include?(k)\n ret[k] = v[:tf]\n end\n end\n\n progress&.call(80)\n\n # Clean out zero values from the blocks\n blocks.map! do |b|\n b.reject { |_, v| v.to_i.zero? }\n end\n\n progress&.call(90)\n\n self.block_stats = documents.each_with_index.map do |d, i|\n progress&.call((i.to_f / total.to_f * 10).to_i + 90)\n\n {\n name: I18n.t('lib.frequency.block_count_doc',\n num: 1, total: 1, title: d.uid),\n types: d.term_vectors.size,\n tokens: d.term_vectors.map { |_, v| v[:tf] }.reduce(:+)\n }\n end\n end",
"def contentScore\n return @@analyzer.score(@reviewContent)\n end",
"def content(clean = false, index = 0)\n return @content[[clean, index]] if @content[[clean, index]]\n return '' if !@content_candidates || @content_candidates.empty?\n \n content_branch = content_at(index)\n orphans_to_remove = []\n \n #ap content_branch.to_html\n #exit\n \n # Go through every piece of the content and rip out sections that contain too many tags compared to words\n # This is usually indicative of \"widgets\" or link bar sections\n content_branch.css('*').each_with_index do |el, i|\n next unless el\n\n if el.name == \"h1\"\n el.remove\n next\n end\n\n if el.name == \"h2\" && content_branch.inner_html.scan('<h2').size == 1\n el.remove\n end\n\n # Remove elements that contain words but there are more tags than words overall\n # First, count the words\n #word_count = 0\n #el.traverse do |subel|\n # if subel.text? && subel.path !~ /\\/a\\// && subel.path !~ /\\/(h1|h2|h3|h4|h5|h6)\\//\n # word_count += (subel.text.downcase.scan(/[a-z]{4,}/) - META_WORDS).size\n # end\n #end\n #\n ## .. then count the tags\n #\n #inner_tags = el.inner_html.scan(/\\<\\w.*?\\>/).size\n #if word_count < inner_tags && inner_tags > 3 && word_count < 250\n # puts \"At #{el.name} #{el['id']} #{el['class']} containing '#{el.text[0..20]}' we have #{word_count} valid words to #{el.inner_html.scan(/\\<\\w.*?\\>/).size} tags\"\n # #puts \"Removing #{el.name} #{el['id']} #{el['class']} TOO MANY TAGS FOR WORDS\"\n # el.remove\n # next\n #end\n\n # If there are at least 2 words and a third of them are \"meta words,\" remove the element\n #inner_words = el.text.to_s.downcase.scan(/[a-z]{3,}/)\n #if BLOCK_OUTPUT_ELEMENTS.include?(el.name) && inner_words.size >= 2\n # if ((inner_words & META_WORDS).size >= (inner_words.size / 3))\n # el.remove\n # end\n #end\n\n if el.text && el.text.strip.length < 3 && !%w{img}.include?(el.name) && el.inner_html !~ /\\<img/\n el.remove\n next\n end\n\n if el.name == \"p\" && el.text !~ /(\\.|\\?|\\!|\\\"|\\')(\\s|$)/ && el.inner_html !~ /\\<img/\n el.remove\n next\n end\n\n # If the ID or class of the element contains a fatally bad word, get rid of it\n if (BAD_WORDS & (el['id'].to_s + ' ' + el['class'].to_s).downcase.scan(/[a-z]+/)).length > 0\n #puts \"Removing #{el.name} #{el['id']} #{el['class']} BAD\"\n el.remove\n next\n end\n end\n\n # If a title was found early in the result document but had text before it, remove that text - it's probably crap\n orphans_to_remove.each { |el| el.remove }\n \n # Clean up the HTML again - Nokogiri outputs it with full doctype and crap\n clean_html = strip(Sanitize.clean(content_branch.to_html, :elements => (clean ? BLOCK_OUTPUT_ELEMENTS : OUTPUT_ELEMENTS), :attributes => (clean ? OK_CLEAN_ATTRIBUTES : OK_ATTRIBUTES)))\n \n # If the content is desired as \"clean\" (i.e. plain-text), do some quick fix-ups\n if clean\n # Get rid of line break tags, make list items look nice, remove all other HTML tags, and clean up spaces and newlines\n clean_html.gsub!(/<br.*?>/, \"\\n\")\n clean_html.gsub!(/<li>/, '* ')\n clean_html.gsub!(/<\\w+>/, '')\n clean_html.gsub!(/<\\/\\w+>/, \"\\n\")\n clean_html.gsub!(/\\ +/, ' ')\n clean_html.gsub!(/^\\s+\\n/, \"\\n\")\n clean_html.gsub!(/\\n{2,}/, \"\\n\")\n clean_html.strip!\n end\n \n # If tags butt up against each other across lines, remove the line break(s)\n clean_html.gsub!(/\\>\\n+\\</, '><')\n\n # Get rid of images whose sources are relative (TODO: Make this optional)\n clean_html.gsub!(/\\<img .*?\\>/i) do |img_tag|\n img_tag =~ /\\Whttp/ ? img_tag : ''\n end\n\n # Remove empty tags\n clean_html.gsub!(/<(\\w+)><\\/\\1>/, \"\")\n\n # Just a messy, hacky way to make output look nicer with subsequent paragraphs..\n clean_html.gsub!(/<\\/(div|p|h1|h2|h3|h4|h5|h6)>/, '</\\1>' + \"\\n\\n\")\n \n @content[[clean, index]] = clean_html\n end",
"def process_html(content)\n\t\t\t\tcontent.output = if content.output.include? ASIDE_START_TAG\n\t\t\t\t\thead, opener, tail = content.output.partition(CLOSING_ASIDE_TAG_REGEX)\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\thead, opener, tail = content.output.partition(POST_CONTENT_CLASS)\n\t\t\t\t\t\t\t\tend\n\t\t\t\tbody_content, *rest = tail.partition(\"</body>\")\n\t\t\t\t\n\t\t\t\tprocessed_markup = process_words(body_content)\n\t\t\t\t\n\t\t\t\tcontent.output = String.new(head) << opener << processed_markup << rest.join\n\t\t\tend",
"def parse_block_html; end",
"def parse_block_html\n line = @src.current_line_number\n if (result = @src.scan(HTML_COMMENT_RE))\n @tree.children << Element.new(:xml_comment, result, nil, category: :block, location: line)\n @src.scan(TRAILING_WHITESPACE)\n true\n else\n if @src.check(/^#{OPT_SPACE}#{HTML_TAG_RE}/o) && !HTML_SPAN_ELEMENTS.include?(@src[1].downcase)\n @src.pos += @src.matched_size\n handle_html_start_tag(line, &method(:handle_kramdown_html_tag))\n Kramdown::Parser::Html::ElementConverter.convert(@root, @tree.children.last) if @options[:html_to_native]\n true\n elsif @src.check(/^#{OPT_SPACE}#{HTML_TAG_CLOSE_RE}/o) && !HTML_SPAN_ELEMENTS.include?(@src[1].downcase)\n name = @src[1].downcase\n\n if @tree.type == :html_element && @tree.value == name\n @src.pos += @src.matched_size\n throw :stop_block_parsing, :found\n else\n false\n end\n else\n false\n end\n end\n end",
"def parse_codeblocks(html); end",
"def match(source, code)\n @html_errors = Array.new\n html_errors = @html_errors\n\n code = Nokogiri::HTML(code)\n\n elements = get_elements(source)\n\n css_code_checked = Array.new\n\n exist_in_body = Array.new\n\n error_elements = Array.new\n\n\n error333 = nil\n\n elements.each do |e|\n error_count = 0\n\n item = e[:tag]\n\n if item == \"text\" or item == \"comment\"\n # Check the text\n if e[:content]\n if code.css(e[:parent]).count < 2\n if code.css(e[:parent]).class == Nokogiri::XML::NodeSet\n #look for children elements with texts or comments\n look_comment_or_text(code,e)\n end\n else\n #check if parent tag of the user code has text apart from the children tags\n look_parent_text(code,e)\n end\n end\n #end if content is null\n\n else\n #item class is different to text or comment\n\n if code.css(e[:tag]).length > 0\n\n # error_elements = Array.new\n\n code.css(e[:tag]).each do |tag|\n\n p \"code original css + \" + e[:tag].to_s\n p \"pointer original element \" + e[:pointer].to_s\n p \"pointer element code \" + tag.pointer_id.to_s\n\n e_check = css_code_checked.select {|element| element[:target_pointer].to_s == e[:pointer].to_s }\n p \"echeck \" + e_check.to_s\n e_check2 = css_code_checked.select {|element| element[:pointer].to_s == tag.pointer_id.to_s }\n #e_check3 = css_code_checked.select {|element| element[:target_parent_pointer].to_s == e[:parent_pointer].to_s }\n\n # e_check_exist = css_code_checked.select {|element| element[:pointer].to_s == tag.pointer_id.to_s && element[:target_pointer].to_s == e[:pointer]}\n # e_check_2_exist = css_code_checked.select {|element| element[:pointer].to_s == tag.pointer_id.to_s && element[:target_pointer].to_s != e[:pointer]}\n # e_check_3_exist = css_code_checked.select {|element| element[:pointer].to_s == tag.pointer_id.to_s && element[:target_pointer].to_s != e[:pointer]}\n\n # p \"check1 \" + e_check_exist.to_s\n # p \"check2 \" + e_check_2_exist.to_s\n #si el target pointer- pointer no esta en la lista de check agregar,\n #si es target-pointer que ya existe + otro pointer da error,\n #si es target-pointer y si esta, hacer nada.\n #si pointer ya esta en la lista hacer nada\n #look for same tags in code\n # p elements.select {|x| x[:tag].to_s == e[:tag].to_s }\n if css_code_checked.select {|element| element[:target_pointer].to_s == e[:pointer].to_s }.count == 0\n if elements.select {|x| x[:tag].to_s == e[:tag].to_s }.count > 1\n if e_check.count == 0 && e_check2.count == 0\n element_checked = Hash.new\n element_checked[:pointer] = tag.pointer_id\n element_checked[:tag] = e[:tag]\n element_checked[:target_pointer] = e[:pointer]\n element_checked[:target_parent_pointer] = e[:parent_pointer]\n css_code_checked << element_checked\n p \"code_checked \" + css_code_checked\n elsif (e_check.count == 1) || (e_check2.count == 1 && e_check.count == 0)\n error_count += 1\n\n # html_errors << new_error(element: e, type: 440, description: \"Remember to add the `<#{e[:tag]}>` tag inside `<#{e[:parent]}>`\")\n # p \"css code list \" + css_code_checked.to_s\n # if css_code_checked.select {|element| element[:pointer].to_s == tag.pointer_id.to_s }\n #\n # end\n # elsif e_check_exist.count == 1\n # html_errors << new_error(element: e, type: 440, description: \"Remember to add the `<#{e[:tag]}>` tag inside `<#{e[:parent]}>`\")\n end\n end\n # e_check_exist = nil\n end\n # if tag\n # if tag.respond_to? :parent\n # p \"check if exists in parent tags\"\n # p e_check4 = css_code_checked.select {|element| element[:pointer].to_s == e[:pointer].to_s }\n # p e_check5 = css_code_checked.select {|element| element[:target_parent_pointer].to_s == e[:parent_pointer].to_s }\n # if (tag.count < 2 && tag.first) or (e_check4.count < 1 && e_check5.count < 1)\n # if tag.parent.name != e[:parent]\n # html_errors << new_error(element: e, type: 440, description: \"Remember to add the `<#{e[:tag]}>` tag inside `<#{e[:parent]}>`\")\n # end\n # else\n # exist_in_parent = false\n # tag.each do |code_css|\n # exist_in_parent = true if code_css.parent.name == e[:parent]\n # end\n # html_errors << new_error(element: e, type: 440, description: \"Remember to add the `<#{e[:tag]}>` tag inside `<#{e[:parent]}>`\") if !exist_in_parent\n # end\n # end\n # end\n\n\n if e_check.count < 1 and e_check2.count < 1\n\n element_checked = Hash.new\n element_checked[:pointer] = tag.pointer_id\n element_checked[:tag] = e[:tag]\n element_checked[:target_pointer] = e[:pointer]\n element_checked[:target_parent_pointer] = e[:parent_pointer]\n\n\n if e[:attribute]\n # Check the tag's attributes\n if tag.attribute(e[:attribute]).nil?\n html_errors << new_error(element: e, type: 334, description: \"`<#{e[:tag]}>` should have an attribute named #{e[:attribute]}\")\n else\n if tag.attribute(e[:attribute]).value != e[:value]\n exist_in_body << false\n # p \"type \" + e[:tag] + \" with attribute \" + e[:attribute] + \" value \" + e[:value]\n # Check if the img have attribute src and value is null, the user can write whatever image he wants\n if !(e[:tag] == \"img\" && e[:attribute] == \"src\" && e[:value] == \"\")\n error333 = new_error(element: e, type: 333, description: \"Make sure that the attribute #{e[:attribute]} in `<#{e[:tag]}>` has the value #{e[:value]}\")\n end\n else\n p \"add code_checked\"\n css_code_checked << element_checked\n exist_in_body << true\n end\n\n end\n\n end #if element checked\n\n end\n\n\n # p \"respond\" + tag.parent.to_s\n # Check that tags exist within parent tags\n if tag.first.respond_to? :parent\n\n p \"check if exists in parent tags\"\n\n e_check4 = css_code_checked.select {|element| element[:pointer].to_s == e[:pointer].to_s }\n e_check5 = css_code_checked.select {|element| element[:target_parent_pointer].to_s == e[:parent_pointer].to_s }\n\n if (tag.count < 2 && tag.first) or (e_check4.count < 1 && e_check5.count < 1)\n if tag.first.parent.name != e[:parent]\n html_errors << new_error(element: e, type: 440, description: \"Remember to add the `<#{e[:tag]}>` tag inside `<#{e[:parent]}>`\")\n end\n else\n exist_in_parent = false\n tag.each do |code_css|\n exist_in_parent = true if code_css.parent.name == e[:parent]\n end\n html_errors << new_error(element: e, type: 440, description: \"Remember to add the `<#{e[:tag]}>` tag inside `<#{e[:parent]}>`\") if !exist_in_parent\n end\n end\n\n\n end\n\n\n else\n \"pasa else\"\n # Check that the tag is present\n # p \"check if exists in parent\"\n e_check4 = css_code_checked.select {|element| element[:pointer].to_s == e[:pointer].to_s }\n e_check5 = css_code_checked.select {|element| element[:target_parent_pointer].to_s == e[:parent_pointer].to_s }\n if code.at_css(e[:tag]).nil? or e_check4.count < 1 and e_check5.count < 1\n html_errors << new_error(element: e, type: 404, description: \"Remember to add the `<#{e[:tag]}>` tag\")\n end\n end\n\n if exist_in_body && !exist_in_body.include?(true) && error333\n html_errors << error333\n end\n exist_in_body = []\n\n end\n # p \"code checked\" + css_code_checked.to_s\n # p \"errors = \" + error_elements.to_s\n # # errors_x = error_elements.group_by{|k,v| v}\n # error_elements.each do |error|\n # p error.to_s\n # e_check_errors = css_code_checked.select {|element| element[:pointer].to_s == error[:pointer].to_s}\n # # p e_check_errors = css_code_checked.select {|element| element[:pointer].to_s == error[:pointer].to_s && element[:target_pointer].to_s == error[:e][:pointer].to_s}\n #\n # # e_check2_errors = css_code_checked.select {|element| element[:target_pointer].to_s == error[:e][:pointer].to_s }\n # if e_check_errors.count < 1\n # html_errors << new_error(element: error[:e], type: 404, description: \"Remember to add the `<#{error[:e][:tag]}>` tag\")\n # end\n # end\n\n p \"count \" + error_count.to_s\n end\n html_errors\n\n end",
"def structurize!\n # Assuming doc is a Nokogiri::HTML::Document\n if body = doc.css('book').first then\n stack = []\n \n body.children.each do |node|\n # non-matching nodes will get level of 0\n level = node.name[ /h([1-6])/i, 1 ].to_i\n level = 99 if level == 0\n \n stack.pop while (top=stack.last) && top[:level]>=level\n stack.last[:div].add_child( node ) if stack.last\n if level<99\n if node.name == \"h1\"\n div = Nokogiri::XML::Node.new(\"chapter\",doc)\n else\n div = Nokogiri::XML::Node.new(\"sect#{level -1}\",doc)\n end\n if node.attr(\"i\")\n div.set_attribute(\"xml:id\", node.attr(\"id\").to_s) \n node.remove_attribute(\"id\")\n end\n node.add_next_sibling(div)\n node.name=\"title\"\n div.add_child(node)\n node.delete(node)\n stack << { :div=>div, :level=>level }\n end\n end\n \n\n end\n end",
"def process_words(html)\n\t\t\t\tpage_content = html\n# \t\t\t\tpage_content = Nokogiri::HTML::DocumentFragment.parse(html)\n# \t\t\t\tpage_content = page_content.css(\"page__content\")\n\t\t\t\t@posts.docs.each do |post|\n\t\t\t\t\tpost_title = post.data['title'] || post.name\n\t\t\t\t\tpost_title_lowercase = post_title.downcase\n# \t\t\t\t\tif post_title != @title\n\t\t\t\t\t\tif page_content.include?(\" \" + post_title_lowercase + \" \") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title_lowercase + \" \") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title_lowercase + \",\") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title_lowercase + \".\")\n# \t\t\t\t\t\t\tif post_title_lowercase == \"groller\"\n# \t\t\t\t\t\t\tputs \"YES, \" + post_title_lowercase + \" will be replaced\"\n# \t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tpage_content = page_content.sub(post_title_lowercase, \"<a href=\\\"#{post.url}\\\">#{post_title.downcase}</a>\")\n\t\t\t\t\t\telsif page_content.include?(\" \" + post_title + \" \") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title + \" \") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title + \",\") ||\n\t\t\t\t\t\t\tpage_content.include?(post_title + \".\")\n# \t\t\t\t\t\t\tif post_title == \"Groller\"\n# \t\t\t\t\t\t\tputs \"YES, \" + post_title + \" will be replaced\"\n# \t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tpage_content = page_content.sub(post_title, \"<a href=\\\"#{post.url}\\\">#{post_title}</a>\")\n\t\t\t\t\t\tend\n# \t\t\t\t\tend\n\t\t\t\tend\n# \t\t\t\tpage_content.to_html\n\t\t\t\tpage_content\n\t\t\tend",
"def div\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 18 )\n __DIV12__ = nil\n __DIV13__ = nil\n\n begin\n # at line 110:4: ( ^( TAG DIV attrs ( body_content )+ ) | ^( TAG DIV attrs ) )\n alt_21 = 2\n alt_21 = @dfa21.predict( @input )\n case alt_21\n when 1\n # at line 110:6: ^( TAG DIV attrs ( body_content )+ )\n match( TAG, TOKENS_FOLLOWING_TAG_IN_div_707 )\n\n match( DOWN, nil )\n __DIV12__ = match( DIV, TOKENS_FOLLOWING_DIV_IN_div_709 )\n # --> action\n printStartTag(__DIV12__);\n # <-- action\n @state.following.push( TOKENS_FOLLOWING_attrs_IN_div_713 )\n attrs\n @state.following.pop\n # --> action\n putsEndingBracket;\n # <-- action\n # at file 110:66: ( body_content )+\n match_count_20 = 0\n while true\n alt_20 = 2\n look_20_0 = @input.peek( 1 )\n\n if ( look_20_0.between?( TAG, DATA ) || look_20_0 == PCDATA )\n alt_20 = 1\n\n end\n case alt_20\n when 1\n # at line 110:66: body_content\n @state.following.push( TOKENS_FOLLOWING_body_content_IN_div_717 )\n body_content\n @state.following.pop\n\n else\n match_count_20 > 0 and break\n eee = EarlyExit(20)\n\n\n raise eee\n end\n match_count_20 += 1\n end\n\n\n match( UP, nil )\n # --> action\n printEndTag(__DIV12__);\n # <-- action\n\n when 2\n # at line 111:6: ^( TAG DIV attrs )\n match( TAG, TOKENS_FOLLOWING_TAG_IN_div_728 )\n\n match( DOWN, nil )\n __DIV13__ = match( DIV, TOKENS_FOLLOWING_DIV_IN_div_730 )\n # --> action\n printStartTag(__DIV13__);\n # <-- action\n @state.following.push( TOKENS_FOLLOWING_attrs_IN_div_734 )\n attrs\n @state.following.pop\n # --> action\n printEndingBracket;\n # <-- action\n\n match( UP, nil )\n # --> action\n putsEndTag(__DIV13__);\n # <-- action\n\n end\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 18 )\n\n end\n \n return \n end",
"def sub_page_parser\n\t\twhile @words.count < @min_words && !@pages_to_parse.empty?\n\t\t\tlink = @pages_to_parse.pluck!\n\t\t\tputs \"Processing #{link}\"\n\n\t\t\tdoc = Nokogiri::HTML( open( link ) )\n\t\t\tprocess_page( doc )\n\t\t\tputs \"Word count : #{@words.count}\"\n\n\t\t\tprocess_links( doc )\n\t\tend\n\tend",
"def parse_html_files\n Find.find(Dir.getwd) do |file|\n if !File.directory? file and File.extname(file) == '.html'\n # exclude and skip if in a bad directory\n # we may be on an html file, but some we just do not want\n current = File.new(file).path\n\n # skip these folders entirely\n if current.match(/(blog|old|draft|archive|font)/i)\n next\n end\n\n # open file, pluck content out by its element(s)\n page = Nokogiri::HTML(open(file));\n\n # grab title\n title = page.css('title').text.to_s;\n title = strip_bad_chars(title)\n\n # for page title, destroy any pipes and MS pipes and return the first match\n title.sub!('Velir | ', '')\n\n # Grab hero title and tagline\n hero = page.css('article.type-centered h2').text\n hero_tagline = page.css('article.type-centered .type-hero').text\n\n # grab the body content\n body = page.css('.outer-wrapper .row .columns').to_html\n body = clean_body(body)\n\n # clean the file path\n path = File.new(file).path\n path.gsub! $base_path, \"/\"\n\n # if we have content, add this as a page to our page array\n if (body.length > 0)\n $count += 1\n puts \"Processing \" + title\n\n # insert into array\n data = {\n 'title' => title,\n 'path' => path,\n 'hero' => hero,\n 'hero_tagline' => hero_tagline,\n 'body' => body,\n }\n\n $pages.push data\n end\n end\n end\n\n write_csv($pages)\n report($count)\nend",
"def prepare_html(content , page_type = 'N')\n #header\n 1.upto 5 do |no| content.gsub! /^(={#{no}}) (.*) (={#{no}})/ ,\"\\nh#{no+1}. \\\\2\\n\" end\n 1.upto 5 do |no| content.gsub! /^(={#{no}}) (.*)/ ,\"\\nh#{no+1}. \\\\2\\n\" end\n\n #list\n 1.upto 5 do |no| content.gsub! /^([ ]{#{no}})(\\*) ?(.*)/ ,\"#{'*'*no} \\\\3\" end\n 1.upto 5 do |no| content.gsub! /^([ ]{#{no}})(#) ?(.*)/ ,\"#{'#'*no} \\\\3\" end\n #content.gsub! /(\\*) v (.*)/ , \"\\\\1 -\\\\2-\"\n \n #block\n content.gsub! /^\\{\\{\\{/ , \"<pre>\" ; content.gsub! /^\\}\\}\\}/ , \"</pre>\"\n content.gsub! /^\\{\\{\\\"/ , \"<blockquote>\" ; content.gsub! /^\\\"\\}\\}/ , \"</blockquote>\"\n content.gsub! /^\\{\\{\\[/ , \"<math>\" ; content.gsub! /^\\]\\}\\}/ , \"</math>\"\n \n #concept & property\n content.gsub! /\\[\\[(.*?):=(.*?)\\]\\]/ , '\\1(\\2)'\n #content.gsub! /\\[\\[(.*?)[<>=].*?\\]\\]/ , \\\"\\\\1\\\":#{APP_ROOT}/page/\\\\1\" \n content.gsub! /\\[\\[(.*?)\\]\\]/ , \"\\\"\\\\1\\\":#{APP_ROOT}/entry/\\\\1\" if defined?(APP_ROOT)\n\n #comment\n content.gsub! PTN_COMMENT , \"\\\\1\"\n content.gsub! PTN_COMMENT_MULTILINE , \"\"\n if defined? SystemConfig\n SystemConfig.site_info.each do |e|\n content.gsub! /(\\s)#{e[1]}:/ , \"\\\\1#{e[2]}\"\n end\n content.gsub! SystemConfig.ptn_url_unnamed , \"\\\\1\\\"\\\\2\\\":\\\\2\"\n content.gsub! \"%ROOT%\" , APP_ROOT\n end\n \n #Process by page_type\n case page_type\n when 'N'\n math_list = content.scan( PTN_MATH ) ; math_list.each do |m|\n #content.gsub! \"$#{m[0]}$\" , latex_render(m[0])\n content.gsub! \"$#{m[0]}$\" , get_math_img(m[0])\n end\n math_block_list = content.scan( PTN_MATH_BLOCK ) ; math_block_list.each do |m|\n #content.gsub! \"#{m[0]}\" , latex_render(m[0])\n content.gsub! \"#{m[0]}\" , get_math_img(m[0])\n end\n when 'S'\n menu_list = content.scan( PTN_MENU ) ; menu_list.each do |m|\n menu_title = m[0] ; menu_target = m[1] ; menu_str = \"M{{#{menu_title}|#{menu_target}}}\"\n #$lgr.info \"#{menu_title} / #{menu_target}\"\n result = link_to_remote(menu_title , :url => { :action => 'menu' , :query => CGI.escape(menu_target) })\n content.gsub! menu_str , result\n end\n end\n #$lgr.info \"[prepare_html] \"+content\n query_list = content.scan( PTN_QUERY ) ; query_list.each do |q|\n query_type = q[0] ; query_content = q[1] ; query_str = \"#{query_type}{{#{query_content}}}\"\n case query_type\n when 'P'\n result = eval(\"find_page :display=>'|@title|@tags|@created_at|' ,\" + query_content )\n result = result.join(\"\\n\") if result.class == Array\n result = \"|_.Title|_.Tag|_.CreatedAt|\\n\"+result if query_content.scan(/:display/).size == 0\n #$lgr.info \"[prepare_html] Query : #{query_str} , #{result}\"\n content.gsub! query_str , result\n end\n end\n #content.gsub! SystemConfig.ptn_url , \"\\\"\\\\0\\\":\\\\0\"\n #???content.gsub!(SystemConfig.ptn_site) \"\\\"#{ApplicationController.SystemConfig(\\\\0)}\\\":\\\\0\"\n content\n end",
"def every_html_doc\n every_page do |page|\n if (block_given? && page.html?)\n if (doc = page.doc)\n yield doc\n end\n end\n end\n end",
"def extract_text body, options = {}\n # spans will have no effect on the way things look, we'll just get rid of them\n body.gsub!(/<\\/?span[^>]*>/, '')\n\n # there shall be only one white space between things.\n body.gsub!(/\\s+/o, ' ')\n\n # block-level tag don't need surrounding white space\n ['p', 'li', 'ul', 'ol', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'div'].each do |tagname|\n body.gsub!(/\\s*(<#{tagname}[^>]*>)\\s*/i, \"\\\\1\")\n body.gsub!(/\\s*(<\\/#{tagname}>)\\s*/i, \"\\\\1\")\n end\n\n document = Hpricot(body)\n\n # replace a lot of common elements, outputs something like markdown\n document.search('head').remove();\n document.search('script').remove();\n document.search('h1').prepend(\"\\n\\n# \").append(\" #\\n\")\n document.search('h2').prepend(\"\\n\\n## \").append(\" ##\\n\")\n document.search('h3').prepend(\"\\n\\n### \").append(\" ###\\n\")\n document.search('h4').prepend(\"\\n\\n#### \").append(\" ####\\n\")\n document.search('h5').prepend(\"\\n\\n##### \").append(\" #####\\n\")\n document.search('h6').prepend(\"\\n\\n###### \").append(\" ######\\n\")\n document.search('p, li').append(\"\\n\")\n document.search('ul li').prepend(\"* \")\n document.search('ol li').prepend(\"1. \") # markdown doesn't care.\n document.search('br').each {|br| br.swap(\"\\n\")}\n document.search('ul, ol').prepend(\"\\n\").append(\"\\n\")\n document.search('a').each {|a| a.swap(\"[#{a.inner_text}](#{a.attributes['href']})\") }\n\n content = if options.has_key? :css\n document.search(options[:css]).inner_text.strip\n elsif options.has_key? :xpath\n (document/options[:xpath]).inner_text.strip\n else\n document.inner_text.strip\n end\n\n if content.length < 100 # 100 characters is an abritrary value. Basically \"small\"\n raise \"Very short content (#{content.length} bytes) after text-extraction. Double-check the selector \\\"#{options[:css] || options[:xpath]}\\\"\"\n end\n content\nend",
"def rule4(block)\r\n condition1Flag = true\r\n condition2Flag = true\r\n firstTimeFlag = true\r\n\tcurrentFontSize = nil\r\n\tcurrentFontWeight = nil\r\n\t\r\n if block.node.respond_to? :each_child \r\n block.node.each_child do |child|\r\n\t if (@nodeChecker.isTextNode(child) || @nodeChecker.isVirtualTextNode(child))\r\n if firstTimeFlag == true\r\n\t\t\tcurrentFontSize = getPropertyValue(child, \"myfontsize\").nil? ? block.fontsize : getPropertyValue(child, \"myfontsize\")\r\n\t\t\tcurrentFontWeight = getPropertyValue(child, \"myfontweight\").nil? ? block.fontweight : getPropertyValue(child, \"myfontweight\")\r\n\t\t\tfirstTimeFlag = false\r\n else \r\n\t\t\tfontsize = getPropertyValue(child, \"myfontsize\").nil? ? block.fontsize : getPropertyValue(child, \"myfontsize\")\r\n\t\t\tfontweight = getPropertyValue(child, \"myfontweight\").nil? ? block.fontweight : getPropertyValue(child, \"myfontweight\")\r\n\t\t\t\r\n if currentFontSize != getPropertyValue(child, \"myfontsize\") \r\n condition2Flag = false\r\n end\r\n if currentFontWeight != getPropertyValue(child, \"myfontweight\") \r\n condition2Flag = false\r\n end \r\n end\r\n\t\telse\r\n\t\t\tcondition1Flag = false\r\n\t\t\tbreak\r\n\t\tend \r\n\t end\r\n\tend\r\n\t \r\n\tif condition1Flag\r\n\t\tif condition2Flag \r\n block.doc = 10\r\n else\r\n\t\t if (@p_block.doc <= 9)\r\n\t\t\tblock.doc = 9\r\n\t\t else\r\n\t\t\tblock.doc = 10\r\n\t\t end\r\n end\r\n\t\treturn NOT_DIVIDE\r\n\tend\r\n\t\r\n\treturn\r\n end"
] | {
"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\", \"H5\", \"H6\", \"OL\", \"UL\", \"PRE\", \"DL\", \"DIV\", \"NOSCRIPT\", \"BLOCKQUOTE\", \"FORM\", \"HR\", \"TABLE\", \"FIELDSET\", \"ADDRESS\"]\n r = /<(\\w+).*>/\n res = r.match(html)\n if res.nil?\n false\n else\n blockelems.include?(res[1].upcase) ? true : false\n end\n end",
"def contains_no_text_elements?\n children.each do |element| \n return true if element.is_a? REXML::Element\n end\n false\n end",
"def has_html?(text); !!text.match(/<[a-z][\\s\\S]*>/i) end",
"def untagged?( *tags )\n not tagged?( *tags )\n end",
"def is_text?(text)\n !text.empty? and text.is_a?(String) and text != VTT_HEADER\n end",
"def is_block_element; false; end",
"def strip_block(block_name)\n print \"Stripping block {block:#{block_name}}...\"\n if self.gsub!(ThemeSnippet.block_regex_pattern_for(block_name), '')\n puts \"removed!\"\n else\n puts \"no match found!\"\n end\n end",
"def is_tag?(string)\n !!string.match(/<\\s?[^<>\\/]*\\s?>/)\n end",
"def clean_block(block)\n # Return empty block if it is a list of links\n return \"\" if is_link_list?(block)\n\n # Return empty block if it is a very link heavy block\n count = 0\n no_links = block.gsub(/<a\\s[^>]*>.*?<\\/a\\s*>/im){count+=1;''}.gsub(/<form\\s[^>]*>.*?<\\/form\\s*>/im, '')\n return \"\" if no_links.length < 20 * count\n\n strip_tags(no_links)\n end",
"def body_has_meaningful_content?(body_elt)\n body_elt && body_elt.to_s != \"<body><p></p></body>\"\n end",
"def delete_tag_if(&block); end",
"def each_tag_not_in_layout(marc_item)\n layout_tags\n marc_item.marc.each_data_tags_present do |tag|\n yield tag if !layout_tags.include? tag\n end\n end",
"def delete_invalid_empty_tags!(node)\n\t\t\tnode.children.reject! do |child|\n\t\t\t\tif child.is_a?(TagNode)\n\t\t\t\t\tif child.children.empty? and !@schema.tag_may_be_empty?(child.tag_name)\n\t\t\t\t\t\ttrue\n\t\t\t\t\telse\n\t\t\t\t\t\tdelete_invalid_empty_tags!(child)\n\t\t\t\t\t\tfalse\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tnode\n\t\tend",
"def does_not_contain(&block)\n [:does_not_contain, block]\n end",
"def remove_emptytext_below_blocknodes(nodes)\n nodes.each do |node|\n node.children.each {|c| c.unlink if c.text? and c.inner_text =~ /^\\s*$/ }\n end\nend",
"def block_is_template?(block) \n block && (block_is_erb?(block) || (self.respond_to?(:block_is_haml?) && block_is_haml?(block)))\n end"
] | {
"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, '')
return "" if no_links.length < 20 * count
strip_tags(no_links)
end | [
"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|d|h|r|foot|itle)' +\n '|ul)\\\\b[^>]*>)'\n\n re = Regexp.new(re)\n out.gsub!(re, '\\\\1')\n\n # remove whitespaces outside of all elements\n out.gsub! />([^<]+)</ do |m|\n m.gsub(/^\\s+|\\s+$/, ' ')\n end\n\n out\n end",
"def process_block_elements (out)\n re = '[ \\t]+(<\\\\/?(?: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|d|h|r|foot|itle)' +\n '|ul)\\\\b[^>]*>)'\n\n re = Regexp.new(re)\n out.gsub!(re, '\\\\1')\n\n # remove whitespaces outside of all elements\n out.gsub! />([^<]+)</ do |m|\n m.gsub(/^[ \\t]+|[ \\t]+$/, ' ')\n end\n\n out\n end",
"def strip_links(html); end",
"def remove_links(block)\n inline_block = block.gsub(LINK_PATTERN) do |s|\n url = URL_PATTERN.match(s)[2]\n extension = File.extname(url)\n /\\.js|\\.css/.match(extension) && !URI.parse(url).absolute? ? '' : s\n end\n inline_block\n end",
"def prune_basic_blocks(blocks); end",
"def unwrap_links(elements); end",
"def unlink!\n parse \n @tags.each do |tag|\n @doc.xpath(\"//a[ends_with(@href,'#{tag}')]\", EndsWithFilter.new).each do |element|\n element.swap(element.children)\n end\n end\n output = @doc.xpath(\"/#{@wrap_tag}/body/p\").inner_html\n output = @doc.xpath(\"/#{@wrap_tag}/body\").inner_html if output == \"\"\n output\n end",
"def untag!\n parse\n @tags.each do |tag|\n @doc.xpath(\"//a[contains(@href,'#{tag}')]\").each do |element|\n element.swap(element.children)\n end\n end\n @doc.xpath(\"/#{@wrap_tag}\").inner_html\n end",
"def textize_links_and_strip_tags( html )\n return html if html.blank?\n if html.index(\"<\")\n text = \"\"\n link = \"\"\n tokenizer = HTML::Tokenizer.new(html)\n\n while token = tokenizer.next\n node = HTML::Node.parse(nil, 0, 0, token, false)\n if node.match :tag => 'a'\n # see if its a link tag\n if ! node.attributes.nil? and node.attributes['href']\n link = node.attributes['href']\n end\n elsif node.class == HTML::Text\n # result is only the content of any Text nodes\n text << node.to_s\n if link != \"\"\n text << ' ('+link+') '\n link = \"\"\n end\n end\n end\n \n # strip any comments, and if they have a newline at the end (ie. line with\n # only a comment) strip that too\n text.gsub(/<!--(.*?)-->[\\n]?/m, \"\")\n else\n html # already plain text\n end \n end",
"def remove_emptytext_below_blocknodes(nodes)\n nodes.each do |node|\n node.children.each {|c| c.unlink if c.text? and c.inner_text =~ /^\\s*$/ }\n end\nend",
"def remove_typepad_links\n results = @content.scan(/<a href=.*?<\\/a>/)\n\n results.each do |result|\n # if result contains an image with an image-full class\n if result =~ /image-full/\n temp = result.sub(/<a href=.*?>/, \"\").sub(/<\\/a>/, \"\")\n @content.sub!(result, temp)\n end\n end\n end",
"def removePageRelatedTags(contents)\n regex = '(?:<br\\/>\\n)?(?:<hr\\/>\\n)?<a name=\\d+><\\/a>(<img src=\"list-\\d+_\\d+.jpg\"\\/?><br\\/>\\n)*\\d*(?:\\s<br\\/>\\n\\s<br\\/>)?\\n*'\n scan = contents.scan(/#{regex}/m)\n\n if scan.length == 92\n contents = contents.gsub(/#{regex}/m, '')\n else\n fail 'Did not find 92 page tags'\n end\n checkNoImgTags(contents)\n\n contents\n end",
"def strip_tags(html) \n return html if html.blank? || !html.index(\"<\")\n tokenizer = HTML::Tokenizer.new(html)\n\n text = returning [] do |text|\n while token = tokenizer.next\n node = HTML::Node.parse(nil, 0, 0, token, false)\n # result is only the content of any Text nodes\n text << node.to_s if node.class == HTML::Text \n end\n end\n \n # strip any comments, and if they have a newline at the end (ie. line with\n # only a comment) strip that too\n result = text.join.gsub(/<!--(.*?)-->[\\n]?/m, \"\")\n \n # Recurse - handle all dirty nested tags\n result == html ? result : strip_tags(result)\n end",
"def strip_tags(tag_nodeset)\n ret = []\n tag_nodeset.each { |node| ret << node.text}\n return ret\n #return sort_by_occurance(ret)\nend",
"def remove_tags_html() self.gsub(%r{</?[^>]+?>}, '').gsub(\"\\r\\n\", ' ') end",
"def remove_all_html_tags!() gsub!(%r{</?[^>]+?>}, \"\"); strip! end",
"def delete_tag_if(&block); end",
"def parse_block_html; end",
"def strip_links(text)\n text.gsub(/<a\\b.*?>(.*?)<\\/a>/mi, '\\1')\n end"
] | {
"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)
outside.length <= st.length / (45 / rate)
end
end | [
"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?(); @type == GRT_LINKTYPE; end",
"def is_link_slot?\n return true\n end",
"def is_link_slot?\n return false\n end",
"def links?\n links.length > 0\n end",
"def isLinkkeys\n @RecordType == LINKKEYS\n end",
"def linked?\n return BlizzABS::Alignments::LINKED_GROUPS.include?(@group)\n end",
"def list_url?(u = nil, parsed: nil)\n return false if (u.nil? || u.empty?) && parsed.nil?\n parsed ||= parse_url(u)\n child_type = parsed[:child_type]\n parsed[:type] == 'lists' && (child_type.nil? || child_type.empty?)\n end",
"def list?(strict: true)\n # The cache entry must be a list or the child of a list\n return false unless parsed_url[:type] == 'lists'\n # Strict checking requires that the cache entry is a list, not a child\n return false if strict && !parsed_url[:child_type].nil?\n true\n end",
"def is_linkkeys?(); @type == GRT_LINKKEYS; end",
"def has_link_to_playlist?\n link_class == '2' || text.include?('&list=')\n end",
"def linked? cell:\n\t\t\t@links.key? cell\n\t\tend",
"def links?\n self.links.any?\n end",
"def\tcan_make_bulleted_list?()\n insert_mark = self.get_mark('insert')\n iter = self.get_iter_at_mark(insert_mark)\n return (iter.line!=0)\n end",
"def require_links?\n @require_links\n end",
"def is_link?\n kind == Story::Link\n end"
] | {
"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 .gsub('/', '')\n .gsub(\"'\", ' ')\n .gsub(/\\s+/, ' ')\n end",
"def filter_illegal_characters(value)\n value.tr(\"-_+$<>:;?!=[]`^|\\\\'\\\"`~\", \"\")\n end",
"def filter_text(text)\n text = text.to_s\n text.gsub('&', '&')\n text.gsub('\\'', ''')\n text.gsub('\"', '"')\n text.gsub('<', '<')\n text.gsub('>', '>')\n text\n end",
"def cgi_escape(input)\n CGI.escape(input)\n end",
"def unescape_value(value)\n CGI.unescape(value)\n end",
"def slugify_unsafe(text)\n # Gets rid of *most* things without making it completely unusable?\n text.gsub(%r{[\"'\\\\/;:,.!@#$%^&*()]}, '').gsub(/\\s/, '-').gsub(/-+/, '-')\n end",
"def replace_escaped_characters_in_place(raw_string); end",
"def escape_special_html_chars(value); end",
"def clean_query_string(q)\n ERB::Util.url_encode(q.gsub(/-|\\(|\\)|:/, \"\"))\n end",
"def strip_non_word_characters!\n @raw.gsub!(/[^\\w\\ \\-.,]/, ' ')\n end",
"def sanitize_tag(in_tag)\n in_tag.gsub(/[^\\w%=-\\\\+]+/,\"\")\n end",
"def clean_uniname(text)\n text.gsub!(\"'\", '')\n \n text\n end",
"def escape( str )\n str.downcase!\n str.gsub!('::', '__')\n str.gsub!(/[^a-z0-9\\-_$\\(\\)\\+\\/]/, '')\n str.gsub!('/', '%2')\n str\n end",
"def remove_dots\n @username.delete!('.')\n end",
"def sanitize_file_name(name)\r\n # NOTE: We could use ActiveSupport::Inflector#transliterate also, but that would remove diacritics also...\r\n name.gsub! /^.*(\\\\|\\/)/, ''\r\n name.gsub! /[\\:\\*\\?\\\"\\<\\>\\|]/, '_'\r\n name.gsub! \"—\", \"-\"\r\n return name.encode('ISO-8859-1', :invalid => :replace, :undef => :replace, :replace => '_')\r\n end",
"def uri_escape(input); end"
] | {
"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_metadata('aufirst', metadata['aufirst']) if metadata['aufirst']
cor.set_metadata('aucorp', metadata['aucorp']) if metadata['aucorp']
cor.set_metadata('title', wh['title'])
link = @openurl_base + '?' + co.kev
return link
end | [
"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_date.to_s + headline.to_s\n end",
"def u(str)\n str.to_url\nend",
"def create_uri url\n uri = URI.parse url\n uri.user = @login\n uri.password = @password\n uri\n end",
"def build_call_url(word)\r\n\t\t\tURI.parse(URI.escape(base_url + word))\r\n\t\tend",
"def open_url(term)\n Defcli.open_in_browser search_url(term, :api => false)\n end",
"def construct_openurl(resolver_base_url, record, record_id)\n raise_required_setup_parameter_error :record if record.nil?\n raise_required_setup_parameter_error :record_id if record_id.nil?\n openurl = (resolver_base_url.nil?) ? \"?\" : \"#{resolver_base_url}?\"\n record.search(\"addata/*\",record.namespaces).each do |addata|\n openurl << \"rft.#{addata.name}=#{addata.inner_text}&\" unless (addata.inner_text.nil? or addata.inner_text.strip.empty?)\n end\n openurl << \"rft.primo=#{record_id}\"\n return openurl\n end",
"def url(env, *args)\n end",
"def open(name, *rest, &block) # :doc:\n if name.respond_to?(:to_str) && %r{\\A[A-Za-z][A-Za-z0-9+\\-\\.]*://} =~ name\n OpenURI.open_uri(name, *rest, &block)\n else\n open_uri_original_open(name, *rest, &block)\n end\n end",
"def set_full_url(full_url)\n @url_base_str = @query_str_verb = @query_str_next_page = query_str = ''\n msg = <<-MSG_BAD_URL.gsub(/^\\t*/, '')\n\tERROR! Bad initial URL for OAI-PMH was supplied:\n\t '#{full_url}'\n\n\tValid examples are:\n\t 'http://example.com/myapp/harvest?verb=ListRecords&metadataPrefix=oai_dc'\n\t 'https://example.com/myapplic/oai?verb=ListRecords&metadataPrefix=my_oai_md&set=myset'\n\n\t- Initial URLs must not specify a resumption token.\n\t- The URLs are shown within quotes as these are probably needed to escape\n\t special characters (eg. \"&\") from the Unix shell.\n MSG_BAD_URL\n\n begin\n @url_base_str, query_str = full_url.match(/^([^\\?]*)\\?(.*)$/)[1,2]\t# full_url = @url_base_str+'?'+query_str \n @query_str_verb = query_str.match(/(verb=[^&]*)(&|$)/)[1]\t\t\t# Extract 'verb=XXXX'\n @query_str_next_page = query_str.sub(@query_str_verb, '').sub(/&&/, '&').sub(/^&|&$/, '') # All query string except 'verb=XXXX&'\n rescue Exception => ex\n STDERR.puts msg\n exit 2\n end\n\n if [@url_base_str, @query_str_verb].include?('') ||\n query_str.match(/resumptionToken/)\n STDERR.puts msg\n exit 2\n end\n end",
"def url_create(state_code, city_name)\r\n final_url = @web_url + self.url_suffix_create(state_code, city_name)\r\n puts final_url\r\n final_url\r\n end",
"def final_url=(_arg0); end",
"def url_for(string); end",
"def make_url(params) #:nodoc:\n super params.merge(:output => \"xml\", :oe => 'utf8', :ll => @ll, :spn => @spn, :sensor => false)\n end",
"def build_aeon_request_url\n # hash for params required for aeon extracted from @request\n callnum = id_to_callnum\n site = site_lookup\n specialrequest = note_to_specialrequest\n sublocation = locations_to_sublocation\n title = title_with_hierarchy\n volume = containers_to_volume\n\n params = {\n callnum: callnum,\n site: site,\n title: title,\n }\n params[:specialrequest] = specialrequest unless specialrequest.empty?\n params[:sublocation] = sublocation unless sublocation.empty?\n params[:volume] = volume unless volume.empty?\n\n AppConfig[:aspace_aeon_requests_params_transform].each do |param, transform|\n params[param] = transform.call(params[param]) if params.has_key?(param)\n end\n\n URI::HTTPS.build(host: @endpoint, path: '/OpenURL', query: URI.encode_www_form(params))\n end",
"def create_request_url uri\n uri_noslash = uri.gsub %r{^/}, \"\"\n \"#{@endpoint}/#{uri_noslash}\"\n end",
"def open_url(term)\n Defcli.open_in_browser search_url(term)\n end"
] | {
"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']
oclcnum = top_holding_info['oclcnum']
link = 'http://www.worldcat.org/oclc/' << oclcnum
cover_image_link = extract_cover_image_link(request, most)
notes = "this author's most widely held work in WorldCat"
if cover_image_link
display_text = '<img src="' << cover_image_link << '" style="width:75px;"/>'
notes = title << ' is ' << notes
else
display_text = title
end
request.add_service_response(
:service=>self,
:url=>link,
:display_text=> display_text,
:notes => notes,
:service_type_value => :highlighted_link)
end | [
"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 maps repo\n end",
"def corporation(c)\n image_tag(c.logo(16), :class=>'logo')+\" \"+h(c.name)\n end",
"def set_cat_link_class\n @loc.blank? ? 'pixi-cat-link' : 'img-link'\n end",
"def loc_cat_id(object)\n category_name = WAREHOUSE.execute(\"SELECT name FROM categories WHERE id = #{object.category_id}\")[0][\"name\"]\n location_name = WAREHOUSE.execute(\"SELECT name FROM locations WHERE id = #{object.location_id}\")[0][\"name\"]\n return location_name, category_name\n end",
"def display_cs_owl\n image_tag 'logos/Owl_FavIcon.png', class: \"mr-1 mb-0 pl-0 border-none padding-t-0 margin-t-5 no-border\", id: \"brand_ossemble\", style: \"height: 65px; width: 65px;\" \n end",
"def oai_catalog_url(*args)\n oai_pmh_oai_url(*args)\n end",
"def detail_link_to_searchworks(catkey)\n return if catkey.blank?\n\n tag.div(class: 'row') do\n tag.div(class: 'col-11 offset-1 col-md-10 offset-md-2') do\n link_to Settings.sw.url + catkey, rel: 'noopener', target: '_blank' do\n sul_icon(:'sharp-open_in_new-24px') + ' View in SearchWorks' # rubocop:disable Style/StringConcatenation\n end\n end\n end\n end",
"def photo_link(object)\n # get external record id from contributor association with\n # to create a link to the external url for the photo\n @extern_rec = get_contr_from_id(object)\n unless @extern_rec.blank?\n if @extern_rec.contr_id == 9\n return \"http://www.canadianheadstones.com/ab/view.php?id=\" + @extern_rec.ex_rec_id.to_s\n else \n return object.photo_URL\n end\n else\n # else return nil\n return nil\n end\n return nil\n end",
"def construct_ss_cathist_url(brand)\n if (brand.casecmp(\"jcrew\") == 0)\n url_str = \"http://api.shopstyle.com/action/apiGetCategoryHistogram?pid=uid289-3680017-16&fl=b284\"\n elsif (brand.casecmp(\"express\") == 0)\n url_str = \"http://api.shopstyle.com/action/apiGetCategoryHistogram?pid=uid289-3680017-16&fl=b13342\"\n elsif (brand.casecmp(\"bananarepublic\") == 0)\n url_str = \"http://api.shopstyle.com/action/apiGetCategoryHistogram?pid=uid289-3680017-16&fl=b2683\"\n end\nend",
"def create_openurl(request, wh)\n metadata = request.referent.metadata\n \n co = OpenURL::ContextObject.new\n cor = co.referent\n cor.set_format(wh['record_type'])\n cor.add_identifier(\"info:oclcnum/#{wh['oclcnum']}\")\n cor.set_metadata('aulast', metadata['aulast'] ) if metadata['aulast']\n cor.set_metadata('aufirst', metadata['aufirst']) if metadata['aufirst']\n cor.set_metadata('aucorp', metadata['aucorp']) if metadata['aucorp']\n cor.set_metadata('title', wh['title'])\n link = @openurl_base + '?' + co.kev\n return link\n end",
"def capsule_map_path(count, world)\n \"#{world.urls[:images]}/map/npczahl#{count}.gif\"\n end",
"def view_lot_link\n \"#{app_config.urls['aurora_url_prefix']}/#{self.lot_num}\"\n end",
"def link_to_ecoologic\n image = image_tag(Setting.ecoologic_link_image_url,\n {:alt => Setting.ecoologic_alt, :height => '64px'})\n url = Setting.ecoologic_link_url\n link_opts = {:title => Setting.ecoologic_link_title, :target => '_blank'}\n # :id => :ecoologic_link\n \n link_to image, url, link_opts\n end",
"def link_orthomcl_and_coding_regions_loose(interesting_orgs=['mmu'], warn=true)\n # def link_orthomcl_and_coding_regions_loose(interesting_orgs=['sce'], warn=false)\n #def link_orthomcl_and_coding_regions_loose(interesting_orgs=['cel'], warn=false)\n goods = 0\n if !interesting_orgs or interesting_orgs.empty?\n # interesting_orgs = ['pfa','pvi','the','tan','cpa','cho','ath']\n # interesting_orgs = ['pfa','pvi','the','tan','cpa','cho']\n # interesting_orgs = ['ath']\n #interesting_orgs = ['cel']\n interesting_orgs = ['mmu']\n end\n \n puts \"linking genes for species: #{interesting_orgs.inspect}\"\n \n # Maybe a bit heavy handed but ah well.\n OrthomclGene.codes(interesting_orgs).all.each do |orthomcl_gene|\n \n org, name = official_split(orthomcl_gene.orthomcl_name)\n if org.nil? #error check\n raise Exception, \"Couldn't parse orthomcl name: #{orthomcl_gene.orthomcl_name}\"\n end\n \n species = Species.find_by_orthomcl_three_letter(org)\n raise if !species\n codes = CodingRegion.find_all_by_name_or_alternate_and_species(name, species.name)\n if !codes or codes.length == 0\n if warn\n $stderr.puts \"No coding region found for #{orthomcl_gene.inspect}\"\n end\n next\n elsif codes.length > 1\n if warn\n $stderr.puts \"Multiple coding regions found for #{orthomcl_gene.inspect}\"\n end\n next\n else\n code = codes[0]\n goods += 1\n end\n \n OrthomclGeneCodingRegion.find_or_create_by_orthomcl_gene_id_and_coding_region_id(\n orthomcl_gene.id,\n code.id\n )\n end \n puts \"Properly linked #{goods} coding regions\"\n end",
"def activate_c1; activate_cat(@category_window); end",
"def oclc\n @edition['oclc']\n end",
"def build_url(cat)\n quoted = \"\\\"#{cat}\\\"\"\n escaped = self.escape_non_chars(quoted)\n \"http://www.energy.gov/search/site/#{escaped}?f[0]=bundle%3Aarticle\"\n end",
"def convert_to_url_cloudinary(path_image)\n Cloudinary::Uploader.upload(Rails.root.join(\"uploads\", path_image).to_s, :tags => \"lanscape_stories\")['url'] \n end"
] | {
"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_table = @generated.length > 100 || @expected.length > 100
@gen_header_indices, @exp_header_indices, @gen_headers, @exp_headers, @combined_headers = diff_header_indices(@gen_headers, @exp_headers)
@diff = unless @simplified_table
Diff::LCS.sdiff(@generated, @expected).map do |chunk|
gen_result = chunk.old_element || []
exp_result = chunk.new_element || []
if chunk.action == '!'
gen_result, exp_result = diff_arrays(gen_result, exp_result)
else
gen_result = gen_result.map { |el| CGI.escape_html el }
exp_result = exp_result.map { |el| CGI.escape_html el }
end
Diff::LCS::ContextChange.new(chunk.action, chunk.old_position, gen_result, chunk.new_position, exp_result)
end
end
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 = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end",
"def create_csv(table)\n time = Time.new()\n file_start = \"/extraction/csv/#{time.year}#{time.month}#{time.day}#{time.hour}#{time.min}#{time.sec}#{time.usec}\"\n CSV.open(\"public#{file_start}-data.csv\", \"w\") do |csv|\n csv << table.column_data\n table.row_data.each do |row|\n csv << row\n end\n end\n @filename << \"#{file_start}-data.csv\"\n\n #If ID data was tracked, generate id CSV as well\n if table.id_data.length > 0\n CSV.open(\"public#{file_start}-ids.csv\", \"w\") do |csv|\n csv << table.column_data\n table.id_data.each do |row|\n csv << row\n end\n end\n @filename << \"#{file_start}-ids.csv\"\n end\n end",
"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 builder.tr do\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do\n builder.i(class: 'mdi mdi-18 mdi-file-account')\n end\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do\n builder.i(class: 'mdi mdi-18 mdi-file-check')\n end\n builder.th(colspan: @combined_headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder.th(class: 'line-nr')\n builder << @combined_headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n unified_simple_body builder\n else\n @diff.each do |chunk|\n is_empty, row = old_row chunk\n\n unless is_empty\n full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\">#{chunk.old_position + 1}</td>\n <td class=\"line-nr\"></td>\n #{full_row.join}\n </tr>)\n end\n\n is_empty, row = new_row chunk\n\n next if is_empty\n\n full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\"></td>\n <td class=\"line-nr\">#{chunk.new_position + 1}</td>\n #{full_row.join}\n </tr>)\n end\n end\n end\n end.html_safe\n end",
"def test_s_parseAndCreate\n colSize = 8\n csvStr = \"foo,!!!foo!!!,!foo,bar!,!!!!!!,!!,,!\\r!,!\\r\\n!\\nNaHi,!!!Na!!!,!Na,Hi!,!\\r.\\n!,!\\r\\n\\n!,!!!!,!\\n!,!\\r\\n!\".gsub!('!', '\"')\n csvStrTerminated = csvStr + \"\\n\"\n\n myStr = csvStr.dup\n res1 = []; res2 = []\n idx = 0\n col, idx = CSV::parse_row(myStr, 0, res1)\n col, idx = CSV::parse_row(myStr, idx, res2)\n\n buf = ''\n col = CSV::generate_row(res1, colSize, buf)\n col = CSV::generate_row(res2, colSize, buf)\n assert_equal(csvStrTerminated, buf)\n\n parsed = []\n CSV::Reader.parse(csvStrTerminated) do |row|\n parsed << row\n end\n\n buf = ''\n CSV::Writer.generate(buf) do |writer|\n parsed.each do |row|\n\twriter.add_row(row)\n end\n end\n assert_equal(csvStrTerminated, buf)\n\n buf = ''\n CSV::Writer.generate(buf) do |writer|\n parsed.each do |row|\n\twriter << row\n end\n end\n assert_equal(csvStrTerminated, buf)\n end",
"def from_csv old_csv, new_csv, split_string = ',', id_column_number = 0\n\t\t@old_hash = HashCompare::csv_to_hash old_csv, split_string, id_column_number\n\t\t@new_hash = HashCompare::csv_to_hash new_csv, split_string, id_column_number\n\tend",
"def render_csv(t)\n io = StringIO.new\n io.puts (\n t.header.collect do |v|\n v ? \"\\\"#{v.to_s.gsub(/\"/, '\"\"')}\\\"\" : \"\"\n end.join(',')\n ) unless @options[:plain]\n t.each do |row|\n next if row === t.header\n io.puts (\n row.collect do |v|\n v ? \"\\\"#{v.to_s.gsub(/\"/, '\"\"')}\\\"\" : \"\"\n end.join(',')\n )\n end\n io.rewind\n io.gets(nil).encode(crlf_newline: true)\n end",
"def import_csv_full\n \n end",
"def initialize(delimited, cleanse_header: true, **args)\n @tabular = IOStreams::Tabular.new(**args)\n @delimited = delimited\n @cleanse_header = cleanse_header\n end",
"def import_csv_new(csv_params:, \n table_name:, \n table_cols:)\n # using table name temp load the intial csv\n # and then updating the results back in.\n table_name_temp = table_name.to_s + \"_clone\"\n \n # 1. clone and load\n ###################\n self.clone_and_load(csv_params: csv_params, \n table_name: table_name, \n table_cols: table_cols)\n \n # 2. compare clone and orig table.\n ##################################\n \n # 3. \n \n return false\n end",
"def test_table_csv\n line = \"\"\n line << \",abc,def,ghi,aaa\\n\"\n line << \",jkl,mno\\n\"\n line << \",pqr,stu,\\n\"\n line << \",vwx\\n\"\n\n puts @syntax.compile(line, \"\")\n end",
"def csv_object\n @csv_object ||= CSV.new(input, headers:true, return_headers: true)\n end",
"def write_data\n table = STI[self.class.name]\n table.delete_all\n\n lines = CsvStorage.find_by!(csv_file_type: self.class.name).data_store.lines\n lines.shift(self.class::SKIP_LINES_BEFORE_HEADER)\n\n headers = get_headers(clean_line(lines.shift))\n lines.shift(self.class::SKIP_LINES_AFTER_HEADER)\n\n row = nil\n line = nil\n row_number = 1 + self.class::SKIP_LINES_BEFORE_HEADER +\n self.class::SKIP_LINES_AFTER_HEADER\n\n begin\n ActiveRecord::Base.transaction do\n lines.each do |l|\n row_number += 1\n\n line = clean_line(l) || \"\"\n row = get_row(line, headers)\n\n # Allow a block, if given to determine if row is created\n unless row.values.join.blank?\n table.create!(row) if !block_given? || yield(row)\n end\n end\n end\n rescue StandardError => e\n msg = \"row #{row_number}: #{e.message} '#{line.inspect}' \"\n raise StandardError.new(msg)\n end\n end",
"def construct_data(new_snippets)\n @snippet_csv = CSV.generate { |csv| new_snippets.each { |s| csv << [s[0], s[1]] } }\n end",
"def initialize (csv_data=nil, &block)\n\n super()\n\n csv_data = block.call if block\n\n @csv_table = Rufus::DecisionTable.new csv_data\n end",
"def csvString\n resultColumns = self.generateResultColumns\n headers = resultColumns[:columns].keys\n # Start off instantiating the csv string with the header values\n csvString = headers.map{|s| self.filterValue(s)}.join(@options[:delimiter])\n\n # Now iterate over each row, sticking its value under each header\n (0..resultColumns[:maxRowIndex]).each do |rowIndex|\n csvString << \"\\r\\n\"\n csvString << headers.map{ |header|\n self.filterValue(resultColumns[:columns][header][rowIndex])\n }.join(@options[:delimiter])\n end\n return csvString\n end",
"def initialize(delimited, columns: nil, **args)\n @tabular = IOStreams::Tabular.new(columns: columns, **args)\n @delimited = delimited\n\n # Render header line when `columns` is supplied.\n @delimited << @tabular.render_header if columns && @tabular.requires_header?\n end",
"def convert\n # Create an object to store *all* lines of the *output* CSV\n @csv_out_data = FasterCSV.generate(FCSV_OUT_OPTS){|csv_out| \n\n # Iterate thru each *input* line\n line_in_count = 0\n FasterCSV.foreach(@in_file, FCSV_IN_OPTS) {|line_in|\n line_in_count += 1\n if line_in_count == 1\n self.class.verify_csv_in_headers(line_in.headers)\n # The output CSV shall be indentical to the input CSV but with\n # the COLUMN_ITEM_HANDLE replaced with COLUMN_ITEM_ID.\n @csv_out_headers = line_in.headers.deep_copy\n @index = @csv_out_headers.index(COLUMN_ITEM_HANDLE) # Index of column to be replaced\n @csv_out_headers[@index] = COLUMN_ITEM_ID\t# Replace this column in the header\n end\n\n # Iterate thru each *output* column\n line_out = []\n @csv_out_headers.each_with_index{|col,i|\n csv_out << @csv_out_headers if line_in_count == 1 && i == 0\t# Header line\n\n unless i == @index\n line_out << line_in[col]\n else\t\t\t\t\t\t# Replace with item_id\n h = DSpaceResource.new(line_in[COLUMN_ITEM_HANDLE], :item)\n if h && h.resource_id\n line_out << h.resource_id\t\t\t# The item_id corresponding to handle\n else\n STDERR.puts <<-MSG_HANDLE_LOOKUP.gsub(/^\\t*/, '')\n\t\tERROR: Either the handle '#{line_in[COLUMN_ITEM_HANDLE]}' was not found or it was\n\t\tfound but the corresponding item_id is NULL (eg. perhaps the item was\n\t\tdeleted from the database).\n MSG_HANDLE_LOOKUP\n exit ERROR_HANDLE_LOOKUP\n end\n end\n }\n csv_out << line_out\n }\n }\n end",
"def create_dataset_csv(dataset_name, csv)\n content = process_csv_to_s csv\n create_dataset dataset_name, content, 'text/csv'\n end",
"def split_atop_csv_results(csv_path)\n puts \"processing CSV file: #{csv_path}\"\n output_path_summary = csv_path.gsub(\".csv\", \".summary.csv\")\n output_path_detail = csv_path.gsub(\".csv\", \".detail.csv\")\n\n output_path = output_path_summary\n\n contents = File.read(csv_path)\n\n puts \"creating summary: #{output_path_summary}\"\n File.open(output_path_summary, \"w\")\n\n puts \"creating detail: #{output_path_detail}\"\n File.open(output_path_detail, \"w\")\n\n line_ct = 0\n contents.each_line do |line|\n line_ct += 1\n\n output_path = output_path_detail if line_ct > 3\n line.rstrip!\n next if line.empty?\n\n File.open(output_path, \"a\") do |f|\n f.puts line\n end\n end\n\n # csv2html\n puts \"converting CSV files to HTML:\"\n csv2html(output_path_summary)\n csv2html(output_path_detail)\n end"
] | {
"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
builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do
builder.i(class: 'mdi mdi-18 mdi-file-account')
end
builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do
builder.i(class: 'mdi mdi-18 mdi-file-check')
end
builder.th(colspan: @combined_headers.length)
end
builder.tr do
builder.th(class: 'line-nr')
builder.th(class: 'line-nr')
builder << @combined_headers.join
end
end
builder.tbody do
if @simplified_table
unified_simple_body builder
else
@diff.each do |chunk|
is_empty, row = old_row chunk
unless is_empty
full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }
builder << %(<tr>
<td class="line-nr">#{chunk.old_position + 1}</td>
<td class="line-nr"></td>
#{full_row.join}
</tr>)
end
is_empty, row = new_row chunk
next if is_empty
full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }
builder << %(<tr>
<td class="line-nr"></td>
<td class="line-nr">#{chunk.new_position + 1}</td>
#{full_row.join}
</tr>)
end
end
end
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 = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end",
"def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end",
"def render_table(arel)\n return if arel.first.nil?\n partial :table, :locals => {:model => arel.first.class, :arel => arel}\n end",
"def table(options = {})\n options = {\n :collection => @collection,\n :context => @context,\n :template_name => :table_row,\n :separator => nil\n }.merge(options)\n\n render_partial 'table', options\n end",
"def render!\n if displayed? then\n buffer = table.rows.map do |row|\n row.render + \"\\n\" + Terminal::Table::Separator.new(table).render\n end.join(\"\\n\")\n else\n buffer = table.render\n end\n set_displayed\n @table = Terminal::Table.new\n buffer\n end",
"def table(options = {})\n options = {\n :collection => @model_collection,\n :context => @context,\n :template_name => :table_row,\n :separator => nil\n }.merge(options)\n\n render_partial 'table', options\n end",
"def show_table\n build_html do\n if shipped_files.length == 0\n div.sha1s do\n span \"Did not find any files matching SHA1 of #{sha1.sha1}\"\n end\n else\n table.sha1s do\n thead do\n tr do\n th \"aix file\"\n th \"image path\"\n th \"lpp\"\n th \"package\"\n th \"service pack\"\n th \"aix file sha1\"\n th \"vrmf\"\n end\n end\n tbody do\n shipped_files.each do |shipped_file|\n tr do\n td shipped_file.aix_file\n td shipped_file.image_path\n td shipped_file.lpp\n td shipped_file.package\n td shipped_file.service_pack\n td shipped_file.aix_file_sha1\n td shipped_file.vrmf\n end\n end\n end\n end\n end\n end\n end",
"def generate_html\n\n # Return our to_string function if we aren't reconstructed yet\n return self.to_s if !@reconstructed_table\n\n # Create an HTML table\n html = \"<table style='border:1px solid black'>\\n\";\n\n # Loop over each row and create a new table row\n @reconstructed_table.each do |row|\n html += \"<tr>\\n\";\n\n # Loop over each column and place the cell value into a td\n row.each do |column|\n to_show = column\n to_show = \" \" if to_show == \"\"\n html += \"<td style='border:1px solid black'>#{to_show}</td>\\n\";\n end\n\n # Close the row\n html += \"</tr>\\n\";\n end\n\n # Close the table\n html += \"</table>\\n\";\n return html\n end",
"def format_html\n formatted = \"<table summary=\\\"Tide tables with columns for time of day and tide height (in meters).\\\">\\n\\t<thead>\\n\\t\\t<tr><th scope=\\\"col\\\">Time</th><th scope=\\\"col\\\">Height</th></tr>\\n\\t</thead>\\n\"\n last_date = nil\n to_csv.each_line do |row|\n row = row.chomp.split(',')\n if row[0] != last_date\n formatted += \"\\t</tbody>\\n\" unless last_date.nil?\n formatted += \"\\t<tbody>\\n\\t\\t<tr><th scope=\\\"rowgroup\\\" colspan=\\\"2\\\">#{row[0]}</th></tr>\\n\"\n last_date = row[0]\n end\n formatted += \"\\t\\t<tr><td>#{row[1]}</td><td>#{row[2]}m</td></tr>\\n\"\n end\n formatted += \"\\t</tbody>\\n</table>\\n\"\n formatted\n end",
"def initialize(generated, expected)\n @generated = CSV.parse((generated || '').lstrip, nil_value: '')\n @expected = CSV.parse((expected || '').lstrip, nil_value: '')\n\n @gen_headers, *@generated = @generated\n @gen_headers ||= []\n @exp_headers, *@expected = @expected\n @exp_headers ||= []\n\n @simplified_table = @generated.length > 100 || @expected.length > 100\n\n @gen_header_indices, @exp_header_indices, @gen_headers, @exp_headers, @combined_headers = diff_header_indices(@gen_headers, @exp_headers)\n\n @diff = unless @simplified_table\n Diff::LCS.sdiff(@generated, @expected).map do |chunk|\n gen_result = chunk.old_element || []\n exp_result = chunk.new_element || []\n if chunk.action == '!'\n gen_result, exp_result = diff_arrays(gen_result, exp_result)\n else\n gen_result = gen_result.map { |el| CGI.escape_html el }\n exp_result = exp_result.map { |el| CGI.escape_html el }\n end\n Diff::LCS::ContextChange.new(chunk.action, chunk.old_position, gen_result, chunk.new_position, exp_result)\n end\n end\n end",
"def diff_template= table\n @diff_template = table\n end",
"def render\n table(@table_attributes) do\n unless @header.empty?\n tr(@row_attributes.merge(@header_attributes)) do\n @header.component_map do |h|\n th(@cell_attributes.merge(@header_cell_attributes)) {h}\n end\n end\n else\n Builder.new\n end +\n @rows.component_map do |row|\n attributes = {row: @row_attributes, cell: @cell_attributes}\n TableRowComponent.new(row, attributes: attributes, &@block)\n end\n end\n end",
"def render\n tr(@row_attributes) do\n @data.component_map do |c|\n td(@cell_attributes) {@block ? @block.call(c) : c}\n end\n end\n end",
"def diff!(other_table, options = {})\n other_table = ensure_table(other_table)\n other_table.convert_headers!\n other_table.convert_columns!\n\n convert_headers!\n convert_columns!\n\n DiffMatrices.new(cell_matrix, other_table.cell_matrix, options).call\n end",
"def display_table\n new_table = to_array\n row_count.times do |rr|\n column_count.times do |cc|\n if yield(self[rr, cc])\n new_table[rr][cc] = { content: self[rr, cc].to_s, style: { background: '#e6e6ff' } } # purple\n else\n new_table[rr][cc] = { content: self[rr, cc].to_s, style: { background: '#000000' } } # black\n end\n end\n end\n new_table\n end",
"def table(records, &block)\n return if records.empty?\n rows = collect_rows(records, &block)\n col_widths = calculate_column_widths(rows)\n\n rows.each do |row|\n line = row.values.each_with_index.map do |value, col|\n value.to_s.ljust(col_widths[col])\n end.join(\" \").rstrip\n line = color.colorize(line, row.color) if row.color\n puts line\n end\n end",
"def show_table\n\t\t\tmainWindow2 = FXMainWindow.new(app, \"CSV File\", :width => 103*@data_set.data_labels.length, :height => 300)\t\n\t\t\ttable = FXTable.new(mainWindow2, :opts => LAYOUT_FILL)\n\t\t\ty = @data_set.data_labels.length\n\t\t\tx = @data_set.data_items.length\n\t\t\ttable.setTableSize(x, y)\n\t\t\tmainWindow2.create\n\t\t\tmainWindow2.show(PLACEMENT_SCREEN)\n\t\t\ttable.rowHeaderMode = LAYOUT_FIX_WIDTH\n\t\t\ttable.rowHeaderWidth = 0\n\t\t\tndex = 0\n\t\t\t@data_set.data_labels.each do |line|\n\t\t\t\ttable.setColumnText(ndex, line)\n\t\t\t\tndex += 1\n\t\t\tend\n\t\t\trowndex, coldex = 0, 0\n\t\t\t@data_set.data_items.each do |line|\n\t\t\t\tline.each do |inner|\n\t\t\t\t\ttable.setItemText(rowndex, coldex, inner)\n\t\t\t\t\tcoldex += 1\n\t\t\t\tend\n\t\t\t\trowndex += 1\n\t\t\t\tcoldex = 0\n\t\t\tend\n\t\t\t\n\t\tend",
"def show_table_for_files(locals={})\n files = get_files_by_type(locals[:files], locals[:file_type])\n unless files.empty?\n locals[:files] = files\n render(:partial => \"sfile_table\", :locals => locals)\n end\n end",
"def build_walkin_table()\n\n # Build a simple table\n @walkin_table = TableDisplayer.new()\n\n # Specify the column headings\n @walkin_table.columns('Referer',\n 'Revenue',\n 'Total Profit',\n '# Cust',\n 'Profit / Cust')\n\n start_date = @start_date ? @start_date : Date.parse('0000-01-01')\n end_date = @end_date ? @end_date : Date.parse('3000-01-01')\n\n # Look through all referers and get the top level list of domains\n origins = Origin.find_by_sql(\"SELECT customer_origins.referer, customer_origins.customer_id\n FROM customer_origins, (SELECT customer_id, min(orderDate) AS orderDate\n FROM orders\n GROUP BY customer_id) AS firstOrders\n WHERE customer_origins.customer_id = firstOrders.customer_id\n AND firstOrders.orderDate >= '#{start_date.to_s}'\n AND firstOrders.orderDate <= '#{end_date.to_s}'\n AND (ISNULL(first_uri) OR first_uri NOT LIKE '%ga=1%')\n AND ISNULL(first_coupon)\n GROUP BY customer_origins.customer_id\")\n\n urls = Hash.new() { |hash, key| hash[key] = Array.new() }\n\n origins.each do |origin|\n match = /:\\/\\/(www.)?([a-zA-Z0-9._-]+)\\//.match(origin.referer)\n urls[match[2].to_s] << origin.customer_id if (match)\n urls['DIRECT'] << origin.customer_id if origin.referer.nil?\n end\n\n urls.each do |url, cust_ids|\n\n customer_count = cust_ids.size\n\n # Go through all customers and figure out total revenue and profit\n\n revenue = 0.0\n profit = 0.0\n\n cust_ids.each do |cust_id|\n\n this_revenue, this_profit = revenue_and_profit(cust_id, start_date, end_date)\n revenue += this_revenue\n profit += this_profit\n\n end\n\n profit_per_customer = profit / customer_count\n\n @walkin_table.row(url,\n \"$%.2f\" % revenue,\n \"$%.2f\" % profit,\n \"%d\" % customer_count,\n \"$%.2f\" % profit_per_customer)\n\n end\n\n end"
] | {
"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 = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end",
"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 builder.tr do\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do\n builder.i(class: 'mdi mdi-18 mdi-file-account')\n end\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do\n builder.i(class: 'mdi mdi-18 mdi-file-check')\n end\n builder.th(colspan: @combined_headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder.th(class: 'line-nr')\n builder << @combined_headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n unified_simple_body builder\n else\n @diff.each do |chunk|\n is_empty, row = old_row chunk\n\n unless is_empty\n full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\">#{chunk.old_position + 1}</td>\n <td class=\"line-nr\"></td>\n #{full_row.join}\n </tr>)\n end\n\n is_empty, row = new_row chunk\n\n next if is_empty\n\n full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\"></td>\n <td class=\"line-nr\">#{chunk.new_position + 1}</td>\n #{full_row.join}\n </tr>)\n end\n end\n end\n end.html_safe\n end",
"def split_entries_div\n id = params[:record_id].to_i\n time_record = TimeRecord.find(id)\n render partial: \"split_entries\", locals: {record_id: id, old_duration: time_record.duration.to_f}, layout: false\n end",
"def render!\n if displayed? then\n buffer = table.rows.map do |row|\n row.render + \"\\n\" + Terminal::Table::Separator.new(table).render\n end.join(\"\\n\")\n else\n buffer = table.render\n end\n set_displayed\n @table = Terminal::Table.new\n buffer\n end",
"def render_row(files)\n rendered_files = files.collect {|file| render_post(file)}.join(\"\\n\")\n if split_rows\n Html::Div.new(:class => 'row') << rendered_files\n else\n rendered_files\n end\n end",
"def show_table\n\t\t\tmainWindow2 = FXMainWindow.new(app, \"CSV File\", :width => 103*@data_set.data_labels.length, :height => 300)\t\n\t\t\ttable = FXTable.new(mainWindow2, :opts => LAYOUT_FILL)\n\t\t\ty = @data_set.data_labels.length\n\t\t\tx = @data_set.data_items.length\n\t\t\ttable.setTableSize(x, y)\n\t\t\tmainWindow2.create\n\t\t\tmainWindow2.show(PLACEMENT_SCREEN)\n\t\t\ttable.rowHeaderMode = LAYOUT_FIX_WIDTH\n\t\t\ttable.rowHeaderWidth = 0\n\t\t\tndex = 0\n\t\t\t@data_set.data_labels.each do |line|\n\t\t\t\ttable.setColumnText(ndex, line)\n\t\t\t\tndex += 1\n\t\t\tend\n\t\t\trowndex, coldex = 0, 0\n\t\t\t@data_set.data_items.each do |line|\n\t\t\t\tline.each do |inner|\n\t\t\t\t\ttable.setItemText(rowndex, coldex, inner)\n\t\t\t\t\tcoldex += 1\n\t\t\t\tend\n\t\t\t\trowndex += 1\n\t\t\t\tcoldex = 0\n\t\t\tend\n\t\t\t\n\t\tend",
"def table(options = {})\n options = {\n :collection => @collection,\n :context => @context,\n :template_name => :table_row,\n :separator => nil\n }.merge(options)\n\n render_partial 'table', options\n end",
"def table(options = {})\n options = {\n :collection => @model_collection,\n :context => @context,\n :template_name => :table_row,\n :separator => nil\n }.merge(options)\n\n render_partial 'table', options\n end",
"def render_table(arel)\n return if arel.first.nil?\n partial :table, :locals => {:model => arel.first.class, :arel => arel}\n end",
"def put_file_div(lines, which, src_file)\n div id: \"#{which}-title-table\" do\n div id: \"#{which}-title\" do\n \"#{src_file.release} #{src_file.path} #{src_file.version}\"\n end\n end\n div id: which do\n @last_num = nil\n\n length = lines.length\n digits = 1\n while (length > 0)\n length /= 10\n digits += 1\n end\n\n lineno = 0\n fmt = \"%#{digits}d|%s\"\n lines.each do |type, num, line_id|\n attr_hash = { class: \"code #{type.gsub(/_/, '-')}\"}\n if line_id\n lineno += 1\n line = fmt % [ lineno, line_id ]\n else\n line = \" \"\n end\n if type != \"match\" && @last_num != num\n attr_hash[:id] = \"diff-#{which}-#{num}\"\n end\n @last_num = num\n pre attr_hash do\n line\n end\n end\n end\n end",
"def show_debit_table\n @renter = Renter.find(params[:id])\n @debit_bills = @renter.get_debit_bills\n @renter.calculate_debit\n render :partial => 'debit_bills_table'\n end",
"def split_apart_tables(raw_data) #:doc:\n raw_data.split(/\\n\\n/)\n end",
"def show_table\n build_html do\n if shipped_files.length == 0\n div.sha1s do\n span \"Did not find any files matching SHA1 of #{sha1.sha1}\"\n end\n else\n table.sha1s do\n thead do\n tr do\n th \"aix file\"\n th \"image path\"\n th \"lpp\"\n th \"package\"\n th \"service pack\"\n th \"aix file sha1\"\n th \"vrmf\"\n end\n end\n tbody do\n shipped_files.each do |shipped_file|\n tr do\n td shipped_file.aix_file\n td shipped_file.image_path\n td shipped_file.lpp\n td shipped_file.package\n td shipped_file.service_pack\n td shipped_file.aix_file_sha1\n td shipped_file.vrmf\n end\n end\n end\n end\n end\n end\n end",
"def get_table\n parts = @rest.split(TABLE_DIV_REGEXP)\n\n @table_name = parts.pop\n\n if match = VIEW_REGEXP.match(table_name)\n @view = true\n @table_name = match[1]\n end\n\n parts.pop\n @rest = parts.join('_')\n end",
"def index\n @splitters = Splitter.all\n end",
"def show_table_for_files(locals={})\n files = get_files_by_type(locals[:files], locals[:file_type])\n unless files.empty?\n locals[:files] = files\n render(:partial => \"sfile_table\", :locals => locals)\n end\n end",
"def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end",
"def cut_fragments grouped_ops \n show {\n title \"Cut Out Fragments\"\n check \"Take out #{grouped_ops.length} 1.5 mL tubes and label accordingly: #{grouped_ops.map { |op| \"#{op.output(\"Fragment\").item}\" }.to_sentence}\"\n check \"Now, cut out the bands and place them into the 1.5 mL tubes according to the following table:\"\n table grouped_ops.start_table \n .custom_column(heading: \"Gel ID\") { |op| \"#{op.input(FRAGMENT).item}\" }\n .custom_column(heading: \"Row\") { |op| op.input(FRAGMENT).row + 1 }\n .custom_column(heading: \"Column\", checkable: true) { |op| op.input(FRAGMENT).column + 1 }\n .custom_column(heading: \"1.5 mL Tube ID\") { |op| \"#{op.output(FRAGMENT_OUT).item}\" }\n .custom_column(heading: \"Length\") { |op| op.output(FRAGMENT_OUT).sample.properties[\"Length\"] }\n .end_table\n }\n end",
"def build_report_body\n draw_table(data, :width => 600)\n end"
] | {
"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-account'
title = I18n.t('submissions.show.your_output')
else
icon_cls = 'mdi-file-check'
title = I18n.t('submissions.show.expected')
end
builder.tr do
builder.th(class: 'line-nr', title: title) do
builder.i(class: %(mdi mdi-18 #{icon_cls}))
end
builder.th(title, colspan: headers.length)
end
builder.tr do
builder.th(class: 'line-nr')
builder << headers.join
end
end
builder.tbody do
if @simplified_table
if is_generated_output
split_simple_body(builder, @generated, 'del')
else
split_simple_body(builder, @expected, 'ins')
end
else
@diff.each do |chunk|
builder.tr do
if is_generated_output
is_empty, row = old_row(chunk)
position = chunk.old_position
else
is_empty, row = new_row(chunk)
position = chunk.new_position
end
builder << %(<td class="line-nr">#{position + 1 unless is_empty}</td>)
builder << row.join
end
end
end
end
end
end | [
"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 if match = VIEW_REGEXP.match(table_name)\n @view = true\n @table_name = match[1]\n end\n\n parts.pop\n @rest = parts.join('_')\n end",
"def split_apart_tables(raw_data) #:doc:\n raw_data.split(/\\n\\n/)\n end",
"def split_rows(raw_table_data) #:doc:\n tables_with_rows = Array.new\n raw_table_data.each_with_index do |table, i|\n table_rows = Array.new\n table = table.gsub(/\\n+^[\\t|\\s|\\s\\s|\\t\\s]/,\"\")\n table = table.split(/^[-]+$/)\n table.each_with_index do |sect, i|\n table[i] = sect.split(/\\n/)\n end\n tables_with_rows[i] = table\n end\n tables_with_rows\n end",
"def buildTables()\n @tableByName = {} ;\n @tableById = {} ;\n @tableByOrder = {} ;\n @stopList.each{|entry|\n @tableByName[entry.getValue(:name)] = entry ;\n @tableById[entry.getValue(:id)] = entry ;\n @tableByOrder[entry.getValue(:order)] = entry ;\n }\n end",
"def slice(table)\n head, body, array_h, array_b = 4.times.map { [] }\n index = 0\n first_column = 0\n second_column = 1\n\n (0...table.original_columns * table.original_rows).each do |col_index|\n row = table.rows[index]\n array_h += [row[first_column]]\n array_b += [row[second_column]]\n\n if col_index % table.original_columns == 2\n head << array_h\n body << array_b\n array_h, array_b = [], []\n end\n index += 1\n end\n [head, body]\n end",
"def tables\n @tables ||= {:left => left_table, :right => right_table}\n end",
"def base_table ops\n ops.start_table\n .custom_column(heading: \"Sample\") { |op| op.temporary[:item].sample.name }\n .custom_column(heading: \"Item\") { |op| op.temporary[:item].id }\n end",
"def build_table(endpoint_hash, track_ids)\n final_table = ExtractionTable.new(track_ids)\n last_doc_id = nil\n\n endpoint_hash.each do |endpoint|\n curr_bb_grp = @backbone_data[endpoint['document_id']][endpoint['id']]\n\n #If we've moved on to a new doc, remove the old data to save memory/processing later\n if last_doc_id != endpoint['document_id']\n if !last_doc_id.nil?\n @backbone_data.delete(last_doc_id)\n @flattened_data.delete(last_doc_id)\n final_table.clear_cache()\n end\n last_doc_id = endpoint['document_id']\n end\n\n final_table.new_row()\n final_table.add_group_data(endpoint['id'], curr_bb_grp, nil)\n\n #Add backbone/flattened data\n curr_bb_grp = @backbone_data[endpoint['document_id']][endpoint['parent_id']]\n grp_id = endpoint['parent_id']\n while !grp_id.nil?\n flat_data = @flattened_data[endpoint['document_id']][grp_id]\n final_table.add_group_data(grp_id, curr_bb_grp, flat_data) if !(curr_bb_grp[:annos].length == 0 && flat_data.nil?)\n grp_id = curr_bb_grp[:parent_id]\n curr_bb_grp = @backbone_data[endpoint['document_id']][grp_id]\n end\n end\n\n return final_table\n end",
"def build_table(sections) #:doc:\n \"<table>\\n\"+sections.join(\"\\n\")+\"\\n</table>\\n\\n\"\n end",
"def create_tables\n schema, table = @partition[:parent_table].split(\".\")\n start = @start\n stop = period_end(start)\n\n # Note that this starts in the *current* period, so we start at 0 rather\n # than 1 for the range, to be sure the current period gets a table *and*\n # we make the number of desired future tables\n (0..(@partition[:premake] || 4)).map do |month|\n child_table = \"#{schema}.#{table}_p#{start.to_s.tr(\"-\", \"_\")}\"\n\n if @partition[:ulid] == true\n # ULID is lexographic https://github.com/rafaelsales/ulid\n # First 10 chars are timestamp, next 16 are random. Alphabet starts with 0 and ends with Z\n pg_start = ULID.generate(start.to_time).first(10) + (\"0\" * 16) # pin to start\n pg_stop = ULID.generate(stop.to_time - 1).first(10) + (\"Z\" * 16) # pin to end\n else\n pg_start = start\n pg_stop = stop\n end\n @db.exec(\"create table if not exists #{child_table} partition of #{schema}.#{table} for values from ('#{pg_start}') to ('#{pg_stop}')\")\n start = stop\n stop = period_end(start)\n child_table\n end\n end",
"def build_table (number)\n @main_table.each{|child| @main_table.remove(child)}\n if number<=3\n @main_table.n_columns = number\n @main_table.n_rows = 1\n i = 0\n while i<number\n text = @texts[i]\n scrolled = @scrolls[i]\n if text == nil\n scrolled = Gtk::ScrolledWindow.new\n text = Gtk::TextView.new\n text.name = \"txtNumber#{i+1}\"\n text.editable = false\n scrolled.name = \"scrollNumber#{i+1}\"\n scrolled.add(text)\n scrolled.show_all\n @texts[i] = text\n @scrolls[i] = scrolled\n end\n @main_table.attach(scrolled,i,i+1,0,1)\n @main_table.show_all\n i+=1\n end\n else\n @main_table.n_rows = 2\n @main_table.n_columns = (number+1)/2\n i = 0\n fil = col = 0\n while i<number\n text = @texts[i]\n scrolled = @scrolls[i]\n if text == nil\n scrolled = Gtk::ScrolledWindow.new\n text = Gtk::TextView.new\n text.name = \"txtNumber#{i+1}\"\n scrolled.name = \"scrollNumber#{i+1}\"\n scrolled.add(text)\n scrolled.show_all\n @texts[i] = text\n @scrolls[i] = scrolled\n end\n #Fils the first row. The fil variable acts like a controller. When it changes, the row has changed.\n if (col < @main_table.n_columns && fil == 0)\n @main_table.attach(scrolled,col,col+1,0,1)\n col+=1\n if col==@main_table.n_columns #All the columns have been filled. We change rows\n fil = 1; col = 0 #Restart the columns index\n end\n else #Second row statrs here\n @main_table.attach(scrolled,col,col+1,1,2)\n col+=1\n end\n @main_table.show_all\n i+=1\n end\n end\n end",
"def table_creation(table_title, webpage_url, parameter_for_table = nil)\n table = [table_title]\n text = table_text(webpage_url, parameter_for_table)\n (0...text.length / 2).each do |i|\n table[i + 1] = \"#{text[i * 2]} #{text[i * 2 + 1]}\"\n end\n table\n end",
"def create_table_and_copy_info\n create_new_table\n paged_copy\n multi_pass_delta_copy if multi_pass?\n end",
"def create_join_table_mobil(filter, all_savings)\n filter.each_with_index do |contract, index|\n JoinTableMobilContract.create(mobil_simulation: self, mobil_contract: contract, savings: all_savings[index])\n end\n end",
"def split_old_bin(table, new_table, i, node, node_hash, forwarder); end",
"def create_add_partner_table(options_table2)\n options_table2.raw.each do |row|\n case row[0].downcase\n when 'first name'\n first_name.set row[1]\n when 'last name'\n last_name.set row[1]\n when 'email'\n sleep 1\n email.set row[1]\n when 'date of birth'\n sleep 3\n dob.click\n dob.set row[1]\n sleep 1\n when 'gender'\n gender_dropdown.click\n sleep 2\n gender_select.each do |gen|\n gen.click if gen.text == row[1]\n end\n when 'partner info'\n sleep 2\n partner_information_dropdown.click\n partiner_info_select.each do |pi|\n pi.click if pi.text == row[1]\n end\n end\n end\n end",
"def split(table_or_region_name)\n @admin.split(table_or_region_name)\n end",
"def cut_fragments grouped_ops \n show {\n title \"Cut Out Fragments\"\n check \"Take out #{grouped_ops.length} 1.5 mL tubes and label accordingly: #{grouped_ops.map { |op| \"#{op.output(\"Fragment\").item}\" }.to_sentence}\"\n check \"Now, cut out the bands and place them into the 1.5 mL tubes according to the following table:\"\n table grouped_ops.start_table \n .custom_column(heading: \"Gel ID\") { |op| \"#{op.input(FRAGMENT).item}\" }\n .custom_column(heading: \"Row\") { |op| op.input(FRAGMENT).row + 1 }\n .custom_column(heading: \"Column\", checkable: true) { |op| op.input(FRAGMENT).column + 1 }\n .custom_column(heading: \"1.5 mL Tube ID\") { |op| \"#{op.output(FRAGMENT_OUT).item}\" }\n .custom_column(heading: \"Length\") { |op| op.output(FRAGMENT_OUT).sample.properties[\"Length\"] }\n .end_table\n }\n end"
] | {
"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| @gen_header_indices.index(i) }.map do |idx|
if idx.nil?
'<td></td>'
else
%(<td class="del">#{CGI.escape_html gen_cols[idx]}</td>)
end
end.join
end
exp_cols = @expected.transpose.map { |col| col.join("\n") }
builder.tr do
builder.td(class: 'line-nr')
builder.td(class: 'line-nr') do
builder << (1..@expected.length).to_a.join("\n")
end
builder << Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map do |idx|
if idx.nil?
'<td></td>'
else
%(<td class="ins">#{CGI.escape_html exp_cols[idx]}</td>)
end
end.join
end
end | [
"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 builder.tr do\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do\n builder.i(class: 'mdi mdi-18 mdi-file-account')\n end\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do\n builder.i(class: 'mdi mdi-18 mdi-file-check')\n end\n builder.th(colspan: @combined_headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder.th(class: 'line-nr')\n builder << @combined_headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n unified_simple_body builder\n else\n @diff.each do |chunk|\n is_empty, row = old_row chunk\n\n unless is_empty\n full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\">#{chunk.old_position + 1}</td>\n <td class=\"line-nr\"></td>\n #{full_row.join}\n </tr>)\n end\n\n is_empty, row = new_row chunk\n\n next if is_empty\n\n full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\"></td>\n <td class=\"line-nr\">#{chunk.new_position + 1}</td>\n #{full_row.join}\n </tr>)\n end\n end\n end\n end.html_safe\n end",
"def build_table_body\n body =\n if data.column_names && !data.column_names.empty?\n data\n else\n data[1..-1]\n end\n body.each { |row| build_md_row(output, row) }\n end",
"def split_simple_body(builder, data, cls)\n gen_cols = data.transpose.map { |col| col.join(\"\\n\") }\n\n builder.tr do\n builder.td(class: 'line-nr') do\n builder << (1..data.length).to_a.join(\"\\n\")\n end\n gen_cols.each do |col|\n builder.td(class: cls) do\n builder << CGI.escape_html(col)\n end\n end\n end\n end",
"def to_s\n string_to_add = \" with cells: \"\n @reconstructed_table.each do |row|\n string_to_add += \"\\n\\t#{row}\"\n end\n super + string_to_add\n 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 = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end",
"def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n new_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n new_rows << nil if include_header_row? || grp_k.positive?\n # Compute group body\n grp_col = {}\n grp.each_with_index do |row, grp_row_k|\n new_row = {}\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n table.headers.each do |h|\n grp_col[h] ||= Column.new(header: h)\n grp_col[h] << row[h]\n istruct = format_at[location][h]\n new_row[h] = [row[h], format_cell(row[h], istruct,\n decorate: decorate)]\n end\n new_rows << [location, new_row]\n tbl_row_k += 1\n end\n # Compute group footers\n gfooters.each_pair do |label, gfooter|\n # Mark the beginning of a group footer\n new_rows << nil\n gfoot_row = {}\n first_h = nil\n grp_col.each_pair do |h, col|\n first_h ||= h\n gfoot_row[h] =\n if gfooter[h]\n val = col.send(gfooter[h])\n istruct = format_at[:gfooter][h]\n [val, format_cell(val, istruct, decorate: decorate)]\n else\n [nil, '']\n end\n end\n if gfoot_row[first_h].last.blank?\n istruct = format_at[:gfooter][first_h]\n gfoot_row[first_h] =\n [label, format_cell(label, istruct, decorate: decorate)]\n end\n new_rows << [:gfooter, gfoot_row]\n end\n end\n new_rows\n end",
"def to_markdown\n raise \"expected 2D array\" unless self.first.is_a?(Array)\n\n # Find max widths of data/headers: eg => [10, 25, 18, 21, 6]\n widths = self.transpose.map{ |col| ([col.first.class.to_s.length] + col.map{ |i| i.to_s.length }).max }\n\n # Use the class of each cell in the first row for the table headers.\n out = self.first.map.with_index{|c,i| c.class.to_s.ljust(widths[i])}.join(\" | \") + \"\\n\"\n out << out.gsub(/[^|]/, \"-\") + \"\\n\"\n\n # Left justify each cell\n self.each do |row|\n out << row.map(&:to_s).map.with_index{|c,i| c.ljust(widths[i])}.join(\" | \") + \"\\n\"\n end\n out\n\n rescue => e\n warn \"Unable to generate table: #{e}\"\n nil\n end",
"def tableify header_and_rows_ary, padding = 0\n table = Text::Table.new(:horizontal_padding => 1,\n :vertical_boundary => '-',\n :horizontal_boundary => '|',\n :boundary_intersection => '+',\n # :boundary_intersection => '-',\n # :boundary_intersection => ' ',\n :first_row_is_head => true,\n # :rows => header_and_rows_ary # works only for to_table\n )\n table.head = header_and_rows_ary[0]\n table.rows = header_and_rows_ary[1..-1]\n\n # table.to_s\n # table.rows = header_and_rows_ary\n #\n # table = header_and_rows_ary.to_table(:first_row_is_head => true)\n\n res = table.to_s.split(\"\\n\")\n res.map {|row_str| ' ' * padding + row_str}\n end",
"def output\n # If there are neither headers nor any rows in the table, return an\n # empty string.\n return '' if table.empty? && table.headers.empty?\n\n # This results in a hash of two-element arrays. The key\n # is the header and the value is an array of the header and formatted\n # header. We do the latter so the structure parallels the structure for\n # rows explained next.\n formatted_headers = build_formatted_headers\n\n # These produce an array with each element representing a row of the\n # table. Each element of the array is a two-element array. The location of\n # the row in the table (:bfirst, :body, :gfooter, etc.) is the first\n # element and a hash of the row is the second element. The keys for the\n # hash are the row headers as in the Table, but the values are two element\n # arrays as well. First is the raw, unformatted value of the cell, the\n # second is a string of the first value formatted according to the\n # instructions for the column and location in which it appears. The\n # formatting done on this pass is only formatting that affects the\n # contents of the cells, such as inserting commas, that would affect the\n # width of the columns as displayed. We keep both the raw value and\n # unformatted value around because we have to make two passes over the\n # table if there is any alignment, and we want to know the type of the raw\n # element for the second pass of formatting for type-specific formatting\n # (e.g., true_color, false_color, etc.).\n new_rows = build_formatted_body\n new_rows += build_formatted_footers\n\n # Having formatted the cells, we can now compute column widths so we can\n # do any alignment called for if this is a Formatter that performs its own\n # alignment. On this pass, we also decorate the cells with colors, bold,\n # etc.\n if aligned?\n widths = width_map(formatted_headers, new_rows)\n table.headers.each do |h|\n fmt_h = formatted_headers[h].last\n istruct = format_at[:header][h]\n formatted_headers[h] =\n [h, format_cell(fmt_h, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows = []\n new_rows.each do |loc_row|\n if loc_row.nil?\n aligned_rows << nil\n next\n end\n loc, row = *loc_row\n aligned_row = {}\n row.each_pair do |h, (val, _fmt_v)|\n istruct = format_at[loc][h]\n aligned_row[h] =\n [val, format_cell(val, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows << [loc, aligned_row]\n end\n new_rows = aligned_rows\n end\n\n # Now that the contents of the output table cells have been computed and\n # alignment applied, we can actually construct the table using the methods\n # for constructing table parts, pre_table, etc. We expect that these will\n # be overridden by subclasses of Formatter for specific output targets. In\n # any event, the result is a single string (or ruby object if eval is true\n # for the Formatter) representing the table in the syntax of the output\n # target.\n result = ''\n result += pre_table\n if include_header_row?\n result += pre_header(widths)\n result += pre_row\n cells = []\n formatted_headers.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n result += post_header(widths)\n end\n new_rows.each do |loc_row|\n if loc_row.nil?\n result += hline(widths)\n next\n end\n\n _loc, row = *loc_row\n result += pre_row\n cells = []\n row.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n end\n result += post_footers(widths)\n result += post_table\n\n # If this Formatter targets a ruby data structure (e.g., AoaFormatter), we\n # eval the string to get the object.\n evaluate? ? eval(result) : result\n end",
"def generate_html\n\n # Return our to_string function if we aren't reconstructed yet\n return self.to_s if !@reconstructed_table\n\n # Create an HTML table\n html = \"<table style='border:1px solid black'>\\n\";\n\n # Loop over each row and create a new table row\n @reconstructed_table.each do |row|\n html += \"<tr>\\n\";\n\n # Loop over each column and place the cell value into a td\n row.each do |column|\n to_show = column\n to_show = \" \" if to_show == \"\"\n html += \"<td style='border:1px solid black'>#{to_show}</td>\\n\";\n end\n\n # Close the row\n html += \"</tr>\\n\";\n end\n\n # Close the table\n html += \"</table>\\n\";\n return html\n end",
"def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end",
"def table_body; end",
"def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n out_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # NB: grp is an array of hashes, one for each row in the group.\n #\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n out_rows << nil if include_header_row? || grp_k.positive?\n # Format group body rows\n grp.each_with_index do |row, grp_row_k|\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n\n out_row = {}\n row.each_pair do |h, v|\n istruct = format_at[location][h]\n out_row[h] = [row[h], format_cell(row[h], istruct, decorate: decorate)]\n end\n out_rows << [location, out_row]\n tbl_row_k += 1\n end\n # Format group footers\n gfooters.each_pair do |label, gfooter|\n out_rows << nil\n gfoot_row = Hash.new([nil, ''])\n gfooter.to_h(grp_k).each_pair do |h, v|\n istruct = format_at[:gfooter][h]\n gfoot_row[h] = [v, format_cell(v, istruct, decorate: decorate)]\n end\n out_rows << [:gfooter, gfoot_row]\n end\n end\n out_rows\n end",
"def wrap_row(cells) #:doc:\n if cells.length > 0\n \"\\t<tr> \"+cells.join(\"\")+ \" </tr>\"\n end\n end",
"def output\n # This results in a hash of two-element arrays. The key is the header and\n # the value is an array of the header and formatted header. We do the\n # latter so the structure parallels the structure for rows explained next.\n formatted_headers = build_formatted_headers\n\n # These produce an array with each element representing a row of the\n # table. Each element of the array is a two-element array. The location of\n # the row in the table (:bfirst, :body, :gfooter, etc.) is the first\n # element and a hash of the row is the second element. The keys for the\n # hash are the row headers as in the Table, but the values are two element\n # arrays as well. First is the raw, unformatted value of the cell, the\n # second is a string of the first value formatted according to the\n # instructions for the column and location in which it appears. The\n # formatting done on this pass is only formatting that affects the\n # contents of the cells, such as inserting commas, that would affect the\n # width of the columns as displayed. We keep both the raw value and\n # unformatted value around because we have to make two passes over the\n # table if there is any alignment, and we want to know the type of the raw\n # element for the second pass of formatting for type-specific formatting\n # (e.g., true_color, false_color, etc.).\n new_rows = build_formatted_body\n new_rows += build_formatted_footers\n\n # Having formatted the cells, we can now compute column widths so we can\n # do any alignment called for if this is a Formatter that performs its own\n # alignment. On this pass, we also decorate the cells with colors, bold,\n # etc.\n if aligned?\n widths = width_map(formatted_headers, new_rows)\n table.headers.each do |h|\n fmt_h = formatted_headers[h].last\n istruct = format_at[:header][h]\n formatted_headers[h] =\n [h, format_cell(fmt_h, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows = []\n new_rows.each do |loc_row|\n if loc_row.nil?\n aligned_rows << nil\n next\n end\n loc, row = *loc_row\n aligned_row = {}\n row.each_pair do |h, (val, _fmt_v)|\n istruct = format_at[loc][h]\n aligned_row[h] =\n [val, format_cell(val, istruct, width: widths[h], decorate: true)]\n end\n aligned_rows << [loc, aligned_row]\n end\n new_rows = aligned_rows\n end\n\n # Now that the contents of the output table cells have been computed and\n # alignment applied, we can actually construct the table using the methods\n # for constructing table parts, pre_table, etc. We expect that these will\n # be overridden by subclasses of Formatter for specific output targets. In\n # any event, the result is a single string (or ruby object if eval is true\n # for the Formatter) representing the table in the syntax of the output\n # target.\n result = ''\n result += pre_table\n if include_header_row?\n result += pre_header(widths)\n result += pre_row\n cells = []\n formatted_headers.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n result += post_header(widths)\n end\n new_rows.each do |loc_row|\n result += hline(widths) if loc_row.nil?\n next if loc_row.nil?\n\n _loc, row = *loc_row\n result += pre_row\n cells = []\n row.each_pair do |h, (_v, fmt_v)|\n cells << pre_cell(h) + quote_cell(fmt_v) + post_cell\n end\n result += cells.join(inter_cell)\n result += post_row\n end\n result += post_footers(widths)\n result += post_table\n\n # If this Formatter targets a ruby data structure (e.g., AoaFormatter), we\n # eval the string to get the object.\n evaluate? ? eval(result) : result\n end",
"def table_s(tb = nil)\n if tb.nil?\n aux = @table.clone\n else\n aux = tb\n end\n l = []\n table_str = []\n aux.each do |line|\n line.each do |e|\n if e.class == String\n l << e\n else\n l << e.round(3).to_s\n end\n end\n table_str << l.clone\n l.clear\n end\n table_str\n end",
"def table\n table = []\n 3.times do\n table << \"#{Lorem.word} | #{Lorem.word} | #{Lorem.word}\"\n end\n table.insert(1, '---- | ---- | ----')\n table.join(\"\\n\")\n end",
"def format_html\n formatted = \"<table summary=\\\"Tide tables with columns for time of day and tide height (in meters).\\\">\\n\\t<thead>\\n\\t\\t<tr><th scope=\\\"col\\\">Time</th><th scope=\\\"col\\\">Height</th></tr>\\n\\t</thead>\\n\"\n last_date = nil\n to_csv.each_line do |row|\n row = row.chomp.split(',')\n if row[0] != last_date\n formatted += \"\\t</tbody>\\n\" unless last_date.nil?\n formatted += \"\\t<tbody>\\n\\t\\t<tr><th scope=\\\"rowgroup\\\" colspan=\\\"2\\\">#{row[0]}</th></tr>\\n\"\n last_date = row[0]\n end\n formatted += \"\\t\\t<tr><td>#{row[1]}</td><td>#{row[2]}m</td></tr>\\n\"\n end\n formatted += \"\\t</tbody>\\n</table>\\n\"\n formatted\n end",
"def build_table(sections) #:doc:\n \"<table>\\n\"+sections.join(\"\\n\")+\"\\n</table>\\n\\n\"\n end"
] | {
"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(col)
end
end
end
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 = 'mdi-file-account'\n title = I18n.t('submissions.show.your_output')\n else\n icon_cls = 'mdi-file-check'\n title = I18n.t('submissions.show.expected')\n end\n builder.tr do\n builder.th(class: 'line-nr', title: title) do\n builder.i(class: %(mdi mdi-18 #{icon_cls}))\n end\n builder.th(title, colspan: headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder << headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n if is_generated_output\n split_simple_body(builder, @generated, 'del')\n else\n split_simple_body(builder, @expected, 'ins')\n end\n else\n @diff.each do |chunk|\n builder.tr do\n if is_generated_output\n is_empty, row = old_row(chunk)\n position = chunk.old_position\n else\n is_empty, row = new_row(chunk)\n position = chunk.new_position\n end\n builder << %(<td class=\"line-nr\">#{position + 1 unless is_empty}</td>)\n builder << row.join\n end\n end\n end\n end\n end\n end",
"def unified_simple_body(builder)\n gen_cols = @generated.transpose.map { |col| col.join(\"\\n\") }\n builder.tr do\n builder.td(class: 'line-nr') do\n builder << (1..@generated.length).to_a.join(\"\\n\")\n end\n builder.td(class: 'line-nr')\n\n builder << Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map do |idx|\n if idx.nil?\n '<td></td>'\n else\n %(<td class=\"del\">#{CGI.escape_html gen_cols[idx]}</td>)\n end\n end.join\n end\n\n exp_cols = @expected.transpose.map { |col| col.join(\"\\n\") }\n builder.tr do\n builder.td(class: 'line-nr')\n builder.td(class: 'line-nr') do\n builder << (1..@expected.length).to_a.join(\"\\n\")\n end\n\n builder << Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map do |idx|\n if idx.nil?\n '<td></td>'\n else\n %(<td class=\"ins\">#{CGI.escape_html exp_cols[idx]}</td>)\n end\n end.join\n end\n end",
"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 builder.tr do\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.your_output')) do\n builder.i(class: 'mdi mdi-18 mdi-file-account')\n end\n builder.th(class: 'line-nr', title: I18n.t('submissions.show.expected')) do\n builder.i(class: 'mdi mdi-18 mdi-file-check')\n end\n builder.th(colspan: @combined_headers.length)\n end\n builder.tr do\n builder.th(class: 'line-nr')\n builder.th(class: 'line-nr')\n builder << @combined_headers.join\n end\n end\n builder.tbody do\n if @simplified_table\n unified_simple_body builder\n else\n @diff.each do |chunk|\n is_empty, row = old_row chunk\n\n unless is_empty\n full_row = Array.new(@combined_headers.length) { |i| @gen_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\">#{chunk.old_position + 1}</td>\n <td class=\"line-nr\"></td>\n #{full_row.join}\n </tr>)\n end\n\n is_empty, row = new_row chunk\n\n next if is_empty\n\n full_row = Array.new(@combined_headers.length) { |i| @exp_header_indices.index(i) }.map { |idx| idx.nil? ? '<td></td>' : row[idx] }\n\n builder << %(<tr>\n <td class=\"line-nr\"></td>\n <td class=\"line-nr\">#{chunk.new_position + 1}</td>\n #{full_row.join}\n </tr>)\n end\n end\n end\n end.html_safe\n end",
"def build_table_body\n body =\n if data.column_names && !data.column_names.empty?\n data\n else\n data[1..-1]\n end\n body.each { |row| build_md_row(output, row) }\n end",
"def split_rows(raw_table_data) #:doc:\n tables_with_rows = Array.new\n raw_table_data.each_with_index do |table, i|\n table_rows = Array.new\n table = table.gsub(/\\n+^[\\t|\\s|\\s\\s|\\t\\s]/,\"\")\n table = table.split(/^[-]+$/)\n table.each_with_index do |sect, i|\n table[i] = sect.split(/\\n/)\n end\n tables_with_rows[i] = table\n end\n tables_with_rows\n end",
"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 wrap(cols=80, tabsize=2, line_sep=\"\\n\", fragment_sep=\" \", strip=true)\n lines = super(comment(fragment_sep, \"\\n\", strip), cols, tabsize)\n line_sep ? lines.join(line_sep) : lines\n end",
"def add_divider_row_to_table\n table << \" -\"\n size.times { table << '-----' }\n table << \"\\n\"\n end",
"def split_apart_tables(raw_data) #:doc:\n raw_data.split(/\\n\\n/)\n end",
"def to_s\n string_to_add = \" with cells: \"\n @reconstructed_table.each do |row|\n string_to_add += \"\\n\\t#{row}\"\n end\n super + string_to_add\n end",
"def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n new_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n new_rows << nil if include_header_row? || grp_k.positive?\n # Compute group body\n grp_col = {}\n grp.each_with_index do |row, grp_row_k|\n new_row = {}\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n table.headers.each do |h|\n grp_col[h] ||= Column.new(header: h)\n grp_col[h] << row[h]\n istruct = format_at[location][h]\n new_row[h] = [row[h], format_cell(row[h], istruct,\n decorate: decorate)]\n end\n new_rows << [location, new_row]\n tbl_row_k += 1\n end\n # Compute group footers\n gfooters.each_pair do |label, gfooter|\n # Mark the beginning of a group footer\n new_rows << nil\n gfoot_row = {}\n first_h = nil\n grp_col.each_pair do |h, col|\n first_h ||= h\n gfoot_row[h] =\n if gfooter[h]\n val = col.send(gfooter[h])\n istruct = format_at[:gfooter][h]\n [val, format_cell(val, istruct, decorate: decorate)]\n else\n [nil, '']\n end\n end\n if gfoot_row[first_h].last.blank?\n istruct = format_at[:gfooter][first_h]\n gfoot_row[first_h] =\n [label, format_cell(label, istruct, decorate: decorate)]\n end\n new_rows << [:gfooter, gfoot_row]\n end\n end\n new_rows\n end",
"def tableify header_and_rows_ary, padding = 0\n table = Text::Table.new(:horizontal_padding => 1,\n :vertical_boundary => '-',\n :horizontal_boundary => '|',\n :boundary_intersection => '+',\n # :boundary_intersection => '-',\n # :boundary_intersection => ' ',\n :first_row_is_head => true,\n # :rows => header_and_rows_ary # works only for to_table\n )\n table.head = header_and_rows_ary[0]\n table.rows = header_and_rows_ary[1..-1]\n\n # table.to_s\n # table.rows = header_and_rows_ary\n #\n # table = header_and_rows_ary.to_table(:first_row_is_head => true)\n\n res = table.to_s.split(\"\\n\")\n res.map {|row_str| ' ' * padding + row_str}\n end",
"def change_verbatim_blank_lines\n frag_block = nil\n blank_count = 0\n @fragments.each_with_index do |frag, i|\n if frag_block.nil?\n frag_block = frag if Verbatim === frag\n else\n case frag\n when Verbatim\n blank_count.times { frag_block.add_text(\"\\n\") }\n blank_count = 0\n frag_block.add_text(frag.txt)\n @fragments[i] = nil # remove out current fragment\n when BlankLine\n if frag_block\n blank_count += 1\n @fragments[i] = nil\n end\n else\n frag_block = nil\n blank_count = 0\n end\n end\n end\n @fragments.compact!\n end",
"def split_into_columns\r\n split_into_rows.transpose\r\n end",
"def table_body; end",
"def build_formatted_body\n # Don't decorate if this Formatter calls for alignment. It will be done\n # in the second pass.\n decorate = !aligned?\n out_rows = []\n tbl_row_k = 0\n table.groups.each_with_index do |grp, grp_k|\n # NB: grp is an array of hashes, one for each row in the group.\n #\n # Mark the beginning of a group if this is the first group after the\n # header or the second or later group.\n out_rows << nil if include_header_row? || grp_k.positive?\n # Format group body rows\n grp.each_with_index do |row, grp_row_k|\n location =\n if tbl_row_k.zero?\n :bfirst\n elsif grp_row_k.zero?\n :gfirst\n else\n :body\n end\n\n out_row = {}\n row.each_pair do |h, v|\n istruct = format_at[location][h]\n out_row[h] = [row[h], format_cell(row[h], istruct, decorate: decorate)]\n end\n out_rows << [location, out_row]\n tbl_row_k += 1\n end\n # Format group footers\n gfooters.each_pair do |label, gfooter|\n out_rows << nil\n gfoot_row = Hash.new([nil, ''])\n gfooter.to_h(grp_k).each_pair do |h, v|\n istruct = format_at[:gfooter][h]\n gfoot_row[h] = [v, format_cell(v, istruct, decorate: decorate)]\n end\n out_rows << [:gfooter, gfoot_row]\n end\n end\n out_rows\n end",
"def table\n table = []\n 3.times do\n table << \"#{Lorem.word} | #{Lorem.word} | #{Lorem.word}\"\n end\n table.insert(1, '---- | ---- | ----')\n table.join(\"\\n\")\n end",
"def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end",
"def generate_html\n\n # Return our to_string function if we aren't reconstructed yet\n return self.to_s if !@reconstructed_table\n\n # Create an HTML table\n html = \"<table style='border:1px solid black'>\\n\";\n\n # Loop over each row and create a new table row\n @reconstructed_table.each do |row|\n html += \"<tr>\\n\";\n\n # Loop over each column and place the cell value into a td\n row.each do |column|\n to_show = column\n to_show = \" \" if to_show == \"\"\n html += \"<td style='border:1px solid black'>#{to_show}</td>\\n\";\n end\n\n # Close the row\n html += \"</tr>\\n\";\n end\n\n # Close the table\n html += \"</table>\\n\";\n return html\n end"
] | {
"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.compact.each_with_index.map{ |cell, i|\n # ... fixme\n if cell.is_a? Hash\n cell_content = ERB::Util.h(cell[:content])\n cell_opts = cell\n else\n cell_content = ERB::Util.h(cell)\n cell_opts = {}\n end\n classes = []\n classes << 'small_label' if i.even? && opts[:labels] && cells.length > 1\n classes << 'pre' if cell_opts[:pre]\n classes << 'tiny' if cell_opts[:tiny]\n classes << 'small' if cell_opts[:small]\n classes << 'bold' if cell_opts[:bold]\n classes << 'light' if cell_opts[:light]\n classes << 'superlight' if cell_opts[:superlight]\n\n styles = []\n styles << 'padding-left:2em' if i != 0 && i.even?\n # Yuck, this is nuts..\n \"<td\" +\n \"#{\" colspan='#{cell_opts[:colspan]}'\" if cell_opts[:colspan]}\" +\n \" style='#{safe_join(styles, ';')}'\" +\n \" class='#{safe_join(classes, ' ')}'\" +\n \">#{cell_content}\"+\n \"#{\"<br/><span class='small light'>#{cell_opts[:note]}</span>\" if cell_opts[:note]}\" + # even more hackery\n \"</td>\"\n }.join(\"\\n\")}</tr>\".html_safe\n end\n end",
"def render_line\n if @type == :thead\n return content_tag(:tr, Tools::html_safe(@cells.collect { |cell| cell.render_cell_thead }.join), @html_options)\n elsif @type == :tfoot\n return content_tag(:tr, Tools::html_safe(@cells.collect { |cell| cell.render_cell_tfoot }.join), @html_options)\n else\n content_tag(:tr, Tools::html_safe(@cells.collect { |cell| cell.render_cell_tbody }.join), @html_options.merge(:class => \"#{@html_options[:class]} #{@@template.cycle(:odd, :even)}\".strip))\n end\n end",
"def css_classes_for_row(); \"rsrcRow #{self.kind}row #{@tag}row\" end",
"def css_classes_for_row(); \"rsrcRow #{self.kind}row #{@tag}row #{self.kind}Row #{@tag}Row\" end",
"def wrap_row(cells) #:doc:\n if cells.length > 0\n \"\\t<tr> \"+cells.join(\"\")+ \" </tr>\"\n end\n end",
"def render\n tr(@row_attributes) do\n @data.component_map do |c|\n td(@cell_attributes) {@block ? @block.call(c) : c}\n end\n end\n end",
"def complete_row\n if @row\n @row.each do |cell|\n attributes = \"\"\n classes = []\n cell.keys.each{|k| classes << k unless (k == :content ||\n k == :top_border ||\n k == :bottom_border)}\n if cell[:top_border] == :single\n classes << :top_border_single\n elsif cell[:top_border] == :double\n classes << :top_border_double\n end\n\n if cell[:bottom_border] == :single\n classes << :bottom_border_single\n elsif cell[:bottom_border] == :double\n classes << :bottom_border_double\n end\n\n attributes = classes.empty? ? \"\" : \" class='#{classes.join(' ')}'\"\n\n @html << \" <td#{attributes}>#{cell[:content]}</td>\\n\"\n end\n @html << \" </tr>\\n\"\n end\n\n @last_row = @row\n @row = nil\n end",
"def row(klass, *items)\n @processed_rows += 1\n [ '', %Q(<tr class=\"#{klass}\">), items, '</tr>' ].flatten.join\n \n end",
"def game_td(game, left_or_right, row_span, &block)\n rowspan = 2 ** (row_span || (game.round.number - 1))\n concat content_tag(:td, capture(&block), :rowspan => rowspan, :align => left_or_right), block.binding\n end",
"def render_cell_tbody\n if @type == :action\n cell_value = action_link_to(@ask)\n elsif @ask\n cell_value = (@ask.is_a?(Symbol)) ? format_cell_value(@object[@ask], @ask) : format_cell_value(@ask)\n else\n cell_value = @block\n end\n cell_value = action_link_to(@options[:action], cell_value) if @type != :action and @options.has_key?(:action)\n content_tag(:td, cell_value, @html_options)\n end",
"def row_to_cells(parser, row, cells)\n cells.map do |cell|\n # Remove consistent indentation at the front of the cell body\n body = self.trim_indent(cell)\n # Parse the body into blocks\n blocks = parser.parse_thin(body)\n \n Blocks::TableCell.new(row, blocks)\n end\n end",
"def get_row_class\n return @classes[:even] if @processed_rows % 2 == 0\n @classes[:odd]\n end",
"def html_row(entry)\n attrs = {}\n attrs[:id] = dom_id(entry) if entry.respond_to?(:to_key)\n content_tag_nested(:tr, cols, attrs) { |c| c.html_cell(entry) }\n end",
"def split_simple_body(builder, data, cls)\n gen_cols = data.transpose.map { |col| col.join(\"\\n\") }\n\n builder.tr do\n builder.td(class: 'line-nr') do\n builder << (1..data.length).to_a.join(\"\\n\")\n end\n gen_cols.each do |col|\n builder.td(class: cls) do\n builder << CGI.escape_html(col)\n end\n end\n end\n end",
"def event_cell event, colspan\n content_tag(:td, event.name, { :class => 'event', :rowspan => event.duration.to_s, :colspan => colspan.to_s })\n end",
"def html_row(entry)\n attrs = {}\n attrs[:id] = dom_id(entry) if entry.respond_to?(:to_key)\n content_tag_nested(:tr, cols, attrs) { |c| c.html_cell(entry) }\n end",
"def render_html_table(rde_table)\n content_tag(:table, class: 'table rde-table') do\n rde_table.rows.map { |row|\n content_tag(row.tag, class: row.css_class) do\n row.cells.map { |cell|\n if cell.ruby_formatter\n content_tag(\n cell.tag,\n instance_exec(cell.value, &cell.ruby_formatter),\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n else\n content_tag(\n cell.tag,\n cell.value,\n class: cell.css_class,\n title: cell.title,\n style: cell.style,\n )\n end\n }.join.html_safe\n end\n }.join.html_safe\n end\n end",
"def to_html_row\n row = ''\n count = 0\n name = ''\n @schedule.each_with_index do |block, index|\n\n if block.nil? && count.zero?\n row << '<td></td>'\n elsif !count.zero? && block.nil?\n row << count.to_s\n row << '\">'\n row << name\n row << '</td>'\n row << '<td></td>'\n count = 0\n elsif !count.zero? && index == @schedule.length - 1\n row << (count + 1).to_s\n row << '\">'\n row << name\n row << '</td>'\n elsif !count.zero?\n count += 1\n else\n row << '<td class=\"bg-primary table-dark\"\" colspan=\"' if count.zero?\n count += 1\n name = block\n end\n\n end\n row.html_safe\n end",
"def event_row_tag(event) \n if event.ended? || (event.out_of_date && event.one_off?)\n class_string = \"inactive\"\n elsif event.out_of_date\n class_string = \"out_of_date\"\n elsif event.near_out_of_date\n class_string = \"near_out_of_date\"\n end\n tag :tr, {:class => class_string}, true\n end"
] | {
"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
gen_headers << %(<th class="del"><strong>#{CGI.escape_html chunk.old_element}</strong></th>)
combined_headers << %(<th class="del"><strong>#{CGI.escape_html chunk.old_element}</strong></th>)
when '+'
exp_indices << counter
counter += 1
exp_headers << %(<th class="ins"><strong>#{CGI.escape_html chunk.new_element}</strong></th>)
combined_headers << %(<th class="ins"><strong>#{CGI.escape_html chunk.new_element}</strong></th>)
when '='
gen_indices << counter
exp_indices << counter
counter += 1
gen_headers << %(<th>#{CGI.escape_html chunk.old_element}</th>)
exp_headers << %(<th>#{CGI.escape_html chunk.new_element}</th>)
combined_headers << %(<th>#{CGI.escape_html chunk.new_element}</th>)
when '!'
gen_indices << counter
counter += 1
gen_headers << %(<th class="del"><strong>#{CGI.escape_html chunk.old_element}</strong></th>)
combined_headers << %(<th class="del"><strong>#{CGI.escape_html chunk.old_element}</strong></th>)
exp_indices << counter
counter += 1
exp_headers << %(<th class="ins"><strong>#{CGI.escape_html chunk.new_element}</strong></th>)
combined_headers << %(<th class="ins"><strong>#{CGI.escape_html chunk.new_element}</strong></th>)
end
end
[gen_indices, exp_indices, gen_headers, exp_headers, combined_headers]
end | [
"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, expected)\n testcase_desc = \"TestCase header: #{header.inspect} \" +\n \"expected result: #{expected.inspect}\"\n count = 0\n header.each_with_index { |value, index|\n count = count.succ\n assert_operator(index, '<', expected.length,\n\t\t \"result has too few elements. #{testcase_desc}\")\n assert_operator(2, '<=', expected[index].length,\n\t\t \"Expected result item must have at last two elements. \" +\n testcase_desc)\n assert_operator(3, '>=', expected[index].length,\n\t\t \"Expected result item must have no more than three \" +\n\t\t \"elements. \" + testcase_desc)\n assert_equal(2, value.length, testcase_desc)\n\n expected_tag, expected_header = expected[index]\n got_tag, got_header = value\n\n assert_equal(header[index], got_header, testcase_desc)\n\n assert_equal(expected_tag, got_tag,\n\t\t \"field #{index} has incorrect name. \" + testcase_desc)\n assert_equal(expected_header, got_header,\n\t\t \"field #{index} has incorrect line, \" +\n\t\t \"expected #{expected_header.inspect} got \" +\n\t\t \"#{got_header.inspect}. \" + testcase_desc)\n assert_equal(header[expected_tag], expected_header, testcase_desc)\n }\n assert_equal(count, expected.length,\n \"result has too few elements \" +\n \"(#{count} < #{expected.length}). \" + testcase_desc)\n end",
"def build_sorted_header_array\n array_to_compare = []\n self.header_array.each do |name|\n field = @@all_fields.find {|field| field[:name] == name}\n array_to_compare << field unless field.blank?\n end\n array_to_compare\n end",
"def verify_header_names(key, models_columns, header)\n normalized_header = []\n \n got_error = false\n header.each_with_index do |h, i|\nlogger.debug \"verify header: #{h}\"\n if h == \"id\"\n error(cur_sheet_name, 1, \"Header column #{h} not allowed, update not supported yet\")\n next\n end\n\n if h.nil?\t# ignore mepty header\n normalized_header[i] = nil\n next\n else\n normalized_header[i] = normalize_header(h)\n end\n\n # see if heading is an attribute name, pseudo attribute,\n # fk_finder, refrerence id or reference to one\n # if so, put it in the models_columns :headers hash with header index\n header_is_known = false\n show_header_in_results = true\n models_columns.each_with_index do |mc, ci|\n\n # check for ambiguous header name\n if mc[:dups].has_key?(normalized_header[i])\n#logger.debug \"verify_header: ci: #{ci} found ambiguous header: #{normalized_header[i]}\"\n dup_index = mc[:dups][normalized_header[i]]\n#logger.debug \"verify_header: ci: #{ci} dup_index: #{dup_index}\"\n next if dup_index.nil?\n if dup_index == i\n header_is_known = true\n mc[:headers] << [normalized_header[i], i] # 0 based index\n#logger.debug \"header #{h} i: #{i} ci: #{ci} is_ambiguous_model_column mc[:headers]: #{mc[:headers]}\"\n break\n end\n next\n end\n\n if mc[:allowed_cols].include?(normalized_header[i])\n header_is_known = true\n mc[:headers] << [normalized_header[i], i] # 0 based index\n#logger.debug \"header #{h} is_model_column mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_pseudo_attr(mc[:model], normalized_header[i])\n header_is_known = true\n mc[:headers] << [normalized_header[i], i]\n#logger.debug \"header #{h} is_model_pseudo_attr mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_fk_finder_header(normalized_header[i], mc)\n header_is_known = true\n mc[:headers] << [normalized_header[i], i]\n#logger.debug \"header #{h} is_fk_finder mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_ref_def_header(normalized_header[i], mc[:model])\n header_is_known = true\n show_header_in_results = false\n @sheet_results[key][:_refs][(mc[:model]).name] = normalized_header[i]\n @sheet_results[key][:_ref_ids][normalized_header[i]] = {}\n mc[:headers] << [normalized_header[i], i]\n#logger.debug \"header #{h} is_ref_def mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_ref_ref_header(normalized_header[i], mc)\n header_is_known = true\n mc[:headers] << [normalized_header[i], i]\n#logger.debug \"header #{h} is_ref_ref mc[:headers]: #{mc[:headers]}\"\n break\n end\n end\n if !show_header_in_results\n normalized_header.delete_at(i)\n end\n next if header_is_known\n\n # error if not recognized, but continue to gather all errors\n got_error = true\n error(cur_sheet_name, 1, \"Header name '#{h}' is not recognized for model(s) #{model_column_names(models_columns)}\")\n end\n return false if got_error\n\n#logger.debug \"mc[0][:headers]: #{models_columns[0][:headers]}\"\n#logger.debug \"mc[1][:headers]: #{models_columns[1][:headers]}\"\n\n @sheet_results[key][:header] = [\"id\"] + normalized_header.compact\nlogger.debug \"Normalized header: key: #{key} #{@sheet_results[key][:header]}\"\n return true\n end",
"def verify_header_names(key, models_columns, header)\n normalized_header = []\n\n got_error = false\n header.each_with_index do |h, i|\n logger.debug \"verify header: #{h}\"\n if h == \"id\"\n error(cur_sheet_name, 1, \"Header column #{h} not allowed, update not supported yet\")\n next\n end\n\n if h.nil?\t# ignore empty header\n normalized_header[i] = nil\n next\n else\n normalized_header[i] = normalize_header(h)\n end\n\n # see if heading is an attribute name, pseudo attribute,\n # fk_finder, refrerence id or reference to one\n # if so, put it in the models_columns :headers hash with header index\n header_is_known = false\n show_header_in_results = true\n models_columns.each_with_index do |mc, ci|\n\n # check for ambiguous header name\n if mc[:dups].has_key?(normalized_header[i])\nlogger.debug \"verify_header: ci: #{ci} found ambiguous header: #{normalized_header[i]}\"\n dup_index = mc[:dups][normalized_header[i]]\nlogger.debug \"verify_header: ci: #{ci} dup_index: #{dup_index}\"\n next if dup_index.nil?\n if dup_index == i\n header_is_known = true\n mc[:headers] << [normalized_header[i], i] # 0 based index\nlogger.debug \"header #{h} i: #{i} ci: #{ci} is_ambiguous_model_column mc[:headers]: #{mc[:headers]}\"\n break\n end\n next\n end\n\n if mc[:allowed_cols].include?(normalized_header[i])\n header_is_known = true\n mc[:headers] << [normalized_header[i], i] # 0 based index\nlogger.debug \"header #{h} is_model_column mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_pseudo_attr(mc[:model], normalized_header[i])\n header_is_known = true\n mc[:headers] << [normalized_header[i], i]\nlogger.debug \"header #{h} is_model_pseudo_attr mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_fk_finder_header(normalized_header[i], mc)\n header_is_known = true\n mc[:headers] << [normalized_header[i], i]\nlogger.debug \"header #{h} is_fk_finder mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_ref_def_header(normalized_header[i], mc[:model])\n header_is_known = true\n show_header_in_results = false\n @sheet_results[key][:_refs][(mc[:model]).name] = normalized_header[i]\n @sheet_results[key][:_ref_ids][normalized_header[i]] = {}\n mc[:headers] << [normalized_header[i], i]\nlogger.debug \"header #{h} is_ref_def mc[:headers]: #{mc[:headers]}\"\n break\n end\n\n if is_ref_ref_header(normalized_header[i], mc)\n header_is_known = true\n mc[:headers] << [normalized_header[i], i]\nlogger.debug \"header #{h} is_ref_ref mc[:headers]: #{mc[:headers]}\"\n break\n end\n end\n if !show_header_in_results\n normalized_header.delete_at(i)\n end\n next if header_is_known\n\n # error if not recognized, but continue to gather all errors\n got_error = true\n error(cur_sheet_name, 1, \"Header name '#{h}' is not recognized for model(s) #{model_column_names(models_columns)}\")\n end\n return false if got_error\n\n#logger.debug \"mc[0][:headers]: #{models_columns[0][:headers]}\"\n#logger.debug \"mc[1][:headers]: #{models_columns[1][:headers]}\"\n\n @sheet_results[key][:header] = [\"id\"] + normalized_header.compact\n logger.debug \"Normalized header: key: #{key} #{@sheet_results[key][:header]}\"\n return true\nend",
"def resolve_amgiguous_headers(models_columns, raw_header)\n return if models_columns.size < 2\n m0_cols = models_columns[0][:allowed_cols] - [\"id\", \"updated_by\", \"created_at\", \"updated_at\"]\n m1_cols = models_columns[1][:allowed_cols] - [\"id\", \"updated_by\", \"created_at\", \"updated_at\"]\n dup_names = []\n m0_cols.each do |n1|\n m1_cols.each do |n2|\n if n1 == n2\n dup_names << n1\n end\n end\n end\n#logger.debug \"resolve_amgiguous_headers found dup_names: #{dup_names}\"\n return if dup_names.empty?\n # normalize all headers\n header = raw_header.map {|h| normalize_header(h) }\n dup_names.each do |dn|\n#logger.debug \"resolve_amgiguous_headers handle dup_name: #{dn}\"\n fi = li = nil\n # find first instance of the dup name in header\n header.each_with_index do |h, i|\n if dn == h\n fi = i\n break\n end\n end\n#logger.debug \"resolve_amgiguous_headers dup_name: #{dn} first index: #{fi}\"\n # next if the dup name is not used in the sheet\n next if fi.nil?\n # find last instance of the dup name in header\n header.reverse_each.with_index do |h, ri|\n if dn == h\n li = (header.size - 1) - ri\n break\n end\n end\n#logger.debug \"resolve_amgiguous_headers dup_name: #{dn} last index: #{li}\"\n if fi == li\n # one instance of dup name\n m1_no_dups = models_columns[1][:allowed_cols] - dup_names\n first_m1_index = nil\n header.each_with_index do |h, i|\n if m1_no_dups.include?(h)\n # we foud the first non-ambiguous header of 2nd model\n first_m1_index = i\n break\n end\n end\n if first_m1_index.nil? || fi < first_m1_index\n # assign to the 1st model\n#logger.debug \"resolve_amgiguous_headers dup_name: #{dn} assign to first\"\n models_columns[0][:dups][dn] = fi\n models_columns[1][:dups][dn] = nil\n else\n # assign to the 2nd model\n#logger.debug \"resolve_amgiguous_headers dup_name: #{dn} assign to second\"\n models_columns[0][:dups][dn] = nil\n models_columns[1][:dups][dn] = fi\n end\n else\n#logger.debug \"resolve_amgiguous_headers assign dup_name: #{dn} first index: #{fi} last index: #{li}\"\n # two instances of dup name\n models_columns[0][:dups][dn] = fi\n models_columns[1][:dups][dn] = li\n end\n end\n end",
"def resolve_ambiguous_headers(models_columns, raw_header)\n return if models_columns.size < 2\n m0_cols = models_columns[0][:allowed_cols] - [\"id\", \"updated_by\", \"created_at\", \"updated_at\"]\n m1_cols = models_columns[1][:allowed_cols] - [\"id\", \"updated_by\", \"created_at\", \"updated_at\"]\n dup_names = []\n m0_cols.each do |n1|\n m1_cols.each do |n2|\n if n1 == n2\n dup_names << n1\n end\n end\n end\n#logger.debug \"resolve_ambiguous_headers found dup_names: #{dup_names}\"\n return if dup_names.empty?\n# normalize all headers\n header = raw_header.map {|h| normalize_header(h) }\n dup_names.each do |dn|\n#logger.debug \"resolve_ambiguous_headers handle dup_name: #{dn}\"\n fi = li = nil\n # find first instance of the dup name in header\n header.each_with_index do |h, i|\n if dn == h\n fi = i\n break\n end\n end\n #logger.debug \"resolve_ambiguous_headers dup_name: #{dn} first index: #{fi}\"\n # next if the dup name is not used in the sheet\n next if fi.nil?\n # find last instance of the dup name in header\n header.reverse_each.with_index do |h, ri|\n if dn == h\n li = (header.size - 1) - ri\n break\n end\n end\n #logger.debug \"resolve_ambiguous_headers dup_name: #{dn} last index: #{li}\"\n if fi == li\n # one instance of dup name\n m1_no_dups = models_columns[1][:allowed_cols] - dup_names\n first_m1_index = nil\n header.each_with_index do |h, i|\n if m1_no_dups.include?(h)\n # we foud the first non-ambiguous header of 2nd model\n first_m1_index = i\n break\n end\n end\n if first_m1_index.nil? || fi < first_m1_index\n # assign to the 1st model\n #logger.debug \"resolve_ambiguous_headers dup_name: #{dn} assign to first\"\n models_columns[0][:dups][dn] = fi\n models_columns[1][:dups][dn] = nil\n else\n # assign to the 2nd model\n #logger.debug \"resolve_ambiguous_headers dup_name: #{dn} assign to second\"\n models_columns[0][:dups][dn] = nil\n models_columns[1][:dups][dn] = fi\n end\n else\n#logger.debug \"resolve_ambiguous_headers assign dup_name: #{dn} first index: #{fi} last index: #{li}\"\n# two instances of dup name\n models_columns[0][:dups][dn] = fi\n models_columns[1][:dups][dn] = li\n end\n end\n end",
"def indices_table_header( query_command )\n preferences = query_command.preferences\n if preferences.compare_areas?\n colspan = query_command.data_columns_count\n label_0 = preferences.selected_location_name( preferences.search_id( 0 ) )\n label_1 = preferences.selected_location_name( preferences.search_id( 1 ) )\n end\n\n capture do\n if preferences.compare_areas?\n concat content_tag( :colgroup, \"\", span: 1, class: \"column-date\" )\n concat content_tag( :colgroup, \"\", span: colspan, class: \"column-location column-location-1\" )\n concat content_tag( :colgroup, \"\", span: colspan, class: \"column-location column-location-2\" )\n end\n\n concat(\n content_tag( :thead ) do\n\n # location headings\n if preferences.compare_areas?\n concat(\n content_tag( :tr ) do\n content_tag( :th ) +\n content_tag( :th, label_0, colspan: colspan, class: \"text-center\" ) +\n content_tag( :th, label_1, colspan: colspan, class: \"text-center\" )\n end\n )\n end\n\n # column headings\n concat(\n content_tag( :tr ) do\n query_command.columns.each_with_index do |col, i|\n concat(\n content_tag( :th, class: (i > 0) ? \"text-right\" : \"text-center\",\n \"data-location\" => col[:location],\n \"data-type\" => col[:sType],\n \"data-aspect\" => col[:aspect]\n ) do\n col[:label]\n end\n )\n end\n end\n )\n end\n )\n end #/capture\n end",
"def header_cells_in_data_sheet_file\n schema.header_cells.select(&:present_in_sheet).sort_by(&:column_index)\n end",
"def ar_index_table_headers \n label_header= content_tag(:th, controller.ardata.labels[:label])\n \n # This will be used when adding the table rows.\n # it will contain, in the order in wich they are retrieved,\n # a true of false value depending on the presence of the label\n # for the table header. This means that a column can be disabled\n # simply by labeling it with an empty string (most usefull when the\n # label of the column comes from a method or a Proc that can enable/disable\n # the output given a set of conditions\n @display_current_ar_index_table_column= []\n \n headers= []\n \n controller.ardata.fields.for_index.each do |column, title|\n label= ar_get_index_label(title)\n \n if label && !label.strip.empty?\n headers << content_tag(:th, label) \n @display_current_ar_index_table_column << true\n else\n @display_current_ar_index_table_column << false\n end\n end\n \n colspan= ar_index_colspan\n \n \"<tr>\\n #{label_header}\" \\\n \"\\n #{headers.join(\"\\n \")}\" \\\n \"\\n #{colspan}\" \\\n \"\\n </tr>\"\n end",
"def get_ordered_headers\n headers = get_headers\n template_headers = get_template_headers\n ordered_headers = ['druid', 'sourceId']\n # Select only headers with values somewhere in the data\n template_headers.each {|th| ordered_headers << th if headers.include?(th)}\n ordered_headers\n end",
"def build_table_header\n names = column_names(data)\n build_md_row(output, names)\n build_md_row(output, alignment_strings(names))\n end",
"def sort_headers(columns)\n\t\tfront_headers = ['id']\n\t\tback_headers = ['created_at', 'updated_at']\n\t\texcluded_headers = []\n\n\t\tsorted = []\n\t\tfront = []\n\t\tback = []\n\t\texcluded = []\n\n\t\tcolumns.each do |column|\n\t\t\tif front_headers.include?(column.name)\n\t\t\t\tfront << column\n\t\t\telsif back_headers.include?(column.name)\n\t\t\t\tback << column\n\t\t\telsif excluded_headers.include?(column.name)\n\t\t\t\texcluded << column\n\t\t\telse\n\t\t\t\tsorted << column\n\t\t\tend\n\t\tend\n\t\tfront + sorted + back\n\tend",
"def merge_headers(head1, head2, sepr=\"\", open=\"\", close=\"\")\n merged_arr = head1.zip(head2) #merges 2 headers (arrays) together into a \"2D\" array\n \n merged_str = []\n #converts merged array into a string (with optional seperator and opening/closeing containers)\n merged_arr.each do |h1,h2|\n if (h1.empty? and h2.empty?)\n h3 = '\"\"' #empty double header cells should stay empty\n else\n h3 = h1 + sepr + open + h2 + close\n end\n merged_str << h3\n end\n return merged_str\n end",
"def merge_headers(head1, head2, sepr=\"\", open=\"\", close=\"\")\n merged_arr = head1.zip(head2) #merges 2 headers (arrays) together into a \"2D\" array\n\n merged_str = []\n #converts merged array into a string (with optional seperator and opening/closeing containers)\n merged_arr.each do |h1,h2|\n if (h1.empty? and h2.empty?)\n h3 = '\"\"' #empty double header cells should stay empty\n else\n h3 = h1 + sepr + open + h2 + close\n end\n merged_str << h3\n end\n return merged_str\nend",
"def table_headers\n raise NotImplementedError\n end",
"def check_duplicate_csv_headers(table)\n if table.headers.size != table.headers.uniq.size\n dups = table.headers.select{|e| table.headers.count(e) > 1 }\n Squib.logger.warn \"CSV duplicated the following column keys: #{dups.join(',')}\"\n end\n end",
"def check_indexes(table)\n indexes = table_indexes(table)\n\n indexes.permutation(2).each_with_object([]) do |(source_index, target_index), response|\n next unless source_index.columns.start_with?(target_index.columns)\n\n if target_index.unique\n response << {\n index: source_index,\n result: \"#{source_index.name} has column(s) on the right side of unique index (#{target_index.name}). You can drop if low cardinality\",\n }\n else\n response << {\n index: target_index,\n result: \"#{target_index.name} is a left-prefix of #{source_index.name}\",\n }\n end\n end\n end",
"def semanticize_table_headers!\n @document.tree.search('table tr:first td').each { |node| node.node_name = 'th' }\n end"
] | {
"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 _add_timeout_arg(a_func, timeout)\n proc do |request, **kwargs|\n kwargs[:timeout] = timeout\n a_func.call(request, **kwargs)\n end\n end",
"def timeout_timer\n timer = EventMachine::PeriodicTimer.new(1) do\n if get_idle_time.nil?\n timer.cancel\n elsif get_idle_time > config.timeout\n event(:connection_timeout, :msec => msec, :signature => @signature)\n timer.cancel\n close\n end\n end\n end",
"def on_timeout=(callback)\n @timeout_callback = callback\n end",
"def initialize(timeout=600)\n @holder = NameTimerHolder.new(timeout)\n end",
"def initialize(timeout=600)\n @holder = TimerHolder2.new(timeout)\n end",
"def add_timeout_arg(a_func, timeout, metadata)\n proc do |request, block|\n deadline = Time.now + timeout unless timeout.nil?\n op = a_func.call(request,\n deadline: deadline,\n metadata: metadata,\n return_op: true)\n res = op.execute\n block.call res, op if block\n res\n end\n end",
"def registerTimeout(timeout, met_sym_tocall, met_notifier)\n #p \"register timer for msec #{timeout}\"\n unless @timeout_cb[:locked]\n # register only one timeout at the same time\n @timeout_cb[:meth] = met_sym_tocall\n @timeout_cb[:notifier] = met_notifier\n @timeout_cb[:locked] = true\n getApp().addTimeout(timeout, method(:onTimeout))\n else\n #@corelogger.debug(\"registerTimeout on timeout pending, put it on the queue\")\n # store info about timeout in order to submit after a timeout\n @timeout_cb[:queue] << {:timeout => timeout, \n :meth => met_sym_tocall, \n :notifier => met_notifier, \n :started => Time.now\n }\n end\n end",
"def clear_timeout(listener)\n @timeout_listeners.delete listener\n end",
"def push_timable(ident, timeout, handler, persistent = true)\n @timer_polls.push(ident, handler, persistent, timeout)\n end",
"def set_timeout_source\n %Q|\n var setTimeout = function(cb, delay) {\n var timer = Components.classes[\"@mozilla.org/timer;1\"].createInstance(Components.interfaces.nsITimer);\n timer.initWithCallback({notify:cb}, delay, Components.interfaces.nsITimer.TYPE_ONE_SHOT);\n return timer;\n };\n |\n end",
"def timeout(seconds, &block)\n Timeout.timeout seconds, Pinglish::TooLong, &block\n end",
"def invite_timeout\n run_on_invite_timeout_cbs\n end",
"def timeout_after(time); end",
"def with_timeout(timeout)\n start_time = ::NATS::MonotonicTime.now\n yield\n end_time = ::NATS::MonotonicTime.now\n duration = end_time - start_time\n raise ::NATS::IO::Timeout.new(\"nats: timeout\") if duration > timeout\n end",
"def after_timeout=(block)\n register_hook(:after_timeout, block)\n end",
"def timeout=(timeout=:default)\n @timeout = TIMEOUTS.member?(timeout) ? TIMEOUTS[timeout] : timeout\n NOTIFICATION[:set_timeout].call @notification, @timeout\n end",
"def timeout(time, *args); end",
"def timeout_after (time)\n @timeout = time\n\n pool.timeout_for self, time\n\n self\n end"
] | {
"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, classification)
end
end; [classification, comparability]
end | [
"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_comparability_explore(e, k, classification)\r\n end\r\n end; [classification, comparability]\r\n end",
"def getGraphEdges(graph)\n edges = Hash.new\n graph.edges.each { |e|\n if @asymetric\n edges[e.source+e.target] = e\n else\n edges[e.source+e.target] = edges[e.target+e.source] = e\n end\n }\n edges\n end",
"def reachable\n # out = []\n # from = Hash.new\n # @vertices.each do |vk, is_up|\n # if is_up\n # out << \"#{vk}\"\n # if @edges_up[vk]\n # from[vk] = []\n # @edges_up[vk].each do |ek, up_too|\n # if up_too\n # from[vk] << \" #{ek}\"\n # end\n # end\n # end\n # end\n # end\n # out.sort!\n # out.each do |x|\n # puts x\n # from[x].sort!\n # from[x].each do |y|\n # puts y\n # end\n # end\n # end\n ind = []\n arr = []\n count = 0\n @vertices.each do |vk, is_up|\n if is_up\n ind << vk\n count += 1\n end\n end\n ind.sort!\n arr = Array.new(count) { Array.new(count) }\n ind.size.times do |y|\n ind.size.times do |x|\n if @edges_up[ind[y]].member?(ind[x])\n arr[y][x] = @edges_up[ind[y]].fetch(ind[x])\n end\n end\n end\n\n ind.size.times do |k|\n ind.size.times do |i|\n ind.size.times do |j|\n arr[i][j] = arr[i][j] or (arr[i][k] and arr[k][j])\n end\n end\n end\n\n ind.size.times do |y|\n puts ind[y]\n ind.size.times do |x|\n print \" \"\n puts ind[x]\n end\n end\n end",
"def calculate_needed_edges_to_form_tree (adjacency_hashmap)\r\n minimum_array = []\r\n minimum2_array = []\r\n test1 = adjacency_hashmap.values\r\n test2 = adjacency_hashmap.keys\r\n\r\n test1.each do |node|\r\n if !(adjacency_hashmap.keys.include?(node))\r\n minimum_array.push(node)\r\n end\r\n end\r\n test2.each do |node2|\r\n if !(adjacency_hashmap.values.include?(node2))\r\n minimum2_array.push(node2)\r\n end\r\n end\r\n return [minimum_array.uniq.length, minimum2_array.uniq.length].min()\r\nend",
"def build_adjacency_list(tg)\n result = Hash.new\n tg[0].each do |task|\n result[task] = Array.new\n tg[1].each do |edge|\n result[task] << edge if edge[0] == task[0] or edge[1] == task[0]\n end\n end\n return result\nend",
"def reachable(graph, v1, v2)\n hash = Hash.new {|h,k| h[k] = Array.new }\n\n graph.each {|x|\n hash[x[0]] << x[1]\n }\n\n visited = []\n queue = []\n\n queue = hash[v1]\n\n while queue.size > 0 do\n v = queue.shift\n\n if v == v2 then return true end\n\n visited << v\n hash[v].each {|x|\n if !visited.include?(x) && !queue.include?(x) then\n queue << x\n end\n }\n end\n\n return false\nend",
"def findCycle(graph)\n\t\tunusedEdges = Array.new\n\t\tadjacentList = Hash.new\n\t\tfor i in 0..graph.row_count-1\n\t\t\tadjacentList[i] = Array.new\n\t\t\tfor j in 0..graph.row_count-1\n\t\t\t\tif(graph.element(i,j) >= 1)\n\t\t\t\t\tadjacentList[i].push(j)\n\t\t\t\t\tunusedEdges.push([i,j])\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\t\n\t\t#Abort if the degree of the vertices is odd\n\t\tadjacentList.each do |i|\n\t\t\tif(i.length % 2 != 0)\n\t\t\t\tabort(\"Not Eulerian\")\n\t\t\tend\n\t\tend\n\n\t\treturn heir(adjacentList, Array.new).compact #remove any nil values by compacting the array\n\t\t\n\tend",
"def detect_cycle_in_graph(edges)\nend",
"def graphEdges(matrix)\n matrix.uniq.length == 1 ? 0 : matrix.uniq.length\nend",
"def find_cycles_in_graph\n state = {\n :number => 0, :index => {}, :lowlink => {}, :scc => [],\n :stack => [], :seen => {}\n }\n\n # we usually have a disconnected graph, must walk all possible roots\n vertices.each do |vertex|\n if ! state[:index][vertex] then\n tarjan vertex, state\n end\n end\n\n # To provide consistent results to the user, given that a hash is never\n # assured to return the same order, and given our graph processing is\n # based on hash tables, we need to sort the cycles internally, as well as\n # the set of cycles.\n #\n # Given we are in a failure state here, any extra cost is more or less\n # irrelevant compared to the cost of a fix - which is on a human\n # time-scale.\n state[:scc].select { |c| c.length > 1 }.map {|x| x.sort }.sort\n end",
"def init_graph()\n map = []\n temp_map = []\n\n \n (0..999).each do |x|\n temp_map = []\n (0..999).each do |y|\n if sum_ints(x, y) < 20\n temp_map << false\n else\n temp_map << true\n end\n end\n map[x] = temp_map\n \n end\n return map\n end",
"def twoDArray(m,n)\n arr = Hash.new\n for m in 0..m\n for n in 0..n\n if m.gcd(n) == 1\n arr[[m,n]] = true\n else\n arr[[m,n]] = false\n end\n end\n end\n\n for m in 0..m\n for n in 0..n\n if arr[[m,n]] == true\n puts \"#{m} :m and #{n} :n\"\n end\n end\n end\nend",
"def dfs\n visited = Hash.new(false)\n @v.each do |vertex| \n visited.merge(explore(vertex)) if !visited[vertex]\n end\n return visited\n end",
"def checkNode()\n source_set = []\n neighbor_set = []\n $networks.each do |s, nb|\n source_set << s\n nb[\"neighbors\"].each do |s_, dist|\n neighbor_set << s_\n end\n end\n source_set.sort!\n source_set.uniq!\n neighbor_set.sort!\n neighbor_set.uniq!\n return source_set == neighbor_set\nend",
"def has_nodes?\n @visited.keys.size < @nodes.keys.size ? true : false\n end",
"def has_cycle?(graph)\n visited = Hash.new\n\n graph.each do |vertex, _|\n visited[vertex] = Hash.new\n visited[vertex][:state] = \"not visited\"\n end\n\n graph.each do |vertex, _|\n unless visited[vertex][:state] == \"done\"\n result = dfs_visit(graph, vertex, visited)\n return true if result\n end\n end\n\n false\nend",
"def nodes_with_levels\n level = nodes_sorted.inject(Pazy::HashMap.new) do |h, v|\n h.with(v, 1 + (graph.pred(v).map { |w| h[w] }.compact.max || -1))\n end\n\n nodes_sorted.map { |v| [v, level[v], bottlenecks.include?(v)] }\n end",
"def some_edges_in_all_hamiltonian_cycles\n stack = DS::Stack.new\n result = EdgeSearchResult.new\n\n # As we are deleting edges, make a deep copy to start with\n g = copy\n\n # Fill up the stack, in reverse to ease testing\n g.vertices.to_a.reverse.each do |v|\n stack.push v\n end\n\n while v = stack.pop\n all_neighbours = g.neighbours(v)\n ham_neighbours = result.hamiltonian_neighbours(v)\n# p v\n# p all_neighbours\n# p ham_neighbours\n\n # If a vertex contains 1 or 0 total neighbours, then the graph cannot contain\n # any hamcycles (in contrast, degree 1 doesn't preclude hampaths).\n if all_neighbours.length < 2\n result.contains_hamcycle = false\n\n elsif all_neighbours.length == 2\n # If a vertex has degree 2 then both edges must be a part of the hamcycle\n all_neighbours.each do |n|\n unless result.edges_in_all.edge?(v,n)\n result.edges_in_all.add_edge(v,n)\n stack.push n #now need to re-evalute the neighbour, as its neighbourhood is changed\n end\n\n # if an edge be and must not be in all hamcycles, then the graph is not Hamiltonian.\n # Are there any concrete examples of this? Possibly.\n if result.edges_in_all[v].include?(n) and result.edges_in_none[v].include?(n)\n result.contains_hamcycle = false\n end\n end\n\n elsif ham_neighbours.length >= 2\n # There cannot be any further hamcycle edges from this vertex, so the rest of the edges\n # cannot be a part of _any_ hamcycle\n all_neighbours.each do |n|\n next if ham_neighbours.include?(n)\n\n result.edges_in_none.add_edge(v,n)\n g.delete_edge(v,n)\n stack.push n #reconsider the neighbour\n end\n\n else\n # Anything else that can be done cheaply?\n # Maybe edges that create non-Hamiltonian cycles when only considering edges\n # that are in all Hamiltonian cycles -> these cannot be in any hamcycle\n\n end\n #p stack\n end\n #p result\n\n return result\n end",
"def to_a(res = Identicon.res)\n\t\t#Distribute the hash over the dimensions\n\t\tret = []\n\t\thash = self.to_hash\n\n\t\t#Loop through x 0..res\n\t\t0.upto(res-1) do |x|\n\t\t\tx_partial = hash[x*((hash.length/res)-1)+x, hash.length/res]\n\n\t\t\tret[x] = []\n\n\t\t\t#Loop through y 0..res\n\t\t\t0.upto(res-1) do |y|\n\t\t\t\ty_partial = x_partial[y*((x_partial.length/res)-1)+y, x_partial.length/res]\n\n\t\t\t\tret[x][y] = []\n\n\t\t\t\t#Loop through z 0..res\n\t\t\t\t0.upto(res-1) do |z|\n\t\t\t\t\tz_partial = y_partial[z*((y_partial.length/res)-1)+z, y_partial.length/res]\n\n\t\t\t\t\tret[x][y][z] = (z_partial.hex > 7 ? true : false)\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\n\t\tret\n\tend"
] | {
"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, orient].to_oriented_segment)\n end\n end\n end\n g.adjacent_iterator do |oriented_segment, block|\n s = segment(oriented_segment.segment)\n o = oriented_segment.orient\n s.links[:from][o].each do |l|\n os = [segment(l.to), l.to_orient].to_oriented_segment\n block.call(os)\n end\n o = oriented_segment.invert_orient\n s.links[:to][o].each do |l|\n os = [segment(l.from), l.from_orient].to_oriented_segment\n block.call(os.invert_orient)\n end\n end\n g.directed = true\n end\n end",
"def to_undirected\n graph = NetworkX::Graph.new(@graph)\n @nodes.each { |node, node_attr| graph.add_node(node, node_attr) }\n @adj.each do |node_1, node_1_edges|\n node_1_edges.each do |node_2, node_1_node_2|\n edge_attrs = {}\n node_1_node_2.each { |_key, attrs| edge_attrs.merge!(attrs) }\n graph.add_edge(node_1, node_2, edge_attrs)\n end\n end\n graph\n end",
"def to_undirected\n new_graph = NetworkX::Graph.new(@graph)\n @nodes.each { |u, attrs| new_graph.add_node(u, attrs) }\n @adj.each do |u, edges|\n edges.each { |v, attrs| new_graph.add_edge(u, v, attrs) }\n end\n new_graph\n end",
"def to_undirected_graph(&proc)\n inject(UndirectedGraph.new()) do |ug,(a,targets)|\n targets.each do |(b,weight_a_b)|\n if !ug[a][b]\n weight_b_a = self[b][a]\n undw = proc.call(a,b,weight_a_b, weight_b_a)\n ug[a][b]=undw if undw\n end\n end\n ug\n end\n end",
"def to_undirected\n return self unless directed?\n AdjacencyGraph.new(Set, self)\n end",
"def flip_graph g\n fg = g.deep_copy\n fg.adj_list.each{|n|\n n.nbrs.reverse!\n n.edges.reverse!}\n return fg\n end",
"def adjacency_graph(opts={})\n implicit_graph(opts).to_adjacency\n end",
"def adjacency_graph(opts = {})\n implicit_graph(opts).to_adjacency\n end",
"def degrees_graph\n @degrees_graph ||= begin\n g = RDF::Graph.new\n mit_degrees.each do |acronym, description|\n uri = degree_prefix + acronym\n abbrev = acronym.chars.join('.') + '.'\n label = \"#{abbrev} #{description}\"\n g << [uri, RDF.type, RDF::VIVO.AcademicDegree]\n g << [uri, RDF::RDFS.label, label]\n g << [uri, RDF::SKOS.prefLabel, label]\n g << [uri, RDF::VIVO.abbreviation, abbrev]\n g << [uri, RDF::VIVO.abbreviation, acronym]\n end\n vivo_degree_labels.each do |label|\n abbrev = label.split.first\n acronym = abbrev.gsub(/\\W/,'')\n uri = degree_prefix + acronym\n g << [uri, RDF.type, RDF::VIVO.AcademicDegree]\n g << [uri, RDF::RDFS.label, label]\n g << [uri, RDF::SKOS.prefLabel, label]\n g << [uri, RDF::VIVO.abbreviation, abbrev]\n g << [uri, RDF::VIVO.abbreviation, acronym]\n end\n harvard_degrees.each do |degree|\n abbrev = degree.first\n acronym = abbrev.gsub(/\\W/,'')\n description_latin = degree[1]\n description_english = degree[2]\n label = \"#{abbrev} #{description_english}\"\n uri = degree_prefix + acronym\n g << [uri, RDF.type, RDF::VIVO.AcademicDegree]\n g << [uri, RDF::RDFS.label, label]\n g << [uri, RDF::SKOS.prefLabel, label]\n g << [uri, RDF::SKOS.altLabel, \"#{abbrev} #{description_latin}\"]\n g << [uri, RDF::VIVO.abbreviation, abbrev]\n g << [uri, RDF::VIVO.abbreviation, acronym]\n end\n g\n end\n end",
"def reverse\n reverseDiGraph = DiGraph.new\n @vertices.each {|x| adj(x).each { |y| reverseDiGraph.add_edge(y, x) } }\n reverseDiGraph\n end",
"def reversal\r\n result = self.class.new\r\n edges.inject(result) {|a,e| a << e.reverse}\r\n vertices.each { |v| result.add_vertex!(v) unless result.vertex?(v) }\r\n result\r\n end",
"def reversal\n result = self.class.new\n edges.inject(result) {|a,e| a << e.reverse}\n vertices.each { |v| result.add_vertex!(v) unless result.vertex?(v) }\n result\n end",
"def reverse\n g = Graph.new(@v)\n each.do { |e| g.add_edge(e.to, e.from) }\n return g\n end",
"def undirected\n if directed?\n @undirected = true\n self.to_list\n end\n end",
"def to_undirected(&edge_factory)\n edge_factory ||= Proc.new{ |e1, e2| UndirectedEdge.new(e1.from, e1.to) if e1 && e2 } \n\n edges = Set.new\n with_each_edge_and_inverse do |e, e_inverse|\n new_edge = edge_factory.call(e, e_inverse)\n edges.add(new_edge) if new_edge\n end\n\n UndirectedGraph.new.tap do |g|\n edges.each{ |e| g.add_edge(e) } \n end\n end",
"def oriented_nodes\n raise unless converged?\n seen_nodes = {}\n stack = DS::Stack.new\n initial_solution = @known_problems[@converging_oriented_node_settable][0]\n converging_onode = initial_solution.path[-1]\n stack.push converging_onode\n\n while onode = stack.pop\n settable = onode.to_settable\n next if seen_nodes.key?(settable)\n\n if block_given?\n if @is_reverse\n yield onode.reverse\n else\n yield onode\n end\n end\n\n seen_nodes[settable] = onode\n\n # queue neighbours for paths that don't contain the converging onode\n @known_problems[settable].each do |dpp|\n stack.push dpp.path[-2] unless dpp.path.length < 2 or dpp.path[0...-1].include? converging_onode\n end\n end\n\n return nil if block_given?\n return seen_nodes.values\n end",
"def get_transpose()\n transpose_graph = Graph.new(26)\n\n for i in 0..@number_of_vertices -1 do\n @adjacent_list[i].each do |x|\n transpose_graph.add_edge(x, i)\n end\n end\n\n transpose_graph\n end",
"def complete_directed (n)\n\t\t\ti1 = (1..n).to_a\n\t\t\tg = CityGraph.new\t\t\t\n\t\t\ti1.permutation(2).to_a.each{\n\t\t\t\t|edge|\n\t\t\t\tg.add_edge(edge[0], edge[1])\n\t\t\t}\t\n\t\t\treturn g\n\t\tend"
] | {
"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_hash[k] if @book_hash[k].blank?
}
@book_hash.each {|k,v|
@book_hash[k] = isbndb_hash[k] if @book_hash[k].blank?
}
@book_hash.each {|k,v|
@book_hash[k] = gb_hash[k] if @book_hash[k].blank?
}
if !object.nil? and object.respond_to? :from_hash
puts @book_hash.inspect
object.from_hash(@book_hash)
object
else
@book_hash
end
end | [
"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(\"http://bnb.data.bl.uk/sparql\") \n #build the SPARQL query\n query = add_parameters(query, { \"isbn\" => isbn })\n \n #execute the query and build JSON response \n results = sparql.query(query) \n response = { :isbn => isbn, :results => []}\n results.each do |result|\n response[:results] << { :title => result[:otherTitle], :isbn => result[:otherIsbn] }\n end \n return response \n end",
"def search_url\n \"http://books.google.com/books/feeds/volumes?q=ISBN#{ isbn }\"\n end",
"def get_book( book_id )\n response = if book_id.to_s.length >= 10\n Amazon::Ecs.item_lookup( book_id, :id_type => 'ISBN', :search_index => 'Books', \n :response_group => 'Large,Reviews,Similarities,AlternateVersions' )\n else\n Amazon::Ecs.item_lookup( book_id, :response_group => 'Large,Reviews,Similarities' )\n end\n response.items.each do |item|\n binding = item.get('ItemAttributes/Binding')\n next if binding.match(/Kindle/i)\n return Book.new( item )\n end\n return nil\n end",
"def book_by_title(title)\n\t\t\tresponse = request('/book/title', :title => title)\n\t\t\tHashie::Mash.new(response['book'])\n\t\tend",
"def isbn(id, options={})\n perform_lookup('isbn', id, options)\n end",
"def get_book( book_id )\n response = if book_id.to_s.length >= 10\n Amazon::Ecs.item_lookup( book_id, :id_type => 'ISBN', :search_index => 'Books', :response_group => 'Large,Reviews,Similarities' )\n else\n Amazon::Ecs.item_lookup( book_id, :response_group => 'Large,Reviews,Similarities' )\n end\n response.items.each do |item|\n binding = item.get('ItemAttributes/Binding')\n next if binding.match(/Kindle/i)\n return parse_item( item )\n end\n end",
"def link_7xx(link, hash, options={})\n options = {\n :isbn_field => \"number\",\n :issn_field => \"number\"\n }.merge(options)\n\n parts = extract_7xx_pieces(link.line.marc_field)\n\n if parts[:isbn]\n # phrase quoting is good for isbn and issn, becuase it allows\n # solr analyzers to normalize issn/isbn to work, even if there's\n # a space used in the issn or isbn.\n hash[:q] = '\"' + parts[:isbn] + '\"'\n hash[:search_field] = options[:isbn_field]\n elsif parts[:issn]\n hash[:q] = '\"' + parts[:issn] + '\"'\n hash[:search_field] = options[:issn_field]\n elsif parts[:author] || parts[:title]\n hash[:q] = \"\"\n hash[:q] << %|\"#{parts[:author].gsub('\"', '')}\" | if parts[:author]\n hash[:q] << %|\"#{parts[:title].gsub('\"', '')}\"| if parts[:title]\n else\n # no linking!\n hash = false\n end\n return hash\n end",
"def book(id)\n\t\t\tresponse = request('/book/show', :id => id)\n\t\t\tHashie::Mash.new(response['book'])\n\t\tend",
"def scrape_book_info(html)\n retval = {}\n html = restrict(html,\n /<div.+class\\s*=\\s*\"buying\".*?>\\s*<b/,\n %r{</div\\s*>})\n retval[:title] = scrape_title(html)\n retval[:authors] = scrape_authors(html)\n retval\n end",
"def initialize(book_hash)\n @num = book_hash[:num]\n @name = book_hash[:name]\n @author = book_hash[:author]\n @link = book_hash[:link]\n @@all << self \n end",
"def book_by_author(author)\n\t\t\tresponse = request('/book/author', :author => author)\n\t\t\tHashie::Mash.new(response['book'])\n\t\tend",
"def get_review_statistics_from_isbn(isbns, oauth = true)\n\t\t\t#isbns can be a single isbn or a string of isbns seperated by commas ex: \"111111111,2222222222,3333333333\"\n\t\t\toptions = {\"isbns\"=> isbns}\n\t\t\tif oauth\n\t\t\t\toptions.merge!(key: Goodreads.configuration[:api_key])\n\t\t\t\tdata = oauth_request(\"/book/review_counts.json\", options)\n\t\t\telse\n\t\t\t\tdata = request(\"/book/review_counts.json\", options)\n\t\t\tend\n\t\t\tHashie::Mash.new(data)\n\t\tend",
"def scrape_book_info(html)\n retval = {}\n html = restrict(html,\n /<div.+class\\s*=\\s*\"buying\".*?>\\s*<b/,\n %r{</div\\s*>})\n retval[:title] = scrape_title(html)\n retval[:authors] = scrape_authors(html)\n retval\nend",
"def isbn\n @isbn\n end",
"def book_info_goodreads_library\n client = Goodreads::Client.new(Goodreads.configuration)\n results = client.book_by_title(params[:q]) if (params[:t] == \"title\" || params[:t].blank?)\n results = client.book_by_isbn(params[:q]) if params[:t] == \"isbn\"\n return results\n end",
"def books_by_author(id, params={})\n params[:id] = id\n data = request('/author/list', params)\n book_list = data['author']['books']['book']\n\n books = []\n books = book_list.map {|b| Hashie::Mash.new(b)}\n\n Hashie::Mash.new({\n :start => data['author']['books']['start'].to_i,\n :end => data['author']['books']['end'].to_i,\n :total => data['author']['books']['total'].to_i,\n :books => books\n }) \n end",
"def book_info(book_title)\n for book in @books\n return book if book[:title] == book_title\n end\n return nil\n end"
] | {
"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 4096. :key_size:: The keysize of the cipher. Defaults to 256. :iv:: The Initial Vector (IV) to use with the cipher. Defaults to 19070547872603305. :hash:: The hash to use with the cipher. Defaults to SHA256. :key:: The key to use with the cipher. :password:: If :key is not given, :password can be given. The password will be hashed and used as the key. AESPipe.new(:mode => :encrypt, :password => 'pants') do |aes| aes.cipher do |cipher| aes.process_output(output_file) do |output| aes.process_input(input_file) do |text| output << cipher.update(text) end output << cipher.final end end end | 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(:hash,DEFAULT_HASH).to_s.downcase
@key = if options[:key]
options[:key].to_s
elsif (password = options[:password])
begin
Digest.const_get(@hash.upcase).hexdigest(password)
rescue RuntimeError => e
raise(InvalidHash,"invalid hash name #{@hash.dump}")
end
end
yield self if block_given?
end | [
"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 yield aes if block_given?\n return aes\n end",
"def decryption_cipher options, &block\n encryption_key_for(options) do |encryption_key|\n\n check_encryption_materials(:decrypt, encryption_key)\n\n location = options[:encryption_materials_location] ||\n config.s3_encryption_materials_location\n\n cipher =\n decryption_materials(location, options) do |envelope_key, envelope_iv|\n envelope_key, envelope_iv =\n decode_envelope_key(envelope_key, envelope_iv, encryption_key)\n get_aes_cipher(:decrypt, :CBC, envelope_key, envelope_iv)\n end\n\n remove_cse_options(options)\n\n yield(cipher)\n\n end\n end",
"def initialize(options, &block)\n super\n input_channel.register(self)\n @block = block if block\n end",
"def pipe(&block)\n cmds = Commands.new(mode: :pipe)\n cmds.instance_eval(&block)\n self.!(cmds.to_a)\n end",
"def create_cipher(klass, options, value)\n options = options.is_a?(Proc) ? options.call(self) : options.dup\n\n # Only use the contextual information for this plugin's ciphers\n klass.parent == EncryptedAttributes ? klass.new(value, options) : klass.new(options)\n end",
"def crypto(&block)\n @crypto = Crypto::Configuration.new(&block) if block_given?\n @crypto\n end",
"def do_aes(key_binary_p, iv_binary_p, input_binary_p, output_binary_p,\n response_length_p, status_p, decrypt: false, mode: :CBC)\n key = Binary.from_pointer(key_binary_p).to_s\n iv = Binary.from_pointer(iv_binary_p).to_s\n input = Binary.from_pointer(input_binary_p).to_s\n\n write_binary_string_and_set_status(output_binary_p, status_p) do\n output = Hooks.aes(key, iv, input, decrypt: decrypt, mode: mode)\n response_length_p.write_int(output.bytesize)\n\n output\n end\n end",
"def from_block\n options = new\n dsl = ExecutionOptionsDSL.new(options)\n yield dsl\n options\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 encrypt_with\n log!\n prepare\n\n if mode_options.empty?\n raise Error, \"Encryption could not be performed for mode '#{mode}'\"\n end\n\n yield \"#{utility(:gpg)} #{base_options} #{mode_options}\", \".gpg\"\n ensure\n cleanup\n end",
"def encrypt_with\n log!\n yield \"#{utility(:openssl)} #{options}\", \".enc\"\n end",
"def aes_ecb_internal(mode, buffer, key)\n raise 'Buffer must be composed of 16-byte chunks' unless (buffer.size % 16).zero?\n cipher = OpenSSL::Cipher.new('AES-128-ECB')\n cipher.send(mode)\n cipher.key = key.pack('C*')\n cipher.padding = 0 # decryption will otherwise fail\n result = cipher.update(buffer.pack('C*')) + cipher.final\n result.unpack('C*')\nend",
"def initialize(options = {})\n @options = merge_defaults(options)\n @options[:encryptor] = HipaaCrypt::Encryptor if @options[:encryptor] == self.class\n @encryptors = build_encryptors\n end",
"def initialize_cipher_for(mode)\n @cipher.send mode\n @cipher.key = @config[:key]\n @cipher.iv = @config[:iv]\n end",
"def initialize(options = {}, &block)\n options ||= {}\n @options = {\n host: options[:host] || 'localhost',\n port: options[:port] || 22,\n user: options[:user],\n password: options[:password],\n prompt: (options[:prompt].to_s.strip == '') ? '~~#' : options[:prompt],\n silence_wait: (options[:silence_wait] || 5),\n replace_cr: options[:replace_cr].to_s,\n retrieve_exit_code: options[:retrieve_exit_code].nil? ? true : options[:retrieve_exit_code],\n on_non_zero_exit_code: options[:on_non_zero_exit_code] ? options[:on_non_zero_exit_code].to_s.to_sym : :ignore,\n filter_password: options[:filter_password].nil? ? true : options[:filter_password],\n }\n\n raise ArgumentError.new('Missing block.') unless block_given?\n raise ArgumentError.new('Missing host.') if @options[:host].to_s.strip == ''\n raise ArgumentError.new('Missing user.') if @options[:user].to_s.strip == ''\n raise ArgumentError.new('Missing password.') if @options[:password].to_s.strip == ''\n raise ArgumentError.new('Missing prompt.') if @options[:prompt].to_s.strip == ''\n raise ArgumentError.new('Invalid option for on_non_zero_exit_code.') unless [:ignore, :raise_error].include?(@options[:on_non_zero_exit_code])\n\n @options[:prompt] = @options[:prompt]\n .gsub('!', '#')\n .gsub('$', '#')\n .gsub('\\\\', '.')\n .gsub('/', '.')\n .gsub('\"', '-')\n .gsub('\\'', '-')\n\n executed = false\n\n @last_exit_code = 0\n @sftp = nil\n Net::SSH.start(\n @options[:host],\n @options[:user],\n password: @options[:password],\n port: @options[:port],\n non_interactive: true,\n ) do |ssh|\n @ssh = ssh\n ssh.open_channel do |ssh_channel|\n ssh_channel.request_pty do |pty_channel, pty_success|\n raise FailedToRequestPTY.new('Failed to request PTY.') unless pty_success\n\n pty_channel.send_channel_request('shell') do |_, shell_success|\n raise FailedToStartShell.new('Failed to start shell.') unless shell_success\n\n # cache the channel pointer and start buffering the input.\n @channel = pty_channel\n buffer_input\n\n # give the shell a chance to catch up and initialize fully.\n sleep 0.25\n\n # set the shell prompt so that we can determine when processes end.\n # does not work with background processes since we are looking for\n # the shell to send us this when it is ready for more input.\n # a background process can easily bury the prompt and then we are stuck in a loop.\n exec \"PS1=\\\"#{@options[:prompt]}\\\"\"\n\n block.call(self)\n\n executed = true\n\n # send the exit command and remove the channel pointer.\n quit\n @channel = nil\n end\n end\n ssh_channel.wait\n end\n end\n\n @ssh = nil\n\n if @sftp\n @sftp.session.close\n @sftp = nil\n end\n\n # remove the cached user and password.\n options.delete(:user)\n options.delete(:password)\n\n raise FailedToExecute.new('Failed to execute shell.') unless executed\n end",
"def initialize *args, &block\n @pipes = {}\n @command = EM::SystemCommand::Builder.new *args\n\n @execution_proc = block\n end",
"def initialize_cipher_for(mode)\n @cipher.send mode\n @cipher.key = @config['key']\n @cipher.iv = @config['iv']\n end",
"def initialize(options = {})\n @options = {:mode => :lines, :no_buffer => false}.merge(options)\n\n logger.info \"Initializing with options: #{@options.inspect}\"\n\n if @options[:mode] == :chars\n @reader = proc {|s| s.getc }\n else\n @reader = proc {|s| s.gets }\n end\n\n @mutex = Mutex.new\n reset\n end",
"def protecting_encrypted_data(&block)\n with_encryption_context encryptor: ActiveRecord::Encryption::EncryptingOnlyEncryptor.new, frozen_encryption: true, &block\n end"
] | {
"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?
return aes
end | [
"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_cipher(mode)\n create_cipher_simple(mode)\n end",
"def create_cipher(klass, options, value)\n options = options.is_a?(Proc) ? options.call(self) : options.dup\n\n # Only use the contextual information for this plugin's ciphers\n klass.parent == EncryptedAttributes ? klass.new(value, options) : klass.new(options)\n end",
"def new_cipher(direction, password, salt)\n cipher = OpenSSL::Cipher::Cipher.new(CIPHER_TYPE)\n direction == :encrypt ? cipher.encrypt : cipher.decrypt\n cipher.key = encrypt_key(password, salt)\n cipher\n end",
"def new_cipher(direction, passwd, options = {})\n check_platform_can_encrypt!\n cipher = OpenSSL::Cipher::Cipher.new(CIPHER_TYPE)\n case direction\n when :encrypt\n cipher.encrypt\n when :decrypt\n cipher.decrypt\n else\n raise \"Bad cipher direction #{direction}\"\n end\n cipher.key = encrypt_key(passwd, options)\n cipher\n end",
"def get( name,\n iv=nil, key=nil,\n shared=nil, hash=nil,\n digester=nil,\n encrypt=false )\n # begin\n ossl_name = @cipher_map.fetch( name ) do\n raise CipherNotFound, name\n end\n\n return @identity_cipher if ossl_name == \"none\"\n\n cipher = OpenSSL::Cipher::Cipher.new( ossl_name )\n cipher.send( encrypt ? :encrypt : :decrypt )\n\n cipher.padding = 0\n cipher.iv = make_key( cipher.iv_len, iv, shared, hash, digester )\n cipher.key = make_key( cipher.key_len, key, shared, hash, digester )\n\n return cipher\n end",
"def with_cipher\n return yield(init_cipher) unless cipher_reuse_enabled?\n\n with_reusable_cipher do |reusable_cipher|\n yield reusable_cipher\n end\n end",
"def crypto(&block)\n @crypto = Crypto::Configuration.new(&block) if block_given?\n @crypto\n end",
"def decryption_cipher options, &block\n encryption_key_for(options) do |encryption_key|\n\n check_encryption_materials(:decrypt, encryption_key)\n\n location = options[:encryption_materials_location] ||\n config.s3_encryption_materials_location\n\n cipher =\n decryption_materials(location, options) do |envelope_key, envelope_iv|\n envelope_key, envelope_iv =\n decode_envelope_key(envelope_key, envelope_iv, encryption_key)\n get_aes_cipher(:decrypt, :CBC, envelope_key, envelope_iv)\n end\n\n remove_cse_options(options)\n\n yield(cipher)\n\n end\n end",
"def get_local_cipher_obj\n r = Aws::Kms.new('kyc', 'admin').decrypt(@user_extended_detail.kyc_salt)\n raise r unless r.success?\n LocalCipher.new(r.data[:plaintext])\n end",
"def p_cipher(algorithm)\n ::OpenSSL::Cipher.new(algorithm)\n end",
"def initialize_cipher_for(mode)\n @cipher.send mode\n @cipher.key = @config[:key]\n @cipher.iv = @config[:iv]\n end",
"def initialize(options={},&block)\n @mode = options.fetch(:mode,:encrypt).to_sym\n @block_size = options.fetch(:block_size,DEFAULT_BLOCK_SIZE).to_i\n @key_size = options.fetch(:key_size,DEFAULT_KEY_SIZE).to_i\n @iv = options.fetch(:iv,DEFAULT_IV).to_s\n @hash = options.fetch(:hash,DEFAULT_HASH).to_s.downcase\n @key = if options[:key]\n options[:key].to_s\n elsif (password = options[:password])\n begin\n Digest.const_get(@hash.upcase).hexdigest(password)\n rescue RuntimeError => e\n raise(InvalidHash,\"invalid hash name #{@hash.dump}\")\n end\n end\n\n yield self if block_given?\n end",
"def encrypt_with(name, &block)\n @encryptors << Backup::Encryptor.const_get(\n last_constant(name)\n ).new(&block)\n end",
"def find_cipher(*args)\n fail ArgumentError, 'Unknown algorithm ' + algorithm unless args[0] == 'http://www.w3.org/2001/04/xmlenc#aes256-cbc'\n\n cipher = ::OpenSSL::Cipher.new('AES-256-CBC')\n cipher.decrypt\n cipher.padding = 0\n cipher.key = find_cipher_key(cipher, *args[1..4])\n cipher.iv = args[5]\n\n cipher\n end",
"def initialize_cipher_for(mode)\n @cipher.send mode\n @cipher.key = @config['key']\n @cipher.iv = @config['iv']\n end",
"def initialize(raw_passphrase, cipher = \"aes-256-cbc\")\n @encrypt_cipher = OpenSSL::Cipher::Cipher.new(cipher)\n @decrypt_cipher = OpenSSL::Cipher::Cipher.new(cipher)\n @key = Digest::SHA1.hexdigest(raw_passphrase)\n end",
"def cipher\n @cipher ||= SymmetricEncryption.cipher(version)\n end"
] | {
"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 return nil if(block >= @file_size)\n return nil if(block < 0)\n file_handle = File.open(@filename,'rb')\n file_handle.pos = block\n @previous_block_read = file_handle.pos\n data = file_handle.read(@@BLOCK_SIZE)\n @last_block_read = file_handle.pos\n Rula.log(Logger::DEBUG,\"Read #{data.length} bytes\",self)\n @file_eof = file_handle.eof\n return data\n ensure \n file_handle.close() unless file_handle.nil?\n end",
"def handle_block(block_info) # :nodoc:\n if block_info.type == CONTROL_BLOCK\n read_control_block\n elsif block_info.type == DATA_BLOCK\n if !declared_stream?(block_info.index)\n Pocolog.warn \"found data block for stream #{block_info.index} but this stream has never been declared, seems Logfile is Corrupted. Skipping...\"\n end\n elsif block_info.type == STREAM_BLOCK\n read_stream_declaration\n end\n block_info.type\n end",
"def read(input)\n opts[:read_block].call(input)\n end",
"def pass_file_to_block(filename)\n File.open(filename, \"r\") do |infile|\n while (line = infile.gets)\n puts \"#{counter}: #{line}\"\n counter = counter + 1\n end\n end\n end",
"def io(input = nil, output = nil, &block)\n orig_stdin, orig_stdout = $stdin, $stdout\n $stdin = File.new(input) if input\n $stdout = File.new(output, 'r+') if output\n return unless block\n\n yield\n $stdin, $stdout = orig_stdin, orig_stdout\n reset_io\n end",
"def read_block\n decompress_block(f)\n end",
"def run(stream = nil, &block)\n unless stream\n # No stream given\n to_return = true\n stream = StringIO.new(\"\")\n end\n # Creates the pipe for communicating with the block.\n rd,wr = IO.pipe\n # # Creates a process for executing the block.\n # pid = fork\n # if pid then\n # # This is the parent: waits for the block execution result.\n # # No need to write on the pipe. close it.\n # wr.close\n # # Read the result of the process and send it to stream\n # until rd.eof?\n # stream << rd.read\n # end\n # # No more need of rd.\n # rd.close\n # # Wait the end of the child process\n # Process.wait(pid)\n # # Where there a trouble?\n # unless $?.exited? then\n # # pid did not exit, internal error.\n # raise \"*Internal error*: safer process #{pid} did not exit.\"\n # end\n # if $?.exitstatus !=0 then\n # # Reconstruct the exception from the stream, the exit\n # # status is the number of line to use.\n # e0 = Marshal.load( stream.string.each_line.\n # to_a[-$?.exitstatus..-1].join )\n # # Then resend the eception encapsulated into another one\n # # telling the safer process failed.\n # begin\n # raise e0\n # rescue Exception => e1\n # raise SaferException.new(\"*Error*: exception occured in safer process #{pid}.\")\n # end\n # end\n # else\n # # This is the child: enter in safe mode and execute the block.\n # # No need to write on the pipe. close it.\n # rd.close\n # # Secure.\n # secure\n # # Execute the block.\n # begin\n # block.call(wr)\n # rescue Exception => e\n # # The exception is serialized and passed to the main process\n # # through the pipe.\n # e = Marshal.dump(e)\n # wr << \"\\n\" << e \n # # The exit status is the number of line of the serialized\n # # exception.\n # exit!(e.each_line.count)\n # end\n # # No more need of wr.\n # wr.close\n # # End the process without any error.\n # exit!(0)\n # end\n # \n # # Is there a string to return?\n # if to_return then\n # return stream.string\n # else\n # return nil\n # end\n\n # Secure.\n secure\n trouble = nil\n # Execute the block.\n begin\n block.call(wr)\n rescue Exception => e\n trouble = e\n end\n # No more need of wr.\n wr.close\n\n # Unsecure and process the result.\n unsecure\n # Read the result of the process and send it to stream\n until rd.eof?\n stream << rd.read\n end\n # No more need of rd.\n rd.close\n if trouble then\n begin\n raise trouble\n rescue Exception => e1\n raise SaferException.new(\"*Error*: exception occured in safe mode.\")\n end\n end\n \n # Is there a string to return?\n if to_return then\n return stream.string\n else\n return nil\n end\n end",
"def block\n (@blocks ||= Array.new) << Block.new\n @in_block = @blocks.last\n yield\n @in_block = nil\n end",
"def each(&block)\n @file.rewind\n @file.each do | line |\n parse(line).do_with_line(&block)\n end\n self\n end",
"def read_block_file(blockfile, snp_list)\n\n letters = [\"N\",\"A\",\"C\",\"G\",\"T\"]\n\n begin\n File.open(blockfile) do |file|\n while line = file.gets\n if line =~ /BLOCK/\n line.chomp!\n pieces = line.split\n pieces = pieces[3..pieces.length-1]\n integers = Array.new\n pieces.each do|piece|\n integers << piece.to_i\n end\n \n newblock = Block.new(integers)\n line = file.gets\n \n # read haplotype frequency and block genotypes\n total_frequency = 0.0\n while line and line !~ /Multiallelic/ \n line.chomp!\n pieces = line.split\n genotypes = pieces[0].split('')\n letter_genos = []\n # convert to letters from numbers (1-4)\n genotypes.each do |g|\n g = letters[g.to_i]\n letter_genos << g\n end\n \n # frequency will be the second element\n frequency = pieces[1]\n # remove parentheses\n frequency.delete!(\"(\")\n frequency.delete!(\")\")\n\n frequency = frequency.to_f\n \n newblock.haplotypes << Haplotype.new(letter_genos, frequency.to_f)\n line = file.gets\n end\n snp_list.add_new_block(newblock)\n end\n end\n\n end\n rescue StandardError => e\n puts e\n exit(1)\n end\n\n end",
"def open(file, &blk)\n encoding = file_encoding(file)\n mode = encoding.nil? ? \"r\" : \"rb:#{encoding}\"\n File.open(file, \"#{mode}\") do |f|\n while line = f.gets\n line = line.nil? ? nil : cook_line(line.encode(@encoding))\n blk.call(line)\n end\n end\n end",
"def each_block(rewind = true, with_prologue = true)\n\t self.rewind if rewind\n\t while !eof?\n\t\tio = self.rio\n\t\tif @next_block_pos == 0 && with_prologue\n\t\t read_prologue\n\t\telse\n\t\t io.seek(@next_block_pos)\n\t\tend\n\n\t\t@data = nil\n\t\t@data_header.updated = false\n\n if !read_block_header\n next_io\n next\n end\n\n\t\tyield(@block_info)\n\t end\n\trescue EOFError\n\tend",
"def set_read_file(&block)\n @read_proc = block\n end",
"def consume_raw stream_method=:common\n raise ArgumentError, \"Block required, non given\" unless block_given?\n if stream_method == :common\n read_stream do |data|\n yield(data)\n end\n elsif stream_method == :io\n read_io_stream do |data|\n yield(data)\n end\n elsif stream_method == :pty\n read_pty_stream do |data|\n yield(data)\n end\n else \n raise ArgumentError, \"Undefined stream method #{stream_method}\"\n end\n end",
"def input_handler\n STDIN.read.split(\"\\n\").each do |line|\n process_line(line)\n end\n end",
"def consume stream_method=:common\n raise ArgumentError, \"Block required, non given\" unless block_given?\n if stream_method == :common\n read_stream do |data|\n yield(process_entries(data))\n end\n elsif stream_method == :io\n read_io_stream do |data|\n yield(process_entries([data]))\n end\n elsif stream_method == :pty\n read_pty_stream do |data|\n yield(process_entries([data]))\n end\n else \n raise ArgumentError, \"Undefined stream method #{stream_method}\"\n end\n end",
"def process_block(node)\n node\n end",
"def each_chunk stream\n while !stream.eof?\n yield read_chunk stream\n end\n end"
] | {
"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_instances(app_master: true, app: true, util: %w[resque redis]) Select all instances (same as the method instances): select_instances(all: true) See instances_by_role for a simpler interface. | 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 then val
when inst.name then true
when nil, '' then [nil, ''].include?(inst.name)
when Array then val.include?(inst.name)
else false
end
end
end | [
"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 instance.tags.fetch('role', '').split(',').include? role\n end\n end\n end",
"def instances_for_role(role, state = \"running\")\n instances_for_filter(\"tag:role\", role, state)\n end",
"def instances\n instance_ids = ey_instances(@cloud_info.env_name)\n if instance_ids.empty?\n instances = []\n else\n group_id = aws_group_for_instance_id(instance_ids.first)\n instances = instances_in_group(group_id)\n instances\n end\n end",
"def find_instances(query = @argv.join(' '), print_output = true)\n query = query.join(' ') if query.is_a? Array\n\n if query.start_with?('i-') # amazon instance ids\n find_args = [\"--filter\", \"Name=instance-id,Values=\\\"#{query.split.join(',')}\\\"\"]\n elsif query.start_with?(\"ip-\") or query.start_with?(\"domU-\") # aws private dns\n find_args = [\"--filter\", \"Name=private-dns-name,Values=\\\"#{query}*\\\"\"] # trailing * to match .ec2.internal\n elsif query.start_with?(\"10.\") # aws private ip\n find_args = [\"--filter\", \"Name=private-ip-address,Values=\\\"#{query}\\\"\"]\n elsif query =~ /^[0-9]+\\./ # aws public ip\n find_args = [\"--filter\", \"Name=ip-address,Values=\\\"#{query}\\\"\"]\n elsif query.start_with?(\"ec2-\") # aws private ip\n find_args = [\"--filter\", \"Name=dns-name,Values=\\\"#{query}\\\"\"]\n elsif query.start_with?(\"--filters\")\n find_args = query\n elsif config[:group]\n find_args = [\"--filter\", \"Name=group-name,Values=\\\"#{query}\\\"\"]\n else\n # all else fails, check for names with that substring\n find_args = [\"--filter\", \"Name=tag:Name,Values=\\\"*#{query}*\\\"\"]\n end\n\n find_command = \"#{aws_cli} ec2 describe-instances #{find_args.join(' ')}\"\n debug \"finding with command '#{find_command}'\"\n result = JSON.parse(`#{find_command}`)\n\n # reservations can have several instances each\n instances = result[\"Reservations\"].map do |r|\n r[\"Instances\"]\n end.flatten.select do |instance|\n instance[\"State\"][\"Name\"] == \"running\"\n end.map do |instance|\n instance\n end\n\n\n # put the first hostname we found in the mac clipboard\n if print_output\n puts \"\\nFound (#{instances.size}) instances:\"\n instances.each do |instance|\n puts \"#{instance[\"PrivateIpAddress\"]} - #{instance[\"InstanceId\"]}\"\n end\n if instances.any?\n puts \"\\n\\nSingle line output for cssh into #{instances.size} hosts:\"\n puts instances.map{|instance| \"#{instance[\"PrivateIpAddress\"]}\"}.join\n\n first = instances.first\n IO.popen(\"pbcopy\", \"r+\" ){|p| p.print first[\"PrivateIpAddress\"] }\n puts \"\\n\\nPasted the first hostname '#{first[\"PrivateIpAddress\"]}' - (#{first[\"InstanceId\"]}) into the clipboard.\\n\\n\"\n\n end\n end\n\n instances.map{|instance| \"#{instance[\"PrivateIpAddress\"]}\"}\n end",
"def instances(name)\n filter = {name: 'tag:aws:cloudformation:stack-name', values: [name]}\n paginate(:reservations) do |token|\n client.describe_instances(filters: [filter], next_token: token)\n end.map(&:instances).flatten\n end",
"def list_instances()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end",
"def list_instances_detail()\n response = dbreq(\"GET\", dbmgmthost, \"#{dbmgmtpath}/instances/detail\", dbmgmtport, dbmgmtscheme)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n instances = CloudDB.symbolize_keys(JSON.parse(response.body)[\"instances\"])\n return instances\n end",
"def auto_scaling_instances(group)\n auto_scaling.describe_auto_scaling_instances.map(&:auto_scaling_instances).flatten.select do |instance|\n instance.auto_scaling_group_name == group\n end\nend",
"def where(options = {})\n filters = {}\n\n filters[\"vpc-id\"] = options.delete(:vpc_id) if options.has_key?(:vpc_id)\n filters[\"tag:Name\"] = options.delete(:name) if options.has_key?(:name)\n filters[\"instance-ids\"] = options.delete(:ids) if options.has_key?(:ids)\n filters[\"subnet-id\"] = options.delete(:subnet_id) if options.has_key?(:subnet_id)\n filters[\"tag:Role\"] = options.delete(:role) if options.has_key?(:role)\n filters[\"tag:Environment\"] = options.delete(:environment) if options.has_key?(:environment)\n\n if options.any?\n raise ArgumentError, \"Unknown filters '#{options.keys.join(\", \")}'!\"\n end\n\n api.servers.all(filters).map {|server| new(server) }\n end",
"def list_of_instances(keyp=nil)\n tmp_key = (keyp ? keyp : nil)\n \n unless @describe_instances\n tmpInstanceList = remote_base.describe_instances(options).select {|a| a if (tmp_key.nil? || tmp_key.empty? ? true : a[:keypair] == tmp_key) }\n has_master = !tmpInstanceList.select {|a| a[:name] == \"master\" }.empty? \n if has_master\n @describe_instances = tmpInstanceList\n else\n @id = 0\n running = select_from_instances_on_status(/running/, tmpInstanceList)\n pending = select_from_instances_on_status(/pending/, tmpInstanceList)\n terminated = select_from_instances_on_status(/shutting/, tmpInstanceList)\n \n running = running.map do |inst|\n inst[:name] = (@id == 0 ? \"master\" : \"node#{@id}\")\n @id += 1\n inst\n end.sort_by {|a| a[:index] }\n \n @describe_instances = [running, pending, terminated].flatten\n end\n end\n @describe_instances\n end",
"def list_instances token: nil\n execute do\n instances.list_instances(\n project_path,\n page_token: token\n )\n end\n end",
"def instances(*options)\n options = options.to_options_hash\n \n ls = @node.exec(\"ls /proc/net/ipt_CLUSTERIP/\")\n return [] if !ls || ls =~ /No such file or directory/\n \n ips = ls.split\n clusterips = []\n ips.each do |ip|\n clusterip = self.instance(:ip => ip)\n clusterips << clusterip\n end\n \n return clusterips\n end",
"def describe_instances(optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'DescribeInstances'\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :instance_ids\n\t\t\targs[:query]['InstanceIds'] = optional[:instance_ids]\n\t\tend\n\t\tif optional.key? :instance_status\n\t\t\traise ArgumentError, 'instance_status must be Available|Changing|Creating|Unavailable' unless 'Available|Changing|Creating|Unavailable'.split('|').include? optional[:instance_status]\n\t\t\targs[:query]['InstanceStatus'] = optional[:instance_status]\n\t\tend\n\t\tif optional.key? :network_type\n\t\t\traise ArgumentError, 'network_type must be CLASSIC|VPC' unless 'CLASSIC|VPC'.split('|').include? optional[:network_type]\n\t\t\targs[:query]['NetworkType'] = optional[:network_type]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :page_number\n\t\t\traise ArgumentError, 'page_number must be equal or greater than 1' unless optional[:page_number] < 1\n\t\t\targs[:query]['PageNumber'] = optional[:page_number]\n\t\tend\n\t\tif optional.key? :page_size\n\t\t\traise ArgumentError, 'page_size must be equal or greater than 1' unless optional[:page_size] < 1\n\t\t\traise ArgumentError, 'page_size must be equal or less than 50' unless optional[:page_size] > 50\n\t\t\targs[:query]['PageSize'] = optional[:page_size]\n\t\tend\n\t\tif optional.key? :private_ip_addresses\n\t\t\targs[:query]['PrivateIpAddresses'] = optional[:private_ip_addresses]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :v_switch_id\n\t\t\targs[:query]['VSwitchId'] = optional[:v_switch_id]\n\t\tend\n\t\tif optional.key? :vpc_id\n\t\t\targs[:query]['VpcId'] = optional[:vpc_id]\n\t\tend\n\t\tself.run(args)\n\tend",
"def instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving active instances\"\n fetch_instances\n end",
"def describe_auto_scaling_instances(options = {})\n if instance_ids = options.delete('InstanceIds')\n options.merge!(AWS.indexed_param('InstanceIds.member.%d', [*instance_ids]))\n end\n request({\n 'Action' => 'DescribeAutoScalingInstances',\n :parser => Fog::Parsers::AWS::AutoScaling::DescribeAutoScalingInstances.new\n }.merge!(options))\n end",
"def active_instances\n Egi::Fedcloud::Vmhound::Log.info \"[#{self.class}] Retrieving running instances\"\n fetch_instances ['ACTIVE']\n end",
"def list_instances token: nil\n instances.list_instances parent: project_path, page_token: token\n end",
"def app_instances(name)\n require_login\n raise CloudFoundry::Client::Exception::BadParams, \"Name cannot be blank\" if name.nil? || name.empty?\n get(\"#{CloudFoundry::Client::APPS_PATH}/#{name}/instances\")\n end"
] | {
"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 true, false then val\n when inst.name then true\n when nil, '' then [nil, ''].include?(inst.name)\n when Array then val.include?(inst.name)\n else false\n end\n end\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 instance.tags.fetch('role', '').split(',').include? role\n end\n end\n end",
"def instances_for_role(role, state = \"running\")\n instances_for_filter(\"tag:role\", role, state)\n end",
"def filter_instances\n suites.product(platforms).select do |suite, platform|\n if !suite.includes.empty?\n suite.includes.include?(platform.name)\n elsif !suite.excludes.empty?\n !suite.excludes.include?(platform.name)\n else\n true\n end\n end\n end",
"def selected_virtual_machines\n case\n when config[:all] && config[:exclude]\n VirtualMachine.select { |vm| !given_virtual_machines.include?(vm) }\n when config[:all]\n VirtualMachine.all\n else\n given_virtual_machines\n end\n end",
"def select_app_role(app_role = {})\n apps_in_page = roles_sections.last.app_name\n roles = roles_sections.last.app_role\n app_role.each do |app, role|\n apps_in_page.each_with_index do |apps_roles, index|\n if apps_roles.text==app\n raise \"Role:#{role} found in the page!\" unless roles.at(index).text.include?(role)\n roles.at(index).select(role)\n break\n end\n end\n end\n end",
"def find query=nil\n return @server_apps if query.nil? || query == :all\n\n @server_apps.select do |sa|\n next unless [*query[:user]].include? sa.shell.user if query[:user]\n next unless [*query[:host]].include? sa.shell.host if query[:host]\n\n next unless sa.has_roles?(query[:role], true) if query[:role]\n\n true\n end\n end",
"def role_select\n @@Roles.list\n end",
"def selectors\n find_related_frbr_objects( :is_selected_by, :which_roles?) \n end",
"def find_host_with_role role\n if (defined? options) && options[:masterless]\n find_at_most_one role\n else\n find_only_one role\n end\n end",
"def select_from_instances_on_status(status=/running/, list=[])\n list.select {|a| a[:status] =~ status}\n end",
"def serversForCapRoles(roles)\n find_servers(:roles => roles).collect { |x| x.host }\nend",
"def select_from_instances_on_status(status=/running/, list=[])\n list.select {|a| a[:status] =~ status}\n end",
"def instances\n # Qubell public API is too enterprise for just getting list of instances\n # by application ID. Actually there is no method for this yet.\n # So, store ID of organization in Application class and to get a list of\n # instances we init new organization class, get all environments in this\n # organization, get all instances in this environment and finally\n # filter them by application.\n # Like in one russian fairytail: \"his death is at the end of the needle,\n # that needle is in the egg, then egg is in a duck, that duck is in a\n # hare, the hare is in the trunk, and the trunk stands on a high oak\"\n Qubell::Resources::Organization.new(id: @organization)\n .environments.map(&:instances)\n .flatten.select do |instance|\n instance.instance_of_app?(self)\n end\n end",
"def where(options = {})\n filters = {}\n\n filters[\"vpc-id\"] = options.delete(:vpc_id) if options.has_key?(:vpc_id)\n filters[\"tag:Name\"] = options.delete(:name) if options.has_key?(:name)\n filters[\"instance-ids\"] = options.delete(:ids) if options.has_key?(:ids)\n filters[\"subnet-id\"] = options.delete(:subnet_id) if options.has_key?(:subnet_id)\n filters[\"tag:Role\"] = options.delete(:role) if options.has_key?(:role)\n filters[\"tag:Environment\"] = options.delete(:environment) if options.has_key?(:environment)\n\n if options.any?\n raise ArgumentError, \"Unknown filters '#{options.keys.join(\", \")}'!\"\n end\n\n api.servers.all(filters).map {|server| new(server) }\n end",
"def get_nodes_by_role(role, includeme=true, options={})\n options = {\n :search_string => role,\n :include_me => includeme,\n :order => [:role],\n :safe_deref => nil,\n :current_node => nil,\n :one_or_all => :all\n }.merge(options)\n opsit_search(options)\n end",
"def find_roles *roles\n role_model.where(:name => roles.flatten)\n end",
"def filtered_instances(regexp)\n result = begin\n @config.instances.get(regexp) ||\n @config.instances.get_all(/#{regexp}/)\n rescue RegexpError => e\n die \"Invalid Ruby regular expression, \" \\\n \"you may need to single quote the argument. \" \\\n \"Please try again or consult http://rubular.com/ (#{e.message})\"\n end\n result = Array(result)\n\n if result.empty?\n die \"No instances for regex `#{regexp}', try running `kitchen list'\"\n else\n result\n end\n end",
"def find_selected_elements(options, show_non_public = false)\n public_condition = show_non_public ? nil : ' AND elements.public = 1'\n if !options[:except].blank?\n condition = [\"elements.name NOT IN (?)#{public_condition}\", options[:except]]\n elsif !options[:only].blank?\n condition = [\"elements.name IN (?)#{public_condition}\", options[:only]]\n else\n condition = show_non_public.nil? ? nil : {:public => true}\n end\n return self.elements.find(:all, :conditions => condition, :limit => options[:count], :order => options[:random].blank? ? nil : \"RAND()\")\n end"
] | {
"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 MUST be either "app" or "util". No other value is acceptable. The "name" parameter can be anything, but it only applies to utility instances. Note also that if you add a util instance, you must specify a name. This method will raise if you don't. | 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[:name]
name = opts[:name].gsub(/\s+/, '')
end
if opts[:role] == 'util'
unless name && name.length > 0
raise InvalidInstanceName, "When specifying a util instance you must also specify a name."
end
end
request = { "role" => opts[:role], "name" => opts[:name] }
request['snapshot_id'] = opts[:snapshot_id] if opts.key?(:snapshot_id)
request['instance_size'] = opts[:instance_size] if opts.key?(:instance_size)
# We know opts[:role] is right, name can be passed straight to the API.
# Return the response body for error output, logging, etc.
return api.post("/environments/#{id}/add_instances", :request => request)
end | [
"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_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n remaining_instance_count = register_response.instances.size\n puts \"Added #{instance.hostname} to ELB #{name}. Attached instances: #{remaining_instance_count}\".light_blue\n _wait_for_instance_health_check(instance)\n end",
"def create \n\n # Find the user\n current_user ||= User.find_by_remember_token(cookies[:remember_token])\n \n # Get information from form\n image = params[:instance][:image]\n instanceType = params[:instance][:instanceType]\n sshKeys = params[:instance][:sshKeys]\n\n # Update weights\n success = updateWeight(current_user, instanceType, \"add\")\n\n if success\n # Create the new instance in AWS\n cloud = Cloud.new(\"/apps/local/ttgt-aws/conf/AWS.conf\")\n cloudInstance = cloud.createInstance(image, instanceType, sshKeys)\n cloudID = cloudInstance.id\n cloudIP = nil\n \n # Wait for amazon to assign the ip address to the instance\n while cloudIP.nil?\n cloudIP = cloudInstance.ip_address\n sleep(1)\n end\n \n # Save the instance information in the database\n @instance = current_user.instances.build(params[:instance].merge(:instanceID => cloudID, :ip => cloudIP))\n if @instance.save\n flash[:success] = \"Instance Created!\"\n redirect_to \"/users/#{current_user.id}\"\n else\n render 'new'\n end\n end\n end",
"def add_service_instance\n @app.service_instances << ServiceInstance.find(params[:service_instance_id])\n respond_with(:api, :v1, @app)\n end",
"def environment_add(envname, attributes)\n envname = envname.intern\n # assert !@environments.key? envname\n @environments[envname] = Environment.new(envname, attributes)\n end",
"def create_instance project:, zone:, instance_name:,\n machine_type: \"n2-standard-2\",\n source_image: \"projects/debian-cloud/global/images/family/debian-10\",\n network_name: \"global/networks/default\"\n # Initialize client that will be used to send requests. This client only needs to be created\n # once, and can be reused for multiple requests.\n client = ::Google::Cloud::Compute::V1::Instances::Rest::Client.new\n\n # Construct the instance object.\n # It can be either a hash or ::Google::Cloud::Compute::V1::Instance instance.\n instance = {\n name: instance_name,\n machine_type: \"zones/#{zone}/machineTypes/#{machine_type}\",\n # Instance creation requires at least one persistent disk.\n disks: [{\n auto_delete: true,\n boot: true,\n type: :PERSISTENT,\n initialize_params: {\n source_image: source_image,\n disk_size_gb: 10\n }\n }],\n network_interfaces: [{ name: network_name }]\n }\n\n # Prepare a request to create the instance in the specified project and zone.\n request = { project: project, zone: zone, instance_resource: instance }\n\n puts \"Creating the #{instance_name} instance in #{zone}...\"\n begin\n # Send the insert request.\n operation = client.insert request\n # Wait for the create operation to complete.\n operation = wait_until_done operation: operation\n\n if operation.error?\n warn \"Error during creation:\", operation.error\n else\n compute_operation = operation.operation\n warn \"Warning during creation:\", compute_operation.warnings unless compute_operation.warnings.empty?\n puts \"Instance #{instance_name} created.\"\n end\n rescue ::Google::Cloud::Error => e\n warn \"Exception during creation:\", e\n end\nend",
"def create\n\n return unless APP[:app][:steps][:ec2]\n\n instance = image.run_instance( \n :key_name => props[:instance][:key_name],\n :security_groups => sec_group,\n :instance_type => props[:instance_type],\n )\n instance\n end",
"def add(body)\n if expired?(@begin_time)\n @auth = get_auth(@api_key)\n end\n #body['alias'] = body['alias'] || 'MachineName'\n #key_string = get_keystring(auth)\n #body['keystring'] = get_keystring(auth)\n #body['keystring'] = 'DV4BSDG44D8TQAD97A3D'\n Log.debug \"===============================\"\n Log.debug \"#{@base_url}#{@add_url}\"\n Log.debug body.to_json\n Log.debug header\n Log.debug \"===============================\"\n machine = RestClient.post \"#{@base_url}#{@add_url}\", body.to_json, header\n Log.debug('add 1 machine')\n machine_id = JSON.parse(machine.body)['items'][0]['data']['id']\n end",
"def add_environment(env)\n @environments << env\n end",
"def start_instance\n\n return unless APP[:app][:steps][:ec2]\n\n instance = case\n when self.create? \n self.create\n when self.reuse?\n list = self.find_id\n if list \n self.instances[list[:id]] \n else \n self.create\n end\n when props[:instance][:id]\n self.instances[props[:instance][:id]]\n else\n abort \"Asking to re-use exising instance, but instance ID is not provided in the configuration\"\n end\n \n abort \"Instance ID not known\" if instance.nil?\n sleep 1 until instance.status != :pending\n\n instance.add_tag('Name', :value => props[:instance][:name])\n\n instance.start unless instance.running?\n sleep 1 until instance.running?\n instance\n end",
"def create_instance(options = {})\n body = Hash.new\n (body[:flavor_ref] = options[:flavor_ref]) or raise CloudDB::Exception::MissingArgument, \"Must provide a flavor to create an instance\"\n (body[:size] = options[:size]) or raise CloudDB::Exception::MissingArgument, \"Must provide a size to create an instance\"\n body[:name].upcase! if body[:name]\n response = dbreq(\"POST\",lbmgmthost,\"#{lbmgmtpath}/instances\",lbmgmtport,lbmgmtscheme,{},body.to_json)\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n body = JSON.parse(response.body)['instance']\n return get_instance(body[\"id\"])\n end",
"def create\n @instance_name = InstanceName.new(params[:instance_name])\n\n respond_to do |format|\n if @instance_name.save\n flash[:notice] = 'InstanceName was successfully created.'\n format.html { redirect_to(@instance_name) }\n format.xml { render :xml => @instance_name, :status => :created, :location => @instance_name }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @instance_name.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create_instances(instances, optional={})\n\t\targs = self.class.new_params\n\t\targs[:query]['Action'] = 'CreateInstances'\n\t\targs[:query]['Instances'] = instances\n\t\targs[:region] = optional[:_region] if (optional.key? :_region)\n\t\tif optional.key? :_method\n\t\t\traise ArgumentError, '_method must be GET|POST' unless 'GET|POST'.split('|').include? optional[:_method]\n\t\t\targs[:method] = optional[:_method]\n\t\tend\n\t\tif optional.key? :_scheme\n\t\t\traise ArgumentError, '_scheme must be http|https' unless 'http|https'.split('|').include? optional[:_scheme]\n\t\t\targs[:scheme] = optional[:_scheme]\n\t\tend\n\t\tif optional.key? :auto_pay\n\t\t\targs[:query]['AutoPay'] = optional[:auto_pay]\n\t\tend\n\t\tif optional.key? :owner_account\n\t\t\targs[:query]['OwnerAccount'] = optional[:owner_account]\n\t\tend\n\t\tif optional.key? :owner_id\n\t\t\targs[:query]['OwnerId'] = optional[:owner_id]\n\t\tend\n\t\tif optional.key? :resource_owner_account\n\t\t\targs[:query]['ResourceOwnerAccount'] = optional[:resource_owner_account]\n\t\tend\n\t\tif optional.key? :resource_owner_id\n\t\t\targs[:query]['ResourceOwnerId'] = optional[:resource_owner_id]\n\t\tend\n\t\tif optional.key? :token\n\t\t\targs[:query]['Token'] = optional[:token]\n\t\tend\n\t\tself.run(args)\n\tend",
"def create_instance(image_id, opts={}, &block)\n name = opts[:name]\n realm_id = opts[:realm]\n user_data = opts[:user_data]\n key_name = opts[:key_name]\n security_group = opts[:security_group]\n\n params = {}\n ( params[:realm_id] = realm_id ) if realm_id\n ( params[:name] = name ) if name\n ( params[:user_data] = user_data ) if user_data\n ( params[:keyname] = key_name ) if key_name\n ( params[:security_group] = security_group) if security_group\n\n if opts[:hardware_profile].is_a?(String)\n params[:hwp_id] = opts[:hardware_profile]\n elsif opts[:hardware_profile].is_a?(Hash)\n opts[:hardware_profile].each do |k,v|\n params[:\"hwp_#{k}\"] = v\n end\n end\n\n params[:image_id] = image_id\n instance = nil\n\n request(:post, entry_points[:instances], {}, params) do |response|\n c = DeltaCloud.define_class(\"Instance\")\n instance = base_object(c, :instance, response)\n yield instance if block_given?\n end\n\n return instance\n end",
"def add_instances request_pb, options:, &block\n uri = \"/compute/v1/projects/#{request_pb.project}/zones/#{request_pb.zone}/instanceGroups/#{request_pb.instance_group}/addInstances\"\n body = request_pb.instance_groups_add_instances_request_resource.to_json\n\n response = @client_stub.make_post_request(\n uri: uri,\n body: body,\n options: options,\n )\n\n result = ::Google::Cloud::Compute::V1::Operation.decode_json response.body, ignore_unknown_fields: true\n\n yield result, response if block_given?\n\n result\n end",
"def create_instance(name, tasks, priority = 1, comment = nil)\n instance = Instance.new\n instance.name = name\n instance.priority = priority\n instance.comment = comment if comment\n if tasks.instance_of? Array\n instance.tasks = tasks\n else\n instance.tasks = [tasks]\n end\n\n res = ODPS.conn.post do |req|\n req.url \"projects/#{ODPS.current_project}/instances\"\n req.headers['Content-Type'] = 'application/xml'\n req.body = instance.serialize [String, ['Job'], 'Name', name],\n [String, ['Job'], 'Comment', comment],\n [String, ['Job'], 'Priority', priority],\n [Array, ['Job'], 'Tasks', instance.tasks.map { |t| REXML::Document.new t.to_xml }]\n end\n\n if res.status == 201\n instance.location = res['Location']\n instance\n end\n end",
"def create\n @instance = Instance.new(params[:instance])\n\n respond_to do |format|\n if @instance.save\n format.html { redirect_to \"/instances/#{@instance.instanceid}/show\", notice: \"Instance was successfully created.\" }\n format.json { render json: @instance, status: :created, location: @instance }\n else\n format.html { render action: \"new\" }\n format.json { render json: @instance.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @instance = current_account.instances.new(params[:instance])\n\n respond_to do |format|\n if @instance.save\n flash[:notice] = 'Instance was successfully created.'\n format.html { redirect_to(@instance) }\n format.xml { render :xml => @instance, :status => :created, :location => @instance }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @instance.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def clone args\n\t\tif args.size < 2\n\t\t\traise RuntimeError, \"Must specify an exsting instance name and a name for the new instance.\"\n\t\tend\n\n\t\texisting_name = args[0]\n\t\tnew_instance_name = args[1]\n\t\tinstance = $all_instances.get_instance existing_name\n\t\tif instance.nil?\n\t\t\tputs \"Error, bad instance returned.\"\n\t\t\texit 1\n\t\tend\n\t\tsettings = {\n\t\t\t\"zone\" => instance[:aws_availability_zone],\n\t\t\t\"access_groups\" => instance[:aws_groups],\n\t\t\t\"ami\" => instance[:aws_image_id],\n\t\t\t\"key\" => instance[:ssh_key_name]\n\t\t}\n\t\t$all_instances.create(new_instance_name, settings)\n\t\tputs \"Created #{new_instance_name} as a clone of #{existing_name}.\"\n\tend"
] | {
"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) Warnings/caveats: + The API is responsible for actually removing this instance. All this does is send an appropriate request to the API. + You should look carefully at the API response JSON to see whether or not the API accepted or rejected your request. If it accepted the request, that instance should be removed as soon as possible. + Note that this is a client that talks to an API, which talks to an API, which talks to an API. Ultimately the IaaS provider API has the final say on whether or not to remove an instance, so a failure there can definitely affect how things work at every point down the line. + If the instance you pass in doesn't exist in the live cloud environment you're working on, the status should be rejected and thus the instance won't be removed (because that instance isn't there). This is important to keep in mind for scheduled/auto scaling; if for some reason the automatically added instance is removed before a "scale down" event that you might trigger, you may wind up with an unknown/unexpected number of instances in your environment. + Only works for app/util instances. Raises an error if you pass one that isn't valid. | 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 InvalidInstanceRole, "Removing instances is only supported for app, util instances"
end
# Check to be sure that instance is actually provisioned
# TODO: Rip out the amazon_id stuff when we have IaaS agnosticism nailed down
unless instance.amazon_id && instance.provisioned?
raise InstanceNotProvisioned, "Instance is not provisioned or is in unusual state."
end
response = api.post("/environments/#{id}/remove_instances", :request => {
:provisioned_id => instance.amazon_id,
:role => instance.role,
:name => instance.name
})
# Reset instances so they are fresh if they are requested again.
@instances = nil
# Return the response.
return response
end | [
"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(\"#{@path}/remove_instances\",request)\n end",
"def destroy instance_id\n params = {\n \"InstanceId.1\" => instance_id\n }\n\n response = @client.action \"TerminateInstances\", params\n\n Response::Return.new response.body['TerminateInstancesResponse']\n end",
"def remove_instance(instance)\n deregister_response = client.deregister_instances_from_load_balancer(load_balancer_name: name,\n instances: [{instance_id: instance.ec2_instance_id}])\n remaining_instance_count = deregister_response.instances.size\n puts \"Removed #{instance.hostname} from ELB #{name}. Remaining instances: #{remaining_instance_count}\".light_blue\n _wait_for_connection_draining\n end",
"def delete_instance instance_id\n instances.delete_instance name: instance_path(instance_id)\n end",
"def remove_status\n EngineyardAPI::API.get(\"#{@path}/remove_instances\")\n end",
"def remove_instance_from_provisioner(provisioner_name, key, value)\n instances_for_provisioner(provisioner_name).delete_if do |instance|\n instance[key] == value\n end\n end",
"def delete_pvm_instance(instance_id)\n delete(\"cloud-instances/#{guid}/pvm-instances/#{instance_id}\")\n end",
"def instance_delete_req(name)\n { :api_method => @compute.instances.delete,\n :parameters => { 'project' => @options[:gce_project], 'zone' => DEFAULT_ZONE_NAME, 'instance' => name } }\n end",
"def destroy\n @ec2_instance.destroy\n respond_to do |format|\n format.html { redirect_to ec2_instances_url, notice: 'Ec2 instance was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def stop instance_id\n params = {\n \"InstanceId.1\" => instance_id\n }\n\n response = @client.action \"StartInstances\", params\n\n Response::Return.new response.body\n end",
"def destroy\n @instance_name = InstanceName.find(params[:id])\n @instance_name.destroy\n\n respond_to do |format|\n format.html { redirect_to(instance_names_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n ensure_service!\n service.delete_instance instance_id\n true\n end",
"def stop_pvm_instance(instance_id)\n post(\n \"cloud-instances/#{guid}/pvm-instances/#{instance_id}/action\",\n {\"action\" => \"stop\"}.to_json\n )\n end",
"def aws_terminate_instance( iprops, delete_attached_storage = false, do_wait = true )\n ec2 = AWS::EC2.new.regions[ iprops[ :region ] ]\n inst = ec2.instances[ iprops[ :id ] ]\n unless inst.exists?\n raise \"Instance #{iprops[:id]} does not exist in #{iprops[:region]}\"\n end\n\n ebs_volumes = []\n if delete_attached_storage\n ebs_volumes = inst.block_devices.map do |dev|\n ebs = dev[ :ebs ]\n\n if ebs && !ebs[:delete_on_termination] &&\n ( dev[:device_name] =~ /dh\\d+$/ ||\n dev[:device_name] =~ /sd[f-p]$/ )\n ebs[ :volume_id ]\n end\n end.compact\n end\n\n inst.terminate\n if do_wait || !ebs_volumes.empty?\n wait_until( \"termination of #{inst.id}\", 2.0 ) { inst.status == :terminated }\n end\n\n ebs_volumes = ebs_volumes.map do |vid|\n volume = ec2.volumes[ vid ]\n if volume.exists?\n volume\n else\n puts \"WARN: #{volume} doesn't exist\"\n nil\n end\n end.compact\n\n ebs_volumes.each do |vol|\n wait_until( \"deletion of vol #{vol.id}\" ) do\n vol.status == :available || vol.status == :deleted\n end\n vol.delete if vol.status == :available\n end\n\n end",
"def destroy\n @instance = Instance.find(params[:id])\n @instance.destroy\n\n respond_to do |format|\n format.html { redirect_to(instances_url) }\n format.xml { head :ok }\n end\n end",
"def destroy_ami(response, payload, parameters)\n ami_id = payload[:physical_resource_id].split(PHYSICAL_ID_JOINER).last\n begin\n compute_api(parameters[:region]).deregister_image(ami_id)\n rescue ::Fog::Compute::AWS::Error => e\n warn \"Failed to remove AMI: #{e.class}: #{e}\"\n response['Reason'] = \"Failed to remove AMI resource: #{e}. Ignoring.\"\n rescue => e\n error \"Unexpected error removing AMI: #{e.class}: #{e}\"\n response['Status'] = 'FAILED'\n response['Reason'] = e.message\n end\n true\n end",
"def destroy\n @physical_instance = PhysicalInstance.find(params[:id])\n @physical_instance.destroy\n\n respond_to do |format|\n format.html { redirect_to physical_instances_url }\n format.json { head :no_content }\n end\n end",
"def destroy_instance(deploy_id)\n raise \"You should implement this method.\"\n end",
"def destroy\n @instance = Instance.find(params[:id])\n @instance.destroy\n\n respond_to do |format|\n format.html { redirect_to instances_url }\n format.json { head :no_content }\n end\n end"
] | {
"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 end",
"def last_updated_time\n data[:last_updated_time]\n end",
"def last_updated\n self.dig_for_datetime(\"companySummary\", \"lastUpdateOn\")\n end",
"def last_update(*) end",
"def last_sensor_reading\n render json: Sensor.all.map { |s| s.weather_datum.last }\n end",
"def last_update\n Time.parse(@record.SystemModstamp)\n end",
"def weather\n @connection.response[\"weather\"].first\n end",
"def last_updated_at\n if File.file?(update_timestamp_path)\n timestamp = File.read(update_timestamp_path)\n Time.at(timestamp.strip.to_i)\n end\n end",
"def last_updated\n self.dig_for_datetime(\"listingSummary\", \"lastUpdateOn\")\n end",
"def last_update_date_time\n return @last_update_date_time\n end",
"def last_updated\n time = self.updated_at\n if time < Time.now - (3600 * 24)\n time.strftime(\"%b %-d, %Y\")\n else\n time.strftime(\"%l:%M %p\")\n end\n end",
"def last_update\n convert_time(@channel.pubDate)\n end",
"def last_update\n Time._load(index_time_dbm_file['last']) rescue \"none\"\n end",
"def get_metric_last_update_at(_metric)\n raise \"Not implemented\"\n end",
"def latest_ust\n self.delta_pack[\"latestUST\"]\n end"
] | {
"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_rights\n public_xml_doc.xpath('//rightsMetadata/access[@type=\"read\"]/machine/*').map(&:name)\n end",
"def permits_read_access_for(user)\n permits_access_for(user, :r)\n end",
"def _read_check(op, obj, actor, context = nil)\n obj.commentable.permission?(actor, Fl::Framework::Access::Grants::READ, context)\n end",
"def list_users_who_can_read\n User.find(:all, :order => \"name\").select{|user| user.can_read(self.id)}\n end",
"def device_ownership\n return @device_ownership\n end",
"def read_level\n level_name = @options[:read_level] || @options[:user_level] || :none\n Spontaneous::Permissions[level_name]\n end",
"def reseller_allow_read(permission)\n return reseller_right(permission) > 0\n end",
"def resource_access\n return @resource_access\n end",
"def is_readable_by( user )\n if self.is_public || self.accepts_role?( :owner, user ) \n return true\n else\n return( self.accepts_role? :reader, user ) \n end#end if\n end",
"def access\n return @access\n end",
"def device_access_mode(dev_name)\n st = File.stat(File.join('/', dev_name))\n st.mode & 07777\n\n rescue Errno::ENOENT\n 0644\n end",
"def authorise_read\n authorize! :read, Note\n end",
"def access\n\t\treturn self.access_level\n\tend",
"def has_access?(type)\n case type\n when :read\n read_write.include? 'r'\n when :write\n read_write.include? 'w'\n when :read_write, :write_read\n read_write == 'rw'\n end\n end",
"def is_read_only\n return @is_read_only\n end"
] | {
"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_genre }\n end\n end",
"def index\n render json: Genre.all\n end",
"def index\n @pictures = @album.pictures #JRD111115\n\n respond_to do |format|\n format.html #index.html.erb\n format.json { render json: @pictures}\n end\n end",
"def new\n @album_genre = AlbumGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album_genre }\n end\n end",
"def get_album album_id\n get(\"/albums/#{album_id}\")\n end",
"def show\n @book_genre = BookGenre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @book_genre }\n end\n end",
"def show\n @genre_band = GenreBand.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @genre_band }\n end\n end",
"def show\n @picture = @album.pictures.find(params[:id]) #JRD111115\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @picture}\n end\n end",
"def index\n @book_genres = BookGenre.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @book_genres }\n end\n end",
"def show\n # Pull the selected photo album.\n @photo_album = PhotoAlbum.find(params[:id])\n\n respond_to do |format|\n format.json do\n render json: @photo_album\n end\n end\n end",
"def get_album_images(hash)\n response = make_request(\"GET\", \"album/#{hash}/images\")\n return response\nend",
"def show\n @sub_genre = SubGenre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sub_genre }\n end\n end",
"def get_genres\n \tRails.cache.fetch(\"tmdb/genres_list\", expires_in: 24.hours) do\n \t\taction = \"genre/movie/list\"\n \t\targument = \"&language=en-US\"\n\t\t\tresponse = call_api(action, argument)\n\t\t\t@result = Hash.new\n\t\t\tresponse[\"genres\"].each do |genre|\n\t\t\t\t@result[genre[\"id\"]] = genre[\"name\"]\n\t\t\tend\n\t\t\t@result\n\t\tend\n\tend",
"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 format.xml { head :ok }\n end \n end",
"def show\n @genre_type = GenreType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @genre_type }\n end\n end",
"def image_list\n @images = Picture.where(album_id: params[:album_id])\n respond_to do |format|\n format.json { render json: @images.to_json(methods: [:path])}\n end\n end",
"def show_by_genre\n\t\t@genre = Genre.find(params[:id])\n\t\t@painting = @genre.paintings\n\t\trender json: { painting: @painting },:include => {:user => {:only => :username }, :genre => {:only => :genretitle }}\n\tend"
] | {
"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",
"def new\n @song_genre = SongGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @song_genre }\n end\n end",
"def create\n @album_genre = AlbumGenre.new(params[:album_genre])\n\n respond_to do |format|\n if @album_genre.save\n format.html { redirect_to @album_genre, notice: 'Album genre was successfully created.' }\n format.json { render json: @album_genre, status: :created, location: @album_genre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @album_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @albumm = Albumm.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @albumm }\n end\n end",
"def new\n\n @album = @user.albums.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album }\n end\n end",
"def new\n @album = current_user.albums.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album }\n end\n end",
"def new\n @genre_type = GenreType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @genre_type }\n end\n end",
"def new\n @book_genre = BookGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @book_genre }\n end\n end",
"def new\n @photoalbum = Photoalbum.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @photoalbum }\n end\n end",
"def new\n @gen = Gen.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gen }\n end\n end",
"def new\n @genre_band = GenreBand.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @genre_band }\n end\n end",
"def new\n @subgenre = Subgenre.new\n @genres = Genre.all\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @subgenre }\n end\n end",
"def new\n @user_album = UserAlbum.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @user_album }\n end\n end",
"def new\n @album2photo = Album2photo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album2photo }\n end\n end",
"def new\n @genotype = Genotype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @genotype }\n end\n end",
"def create\n @song_genre = SongGenre.new(params[:song_genre])\n\n respond_to do |format|\n if @song_genre.save\n format.html { redirect_to @song_genre, notice: 'Song genre was successfully created.' }\n format.json { render json: @song_genre, status: :created, location: @song_genre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @song_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @sub_genre = SubGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sub_genre }\n end\n end",
"def new\n @album = Album.find_by_slug(params[:album_id])\n @album_item = AlbumItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album_item }\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 }
else
format.html { render action: "new" }
format.json { render json: @album_genre.errors, status: :unprocessable_entity }
end
end
end | [
"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 format.xml { head :ok }\n end \n end",
"def create_albums\n url = 'https://stg-resque.hakuapp.com/albums.json'\n uri = URI(url)\n response = Net::HTTP.get(uri)\n albums = JSON.parse(response)\n\n albums.each do |album|\n Album.create!(album.except('id'))\n end\nend",
"def index\n @genres = Genre.all\n\n render json: @genres\n end",
"def create\n @genres_song = GenresSongs.new(genres_song_params)\n\n respond_to do |format|\n if @genres_song.save\n format.html { redirect_to @genres_song, notice: 'Genres songs was successfully created.' }\n format.json { render :show, status: :created, location: @genres_song }\n else\n format.html { render :new }\n format.json { render json: @genres_song.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @album_genre = AlbumGenre.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @album_genre }\n end\n end",
"def genres( album )\n return get_metadata( album )[:genres]\n end",
"def create\n @song_genre = SongGenre.new(params[:song_genre])\n\n respond_to do |format|\n if @song_genre.save\n format.html { redirect_to @song_genre, notice: 'Song genre was successfully created.' }\n format.json { render json: @song_genre, status: :created, location: @song_genre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @song_genre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @galleries_album = Galleries::Album.new(galleries_album_params)\n @galleries_album.user = current_user\n respond_to do |format|\n if @galleries_album.save\n format.html { redirect_to @galleries_album, notice: 'Album was successfully created.' }\n format.json { render :show, status: :created, location: @galleries_album }\n else\n format.html { render :new }\n format.json { render json: @galleries_album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\t\t@genre = Genre.new(genre_params)\n\t\t@genre.user_id = current_user.id\n\n\t\trespond_to do |format|\n\t\t\tif @genre.save\n\t\t\t\t@genres=Genre.where(\"user_id = ?\", current_user.id).order(\"name\")\n\t\t\t\t@genres = @genres.paginate(page: params[:page], per_page: 18)\n\t\t\t\tformat.html { redirect_to @genre; flash[:success]= 'Genre was successfully created.' }\n\t\t\t\tformat.json { render :show, status: :created, location: @genre }\n\t\t\t\tformat.js\n\t\t\telse\n\t\t\t\tformat.html { render :new }\n\t\t\t\tformat.json { render json: @genre.errors, status: :unprocessable_entity }\n\t\t\t\tformat.js\n\t\t\tend\n\t\tend\n\tend",
"def create\n image_ids = params[:album][:image_ids]\n\n @album = @event.albums.new(album_params)\n\n respond_to do |format|\n if @album.save\n @album.add_images_by_id(image_ids)\n format.html { redirect_to [@event, @album], notice: 'Album was successfully created.' }\n format.json { render :show, status: :created, location: @album }\n else\n format.html { render :new }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @subgenre = Subgenre.new\n\n @subgenre.title = params[:subgenre]['title']\n @subgenre.genre = params[:subgenre]['genre']\n @subgenre.subgenre = SubgenreUploader.new\n @subgenre.subgenre.store!(params[:subgenre]['subgenre'])\n\n respond_to do |format|\n if @subgenre.save\n format.html { redirect_to subgenres_path, notice: 'Subgenre was successfully created.' }\n format.json { render json: @subgenre, status: :created, location: @subgenre }\n else\n format.html { render action: \"new\" }\n format.json { render json: @subgenre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @album = Album.find(params[:album_id])\n @photo = @album.photos.new(params[:photo])\n \n if @photo.save \n # AW\n # had to override to use gem and multiphoto upload \n # there is the manual input of json, found under views/photos/create.json.jbuilder\n else\n render :json => { \"errors\" => @photo.errors } \n end\n end",
"def get_genre_list \n @get_genre_list = HTTP.get(\"https://api.themoviedb.org/3/genre/movie/list?language=en-US&api_key=a535faacf3a8b1eb413a9dce8ae2ca51\").to_s\n @genre_data = JSON.parse(@get_genre_list)\n\n #Loop through moviedb list and add each genre to Genre model\n for i in 0..@genre_data[\"genres\"].length-1\n current_genre = @genre_data[\"genres\"][i]\n number = current_genre[\"id\"]\n name = current_genre[\"name\"]\n Genre.create ({ \"number\" => number,\n \"name\" => name })\n end\n end",
"def create\n\n @album = @user.albums.create(params[:album])\n \n \n respond_to do |format|\n if @album.save\n format.html { redirect_to '/profile/edit', notice: '@user.albums was successfully created.' }\n format.json { render json: @album, status: :created, location: @album }\n else\n format.html { render action: \"new\" }\n format.json { render json: @album.errors, status: :unprocessable_entity }\n end\n end\n end",
"def genres=(genres_from_response)\n @genres = Enceladus::Genre.build_collection(genres_from_response)\n end",
"def show\n @album_genre = AlbumGenre.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @album_genre }\n end\n end",
"def create\n @albumm = Albumm.new(params[:albumm])\n\n respond_to do |format|\n if @albumm.save\n format.html { redirect_to @albumm, notice: 'Albumm was successfully created.' }\n format.json { render json: @albumm, status: :created, location: @albumm }\n else\n format.html { render action: \"new\" }\n format.json { render json: @albumm.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n set_genre\n @subgenre = @genre.subgenres.new(subgenre_params)\n respond_to do |format|\n if @subgenre.save\n format.html { redirect_to subgenres_link_url, notice: 'Subgenre was successfully created.' }\n format.json { render :show, status: :created, location: @subgenre }\n else\n format.html { render :new }\n format.json { render json: @subgenre.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @gallery = Gallery.new(gallery_params)\n\n if @gallery.save\n render json: @gallery, status: :created, location: @gallery\n else\n render json: @gallery.errors, status: :unprocessable_entity\n end\n end"
] | {
"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 end\n end",
"def destroy\n @song_genre = SongGenre.find(params[:id])\n @song_genre.destroy\n\n respond_to do |format|\n format.html { redirect_to song_genres_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @galleries_album.destroy\n respond_to do |format|\n format.html { redirect_to galleries_albums_url, notice: 'Album was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @albumsix.destroy\n respond_to do |format|\n format.html { redirect_to albumsixes_url, notice: 'Albumsix was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n \t@album = Album.find(params[:album_id])\n @photo = @album.photos.find(params[:id])\n @photo.destroy\n\n respond_to do |format|\n format.html { redirect_to albums_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @omdb_genre.destroy\n respond_to do |format|\n format.html { redirect_to omdb_genres_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @albumm = Albumm.find(params[:id])\n @albumm.destroy\n\n respond_to do |format|\n format.html { redirect_to albumms_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @albumone.destroy\n respond_to do |format|\n format.html { redirect_to albumones_url, notice: 'Albumone was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @photoalbum = Photoalbum.find(params[:id])\n @photoalbum.destroy\n\n respond_to do |format|\n format.html { redirect_to photoalbums_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @photo_album = PhotoAlbum.find(params[:id])\n @photo_album.destroy\n\n respond_to do |format|\n format.html { redirect_to photo_albums_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album = Album.find(params[:id])\n @album.album.destroy\n @album.destroy\n respond_to do |format|\n format.html { redirect_to(albums_path, :notice => 'photo was successfully deleted.') }\n format.xml { head :ok }\n end\n end",
"def destroy\n @baptism_album.destroy\n respond_to do |format|\n format.html { redirect_to baptism_albums_url, notice: 'Baptism album was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @albumseven.destroy\n respond_to do |format|\n format.html { redirect_to albumsevens_url, notice: 'Albumseven was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @private_album.destroy\n respond_to do |format|\n format.html { redirect_to private_albums_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album = Album.find(params[:id])\n @album.destroy\n\n respond_to do |format|\n format.html { redirect_to(admin_albums_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @user_album = UserAlbum.find(params[:id])\n @user_album.destroy\n\n respond_to do |format|\n format.html { redirect_to user_albums_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @album_owned = AlbumOwned.find(params[:id])\n @album_owned.destroy\n\n respond_to do |format|\n format.html { redirect_to album_owneds_url }\n format.json { head :no_content }\n end\n end"
] | {
"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 @total_cost = nil \n super\n end",
"def initialize(initial_price, interest_rate, volatility)\n @initial_price = initial_price\n @interest_rate = interest_rate / 100\n @volatility = volatility / 100\nend",
"def initialize(energy_cost=1)\n self.energy_cost = energy_cost\n end",
"def initialize(discount = 20)\n @total = 0\n @discount = discount\nend",
"def initialize original_price\n # @product = Product.new(original_price)\n @original_price = original_price\n @current_price = original_price\n @days = 0\n @discount = discount\n end",
"def initialize(required_to_redeem)\n @pop_cost = 2\n @leftover = 0\n @initial_bottles = 0\n @required_to_redeem = required_to_redeem\n end",
"def initialize(options)\n @id = options[:id].to_i\n @year = options[:year].to_i\n @model = options[:model].to_s\n @engine = options[:engine].to_s\n @sale_price = options[:sale_price].to_i\n @mpg_city = options[:mpg_city].to_i\n @mpg_hwy = options[:mpg_hwy].to_i\n @maint_cost = options[:maint_cost].to_i\n @rpr_cost = options[:rpr_cost].to_i\n @ins_cost = options[:ins_cost].to_i\n @grade_fuel = options[:grade_fuel].to_s\n @regular = 2.79\n @mid_grade = 2.95\n @premium = 3.05\n @diesel = 2.85\n @annual_miles = 12000\n @years_to_keep = options[:years_to_keep].to_i\n end",
"def initialize(name, cost, interest_rate, length)\n @name = name\n @cost = cost\n @interest_rate = interest_rate\n @length = length\n @mature_value = (@cost * (1+ @interest_rate / 100.0)).to_i\n end",
"def initialize\n @price = 0\n end",
"def initialize(employee_discount = 0, total = 0) #dont need splat becasue pours into array\n #in test, they provide the 20, default discount set it equal to 0\n @total = total\n @employee_discount = employee_discount #if you are passing it in when you create\n #@employee_discount = 20\n #@list = list\n @list = []\n end",
"def initialize(cost, percent, guests)\n @cost = cost\n @percent = percent\n @guests = guests\n end",
"def initialize (id, name , departure , arrival, first_class_capacity ,economic_class_capacity ,business_class_capacity,economic_class_price,first_class_price,business_class_price , duration , departure_time , arrival_time,first_class_availability ,economic_class_availability ,business_class_availability)\n\n @name = name\n @id = id\n\n\n @first_class_capacity = first_class_capacity\n @economic_class_capacity = economic_class_capacity\n @business_class_capacity =business_class_capacity\n @economic_class_price = economic_class_price\n @first_class_price =first_class_price\n @business_class_price =business_class_price\n\n @departure = departure\n @arrival = arrival\n\n @available_seats_business= business_class_availability\n @available_seats_economic = economic_class_availability\n @available_seats_first_class = first_class_availability\n\n\n @duration = duration\n\n @departure_time = departure_time\n @arrival_time = arrival_time\n end",
"def initialize(amount)\n @amount = amount\n @quarters = 0\n @dimes = 0\n @nickels = 0\n @pennies = 0\n end",
"def initialize\n @funds = 1000\n end",
"def initialize(name)\n @rentals = {}\n @name = name\n @frequent_renter_points = 0\n @total_price = 0\n @price_breakdown = ''\n end",
"def initialize(hash = {})\n hash.delete_if { |k, v| v.nil? }\n hash = defaults.merge(hash)\n\n @id = hash[:id]\n @name = hash[:name]\n @multiplier = hash[:multiplier]\n @start_date = Date.new(hash[:start_date])\n @end_date = Date.new(hash[:end_date])\n\n @total_site_energy_kwh = hash[:total_site_energy_kwh]\n @total_source_energy_kwh = hash[:total_source_energy_kwh]\n @site_EUI_kwh_per_m2 = hash[:site_EUI_kwh_per_m2]\n @site_EUI_kbtu_per_ft2 = hash[:site_EUI_kbtu_per_ft2]\n @source_EUI_kwh_per_m2 = hash[:source_EUI_kwh_per_m2]\n @source_EUI_kbtu_per_ft2 = hash[:source_EUI_kbtu_per_ft2]\n @net_site_energy_kwh = hash[:net_site_energy_kwh]\n @net_source_energy_kwh = hash[:net_source_energy_kwh]\n @net_utility_cost_dollar = hash[:net_utility_cost_dollar]\n @total_utility_cost_dollar = hash[:total_utility_cost_dollar]\n @electricity_kwh = hash[:electricity_kwh]\n @natural_gas_kwh = hash[:natural_gas_kwh]\n @propane_kwh = hash[:propane_kwh]\n @fuel_oil_kwh = hash[:fuel_oil_kwh]\n @other_fuels_kwh = hash[:other_fuels_kwh]\n @district_cooling_kwh = hash[:district_cooling_kwh]\n @district_heating_kwh = hash[:district_heating_kwh]\n @water_qbft = hash[:water_qbft]\n @electricity_produced_kwh = hash[:electricity_produced_kwh]\n @end_uses = EndUses.new(hash[:end_uses])\n\n @energy_production_kwh = hash[:energy_production_kwh]\n\n @utility_costs_dollar = hash[:utility_costs_dollar]\n\n @comfort_result = hash[:comfort_result]\n\n # initialize class variables @@validator and @@schema\n @@validator ||= Validator.new\n @@schema ||= @@validator.schema\n end",
"def initialize(discount = 0)\n @discount = discount\n @total = 0\n @items = []\n @transaction_id = 0\n @transactions = {}\n end",
"def initialize(name, price, sales_tax, import_tax)\n @name = name\n @price = price #Rounds to the second decemal point\n @sales_tax = sales_tax\n @import_tax = import_tax\n @total_tax = total_tax\n end"
] | {
"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\t # TODO: Ooops I forgot to store the item description in an array for the customer!\n\t # You'll need to initialize the purchases array in the initialize method or\n\t # check it here, how will I do this once Customer is a Class?\n\t # @purchases.push description\n\n\n\n \"APPROVED: $#{'%.2f' % amount} #{description}\"\n \telse\n \"DECLINED: $#{'%.2f' % amount} #{description} Purchase! Only $#{'%.2f' % available_credit} credit available\"\n \tend\n\tend",
"def credit(amount = nil, options = {})\n execute(:credit, {:amount => amount || self.amount}.reverse_merge(options))\n end",
"def attempt_credit_purchase (customer, amount, description)\n if use_credit(customer, amount)\n\n # TODO: Ooops I forgot to store the item description in an array for the customer!\n # You'll need to initialize the purchases array in the initialize method or\n # check it here, how will I do this once Customer is a Class?\n # @purchases.push description\n\n \"APPROVED: $#{'%.2f' % amount} #{description}\"\n else\n \"DECLINED: $#{'%.2f' % amount} #{description} Purchase! Only $#{'%.2f' % available_credit(customer)} credit available\"\n end\nend",
"def credit(amount, authorization, options={})\n adjust_and_save(amount.abs, :credit, {:authorization => authorization}.merge(options))\n end",
"def credit\n account.balance += amount\n end",
"def credit\n account_credit ? account_credit.amount : BigDecimal('0.0')\n end",
"def fund\n transaction = debits.build credit: household.cash, date: Date.today, user: household.default_user, household: household\n\n if accruing?\n transaction.amount = budget\n else\n if balance < 0\n transaction.amount = budget + (balance * -1)\n else\n transaction.amount = budget - balance\n end\n end\n\n transaction.save\n\n transaction\n end",
"def create\n @credit = Credit.new(credit_params)\n @credit.email = current_user.email\n\t@credit.create_amount(@credit.amount, current_user.percent, @credit.term)\n respond_to do |format|\n if @credit.save\n format.html { redirect_to '/credits', notice: 'Credit was successfully created.' }\n format.json { render :show, status: :created, location: @credit }\n else\n format.html { render :new }\n format.json { render json: @credit.errors, status: :unprocessable_entity }\n end\n end\n end",
"def credit_amount\n sum( credits )\n end",
"def buy_60_credits\n x_tran_key=\"9Pk82B77ab9nh7Nq\"\n @order=Purchase.new\n baseprice = 75\n amount = baseprice\n amount = amount.to_s() + \".00\"\n @amount = amount\n @order.amount = amount\n @order.credits = 60\n @order.number = number\n @order.state = \"pending\"\n loginid=\"8Ty3NvP8z7z\"\n fp = InsertFP(loginid, x_tran_key, @amount, \"0001\")\n id = session[:company_id]\n @company = Company.find(id)\n @order.company = id\n @order.save\n end",
"def credit(amount)\n credit = Credit.new(:amount => amount)\n result = api_request(:post, \"/subscribers/#{self.customer_id}/credits.xml\", :body => credit.to_xml)\n self.store_credit = (self.store_credit || 0) + amount\n true\n end",
"def record_payment amount=0, detail_type=UrTransaction.detail_types[:cc_payment]\n # raise error is amount is less that outstanding balance\n if self.check_outstanding > amount then\n raise \"Amount is not enough to cover expenses\"\n return\n end\n\n self.transaction do\n #split payment into tax, cut to jomgolf and actual revenue\n #need to take note when doing delta payments (esp when updating revenue count)\n outstanding_balance = self.check_outstanding\n tax_payment = outstanding_balance - (outstanding_balance / (1 + self.golf_club.tax_schedule.rate)).round(2)\n jomgolf_share = self.reserve_method == \"online\" ? NovGolf::PROVIDER_SHARE : NovGolf::DASHBOARD_PROVIDER_SHARE\n jomgolf_cut = ((outstanding_balance - tax_payment) * jomgolf_share).round(2)\n revenue_payment = outstanding_balance - tax_payment - jomgolf_cut\n cash_change_amount = amount - outstanding_balance\n\n #tax payment\n tranx = self.ur_transactions.new({trans_amount:-(tax_payment), detail_type:UrTransaction.detail_types[:tax_payment]})\n tranx.save!\n\n #service provider share\n tranx = self.ur_transactions.new({trans_amount:-(jomgolf_cut), detail_type:UrTransaction.detail_types[:provider_share]})\n tranx.save!\n\n #actual revenue payment\n tranx = self.ur_transactions.new({trans_amount:-(revenue_payment), detail_type:detail_type})\n tranx.save!\n\n #excess balance\n tranx = self.ur_transactions.new({trans_amount:-(cash_change_amount), detail_type:UrTransaction.detail_types[:excess_payment]})\n tranx.save!\n\n #record the change that needs to be given\n tranx = self.ur_transactions.new({detail_type:UrTransaction.detail_types[:cash_change], trans_amount:-(self.check_outstanding)})\n tranx.save!\n end\n end",
"def charge_cost_to_my_account\n self.my_account.debit(self.aircrafttype.cost)\n end",
"def credit(money, creditcard, options = {})\n raise ArgumentError, 'Reference credits are not supported. Please supply the original credit card' if creditcard.is_a?(String)\n\n form = {}\n add_invoice(form, options)\n add_creditcard(form, creditcard)\n add_address(form, options)\n add_customer_data(form, options)\n add_test_mode(form, options)\n commit(:credit, money, form)\n end",
"def credits_balance\n credit_amounts.balance\n end",
"def credit(money, creditcard, options = {})\n if creditcard.is_a?(String)\n raise ArgumentError, \"Reference credits are not supported. Please supply the original credit card or use the #refund method.\"\n end\n\n form = {}\n add_invoice(form, options)\n add_creditcard(form, creditcard)\n add_address(form, options)\n add_customer_data(form, options)\n add_test_mode(form, options)\n commit(:credit, money, form)\n end",
"def deduct_from_credit\n if self.account.has_credit? && self.payment_method != Charge::COMPED_PAYMENT\n credit_amount_string = ActionController::Base.helpers.number_to_currency(self.account.credit)\n charge_amount_string = ActionController::Base.helpers.number_to_currency(self.amount)\n\n # credit > charge\n # subtract charge amount from credit amount, pay charge completely\n if self.account.credit >= self.amount\n self.update_attribute(:payment_method, Charge::COMPED_PAYMENT)\n self.update_attribute(:paid_at, Time.now)\n self.update_attribute(:description, self.description + \" (#{charge_amount_string} paid by lab credit)\")\n self.account.update_attribute(:credit, self.account.credit - self.amount)\n\n\n # charge > credit: \n # split charge into two charges -- covered by credit and not covered\n # pay charge covered by credit\n else\n paid_amount = self.account.credit \n unpaid_amount = self.amount - self.account.credit\n\n self.account.update_attribute(:credit, 0)\n\n Charge.create(amount: paid_amount, \n payment_method: Charge::COMPED_PAYMENT,\n paid_at: Time.now,\n charge_type: self.charge_type,\n account: self.account,\n description: \"Parital lab credit payment (original charge #{charge_amount_string}, #{credit_amount_string} paid by lab credit)\" \n )\n\n self.update_attribute(:amount, unpaid_amount)\n self.update_attribute(:description, self.description + \" (original charge #{charge_amount_string}, #{credit_amount_string} paid by lab credit)\")\n end\n end\n end",
"def credit(money, identification, options = {})\n post = { :gateid => identification }\n\n commit('CREDIT', money, post)\n end"
] | {
"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.student_id == self.id}\n end",
"def appointments_attributes=(appointments_attributes)\n # If submitted client is valid\n if self.valid?\n appointments_attributes.values.each do |appointment_attributes|\n # Clients have only 1 associated appointment object. Instead of creating new objects\n # we simply update the date attribute once an appointment is completed\n if self.appointments.last != nil\n self.appointments.last.update(appointment_attributes)\n else\n # Create new appointment object and make it belong to new client\n appointment = Appointment.create(appointment_attributes)\n self.appointments << appointment\n end\n end\n end\n end",
"def appointments\n @date = Date.today\n @start_date = @date.beginning_of_week(:sunday).to_date\n @end_date = @date.end_of_week(:sunday).to_date\n @rooms = Room.all\n @counselors = Counselor.all\n @cases = Case.all\n @counselor_room = CounselorAvailability.new\n @counselor_availabilities = CounselorAvailability.where(\"start_at BETWEEN '#{@start_date} 00:01:01' and '#{@end_date} 23:59:59'\")\n @common_appointments = Array.new\n @main_appoints = Array.new\n @counselor_availabilities.each do |a|\n @common_appointments << a.start_at.strftime(\"%Y-%m-%d %H:%M:%S\")+a.room_id.to_s\n @main_appoints << a\n end\n end",
"def appointments(officer_id)\n client.get(\"officers/#{officer_id}/appointments/\")\n end",
"def appointments\n return @appointments\n end",
"def created_appointments\n Appointment.all(created_by: to_s)\n end",
"def appointments=(value)\n @appointments = value\n end",
"def add_appointment(appointment)\n appointment.doctor = self\n @appointments << appointment\n end",
"def patients\r\n self.appointments.collect do |appt|\r\n appt.patient\r\n end\r\n end",
"def upcoming_appointments\n appointments.upcoming\n end",
"def appointments_on(date)\n appointments.starts_on(date).to_a\n end",
"def approval\n @appointments = Appointment.in_clinic(@admin).requests.\n order_by_time.includes(:doctor, :patient).not_past\n end",
"def index\n @approved_appointments = ApprovedAppointment.all\n end",
"def test_has_many_appontments\r\n appointments_count = @my_loc.appointments.count\r\n assert_not_equal(0, appointments_count, \"No Appointment found for this Location.\")\r\n end",
"def show\n @upcoming_appointments = Appointment.where('resident_id = ?', @resident.id)\n end",
"def test_has_many_appointments\r\n patient_appointment_count = @patient.appointments.count\r\n appointment_count = Appointment.count\r\n assert_not_equal(0, patient_appointment_count, \"No Appointment found for this patient.\")\r\n end",
"def index\n @client_has_conjoints = ClientHasConjoint.all\n end"
] | {
"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 @index = {}\n self.seek(offset.to_i)\n tmp = Nokogiri::XML.parse(self.read).root\n tmp.css(\"index\").each do |idx|\n index_type = idx[:name].to_sym\n @index[index_type] = {}\n idx.css(\"offset\").each do |o|\n @index[index_type][o[:idRef]] = o.text().to_i\n end\n end\n return @index\n end",
"def match parser, index\r\n raise \"no children added to sequence\" unless @list\r\n each do |element|\r\n index = element.match parser, index\r\n return NO_MATCH unless index\r\n end\r\n report index\r\n end",
"def indexed\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 42 )\n return_value = IndexedReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n char_literal185 = nil\n char_literal187 = nil\n identified184 = nil\n expression186 = nil\n\n tree_for_char_literal185 = nil\n tree_for_char_literal187 = nil\n\n begin\n root_0 = @adaptor.create_flat_list\n\n\n # at line 312:4: identified ( '[' expression ']' )*\n @state.following.push( TOKENS_FOLLOWING_identified_IN_indexed_1776 )\n identified184 = identified\n @state.following.pop\n @adaptor.add_child( root_0, identified184.tree )\n # --> action\n return_value.result = ( identified184.nil? ? nil : identified184.result )\n # <-- action\n # at line 314:3: ( '[' expression ']' )*\n while true # decision 42\n alt_42 = 2\n look_42_0 = @input.peek( 1 )\n\n if ( look_42_0 == T__67 )\n alt_42 = 1\n\n end\n case alt_42\n when 1\n # at line 314:4: '[' expression ']'\n char_literal185 = match( T__67, TOKENS_FOLLOWING_T__67_IN_indexed_1786 )\n\n tree_for_char_literal185 = @adaptor.create_with_payload( char_literal185 )\n @adaptor.add_child( root_0, tree_for_char_literal185 )\n\n @state.following.push( TOKENS_FOLLOWING_expression_IN_indexed_1788 )\n expression186 = expression\n @state.following.pop\n @adaptor.add_child( root_0, expression186.tree )\n char_literal187 = match( T__68, TOKENS_FOLLOWING_T__68_IN_indexed_1790 )\n\n tree_for_char_literal187 = @adaptor.create_with_payload( char_literal187 )\n @adaptor.add_child( root_0, tree_for_char_literal187 )\n\n # --> action\n return_value.result = [IndexTree.new(return_value.result, ( expression186.nil? ? nil : expression186.result )),identified184.tree]\n # <-- action\n\n else\n break # out of loop for decision 42\n end\n end # loop for decision 42\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 42 )\n\n end\n \n return return_value\n end",
"def check_index_elements_calculated!\n unless index_elements.size > 0\n raise \"primary access rights not calculated. instantiate by calling '.parse(xml, forindex = true)'.\"\n end\n end",
"def index_results!\r\n raise \"You must first call parse!\" unless parse_results\r\n @index = new Hash {|h, k| h[k] = []}\r\n parse_results.each_pair do |index, prod_map|\r\n prod_map[:found_order].reverse_each\r\n prod_map.each_value\r\n @index[prod]\r\n end\r\n end",
"def first_nil_parse_index_assert\n idx = @children.index{|x| x.is_nil_parse? }\n if idx.nil?\n return @children.length\n end\n bad1 = (0..idx-1).map{|i|\n @children[i].is_nil_parse? ?\n [i,@children[i]] : nil\n }.compact\n bad2 = (idx..@children.length-1).map{|i|\n @children[i].is_nil_parse? ?\n nil : [i, @children[i]]\n }.compact\n bads = bad1 + bad2\n if bads.any? then no(\n \"found nil parses or non where we didn't expect to:\" <<\n \"i am #{short} and these are my bad children: \" << (\n bads.map{|b| \"at #{b[0]}: #{b[1].short}\"}.join(';')\n )\n ) end\n idx\n end",
"def create_index\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 3 )\n return_value = CreateIndexReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n string_literal4 = nil\n __ID5__ = nil\n string_literal6 = nil\n __ID7__ = nil\n char_literal8 = nil\n __ID9__ = nil\n char_literal10 = nil\n __ID11__ = nil\n string_literal12 = nil\n\n tree_for_string_literal4 = nil\n tree_for_ID5 = nil\n tree_for_string_literal6 = nil\n tree_for_ID7 = nil\n tree_for_char_literal8 = nil\n tree_for_ID9 = nil\n tree_for_char_literal10 = nil\n tree_for_ID11 = nil\n tree_for_string_literal12 = nil\n\n begin\n root_0 = @adaptor.create_flat_list\n\n\n # at line 25:5: 'create index' ID 'on' ID '(' ID ( ',' ID )* ');'\n string_literal4 = match( CREATE_INDEX, TOKENS_FOLLOWING_CREATE_INDEX_IN_create_index_117 )\n\n tree_for_string_literal4 = @adaptor.create_with_payload( string_literal4 )\n root_0 = @adaptor.become_root( tree_for_string_literal4, root_0 )\n\n __ID5__ = match( ID, TOKENS_FOLLOWING_ID_IN_create_index_120 )\n\n tree_for_ID5 = @adaptor.create_with_payload( __ID5__ )\n @adaptor.add_child( root_0, tree_for_ID5 )\n\n string_literal6 = match( T__16, TOKENS_FOLLOWING_T__16_IN_create_index_122 )\n __ID7__ = match( ID, TOKENS_FOLLOWING_ID_IN_create_index_125 )\n\n tree_for_ID7 = @adaptor.create_with_payload( __ID7__ )\n @adaptor.add_child( root_0, tree_for_ID7 )\n\n char_literal8 = match( T__17, TOKENS_FOLLOWING_T__17_IN_create_index_127 )\n __ID9__ = match( ID, TOKENS_FOLLOWING_ID_IN_create_index_130 )\n\n tree_for_ID9 = @adaptor.create_with_payload( __ID9__ )\n @adaptor.add_child( root_0, tree_for_ID9 )\n\n # at line 25:41: ( ',' ID )*\n while true # decision 3\n alt_3 = 2\n look_3_0 = @input.peek( 1 )\n\n if ( look_3_0 == T__18 )\n alt_3 = 1\n\n end\n case alt_3\n when 1\n # at line 25:42: ',' ID\n char_literal10 = match( T__18, TOKENS_FOLLOWING_T__18_IN_create_index_133 )\n __ID11__ = match( ID, TOKENS_FOLLOWING_ID_IN_create_index_136 )\n\n tree_for_ID11 = @adaptor.create_with_payload( __ID11__ )\n @adaptor.add_child( root_0, tree_for_ID11 )\n\n\n else\n break # out of loop for decision 3\n end\n end # loop for decision 3\n string_literal12 = match( T__19, TOKENS_FOLLOWING_T__19_IN_create_index_140 )\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 3 )\n\n end\n \n return return_value\n end",
"def build_index\n index = {}\n\n rules.each_with_index do |rule, idx|\n key = rule.key\n\n # Use this to make sure any duplicate entry uses the maximum index (i.e. last defined rule).\n index[key] = [ index[key], idx ].compact.max\n end\n index\n end",
"def build_indices\n\n @toplevels.each do |toplevel|\n @files << HtmlFile.new(toplevel, @options, FILE_DIR)\n end\n\n RDoc::TopLevel.all_classes_and_modules.each do |cls|\n build_class_list(cls, @files[0], CLASS_DIR)\n end\n end",
"def arrayIndexTarget\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 38 )\n return_value = ArrayIndexTargetReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n __INT160__ = nil\n __NULL166__ = nil\n subexpression159 = nil\n callVar161 = nil\n array162 = nil\n alloc163 = nil\n readInstruction164 = nil\n string165 = nil\n openFile167 = nil\n sizeOf168 = nil\n readNumber169 = nil\n writeFile170 = nil\n\n tree_for_INT160 = nil\n tree_for_NULL166 = nil\n\n begin\n # at line 280:2: ( subexpression | INT | callVar | array | alloc | readInstruction | string | NULL | openFile | sizeOf | readNumber | writeFile )\n alt_36 = 12\n case look_36 = @input.peek( 1 )\n when LB then alt_36 = 1\n when INT then alt_36 = 2\n when ID then alt_36 = 3\n when T__67 then alt_36 = 4\n when ALLOC then alt_36 = 5\n when READ then alt_36 = 6\n when STRING then alt_36 = 7\n when NULL then alt_36 = 8\n when OPENFILE then alt_36 = 9\n when SIZEOF then alt_36 = 10\n when READNUMBER then alt_36 = 11\n when WRITEFILE then alt_36 = 12\n else\n raise NoViableAlternative( \"\", 36, 0 )\n end\n case alt_36\n when 1\n root_0 = @adaptor.create_flat_list\n\n\n # at line 280:4: subexpression\n @state.following.push( TOKENS_FOLLOWING_subexpression_IN_arrayIndexTarget_1575 )\n subexpression159 = subexpression\n @state.following.pop\n @adaptor.add_child( root_0, subexpression159.tree )\n # --> action\n return_value.result = ( subexpression159.nil? ? nil : subexpression159.result )\n # <-- action\n\n when 2\n root_0 = @adaptor.create_flat_list\n\n\n # at line 281:4: INT\n __INT160__ = match( INT, TOKENS_FOLLOWING_INT_IN_arrayIndexTarget_1582 )\n\n tree_for_INT160 = @adaptor.create_with_payload( __INT160__ )\n @adaptor.add_child( root_0, tree_for_INT160 )\n\n # --> action\n return_value.result = [AtomTree.new(__INT160__.text.to_i),tree_for_INT160]\n # <-- action\n\n when 3\n root_0 = @adaptor.create_flat_list\n\n\n # at line 282:4: callVar\n @state.following.push( TOKENS_FOLLOWING_callVar_IN_arrayIndexTarget_1589 )\n callVar161 = callVar\n @state.following.pop\n @adaptor.add_child( root_0, callVar161.tree )\n # --> action\n return_value.result = ( callVar161.nil? ? nil : callVar161.result )\n # <-- action\n\n when 4\n root_0 = @adaptor.create_flat_list\n\n\n # at line 283:4: array\n @state.following.push( TOKENS_FOLLOWING_array_IN_arrayIndexTarget_1596 )\n array162 = array\n @state.following.pop\n @adaptor.add_child( root_0, array162.tree )\n # --> action\n return_value.result = [ArrayTree.new(( array162.nil? ? nil : array162.result )),array162.tree]\n # <-- action\n\n when 5\n root_0 = @adaptor.create_flat_list\n\n\n # at line 284:4: alloc\n @state.following.push( TOKENS_FOLLOWING_alloc_IN_arrayIndexTarget_1603 )\n alloc163 = alloc\n @state.following.pop\n @adaptor.add_child( root_0, alloc163.tree )\n # --> action\n return_value.result = ( alloc163.nil? ? nil : alloc163.result )\n # <-- action\n\n when 6\n root_0 = @adaptor.create_flat_list\n\n\n # at line 285:4: readInstruction\n @state.following.push( TOKENS_FOLLOWING_readInstruction_IN_arrayIndexTarget_1610 )\n readInstruction164 = readInstruction\n @state.following.pop\n @adaptor.add_child( root_0, readInstruction164.tree )\n # --> action\n return_value.result = ( readInstruction164.nil? ? nil : readInstruction164.result )\n # <-- action\n\n when 7\n root_0 = @adaptor.create_flat_list\n\n\n # at line 286:4: string\n @state.following.push( TOKENS_FOLLOWING_string_IN_arrayIndexTarget_1617 )\n string165 = string\n @state.following.pop\n @adaptor.add_child( root_0, string165.tree )\n # --> action\n return_value.result = [StringTree.new(( string165.nil? ? nil : string165.result )),string165.tree]\n # <-- action\n\n when 8\n root_0 = @adaptor.create_flat_list\n\n\n # at line 287:4: NULL\n __NULL166__ = match( NULL, TOKENS_FOLLOWING_NULL_IN_arrayIndexTarget_1624 )\n\n tree_for_NULL166 = @adaptor.create_with_payload( __NULL166__ )\n @adaptor.add_child( root_0, tree_for_NULL166 )\n\n # --> action\n return_value.result = [NilTree.new,tree_for_NULL166]\n # <-- action\n\n when 9\n root_0 = @adaptor.create_flat_list\n\n\n # at line 288:4: openFile\n @state.following.push( TOKENS_FOLLOWING_openFile_IN_arrayIndexTarget_1631 )\n openFile167 = openFile\n @state.following.pop\n @adaptor.add_child( root_0, openFile167.tree )\n # --> action\n return_value.result = ( openFile167.nil? ? nil : openFile167.result )\n # <-- action\n\n when 10\n root_0 = @adaptor.create_flat_list\n\n\n # at line 289:4: sizeOf\n @state.following.push( TOKENS_FOLLOWING_sizeOf_IN_arrayIndexTarget_1638 )\n sizeOf168 = sizeOf\n @state.following.pop\n @adaptor.add_child( root_0, sizeOf168.tree )\n # --> action\n return_value.result = ( sizeOf168.nil? ? nil : sizeOf168.result )\n # <-- action\n\n when 11\n root_0 = @adaptor.create_flat_list\n\n\n # at line 290:4: readNumber\n @state.following.push( TOKENS_FOLLOWING_readNumber_IN_arrayIndexTarget_1645 )\n readNumber169 = readNumber\n @state.following.pop\n @adaptor.add_child( root_0, readNumber169.tree )\n # --> action\n return_value.result = ( readNumber169.nil? ? nil : readNumber169.result )\n # <-- action\n\n when 12\n root_0 = @adaptor.create_flat_list\n\n\n # at line 291:4: writeFile\n @state.following.push( TOKENS_FOLLOWING_writeFile_IN_arrayIndexTarget_1652 )\n writeFile170 = writeFile\n @state.following.pop\n @adaptor.add_child( root_0, writeFile170.tree )\n # --> action\n return_value.result = ( writeFile170.nil? ? nil : writeFile170.result )\n # <-- action\n\n end# - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 38 )\n\n end\n \n return return_value\n end",
"def crawl(addresses) #, index = Hash.new(0))\n index = Hash.new(0)\n addresses.each do |address|\n index = extract_urls(address, index)\n end\n return index\nend",
"def match parser, index\r\n raise \"multiple element child not set\" unless child\r\n raise \"multiple element range not set\" unless range\r\n count = 0\r\n while count < range.last\r\n found = child.match parser, index\r\n break unless found\r\n index = found\r\n count += 1\r\n end\r\n report range === count ? index : NO_MATCH\r\n end",
"def arrayIndexTarget\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 31 )\n return_value = ArrayIndexTargetReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n\n root_0 = nil\n __ID130__ = nil\n __LB131__ = nil\n __RB133__ = nil\n __INT134__ = nil\n __FLOAT135__ = nil\n expression132 = nil\n string136 = nil\n call137 = nil\n array138 = nil\n readInstruction139 = nil\n new140 = nil\n\n tree_for_ID130 = nil\n tree_for_LB131 = nil\n tree_for_RB133 = nil\n tree_for_INT134 = nil\n tree_for_FLOAT135 = nil\n\n begin\n # at line 233:2: ( ID | LB expression RB | INT | FLOAT | string | call | array | readInstruction | new )\n alt_36 = 9\n alt_36 = @dfa36.predict( @input )\n case alt_36\n when 1\n root_0 = @adaptor.create_flat_list\n\n\n # at line 233:4: ID\n __ID130__ = match( ID, TOKENS_FOLLOWING_ID_IN_arrayIndexTarget_1379 )\n\n tree_for_ID130 = @adaptor.create_with_payload( __ID130__ )\n @adaptor.add_child( root_0, tree_for_ID130 )\n\n # --> action\n return_value.result = [VarTree.new(__ID130__.text),tree_for_ID130]\n # <-- action\n\n when 2\n root_0 = @adaptor.create_flat_list\n\n\n # at line 234:4: LB expression RB\n __LB131__ = match( LB, TOKENS_FOLLOWING_LB_IN_arrayIndexTarget_1386 )\n @state.following.push( TOKENS_FOLLOWING_expression_IN_arrayIndexTarget_1389 )\n expression132 = expression\n @state.following.pop\n @adaptor.add_child( root_0, expression132.tree )\n __RB133__ = match( RB, TOKENS_FOLLOWING_RB_IN_arrayIndexTarget_1391 )\n # --> action\n return_value.result = ( expression132.nil? ? nil : expression132.result )\n # <-- action\n\n when 3\n root_0 = @adaptor.create_flat_list\n\n\n # at line 235:4: INT\n __INT134__ = match( INT, TOKENS_FOLLOWING_INT_IN_arrayIndexTarget_1399 )\n\n tree_for_INT134 = @adaptor.create_with_payload( __INT134__ )\n @adaptor.add_child( root_0, tree_for_INT134 )\n\n # --> action\n return_value.result = [AtomTree.new(__INT134__.text.to_i),tree_for_INT134]\n # <-- action\n\n when 4\n root_0 = @adaptor.create_flat_list\n\n\n # at line 236:4: FLOAT\n __FLOAT135__ = match( FLOAT, TOKENS_FOLLOWING_FLOAT_IN_arrayIndexTarget_1406 )\n\n tree_for_FLOAT135 = @adaptor.create_with_payload( __FLOAT135__ )\n @adaptor.add_child( root_0, tree_for_FLOAT135 )\n\n # --> action\n return_value.result = [AtomTree.new(__FLOAT135__.text.to_f),tree_for_FLOAT135]\n # <-- action\n\n when 5\n root_0 = @adaptor.create_flat_list\n\n\n # at line 237:4: string\n @state.following.push( TOKENS_FOLLOWING_string_IN_arrayIndexTarget_1413 )\n string136 = string\n @state.following.pop\n @adaptor.add_child( root_0, string136.tree )\n # --> action\n return_value.result = [AtomTree.new(( string136.nil? ? nil : string136.result )),string136.tree]\n # <-- action\n\n when 6\n root_0 = @adaptor.create_flat_list\n\n\n # at line 238:4: call\n @state.following.push( TOKENS_FOLLOWING_call_IN_arrayIndexTarget_1420 )\n call137 = call\n @state.following.pop\n @adaptor.add_child( root_0, call137.tree )\n # --> action\n return_value.result = ( call137.nil? ? nil : call137.result )\n # <-- action\n\n when 7\n root_0 = @adaptor.create_flat_list\n\n\n # at line 239:4: array\n @state.following.push( TOKENS_FOLLOWING_array_IN_arrayIndexTarget_1427 )\n array138 = array\n @state.following.pop\n @adaptor.add_child( root_0, array138.tree )\n # --> action\n return_value.result = [ArrayTree.new(( array138.nil? ? nil : array138.result )),array138.tree]\n # <-- action\n\n when 8\n root_0 = @adaptor.create_flat_list\n\n\n # at line 240:4: readInstruction\n @state.following.push( TOKENS_FOLLOWING_readInstruction_IN_arrayIndexTarget_1434 )\n readInstruction139 = readInstruction\n @state.following.pop\n @adaptor.add_child( root_0, readInstruction139.tree )\n # --> action\n return_value.result = ( readInstruction139.nil? ? nil : readInstruction139.result )\n # <-- action\n\n when 9\n root_0 = @adaptor.create_flat_list\n\n\n # at line 241:4: new\n @state.following.push( TOKENS_FOLLOWING_new_IN_arrayIndexTarget_1441 )\n new140 = new\n @state.following.pop\n @adaptor.add_child( root_0, new140.tree )\n # --> action\n return_value.result = ( new140.nil? ? nil : new140.result )\n # <-- action\n\n end# - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 31 )\n\n end\n \n return return_value\n end",
"def _lex_index_offsets; end",
"def clean\n ast = AST.new\n ast.push(*each_with_index.map(&method(:clean_node)).reject(&:nil?))\n ast\n end",
"def search_index\n search_index = Hash.new { |hash, k| hash[k] = Hash.new { |hh, kk| hh[kk] = 0 } }\n\n @pages.each do |p|\n i = urls.index(p.path)\n\n if p.to_s.count(' ') > 0\n # Partial title match\n fuzzy_words(p).each { |word| search_index[word][i] += 30 }\n else\n # Exact title match\n fuzzy_words(p).each { |word| search_index[word][i] += 60 }\n end\n\n # Fuzzy title match\n fuzzy_words(p).each { |word| search_index[word][i] += 3 }\n\n # Content match\n fuzzy_words(p.content).each { |word| search_index[word][i] += 1 }\n end\n\n search_index\n end",
"def freshen_parent_and_child_indexes\n freshen_parent_and_child_indexes(0)\n end",
"def index_name\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 74 )\n return_value = IndexNameReturnValue.new\n\n # $rule.start = the first token seen before matching\n return_value.start = @input.look\n index_name_start_index = @input.index\n\n root_0 = nil\n identifier543 = nil\n\n\n success = false # flag used for memoization\n\n begin\n # rule memoization\n if @state.backtracking > 0 and already_parsed_rule?( __method__ )\n success = true\n return return_value\n end\n root_0 = @adaptor.create_flat_list\n\n\n # at line 501:4: identifier\n @state.following.push( TOKENS_FOLLOWING_identifier_IN_index_name_3198 )\n identifier543 = identifier\n @state.following.pop\n if @state.backtracking == 0\n @adaptor.add_child( root_0, identifier543.tree )\n end\n # - - - - - - - rule clean up - - - - - - - -\n return_value.stop = @input.look( -1 )\n\n if @state.backtracking == 0\n\n return_value.tree = @adaptor.rule_post_processing( root_0 )\n @adaptor.set_token_boundaries( return_value.tree, return_value.start, return_value.stop )\n\n end\n success = true\n\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n return_value.tree = @adaptor.create_error_node( @input, return_value.start, @input.look(-1), re )\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 74 )\n memoize( __method__, index_name_start_index, success ) if @state.backtracking > 0\n\n end\n \n return return_value\n end",
"def visit_indexterm node\n previous_skipped = false\n if @skip.has_key? :indexterm\n skip_count = @skip[:indexterm]\n if skip_count > 0\n @skip[:indexterm] -= 1\n return false\n else\n @skip.delete :indexterm\n previous_skipped = true\n end\n end\n\n @requires_index = true\n entries = [(text_at_css node, 'primary'), (text_at_css node, 'secondary'), (text_at_css node, 'tertiary')].compact\n #if previous_skipped && (previous = node.previous_element) && previous.name == 'indexterm'\n # append_blank_line\n #end\n @skip[:indexterm] = entries.size - 1 if entries.size > 1\n append_line %[(((#{entries * ','})))]\n # Only if next word matches the index term do we use double-bracket form\n #if entries.size == 1\n # append_text %[((#{entries.first}))]\n #else\n # @skip[:indexterm] = entries.size - 1\n # append_text %[(((#{entries * ','})))]\n #end\n false\n end"
] | {
"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_code}'").map{|g|[g.basic_pack_code]}
@basic_pack_codes.unshift("<empty>")
# render (inline) the html to replace the contents of the td that contains the dropdown
render :inline => %{
<%= select('carton_pack_product','basic_pack_code',@basic_pack_codes)%>
<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_carton_pack_product_basic_pack_code'/>
<%= observe_field('carton_pack_product_basic_pack_code',:update => 'carton_pack_style_code_cell',:url => {:action => session[:carton_pack_product_search_form][:basic_pack_code_observer][:remote_method]},:loading => "show_element('img_carton_pack_product_basic_pack_code');",:complete => session[:carton_pack_product_search_form][:basic_pack_code_observer][:on_completed_js])%>
}
end | [
"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 from fg_products where item_pack_product_code = '#{item_pack_product_code}'\").map{|g|[g.unit_pack_product_code]}\n\t@unit_pack_product_codes.unshift(\"<empty>\")\n\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('fg_product','unit_pack_product_code',@unit_pack_product_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_fg_product_unit_pack_product_code'/>\n\t\t<%= observe_field('fg_product_unit_pack_product_code',:update => 'carton_pack_product_code_cell',:url => {:action => session[:fg_product_search_form][:unit_pack_product_code_observer][:remote_method]},:loading => \"show_element('img_fg_product_unit_pack_product_code');\",:complete => session[:fg_product_search_form][:unit_pack_product_code_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def unit_pack_product_type_code_search_combo_changed\n type_code = get_selected_combo_value(params)\n session[:unit_pack_product_search_form][:type_code_combo_selection] = type_code\n @subtype_codes = UnitPackProduct.find_by_sql(\"Select distinct subtype_code from unit_pack_products where type_code = '#{type_code}'\").map{|g|[g.subtype_code]}\n @subtype_codes.unshift(\"<empty>\")\n\n #\trender (inline) the html to replace the contents of the td that contains the dropdown\n render :inline => %{\n\t\t<%= select('unit_pack_product','subtype_code',@subtype_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_unit_pack_product_subtype_code'/>\n\t\t<%= observe_field('unit_pack_product_subtype_code',:update => 'gross_mass_cell',:url => {:action => session[:unit_pack_product_search_form][:subtype_code_observer][:remote_method]},:loading => \"show_element('img_unit_pack_product_subtype_code');\",:complete => session[:unit_pack_product_search_form][:subtype_code_observer][:on_completed_js])%>\n\t\t}\n\n end",
"def gen_dynamic_combos_handlers\n \n lines = Array.new\n @model_settings.associated_tables.each do |key,assoc_table|\n if assoc_table[:index_fields]!= nil\n lines.push \"#\\t--------------------------------------------------------------------------------\"\n lines.push \"#\\t combo_changed event handlers for composite foreign key: \" + key\n lines.push \"#\\t---------------------------------------------------------------------------------\"\n for i in 0..assoc_table[:index_fields].length() -2 #as said, ignore the last field- it doesn't need handler\n lines.concat(gen_combo_changed_handler(assoc_table,i))\n lines.push \"\\n\"\n end\n end\n end\n \n return lines\n \n end",
"def product_product_subtype_code_search_combo_changed\n\tproduct_subtype_code = get_selected_combo_value(params)\n\tsession[:product_search_form][:product_subtype_code_combo_selection] = product_subtype_code\n\t@tag1s = Product.find_by_sql(\"Select distinct tag1 from products where product_subtype_code = '#{product_subtype_code}' and product_type_code = 'PACK_MATERIAL' and is_composite = 'true'\").map{|g|[g.tag1]}\n\t@tag1s.unshift(\"<empty>\")\n\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('product','tag1',@tag1s)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_product_tag1'/>\n\t\t<%= observe_field('product_tag1',:update => 'tag2_cell',:url => {:action => session[:product_search_form][:tag1_observer][:remote_method]},:loading => \"show_element('img_product_tag1');\",:complete => session[:product_search_form][:tag1_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def cartons_per_pallet_pallet_format_product_code_search_combo_changed\n\tpallet_format_product_code = get_selected_combo_value(params)\n\tsession[:cartons_per_pallet_search_form][:pallet_format_product_code_combo_selection] = pallet_format_product_code\n\t@carton_pack_product_codes = CartonsPerPallet.find_by_sql(\"Select distinct carton_pack_product_code from cartons_per_pallets where pallet_format_product_code = '#{pallet_format_product_code}'\").map{|g|[g.carton_pack_product_code]}\n\t@carton_pack_product_codes.unshift(\"<empty>\")\n\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('cartons_per_pallet','carton_pack_product_code',@carton_pack_product_codes)%>\n\t\t<img src = '/images/spinner.gif' style = 'display:none;' id = 'img_cartons_per_pallet_carton_pack_product_code'/>\n\t\t<%= observe_field('cartons_per_pallet_carton_pack_product_code',:update => 'cartons_per_pallet_cell',:url => {:action => session[:cartons_per_pallet_search_form][:carton_pack_product_code_observer][:remote_method]},:loading => \"show_element('img_cartons_per_pallet_carton_pack_product_code');\",:complete => session[:cartons_per_pallet_search_form][:carton_pack_product_code_observer][:on_completed_js])%>\n\t\t}\n\nend",
"def gen_combo_changed_handler(assoc_table,field_pos)\n begin\n lines = Array.new\n fields = assoc_table[:index_fields]\n lines.push \"def \" + @model_settings.model_var_name + \"_\" + fields[field_pos] + \"_changed\"\n lines.push \"\\t\" + fields[field_pos] + \" = get_selected_combo_value(params)\"\n #code to store selected value in session\n lines.push \"\\tsession[:\" + @model_settings.model_var_name + \"_form][:\" + fields[field_pos] + \"_combo_selection] = \" + fields[field_pos]\n #get the values of all the fields with lower indice than the current field\n params = \"(\"\n method = \"\\t@\" + Inflector.pluralize(fields[(field_pos + 1)]) + \" = \"\n method += @model_settings.model_name + \".\" + Inflector.pluralize(fields[(field_pos + 1)]) + \"_for_\" \n vars = Array.new\n session_var = \"\\tsession[:\" + @model_settings.model_var_name + \"_form][:\"\n \n fields.iterate_back(field_pos + 1) do |curr_field|\n lines.push \"\\t\" + curr_field + \" = \" + session_var + curr_field + \"_combo_selection]\" if curr_field != fields[field_pos]\n params += curr_field + \",\"\n method += curr_field + \"_and_\"\n end\n \n method = method.slice(0,method.length()-5)\n params = params.slice(0,params.length()-1)\n \n lines.push method + params + \")\"\n lines.push gen_combo_rendering(assoc_table[:index_fields],field_pos)\n \n lines.push \"\\nend\"\n return lines\n rescue\n raise \"Method: 'gen_combo_changed_handler' failed for table: \" + assoc_table[:table_name] + \n \"and field: \" + assoc_table[:index_fields][field_pos] + \". Reported exception: \\n \" + $!\n \n end\n \n end",
"def gen_search_combo_changed_handler(index_fields,field_pos)\n begin\n lines = Array.new\n fields = index_fields\n lines.push \"def \" + @model_settings.model_var_name + \"_\" + fields[field_pos] + \"_search_combo_changed\"\n lines.push \"\\t\" + fields[field_pos] + \" = get_selected_combo_value(params)\"\n #code to store selected value in session\n lines.push \"\\tsession[:\" + @model_settings.model_var_name + \"_search_form][:\" + fields[field_pos] + \"_combo_selection] = \" + fields[field_pos]\n #get the values of all the fields with lower indice than the current field\n \n session_var = \"\\tsession[:\" + @model_settings.model_var_name + \"_search_form][:\"\n \n fields.iterate_back(field_pos + 1) do |curr_field|\n lines.push \"\\t\" + curr_field + \" = \" + session_var + curr_field + \"_combo_selection]\" if curr_field != fields[field_pos]\n end\n \n lines.push(build_lookup_snippet(field_pos + 1,index_fields,@model_settings.table_name))\n \n lines.push gen_combo_rendering(index_fields,field_pos,true)\n \n lines.push \"\\nend\"\n return lines\n rescue\n raise \"Method: 'gen_search_combo_changed_handler' failed for table: \" + assoc_table[:table_name] + \n \"and field: \" + assoc_table[:index_fields][field_pos] + \". Reported exception: \\n \" + $!\n \n end\n \n end",
"def stock_item_party_type_name_combo_changed\n party_type_name = get_selected_combo_value(params)\n session[:stock_item_form][:party_type_name_combo_selection] = party_type_name\n @party_names = Party.find_by_sql(\"select distinct party_name from parties where party_type_name='#{party_type_name}'\").map{|g|[g.party_name]}\n @party_names.unshift(\"<empty>\")\n render :inline=>%{\n <%=select('stock_item','party_name',@party_names) %>\n <img src = '/images/spinner.gif' style = 'display:none;' id = 'img_stock_item_party_name'/>\n <%= observe_field('stock_item_party_name', :update=>'parties_role_name_cell', :url => {:action=>session[:stock_item_form][:party_name_observer][:remote_method]}, :loading=>\"show_element('img_stock_item_party_name');\", :complete=>session[:stock_item_form][:party_name_observer][:on_completed_js])%>\n }\n end",
"def pallet_setup_pallet_format_product_code_changed\n\tpallet_format_product_code = get_selected_combo_value(params)\n\tpallet_setup = session[:current_carton_setup].pallet_setup\n\t@num_cartons_list = PalletFormatProduct.cartons_per_pallet_codes(session[:current_carton_setup].trade_unit_setup.carton_pack_product_code,pallet_format_product_code)\n\t\n#\trender (inline) the html to replace the contents of the td that contains the dropdown \n\trender :inline => %{\n\t\t<%= select('pallet_setup','no_of_cartons',@num_cartons_list)%>\n\n\t\t}\n\nend",
"def update\n respond_to do |format|\n if @combo_pack.update(combo_pack_params)\n format.html { redirect_to @combo_pack, notice: 'Combo pack was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @combo_pack.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_from_pallet(params)\n #begin\n ipc_changed = nil\n ipc = nil\n mark_changed = nil\n org_changed = nil\n extended_fg = ExtendedFg.find_by_extended_fg_code(self.extended_fg_code)\n fg_product = FgProduct.find_by_fg_product_code(extended_fg.fg_code)\n fg_code = nil\n\n #---------------\n #Get correct IPC\n #---------------\n ipc = fg_product.item_pack_product\n if params['grade_code'] && params['grade_code'] != self.grade_code\n self.grade_code = params['grade_code']\n ipc_changed = true\n end\n if params['product_class_code'] && params['product_class_code'] != self.product_class_code\n self.product_class_code = params['product_class_code']\n ipc_changed = true\n end\n\n\n if ipc_changed\n ipc = ItemPackProduct.find_by_commodity_code_and_marketing_variety_code_and_actual_count_and_product_class_code_and_grade_code_and_cosmetic_code_name_and_size_ref_and_basic_pack_code(ipc.commodity_code, ipc.marketing_variety_code, ipc.actual_count, self.product_class_code, self.grade_code, ipc.cosmetic_code_name, ipc.size_ref, ipc.basic_pack_code)\n if !ipc\n msg = \"An Item Pack product could not be found for values: <BR>\"\n msg += \"commodity: \" + ipc.commodity_code + \"<BR>\"\n msg += \"marketing_variety: \" + ipc.marketing_variety_code + \"<BR>\"\n msg += \"actual count: \" + ipc.actual_count + \"<BR>\"\n msg += \"product_class_code: \" + self.product_class_code + \"<BR>\"\n msg += \"grade_code: \" + self.grade_code + \"<BR>\"\n msg += \"cosmetic code: \" + ipc.cosmetic_code_name + \"<BR>\"\n msg += \"size_ref: \" + ipc.size_ref_code + \"<BR>\"\n msg += \"basic_pack: \" + ipc.basic_pack_code\n return send_message(msg)\n\n end\n\n fg_record = FgProduct.find_by_item_pack_product_code_and_unit_pack_product_code_and_carton_pack_product_code(ipc.item_pack_product_code, fg_product.unit_pack_product_code, fg_product.carton_pack_product_code)\n if !fg_record\n msg = \"A finished good product could not be found for values: <BR>\"\n msg += \" Item pack product: \" + ipc.item_pack_product_code + \"<BR>\"\n msg += \" Unit pack product: \" + fg_product.unit_pack_product_code + \"<BR>\"\n msg += \" Item pack product: \" + fg_product.carton_pack_product_code + \"<BR>\"\n return send_message(msg)\n end\n\n fg_code = fg_record.fg_product_code\n else\n fg_code = extended_fg.fg_code\n end\n\n\n #-------------------\n #Get correct Fg_Mark\n #-------------------\n fg_mark = FgMark.find_by_fg_mark_code(extended_fg.fg_mark_code)\n if params['carton_mark_code'] && params['carton_mark_code'] != self.carton_mark_code\n self.carton_mark_code = params['carton_mark_code']\n mark_changed = true\n end\n\n if mark_changed\n temp_ru_mark = fg_mark.ru_mark_code\n temp_ri_mark = fg_mark.ri_mark_code\n fg_mark = FgMark.find_by_tu_mark_code_and_ru_mark_code_and_ri_mark_code(self.carton_mark_code, fg_mark.ru_mark_code, fg_mark.ri_mark_code)\n if !fg_mark\n msg = \"An FG Mark code could not be found for values: <BR>\"\n msg += \"Carton mark: \" + self.carton_mark_code + \"<BR>\"\n msg += \"Retail unit mark: \" + temp_ru_mark + \"<BR>\"\n msg += \"Retail item mark: \" + temp_ri_mark + \"<BR>\"\n return send_message(msg)\n end\n end\n\n fg_mark_code = fg_mark.fg_mark_code\n\n if params['organization_code'] && params['organization_code'] != self.organization_code\n self.organization_code = params['organization_code']\n org_changed = true\n end\n\n #----------------------------------------------\n #Get extended fg\n #----------------------------------------------\n if ipc_changed || mark_changed || org_changed\n extended_fg = ExtendedFg.find_by_fg_code_and_units_per_carton_and_fg_mark_code_and_marketing_org_code(fg_code, extended_fg.units_per_carton, fg_mark_code, self.organization_code)\n if !extended_fg\n msg = \"An extended FG code could not be found for values: <BR>\"\n msg += \"FG code: \" + fg_code + \"<BR>\"\n\n msg += \"FG mark code: \" + fg_mark_code + \"<BR>\"\n msg += \"Marketing org: \" + self.organization_code + \"<BR>\"\n return send_message(msg)\n end\n self.extended_fg_code = extended_fg.extended_fg_code\n end\n\n #-------------\n #Target market\n #-------------\n\n\n if params['target_market_code']\n params['target_market_code'] = params['target_market_code'].split(\"_\")[0]\n if !OrganizationsTargetMarket.find_by_short_description_and_target_market_name(self.organization_code, params['target_market_code'])\n raise \"Target market: \" + params['target_market_code'] + \" does not exist for org: \" + self.organization_code\n else\n self.target_market_short = params['target_market_code']\n end\n end\n\n\n if params['inventory_code']\n params['inventory_code'] = params['inventory_code'].split(\"_\")[0]\n if !InventoryCodesOrganization.find_by_short_description_and_inv_code(self.organization_code, params['inventory_code'])\n raise \"Inentory code: \" + params['inventory_code'] + \" does not exist for org: \" + self.organization_code\n else\n self.inventory_code_short = params['inventory_code']\n end\n end\n\n if params['inspection_type_code']\n if !InspectionType.find_by_inspection_type_code_and_grade_code(params['inspection_type_code'], ipc.grade_code)\n raise \"Inspection type : \" + params['inspection_type_code'] + \" does not exist for grade: \" + ipc.grade_code\n else\n self.inspection_type_code = params['inspection_type_code']\n end\n end\n\n return derive_fields\n #rescue\n # raise \"Carton: \" + self.carton_number.to_s + \" could not be updated. Reason: <BR>\" + $!\n #end\n end",
"def agregar_stock\n if combo.nil?\n producto.agregar_stock cantidad\n producto.save!\n else\n combo.agregar_stock cantidad\n combo.save\n end\n end",
"def generic_bulk_carton_update(unchanged_fields)\n #-------------------------------------------------------------------------------\n #Find a unique list of all combinations of carton data that are dependent on other\n #data on same carton: e.g class,grade,size_count_code are dependent on each other\n #for a given combination must exist in the form as a fg_product_code. If we have\n #such a unique list, we can update each group as a whole, because each item\n #in the group will derive the exact same values as the group representative cartons\n #fields are: extended_fg_code,org_code,target_market_code,inventory_code,production_run_code\n # inspection_type_code,sell_by_code,farm_code, puc\n #--------------------------------------------------------------------------------\n carton_group_defs = RwActiveCarton.find_by_sql(\"select distinct sell_by_code, extended_fg_code,organization_code,target_market_code,inventory_code,production_run_code,\n inspection_type_code, track_indicator_code, erp_cultivar,spray_program_code,puc,farm_code from rw_active_cartons where\n (rw_run_id = #{self.rw_run_id})\")\n\n\n errs = \"\"\n representative_cartons = Array.new\n\n carton_group_defs.each do |group_def|\n carton = RwActiveCarton.find_all_by_extended_fg_code_and_puc_and_organization_code_and_target_market_code_and_inventory_code_and_production_run_code_and_inspection_type_code_and_sell_by_code_and_track_indicator_code_and_erp_cultivar_and_spray_program_code_and_farm_code(group_def.extended_fg_code,group_def.puc, group_def.organization_code, group_def.target_market_code, group_def.inventory_code, group_def.production_run_code, group_def.inspection_type_code, group_def.sell_by_code,\n group_def.track_indicator_code,group_def.erp_cultivar,group_def.spray_program_code,group_def.farm_code)[0]\n representative_cartons.push(carton)\n end\n\n #---------------------------------------------------------------------------------------------\n #Call update_from_pallet for each carton. Derived fields will be calculated in\n #this method and the 'derive_fields' method called within that method. Collect errors\n #returned by all representative cartons and raise exception. If no errors are returned, build\n #an update_all statement for each representative carton and execute. Raise exception if any\n #update statement failed\n # ---------------------------------------------------------------------------------------------\n puts \"GROUPS: \" + representative_cartons.length().to_s\n cartons_updated = 0\n representative_cartons.each do |repr_carton|\n # begin\n old_vals = {:farm_code => repr_carton.farm_code,:puc => repr_carton.puc,:spray_program_code => repr_carton.spray_program_code,:extended_fg_code => repr_carton.extended_fg_code, :organization_code => repr_carton.organization_code, :target_market_code => repr_carton.target_market_code, :inventory_code => repr_carton.inventory_code, :inspection_type_code => repr_carton.inspection_type_code, :production_run_code => repr_carton.production_run_code, :sell_by_code => repr_carton.sell_by_code,:erp_cultivar => repr_carton.erp_cultivar,:track_indicator_code => repr_carton.track_indicator_code }\n\n repr_carton.reworks_action = \"reclassified\" if repr_carton.reworks_action.upcase!= \"ALT_PACKED\"\n self.export_attributes(repr_carton, true, unchanged_fields)\n repr_carton.decompose_fields\n repr_carton.changed_fields?\n errs = repr_carton.derive_fields\n puts errs if errs != \"\"\n raise errs if errs != \"\"\n cartons_updated += update_group(repr_carton, old_vals)\n puts \"group updated\"\n # rescue\n # raise \"Group update from representative carton: \" + repr_carton.carton_number.to_s + \" failed. Reason:<BR>\" + $!\n # end\n end\n\n raise \"No cartons were updated\" if cartons_updated == 0\n return cartons_updated\n\n end",
"def create\n @combo_pack = ComboPack.new(combo_pack_params)\n\n respond_to do |format|\n if @combo_pack.save\n format.html { redirect_to @combo_pack, notice: 'Combo pack was successfully created.' }\n format.json { render action: 'show', status: :created, location: @combo_pack }\n else\n format.html { render action: 'new' }\n format.json { render json: @combo_pack.errors, status: :unprocessable_entity }\n end\n end\n end",
"def trocar_por_produto_combo(produto_id)\n produto = ProdutoCombo.find(produto_id)\n if produto and @pedido.produtos_quantidades and not @pedido.produtos_quantidades.empty?\n esvazia_carrinho #@pedido.produtos_quantidades.each { |c| retirar_produto(c.produto_id) }\n incluir_produto(produto.id)\n end\n end",
"def index\n @combo_packs = ComboPack.all\n end",
"def build_season_order_quantity_form(season_order_quantity,action,caption,is_edit = nil,is_create_retry = nil,is_view = nil)#-----Luks\n#\t--------------------------------------------------------------------------------------------------\n#\tDefine a set of observers for each composite foreign key- in effect an observer per combo involved\n#\tin a composite foreign key\n#\t--------------------------------------------------------------------------------------------------\n\tsession[:season_order_quantity_form]= Hash.new\n\t\n\tseason_codes = Season.find_by_sql(\"select * from seasons\").map{|g|[g.season_code]}\n\tseason_codes.unshift(\"<empty>\")\n\t\n#\t---------------------------------\n#\t Define fields to build form from\n#\t---------------------------------\n\tfield_configs = Array.new\n if is_view\n\t field_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'season_code'}\n\t\n\tfield_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'customer_order_number'}\n\n\tfield_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'quantity_required'}\n\n\tfield_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'quantity_produced'}\nelse\n field_configs[field_configs.length] = {:field_type => 'DropDownField',\n\t\t\t\t\t\t:field_name => 'season_code',\n\t\t\t\t\t\t:settings => {:list => season_codes}}\n\t\n\tfield_configs[field_configs.length] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'customer_order_number'}\n\n\tfield_configs[field_configs.length] = {:field_type => 'TextField',\n\t\t\t\t\t\t:field_name => 'quantity_required'}\n\n\tfield_configs[field_configs.length] = {:field_type => 'LabelField',\n\t\t\t\t\t\t:field_name => 'quantity_produced',\n\t\t\t\t\t\t:settings => {:static_value => 0,\n :show_label => true}}\n\nend\n\tbuild_form(season_order_quantity,field_configs,action,'season_order_quantity',caption,is_edit)\n\nend",
"def create\n @product_combobox = ProductCombobox.new(params[:product_combobox])\n\n respond_to do |format|\n if @product_combobox.save\n format.html { redirect_to @product_combobox, notice: 'Product combobox was successfully created.' }\n format.json { render json: @product_combobox, status: :created, location: @product_combobox }\n else\n format.html { render action: \"new\" }\n format.json { render json: @product_combobox.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @product_combobox = ProductCombobox.find(params[:id])\n\n respond_to do |format|\n if @product_combobox.update_attributes(params[:product_combobox])\n format.html { redirect_to @product_combobox, notice: 'Product combobox was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @product_combobox.errors, status: :unprocessable_entity }\n end\n end\n end"
] | {
"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 with each indivdual's box's options Hash. This way, you can create a list of boxes that look the same but some have their own characteristics. Also adds a div with style "clear: both" after the output so other objects won't start floating. If you don't want that, add :noclear => true as an option. | 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_options.nil?
r = render_box(box_options)
unless individual_options[:link].blank?
r = "<a href='#{individual_options[:link]}' target='#{individual_options[:link_target]}' class='no_underline render_boxes'>#{r}</a>"
end
boxes += r unless r.blank?
end
boxes_div = content_tag :div, boxes, :class => "textboxes", :style => options[:textboxes_style]
clear_both_ = ""
unless options[:noclear] === true
clear_both_ = clear_both
end
boxes_div + clear_both_
end | [
"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[:content]\n \n return nil if content.blank? && options[:heading].blank? unless options[:empty]\n\n # Options:\n # float_left\n outer_div_classes.push(\"float_left\") if options[:float_left] === true\n # text_align_center\n inner_div_classes.push(\"text_align_center\") if options[:text_align_center] === true\n # highlight\n inner_div_classes.push(\"highlight\") if options[:highlight] === true\n # background_image\n background_image = options[:background_image]\n # header color\n heading_color = options[:heading_color]\n inner_div_classes.push(\"textbox_#{heading_color}\") unless heading_color.blank?\n # background color\n background_color = options[:background_color]\n\n ############################################################################\n # inner div\n ############################################################################\n\n inner_div_classes.push(\"#{background_color}_background\") unless background_color.blank?\n\n inner_div_options = { :class => c(inner_div_classes) }\n inner_div_styles = []\n unless background_image.blank?\n # opacity:0.4;filter:alpha(opacity=40);\n inner_div_styles.push \"background: url(#{background_image}) no-repeat center;\"\n end\n\n unless options[:height].blank?\n inner_div_styles.push \"height: #{options[:height]}\"\n end\n\n unless options[:width].blank?\n inner_div_styles.push \"width: #{options[:width]}\"\n end\n\n unless inner_div_styles.blank?\n inner_div_options[:style] = c(inner_div_styles)\n\n end\n inner_div_options[:style] ||= options[:inner_div_style] # can be overridden\n\n ############################################################################\n # outer div\n ############################################################################\n\n outer_div_options = { :class => c(outer_div_classes) }\n outer_div_options[:style] = options[:outer_div_style]\n\n ############################################################################\n # text div\n ############################################################################\n\n text_div_options = {}\n text_div_classes = []\n\n text_div_classes.push \"bigfont\" if options[:bigfont] === true\n text_div_classes.push \"solid_background\" if options[:solid_background] === true\n\n text_div_options[:class] = c(text_div_classes)\n\n ############################################################################\n # go render\n ############################################################################\n\n # let's go, outer div\n content_tag :div, outer_div_options do\n content_tag :div, inner_div_options do\n # heading\n heading = \"\"\n heading = content_tag :p, options[:heading], :class => c(heading_classes), :style => options[:heading_style] unless options[:heading].blank?\n # text div\n content_tag_ = content_tag :div, text_div_options do\n content_tag :p, content, :class => \"inner_p\"\n end\n # do it!\n heading + content_tag_\n end\n end\n end",
"def add_box(*boxes)\n boxes = boxes.flatten.compact \n @boxes += boxes.collect do |box|\n box = Rye::Box.new(box, @opts) if box.is_a?(String) \n box.add_keys(@keys)\n box\n end\n self\n end",
"def box_it(array_of_lines, padding = 1, _box_colour = :bc_cyan)\n max_length = max_box_line_length(array_of_lines)\n pad_string = \"\\s\" * padding\n\n box_lines = [\n # Set the top box line\n \"#{BOX_TOP_LEFT}#{BOX_HORIZONTAL_LINE * (max_length + (padding + 1))}#{BOX_TOP_RIGHT}\"\n ]\n\n array_of_lines.each do |line|\n line_length = line.sanitize.length\n box_lines << \"#{BOX_SIDE}#{pad_string}\" + line.to_s + \"#{\"\\s\" * (max_length - line_length)}#{pad_string}#{BOX_SIDE}\"\n end\n\n # Set the bottom box line\n box_lines << \"#{BOX_BOTTOM_LEFT}#{BOX_HORIZONTAL_LINE * (max_length + (padding + 1))}#{BOX_BOTTOM_RIGHT}\"\n box_lines\n end",
"def create_boxes\n unless @children.nil?\n child_boxes = []\n\n children.each { |child| child_boxes << BoxBuilder.new(child).create_boxes }\n\n @content = if child_boxes.length > 1 && direction == 'horizontal'\n BoxBuilder.merge_boxes(*child_boxes)\n else\n child_boxes.join(\"\\n\")\n end\n end\n\n @content = make_box(@content)\n end",
"def compile_all_boxes\n boxes={}\n row=0\n col=0\n i=1\n while row<8\n while col<8\n boxes[\"box_#{i}\"] = compile_box(row, col)\n i+=1\n col+=3\n end\n col=0\n # i+=1\n row+=3\n end\n boxes\n end",
"def create_pokemon_text_boxes\n @pkm_text_boxes = []\n $actors.each do |pkm|\n @pkm_text_boxes << Pokemon_Text_Box.new(@viewport, pkm)\n end\n end",
"def box msgs, box_char=@box_char, box_size=@box_size\n self.liner box_char, box_size\n [msgs].flatten.each do |text|\n text.each_line do |line|\n self.<< '# ' + box_char + ' ' + line.chomp + \"\\n\"\n end\n end\n self.liner box_char, box_size\n end",
"def has_boxes(options = {}, &block)\n # include box controller actions\n self.send(:include, Boxes::Controller::Actions)\n \n # save options and block\n self.boxes_options = options\n raise \"has_boxes: :except and :only are mutualy exclusive\" if options.has_key?(:except) && options.has_key?(:only)\n \n if block_given?\n self.boxes_blocks ||= []\n self.boxes_blocks << block \n end\n \n has_widgets do |root|\n # filter new/remove box calls\n if not [:new_box, :remove_box].include?(action_name.to_sym)\n \n # get back the options\n options = self.class.boxes_options\n \n # filter options\n unless (options[:except] && [options[:except]].flatten.include?(action_name.to_sym)) ||\n (options[:only] && ![options[:only]].flatten.include?(action_name.to_sym))\n \n # record the address\n session[:boxes_address] = \"#{controller_name}##{action_name}\" if not action_name.match(/#{apotomo_event_path(:controller => controller_name).split('/').last}/)\n return if session[:boxes_address].blank? # safe guard, in case of a server restart and the client trying to connect with an ajax call\n \n # Set the @_boxes ivar (used to store stylesheets/javascripts to include)\n self.instance_variable_set(\"@_boxes_content\", {:stylesheets => [], :javascripts => []})\n \n # build widget tree for the address\n Boxes::Core.build_boxes_tree(root, self, Boxes.meta_model.at_address(session[:boxes_address]))\n else\n session[:boxes_address] = nil\n end\n \n end \n \n end # has_widgets\n end",
"def add_boxes( name, number, properties = {} )\n number > 1 or raise \"Number of #{name} boxes #{number} is not positive\"\n ( 1 .. number ).each{ |j| VB_BOXES[ \"#{ name }#{ j }\" ] = properties }\nend",
"def boxes\n @_boxes ||= BoxCollection.new(\n boxes_path,\n hook: method(:hook),\n temp_dir_root: tmp_path)\n end",
"def create_boxes(size)\n\t\t(width**2).times { |i| new_box(i+1)}\n\tend",
"def prettybox(html_options, &proc)\n raise ArgumentError, \"Missing block\" unless block_given?\n concat(tag(\"div\", html_options, true), proc.binding)\n concat(\"<div class=\\\"prettybox_top\\\">\n <div> </div>\n </div><div class=\\\"prettybox_inside\\\">\", proc.binding)\n yield\n concat(\"</div><div class=\\\"prettybox_bot\\\">\n <div> </div>\n </div>\n </div>\", proc.binding)\n end",
"def print_employee_data_box(box_x, box_y)\n\n # Draw box.\n x = box_x\n y = box_y - 0.375\n self.vms_text_box(@data[:employee][:ssn], x, y, 1.25, 0.25, 7, :bold, :center, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:wages][:gross]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:taxes][:federal]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(curr(@data[:wages][:social_security]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:taxes][:social_security]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.125\n self.vms_text_box(@data[:employer][:ein], x, y, 1.25, 0.25, 7, :bold, :center, :center, @data_font, @data_color)\n y -= 0.125\n self.vms_text_box(curr(@data[:wages][:medicare]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:taxes][:medicare]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(\"#{@data[:employer][:name]}\\n#{@data[:employer][:street]}\\n#{@data[:employer][:city]}, #{@data[:employer][:state]} #{@data[:employer][:zip]}\", x + 0.05, y, 3.65, 0.625, 7, :bold, :left, :center, @data_font, @data_color)\n y -= 1\n self.vms_text_box(\"#{@data[:employee][:name]}\\n#{@data[:employee][:street]}\\n#{@data[:employee][:city]}, #{@data[:employee][:state]} #{@data[:employee][:zip]}\", x + 0.05, y, 3.65, 0.625, 7, :bold, :left, :center, @data_font, @data_color)\n y -= 1\n self.vms_text_box(@data[:box_12][:a][:code], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:box_12][:a][:amount]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(\"X\", x + 0.05, y, 0.9, 0.125, 7, :bold, :center, :center, @data_font, @data_color) if @data[:box_13][:statutory]\n self.vms_text_box(@data[:box_12][:b][:code], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:box_12][:b][:amount]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(\"X\", x + 0.05, y, 0.9, 0.125, 7, :bold, :center, :center, @data_font, @data_color) if @data[:box_13][:retirement]\n self.vms_text_box(@data[:box_12][:c][:code], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:box_12][:c][:amount]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.25\n self.vms_text_box(\"X\", x + 0.05, y, 0.9, 0.125, 7, :bold, :center, :center, @data_font, @data_color) if @data[:box_13][:third_party_sick]\n self.vms_text_box(@data[:box_12][:d][:code], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:box_12][:d][:amount]), x + 2.55, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n y -= 0.125\n unless @data[:state][0].blank?\n self.vms_text_box(@data[:state][0][:code], x, y, 0.3, 0.125, 7, :bold, :center, :center, @data_font, @data_color)\n self.vms_text_box(@data[:state][0][:ein], x + 0.35, y, 1, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:state][0][:wages]), x + 1.45, y, 1.1, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:state][0][:tax]), x + 2.65, y, 1.05, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n end\n y -= 0.125\n unless @data[:state][1].blank?\n self.vms_text_box(@data[:state][1][:code], x, y, 0.3, 0.125, 7, :bold, :center, :center, @data_font, @data_color)\n self.vms_text_box(@data[:state][1][:ein], x + 0.35, y, 1, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:state][1][:wages]), x + 1.45, y, 1.1, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:state][1][:tax]), x + 2.65, y, 1.05, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n end\n y -= 0.375\n unless @data[:local][0].blank?\n self.vms_text_box(curr(@data[:local][0][:wages]), x + 0.05, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:local][0][:tax]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(@data[:local][0][:name], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n end\n y -= 0.125\n unless @data[:local][1].blank?\n self.vms_text_box(curr(@data[:local][1][:wages]), x + 0.05, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(curr(@data[:local][1][:tax]), x + 1.3, y, 1.15, 0.125, 7, :bold, :right, :center, @data_font, @data_color)\n self.vms_text_box(@data[:local][1][:name], x + 2.55, y, 1.15, 0.125, 7, :bold, :left, :center, @data_font, @data_color)\n end\n\n end",
"def create_congratulation_text_boxes\n @congrats_text_boxes = []\n $actors.each do |pkm|\n @congrats_text_boxes << Congratulation_Text_Box.new(@viewport, pkm)\n end\n end",
"def generate_square_boxes(row, drawings)\n content_tag :div, :class => \"drawing_section\" do\n 1.upto(row){|item| concat(generate_row(item, row,drawings))}\n end\n end",
"def box(title, options={}, &block)\n\t\tbf = BoxBuilderClass.new(options[:model] || nil)\n\n\t\tif block_given?\n\t\t\tinner = capture(bf, &block)\n\t\telsif options[:model] && options[:fields]\n\t\t\tinner = []\n\n\t\t\tfield_data = options[:model].class.field_data\n\n\t\t\toptions[:fields].each do |field|\n\t\t\t\tfld_data = field_data[field.to_sym]\n\t\t\t\tnext if !fld_data\n\t\t\t\t\n\t\t\t\tlabel = fld_data[:label]\n\t\t\t\t\n\t\t\t\trow_html = options[:model].send(field.to_sym)\n\t\t\t\t\n\t\t\t\t# Don't run h on the value if the model specified the :html attribute to true\n\t\t\t\tif fld_data[:html] == true\n\t\t\t\t\trow_value = row_html\t\t\t\t\t\n\t\t\t\telse\n\t\t\t\t\trow_value = h(row_html).gsub(/\\n/, '<br />')\n\t\t\t\tend\n\t\t\t\tinner << bf.box_row_text(label, row_value)\n\t\t\tend\n\t\t\tinner = inner.join('')\n\t\tend\n\n\t\thtml = '<div class=\"box\">'\n\t\thtml << '<h2>' + h(title) + '</h2>' if title != nil && title != ''\n\t\thtml << inner + '</div>'\n\t\tif bf.fields? || (options[:force] && options[:force] == true)\n\t\t\tif block_given?\n\t\t\t\tconcat(html, block.binding)\n\t\t\telse\n\t\t\t\treturn html\n\t\t\tend\n\t\telse\n\t\t\treturn ''\n\t\tend\n\t\t\n\tend",
"def check_for_boxes\n @boxes = []\n box_parser_hook = 'rpick_box_parser_hook'\n\n box_parser = Proc.new do |server_string|\n if server_string =~ /\\d+ items displayed/\n DownstreamHook.remove(box_parser_hook)\n elsif server_string =~ Dictionary.box_finder_regex\n box_id = $1\n box_noun = $2\n box_name = $3\n @boxes << { id: box_id, noun: box_noun, name: box_name }\n nil\n else\n nil\n end\n end\n\n DownstreamHook.add(box_parser_hook, box_parser)\n fput \"inv full\"\n end",
"def boxes\n @pz.group_by.each_with_index { |val, n| box_id(n) }\n end",
"def build_box\n box = eval(type.sub('Template', '')).new\n box.box_template = self\n box.class.accessible_attributes.each do |attr|\n box.assign_attributes({attr => self.send(attr)}) unless ['type', ''].include? attr\n end\n box\n end"
] | {
"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: 281px;") outer_div_style (same) heading_style (same) height (css style unit, e.g. "100px" or "6em") solid_background (true/false) You can wrap an tag around the box and it will have a:hover CSS enabled, e.g. link_to " do = render_box do "bar" | 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 nil if content.blank? && options[:heading].blank? unless options[:empty]
# Options:
# float_left
outer_div_classes.push("float_left") if options[:float_left] === true
# text_align_center
inner_div_classes.push("text_align_center") if options[:text_align_center] === true
# highlight
inner_div_classes.push("highlight") if options[:highlight] === true
# background_image
background_image = options[:background_image]
# header color
heading_color = options[:heading_color]
inner_div_classes.push("textbox_#{heading_color}") unless heading_color.blank?
# background color
background_color = options[:background_color]
############################################################################
# inner div
############################################################################
inner_div_classes.push("#{background_color}_background") unless background_color.blank?
inner_div_options = { :class => c(inner_div_classes) }
inner_div_styles = []
unless background_image.blank?
# opacity:0.4;filter:alpha(opacity=40);
inner_div_styles.push "background: url(#{background_image}) no-repeat center;"
end
unless options[:height].blank?
inner_div_styles.push "height: #{options[:height]}"
end
unless options[:width].blank?
inner_div_styles.push "width: #{options[:width]}"
end
unless inner_div_styles.blank?
inner_div_options[:style] = c(inner_div_styles)
end
inner_div_options[:style] ||= options[:inner_div_style] # can be overridden
############################################################################
# outer div
############################################################################
outer_div_options = { :class => c(outer_div_classes) }
outer_div_options[:style] = options[:outer_div_style]
############################################################################
# text div
############################################################################
text_div_options = {}
text_div_classes = []
text_div_classes.push "bigfont" if options[:bigfont] === true
text_div_classes.push "solid_background" if options[:solid_background] === true
text_div_options[:class] = c(text_div_classes)
############################################################################
# go render
############################################################################
# let's go, outer div
content_tag :div, outer_div_options do
content_tag :div, inner_div_options do
# heading
heading = ""
heading = content_tag :p, options[:heading], :class => c(heading_classes), :style => options[:heading_style] unless options[:heading].blank?
# text div
content_tag_ = content_tag :div, text_div_options do
content_tag :p, content, :class => "inner_p"
end
# do it!
heading + content_tag_
end
end
end | [
"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 => nil,\n :sidebar_html => nil,\n :orientation => options[:orientation] || :horizontal\n }\n\n # Now render the page and see what happens\n content = widget_content options, &block\n\n # Now we've got tabs and everything else so let's render the rest of the box.\n header = widget_header title, options\n footer = widget_footer options\n\n # And now the box options\n box_options = options.delete(:box) || {}\n \n add_class! box_options, :block\n add_class! box_options, :withsidebar if vertical_tabs?\n\n if options[:small]\n add_class! box_options, :small\n add_class! box_options, options[:small]\n end\n\n # Put it all together\n concat content_tag(:div, header + content + footer, box_options)\n \n # Cleanup\n @widget_options = nil\n @rendering_widget_box = false\n end",
"def prettybox(html_options, &proc)\n raise ArgumentError, \"Missing block\" unless block_given?\n concat(tag(\"div\", html_options, true), proc.binding)\n concat(\"<div class=\\\"prettybox_top\\\">\n <div> </div>\n </div><div class=\\\"prettybox_inside\\\">\", proc.binding)\n yield\n concat(\"</div><div class=\\\"prettybox_bot\\\">\n <div> </div>\n </div>\n </div>\", proc.binding)\n end",
"def link_to_box(content, link, options={})\n box_class = options[:box_class].nil? ? \"fancy\" : options[:box_class]\n elem_id = \"fancylink-#{random_id}\"\n options[:title] = content if options[:title] == :auto\n options[:class] << \" #{box_class}\" unless options[:class].nil?\n options[:class] = \"#{box_class}\" if options[:class].nil?\n options[:class] << \" iframe\" if determine_request(link) == :remote \n options[:id] = elem_id\n link_content = link_to content, link, options\n end",
"def box(title=nil, options={}, &block)\n title = I18n.t(\"admin.boxs.#{title}\", :default => title.to_s.humanize) if title.is_a?(Symbol)\n subtitle = options.delete(:subtitle)\n options[:style] ||= \"width:100%;\"\n options[:start] ||= :open\n concat_content (<<-HTML).gsub(/ {10}/, '')\n <div class=\"#{options[:class]}\" style=\"options[:style]\">\n <div class=\"x-box\">\n <div class=\"x-box-tl\">\n <div class=\"x-box-tr\">\n <div class=\"x-box-tc\"> </div>\n </div>\n </div>\n <div class=\"x-box-ml\">\n <div class=\"x-box-mr\">\n <div class=\"x-box-mc\">\n <div id=\"x-body-title\" style=\"#{\"cursor:pointer\" if options[:collapsible]}\" onclick=\"#{\"Admin.app.collapseBoxes(this);\" if options[:collapsible]}\">\n #{\"<h3 style=\\\"margin-bottom:0px;padding-bottom:0px;float:left;\\\">\"+title+\"</h3>\" if title.present?}\n #{\"<div style=\\\"float:right\\\"><em>\"+subtitle+\"</em></div>\" if subtitle.present?}\n #{\"<br class=\\\"clear\\\" />\" if title.present? || subtitle.present?}\n #{\"<div style=\\\"font-size:0px\\\"> </div>\" if title.present? || subtitle.present?}\n </div>\n <div class=\"#{\"x-box-collapsible\" if options[:collapsible]}\" style=\"width:99%;#{\"display:none\" if options[:collapsible] && options[:start] == :close}\">\n #{\"<div style=\\\"font-size:10px\\\"> </div>\" if title.present? || subtitle.present?}\n #{capture_html(&block)}\n </div>\n </div>\n </div>\n </div>\n <div class=\"x-box-bl\">\n <div class=\"x-box-br\">\n <div class=\"x-box-bc\"> </div>\n </div>\n </div>\n </div>\n </div>\n HTML\n end",
"def box(title=nil, subtitle=nil, options={}, &block)\n options[:style] ||= \"width:100%;\"\n options[:start] ||= :open\n concat <<-HTML\n <div class=\"x-box\" style=\"#{options[:style]}\">\n <div class=\"x-box-tl\">\n <div class=\"x-box-tr\">\n <div class=\"x-box-tc\"> </div>\n </div>\n </div>\n <div class=\"x-box-ml\">\n <div class=\"x-box-mr\">\n <div class=\"x-box-mc\">\n <div id=\"x-body-title\" style=\"#{\"cursor:pointer\" if options[:collapsible]}\" onclick=\"#{\"Backend.app.collapseBoxes(this);\" if options[:collapsible]}\">\n #{\"<h3 style=\\\"margin-bottom:0px;padding-bottom:0px;float:left;\\\">\"+title+\"</h3>\" unless title.blank?}\n #{\"<div style=\\\"float:right\\\"><em>\"+subtitle+\"</em></div>\" unless subtitle.blank?}\n #{\"<br class=\\\"clear\\\" />\" if !title.blank? || !subtitle.blank?}\n #{\"<div style=\\\"font-size:0px\\\"> </div>\" if !title.blank? || !subtitle.blank?}\n </div>\n <div class=\"#{\"x-box-collapsible\" if options[:collapsible]}\" style=\"width:99%;#{\"display:none\" if options[:collapsible] && options[:start] == :close}\">\n #{\"<div style=\\\"font-size:10px\\\"> </div>\" if !title.blank? || !subtitle.blank?}\n #{capture(&block)}\n #{\"<div style=\\\"text-align:right;margin-top:10px\\\">#{submit_tag(I18n.t(\"lipsiadmin.buttons.save\"), :onclick=>\"Backend.app.submitForm()\")}</div>\" if options[:submit]}\n </div>\n </div>\n </div>\n </div>\n <div class=\"x-box-bl\">\n <div class=\"x-box-br\">\n <div class=\"x-box-bc\"> </div>\n </div>\n </div>\n </div>\n HTML\n end",
"def box(title, options={}, &block)\n\t\tbf = BoxBuilderClass.new(options[:model] || nil)\n\n\t\tif block_given?\n\t\t\tinner = capture(bf, &block)\n\t\telsif options[:model] && options[:fields]\n\t\t\tinner = []\n\n\t\t\tfield_data = options[:model].class.field_data\n\n\t\t\toptions[:fields].each do |field|\n\t\t\t\tfld_data = field_data[field.to_sym]\n\t\t\t\tnext if !fld_data\n\t\t\t\t\n\t\t\t\tlabel = fld_data[:label]\n\t\t\t\t\n\t\t\t\trow_html = options[:model].send(field.to_sym)\n\t\t\t\t\n\t\t\t\t# Don't run h on the value if the model specified the :html attribute to true\n\t\t\t\tif fld_data[:html] == true\n\t\t\t\t\trow_value = row_html\t\t\t\t\t\n\t\t\t\telse\n\t\t\t\t\trow_value = h(row_html).gsub(/\\n/, '<br />')\n\t\t\t\tend\n\t\t\t\tinner << bf.box_row_text(label, row_value)\n\t\t\tend\n\t\t\tinner = inner.join('')\n\t\tend\n\n\t\thtml = '<div class=\"box\">'\n\t\thtml << '<h2>' + h(title) + '</h2>' if title != nil && title != ''\n\t\thtml << inner + '</div>'\n\t\tif bf.fields? || (options[:force] && options[:force] == true)\n\t\t\tif block_given?\n\t\t\t\tconcat(html, block.binding)\n\t\t\telse\n\t\t\t\treturn html\n\t\t\tend\n\t\telse\n\t\t\treturn ''\n\t\tend\n\t\t\n\tend",
"def render_boxes(array = [], options = {})\n boxes = \"\"\n\n template = {}\n\n if options[:template].class.to_s.eql?(\"Hash\")\n template = options[:template]\n end\n\n array.each do |individual_options|\n box_options = template\n box_options = template.merge(individual_options) unless individual_options.nil?\n r = render_box(box_options)\n\n unless individual_options[:link].blank?\n r = \"<a href='#{individual_options[:link]}' target='#{individual_options[:link_target]}' class='no_underline render_boxes'>#{r}</a>\"\n end\n\n boxes += r unless r.blank?\n end\n\n boxes_div = content_tag :div, boxes, :class => \"textboxes\", :style => options[:textboxes_style]\n\n clear_both_ = \"\"\n\n unless options[:noclear] === true\n clear_both_ = clear_both\n end\n\n boxes_div + clear_both_\n end",
"def ebox(text:, x_pos:, y_pos:, width:, height:, title: '')\n puts %(\n <rect\n x=\"#{x_pos}\" y=\"#{y_pos}\" width=\"#{width}\" height=\"#{height}\"\n style=\"fill: #{color text}; stroke: black;\">\n <title>#{title}</title>\n </rect>\n )\nend",
"def box\n require 'parsers/abstract/box_parser'\n add_parser(BoxParser.new)\n end",
"def cell(options = {}, &block)\n cont = nil\n width = options[:width] || space_left || 100\n height = options[:height] || pdf.font_height + padding\n new_box_y = options.delete(:new_y) || y\n if x + width > left_base_margin + self.width\n self.y = new_box_y = lower_limit\n self.x = left_base_margin\n self.lower_limit = lower_limit - height\n end\n original_x = self.x\n if shade_color = options[:shaded] \n \n callcc {|continuation| cont = continuation }\n if @shade_height\n self.x = original_x\n if shade_color.is_a?(Symbol)\n shade_color = \"Color::RGB::#{shade_color.to_s.camelize}\".constantize\n else\n shade_color = Color::RGB::Grey90\n end\n pdf.fill_color! shade_color\n pdf.rectangle(self.x,new_box_y, width, @shade_height).fill \n pdf.fill_color! Color::RGB::Black \n cont = nil \n @shade_height = nil \n end\n end\n \n box = Box.new(pdf, x, new_box_y, width, height, self, options)\n self.x, maybe_limit = box.evaluate(&block)\n self.lower_limit = maybe_limit if maybe_limit < lower_limit\n if cont\n @shade_height = self.lower_limit - new_box_y\n cont.call\n end\n end",
"def colored_box(box_text, options={})\n options = { :fill_color => DARK_GRAY,\n :stroke_color => nil,\n :text_color => LIGHT_GRAY,\n :leading => LEADING\n }.merge(options)\n\n register_fonts\n text_options = { :leading => options[:leading], \n :fallback_fonts => [\"Hwkt\"]\n }\n\n box_height = height_of_formatted(box_text, text_options)\n\n bounding_box([INNER_MARGIN + RHYTHM, cursor],\n :width => bounds.width - (INNER_MARGIN+RHYTHM)*2) do\n\n fill_color options[:fill_color]\n stroke_color options[:stroke_color] || options[:fill_color]\n fill_and_stroke_rounded_rectangle(\n [bounds.left - RHYTHM, cursor],\n bounds.left + bounds.right + RHYTHM*2,\n box_height + RHYTHM*2,\n 5\n )\n fill_color BLACK\n stroke_color BLACK\n\n pad(RHYTHM) do\n formatted_text(box_text, text_options)\n end\n end\n\n move_down(RHYTHM*2)\n end",
"def draw_box\n if @box == :border\n @window.box 0,0\n elsif @box\n @window.attron(Ncurses.COLOR_PAIR($normalcolor) | Ncurses::A_REVERSE)\n\n # 2016-01-14 - replacing 1 with space since junk is showing up in some cases.\n space_char = \" \".codepoints.first\n #@window.mvhline 0,0,1,@width\n @window.mvhline 0,0,space_char,@width\n @window.printstring 0,0,@title, $normalcolor #, 'normal' if @title\n @window.attroff(Ncurses.COLOR_PAIR($normalcolor) | Ncurses::A_REVERSE)\n else\n #@window.printstring 0,0,@title, $normalcolor, 'reverse' if @title\n title @title\n end\n end",
"def rounded_box(title, options = {}, &block)\n block_to_partial('common/rounded_box', options.merge(:title => title), &block)\n end",
"def draw_box(x, y, w, h, options = {})\n options[:border] ||= 1\n options[:border_color] ||= RFPDF::COLOR_PALETTE[:black]\n options[:border_width] ||= 0.5\n options[:fill] ||= 1\n options[:fill_color] ||= RFPDF::COLOR_PALETTE[:white]\n options[:fill_colorspace] ||= :rgb\n SetLineWidth(options[:border_width])\n set_draw_color_a(options[:border_color])\n set_fill_color_a(options[:fill_color], options[:fill_colorspace])\n fd = \"\"\n fd = \"D\" if options[:border] == 1\n fd += \"F\" if options[:fill] == 1\n Rect(x, y, w, h, fd)\n end",
"def content_box # :doc:\n \t@browser.div(:class => \"content-box\")\n end",
"def content(options={}, &block)\n raise ArgumentError, \"Missing block\" unless block_given?\n\n content_tag(:div, options) do\n capture(&block)\n end\n end",
"def rounded_titled_box(title, type, options = {}, &block)\n block_to_partial('shared/rounded_titled_box', options.merge(:title => title, :type => type), &block)\n end",
"def colored_box(box_text, options={})\n options = { :fill_color => DARK_GRAY,\n :stroke_color => nil,\n :text_color => LIGHT_GRAY,\n :leading => LEADING\n }.merge(options)\n\n \n text_options = { :leading => options[:leading], \n :fallback_fonts => [\"Helvetica\", \"Kai\"]\n }\n\n box_height = height_of_formatted(box_text, text_options)\n\n bounding_box([INNER_MARGIN + RHYTHM, cursor],\n :width => bounds.width - (INNER_MARGIN+RHYTHM)*2) do\n\n fill_color options[:fill_color]\n stroke_color options[:stroke_color] || options[:fill_color]\n fill_and_stroke_rounded_rectangle(\n [bounds.left - RHYTHM, cursor],\n bounds.left + bounds.right + RHYTHM*2,\n box_height + RHYTHM*2,\n 5\n )\n fill_color BLACK\n stroke_color BLACK\n\n pad(RHYTHM) do\n formatted_text(box_text, text_options)\n end\n end\n\n move_down(RHYTHM*2)\n end",
"def boxview_link_for_object(o, options={}, link_options={})\n data = o.boxview_data().merge(options)\n data[:text] = data[:title] if data[:text].nil?\n data[:action] ||= \"show\"\n url = data[:url].blank? ? url_for(:controller => data[:controller], :action => data[:action], :id => o.id) : data[:url]\n boxview_link(url, data[:text], data[:title], data[:res_id], data[:box_type], link_options)\n end"
] | {
"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_cursor\n end",
"def set_selection(*args)\n return if args.empty?\n\n if (row_col_array = row_col_notation(args.first))\n row_first, col_first, row_last, col_last = row_col_array\n else\n row_first, col_first, row_last, col_last = args\n end\n\n active_cell = xl_rowcol_to_cell(row_first, col_first)\n\n if row_last # Range selection.\n # Swap last row/col for first row/col as necessary\n row_first, row_last = row_last, row_first if row_first > row_last\n col_first, col_last = col_last, col_first if col_first > col_last\n\n sqref = xl_range(row_first, row_last, col_first, col_last)\n else # Single cell selection.\n sqref = active_cell\n end\n\n # Selection isn't set for cell A1.\n return if sqref == 'A1'\n\n @selections = [[nil, active_cell, sqref]]\n end",
"def set_selection(*args)\n # Check for a cell reference in A1 notation and substitute row and column\n if args[0] =~ /^\\D/\n args = substitute_cellref(*args)\n end\n @selection = args\n end",
"def select=(value)\n @select = value\n end",
"def set_selected(sel)\n @column.numItems.times do |i|\n if sel.include?(i)\n @column.selectItem(i)\n else\n @column.deselectItem(i)\n end\n end\n end",
"def set_Select(value)\n set_input(\"Select\", value)\n end",
"def choice=(value)\n @choice = value\n end",
"def selections=(strings)\n @selections = strings\n if @selections.empty?\n self.text = nil\n else\n self.text = @selections[0]\n end\n end",
"def selected=(value)\n @obfuscator.visible = !value\n set_position(value ? 147 : 163, y)\n end",
"def set_selection(objects_hierarchy)\n @selection.set_value(objects_hierarchy)\n end",
"def selection\n\t\t\t$ruvim.editor.selection\n\t\tend",
"def selection\n @selection ||=\n @main.resolver.dup.selection(:cmd_opts => cmd_opts)\n end",
"def select_case\n\t\t@selected = true\n\tend",
"def selection(question, choices)\n\t\t@prompt.select(question, choices)\n\tend",
"def selected=(v)\n @selected = v\n update_background\n @item_sprite.sy = v ? 1 : 0\n @item_text.load_color(v ? 9 : 0)\n end",
"def initialize\n @selection\n end",
"def execute_selection(sel)\r\n method_sym = sel.name.to_sym\r\n values = SelectionAPI.ordered_parameter_values(self,method_sym,sel.parameters) \r\n self.send(method_sym, *values)\r\n end"
] | {
"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",
"def set_title_locally(title)\n @title = title\n end",
"def title=(new_title = nil)\n @info[:Title] = new_title\n end",
"def SetTitle(title)\n #Title of document\n @title = title\n end",
"def setTitle(title)\n if title\n DOM.setAttribute(@element, \"title\", title)\n else\n DOM.removeAttribute(@element, \"title\")\n end\n end",
"def set_SpreadsheetTitle(value)\n set_input(\"SpreadsheetTitle\", value)\n end",
"def title=(title)\n client.update_issue(repository, number, title: title) if title != @title\n @title = title\n end",
"def set_title(iTitle)\n puts \"==== #{iTitle} ... ====\"\n end",
"def title=(title)\n @title = title\n @window.title = @title\n end",
"def title_name(title_name)\n @title = title_name\n end",
"def title(title)\n @schema[:title] = title\n end",
"def set_title\n @title = 'Gene M. Angelo, Jr.'\n end",
"def title=(title)\n Element.attr self, 'title', title\n end",
"def title=(value)\n super\n self.node.title = value\n end",
"def title=(title)\n if not (self.type == :link || self.type == :image)\n raise NodeError, \"can't set title for non-link or image\"\n end\n if !title.kind_of?(String)\n raise NodeError, \"title must be a String\"\n end\n # Make our own copy so ruby won't garbage-collect it:\n c_title = FFI::MemoryPointer.from_string(title)\n res = CMark.node_set_title(@pointer, c_title)\n if res == 0 then raise NodeError, \"could not set header level\" end\n end"
] | {
"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 @url = value\n set_integration_type\n @url\n end",
"def set_url(url)\n end",
"def set_URLSource(value)\n set_input(\"URLSource\", value)\n end",
"def url=(value)\n if value.nil?\n @url = nil\n else\n @url = Addressable::URI.parse(value)\n @url.path << '/' unless @url.path.end_with?('/')\n end\n end",
"def set_ImageURL(value)\n set_input(\"ImageURL\", value)\n end",
"def url=(new_url)\n @data = nil\n @url = new_url\n end",
"def url=(_url)\n @url = _url.sub(/(^https?:\\/)([^\\/])/, '\\1/\\2')\n end",
"def url=(url)\n @url = url\n @connection = nil\n end",
"def url=(url)\n if not (self.type == :link || self.type == :image)\n raise NodeError, \"can't set URL for non-link or image\"\n end\n if !url.kind_of?(String)\n raise NodeError, \"url must be a String\"\n end\n # Make our own copy so ruby won't garbage-collect it:\n c_url = FFI::MemoryPointer.from_string(url)\n res = CMark.node_set_url(@pointer, c_url)\n if res == 0 then raise NodeError, \"could not set header level\" end\n end",
"def endpoint_url=(url)\n @accept_url = @decline_url = @exception_url = @cancel_url = url\n end",
"def set_url\n @url = Url.find_by_key(url_param)\n end",
"def url!(url=nil)\n url.kind_of?(String) ? @session.chanserv.set(self.name, :url, url) : @session.chanserv.set(self.name, :url)\n end",
"def url(url)\n self.default_url = url\n end",
"def set_url(page_url)\n @url = page_url.to_s\n end",
"def url(url)\n @item.url = url.to_s\n self\n end"
] | {
"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_link\n # @subdomain = request.subdomain\n # @site = Site.where(subdomain: request.subdomain).first.user_id\n # @user = User.where(id: @site).first\n if user_signed_in? && @user.id == current_user.id\n html = '<li>' + (link_to '<i class=\"fa fa-cog\"></i> Admin'.html_safe, dashboard_path, target: \"_blank\") + '</li>'\n html.html_safe\n end\n end",
"def log_out_admin\n session.delete(:admin_id)\n @current_admin = nil\n end",
"def logout\n @_current_user = session[:user_id] = nil\n redirect_to admin_login_path, :notice => t('admin.session.notice.logout')\n end",
"def logout\n click_link \"Logout\"\n end",
"def logging_out_as_admin?\n session[:logged_in_with_admin_token]\n end",
"def members_logout\r\n\t@title = \"Members Logout\"\r\n end",
"def admin_user\n redirect_to(root_path) unless is_admin?\n end",
"def require_logout\n if session && !session[:user_id].blank?\n flash[:error] = \"The page you're trying to access is only available to logged out users.\"\n redirect_to dashboard_path and return\n end\n end",
"def admin_user\n redirect_to(news_index_path) unless is_admin?\n end",
"def logout\n self.logoutlink.click\n end",
"def show\n\t\tredirect_if_not_logged_in_admin\n\t\tcurrent_admin\n\tend",
"def admin_panel\n\tpartial 'engine/administrator_panel' if logged_in?('roots')\n end",
"def log_in_or_log_out_link\n if current_user\n link_to \"Logout\", user_session_path, :method => :delete\n else\n link_to 'Log in', new_user_session_path, :class=>\"login\"\n end \n end",
"def admin_user\n redirect_to 'home' unless current_user.admin?\n end",
"def check_logged_out\n if session[:authenticate] == true\n render home_page_index_path\n end\n end",
"def admin_signin_status\n unless user_signed_in? && is_admin?\n redirect_to root_url\n end\n end"
] | {
"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 other_name == client_ID\n client.puts [0x00, \"Success\"].to_json\n else\n other_client.puts [\"#{client_ID.to_s}: #{msg[1]}\"].to_json\n end\n end\n elsif command == 'DISCONNECT'\n puts sprintf(\"disconnecting user '%s'\", client_ID)\n client.puts [0x00, \"DISCONNECT\"].to_json\n @clients.remove client\n elsif command == 'CLIST'\n client.puts [0x00, \"CLIST\", @clients.keys].to_json\n else # catchall for wrong format\n puts \"unknown message format\"\n client.puts [0xFF].to_json\n end\n }\n puts \"outside listen loop\"\n end",
"def send_to_clients(msg)\n EM.schedule do\n @clients.each do |socket|\n socket.send msg\n end\n end\n end",
"def listen_for_user_messages(username, client)\n loop {\n msg = client.gets.chomp\n # send a braodcast message, a message for all connected users, but not to self\n @connections[:clients].each do |other_name, other_client|\n unless other_name == username\n other_client.puts \"#{username}: #{msg}\"\n end\n end\n }\n end",
"def communicate client_server_id\n\n # every communication channel will have its own connection to the database?\n client = Clients[client_server_id]\n client_actual_id = \"\"\n db = DBCommands.new\n\n while message = client.gets\n\n # every message has the following structure\n # PURPOSE - body, PURPOSE = segment[0]\n segments = message.split ' '\n purpose = segments[0]\n index = segments[1]\n body = segments[2..]\n\n if purpose == 'login'\n client_actual_id = _respond_to_login purpose, index, body, db, client\n\n elsif purpose == 'register'\n client_actual_id = _respond_to_register purpose, index, body, db, client\n\n elsif purpose == 'loadGame'\n\n\n\n end\n\n end\n\n end",
"def send_message message\n message = \"#{message}\\n\"\n puts \"client << #{message}\"\n send_data message\n end",
"def send_message(message)\n client.puts message\n end",
"def client_recv(data)\n send_to_dest data\n end",
"def send_and_receive\n\n reader, writer = IO.pipe\n\n pid = fork do\n writer.close\n\n reader.read\n reader.close\n\n send_messages(*MESSAGES)\n end\n\n Process.detach(pid)\n reader.close\n\n received_messages = [ ]\n check_queue = Queue.new\n listen_queue = Queue.new\n\n listen_for_messages(received_messages, check_queue, listen_queue) do\n writer.puts \"ready\"\n writer.close\n\n wait_for_messages(received_messages, check_queue, listen_queue)\n end\n\nend",
"def listen\n puts \"listen...\"\n EM.run do\n WebSocket::EventMachine::Server.start(host: self.host, port: self.port) do |ws|\n\n puts \"listening\"\n\n # Called when a new message arrives at the server\n #\n ws.onmessage do |message, type|\n puts \"onmessage\"\n\n # Attempt to parse the received data as JSON\n #\n message_json = json_try_parse(message)\n if message_json.nil?\n ws.send({payload: \"invalid message\", status: 400}.to_json, :type => :text)\n ws.close\n else\n\n # Execute the appropriate action based on JSON action\n #\n case message_json[:action].to_sym\n\n # Handle authentication requests by calling the authentication\n # method supplied on server setup\n #\n when :authenticate\n puts \"authentication reuqest\"\n authentication_result = authenticate(message_json[:payload])\n if authentication_result\n add_connection(identifier: authentication_result, connection: ws)\n ws.send({payload: \"authenticated\", status: 200}.to_json, :type => :text)\n else\n ws.send({payload: \"authentication failure\", status: 401}.to_json, :type => :text)\n ws.close\n end\n\n # Handle delivery requests by verifying the auth token supplied\n # then push out the payload to all connected specified clients\n #\n when :deliver\n puts \"deliver\"\n puts message_json\n if message_json[:secret_token] == self.secret_token\n puts \"good token\"\n deliver_to_many(payload: message_json[:payload], identifiers: [message_json[:identifiers]].flatten)\n ws.send({payload: \"payload pushed\", status: 201}.to_json, :type => :text)\n ws.close\n else\n puts \"delivery auth failure\"\n ws.send({payload: \"authentication failure\", status: 401}.to_json, :type => :text)\n ws.close\n end\n\n else\n puts \"invalid request\"\n ws.send({payload: \"invalid action\", status: 405}.to_json, :type => :text)\n ws.close\n end\n\n end\n end\n\n # Cleanup connection lists when a connection is closed\n #\n ws.onclose do\n remove_connection(ws)\n end\n\n end\n end\n end",
"def run\n listen\n broadcast\n loop do\n sleep(10)\n @all_clients.each {|client| client.puts \"Krazy Joe #{KJ_VERBS.sample} #{KJ_POS.sample} #{KJ_NOUNS.sample}!\"} \n end\nend",
"def send_all(message)\n @clients.each do |websocket, client|\n websocket.send message\n end\n puts \"send_all: #{message}\"\n end",
"def serve(io_object)\n # increase the client id for this new client and assign it \n @@client_id += 1\n my_client_id = @@client_id\n io_object.sync = true\n\n puts(\"Client #{@@client_id} attached.\")\n loop do\n # Must have chomp or else readline behaves very oddly (sends \"\\n\" \n # which messes up the user's next <Enter> keypress, which then causes a\n # chain reaction of very odd behavior)\n line = io_object.readline.chomp\n \n # Use a case statement to get the string to pass to io_object.puts\n io_string = case line\n when 'x'\n # 'x' causes the TCPSocket in myclient.rb to quit, so \n # notify us that it's quitting\n puts \"#{my_client_id} has exited.\"\n \"Goodbye!\" # Bid a fond farewell to the TCPSocket\n when /^(t|time)$/ # match \"t\" or \"time\"\n \"The time of day is #{get_time}\"\n when %r{^(f|message/fortune)$} # match \"f\" or \"message/fortune\"\n get_fortune\n # This must be before the /^d.../ regex since otherwise the\n # /^d/ one captures the \"date\" line before this can get to it\n when 'date'\n get_date\n when /^d(.+)/ # the regex captures the filename in $1\n # when sending \"d\" followed by filename (\"dtest.txt\"), respond with\n # content of e.g. test.txt\n # If the file doesn't exist, returns a message saying so.\n filename = $1\n if File.exist?(filename)\n # gsub the newlines because they really screw up readline\n File.read(filename).gsub(\"\\n\", \"<NEWLINE>\")\n else\n \"Error: file #{filename} does not exist.\"\n end\n when %r{^message/joke(?:\\?lang=(.+))?$} # match \"message/joke\" or \"message/joke?lang=...\"\n # The regex captures the lang value in $1\n # Default to english if no lang supplied\n language = $1.nil? ? \"en\" : $1\n get_joke(language)\n else\n # Output to STDOUT first\n puts \"received line #{line}\"\n \"What does #{line} mean anyway?\"\n end\n io_object.puts(io_string)\n end\n end",
"def run\n loop do\n memcached = Memcached.new # each client has its oun cache storage\n new_client = @tcp_Server.accept # when a new client connects to the server\n client_handler_id = rand(999999).to_s\n client_handler = ClientHandler.new(id: client_handler_id, clientSocket: new_client, memcached: memcached)\n @@clients << client_handler\n\n Thread.start(client_handler) do |handler| # open a new thread for each accepted connection\n # Here we inform the client of the connections. It's human made, so can be removed if not needed\n puts \"New connection established! Now #{@@clients.length()} clients :>\"\n puts \"WAITING FOR REQUESTS\"\n handler.send(\"Server: Connection established with Client Handler ID: #{client_handler_id}\")\n handler.send(\"Server: You are the client ##{@@clients.length()}\")\n handler.send(\"Server: You may introduce commands now\")\n listen_requests(handler) # allow communication\n end\n end.join\n end",
"def accept_client\n newsocket = @server.accept # Accept newsocket's connection request\n\n # add newsockets to the list of connected sockets\n @sockets.push(newsocket)\n @lastUpdate.push(Time.now)\n @groupids.push(\"TEMP_ID\")\n \n # Inform the socket that it has connected, then inform all sockets of the new connection\n newsocket.puts(\"You're connected to the Ruby Chat Server! Woohoo\")\n str = \"Client joined #{newsocket.peeraddr[2]}\\n\"\n broadcast(str, newsocket)\n end",
"def event_incoming_chat(client, msg)\nend",
"def serve_clients\n clients_arrive\n say_hello_to_clients\n perform_tasks_asked_by_clients\n while_other_clients_wait_in_line\n say_goodbye_to_clients\n end",
"def dispatch(messages)\n with_connection do |connection|\n connection.write(messages)\n connection.read if messages.last.replyable?\n end\n end",
"def process_messages\n # Check status for all streams, reopen as necessary\n @streams.each { |_, stream| try { stream.keep_alive } }\n\n # Actual processing of incoming messages happens in event callbacks\n # Oбрабатываем пришедшее сообщение в интерфейсах обратного вызова\n @conn.ProcessMessage2(100)\n end",
"def send_client_message(client, message)\n nickname = @connections[client]\n @connections.each_key do |other_client|\n unless other_client == client\n other_client.puts 'M' + @spaces + nickname + ': ' + message\n end\n end\n end"
] | {
"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: :athlete, via: 'account.token', id: 'account.strava_id' end | 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.class_eval str
end
end | [
"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 : \"Account\"\n end",
"def get_logged_in_athlete_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: AthletesApi.get_logged_in_athlete ...\"\n end\n # resource path\n local_var_path = \"/athlete\"\n\n # query parameters\n query_params = {}\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['strava_oauth']\n data, status_code, headers = @api_client.call_api(:GET, local_var_path,\n :header_params => header_params,\n :query_params => query_params,\n :form_params => form_params,\n :body => post_body,\n :auth_names => auth_names,\n :return_type => 'DetailedAthlete')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: AthletesApi#get_logged_in_athlete\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def find_athlete\n @athlete = Athlete.find(params[:athlete_id])\n end",
"def access_token_model\n @access_token_model ||= access_token_class.constantize\n end",
"def associated_class\n self[:class] ||= self[:class_name].constantize\n end",
"def create_athlete\n Athlete.create(user_id: id)\n end",
"def tenant_class\n @tenant_class ||= if self.model.respond_to?(:call)\n self.model.call\n elsif self.model.respond_to?(:constantize)\n self.model.constantize\n else\n self.model\n end\n end",
"def associated_class\n if options[:class_name]\n options[:class_name].constantize\n else\n klass.relative_const_get(attribute.to_s.camelize)\n end\n end",
"def assist\n object.current_class.assists.where(student_id: object.id).first.assist\n end",
"def goodo(attrs = {})\n klass.new({\n api_key: \"api_key\",\n }.merge(attrs))\n end",
"def associated_class\n if options[:class_name]\n options[:class_name].constantize\n else\n klass.relative_const_get(attribute.to_s.singularize.camelize)\n end\n end",
"def model(class_or_scope, options = nil)\n ActiveSupport.on_load(:active_record, yield: true) do\n class_or_scope = class_or_scope.constantize if class_or_scope.is_a?(String)\n options ||= {}\n conditions = options.delete(:conditions)\n\n @ar_scoped = conditions ? class_or_scope.where(conditions) : class_or_scope\n @ar_aggregate = AGGREGATES.find { |key| options.has_key?(key) }\n @ar_column = options.delete(@ar_aggregate)\n raise \"Cannot use multiple aggregates in a single metric\" if AGGREGATES.find { |key| options.has_key?(key) }\n\n @ar_timestamp = options.delete(:timestamp) || :created_at\n @ar_timestamp, @ar_timestamp_table = @ar_timestamp.to_s.split('.').reverse\n @ar_timestamp_table ||= @ar_scoped.table_name\n\n @ar_identity_block = options.delete(:identity)\n\n raise \"Unrecognized options: #{options.keys * ', '}\" unless options.empty?\n\n @ar_scoped.after_create(self)\n extend ActiveRecord\n end\n end",
"def create_oauth_strategy_class(keyword)\n class_name = Warden::OAuth::Utils.camelize(keyword.to_s) \n if self.const_defined?(class_name)\n self.const_get(class_name) \n else\n self.const_set(class_name, Class.new(self))\n end\n end",
"def get\n Ata.get self\n end",
"def user_account_instance\n Account.new\n end",
"def model( *args )\n return nil if self['model'].blank? || self['model']['class'].blank? || self['model']['id'].blank?\n\n self['model']['class'].constantize.find( self['model']['id'], *args )\n end",
"def ability_class\n \"#{self.class.name}Ability\".constantize\n end"
] | {
"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. line test is This" =end | 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.split(\" \")\n puts sentence_array\n sentence_array.each do |l|\n l.reverse!\n end\n sentence_array.join(\" \")\nend",
"def reverse_words_in_a_string(s)\n s.split(' ').reverse.join(' ')\nend",
"def reverseWords(s)\n s.split(\" \").reverse.join(\" \")\nend",
"def reverse_words(string)\n string = string.split\n if (string.length != 0) \n string.each {|x| x.reverse!}\n p string.join' '\n else \n \"\"\n end\nend",
"def reverse_words(str)\n words = str.split(\" \")\n words.each { |word| word.reverse! }\n return words.join(\" \")\nend",
"def reverse_words(string)\n string.split(\"\").reverse.join(\"\").split(\" \").reverse.join(\" \") \nend",
"def reverse_each_word(string)\n string.split\n string.split.collect do |s|\n s.reverse!\n s.split.join(\" \")\n end\n .join(\" \")\nend",
"def reverse_each_word(string)\n separate_words = string.split\n \n reversed_words = separate_words.collect {|word| word.reverse}\n \n p reversed_words.join(\" \")\nend",
"def reverse_each_word(string)\n\tx = string.split(\" \")\n\t x.collect do |y|\n y.reverse\nend.join(\" \")\nend",
"def reverse_each_word(string_sentence)\n array_of_words = string_sentence.split\n\n array_of_words.collect do |word|\n word.reverse\n # binding.pry\n end\n .join(\" \")\nend",
"def reverse_words(string)\n array = string.split(\" \")\n array.map! do |x| x.reverse end\n p array.join(\" \")\nend",
"def reverse_words(string)\n process_array = []\n if string == \"\"\n string\n elsif string.include?(\" \") == false\n string.reverse\n else\n process_array = string.split(\" \")\n process_array.reverse!\n string = process_array.join(\" \")\n string.reverse\n end\nend",
"def reverse_words(word)\n word.split(\" \").map!{|word| word.reverse}.join(\" \")\n\nend",
"def reverse_each_word(string)\n sentence_array = string.split(\" \")\n reversed_array = []\n sentence_array.collect do |string|\n reversed_array << string.reverse\n end\n reversed_array.join(\" \")\nend",
"def reverse_each_word(sentence)\n sentence.split.collect {|word| word.reverse}.join(\" \")\n end",
"def reverse_words(string)\n\tif string == \"\"\n\t\treturn \"\"\n\telsif\n\t\tarray=string.split\n\t\tif array.is_a? Array\n\t\t\tarray.each do |index|\n\t\t\t\tindex.reverse!\n\t\t\tend \n\t\tend \n\treturn array.join(\" \")\n\tend \nend"
] | {
"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\n # two instances for different models cannot be equivalent\n return false unless other.kind_of?(model)\n\n # two instances with different keys cannot be equivalent\n return false if key != other.key\n\n # neither object has changed since loaded, so they are equivalent\n return true if repository == other.repository && !dirty? && !other.dirty?\n\n # get all the loaded and non-loaded properties that are not keys,\n # since the key comparison was performed earlier\n loaded, not_loaded = properties.select { |p| !p.key? }.partition do |property|\n attribute_loaded?(property.name) && other.attribute_loaded?(property.name)\n end\n\n # check all loaded properties, and then all unloaded properties\n (loaded + not_loaded).all? { |p| p.get(self) == p.get(other) }\n end",
"def equality_with_same_attributes?\n left_equality? &&\n right_equality? &&\n same_attribute? &&\n constant_value?\n end",
"def equality_fields\n [:id, :dealership, :expires, :next]\n end",
"def eql?(ent)\n if ent.respond_to? :properties\n self.properties == ent.properties\n else\n false\n end\n end",
"def == other\n return false if size != other.size\n deep_compare @relation_hash, other.relation_hash\n end",
"def ==( other )\n other.kind_of?(Attribute) and other.name==name and other.value==value\n end",
"def persistence_state_equal?( other_object )\n\n objects_are_equal = false\n\n if other_object.is_a?( ::Persistence::Object::Complex::ObjectInstance ) and\n self.class.equal?( other_object.class ) and\n other_object.respond_to?( :persistence_id ) and \n persistence_id == other_object.persistence_id\n \n # test non-atomic attributes for equality\n if objects_are_equal = non_atomic_attribute_readers.empty? or \n objects_are_equal = ( persistence_hash_to_port == other_object.persistence_hash_to_port )\n \n # test atomic attributes for equality\n unless atomic_attribute_readers.empty?\n \n atomic_attribute_readers.each do |this_attribute|\n this_value = __send__( this_attribute )\n this_other_value = other_object.__send__( this_attribute )\n break unless objects_are_equal = ( this_value == this_other_value )\n end\n \n end\n \n end\n \n end\n \n return objects_are_equal\n \n end",
"def ==(other)\n other.is_a?(Her::Model) && attributes == other.attributes\n end",
"def fields_equal?(other_object, *field_names)\n if field_names.empty?\n return self.to_hash == other_object.to_hash\n else\n return field_names.all? do |field|\n self[field] == other_object[field]\n end\n end\n end",
"def same?(model_entity, db_entity)\n return false if model_entity.class != db_entity.class\n\n if model_entity.is_a?(Hash)\n model_entity.each do |k, v|\n return false unless same?(v, db_entity[k])\n end\n return true\n else\n return model_entity == db_entity\n end\n end",
"def identical_by_variables(other)\n Dataset.identifical_by_variables self, other\n end",
"def inequality_with_same_attributes?\n left_inequality? &&\n right_inequality? &&\n same_attribute? &&\n constant_value?\n end",
"def eql?(other)\n return true if equal?(other)\n return false unless self == other\n [:id, :fide_id, :rating, :fide_rating, :title, :gender].each do |m|\n return false if self.send(m) && other.send(m) && self.send(m) != other.send(m)\n end\n true\n end",
"def == other\n self.table == other.table\n end",
"def equivalentValues(other) # JS == operator\n other.is_a?(Object) && unwrap.eql?(other.unwrap)\n end",
"def define_equivalent_method\n respond_to = []\n equivalent = []\n\n keys.each do |key|\n respond_to << \"other.respond_to?(#{key.inspect})\"\n equivalent << \"#{key} == other.#{key}\"\n end\n\n module_eval <<-RUBY, __FILE__, __LINE__ + 1\n def ==(other)\n return true if equal?(other)\n return false unless kind_of?(other.class) || other.kind_of?(self.class)\n #{respond_to.join(' && ')} &&\n #{equivalent.join(' && ')}\n end\n RUBY\n end",
"def eql?(obj)\n (obj.class == model) && (obj.values == @values)\n end"
] | {
"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({group_id: params[:group_id], annotation_id: params[:id]}).first\n ag.destroy\n\n #Return data for the original relationship that the unapproved relationship was based on\n based = AnnotationGroup.find(ag.based_on)\n json based\n end",
"def eliminate_unselected_fields\n if params[:blogging] && type = params[:blogging][:subject_type]\n label = type.to_s.downcase\n params[:blogging][:subject_attributes] = params[:blogging][label.to_sym] || {}\n params[:blogging][:subject_attributes][:id] = params[:blogging][\"#{label}_id\".to_sym]\n params[:blogging][:subject_id] = params[:blogging][\"#{label}_id\".to_sym]\n unless params[:blogging][:subject_attributes][:id] \n params[:blogging][:subject_attributes][:subject_type] = type # passes the type through to build_subject\n end\n end\n bloggable_models.each do |exclude|\n params[:blogging].delete(exclude)\n params[:blogging].delete(\"#{exclude}_id\".to_sym)\n end\n end",
"def lock_down_admin_only_params\n # all this bogus return false stuff is to prevent double render errors in some circumstances\n return if check_superuser_restricted_params == false\n return if check_may_set_user_id == false\n\n nil if check_may_set_payment_id == false\n end",
"def remove_req_tree\n unless current_user.type == 'Admin'\n if params[:data]\n if params[:data][:attributes][:tree]\n Rails.logger.debug(\"COURSE: \".green + \"Removed tree param\")\n params[:data][:attributes].delete(:tree)\n end\n end\n end\n end",
"def product_params_without_option\n product_params.to_h.tap do |product_param|\n product_param.delete('options_attributes')\n end\n end",
"def delete_unknown\n @unknown_fields =\n @form.keys - @required_fields - @optional_fields - @require_some_fields\n @unknown_fields.each {|field| @form.delete(field)}\n end",
"def to_modify_unparse_params(&block_)\n @unparse_params_modifier = block_\n end",
"def remove_year_from_params\n if params_contains_user_attr :year\n Rails.logger.warn \"WARNING: Removing protected attribute: year\"\n params[:user].delete :year\n end\n end",
"def strip_unnecessary_params\n params[:donation].delete(:dropoff_location_id) unless params[:donation][:source] == Donation::SOURCES[:dropoff]\n params[:donation].delete(:diaper_drive_participant_id) unless params[:donation][:source] == Donation::SOURCES[:diaper_drive]\n params\n end",
"def remove_all_fields\n end",
"def reset_general_params!(aParams)\n aParams.delete(\"facet.field\")\n aParams.delete(\"page\")\n return aParams\n end",
"def remove_group_popup_empty_fields(group_params)\n group_params[:same_as] = remove_empty_array_fields2(group_params[:same_as])\n group_params[:related_authority] = remove_empty_array_fields2(group_params[:related_authority])\n group_params[:altlabel] = remove_empty_array_fields2(group_params[:altlabel])\n group_params[:note] = remove_empty_array_fields2(group_params[:note])\n rescue => e\n log_error(__method__, __FILE__, e)\n raise\n end",
"def remove_options\n self.route_additional_field_options.each{|o| o.mark_for_destruction} if self.input_type==\"text\"\n end",
"def filter_fields\n\t \n\t \tremove_attribute(:version)\n\t \tremove_attribute(:op_success)\n\t \tattributes\n\n\t \t\n\t end",
"def unban_package(name)\n\t\t\tsoftware_command \"unban_package\",:name => name\n\t\tend"
] | {
"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_name; add_name_extra_to(instrument[:instrument_name]); end",
"def set_instrument\n self.instrument_id = self.code_list.instrument_id\n end",
"def use_instrument(instrument)\n instruments.push(instrument)\n end",
"def show_name=(show_name)\n if `osascript -e 'tell application \\\"iTunes\\\" to set show of file track id #{@id} to \\\"#{show_name}\\\"'` \n @show_name = show_name\n else\n raise \"could not set 'show name' for video\"\n end\n end",
"def set_label(val, instrument)\n self.category = Category.find_by label: val, instrument_id: instrument.id\n if self.category.nil?\n self.category = Category.create label: val, instrument: instrument\n end\n end",
"def instrument(instrument)\n @instruments << instrument\n end",
"def call_recording_display_name=(value)\n @call_recording_display_name = value\n end",
"def instr_desc\n instr_data = $instruments[values]\n\n if instr_data == nil\n return \"- Unknown instrument\"\n end\n\n result = \"\"\n\n for possible in instr_data\n result += \"- Instrument ##{possible[:instrument]} \" \\\n + \"(#{possible[:name]}) \" \\\n + \"v#{possible[:voice]}\\n\"\n end\n\n result\n end",
"def setup_instrument_software(instrument, op = nil)\n open_software(instrument)\n #select_plate_type(instrument)\n get_sample_type_rc_list_hash(instrument).each do |sample_type_name, rc_list|\n if ALLOWABLE_FC_SAMPLETYPES.include? sample_type_name\n if op != nil\n test_group_label = \"#{instrument.measurement_item}-#{op.input('When to Measure? (24hr)')}\"\n else\n test_group_label = \"#{instrument.measurement_item}\"\n end\n\n show do\n title \"Add Group\"\n note \"In the Attune software add a test group and label it #{test_group_label}\"\n end\n\n collection = collection_from(instrument.measurement_item)\n show do\n title \"Add Samples to Plan\"\n separator\n note \"In the Attune software add #{rc_list.length} samples in group #{test_group_label}.\"\n note 'Rename samples per table below'\n table highlight_alpha_rc(collection, rc_list, check: false)\n end\n apply_settings(instrument: instrument)\n end\n end\n end",
"def display_name_set(name)\n display_name.set(name)\n end",
"def setNameSound _obj, _args\n \"_obj setNameSound _args;\" \n end",
"def change_artist(new_song_artist)\n @artist = new_song_artist\n end",
"def display_name=(value)\n @display_name = value\n end",
"def setup_instrument_calibration(instrument)\n open_software(instrument)\n select_plate_type(instrument)\n tube_rack = get_tube_rack \n show do\n title \"Select Wells\"\n separator\n note \"Select the following location of the optical particals #{instrument.measurement_item.object_type.name} #{instrument.measurement_item}.\"\n table highlight_alpha_rc(tube_rack, [[0,0]]) {|r,c| \"#\"}\n note 'After checking the wells on the screen continue to the next step.'\n end\n tube_rack.mark_as_deleted\n apply_settings(instrument: instrument)\n end",
"def setup_instrument_calibration(instrument)\n open_software(instrument)\n select_plate_type(instrument)\n tube_rack = get_tube_rack \n show do\n title \"Select Wells #go to FlowCytometrySoftware library Attune module to customize this step\"\n separator\n note \"Select the following location of the optical particals #{instrument.measurement_item.object_type.name} #{instrument.measurement_item}.\"\n table highlight_alpha_rc(tube_rack, [[0,0]]) {|r,c| \"#\"}\n note 'After checking the wells on the screen continue to the next step.'\n end\n tube_rack.mark_as_deleted\n apply_settings(instrument: instrument)\n end",
"def set_channel(i)\n @tv.channel = i\n end",
"def report_name=(value)\n @report_name = value\n end"
] | {
"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 # Setup virtual machine name\n config.vm.host_name = vm_config['name']\n\n # Set timeout\n config.vm.boot_timeout = vm_config['boot_timeout']\n\n # [Optional] Set disk size\n # Note: vagrant plugin install vagrant-disksize\n config.disksize.size = vm_config['disk_size']\n\n if Vagrant.has_plugin?(\"vagrant-vbguest\")\n config.vbguest.auto_update = false\n end\nend",
"def configure(&block)\n Fastfood::Configuration.instance_eval( &block )\n end",
"def configure\n puts 'Configuring Vault'\n vault = secure_vault\n vault.sys.mount('testing', 'kv', 'Mount used for testing purposes only')\n vault.logical.write('testing/test', value: @random_string)\n end",
"def configure\n yield Prov.configuration\n end",
"def configure( &block )\n yield configuration\n\n run_engine!\n end",
"def configure\n settings.use(:commandline)\n settings.description = description if description\n u = usage\n settings.define_singleton_method(:usage){ u } if u\n Wukong.configure_plugins(settings, program_name)\n end",
"def config_vm(config, node_name, node_conf)\n\t\tconfig.vm.define vm_name = node_name do |config|\n\t\t\tconfig.vm.network :private_network, ip: node_conf['ip']\n\t\t\tconfig.vm.hostname = node_name\n\t\t\n\t\t\t# configures all forwarding ports in JSON array\n\t\t\tports = node_conf['ports']\n\t\t\tports.each do |port|\n\t\t\t\tconfig.vm.network :forwarded_port,\n\t\t\t\t\thost:\tport['host'],\n\t\t\t\t\tguest: \tport['guest'],\n\t\t\t\t\tid:\t\tport['id']\n\t\t\tend\n\n\t\t\tconfig.vm.provider :virtualbox do |vb|\n\t\t\t\tif node_conf['memory']\n\t\t\t\t\tvb.memory = node_conf['memory']\n\t\t\t\tend\n\t\t\t\tif node_conf['cpu']\n\t\t\t\t\tvb.cpus = node_conf['cpu']\n\t\t\t\tend\n\t\t\tend\n\n\t\t\t# enable NFS for sharing the host machine into the coreos-vagrant VM\n\t\t\tconfig.vm.synced_folder \".\", \"/home/core/share\", id: \"core\", :nfs => true, :mount_options => ['nolock,vers=3,udp,noatime']\n\t\t\t# note: many example application containers would require nfs volume to be \"no_root_squash\"\n\t\t\t# e.g. chown on app dir is required.\n\t\t\t# on mac os no_root_squash is not supported, instead using -maproot=0:0\n\t\t\tconfig.nfs.map_uid = 0\n\t\t\tconfig.nfs.map_gid = 0\n\t\t\tconfig.vm.provision :shell, \\\n\t\t\t\t:inline => \"ln -sf /home/core/share/apps /var/lib/ && ln -sf /home/core/share/apps-data /var/lib/\", \\\n\t\t\t\t:privileged => true\n\n\t\t\t# To make the self-signed certs truesed for clients in docker, update the system bundled certs with the test rootCA.\n\t\t\t# This should be done before docker.service starts so it can pick up the testing rootCA.\n\t\t\tconfig.vm.provision :file, :source => \"~/.vagrant.d/insecure_private_key\", :destination => \"/home/core/.ssh/id_rsa_fleetui\"\n # Copy in vagrant private key so it can be used by fleetui container to check cluster status\n\t\t\tconfig.vm.provision :file, :source => \"#{TEST_ROOT_CA_PATH}\", :destination => \"/tmp/XXX-Dockerage.pem\"\n\t\t\tconfig.vm.provision :shell, \\\n\t\t\t\t:inline => \"cd /etc/ssl/certs && ([[ -f XXX-Dockerage.pem ]] || (mv /tmp/XXX-Dockerage.pem . && update-ca-certificates))\", \\\n\t\t\t\t:privileged => true\n\n\t\t\t# enable ssh-agent forwarding in coreos-vagrant VM.\n\t\t\tconfig.vm.provision :shell, \\\n\t\t\t\t:inline => \"echo -e 'Host #{node_conf['subnet']}.* *.#{node_conf['dns_domain']}\\n StrictHostKeyChecking no\\n ForwardAgent yes' > .ssh/config; chmod 600 .ssh/config\", \\\n\t\t\t\t:privileged => false\n\n\t\t\tcloud_init = node_conf['cloud_init']\n\t\t\tif cloud_init then\n\t\t\t\tcloud_init.each do | cnf |\n\t\t\t\t\tcnf_path = File.join(CLOUD_INIT_PATH, \"#{cnf}\")\n\t\t\t\t\tif File.exist?(cnf_path) then\n\t\t\t\t\t\tconfig.vm.provision :file, :source => cnf_path, :destination => \"/tmp/cloud-init/#{cnf}\"\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tconfig.vm.provision \\\n\t\t\t\t\t:shell, \n\t\t\t\t\t:inline => \"cat /tmp/cloud-init/* > /tmp/vagrantfile-user-data; mv /tmp/vagrantfile-user-data /var/lib/coreos-vagrant/\", \\\n\t\t\t\t\t:privileged => true\t\n\t\t\tend\n\t\tend\n\tend",
"def configure\n send_command \"--configure\"\n end",
"def default_config\n UvConfiguration.new\n end",
"def configure(&blk)\n bot.configure(&blk)\n end",
"def configure_plugin_vagrant_vbguest(\n plugin_info = nil,\n auto_update_default = false,\n no_remote_default = true,\n iso_path_default = nil\n)\n\n Vagrant.configure(VAGRANT_VERSION) do |config|\n\n config.vbguest.auto_update = [\n validate_value(lookup_values_yaml(plugin_info, ['settings', 'auto_update'])),\n auto_update_default\n ].find { |i| !i.nil? }\n\n config.vbguest.no_remote = [\n validate_value(lookup_values_yaml(plugin_info, ['settings', 'no_remote'])),\n no_remote_default\n ].find { |i| !i.nil? }\n\n iso_path = [\n lookup_values_yaml(plugin_info, ['settings', 'iso_path']),\n iso_path_default\n ].find { |i| !i.nil? }\n config.vbguest.iso_path = iso_path if iso_path\n\n end\nend",
"def default_config\n UvConfiguration.new\n end",
"def configure(&block)\n @configure_blocks ||= []\n @configure_blocks << block\n end",
"def configure(&block)\n config.rom = Configuration.new unless config.respond_to?(:rom)\n\n if block.arity == 1\n block.call(config.rom)\n else\n super\n end\n end",
"def setup_config\n # To be Extended\n end",
"def configure_libvirt\n log.info \"Setting up libvirt network and storage\"\n Cheetah.run %w(sudo virsh net-autostart default)\n unless libvirt_pool_default_defined?\n Cheetah.run %w(sudo virsh pool-define-as default dir - - - - /var/lib/libvirt/images)\n end\n Cheetah.run %w(sudo virsh pool-autostart default)\n Cheetah.run %w(sudo systemctl reload-or-restart libvirtd)\n end",
"def setup_config(config=nil, &block)\n @config = config || ConfigStruct.block_to_hash(block)\n end",
"def configure\n cfg = euresource_config\n Euresource.configure do\n config.stage_defaults do |defaults|\n defaults.mauth(cfg['mauth_url']) do |mauth_config|\n mauth_config.app_uuid cfg['app_uuid']\n mauth_config.private_key_file cfg['key_file']\n\n # Only set if you want different logger for MAuth\n mauth_config.logger cfg['mauth_logger'].constantize.new if cfg['mauth_logger']\n end\n defaults.use MAuth::Faraday::RequestSigner, defaults.mauth_config\n\n # Turns on develop mode for local development, which adds extra logging and forces API deployments to Eureka\n # without having to delete prior versions of an API document for local development while making changes to an\n # API document.\n defaults.develop_mode false\n\n # Rails logger will be used for all logging if this is not set in Rails.\n defaults.logger EuresourceLogger.new if cfg['eureka_logger']\n\n #Un-comment this option if you want to skip authenticating eureka responses\n defaults.mauth_authenticate_responses cfg['authenticate_responses']\n\n defaults.use FaradayMiddleware::RackCompatible, CacheComplainer::Complainer\n end\n\n # This applies all default from above to configure a Eureka::Client instance for a specific eureka stage\n config.stage(cfg['eureka_url'], cfg['stage']) do |builder|\n builder.deployment_base_uri 'http://localhost:3000'\n builder.faraday_adapter :typhoeus\n end\n end\n end",
"def configure!\n yield self\n setup\n end"
] | {
"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 register_ui thing\n @uis << thing\n end",
"def by_name(name)\n Vedeu.timer(\"Refreshing interface: '#{name}'\") do\n Vedeu.buffers.by_name(name).render\n end\n end",
"def register_dynamic_view(name, content, id = nil)\n id.nil? ? register_view(Hooks::get_caller, name, {:content => content}) : register_view(Hooks::get_caller, name, {:content => content}, id)\n end",
"def register_view(caller, name, options, id = rand(1000000).to_s)\n raise \"Unable to register view for unrecognized plugin! (#{caller})\" if (plugin = Hooks::get_plugin_by_caller(caller)).nil?\n raise \"View hook #{name} is not available!\" unless available_hooks.include?(name)\n @view_hooks ||= {}\n @view_hooks[plugin.id] ||= []\n @view_hooks[plugin.id] << {:id => id, :name => name}.merge(options)\n end",
"def register_outputter(name, klass, method_name)\n outputters[name] = [klass, method_name]\n end",
"def configure_interface(name, commands)\n commands = [*commands]\n commands.insert(0, \"interface #{name}\")\n configure commands\n end",
"def register_command(notification_name, command_class)\n @view.register_observer( notification_name, Observer.new(:execute_command, self) );\n @command_map[notification_name] = command_class\n end",
"def add_output(name, handler)\n @outputs[name] = handler\n end",
"def interface(name, &block)\n raise Vedeu::Error::MissingRequired unless name\n raise Vedeu::Error::RequiresBlock unless block_given?\n\n attributes = { client: client(&block), name: name }\n\n interface = Vedeu::Interfaces::Interface\n .build(attributes, &block)\n .store\n\n add_buffers!(name)\n add_cursor!(name)\n add_editor!(name) if interface.editable?\n add_focusable!(name)\n add_keymap!(name)\n\n interface\n end",
"def register(name, description, clazz)\n renderers << [name, description, clazz]\n (class << self; self; end).\n send(:define_method, name) do |*args|\n clazz.new(*args)\n end\n end",
"def interface_name(arg = nil)\n set_or_return(:interface_name, arg, kind_of: String)\n end",
"def output name, &block\n name = name.to_sym\n @outputs << name\n @output_blocks[name] = block if block\n end",
"def view(name, &block)\n Brief.views[name.to_sym] = block\n end",
"def add_output(type, *args)\n class_name = type.to_s.capitalize\n klass = Drone::Interfaces.const_get(class_name)\n @output_modules << klass.new(*args)\n end",
"def view(name, &block)\n @views[name] = block\n end",
"def add(interface_name)\n model.add(interface_name)\n end",
"def defining_interface\n intf = super\n if intf.is_a?(InterfaceVisitor) # not for value types\n # make sure to do this only once\n intf.class_eval { include AmiNames } unless intf.singleton_class.included_modules.include?(AmiNames)\n end\n intf\n end"
] | {
"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].each { |handler| handler.call(*args) }\n end",
"def call_event name, *args\n name = name.to_s\n if events = self.__classx_pluggable_events_of[name]\n events.map do |event|\n event[:plugin].__send__(event[:method], *args)\n end\n else\n []\n end\n end",
"def trigger(name, data={})\n event = build_event(name, data)\n\n subscribers_for(event.full_name).each do |subscriber|\n subscriber.receive(event)\n end\n end",
"def trigger(name, *args)\n event_table[name].each { |handler| handler.send( name.to_sym , *args) }\n end",
"def trigger(name, *args)\n Vedeu.events.trigger(name, *args)\n end",
"def trigger_event(event_name, *args)\n event_callbacks[event_name].each do |cb|\n begin\n cb.call(*args)\n rescue Exception => ex\n warn \"[OnStomp/Event] triggering #{event_name} raised an error: #{ex}\"\n end\n end\n end",
"def trigger\n Vedeu.log(type: :event,\n message: \"No action for: '#{name.inspect}'\") if results.empty?\n\n return results[0] if results.one?\n\n results\n end",
"def trigger(name, *args)\n # TODO: should this be instance_eval(&blk)? prevents it from non-dsl style\n (@callbacks[name.to_sym] || []).each {|blk| blk.call(*args)}\n end",
"def trigger\n if Vedeu.config.debug? && results.empty?\n Vedeu.log(type: :nonevent,\n message: \"No action for: '#{name.inspect}'\")\n end\n\n return results[0] if results.one?\n\n results\n end",
"def trigger(event, *params, &block)\n catch :return do\n return_value = nil\n __handlers[event.to_sym].each do |handler|\n return_value = handler.call(*params, &block)\n end\n return_value\n end\n end",
"def trigger(event_name, payload = {})\n handlers.each do |handler|\n next unless handler.respond_to?(:trigger)\n\n handler.trigger(self, event_name, payload)\n end\n end",
"def dispatch name, msg = nil\n return unless self.has_key? name\n\n $log.debug(\"events.run\") { name }\n\n self[name].each do |event|\n begin\n unless msg == nil\n next unless Bot::Flags.permit_message? event.owner, msg\n\n event.owner.send event.func, msg\n else\n event.owner.send event.func\n end\n\n rescue => e\n $log.error(\"events.run\") { \"Error running event #{name}: #{e}\" }\n $log.debug(\"events.run\") { \"Backtrace for #{name}: #{e.backtrace}\" }\n end\n end\n end",
"def fire(event_name)\n\t\tend",
"def event(name)\n abi(name: name, type: 'event').first\n end",
"def emit(event_name, *args)\n events.fetch(event_name, []).each do |listener|\n listener.call(*args)\n end\n end",
"def trigger name, *args, &block\n if block\n trigger :before, name\n yield\n trigger :after, name\n else\n return unless hooks[name]\n hooks[name][args.shift].each do |proc|\n proc.call *args\n end\n end\n end",
"def _rg_trigger_given(name) # :nodoc:\n Proc.new { send(name) }\n end",
"def exec_hook(event_name, *args, &block)\n @hooks[event_name] ||= []\n\n # silence warnings to get rid of 1.8's \"warning: multiple values\n # for a block parameter\" warnings\n Pry::Helpers::BaseHelpers.silence_warnings do\n @hooks[event_name].map { |hook_name, callable| callable.call(*args, &block) }.last\n end\n end"
] | {
"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, \"invalid response for #{name} unregister\"\n end\n end",
"def delete(name)\n @event.delete_if { |event| event[:listener_name].to_s == name.to_s }\n end",
"def deregister(name)\n check = collection.delete(name)\n end",
"def clear_event_hooks(event_name); end",
"def unregister(name)\n @health.unregister(name)\n end",
"def off(event_type = ANY_EVENT, name = ANY_STATE, &callback)\n sync_exclusive do\n hooks.unregister event_type, name, callback\n end\n end",
"def unsubscribe(event, handle_name = nil)\n #TODO: implement\n #return @events[event].delete(event.handle_object) if event.kind_of?(EventHandle)\n #return @events[event].delete(handle_name)\n end",
"def unsubscribe(name, cb = nil)\n\n if cb then\n # One\n l = Array.new\n @events[name].each{|o|\n if o != cb then\n l.push(o)\n end\n }\n @events[name] = l\n else\n # All\n @events.delete(name)\n end\n\n self\n end",
"def unregister\n Neo4j.event_handler.remove(self)\n end",
"def clear_event_hooks(event_name)\n @hooks[event_name.to_s] = []\n end",
"def remove_event(event); end",
"def delete_event(event_name)\n !@event.delete(event_name).nil?\n end",
"def off(event_name, listener)\n Array(events[event_name]).delete(listener)\n end",
"def deregister(name)\n\t\t# deregister from alias\n\t\ttask = @alias[name]\n\t\t@alias.delete name if task\n\n\t\t# and also the task list\n task = get(name)\n @registered_tasks.delete task\n rescue Orocos::NotFound\n end",
"def remove_event(event)\n event = event.to_s.to_sym()\n\n if @@events.has_key?(event)\n @@events.delete(event)\n emit_event(:event_removed, event)\n end\n\n return event\n end",
"def remove_event(event)\n @events.delete(event)\n end",
"def del_event(event)\n @hooks.delete(event) \n end",
"def unsubscribe(key)\n @lock.synchronize do\n @handlers.clear\n @@name2inst.delete_if { |k, v| k == id.to_sym || k == address.to_sym}\n end\n end",
"def clear_event(event)\n @events.delete(event)\n end"
] | {
"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",
"def remove_outcome_data\n datapoints = self.outcome_data_points\n unless datapoints.empty?\n datapoints.each do |dp|\n if dp.footnote_number > 0\n # get a new copy in case this function updated it already\n dp_obj = OutcomeDataPoint.find(dp.id) # get a new copy in case this function updated it\n OutcomeDataEntry.update_footnote_numbers_on_delete(dp_obj.footnote_number,self.outcome_id,self.subgroup_id)\n end\n OutcomeDataPoint.destroy(dp.id)\n end\n end\n end",
"def reset!\n @data_series = []\n @telemetry_toggled_off = false\n end",
"def clear_taps!\n self.trace_tap = nil\n end",
"def remove_dataset_attributes\n call_on_each_qernel_object(:reset_dataset_attributes)\n reset_goals\n end",
"def remove_data_entries(attribute_names: nil, sources: nil)\n filter_loaded_data_entries(attributes: attribute_names, sources: sources).each do |data_entry|\n data_entry.mark_for_destruction\n end\n end",
"def remove_unreferenced_histories\n self.history.destroy unless self.history.alerts.count > 0\n end",
"def clear_spans!\n tracer.instance_variable_set(:@spans, [])\n\n @spans = nil\n @span = nil\n end",
"def clear_deprecated\n @data.each do |k, _v|\n @data.delete(k) if @deprecated.include?(k)\n end\n end",
"def purge\n @time_graph.each do |t, te|\n if t <= (@last_entry_time - ROLLING_WINDOW_SIZE)\n te.each { |e| @adj_matrix.delete(e) }\n @time_graph.delete(t)\n end\n end\n end",
"def cleanup_dfs\n # clean up vertices attributes set during dfs\n @vertices.values.each do |vertex|\n vertex.color = nil\n vertex.predecessor = nil\n vertex.discovery = nil\n vertex.finish = nil\n end\n @time = 0\n end",
"def discard_zeroes_data\n @discard_zeroes_data\n end",
"def remove_timelines\n @temporal_statuses = []\n end",
"def clear_all_measures\n @workflow.delete('steps')\n @workflow['steps'] = []\n end",
"def clear\n @extent.clear\n end",
"def pop\n @mutex.synchronize do\n traces = @traces\n @traces = []\n return traces\n end\n end",
"def clear_changed_attributes\n\t\t\t \t\t$TRACE.debug 5, \"clear_changed_attributes\"\n\t\t\t \tself.changed_attributes_aado = []\n\t\t\t \tend"
] | {
"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 end\n end",
"def json_parse(str)\n JSON.load(str)\n rescue JSON::ParserError\n str\n end",
"def json_encode(string)\n string.to_json\n end",
"def json_decode(string)\n begin\n JSON.parse(string)\n rescue JSON::ParserError => e\n raise e\n end\n end",
"def write_json_string(str)\n @context.write(trans)\n trans.write(@@kJSONStringDelimiter)\n str.split('').each do |ch|\n write_json_char(ch)\n end\n trans.write(@@kJSONStringDelimiter)\n end",
"def parse_string_to_json(response)\n JSON.parse(response)\n rescue JSON::ParserError\n response\n 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 end\n end\n end",
"def convert_to_json(record)\n Oj.dump(record, :mode => :compat)\n end",
"def report_to_json(report); end",
"def convert_as_json(text)\n parsed = JSON.parse(text, symbolize_names: true)\n return parsed if parsed.is_a?(Array)\n\n [parsed]\n end",
"def decode_properties(string)\n ::JSON.parse(string)\n end",
"def as_json(*args)\n eval(to_s).as_json(*args)\n end",
"def serialize_track(track)\n json = \"{\\\"id\\\": #{track.id},\n \\\"name\\\": \\\"#{track.name}\\\",\n \\\"artist\\\": {\\\"id\\\": #{track.artist.id},\\\"name\\\": \\\"#{track.artist.name}\\\"},\n \\\"release\\\": {\\\"id\\\": #{track.release.id},\\\"name\\\": \\\"#{track.release.name}\\\"},\n \\\"file\\\": \\\"#{track.file.url}\\\"}\"\n end",
"def serialize trace_context\n format(\n \"%02<version>d-%<trace_id>s-%<span_id>s-%02<trace_options>d\",\n version: 0, # version 0,\n trace_id: trace_context.trace_id,\n span_id: trace_context.span_id,\n trace_options: trace_context.trace_options\n )\n end",
"def clean_json(str)\n str.to_json.sub(/^\\A\"(.*)\"\\z$/, '\\\\1') # Make sure this is the same string that is sent in the JSON\n end",
"def convert_span obj\n TraceProtos::Span.new \\\n name: make_resource_name(@project_id, obj.trace_id, obj.span_id),\n span_id: obj.span_id,\n parent_span_id: obj.parent_span_id || \"\",\n display_name: convert_truncatable_string(obj.name),\n start_time: convert_time(obj.start_time),\n end_time: convert_time(obj.end_time),\n attributes:\n convert_attributes(obj.attributes,\n obj.dropped_attributes_count,\n include_agent_attribute: true),\n stack_trace:\n convert_stack_trace(obj.stack_trace, obj.dropped_frames_count,\n obj.stack_trace_hash_id),\n time_events:\n convert_time_events(obj.time_events,\n obj.dropped_annotations_count,\n obj.dropped_message_events_count),\n links: convert_links(obj.links, obj.dropped_links_count),\n status: convert_optional_status(obj.status),\n same_process_as_parent_span:\n convert_optional_bool(obj.same_process_as_parent_span),\n child_span_count: convert_optional_int32(obj.child_span_count)\n end"
] | {
"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
trace_code = @code[trace.line]
filtered_trace = filter_trace([
trace_stack_ordered_variable_names,
trace_stack_encoded_locals,
trace_heap,
trace_code,
trace.line
])
@new_traces << filtered_trace
trace_string = Yajl::Encoder.encode(filtered_trace)
@traces_json_array << trace_string
@traces_json_string += trace_string + ','
end
end
end | [
"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 end",
"def get_stages exec_trace\n ret_array = []\n lines = exec_trace.split /\\n/\n current_line = 0\n # Skip past preamble\n until lines[current_line] =~ /M@/\n current_line += 1\n end\n pattern = /M@(\\w+)/\n while current_line < lines.length\n if lines[current_line].match pattern\n command = lines[current_line].sub pattern, '\\1'\n case command\n when \"assign\"\n var = lines[current_line += 1]\n exp = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"#{var} := #{exp}\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"new\"\n var = lines[current_line += 1]\n exp = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"#{var} := new(#{exp})\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"dispose\"\n var = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"free(#{var})\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"lookup\"\n var1 = lines[current_line += 1]\n var2 = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"#{var1} := [#{var2}]\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"mutate\"\n var = lines[current_line += 1]\n exp = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n f_store = lines[current_line += 1]\n f_heap = lines[current_line += 1]\n text = \"[#{var}] := #{exp}\"\n ret_array.push Stage.new i_heap, i_store, f_heap, f_store, text\n current_line += 1\n when \"conditional\"\n bool = lines[current_line += 1]\n i_store = lines[current_line += 1]\n i_heap = lines[current_line += 1]\n prog = lines[current_line += 1]\n text = \"if #{bool} (taking branch: #{prog})\"\n ret_array.push Stage.new i_heap, i_store, i_heap, i_store, text\n current_line += 1\n else\n raise \"command did not match\"\n end\n else\n raise \"line #{lines[current_line]} didn't match\"\n end\n end\n ret_array\nend",
"def texify exec_trace\n document_text = \"\"\n File.open \"preamble.tex\" do |file|\n while line = file.gets\n document_text += line\n end\n end\n document_text += \"\\\\begin{document}\\n\"\n stages = get_stages exec_trace\n stages.each do |stage|\n document_text += \"\\\\begin{frame}\\n\\n\"\n document_text += state_text stage.i_heap, stage.i_store\n document_text += \"\\n\"\n document_text += \"Current command: \"\n document_text += \"\\\\il{#{stage.text}}\"\n document_text += \"\\n\"\n document_text += \"\\\\vspace{1cm}\\n\\n\"\n document_text += state_text stage.f_heap, stage.f_store\n document_text += \"\\\\end{frame}\"\n document_text += \"\\n\"\n end\n document_text\nend",
"def traces\n trace_store.keys\n end",
"def get_test_traces(n)\n traces = []\n\n defaults = {\n service: 'test-app',\n resource: '/traces',\n span_type: 'web'\n }\n\n n.times do\n span1 = Datadog::Span.new(nil, 'client.testing', defaults).finish()\n span2 = Datadog::Span.new(nil, 'client.testing', defaults).finish()\n span2.set_parent(span1)\n traces << [span1, span2]\n end\n\n traces\n end",
"def create_traces_markup_from_traces_array(traces_array) #{\n rally_host = $my_base_url.split(\"/\")[-2]\n story_detail_url_prefix = \"https://#{rally_host}/#/detail/userstory\"\n testcase_detail_url_prefix = \"https://#{rally_host}/#/detail/testcase\"\n traces_markup = '<p><b>Caliber TRACES</b></p><br/>'\n trace_counter = 1\n\n traces_array.each do | this_traceid |\n\n is_testcase = this_traceid.match(/^TC/)\n is_requirement = this_traceid.match(/^REQ/)\n\n if !is_testcase.nil? then\n testcase_tag, testcase_fid, testcase_oid, testcase_name = @testcase_TagFidOidName_by_reqid[this_traceid.sub(\"TC\", \"\")]\n\n if testcase_oid.nil? then\n @logger.warn \" *** No Rally TestCase found for Caliber TestCase: CID=#{this_traceid}; (link will be empty)\"\n this_trace = this_traceid\n else\n @logger.info \" Linking Trace JDtraceId=#{this_traceid}; to Rally TestCase: FmtID=#{testcase_fid}; OID=#{testcase_oid};\"\n #this_trace_name = @testcase_name_by_caliber_testcase_id[testcase_oid] || this_traceid\n this_trace_name = \"#{this_traceid}: #{testcase_name}\"\n\n detail_url = \"#{testcase_detail_url_prefix}/#{testcase_oid}\"\n this_trace = \"<a href=\\\"#{detail_url}\\\">#{this_trace_name}</a>\"\n end\n traces_markup += trace_counter.to_s + \". \"\n traces_markup += this_trace\n traces_markup += '<br/>'\n trace_counter += 1\n end\n\n if !is_requirement.nil? then\n story_tag, story_fid, story_oid, story_name = @story_TagFidOidName_by_reqid[this_traceid.sub(\"REQ\", \"\")]\n\n if story_oid.nil? then\n @logger.warn \" *** No Rally UserStory found for Caliber Requirement: CID=#{this_traceid}; (link will be empty)\"\n this_trace = @req_name_by_reqid[this_traceid] || this_traceid\n else\n @logger.info \" Linking Trace JDtraceId=#{this_traceid}; to Rally UserStory: FmtID=#{story_fid}; OID=#{story_oid};\"\n #this_trace_name = @req_name_by_reqid[this_traceid.sub(\"REQ\", \"\")] || this_traceid\n this_trace_name = \"#{this_traceid}: #{story_name}\"\n\n detail_url = \"#{story_detail_url_prefix}/#{story_oid}\"\n this_trace = \"<a href=\\\"#{detail_url}\\\">#{this_trace_name}</a>\"\n end\n traces_markup += trace_counter.to_s + \". \"\n traces_markup += this_trace\n traces_markup += '<br/>'\n trace_counter += 1\n end\n end\n return traces_markup\nend",
"def trace\n set_trace_func proc { |event, _file, _line, id, binding, classname|\n if event == watched && id != :log && classes.include?(classname.to_s)\n vars = variables(binding)\n\n if vars.empty?\n log_this(sprintf(\"%s %-25s #%-20s\",\n class_count, classname, id))\n\n else\n log_this(sprintf(\"%s %-25s #%-20s\\n%s\\n\",\n class_count, classname, id, vars))\n\n end\n end\n } if trace?\n end",
"def process_code(code, tracing_vars)\n # insert information in code here\n tracing_vars\n code\n end",
"def _trace(\n theme: DEFAULT_PALETTE, # Palette to generate screenshot in\n bg: nil, # Background image (screenshot) file object\n animate: false, # Animate trace instead of still image\n coords: [], # Array of coordinates to plot routes\n demos: [], # Array of demo inputs, to mark parts of the route\n texts: [], # Names for the legend\n markers: { jump: true, left: false, right: false} # Mark changes in replays\n )\n return if coords.empty?\n\n _fork do\n # Parse palette\n bench(:start) if BENCH_IMAGES\n themes = THEMES.map(&:downcase)\n theme = theme.to_s.downcase\n theme = DEFAULT_PALETTE.downcase if !themes.include?(theme)\n palette_idx = themes.index(theme)\n\n # Setup parameters and Matplotlib\n coords = coords.take(MAX_TRACES).reverse\n demos = demos.take(MAX_TRACES).reverse\n texts = texts.take(MAX_TRACES).reverse\n n = [coords.size, MAX_TRACES].min\n color_idx = OBJECTS[0][:pal]\n colors = n.times.map{ |i| ChunkyPNG::Color.to_hex(PALETTE[color_idx + n - 1 - i, palette_idx]) }\n Matplotlib.use('agg')\n mpl = Matplotlib::Pyplot\n mpl.ioff\n\n # Prepare custom font (Sys)\n font = \"#{DIR_UTILS}/sys.ttf\"\n fm = PyCall.import_module('matplotlib.font_manager')\n fm.fontManager.addfont(font)\n mpl.rcParams['font.family'] = 'sans-serif'\n mpl.rcParams['font.sans-serif'] = fm.FontProperties.new(fname: font).get_name\n bench(:step, 'Trace setup') if BENCH_IMAGES\n\n # Configure axis\n dx = (COLUMNS + 2) * UNITS\n dy = (ROWS + 2) * UNITS\n mpl.axis([0, dx, dy, 0])\n mpl.axis('off')\n ax = mpl.gca\n ax.set_aspect('equal', adjustable: 'box')\n\n # Load background image (screenshot)\n img = mpl.imread(bg)\n ax.imshow(img, extent: [0, dx, dy, 0])\n bench(:step, 'Trace image') if BENCH_IMAGES\n\n # Plot inputs\n n.times.each{ |i|\n break if markers.values.count(true) == 0 || demos[i].nil?\n demos[i].each_with_index{ |f, j|\n if markers[:jump] && f[0] == 1 && (j == 0 || demos[i][j - 1][0] == 0)\n mpl.plot(coords[i][j][0], coords[i][j][1], color: colors[i], marker: '.', markersize: 1)\n end\n if markers[:right] && f[1] == 1 && (j == 0 || demos[i][j - 1][1] == 0)\n mpl.plot(coords[i][j][0], coords[i][j][1], color: colors[i], marker: '>', markersize: 1)\n end\n if markers[:left] && f[2] == 1 && (j == 0 || demos[i][j - 1][2] == 0)\n mpl.plot(coords[i][j][0], coords[i][j][1], color: colors[i], marker: '<', markersize: 1)\n end\n }\n }\n bench(:step, 'Trace input') if BENCH_IMAGES\n\n # Plot legend\n n.times.each{ |i|\n break if texts[i].nil?\n name, score = texts[i].match(/(.*)-(.*)/).captures.map(&:strip)\n dx = UNITS * COLUMNS / 4.0\n ddx = UNITS / 2\n bx = UNITS / 4\n c = 8\n m = dx / 2.9\n dm = 4\n x, y = UNITS + dx * (n - i - 1), UNITS - 5\n vert_x = [x + bx, x + bx, x + bx + c, x + dx - m - dm, x + dx -m, x + dx - m + dm, x + dx - bx - c, x + dx - bx, x + dx - bx]\n vert_y = [2, UNITS - c - 2, UNITS - 2, UNITS - 2, UNITS - dm - 2, UNITS - 2, UNITS - 2, UNITS - c - 2, 2]\n color_bg = ChunkyPNG::Color.to_hex(PALETTE[2, palette_idx])\n color_bd = colors[i]\n mpl.fill(vert_x, vert_y, facecolor: color_bg, edgecolor: color_bd, linewidth: 0.5)\n mpl.text(x + ddx, y, name, ha: 'left', va: 'baseline', color: colors[i], size: 'x-small')\n mpl.text(x + dx - ddx, y, score, ha: 'right', va: 'baseline', color: colors[i], size: 'x-small')\n }\n bench(:step, 'Trace texts') if BENCH_IMAGES\n\n # Plot or animate traces\n # Note: I've deprecated the animation code because the performance was horrible.\n # Instead, for animations I render each frame in the screenshot function,\n # and then call ffmpeg to render an mp4.\n if false# animate\n anim = PyCall.import_module('matplotlib.animation')\n x = []\n y = []\n plt = mpl.plot(x, y, colors[0], linewidth: 0.5)\n an = anim.FuncAnimation.new(\n mpl.gcf,\n -> (f) {\n x << coords[0][f][0]\n y << coords[0][f][1]\n plt[0].set_data(x, y)\n plt\n },\n frames: 20,\n interval: 200\n )\n an.save(\n '/mnt/c/Users/Usuario2/Downloads/N/test.gif',\n writer: 'imagemagick',\n savefig_kwargs: { bbox_inches: 'tight', pad_inches: 0, dpi: 390 }\n )\n else\n coords.each_with_index{ |c, i|\n mpl.plot(c.map(&:first), c.map(&:last), colors[i], linewidth: 0.5)\n }\n end\n bench(:step, 'Trace plot ') if BENCH_IMAGES\n\n # Save result\n fn = tmp_filename(\"#{name}_aux.png\")\n mpl.savefig(fn, bbox_inches: 'tight', pad_inches: 0, dpi: 390, pil_kwargs: { compress_level: 1 })\n image = File.binread(fn)\n bench(:step, 'Trace save ') if BENCH_IMAGES\n\n # Perform cleanup\n mpl.cla\n mpl.clf\n mpl.close('all')\n\n # Return\n image\n end\n end",
"def build_trace\n if with_bt_set?\n Backtrace.to_s(@with_bt + [first_filtered_bt_line(backtrace)])\n else\n src_line\n end\n end",
"def pythonTrace( traceFileData ) \r\n\r\n\t\ttraceArray = [] \r\n\t\r\n\t\ttraceFileData.each { |line|\r\n\t\t\tfileName = \"\"\r\n\t\t\tlineNum = \"\" \r\n\t\t\tline.strip!\r\n\t\t\r\n\t\t\tm = /File \"(.+)\", line (\\d+),/.match(line) \t\r\n\t\t\tif m != nil\r\n\t\t\t traceArray.insert(0, FileData.new(m[1], m[2]))\r\n\t\t\tend\r\n\t\t}\r\n\t\t\r\n\t\treturn traceArray\r\n\tend",
"def build_trace(backtrace); backtrace.filtered.first.to_s; end",
"def parse_ie_trace_information(payload_data)\n trace_info = {}\n\n trace_info[:trace_info_mcc] = (payload_data[0].unpack(\"h*\")[0] << (payload_data[1].unpack(\"C\")[0] & 0b00001111).to_s).to_i\n trace_info[:trace_info_mnc] = payload_data[2].unpack(\"h*\")[0].to_i\n trace_info[:trace_info_id] = payload_data[3..5].unpack(\"H*\")[0].hex\n trace_info[:trace_info_triggering_events] = payload_data[6..14].unpack(\"H*\")[0].hex\n trace_info[:trace_info_list_of_ne_types] = payload_data[15..16].unpack(\"H*\")[0].hex\n trace_info[:trace_info_session_trace_depth] = payload_data[17].unpack(\"H*\")[0].hex\n trace_info[:trace_info_list_of_interfaces] = payload_data[18..29].unpack(\"H*\")[0].hex\n trace_info[:trace_info_ip_addr_of_trace_collection_entity] = payload_data[30..-1].unpack(\"H*\")[0].hex\n \n return trace_info\n end",
"def read_stack_cache_traces(analysis_task_elem)\n analysis_task_elem.each_element(\"value_analysis/messages/message/textline\") { |e|\n if e.text =~ /trace.*\\(context\\w*(.*)\\).*\\(\"user_(n_(?:fill|spill))\"\\).=.(\\d+)/\n yield $1,$2,$3\n end\n }\n end",
"def debug_info\n if @@our_debug\n puts \"#{debug_time} Eval For_class. Start idx #{@start.value}, End idx #{@end.value}\"\n puts \"#{debug_time} Block content: #{@stmts}\"\n end\n end",
"def stackFrameWalk()\n toKernel32Code = toKernel32()\n data = <<EOS\n push esi\n push ecx\n\n mov eax, ebp\n\n stack_walking:\n mov esi, eax\n lodsd\n mov ecx,[eax]\n test ecx, ecx\n jnz stack_walking\n\n ; esi now points to last stack frame (and since lodsd increments esi by 4 it points to function in ntdll.dll)\n mov eax,[esi]\n\n find_begin:\n dec eax\n xor ax,ax ; work through image until we find base address\n cmp word [eax],0x5A4D ; MZ start of PE header\n jnz find_begin\n\n pop ecx\n pop esi\n\n mov edx, eax\n ; edx now points to ntdll.dll or kernel32.dll base address (depending on windows version)\n\n #{toKernel32Code}\nEOS\n data\n end",
"def exe_Point_Finder(trace)\n symbol_stack = []\n other_list = []\n top_symbol = ''\n exe = ''\n exe_point = ' '\n on = false\n off = false\n trace.split('').each do |i|\n current_symbol = i\n exe_point += current_symbol\n if i == '{' or i == '[' or i == '('\n symbol_stack << i\n elsif i == '}' or i == ')' or i == ']'\n if empty?(symbol_stack) == false\n top_symbol = symbol_stack.pop\n if i == '}' and top_symbol != '{'\n next\n end\n end\n elsif i == ','\n other_list << exe_point\n if symbol_stack.length.zero?\n other_list.each do |thing|\n exe += thing\n end\n if exe.include? 'startTraceNow'\n on = true\n exe = ''\n exe_point = ''\n other_list = []\n elsif exe.include? 'endTraceNow'\n off = true\n return\n else\n flag = verify_exe_point(on, off, exe)\n on = false if flag == false\n exe = ''\n exe_point = ''\n other_list = []\n end\n else\n exe_point = ''\n end\n\n else\n next\n end\n end\n end",
"def traces\n @traces ||= RequestList.new\n end",
"def debug\n return @debug if @debug\n reloc = self.class.reloc\n @debug = self.class.debug.map do |d|\n case d\n when DebugInfo\n data = code[d.addr, d.size]\n h = proc {|as, g| as.map {|c| '%02X'%c.ord}.join g}\n label = if d.labels.last.to_name\n \" :\" + d.labels.map {|n| n.to_name || n.to_i(org).to_s(16) }.join('.')\n end\n unless (relocs = reloc.select {|r| (d.addr...d.addr+d.size).member? r.addr }.map {|r| r.alloc.to_s}.join(', ')).empty?\n label = label.to_s + \" -> #{relocs}\"\n end\n if mnemo = d.text\n if prm = d.args\n mnemo = mnemo % prm.each_slice(2).map do |o, t|\n case t\n when :word\n data[o, 2].unpack('S')[0]\n when :byte\n data[o, 1].unpack('C')[0]\n when :pcrel\n data[o, 1].unpack('c')[0] + d.addr + d.size + org\n end\n end\n end\n \"#{'%04X'%(d.addr+org)}: #{h[data.split(''),''].ljust 12}#{mnemo.ljust 20}#{label}\"\n elsif data.empty? and label\n \"#{'%04X'%(d.addr+org)}: #{' '*32}#{label}\"\n else\n a = d.addr - 8 + org\n data.split('').each_slice(8).map do |ds|\n a+= 8\n \"#{'%04X'%a}: #{h[ds, ' '].ljust 24}#{ds.join.gsub(/[\\x0-\\x1f]/, '.').ljust 8}#{label}\"\n end\n end\n else\n [\" #{@imports[d].class} \".center(38, ?=)] + @imports[d].debug + [\" #{@imports[d].class} \".center(38, ?^)]\n end\n end.flatten\n end"
] | {
"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 end\n end\n end",
"def serialize trace_context\n format(\n \"%02<version>d-%<trace_id>s-%<span_id>s-%02<trace_options>d\",\n version: 0, # version 0,\n trace_id: trace_context.trace_id,\n span_id: trace_context.span_id,\n trace_options: trace_context.trace_options\n )\n end",
"def serialize span_context\n span_context.trace_id.tap do |ret|\n if span_context.span_id\n ret << \"/\" << span_context.span_id.to_i(16).to_s\n end\n if span_context.trace_options\n ret << \";o=\" << span_context.trace_options.to_s\n end\n end\n end",
"def to_string\n str = trace_id\n str += \"/#{span_id}\" if span_id\n unless sampled?.nil?\n options = 0\n options |= 1 if sampled?\n options |= 2 if capture_stack?\n str += \";o=#{options}\"\n end\n str\n end",
"def json\n\n JSON.fast_generate(@gltf)\n\n end",
"def to_json_raw_object()\n #This is a stub, used for indexing\n end",
"def to_json\n diff.to_json\n end",
"def get_traceG()\n return @traceG\n end",
"def json_serialize\n end",
"def get_traceT()\n return @traceT\n end",
"def to_trace_context_header\n @trace_data.formatter.serialize self\n end",
"def debug_out()\n return JSON.pretty_generate(self).gsub(\"\\\": \", \"\\\" => \").gsub(\" => null\", \" => nil\")\n end",
"def to_json\n @raw\n end",
"def to_json\n\t\t\t\t\tto_h.to_json\n\t\t\t\tend",
"def toJsonString(prettyP = false)\n case(prettyP)\n when(true) ;\n return JSON.pretty_generate(toJson()) ;\n when(:line) ;\n _strList = @entryList.map{|entry| JSON.generate(entry.toJson())} ;\n return \"[\\n #{_strList.join(\",\\n \")}\\n]\" ;\n else\n return JSON.generate(toJson()) ;\n end\n end",
"def json\n delta_pack.to_json\n end",
"def report_to_json(report); end",
"def serialize trace_context\n [\n 0, # version\n 0, # field 0\n trace_context.trace_id,\n 1, # field 1\n trace_context.span_id,\n 2, # field 2\n trace_context.trace_options\n ].pack(BINARY_FORMAT)\n end",
"def pretty_json\n JSON.pretty_generate(delta_pack)\n end"
] | {
"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 = ''
lines.each { |line| jUnit_test += line}
jUnit_test.gsub!('\"', "\\" + '\"')
student_file = File.open(File.join(File.dirname(File.expand_path(__FILE__)),
peruser_files_path,
student_file_name), 'w+')
full_string = '{' + "\n" + '"' + 'usercode' + '"' + ':' + '"' + jUnit_test +
'"' + ',' + "\n" + '"' + 'options' + '"' + ':' + '{' + '}' \
',' + "\n" + '"' + 'args' + '"' + ':' + '[' + ']' + ',' \
"\n" + '"' + 'stdin' + '"' + ':' + '"' + '"' + "\n" + '}'
student_file.puts(full_string)
student_file.close
output = `java -cp .:cp:cp/javax.json-1.0.4.jar:java/tools.jar traceprinter.InMemory < cp/traceprinter/output.txt` # the shell command
output
end | [
"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 << '| Job: ' + \"#{i + 1} \".rjust(8) + '|' + 'Pattern:'.rjust(18) + \" #{j.pattern.basename}\".ljust(120) + '|'\n desc << '| |' + 'Compiler ID:'.rjust(18) + \" #{j.id} \".ljust(120) + '|'\n desc << '| |' + 'Pinmap:'.rjust(18) + \" #{j.pinmap_workbook} \".ljust(120) + '|'\n desc << '| |' + '.atp directory:'.rjust(18) + \" #{j.pattern.dirname} \".ljust(120) + '|'\n desc << '| |' + '.pat directory:'.rjust(18) + \" #{j.output_directory} \".ljust(120) + '|'\n desc << '| |' + 'LSF:'.rjust(18) + \" #{j.location == :lsf ? true : false} \".ljust(120) + '|'\n desc << '| |' + 'Delete log files:'.rjust(18) + \" #{j.clean} \".ljust(120) + '|'\n desc << '| |' + 'Verbose:'.rjust(18) + \" #{j.verbose} \".ljust(120) + '|'\n fragment = '| |' + 'Compiler args:'.rjust(18)\n overflow_fragment = '| |' + ' '.rjust(18)\n compiler_args = []\n compiler_fragment = ''\n j.compiler_options.each_key do |k|\n if compiler_fragment.size + \" -#{k}\".size >= 120\n compiler_args << compiler_fragment\n compiler_fragment = nil\n end\n compiler_fragment += \" -#{k}\"\n end\n compiler_args << compiler_fragment unless compiler_fragment.nil?\n compiler_fragment = ''\n j.compiler_options_with_args.each_pair do |k, v|\n if compiler_fragment.size + \" -#{k}:#{v}\".size >= 120\n compiler_args << compiler_fragment\n compiler_fragment = nil\n end\n compiler_fragment += \" -#{k}:#{v}\"\n end\n compiler_args << compiler_fragment unless compiler_fragment.nil?\n if compiler_args.join.length <= 120\n desc << fragment + \"#{compiler_args.join}\".ljust(120) + '|'\n else\n # Need to cycle through compiler args and build a fragment <= 100 characters\n # and print it. Keep going until the remaining args is <= 100 and print again\n char_cnt = 0\n line_cnt = 0\n args = []\n compiler_args = compiler_args.join.strip.split(/\\s+/)\n until compiler_args.empty?\n args = compiler_args.select { |e| (char_cnt += e.length + 1) < 120 }\n # remove the args that fit on the first line\n compiler_args -= args\n if line_cnt == 0\n desc << fragment + \" #{args.join(' ')}\".ljust(120) + '|'\n else\n desc << overflow_fragment + \" #{args.join(' ')}\".ljust(120) + '|'\n end\n args = []\n line_cnt += 1\n char_cnt = 0\n end\n end\n desc << '-' * desc.first.size\n end\n puts desc.flatten.join(\"\\n\")\n end",
"def build_trace\n if with_bt_set?\n Backtrace.to_s(@with_bt + [first_filtered_bt_line(backtrace)])\n else\n src_line\n end\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 << '| Job: ' + \"#{i + 1} \".rjust(8) + '|' + 'Pattern:'.rjust(18) + \" #{j.pattern.basename}\".ljust(100) + '|'\n desc << '| |' + 'Compiler ID:'.rjust(18) + \" #{j.id}\".ljust(100) + '|'\n desc << '| |' + 'Pinmap:'.rjust(18) + \" #{j.pinmap_workbook}\".ljust(100) + '|'\n desc << '| |' + '.atp directory:'.rjust(18) + \" #{j.pattern.dirname}\".ljust(100) + '|'\n desc << '| |' + '.pat directory:'.rjust(18) + \" #{j.output_directory}\".ljust(100) + '|'\n desc << '| |' + 'LSF:'.rjust(18) + \" #{j.location == :lsf ? true : false}\".ljust(100) + '|'\n desc << '| |' + 'Delete log files:'.rjust(18) + \" #{j.clean}\".ljust(100) + '|'\n desc << '| |' + 'Verbose:'.rjust(18) + \" #{j.verbose}\".ljust(100) + '|'\n fragment = '| |' + 'Compiler args:'.rjust(18)\n overflow_fragment = '| |' + ' '.rjust(18)\n compiler_args = []\n compiler_fragment = ''\n j.compiler_options.each_key do |k|\n if compiler_fragment.size + \" -#{k}\".size >= 100\n compiler_args << compiler_fragment\n compiler_fragment = nil\n end\n compiler_fragment += \" -#{k}\"\n end\n compiler_args << compiler_fragment unless compiler_fragment.nil?\n compiler_fragment = ''\n j.compiler_options_with_args.each_pair do |k, v|\n if compiler_fragment.size + \" -#{k}:#{v}\".size >= 100\n compiler_args << compiler_fragment\n compiler_fragment = nil\n end\n compiler_fragment += \" -#{k}:#{v}\"\n end\n compiler_args << compiler_fragment unless compiler_fragment.nil?\n if compiler_args.join.length <= 100\n desc << fragment + \"#{compiler_args.join}\".ljust(100) + '|'\n else\n # Need to cycle through compiler args and build a fragment <= 100 characters\n # and print it. Keep going until the remaining args is <= 100 and print again\n char_cnt = 0\n line_cnt = 0\n args = []\n compiler_args = compiler_args.join.strip.split(/\\s+/)\n until compiler_args.empty?\n args = compiler_args.select { |e| (char_cnt += e.length + 1) < 100 }\n # remove the args that fit on the first line\n compiler_args -= args\n if line_cnt == 0\n desc << fragment + \" #{args.join(' ')}\".ljust(100) + '|'\n else\n desc << overflow_fragment + \" #{args.join(' ')}\".ljust(100) + '|'\n end\n args = []\n line_cnt += 1\n char_cnt = 0\n end\n end\n desc << '-' * desc.first.size\n end\n puts desc.flatten.join(\"\\n\")\n end",
"def java_stack_trace_element; end",
"def compile_java\n mkdir_p \"pkg/classes\"\n sh \"javac -Xlint -Xlint:-serial -g -target 1.5 -source 1.5 -d pkg/classes #{jruby_classpath} #{FileList['src/**/*.java'].join(' ')}\"\nend",
"def dump_compiled code\n\t\t\tbuf = do_compile code,false\n\t\t\tprint buf,\"\\n\"\n\t\tend",
"def stack_trace; end",
"def execute( io = $stderr )\n raise 'No source files' if @source_files.nil? || @source_files.empty?\n \n io.puts 'javac …' if @verbose\n \n execute_compiler(io)\n end",
"def run_ktrace(jobid)\n\n initialize_db = lambda {|dbconn, required_tables|\n init = false\n db_init_script = File.join($script_path, 'ktrace_schema.sql')\n required_tables.each do |t|\n res = dbconn.exec(\"SELECT to_regclass('public.#{t}');\")\n if res.values[0][0].nil?\n init = true\n break\n end\n end\n if init\n stage \"[7] Initializing KTrace DB\"\n dbconn.exec(File.read(db_init_script))\n end\n }\n\n ingest_file = lambda {|dbconn, table_name, file_path|\n dbconn.copy_data \"COPY #{table_name} FROM STDIN delimiter '|' quote '`' csv\" do\n str = File.read(file_path)\n str.each_line do |line|\n dbconn.put_copy_data jobid + \"|\" + line\n end\n end\n }\n\n stage \"[7] Populating KTrace DB\"\n job_sandbox_path = File.join($workdir, \"job_#{jobid}\")\n\n if Dir.exists?(job_sandbox_path)\n globals_path = File.join(job_sandbox_path, \"globals.dsv\")\n messages_path = File.join(job_sandbox_path, \"messages.dsv\")\n peer_role_path = File.join(job_sandbox_path, \"peers.dsv\")\n\n if [globals_path, messages_path, peer_role_path].all? {|f| File.file?(f) }\n stage \"[7] Found trace data, now copying.\"\n conn = PG.connect()\n initialize_db.call(conn, ['Globals', 'Messages', 'Peers'])\n\n ingest_file.call(conn, \"Globals\", globals_path)\n stage \"[7] Copied globals trace data.\"\n\n ingest_file.call(conn, \"Messages\", messages_path)\n stage \"[7] Copied messages trace data.\"\n\n ingest_file.call(conn, \"Peers\", peer_role_path)\n stage \"[7] Copied peer role data.\"\n\n # TODO: automatic querying and verification of job logs.\n else\n stage \"[7] ERROR: No ktrace data found for job #{jobid}\"\n end\n end\n\nend",
"def cmd\n c = \"java -Xms64m -Xmx768m -jar #{jar} -s #{src} -o #{report}\"\n c += \" -r #{ruleset}\" unless ruleset == \"''\"\n c\n end",
"def generateTrace(writer=@writer)\n @vm.setDebugTraceMode(@debugTraceMode)\n evt_thread = EventThread.new(self)\n evt_thread.setEventRequests(@watchFields)\n evt_thread.start()\n STDERR.puts(\"======= starting trace =======\")\n begin\n if @launching_connector == \"com.sun.jdi.CommandLineLaunch\"\n redirectOutput() \n # make sure output is forwarded before we exit\n @err_thread.join \n @out_thread.join\n end\n @vm.resume()\n evt_thread.join\n rescue InterruptedException => exc\n STDERR.puts \"Got InterruptedException: #{exc}\" \n # we don't interrupt\n ensure\n @writer.close() if @writer.is_a?(File)\n end\n end",
"def execute\n\t\t\texec = Cfp_Execute.new @cf\n\t\t\t@codetree.each_exec do | code |\n\t\t\t\texec.do_execute code\n\t\t\tend\n\t\t\t@cf.classlist.dump @cf.cfp_logger\n\t\tend",
"def build_error_log(e)\r\n str = ''\r\n return build_system_stack_error_log(e, str) if e.is_a?(SystemStackError)\r\n return unless e.backtrace_locations\r\n\r\n source_arr = e.backtrace_locations[0]\r\n source_name = fix_source_path(source_arr.path.to_s)\r\n source_line = source_arr.lineno\r\n str << 'Erreur de script'.center(80, '=')\r\n # Formatage du message pour Windows\r\n str << format(\"\\r\\nMessage :\\r\\n%<message>s\\r\\n\\r\\n\", message: e.message.to_s.gsub(/[\\r\\n]+/, \"\\r\\n\"))\r\n str << format(\"Type : %<type>s\\r\\n\", type: e.class)\r\n str << format(\"Script : %<script>s\\r\\n\", script: source_name)\r\n str << format(\"Ligne : %<line>d\\r\\n\", line: source_line)\r\n str << format(\"Date : %<date>s\\r\\n\", date: Time.new.strftime('%d/%m/%Y %H:%M:%S'))\r\n str << format(\"Game Version : %<game_version>s\\r\\n\", game_version: PSDK_CONFIG.game_version)\r\n str << format(\"Logiciel : %<software>s %<version>s\\r\\n\", software: Software, version: PSDK_Version.to_str_version)\r\n str << format(\"Script used by eval command : \\r\\n%<script>s\\r\\n\\r\\n\", script: @eval_script) if @eval_script\r\n str << 'Backtraces'.center(80, '=')\r\n str << \"\\r\\n\"\r\n index = e.backtrace_locations.size\r\n e.backtrace_locations.each do |i|\r\n index -= 1\r\n source_name = fix_source_path(i.path.to_s)\r\n str << format(\"[%<index>s] : %<script>s | ligne %<line>d %<method>s\\r\\n\",\r\n index: index, script: source_name, line: i.lineno, method: i.base_label)\r\n end\r\n str << 'Fin du log'.center(80, '=')\r\n Yuki.set_clipboard(str)\r\n return str\r\n end",
"def texify exec_trace\n document_text = \"\"\n File.open \"preamble.tex\" do |file|\n while line = file.gets\n document_text += line\n end\n end\n document_text += \"\\\\begin{document}\\n\"\n stages = get_stages exec_trace\n stages.each do |stage|\n document_text += \"\\\\begin{frame}\\n\\n\"\n document_text += state_text stage.i_heap, stage.i_store\n document_text += \"\\n\"\n document_text += \"Current command: \"\n document_text += \"\\\\il{#{stage.text}}\"\n document_text += \"\\n\"\n document_text += \"\\\\vspace{1cm}\\n\\n\"\n document_text += state_text stage.f_heap, stage.f_store\n document_text += \"\\\\end{frame}\"\n document_text += \"\\n\"\n end\n document_text\nend",
"def __app_file_trace__\n caller.select do |call| \n call.include?(Merb.root) && !call.include?(Merb.root + \"/framework\")\n end.map do |call|\n file, line = call.scan(Regexp.new(\"#{Merb.root}/(.*):(.*)\")).first\n \"#{file}:#{line}\"\n end\n end",
"def build_trace(backtrace); backtrace.filtered.first.to_s; end",
"def on_program(statements); end",
"def send_to_testrail()\n options = ArgParser.parse_opts\n # Get pass/fail/skips from junit file\n results = load_junit_results(options[:junit_file])\n\n puts \"Run results:\"\n puts \"#{results[:passes].length} Passing\"\n puts \"#{results[:failures].length} Failing or Erroring\"\n puts \"#{results[:skips].length} Skipped\"\n\n # Set results in testrail\n bad_results = set_testrail_results(results, options[:junit_file], options[:testrun_id], options[:dry_run])\n\n # Print error messages\n if not bad_results.empty?\n puts \"Error: There were problems processing these test scripts:\"\n bad_results.each do |test_script, error|\n puts \"#{test_script}:\\n\\t#{error}\"\n end\n end\n end"
] | {
"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 do |lo, new_line_number|\n lo.line_number = new_line_number\n end\n end",
"def set_current_line_number(args={})\n fc = Wihajster::GCode.format_command(\"Set Current Line Number\", arguments)\n write_command(fc)\n end",
"def set_template_line(lineno)\n @lineno = lineno\n update_repr\n end",
"def line n = UNASSIGNED\n if n != UNASSIGNED then\n raise ArgumentError, \"setting %p.line %p\" % [self, n] unless Integer === n\n @line = n\n self\n else\n @line ||= nil\n end\n end",
"def start_line_number=(_); end",
"def beginning_line_number=(_); end",
"def line_numbering=(on_or_not)\n s9_document_builder.setLineNumbering(on_or_not)\n end",
"def start_line_number; end",
"def goto_line(num)\n\t\t\tgoto buffer.line_index(num)\n\t\tend",
"def increase_line_count\n @line_count += 1\n end",
"def lineno\n ensure_open\n\n @lineno\n end",
"def set_linebreaks(number)\n @linebreaks = number if (@linebreaks < number)\n end",
"def line_number\n @current_line\n end",
"def assign_line_numbers\n line_num = 1;\n\n @line_num = [ ]\n @tokens.each do |token|\n @line_num << line_num\n line_num += token.count \"\\n\"\n end\n end",
"def initialize(line_no)\n @line_no = line_no\n end",
"def line_id\n @line_number - 1\n end"
] | {
"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__(caller_depth=0)\n caller[caller_depth][PutsDebuggerer::STACK_TRACE_CALL_LINE_NUMBER_REGEX, 1].to_i\nend",
"def __caller_line_number__(caller_depth=0)\n return if RUBY_ENGINE == 'opal'\n caller[caller_depth] && caller[caller_depth][PutsDebuggerer::STACK_TRACE_CALL_LINE_NUMBER_REGEX, 1].to_i\n end",
"def line_offset(line_index)\n return unless line_exists?(line_index)\n line_index == 0 ? 0 : @line_lengths[0..(line_index - 1)].sum\n end",
"def line_number(node)\n node.loc.line\n end",
"def get_trace_id(line)\n return line.split(\"\\t\")[1].to_i\nend",
"def line\n @line || (backtrace!; @line)\n end",
"def source_line_number\n @source_line_number ||= proc_info[1]\n end",
"def line_id\n @line_number - 1\n end",
"def line_number\n comment.loc.expression.line\n end",
"def linenumber\n return @cmd.nil? ? 0 : @cmd.linenumber\n end",
"def find_calling_line(trace, method_name)\n trace.each_cons(2) do |line, next_line|\n if /(.*):(\\d+):in .(.*)'/ =~ line && \n $3 == method_name &&\n /(.*):(\\d+):in .(.*)'/ =~ next_line\n return [$1,$2]\n end\n end\n nil\n end",
"def trace_number(trace_id=\"99Trizetto\")\n self.traces[trace_id.upcase]\n end",
"def line(line_number)\n @source_map[line_number]\n end",
"def start_line\n @line_number\n end",
"def lineno= integer\n #This is a stub, used for indexing\n end"
] | {
"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",
"def registerNewEvent(event) \n @Events.push event\n end",
"def push(event)\n @events.push(event)\n end",
"def add_event(event_id)\n\t\treturn ERR_UNSUCCESSFUL if not Event.exists?(event_id)\n\t\tself.event_list |= [event_id]\n\t\tself.update_attribute(:event_list, self.event_list)\n\t\tSUCCESS\n\tend",
"def add_event(event)\n raise \"No name given.\" if !event[:name]\n\n @events[event[:name]] = [] if !@events.key?(event[:name])\n @events[event[:name]] = {\n :event => event,\n :callbacks => {},\n :callbacks_count => 0\n }\n end",
"def add_events(*events)\n events.each do |event|\n self.add_event(:name => event)\n end\n end",
"def save_event(event)\n @events.push(event)\n end",
"def register(event)\n attended_events << event\n end",
"def push_event event\n @event_queue << event\n end",
"def add_event(e, task_id)\n @events[task_id] ||= []\n @events[task_id] << e\n end",
"def schedule(event)\n # IMPLEMENT ME\n @events << event\n end",
"def attach_event event\n self.attached_events ||= []\n self.attached_events << event\n end",
"def subscribeTo (event)\r\n @subscribedEvents.add(event)\r\n end",
"def addEvent(name, event)\n @sports[name].addEvent(event)\n @eventCount +=1\n end",
"def add_event(&block) #:yield:event\n push Vevent::Maker.make( &block )\n end",
"def add_raw_event(new_event)\n @rawevents << new_event\n end",
"def add_event(event)\n processed_event = processor_stack.call(event.merge(event_metadata))\n\n return unless processed_event\n\n validate_event_keys(processed_event)\n\n events << formatter.call(processed_event)\n end",
"def add(name, event)\n chain[name] = event\n end"
] | {
"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 clear\n @talks.sort_by {|task| task.start_time }.each do |t|\n puts \"#{t.start_time.strftime(\"%I:%M%p\").delete_prefix(\"0\").downcase} - #{t.end_time.strftime(\"%I:%M%p\").delete_prefix(\"0\").downcase}\"\n puts \" #{t.name} presented by #{t.speaker.name}\"\n end\n puts\n end",
"def show_events\n @event_list.each do |restaurant, diners|\n print restaurant, diners\n end\n @event_list\n end",
"def show_events(num, today = Date.today, io = $stdout)\n return if num == 0\n hl = HighLine.new($stdin, io)\n\n d_e = days_events\n io.puts \"Events:\"\n num.times do |i|\n date = today + i\n str = \" #{date.to_s} #{WEEKDAYS[date.wday]} \"\n\n case date.wday\n when 0\n hl.say(\" <%= color('#{str}', :white, :on_red) %>\\n\")\n when 6\n hl.say(\" <%= color('#{str}', :white, :on_blue) %>\\n\")\n else\n hl.say(\" <%= color('#{str}', :white, :on_black) %>\\n\")\n end\n\n events = d_e[date]\n if events # if plan is not empty.\n #HIGHLINE.say(\"<%= color('red', :red) %>!\")\n #HIGHLINE.say(\" <%= color(#{date.to_s} #{WEEKDAYS[date.wday]}, :white, :red) %>\")\n #hl.say(\" <%= color('red', :red) %>!\")\n #io.puts str\n events.sort_by{|i| i.datetime}.each do |event|\n #pp event\n\n io.print(\" \") #indent\n event_date = Date.new(event.datetime.year,\n event.datetime.month,\n event.datetime.day)\n if event_date != date\n io.printf(\"<%02d/%02d>\", event.datetime.month, event.datetime.day )\n elsif event.flag_time\n io.printf(\"[%02d:%02d]\", event.datetime.hour, event.datetime.minute )\n else\n io.print(\" \")\n end\n io.printf(\"%s\", event.class::SYMBOL_CHAR )\n io.printf(\"%-2s \", event.option.to_s )\n io.puts \"#{event.description}\"\n\n #io.puts \" #{event.description.strip}\"\n end\n else\n io.puts \" (no event)\"\n end\n io.puts\n end\n end",
"def print_events\n\t\t@dungeon.rooms.each_with_index { |room, room_id|\n\t\t\tnext if room.unused?\n\t\t\t\n\t\t\t# Gather room events\n\t\t\tevents = @dungeon.room_at(room_id).events\n\t\t\tnext if events.empty?\n\t\t\t\n\t\t\t\n\t\t\t# Create and print the block\n\t\t\tblock = Block_Templates.events_block(events)\n\t\t\tbegin\n\t\t\t\t@document.print_block_edit(block, @dungeon.coordinate(room_id),\n\t\t\t\t\t[1, 1])\n\t\t\trescue Printing_Error => error\n\t\t\t\t@handler.handle(error)\n\t\t\tend\n\t\t}\n\tend",
"def run events\n events.each do |event| \n interprete event\n end\n# return\n puts \"Statistics:\"\n @counts.each do |k,v|\n puts \"#{k.inspect} =>\"\n i = 0\n step = 6\n while i < v.size\n puts \"\\t#{v[i,step]}\"\n i += step\n end\n end\n end",
"def print_pod_events(pod)\n @output.puts \"POD EVENTS:\"\n print_events(pod.events)\n end",
"def print(io)\n tree.each_with_index do |(command, event_called_handlerss), index|\n io.puts '+++++++++++++++++++++++++++++++++++' if index == 0\n io.puts \"Command: #{command.class} resulted in #{event_called_handlerss.length} events\"\n event_called_handlerss.each_with_index do |event_called_handlers, i|\n io.puts '' if i > 0\n io.puts \"-- Event #{event_called_handlers.event.class} was handled by:\"\n io.puts \"-- Projectors: [#{event_called_handlers.projectors.join(', ')}]\"\n io.puts \"-- Workflows: [#{event_called_handlers.workflows.join(', ')}]\"\n end\n\n io.puts '+++++++++++++++++++++++++++++++++++'\n end\n end",
"def activity_output(obs)\n Thread.start do\n obs.each do |event, tuple|\n puts \"#{event} #{tuple[1]} #{tuple[3]} URI: #{tuple[2].__drburi} ref: #{tuple[2].__drbref}\"\n end\n end\n end",
"def print_events_on_date(date)\n return NO_EVENTS_IN_CALENDAR unless events?\n return NO_EVENTS_AT_DATE unless events_at?(date)\n\n events = @calendar_events[date]\n puts \"Your events on #{date}\"\n print_events(events)\n end",
"def eventDetails(date)\n month , day, year = parseDate(date)\n # puts \"#{date} : \\nDetails for events are : \"\n events = @cal[year][month][year + \"-\" + month + \"-\" + day]\n events.each_with_index { |event, index|\n\n puts \"#{event.printDetails()}\"\n\n }\n end",
"def on_events\n\t\tputs \"\\nEvents in selected room:\"\n\t\t\n\t\t# Display list of events and assigns temporary menu commands\n\t\t@room.events.each_with_index { |event, i|\n\t\t\tindex = (i + 1).to_s\n\t\t\t\n\t\t\tputs \"##{index}: #{event.sformat_asm}\"\n\t\t\t\n\t\t\tcomm = Command.new(index, method(:on_modify_event), [], [i])\n\t\t\tcurrent_menu.add_command(comm)\n\t\t}\n\tend",
"def print_fina_events\n return if self.financial_events.empty?\n\n puts \"ID\\t日期\\t\\t类型\"\n self.financial_events.order(:event_date).each do |fe|\n pretty_json = JSON.pretty_generate(JSON.parse(fe.change_in_json))\n puts \"#{fe.id}\\t#{fe.event_date}\\t#{fe.financial_event_type.name}\"\n puts \"明细: \\n#{pretty_json}\"\n puts\n end\n\n nil\n end",
"def print_event(printer, event)\n $stdout.puts printer.call(event)\nend",
"def showAll()\n\t\tlogs = @log.sort\n\t\tputs \"******************LOG****************OLD\\n\"\n\t\tlogs.each { |date,item| printDate(date)\t} \n\t\tputs \"******************LOG END************NEW\\n\"\n\n\tend",
"def output_events\n @events.map do |event|\n adjusted_event = event.clone\n adjusted_event.at += @start_time\n adjusted_event\n end\n end",
"def process_event(event)\n puts(\"#{event.id} - #{event.description}\")\nend",
"def print_shows()\n\t\tputs 'SHOWS:'\n\t\t@config.get_groups.each_with_index do |group, index|\n\t\t\tputs \"#{index+1}) [#{@config[group.to_s]['finished'] == 'true' ? \"\\u2713\".encode('utf-8') : \"\\u2717\".encode('utf-8')}] #{group} #{\"\\u2799\".encode('utf-8')} s.#{@config[group.to_s]['season']} ep.#{@config[group.to_s]['episode']}\"\n\t\tend\n\tend"
] | {
"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
elsif i == '}' or i == ')' or i == ']'
if empty?(symbol_stack) == false
top_symbol = symbol_stack.pop
if i == '}' and top_symbol != '{'
next
end
end
elsif i == ','
other_list << exe_point
if symbol_stack.length.zero?
other_list.each do |thing|
exe += thing
end
if exe.include? 'startTraceNow'
on = true
exe = ''
exe_point = ''
other_list = []
elsif exe.include? 'endTraceNow'
off = true
return
else
flag = verify_exe_point(on, off, exe)
on = false if flag == false
exe = ''
exe_point = ''
other_list = []
end
else
exe_point = ''
end
else
next
end
end
end | [
"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 end\n print \"exit\"\n end\n end",
"def count_trace(solution)\n @trace = solution.join(\",\")\n state = solution\n @trace_length = -1\n while get_predecessor(state)\n state = get_predecessor(state)\n @trace = (state != \"first\" ? state.join(\",\") : \"first\") + \" >> \" + @trace\n @trace_length += 1\n end\n end",
"def call_details\n @@_monitor.synchronize{\n\n # Skip first 3 on stack (i.e. 0 = block in call_details, 1 = synchronize, 2 = call_detail)\n stack = caller_locations(3, 20)\n\n # Skip past any calls in 'log.rb' or 'monitor.rb'\n i = -1\n while i += 1 do\n mod = File.basename(stack[i].path, '.rb')\n break if !['log', 'monitor'].include?(mod)\n end\n\n # Save lineno from original location\n lineno = stack[i].lineno\n\n # Skip over block type functions to use method.\n # Note: there may not be a non block method e.g. in thread case\n regexps = [Regexp.new('^rescue\\s.*in\\s'), Regexp.new('^block\\s.*in\\s'), Regexp.new('^each$')]\n while regexps.any?{|regexp| stack[i].label =~ regexp} do\n break if i + 1 == stack.size\n i += 1\n end\n\n # Set label, clean up for block case\n label = stack[i].label\n regexps.each{|x| label = label.gsub(label[x], \"\") if stack[i].label =~ x}\n label = stack[i].label if label.empty?\n\n # Construct stamp\n location = \":#{File.basename(stack[i].path, '.rb')}:#{label}:#{lineno}\"\n return Time.now.utc.iso8601(3), location\n }\n end",
"def trace_execution_steps(&block)\n begin\n @trace_execution_steps_counter += 1\n yield\n ensure\n @trace_execution_steps_counter -= 1\n end\n end",
"def trace(begX, begY, endX, endY); MazeSolver.new(plane,graph).trace(begX, begY, endX, endY) end",
"def trace(begX, begY, endX, endY)\n\t\tclear_all\n\t\tnode = @nodes[endY][endX]\n\t\tif solve(begX, begY, endX, endY)\n\t\t\tbegin\n\t\t\t\tnode.node_string = \"X\"\n\t\t\tend while node = node.predecessor\n\t\telse\n\t\t\tputs \"No Solution\"\n\t\tend\n\tend",
"def trace_run(context = \"::\", called_at=caller[1], args=[])\n tracer = Thread.current['st.tracer']\n result = nil\n if tracer.nil?\n Rails.logger.debug{\"Null trace\"}\n result = yield\n else\n tracer.run(context, called_at, args){ result = yield }\n end\n result\n end",
"def trace_execution_scoped_header(options, t0=Time.now.to_f)\n scope = log_errors(\"trace_execution_scoped header\") do\n push_flag!(options[:force])\n scope = stat_engine.push_scope(:method_tracer, t0, options[:deduct_call_time_from_parent])\n end\n # needed in case we have an error, above, to always return\n # the start time.\n [t0, scope]\n end",
"def debug_info\n if @@our_debug\n puts \"#{debug_time} Eval For_class. Start idx #{@start.value}, End idx #{@end.value}\"\n puts \"#{debug_time} Block content: #{@stmts}\"\n end\n end",
"def get_traceT()\n return @traceT\n end",
"def trace(begX, begY, endX, endY)\n result = maze_solver(begX, begY, endX, endY)\n if result == false\n puts \"Maze not solvable.\"\n else\n MazePrinter.print_trace(self, result)\n end\n end",
"def trace(begX, begY, endX, endY)\n path,solution = solve(begX, begY, endX, endY)\n if(solution.length != 0)\n solution.each{|x| self.graph[x[0]][x[1]] = '@'}\n puts graph.map { |x| x.join(' ') }\n else\n puts \"There are no way from #{[begX,begY]} to #{[endX,endY]}\"\n end\n end",
"def execution_summary; end",
"def trace\n set_trace_func proc { |event, _file, _line, id, binding, classname|\n if event == watched && id != :log && classes.include?(classname.to_s)\n vars = variables(binding)\n\n if vars.empty?\n log_this(sprintf(\"%s %-25s #%-20s\",\n class_count, classname, id))\n\n else\n log_this(sprintf(\"%s %-25s #%-20s\\n%s\\n\",\n class_count, classname, id, vars))\n\n end\n end\n } if trace?\n end",
"def possibly_add_trace_info_calls(line)\n # If the current line does not start a logical line, don't bother\n if not @state[:ll_start]\n return line\n end\n\n # We will be making decisions based on the first word on the line\n line_words = line.split\n if line_words.empty?\n # The line is empty, so we disregard it\n return line\n end\n first_word = line_words[0]\n\n # Extract first word and check if it makes us want to refrain from adding a line number call\n if KEYWORDS_WITHOUT_LINE_NUMBERS.include?(first_word)\n # It's one of the statements we don't want\n return line\n\n elsif [\"'\", '\"', \"#\"].include?(first_word[0])\n # The line starts with a string or with a comment\n return line\n end\n\n # Do include a line number call\n return \"#{@state[:indent_string]}garbledwebpiratenlibraryname.debug(locals(), globals())\\n\" +\n \"#{@state[:indent_string]}garbledwebpiratenlibraryname.line(#{@state[:line_number]})\\n\" +\n \"#{line}\"\n end",
"def staged_trace(trace_id)\n candidate = nil\n @staging_lock.synchronize {\n @staging_queue.each do |trace|\n if trace.id == trace_id\n candidate = trace\n break\n end\n end\n }\n unless candidate\n ::Instana.logger.debug(\"Couldn't find staged trace with trace_id: #{trace_id}\")\n end\n candidate\n end",
"def current_trace\n if @@spans.empty?\n nil\n else\n @@spans.slice(-1)\n end\n end",
"def texify exec_trace\n document_text = \"\"\n File.open \"preamble.tex\" do |file|\n while line = file.gets\n document_text += line\n end\n end\n document_text += \"\\\\begin{document}\\n\"\n stages = get_stages exec_trace\n stages.each do |stage|\n document_text += \"\\\\begin{frame}\\n\\n\"\n document_text += state_text stage.i_heap, stage.i_store\n document_text += \"\\n\"\n document_text += \"Current command: \"\n document_text += \"\\\\il{#{stage.text}}\"\n document_text += \"\\n\"\n document_text += \"\\\\vspace{1cm}\\n\\n\"\n document_text += state_text stage.f_heap, stage.f_store\n document_text += \"\\\\end{frame}\"\n document_text += \"\\n\"\n end\n document_text\nend"
] | {
"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 @podval = Podval.find(params[:id])\n @podval.destroy\n\n respond_to do |format|\n format.html { redirect_to(podvals_url) }\n format.xml { head :ok }\n end\n end",
"def index\n @pods = Pod.all\n end",
"def index\n @known_values = KnownValue.find(:all, :order => 'name')\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @known_values }\n end\n end",
"def getResponseProps (resp, props)\n doc = Document.new resp.body\n results = []\n props.each { |s|\n doc.root.elements.each {|e| \n if e.attributes['name'] && e.attributes['name'] == s\n results << e.attributes['value']\n break\n end\n }\n }\n results \nend",
"def get_current_users_preferences \n get(\"/userproperties.json/preferences/\")\nend",
"def prop_find(url, properties, depth = 0)\n dom = LibXML::XML::Document.new\n\n root = LibXML::XML::Node.new('d:propfind')\n LibXML::XML::Namespace.new(root, 'd', 'DAV:')\n prop = LibXML::XML::Node.new('d:prop')\n\n properties.each do |property|\n (namespace, element_name) = Tilia::Xml::Service.parse_clark_notation(property)\n\n if namespace == 'DAV:'\n element = LibXML::XML::Node.new(\"d:#{element_name}\")\n else\n element = LibXML::XML::Node.new(\"x:#{element_name}\")\n LibXML::XML::Namespace.new(element, 'x', namespace)\n end\n\n prop << element\n end\n\n dom.root = root\n root << prop\n\n body = dom.to_s\n\n url = absolute_url(url)\n\n request = Http::Request.new(\n 'PROPFIND',\n url,\n {\n 'Depth' => depth,\n 'Content-Type' => 'application/xml'\n },\n body\n )\n\n response = send_request(request)\n\n fail Http::ClientHttpException.new(response) if response.status.to_i >= 400\n\n result = parse_multi_status(response.body_as_string)\n\n # If depth was 0, we only return the top item\n if depth == 0\n result = result.first.second # value of first key/value pair\n return result.key?('200') ? result['200'] : {}\n end\n\n new_result = {}\n result.each do |href, status_list|\n new_result[href] = status_list.key?('200') ? status_list['200'] : {}\n end\n\n new_result\n end",
"def search(params)\n http.get(\"/service-values\", { params: params }) do |response|\n respond_with_collection(response)\n end\n end",
"def index\n @config_values = ConfigValue\n .page(params[:page])\n .per(10)\n end",
"def get_alert_summary \n get(\"/alerts.json/summary\")\nend",
"def vips\n request :get, '/vips'\n end",
"def index\n @valves = Valve.all\n end",
"def index\n @policy_valuations = PolicyValuation.all\n end",
"def afnetworking_cocoadocs_pod_metrics\n Domain.cocoadocs_pod_metrics.where(pod_id: afnetworking.id).all\n end",
"def index\n @ipadmissions = Ipadmission.all\n\t@v= Verify.new\n\t@value=@v.retrive(\"IP Admission\")\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @ipadmissions }\n end\n end",
"def index\n @pod_reports = PodReport.all\n end",
"def ps(app_name)\n deprecate # 07/31/2012\n json_decode get(\"/apps/#{app_name}/ps\", :accept => 'application/json').to_s\n end",
"def get_endpoints_with_status (doc,vulnerability,type,findings)\n \tnodestring = \"/NexposeReport/nodes/node/endpoints/endpoint/services/service/tests/test[@status='\"+ type + \"' and @id='\" + vulnerability + \"']/ancestor::node\"\n\tendpointstring = \"/NexposeReport/nodes/node/endpoints/endpoint/services/service/tests/test[@status='\"+ type + \"' and @id='\" + vulnerability + \"']/ancestor::endpoint\"\n\n\tvulnerable_node = doc.xpath(nodestring)\n\tvulnerable_endpoint = doc.xpath(endpointstring)\n\n\tvulnerableNodesAddress = vulnerable_node.xpath(\"./@address\").to_a\n\tvulnerableEndpointPort = vulnerable_endpoint.xpath(\"./@port\").to_a\n\tvulnerableEndpointService = vulnerable_endpoint.xpath(\"./services/service/@name\").to_a\n\tvulnerableEndpointKey = vulnerable_endpoint.xpath(\"./services/service/@key\").to_a\n\tvulnerableEndpointFingerprint = vulnerable_endpoint.xpath(\"./services/service/fingerprints\").to_a\n\tvulnerableEndpointConfiguration = vulnerable_endpoint.xpath(\"./services/service/configuration\").to_a\n\tvulnerableEndpointProof = vulnerable_endpoint.xpath(\"./services/service/tests/test[@status='\"+ type + \"' and @id='\" + vulnerability + \"']\").collect(&:text).to_a\n\n\tif !vulnerableNodesAddress.empty? then\n\t\tprint \"DEBUG: found \" + vulnerableNodesAddress.count.to_s + \" endpoint instances.\\n\" \n\t\tfor i in (0..vulnerableNodesAddress.count - 1)\n##\t\t\tprint \"DEBUG: Vulnerable Endpoint: \" + vulnerableNodesAddress[i].to_s + \" \" + vulnerableEndpointPort[i].to_s + \" \" + vulnerableEndpointService[i].to_s + \"\\n\"\n\n\t\t\t# Not sure this applies - TODO\n\t\t\tfindings[vulnerability][:notes] += vulnerableEndpointFingerprint[i].to_s + \"\\n\\n\"\n\t\t\tfindings[vulnerability][:notes] += vulnerableEndpointConfiguration[i].to_s + \"\\n\\n\"\n\t\t\tfindings[vulnerability][:affects] += vulnerableNodesAddress[i].to_s + \":\" + vulnerableEndpointPort[i].to_s + \" \" + vulnerableEndpointKey[i].to_s + \" (\" + vulnerableEndpointService[i].to_s + \")\\n\"\n\t\t\tfindings[vulnerability][:proof] += vulnerableEndpointProof[i].to_s + \"\\n\"\n\t\tend\n\tend\nend"
] | {
"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",
"def new\n @versioned_jnlp_url = MavenJnlp::VersionedJnlpUrl.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @versioned_jnlp_url }\n end\n end",
"def new\n @version = @page.versions.new\n\n respond_to do |format|a\n format.html # new.html.erb\n format.xml { render :xml => @version }\n end\n end",
"def new\n @known_value = KnownValue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @known_value }\n end\n end",
"def new\n @valve = Valve.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @valve }\n end\n end",
"def new\n @policy_change = PolicyChange.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @policy_change }\n end\n end",
"def new\n @pdig = Pdig.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pdig }\n end\n end",
"def new\n @p_stat = PStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @p_stat }\n end\n end",
"def new\n @proyectostatus = Proyectostatus.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @proyectostatus }\n end\n end",
"def new\n @prac = Prac.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prac }\n end\n end",
"def new\n @versioned_jnlp = MavenJnlp::VersionedJnlp.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @versioned_jnlp }\n end\n end",
"def new\n @pulve = Pulve.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @pulve }\n end\n end",
"def new\n @prd_threshold = PrdThreshold.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @prd_threshold }\n end\n end",
"def new_rest\n @v1_page_usage = V1PageUsage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @v1_page_usage }\n end\n end",
"def new\n @periode = Periode.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @periode }\n end\n end",
"def new\n @prepod = Prepod.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @prepod }\n end\n end",
"def new\n @newtype = params[:newtype]\n @ptbudget = Ptbudget.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ptbudget }\n end\n end",
"def new\n @config_value = ConfigValue.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @config_value }\n end\n end"
] | {
"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 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 delete_all(value)\n\t\tdeleted_node = self.delete(value, true)\n\tend",
"def destroy\n @xray_value = XrayValue.find(params[:id])\n @xray_value.destroy\n\n respond_to do |format|\n format.html { redirect_to(xray_values_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @prop_value = PropValue.find(params[:id])\n @prop_value.destroy\n\n respond_to do |format|\n format.html { redirect_to(prop_values_url) }\n format.xml { head :ok }\n end\n end",
"def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def destroy\n @v1_data_element = V1DataElement.find(params[:id])\n @v1_data_element.destroy\n\n respond_to do |format|\n format.html { redirect_to(v1_data_elements_url) }\n format.xml { head :ok }\n end\n end",
"def cmd_delete argv\n setup argv\n e = @hash['element']\n response = @api.delete(e)\n msg response\n return response\n end",
"def destroy\n @config_xml = ConfigXml.find(params[:id])\n @config_xml.destroy\n\n respond_to do |format|\n format.html { redirect_to(config_xmls_url) }\n format.xml { head :ok }\n end\n rescue ActiveRecord::RecordNotFound => e\n prevent_access(e)\n end",
"def destroy\n @nagios_service_escalation = NagiosServiceEscalation.find(params[:id])\n @nagios_service_escalation.destroy\n\n respond_to do |format|\n format.html { redirect_to(nagios_service_escalations_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n name, type = resource[:name].split('/')\n nameserver = resource[:nameserver]\n nsupdate(\"server #{nameserver}\n update delete #{name}. #{type}\n send\")\n end",
"def delete(oid)\n end",
"def destroy\n @primary_expr = PrimaryExpr.find(params[:id])\n @primary_expr.destroy\n\n respond_to do |format|\n format.html { redirect_to(primary_exprs_url) }\n format.xml { head :ok }\n end\n end",
"def del\n @office1 = Office1.find(params[:id])\n @office1.destroy\n\n respond_to do |format|\n format.html { redirect_to(office1s_url) }\n format.xml { head :ok }\n end\n end",
"def delete\n spec[DELETE]\n end",
"def destroy\n @pdig = Pdig.find(params[:id])\n @pdig.destroy\n\n respond_to do |format|\n format.html { redirect_to(pdigs_url) }\n format.xml { head :ok }\n end\n end"
] | {
"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 format.json { render json: @property }\n end\n end",
"def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end",
"def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end",
"def new\n @prop = Prop.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @prop }\n end\n end",
"def new\n @add_property = AddProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @add_property }\n end\n end",
"def new\n @property = @user.properties.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @property }\n end\n end",
"def new\n @spec_property = SpecProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @spec_property }\n end\n end",
"def new\n @prop = @project.props.new\n @project = @props.project\n\n redirect_to\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @prop }\n end\n end",
"def new\n @personal_property = PersonalProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @personal_property }\n end\n end",
"def new\n @leased_property = LeasedProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @leased_property }\n end\n end",
"def new\n @myprop = Myprop.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @myprop }\n end\n end",
"def new\n @property_field = PropertyField.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property_field }\n end\n end",
"def new\n @sample_property = SampleProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @sample_property }\n end\n end",
"def new\n @rent = Rent.new\n @properties = AddProperty.find(:all, :conditions =>\" is_rented = 0 \");\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @rent }\n end\n end",
"def new\n @web_property = WebProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @web_property }\n end\n end",
"def new\n @project_property = ProjectProperty.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project_property }\n end\n end",
"def new\n \tunless ServerProperty.count > 0\n\t @server_property = ServerProperty.new\n\t\telse\n\t\t\tredirect_to server_properties_path, alert: \"There can only be one server properties file. Please update the existing record.\" and return\n\t\tend\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @server_property }\n end\n end",
"def new\n @property = Property.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @property }\n end\n end"
] | {
"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(
unblinded_responses_count: nil,
unblinded_questions_count: nil,
unblinded_percent: nil,
blinded_responses_count: nil,
blinded_questions_count: nil,
blinded_percent: nil
)
end | [
"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.where( :test_id => self.id ).each do |response|\n response.delete\n end\n \n self.complete = false\n self.unanswered = nil\n self.queue = nil\n self.state = nil\n self.started_at = nil\n self.trial = nil\n self.study_pass = nil \n end",
"def clear_all\n @sheets = []; self\n end",
"def reset_counts!\n temp_invitation_count.clear\n temp_visit_count.clear\n temp_invitation_accepted_count.clear\n survey_version_counts.destroy_all\n save\n end",
"def reset\n @results = nil\n end",
"def reset\n @count = 0\n end",
"def reset!\n @last_response = nil\n @last_exit_code = nil\n end",
"def reset_contents\n self.quizzes.destroy_all\n end",
"def reset_response\n self.instance_variable_set(:@_response_body, nil)\n end",
"def reset\n @accounts = Hash.new\n @account_id_count = 0\n end",
"def reset_response\n self.instance_variable_set(:@_response_body, nil)\n end",
"def reset\n @collected_metrics = []\n end",
"def reset_analysis\n @extra_lives = 0\n @voids.clear\n @eyes.clear\n end",
"def reset_rule_counts\n rules_collection.rules.each(&:reset_counter)\n end",
"def reset(pricing_rules = nil)\n @pricing_rules = pricing_rules unless pricing_rules.nil?\n @counter = Hash.new(0)\n end",
"def reset()\r\n @strikes = 0\r\n @balls = 0\r\n end",
"def clear_existing_calc_results!(measure)\n self.calc_results.reject! { |result| result['measure_id'] == measure.hqmf_set_id } if self.calc_results\n self.condensed_calc_results.reject! { |result| result['measure_id'] == measure.hqmf_set_id } if self.condensed_calc_results\n self.results_exceed_storage = false\n self.results_size = 0\n self.save!\n end",
"def clear!\n @requests.clear\n end"
] | {
"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 }
end
else
render_error('Favourite not found', 404)
end
end | [
"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_connect {|conn| create_http_post_request(uri) }\n when :remove\n response = http_connect {|conn| create_http_delete_request(uri) }\n end\n bless_model(Twitter::Status.unmarshal(response.body))\n end",
"def favorite(id)\n post(\"/favorites/create/#{id}.json\")\n end",
"def add_favorite username, password, slideshow_id\n do_request 'add_favorite', username: username, password: password, slideshow_id: slideshow_id\n end",
"def create\n @fav = Fav.new(fav_params)\n @fav.id = @fav.collectionId\n if @fav.save\n render json: @fav, status: :created, location: api_fav_path(@fav)\n else\n render json: @fav.errors, status: :unprocessable_entity\n end\n end",
"def favorite_foods\n get(\"/user/#{@user_id}/foods/log/favorite.json\")\n end",
"def add_to_favourites\n \n #pull out whichever recipe you are clicking on\n yummly_id = params[:yummly_id]\n recipe = Yummly.find(yummly_id)\n\n # make new instance of that recipe\n r = Recipe.find_or_create_by(name: recipe.name, thumbnail: recipe.thumbnail)\n\n UserFavouriteRecipe.create(recipe_id: r.id, user_id: current_user.id, yummly_id: yummly_id)\n\n redirect_to recipes_url, notice: \"Added recipe from your list of favourite recipes\"\n\n end",
"def show\n render json: @favourites\n end",
"def create_favorite(favorite_params)\n handle_error { sendsecure_connection.post(\"api/v2/enterprises/#{@enterprise_account}/users/#{@user_id}/favorites.json\", favorite_params) }\n end",
"def index\n @favourites = Favourite.all\n render json: @favourites\n end",
"def create\n @favourites = Favourite.new()\n @favourites.user_id = current_user.id;\n @favourites.army_list_id = params[:favourite][:army_list_id]\n \n respond_to do |format|\n if @favourites.save\n flash[:notice] = 'Favourites was successfully created.'\n format.html { redirect_back_or_default(user_favourites_url(current_user)) }\n format.xml { render :xml => @favourites, :status => :created, :location => @favourites }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @favourites.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def favorites\n handle_error { sendsecure_connection.get(\"api/v2/enterprises/#{@enterprise_account}/users/#{@user_id}/favorites.json\") }\n end",
"def get_user_favorites username_for\n do_request 'get_user_favorites', username_for: username_for\n end",
"def add_word_to_favorites(word, *args)\n http_method = :post\n path = '/word/{word}/favorite'\n path.sub!('{word}', word.to_s)\n\n # Ruby turns all key-value arguments at the end into a single hash\n # e.g. Wordnik.word.get_examples('dingo', :limit => 10, :part_of_speech => 'verb')\n # becomes {:limit => 10, :part_of_speech => 'verb'}\n last_arg = args.pop if args.last.is_a?(Hash)\n last_arg = args.pop if args.last.is_a?(Array)\n last_arg ||= {}\n\n # Look for a kwarg called :request_only, whose presence indicates\n # that we want the request itself back, not the response body\n if last_arg.is_a?(Hash) && last_arg[:request_only].present?\n request_only = true\n last_arg.delete(:request_only)\n end\n\n params = last_arg\n body ||= {}\n request = Wordnik::Request.new(http_method, path, :params => params, :body => body)\n request_only ? request : request.response.body\n end",
"def get_favorites\n authenticate_rem\n follower = @current_user || User.find_by_id(params[:user_id])\n render json: Product.order(created_at: :desc).limit(20).map(&:simple_info.with(follower)),\n status: :ok\n end",
"def add_favorite_food(food_id)\n post(\"user/#{user_id}/foods/log/favorite/#{food_id}.json\")\n end",
"def test_new_favourite_and_remove_favourite\n \n user = User.getByUsername(\"Adam\")\n bookmark = Bookmark.getAll[0]\n \n result = Favourite.newFavourite(bookmark.bookmarkId, user.userId)\n \n assert_equal true, result\n \n favourites = Favourite.getByUserId(user.userId)\n \n favourite = favourites[0]\n \n assert_equal \"amazon\", favourite.title\n assert_equal bookmark.bookmarkId, favourite.bookmarkId\n \n resultTwo = Favourite.removeFavourite(bookmark.bookmarkId, user.userId)\n \n assert_equal true, resultTwo\n \n end",
"def add_to_favorite\n @structure = Structure.find(params[:id])\n @structure.user_favorites.create(user: current_user)\n # AdminMailer.delay(queue: 'mailers').user_is_now_following_you(@structure, current_user)\n respond_to do |format|\n format.html { redirect_to structure_path(@structure), notice: \"#{@structure.name} a été ajouté à vos favoris\"}\n format.json { render json: { succes: true } }\n end\n end",
"def show_favorites\n authenticate_rem\n follower = @current_user || User.find_by_id(params[:user_id])\n render json: follower.favorite_products.map(&:simple_info.with(follower)), status: :ok\n end",
"def favorite\n user = current_user.uid\n response = TunesTakeoutWrapper.favorite(user, params[\"suggestion\"])\n redirect_to root_path\n end"
] | {
"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[:accepted] || status == Friendship::STATUS[:declined]) && status_was == Friendship::STATUS[:pending]\n end",
"def notifications_to_show_user\n notifications ||= UserEvent.where('user_id = ? AND error_during_render = ? AND event_type != ?', self.id, false, UserEvent.event_type_value(:video_play))\n end",
"def number_notifications_not_seen\n Notification.where(:seen => false, :user_id => self.id).count\n end",
"def notified_users_with_custom_users\n notified = notified_users_without_custom_users\n\n notified_custom_users = (custom_users + custom_users_was).select do |u|\n u.active? && u.notify_custom_user?(self) && visible?(u)\n end\n notified += notified_custom_users\n notified.uniq\n end",
"def validate_seen\n errors.add(:seen, :must_be_false_if_new_record) if !@notification && self.seen\n end",
"def put_seenNotification\n user = User.where(id: params[:idUser]).first\n token = params[:auth_token]\n if(user.auth_token == token)\n req = Notification.where(id: params[:idNotification]).first\n req.update(:seen=>true)\n\n\n render json: { status: 'SUCCESS', message: 'Notificacion actualizada' }, status: :ok\n else\n render json: { status: 'INVALID', message: 'Token invalido'}, status: :unauthorized\n end\n end",
"def notified_users_with_custom_users\n notified = notified_users_without_custom_users\n\n custom_users_current = custom_users\n custom_users_changed = custom_users_added_or_removed\n\n notified_custom_users = (custom_users_current + custom_users_changed).select do |u|\n u.active? && u.notify_custom_user?(self, custom_users_current, custom_users_changed) && visible?(u)\n end\n notified += notified_custom_users\n notified.uniq\n end",
"def show_notifications # :norobots:\n pass_query_params\n data = []\n @observation = find_or_goto_index(Observation, params[:id].to_s)\n return unless @observation\n name_tracking_emails(@user.id).each do |q|\n fields = [:naming, :notification, :shown]\n naming_id, notification_id, shown = q.get_integers(fields)\n next unless shown.nil?\n notification = Notification.find(notification_id)\n if notification.note_template\n data.push([notification, Naming.find(naming_id)])\n end\n q.add_integer(:shown, 1)\n end\n @data = data.sort_by { rand }\n end",
"def get_no_unseen_notification_messages\n if NotificationMessage.exists?(:receiver_user => @current_user.id)\n @notification_message = NotificationMessage.where(:receiver_user => @current_user.id).where(:is_seen => 0)\n @unseen_notification_messages = @notification_message.count\n render json: {status: 'SUCCESS', message: 'Notifications are seen by user', no_unseen_notification_messages: @unseen_notification_messages},status: :ok\n else\n render json: {status: 'FAIL', message: 'No Notification messages For this user'},status: :ok\n end \n end",
"def online_notification_seen_state(user_id_check = nil)\n state = Ticket::State.find_by(id: state_id)\n state_type = Ticket::StateType.find_by(id: state.state_type_id)\n\n # always to set unseen for ticket owner and users which did not the update\n if state_type.name != 'merged'\n if user_id_check\n end\n end\n\n # set all to seen if pending action state is a closed or merged state\n if state_type.name == 'pending action' && state.next_state_id\n state = Ticket::State.find_by(id: state.next_state_id)\n state_type = Ticket::StateType.find_by(id: state.state_type_id)\n end\n\n # set all to seen if new state is pending reminder state\n if state_type.name == 'pending reminder'\n if user_id_check\n return false if owner_id == 1\n\n return true\n end\n return true\n end\n\n # set all to seen if new state is a closed or merged state\n return true if state_type.name == 'closed'\n return true if state_type.name == 'merged'\n\n false\n end",
"def mark_shown_invite_friends\n current_user.shown_invite_friends!\n render nothing: true\n end",
"def user_notification_on\n self.user_notification_enabled_for_model = true\n end",
"def mark_seen\n payload = {\n recipient: sender,\n sender_action: 'mark_seen'\n }\n\n Facebook::Messenger::Bot.deliver(payload, access_token: access_token)\n end",
"def viewed(notificationID,user)\n @notification = Notification.find(notificationID)\n @notification.viewed = true\n @notification.save\n\tend",
"def users_to_notify\n super\n end",
"def personal_pnsqs_in_holder\n if ((@user = User.find_by_id(params[:id])) and (its_me?(@user)))\n\n @pnsqs = @user.privates_all\n\n # Notificaciones leidas\n @user.update_attributes(:notifications_count => 0)\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.js { render }\n end\n\n else\n error404\n end\n end",
"def unseen_notifications\n notifications.where(seen: false)\n end"
] | {
"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)\n @default_offsets[topic] = default_offset\n end",
"def initialize_from_notification(notification)\n @notification, @target, @batch_email = notification, notification.target, false\n end",
"def initialize(message, exceeding_offset)\n super(message)\n @exceeding_offset = exceeding_offset\n end",
"def setup_default_notifications\n #system wide notifications\n Notification.setup_default_notifications_for_user(self)\n end",
"def initialize\n @height = 0\n @offset = 0\n end",
"def notifications_visible_block(offset, limit)\n Notification.order('created_at DESC').where(:user_id => self.id).offset(offset).limit(limit)\n end",
"def offset=(value)\n @offset = value\n end",
"def offset=(new_offset)\n @offset = new_offset\n end",
"def offset\n 0 - @min\n end",
"def initialize initial\n @markers = [initial]\n end",
"def get_offset\n @offset\n end",
"def init_updates\n document.atomic_updates.tap do |updates|\n @conflicts = updates.delete(:conflicts) || {}\n end\n end",
"def offset(amount)\n @offset = amount.to_i\n end",
"def initialize\n self.marker_history = []\n end",
"def x_offset() @x_offset || 0.5; end"
] | {
"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.save!\n end",
"def visited!\n update_attributes(last_visited_at: Time.now) if !last_visited_at || last_visited_at <= AppConfig.channels.activity_threshold.ago\n end",
"def visit\n self.visited = Date.today\n end",
"def update_visited_moves\n visited_coordinates << [x , y]\n end",
"def update_users_last_visit\n if logged_in?\n if current_user.last_visit_at.nil?\n User.find(current_user.id).update_column('last_visit_at', Time.now)\n else\n if (current_user.last_visit_at + 1.hour) < Time.now \n User.find(current_user.id).update_column('last_visit_at', Time.now)\n end\n end\n end\n end",
"def set_last_current\n last = Permalink\n .where(linkable_id: linkable.id)\n .order_by(:updated_at.desc)\n .limit(1)\n .first\n if last\n last.update_attributes!(_current: true)\n end\n end",
"def visited?\n last_visited?\n end",
"def visited\n @visited ||= (begin\n visited = self.node.attributes.to_h[\"visited\"]\n visited ? Time.parse(visited) : nil\n end)\n end",
"def visit!\n $redis.set(visited_key(@url), true)\n end",
"def store_path_visited(path)\n redis.sadd paths_visited_key, path\n end",
"def toggle_visited\n if @visited == 't'\n @visited = 'f'\n elsif\n @visited = 't'\n end\n sql = \"UPDATE trips\n SET visited = $1\n WHERE id = $2\"\n values = [@visited, @id]\n SqlRunner.run(sql, values)\n end",
"def update_last_seen\n unless session[:user_id].nil?\n logged_in_user.update_attributes({ \"last_seen\" => Time.now, \"last_ip\" => request.env['REMOTE_HOST'] })\n end\n end",
"def update_visits_count\n self.update(visits: self.visits + 1)\n end",
"def update_last_access\n\n last_access = Time.now\n save\n\n end",
"def updatePinsVisited\n @user = User.find(params[:id])\n pinId = params[:pinId]\n pins_visited = @user.pins_visited + \",\" + pinId.to_s\n @user.update_attribute(:pins_visited, pins_visited)\n #@user.pins_visited = @user.pins_visited + \" \" + pinId.to_s\n @user.save\n render '/pins'\n end",
"def visited(user)\n # invisible = self.general_settings.anonymous_browsing\n invisible = false\n visit = UserVisit.where(\"visitor_id = ? AND user_id = ?\", self.id, user.id).first\n if visit\n visit.update_attributes({ visited_at: Time.now, seen: false, invisible: invisible })\n else\n visit = user.user_visits.build({ visited_at: Time.now, invisible: invisible })\n visit.visitor_id = self.id\n visit.save\n end\n\n if visit && !invisible\n user.notifications.create({ sender_id: self.id, notifiable_id: visit.id, notifiable_type: 'visit' })\n send_notification_email(:profile_visit, user)\n end\n end",
"def action_save_href\n href = @current_attributes['href']\n if href_index = @links.index(href)\n @last_link_index = href_index + 1\n else\n @links << href\n $links << href\n @last_link_index = @links.size\n end\n end"
] | {
"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 false\n end\n end",
"def creator_in_system\n\t\tcreator_ids = User.all.map { |user| user.id }\n\t\tunless creator_ids.include?(self.user_id)\n\t\t\terrors.add(:creator, 'is not recognized by the system')\n\t\t\treturn false\n\t\tend\n\t\ttrue\n\tend",
"def creator?\n if session[:user_id] == @event.id\n @creator = true\n else\n @creator = false\n end\n end",
"def current_user_is_creator?(dictionary)\n if dictionary.creator == current_user.email\n return true\n else \n return false\n end\n end",
"def owner?\n @credentials.username == owner\n end",
"def generated_by?(user)\n actor == user\n end",
"def owned_by? a_user\n a_user == program.user\n end",
"def owned_by?(u)\n self.user == u\n end",
"def owned_by?(user)\n if user.nil?\n false\n else\n organization == user.organization\n end\n end",
"def isCommentCreator(current_user, comment_id)\n Comment.where(:user_id => current_user, :id => comment_id).exists? \n end",
"def created_by_valid_user?\n User.find_by(id: self.created_by)\n end",
"def is_owner?\n return false unless current_user\n return true if current_user.is_admin | (current_user == @profile)\n end",
"def is_owner?(item)\n current_user_id == item.user_id\n end",
"def user_is_owner?\n current_cookbook.is_owner?(current_user)\n end",
"def owned_by? a_user\n a_user == self\n end",
"def is_owner?(username)\n User.get_user(username).eql?(self.owner)\n end",
"def is_owner?(obj)\n obj.user_id == current_user.id\n end"
] | {
"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 = schema\n ActiveRecord::Migrator.migrate('db/migrate', to_version)\n conn.schema_search_path = current_search_path\n end",
"def run_migration; end",
"def migration\n @migration\n end",
"def full_shared_schema_migration_path\n \"#{Rails.root}/#{shared_migrations_directory}\"\n end",
"def migrations_paths=(_arg0); end",
"def schema?(model_class)\n model_class.name == 'ActiveRecord::SchemaMigration'\n end",
"def migrate_plugin(migration_path)\n # Execute Migrations on engine load.\n ActiveRecord::Migrator.migrations_paths += [migration_path]\n begin\n ActiveRecord::Tasks::DatabaseTasks.migrate\n rescue ActiveRecord::NoDatabaseError\n end\n end",
"def add_migration\n builder.rc(\"dotnet ef migrations add #{ef_migrations.migration_name} --context MsDbContext\") if project_flag.use_sql_server\n builder.rc(\"dotnet ef migrations add #{ef_migrations.migration_name} --context PgDbContext\") if project_flag.use_pgsql\n end",
"def migration_class_name; end",
"def schema_version\n migration_context.current_version\n end",
"def gather_engine_migration_paths\n paths = ActiveRecord::Migrator.migrations_paths\n\n ::Rails::Engine.subclasses.map(&:instance).each.each do |engine|\n migrations_paths = engine.paths['db/migrate'].existent_directories\n\n migrations_paths.each do |migrations_path|\n # Since ActiveRecord::Migrator.migrations_paths can persist between\n # instances of Msf::DBManager, such as in specs,\n # migrations_path may already be part of\n # migrations_paths, in which case it should not be added or multiple\n # migrations with the same version number errors will occur.\n unless paths.include? migrations_path\n paths << migrations_path\n end\n end\n end\n paths\n end",
"def migrate\n raise NotImplementedError\n end",
"def in_migration_spec?(node)\n path = node.location.expression.source_buffer.name\n\n in_spec?(node) &&\n path.start_with?(*migration_directories)\n end",
"def alter_table_generator_class\n Schema::AlterTableGenerator\n end",
"def activate(schema,verify_migration = false)\n base_path = self.initial_search_path\n self.create(schema) if verify_migration\n conn = ActiveRecord::Base.connection\n return false unless conn.schema_exists?(schema)\n conn.schema_search_path = [schema, base_path].compact.join(',')\n end",
"def pre_migrate_database\n old_schema_version = get_schema_version\n new_schema_version = File.read(File.join(source_directory,'db','schema_version')).to_i\n \n return unless old_schema_version > 0\n \n # Are we downgrading?\n if old_schema_version > new_schema_version\n message \"Downgrading schema from #{old_schema_version} to #{new_schema_version}\"\n \n in_directory install_directory do\n unless system(\"rake -s migrate VERSION=#{new_schema_version}\")\n raise InstallFailed, \"Downgrade migrating from #{old_schema_version} to #{new_schema_version} failed.\"\n end\n end\n end\n end",
"def migration_class_name\n migration_name.camelize\n end",
"def migration(&block)\n Class.new(Migration, &block)\n end"
] | {
"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 lamps') && return if values.size > @ports.size
values.map! { |x| x.to_i > 255 ? 255 : x.to_i }
client.pwm_write_registers(start_index: @ports.sort.first, values: values)
end
end | [
"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 = options[:values]\n\n start_at_register = 0 unless (0..NUMBER_OF_PWM_PORTS).include?(start_at_register) # set to 0 if out of bounds\n start_at_register = start_at_register.to_s(16).rjust(2, '0') # convert startindex to hex string\n register_count = values.size.to_s(16).rjust(2, '0')\n\n output_array_string = ''\n\n # convert values to hex string\n values.each do |value|\n value = 0 unless (0..255).include?(value.to_i) # set to 0 if out of bounds\n output_array_string << value.to_i.round.to_s(16).rjust(2, '0')\n end\n\n command = \"PW#{start_at_register}#{register_count}#{output_array_string}\".upcase\n handle { connection.cmd(command) }\n end",
"def pwm_write(number, value)\n pwm_write_registers(start_index: number, values: [value])\n end",
"def pwm_ports\n\t\t\t\t[1, 2, 3, 4] # Board doesn't support enabling/disabling PWM\n\t\t\tend",
"def pwm_ports\n\t\t\t\tcurPWM = read(0x5f, 1)[0]\n\n\t\t\t\tret = []\n\t\t\t\t(1..@num_FETs).each do |port|\n\t\t\t\t\tret << port if curPWM & 2**(port-1) > 0\n\t\t\t\tend\n\t\t\t\tret\n\t\t\tend",
"def pwm_write(value)\n @value = value\n\n # Calculates the pi-blaster required value between 0 and 1 inclusive\n @pb_val = pi_blaster_val(value)\n\n @pwm_file.write(\"#{ pin_num }=#{ @pb_val }\\n\")\n @pwm_file.flush\n end",
"def writer_output(*keys)\n # Registers each signal as writer port\n keys.each do |key|\n # Ensure the key is a symbol.\n key = key.to_sym\n # Register it with the corresponding signal.\n name = HDLRuby.uniq_name # The name of the signal is uniq.\n @writer_outputs[name] = send(key)\n end\n end",
"def write_to_lamp(number, value)\n value = value.to_i >= 1 ? 255 : 0\n @pwm_driver.write_to_port(number, value)\n 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 ports *ports\n @ports = *ports unless ports.length == 0\n @ports\n end",
"def write(*commands)\n serial_port.write(commands.map(&:chr).join)\n end",
"def pwm_global_dim(value)\n pwm_write_registers(start_index: NUMBER_OF_PWM_PORTS, values: [value])\n end",
"def pwm_enable(*port)\n\t\t\t\tcase port.count\n\t\t\t\twhen 0\n\t\t\t\t\traise ArgumentError.new \"wrong number of arguments\"\n\t\t\t\twhen 1\n\t\t\t\t\tport = port.first\n\t\t\t\tend\n\n\t\t\t\tif port.is_a? Array then\n\t\t\t\t\tport.each do |port|\n\t\t\t\t\t\tpwm_enable port\n\t\t\t\t\tend\n\t\t\t\t\treturn true\n\t\t\t\tend\n\t\t\t\traise ArgumentError.new \"Port must be an integer between 1 and #{@num_FETs}\" unless port.is_a? Fixnum and (1..@num_FETs).include? port\n\n\t\t\t\tport = 2**(port-1)\n\n\t\t\t\tcurPWM = read(0x5f, 1)[0]\n\t\t\t\ttgtPWM = curPWM | port\n\t\t\t\twrite(0x5f, tgtPWM)\n\n\t\t\t\ttrue\n\t\t\tend",
"def writer_inout(*keys)\n # Registers each signal as writer port\n keys.each do |key|\n # Ensure the key is a symbol.\n key = key.to_sym\n # Register it with the corresponding signal.\n name = HDLRuby.uniq_name # The name of the signal is uniq.\n @writer_inouts[name] = send(key)\n end\n end",
"def write_vector(task, portname,data)\n write(task, portname, {'data' => data})\n end",
"def write_parameter_to_device(id, value)\n @ramps_arduino.execute_command(\"F22 P#{id} V#{value}\", false, false)\n end",
"def runner_output(*keys)\n # Registers each signal as run port\n keys.each do |key|\n # Ensure the key is a symbol.\n key = key.to_sym\n # Register it with the corresponding signal.\n name = HDLRuby.uniq_name # The name of the signal is uniq.\n @runner_outputs[name] = send(key)\n end\n end",
"def ports\n # prevent original array from being changed\n @ports.dup\n end"
] | {
"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 # Calculates the pi-blaster required value between 0 and 1 inclusive\n @pb_val = pi_blaster_val(value)\n\n @pwm_file.write(\"#{ pin_num }=#{ @pb_val }\\n\")\n @pwm_file.flush\n end",
"def write_to_lamp(number, value)\n value = value.to_i >= 1 ? 255 : 0\n @pwm_driver.write_to_port(number, value)\n end",
"def pwm(v)\n regdata = @@i2c.read(0x08, 1)\n @@i2c.write([0x08, regdata[0] | (1 << @id)])\n @@i2c.write([@ion, v])\n @@i2c.write([0x08, regdata[0]])\n end",
"def set_value(v)\n raise NotOutMode, \"error : mode isn't OUT\" unless @mode == OUT\n raise BadValue, \"error : bad pin value\" unless v.between? 0,1\n File.open(\"#{LIB_PATH}/gpio#{@pin}/value\", 'w') do |file|\n file.write(v)\n end\n end",
"def analog_write(pin, value)\n pin_mode(pin, PWM)\n write(ANALOG_MESSAGE | (pin & 0x0F))\n write(value & 0x7F)\n write(value >> 7)\n end",
"def analog_write(value)\n @board.analog_write(@number, value)\n end",
"def write_parameter_to_device(id, value)\n @ramps_arduino.execute_command(\"F22 P#{id} V#{value}\", false, false)\n end",
"def write(values)\n if values.is_a? Hash # TODO: hacky - refactor\n fail \"wrong hash format, expected the keys 'port' and 'value'\" unless values.key?(:port) && values.key?(:value)\n write_to_port(values[:port], values[:value])\n elsif values.is_a? Array\n log.error('more values than configured lamps') && return if values.size > @ports.size\n values.map! { |x| x.to_i > 255 ? 255 : x.to_i }\n client.pwm_write_registers(start_index: @ports.sort.first, values: values)\n end\n end",
"def pwm_enable(*port)\n\t\t\t\tcase port.count\n\t\t\t\twhen 0\n\t\t\t\t\traise ArgumentError.new \"wrong number of arguments\"\n\t\t\t\twhen 1\n\t\t\t\t\tport = port.first\n\t\t\t\tend\n\n\t\t\t\tif port.is_a? Array then\n\t\t\t\t\tport.each do |port|\n\t\t\t\t\t\tpwm_enable port\n\t\t\t\t\tend\n\t\t\t\t\treturn true\n\t\t\t\tend\n\t\t\t\traise ArgumentError.new \"Port must be an integer between 1 and #{@num_FETs}\" unless port.is_a? Fixnum and (1..@num_FETs).include? port\n\n\t\t\t\tport = 2**(port-1)\n\n\t\t\t\tcurPWM = read(0x5f, 1)[0]\n\t\t\t\ttgtPWM = curPWM | port\n\t\t\t\twrite(0x5f, tgtPWM)\n\n\t\t\t\ttrue\n\t\t\tend",
"def write pin, value\n if value == 0\n set_int_at(GPCLR0 + PI_BANK(pin), PI_BIT(pin))\n else\n set_int_at(GPSET0 + PI_BANK(pin), PI_BIT(pin))\n end\n end",
"def pwm_write_registers(options)\n start_at_register = options[:start_index]\n values = options[:values]\n\n start_at_register = 0 unless (0..NUMBER_OF_PWM_PORTS).include?(start_at_register) # set to 0 if out of bounds\n start_at_register = start_at_register.to_s(16).rjust(2, '0') # convert startindex to hex string\n register_count = values.size.to_s(16).rjust(2, '0')\n\n output_array_string = ''\n\n # convert values to hex string\n values.each do |value|\n value = 0 unless (0..255).include?(value.to_i) # set to 0 if out of bounds\n output_array_string << value.to_i.round.to_s(16).rjust(2, '0')\n end\n\n command = \"PW#{start_at_register}#{register_count}#{output_array_string}\".upcase\n handle { connection.cmd(command) }\n end",
"def digital_write(value)\n @board.digital_write(@number, value)\n end",
"def motor_start(port, value)\n\t\t\t\traise ArgumentError.new(\"Port must be :A or :B\") unless port == :A or port == :B\n\t\t\t\traise ArgumentError.new(\"Value must be an integer beween -255 and 255\") unless value.is_a? Fixnum and (-255..255).include? value\n\n\t\t\t\tbasereg = 0x20\n\t\t\t\tbasereg = 0x30 if port == :B\n\n\t\t\t\tif value < 0 then\n\t\t\t\t\twrite(basereg+1, -value)\n\t\t\t\telsif value > 0 then\n\t\t\t\t\twrite(basereg+1, value)\n\t\t\t\telse\n\t\t\t\t\twrite(basereg+2, 1)\n\t\t\t\tend\n\t\t\tend",
"def digital_write(value)\n set_mode('w') unless @mode == 'w'\n\n if value.is_a? Symbol\n value = (value == :high) ? 1 : 0\n end\n\n value = value.to_i\n\n raise StandardError unless ([HIGH, LOW].include? value)\n\n @status = (value == 1) ? 'high' : 'low'\n\n @pin_file.write(value)\n @pin_file.flush\n end",
"def value=(v)\n if [:count_in_int, :count_in_dir, :count_in_home, :count_out_in, :count_out_dir, :count_out_home].include? self.mode\n @dyio.command_to.set_channel_value @channel_number, v, :time => @duration, :time_size => 4, :val_size => 4\n elsif self.mode == :servo_out\n @dyio.command_to.set_channel_value @channel_number, v, :time => @duration, :time_size => 2, :val_size => 1\n else\n @dyio.command_to.set_channel_value @channel_number, v, :val_size => 1\n end\n end",
"def analog_write(pin, value)\n @pins[pin].value = value\n write(ANALOG_MESSAGE | pin, value & 0x7F, (value >> 7) & 0x7F)\n end"
] | {
"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 => @the_day }\n end\n end",
"def new\n @stuff = Stuff.new\n @days_to_njcee = get_days_to_njcee()\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @stuff }\n end\n end",
"def new\n @when_day = WhenDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @when_day }\n end\n end",
"def new\n @eventday = Eventday.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @eventday }\n end\n end",
"def new\n @day_rec = DayRec.new\n @day_recs = DayRec.find(:all)\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @day_rec }\n end\n end",
"def new\n @day = @user.days.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @day }\n end\n end",
"def new\n @user_day = UserDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @user_day }\n end\n end",
"def new\n @range_day = RangeDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @range_day }\n end\n end",
"def new\n @day_record = DayRecord.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @day_record }\n end\n end",
"def new\n @work_day = WorkDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @work_day }\n end\n end",
"def new\n @bday = Bday.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @bday }\n end\n end",
"def new\n @commission_day = CommissionDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @commission_day }\n end\n end",
"def new\n @hollyday = Hollyday.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @hollyday }\n end\n end",
"def new\n @day = Day.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @day }\n end\n end",
"def new\n @working_day = WorkingDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @working_day }\n end\n end",
"def new\n @dayusage = Dayusage.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @dayusage }\n end\n end",
"def new\n @availability_day = AvailabilityDay.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @availability_day }\n end\n end",
"def new\n @payday = Payday.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @payday }\n end\n end"
] | {
"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]\n end",
"def selectDevice\n result = RestClient.get(action('selectDevice'), @headers)\n \n Nokogiri::XML(result)\n end",
"def root_device_type\n @instance.root_device_type\n end",
"def root_device_type\n data.root_device_type\n end",
"def query_device_management\n @devices = query(\"select * from device_management \")\n end",
"def debug_if_root_device(bdms)\n return if bdms.nil? || bdms.empty?\n image_id = config[:image_id]\n image = ec2.resource.image(image_id)\n begin\n root_device_name = image.root_device_name\n rescue ::Aws::EC2::Errors::InvalidAMIIDNotFound\n # Not raising here because AWS will give a more meaningful message\n # when we try to create the instance\n return\n end\n bdms.find { |bdm|\n if bdm[:device_name] == root_device_name\n logger.info(\"Overriding root device [#{root_device_name}] from image [#{image_id}]\")\n end\n }\n end",
"def enable_root()\n response = @connection.dbreq(\"POST\", @dbmgmthost, \"#{@dbmgmtpath}/instances/#{CloudDB.escape(@id.to_s)}/root\", @dbmgmtport, @dbmgmtscheme, {})\n CloudDB::Exception.raise_exception(response) unless response.code.to_s.match(/^20.$/)\n @root_enabled = true\n body = JSON.parse(response.body)['user']\n return body\n end",
"def default_root_device_type\n data[:default_root_device_type]\n end",
"def set_RootDeviceName(value)\n set_input(\"RootDeviceName\", value)\n end",
"def get_device(name); end",
"def get_current_devices(method = :os)\n if method == :api\n attached_devices\n else\n # Read devices that are currently in use from the last column in /proc/partitions\n partitions = IO.readlines('/proc/partitions').drop(2).map { |line| line.chomp.split.last }\n\n # Eliminate all LVM partitions\n partitions = partitions.reject { |partition| partition =~ /^dm-\\d/ }\n\n # Get all the devices in the form of sda, xvda, hda, etc.\n devices = partitions.select { |partition| partition =~ /[a-z]$/ }.sort.map { |device| \"/dev/#{device}\" }\n\n # If no devices found in those forms, check for devices in the form of sda1, xvda1, hda1, etc.\n if devices.empty?\n devices = partitions.select { |partition| partition =~ /[0-9]$/ }.sort.map { |device| \"/dev/#{device}\" }\n end\n devices\n end\n end",
"def root\n get URI(api_endpoint).path.sub(/\\/$/,'')\n end",
"def server_devices_list\n if !ccl_active? or (session[:usertype] != \"admin\" and ccl_active?)\n dont_be_so_smart\n redirect_to :controller => \"callc\", :action => \"main\" and return false\n end\n @page_title = _('Server_devices')\n @page_icon = 'server.png'\n @help_link = \"http://wiki.kolmisoft.com/index.php/Multi_Server_support\"\n # ip_auth + server_devices.server_id is null + server_devices.server_id is not that server + not server device(which were created with server creation)\n @devices = Device.select(\"devices.*,server_devices.server_id AS serv_id\").joins(\"LEFT JOIN server_devices ON (server_devices.device_id = devices.id AND server_devices.server_id = #{params[:id].to_i}) LEFT JOIN users ON (users.id = devices.user_id)\").where(\"(host != 'dynamic' OR device_type != 'SIP') AND users.owner_id = #{current_user.id} AND server_devices.server_id is null AND user_id != -1 AND name not like 'mor_server_%'\").order(\"extension ASC\").all\n end",
"def get_synthetics_devices\n request(Net::HTTP::Get, \"/api/#{API_VERSION}/synthetics/browser/devices\", nil, nil, false)\n end",
"def default_device\n @context.devices.first\n end"
] | {
"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), or facebook_*_link(:scope => :some_scope)")
end
scope = args.detect { |arg| arg.is_a?(Symbol) } || options[:scope] || ::Devise.default_scope
mapping = ::Devise.mappings[scope]
if mapping.for.include?(:facebook)
scope
else
error_message =
"%s" <<
" Did you forget to devise facebook_connect in your model? Like this: devise :facebook_connectable." <<
" You can also specify scope explicitly, e.g.: facebook_*link :for => :customer."
error_message %=
if scope.present?
"#{scope.inspect} is not a valid facebook devise scope. " <<
"Loaded modules for this scope: #{mapping.for.inspect}."
else
"Could not auto-detect any facebook_connectable devise scope."
end
raise error_message
end
end | [
"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_*_link(:some_scope), or facebook_*_link(:scope => :some_scope)\")\n end\n\n scope = args.detect { |arg| arg.is_a?(Symbol) } || options[:scope] || ::Devise.default_scope\n mapping = ::Devise.mappings[scope]\n\n if mapping.for.include?(:facebook_connectable)\n scope\n else\n error_message =\n \"%s\" <<\n \" Did you forget to devise facebook_connect in your model? Like this: devise :facebook_connectable.\" <<\n \" You can also specify scope explicitly, e.g.: facebook_*link :for => :customer.\"\n error_message %=\n if scope.present?\n \"#{scope.inspect} is not a valid facebook_connectable devise scope. \" <<\n \"Loaded modules for this scope: #{mapping.for.inspect}.\"\n else\n \"Could not auto-detect any facebook_connectable devise scope.\"\n end\n raise error_message\n end\n end",
"def detect_devise_scope(*args)\n unless scope = args.detect { |arg| arg.is_a?(Symbol) && !DEVISE_ACTIONS.keys.include?(arg) } || Warden::Manager.default_scope\n raise \"No scope could be detected. Ensure that you got a authenticatable Devise model in you app.\"\n end\n scope\n end",
"def default_scope\n scope = scope_map.find do |k,v|\n v[:default]\n end\n\n scope ? scope[0] : nil\n end",
"def default_scope\n @default_scope ||= 'entitlements'\n end",
"def default_scope(context)\n if context[:last]\n default(:scope)\n else\n self.class.defaults[:scope]\n end\n end",
"def devise_scope(scope); end",
"def selected_scope\n (params[:scope] || :default).to_sym\n end",
"def default_scope=(scope)\n warn \"[DEPRECATION] Warden::Manager.default_scope= is deprecated. Please set it in the Warden::Manager instance.\"\n end",
"def default_scope\n klass.scoped.with_default_scope\n end",
"def default_scoped(scope = relation, all_queries: nil)\n build_default_scope(scope, all_queries: all_queries) || scope\n end",
"def apply_default_scopes\n self.class.default_scopes.each { |scope| apply_default_scope(scope) }\n end",
"def default_scope(scope)\n self.default_scoping = case scope\n when Scope, nil\n scope\n when Hash\n Scope.new(self).apply_finder_options(scope)\n else\n raise \"Don't know how to set scope with #{scope.class}.\"\n end\n end",
"def default_search_scope\n @default_search_scope ||= default_search_scopes[controller_name.to_sym][:actions][action_name.to_sym] ||\n default_search_scopes[controller_name.to_sym][:default]\n end",
"def default_scope(params = nil)\n params ||= @request_params\n\n if model.respond_to?(:sunrise_search) && params[:search].present?\n scope = model.sunrise_search(params[:search])\n end\n scope ||= model.all\n\n scope = scope.merge(association_scope) unless parent_record.nil?\n scope = scope.merge(sort_scope(params[:sort])) if params[:sort].present?\n scope = scope.merge(list.scope) unless list.scope.nil?\n\n scope\n end",
"def default_scopes\n @default_scopes ||= (parent_scopes + [@default_scope]).compact\n end",
"def default_scope; end",
"def current_scope\n params[:scope].try(:to_sym) || railgun_resource.default_scope.try(:key)\n end",
"def scope\n if has_profile_tag?\n by_profile_tag\n elsif has_only_profile?\n by_profile\n elsif has_only_tag?\n by_tag\n else\n use_default\n end\n end",
"def default_scopes\n Doorkeeper.config.default_scopes.to_a\n end"
] | {
"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.find_by_path(request.path).name rescue scope
url = sign_out_form ? destroy_session_path(scope) : session_path(scope)
form_for(scope, :url => url, :html => options) { |f| }
end | [
"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 :length => :long,\n :background => :white,\n :button => false\n )\n\n content_tag(:div, :class => 'facebook_connect_link sign_out') do\n with_output_buffer { facebook_connect_form(scope, :sign_out => true, :method => :get) } +\n if options[:button]\n fb_login_button('devise.facebook_connectable.sign_out();', options.merge(:autologoutlink => true))\n else\n fb_logout_link(options[:label], destroy_session_path(:user))\n end\n end\n end",
"def facebook_sign_in_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_in, :scope => [:devise, :sessions, :facebook_actions]),\n :size => :large,\n :length => :long,\n :background => :white,\n :button => true,\n :autologoutlink => false\n )\n options.merge!(:sign_out => true) if options[:autologoutlink] && signed_in?(scope)\n\n content_tag(:div, :class => 'facebook_connect_link sign_in') do\n with_output_buffer { facebook_connect_form(scope, options.slice(:method)) } +\n if options[:button]\n fb_login_button('devise.facebook_connectable.sign_in();', options)\n else\n fb_logout_link(options[:label], 'devise.facebook_connectable.sign_in_with_callback();')\n end\n end\n end",
"def sign_forms\r\n if !in_facebook_canvas?\r\n hidden_fields = \"<div class='signiture'>\"\r\n signiture_hash.each do |k,v|\r\n hidden_fields << \"<input type='hidden' name='#{k}' value='#{v}'/>\"\r\n end \r\n hidden_fields << \"</div>\"\r\n parsed_doc.search(\"form\").prepend(hidden_fields) \r\n response.body = parsed_doc.to_html\r\n end\r\n end",
"def draw_login_form\n term.print_block(17, 32, <<END.freeze)\n type 'new' to join\n there is no guest ID\n┌─────────────────────────────────┐\n│ ID : │\n│ PW : │\n│ │\n└─────────────────────────────────┘\nEND\n end",
"def html_logout_form(cgi_dir)\n <<~HTML\n <form NAME=\"login\" ACTION=\"#{cgi_dir}/login.rbx\" METHOD=\"post\">\n <input TYPE=\"submit\" NAME=\"logout\" VALUE=\"logout\" >\n </form>\n HTML\n end",
"def check_facebook_logged_out\n logger.debug \"*** Check facebook logged out\"\n \n if params[:fb_sig_logged_out_facebook] == \"1\"\n render :template => \"errors/logged_out\", :layout => 'errors'\n end\n end",
"def authButtonAction(sender)\n if FBSession.activeSession.open?\n appDelegate.closeSession\n else\n appDelegate.openSessionWithAllowLoginUI(true)\n end\n end",
"def logout_url\n \"https://www.facebook.com/logout.php?next=#{self.class.logout_url}&access_token=#@access_token\"\n end",
"def default_adauth_form\n adauth_form do\n \"<p>#{label_tag :username}: \n #{text_field_tag :username}</p>\n <p>#{label_tag :password}: \n #{password_field_tag :password}</p>\n <p>#{submit_tag \"Login!\"}</p>\"\n end\n end",
"def login_form\n end",
"def facebook_login\n parameters = getParams params\n @fb = Facebook.new parameters\n\n session[:facebook_id] = @fb::facebook_user[\"id\"] if !@fb::facebook_user.nil? \n \n if @fb.loggedout?\n # Redirect to facebook login \n render :facebooklogin, :layout => false\n elsif !User.registered? @fb\n User.register @fb\n end \n end",
"def facebook_login\n \n # if user can not be mapped to an existing user via email hash or facebook_id,\n # render the facebook login page which asks the user to create a local account\n # by entering a login and email address, or login to connect the 2 accounts.\n end",
"def signin_get\n @mode = :signin\n \n if params[:req].present? && !ApplicationController::RequiredIdentity.payload(session)\n @mode = :signup\n kind = params[:req].to_sym\n back = request.env[\"HTTP_REFERER\"]\n \n ApplicationController::RequiredIdentity.set_payload(session, \n :on_success => back,\n :on_cancel => back,\n :kind => kind)\n end\n \n render! :action => \"new\", :layout => \"dialog\"\n end",
"def facebook_sigin\n driver.get(@@base_url+ \"/panel/signin/\")\n driver.find_element(:link, \"Sign Up\").click\n driver.find_element(:css, \"img[alt=\\\"Login with Facebook\\\"]\").click\n window_handles= driver.window_handles\n driver.switch_to.window(window_handles[1])\n driver.find_element(:id, \"email\").clear\n driver.find_element(:id, \"email\").send_keys FACEBOOK_USERNAME\n driver.find_element(:id, \"pass\").clear\n driver.find_element(:id, \"pass\").send_keys FACEBOOK_PASSWORD\n driver.find_element(:name, 'login').click\n window_handles= driver.window_handles\n driver.switch_to.window(window_handles)\n sleep 2\n driver.title\n end",
"def login_popup\n session[:redirect_to_after_auth] = request.env['HTTP_REFERER']\n @login_form = LoginForm.new\n render :layout => \"blank\"\n end",
"def facebook_logout_and_redirect_url\n redirect_path = if current_user\n profile_settings_user_url(current_user)\n else\n new_user_registration_url\n end\n access_token = env[\"omniauth.auth\"].credentials.token\n \"#{ FACEBOOK_CONFIG[:logout_url] }?next=#{ redirect_path }&access_token=#{ access_token }\"\n end",
"def form_url_helpers(form)\n form.input(:redirect_url, as: :hidden) +\n form.input(:cancel_url, as: :hidden) +\n form.input(:render_view, as: :hidden)\n end",
"def form_logout\n post '/goldberg/auth/logout'\n end",
"def show_logout\n @show_logout = true\n end"
] | {
"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.gsub('[\"', '\"').gsub('\"]', '\"')) #in orf method, an array is produced while in the expected file read, an array isn't produced, thus it s necessary to remove \"[ ]\" from either end.\n end",
"def test_RG_line\n data = \"\nRN [1]\nRG The C. elegans sequencing consortium;\nRG The Brazilian network for HIV isolation and characterization;\"\n sp = SPTR.new(data)\n assert_equal(['The C. elegans sequencing consortium', \n 'The Brazilian network for HIV isolation and characterization'],\n sp.ref.first['RG'])\n end",
"def extrst(data)\n io = StringIO.new(data)\n\n _, cb = io.read(4).unpack('vv')\n # reserved (2 bytes): MUST be 1, and MUST be ignored.\n result = { cb: cb } # cb (2 bytes): An unsigned integer that specifies the size, in bytes, of the phonetic string data.\n\n result[:phs] = phs(io.read(4)) # phs (4 bytes): A Phs that specifies the formatting information for the phonetic string.\n result[:rphssub] = rphssub(io) # rphssub (variable): An RPHSSub that specifies the phonetic string.\n\n result[:rphssub][:crun].times do # See 2.5.219 RPHSSub\n result[:rgphruns] ||= []\n result[:rgphruns] << rgphruns(io)\n end\n\n result\n end",
"def readPhobius\n \n query = readQuery\n \n if( !File.exists?( self.actions[0].flash['phobiusfile'] ) ) then return {} end\n ret={'tmconf'=>[], 'tmpred'=>\"\" , 'sppred' =>\"\"}\n ar = IO.readlines( self.actions[0].flash['phobiusfile'])\n start_array = Array.new\n end_array = Array.new\n \n # Outside + Domains\n outside_start_array = Array.new\n outside_end_array = Array.new\n \n # Signal Peptide\n sp_start_array = Array.new\n sp_end_array = Array.new\n \n result=\"\"\n \n \n ar.each do |line|\n \n # Check for Signal Peptide\n line =~ /SIGNAL/\n if $& then\n line =~ /(\\d+)\\s+(\\d+)/\n sp_start_array.push($1)\n sp_end_array.push($2)\n end\n \n # Check for Outside Domains \n line =~ /NON CYTOPLASMIC/\n if $& then\n line =~ /(\\d+)\\s+(\\d+)/\n outside_start_array.push($1)\n outside_end_array.push($2)\n end\n \n \n # Check for Transmembrane Fragment\n line=~ /TRANSMEM/\n if $& then\n line =~ /(\\d+)\\s+(\\d+)/\n start_array.push($1)\n end_array.push($2)\n end\n \n end\n\n result=\"\"\n for i in 0..@query_sequence_length\n result = result+ \"--\" \n end\n\n # Set Transmembrane Regions\n start_array.length.times { |i|\n result[start_array[i].to_i-1..end_array[i].to_i] ='X'*( end_array[i].to_i+1 - start_array[i].to_i )\n }\n # Set Outside Regions\n outside_start_array.length.times { |i|\n result[outside_start_array[i].to_i-1..outside_end_array[i].to_i] ='+'*( outside_end_array[i].to_i+1 - outside_start_array[i].to_i )\n }\n\n # Set Signal Peptide Regions, we need to check wether the next Element is in / outside find the next element to the Sp \n # Test for outside Regions, Sp can only exist once\n start_after_sp = sp_end_array[i].to_i+1\n outside_start_array.length.times { |i|\n if outside_start_array[i].to_i == start_after_sp\n start_after_sp = '+'\n else\n start_after_sp = '-'\n end\n }\n sp_start_array.length.times { |i|\n result[sp_start_array[i].to_i-1..sp_end_array[i].to_i] =start_after_sp*( sp_end_array[i].to_i+1 - sp_start_array[i].to_i )\n }\n\n sp_result = \"\"\n # Signal Peptide Identification\n sp_start_array.length.times { |i|\n sp_result[sp_start_array[i].to_i-1..sp_end_array[i].to_i] =start_after_sp*( sp_end_array[i].to_i+1 - sp_start_array[i].to_i )\n }\n ret['sppred'] += sp_result\n\n\n# outside_start_array.length.times { |i|\n# (outside_start_array[i].to_i-1-result.length).times { result +=\" \" }\n# (outside_end_array[i].to_i-result.length).times { result += \"+\" }\n# }\n\n#\tstart_array.length.times { |i|\n#\t\t(start_array[i].to_i-1-result.length).times { result +=\" \" }\n#\t\t(end_array[i].to_i-result.length).times { result += \"X\" }\n#\t}\n\t(readQuery['sequence'].length-result.length+1).times{ result += \" \" }\n\tret['tmpred'] += result\n\n\tret\n end",
"def extract_data line\n line.split(/\\s*=\\s*/, 2)\n end",
"def interpret_data()\n\t\t\n\t\tvar = @placement.split(\" \"); #making it so it creates a new element every space\n\n\t\tfor y in 0..var.length-1 #looping through the column\n\t\t\tline = var[y]\n\t\t\t\n\t\t\t@xoffset = 0;\n\n\t\t\tfor x in 0..line.length-1 #looping through the row\n\t\t\n\t\t\t\n\t\t\t\tif(line[x] == \"Y\")\n\t\t\t\t\t@team_red = true;\n\t\t\t\t\t@xoffset = -1;\n\t\t\t\t\tid = line[6 + y * 7]\n\t\t\t\t\tputs id\n\t\t\t\t\t#create_piece(line.length,y, id);\n\t\t\t\t\tnext;\n\t\t\t\tend\n\t\t\t\t\n\n\t\t\t\t#gets the id at each coordinate\n\t\t\t\tid = line[x+=@xoffset].to_i\n\t\t\t\t\t\n\t\t\t\t#create a new piece based of the id at that coordinate\n\t\t\t\tcreate_piece(x+=@xoffset, y, id);\n\t\t\t\t\n\t\t\t\t\n\t\t\tend \n\t\t\t\n\t\tend\n\t\t\n\t\t\n\tend",
"def test_data_text\n\ttest_data.map { |l| l[0] }.join(\"\\n\")\nend",
"def test_it_can_split_two_words_braille_letters_into_2x3_grid\n # change message txt to have only lowercase Hello world.\n grid_builder = GridBuilder.new\n expected = \"..0.0.0.0.0. .00.0.0.00\\n..00.00.0..0 00.0000..0\\n.0....0.0.0. .00.0.0...\"\n actual= grid_builder.make_braille_grid_letter_by_letter\n assert_equal expected, actual\n end",
"def test_parse_headword\n entry = BigramEntry.new\n entry.parse_line(\"8\t工作\t18904\t6.89133239246\t213454\")\n assert_equal(\"\",entry.headword_trad)\n assert_equal(\"工作\",entry.headword_simp)\n end",
"def ussd_data\n data = params[:data]\n\n #on fait le decoupage de la chaine de caractere suivant le caractere de delimitation\n splited = data.split('@')\n render plain: \"Voici les données #{splited}\" if !splited.nil?\n end",
"def pcdata\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 9 )\n __PCDATA8__ = nil\n __PCDATA9__ = nil\n\n begin\n # at line 64:7: ( ^( DATA PCDATA ) | PCDATA )\n alt_9 = 2\n look_9_0 = @input.peek( 1 )\n\n if ( look_9_0 == DATA )\n alt_9 = 1\n elsif ( look_9_0 == PCDATA )\n alt_9 = 2\n else\n raise NoViableAlternative( \"\", 9, 0 )\n end\n case alt_9\n when 1\n # at line 64:9: ^( DATA PCDATA )\n match( DATA, TOKENS_FOLLOWING_DATA_IN_pcdata_255 )\n\n match( DOWN, nil )\n __PCDATA8__ = match( PCDATA, TOKENS_FOLLOWING_PCDATA_IN_pcdata_257 )\n\n match( UP, nil )\n # --> action\n (__PCDATA8__.text).each_line{|line| if ((line.strip).length>0) then print ((\"\\t\")*(__PCDATA8__.depth-1));puts line.strip; end;};\n # <-- action\n\n when 2\n # at line 65:9: PCDATA\n __PCDATA9__ = match( PCDATA, TOKENS_FOLLOWING_PCDATA_IN_pcdata_270 )\n # --> action\n (__PCDATA9__.text).each_line{|line| if ((line.strip).length>0) then print ((\"\\t\")*(__PCDATA9__.depth));puts line.strip; end;};\n # <-- action\n\n end\n rescue ANTLR3::Error::RecognitionError => re\n report_error(re)\n recover(re)\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 9 )\n\n end\n \n return \n end",
"def testParseLine\n ep = EiBiScheduleParser.new\n\n line = \"7490;2300-0455;;;WBCQ;E;NA;;;;\"\n bc = ep.parseEiBiTextLine(line)\n assert_equal 7490, bc[:frequency]\n assert_equal \"WBCQ\", bc[:broadcaster]\n assert_equal 23, bc[:startHour]\n assert_equal 0, bc[:startMinute]\n assert_equal 4, bc[:endHour]\n assert_equal 55, bc[:endMinute]\n assert_equal \"NA\", bc[:targetRegion]\n end",
"def question_split\n arr_of_strings = []\n single_question = []\n @data.each do |str|\n if str.length == 3 || str.length == 2\n if str[0].numeric? && str[-1] == '.'\n arr_of_strings << single_question\n single_question = []\n single_question << str\n else\n single_question << str\n end\n else\n single_question << str\n end\n end\n arr_of_strings << single_question\n @data = arr_of_strings\n end",
"def test_data\n\t# [] is mapped to an empty line, that is, a zero-length string and an empty\n\t# array.\n\ttest_lines=[\n\t\t# Simple cases\n\t\t['foo ();' , [] ], # No quoted text\n\t\t['a=\"moo\"' , [false] ], # Quoted text\n\t\t[],\n\t\t# With comments\n\t\t['foo (); // A \"commented\" string' , [] ], # Quoted text in comment\n\t\t['a=\"moo\"; // A comment' , [false] ], # Quoted text and comment\n\t\t['a=\"moo\"; // A \"commented\" string' , [false] ], # Quoted text and quoted text in comment\n\t\t['a=\"moo\", 2/3; // A \"commented\" string', [false] ], # Quoted text and quoted text in comment\n\t\t[],\n\t\t# With include\n\t\t['#include \"foo.h\"' , [true] ], # Regular include\n\t\t[' #include \"foo.h\"' , [true] ], # Indented include\n\t\t['foo (); // #include \"foo.h\"' , [] ], # No quote, include in comment\n\t\t['a=\"moo\"; // #include \"foo.h\"' , [false] ], # Quoted text, #include in comment\n\t\t[],\n\t\t# With tr\n\t\t['foo=tr (\"moo\");' , [true ] ],\n\t\t['foo=tr(\"moo\");' , [true ] ],\n\t\t['foo=notr(\"moo\");' , [true ] ],\n\t\t['foo=qnotr(\"moo\");' , [true ] ],\n\t\t['foo=fauxtr (\"moo\");' , [false] ],\n\t\t['foo=fauxtr(\"moo\");' , [false] ],\n\t\t['foo=t/*.*/r(\"moo\");' , [false] ], # Not tr\n\t\t['foo=faux/*.*/tr(\"moo\");' , [true ] ], # Not fauxtr\n\t\t[],\n\t\t# With string concatenation\n\t\t['foo=tr(\"moo\" \"bert\");' , [true, true] ],\n\t\t['foo=tr(\"moo\" /* ... */ \"bert\");', [true, true] ],\n\t\t['foo=tr(\"moo\" // ...' , [true] ],\n\t\t[' \"bert\");' , [true] ],\n\t\t[],\n\t\t# With two-argument form of tr\n\t\t['foo=tr (\"moo\", \"disambiguation\")' , [true, true] ],\n\t\t['foo=tr (\"moo\" \"bert\", \"disambiguation\")', [true, true, true] ],\n\t\t['foo=tr (\"moo\", \"dis\" \"ambiguation\")' , [true, true, true] ],\n\t\t[],\n\t\t# With escaped quotes\n\t\t['foo=tr (\"foo\\\\\"bar\")', [true ] ], # Single escaped quote\n\t\t['foo=tr (\"foo\\\\\"bar\\\\\"baz\")', [true ] ], # Multiple escaped quotes\n\t\t['foo=tr (\"foo\\\\\\\\\"bar\\\\\\\\\"baz\")', [true, false] ], # Now they are not escaped and actually end the string\n\t\t[],\n\t\t# With more complex tr\n\t\t['foo=qApp->translate(\"context\",\"moo\")' , [true, true] ], # No whitespace\n\t\t[' foo = qApp -> translate ( \" context \" , \" moo \" ) ', [true, true] ], # Lots of whitespace\n\t\t['foo=qApp->translate(\"context\",\"moo\",\"comment\")' , [true, true, true] ], # 3-argument form\n\t\t[],\n\t\t# extern \"C\"\n\t\t['extern\"C\"{}' , [true] ],\n\t\t['extern \"C\" { } ', [true] ],\n\t\t[],\n\t\t# Multi-line strings\n\t\t['foo=\"moo' , [false] ], # Multi-line string\n\t\t['bert\";' , [false] ], # Multi-line string, continued\n\t\t['foo=tr (\"moo', [true ] ], # Multi-line string\n\t\t['bert\");' , [true ] ], # Multi-line string, continued\n\t\t['foo=tr(' , [] ], # String on next line\n\t\t['\"bar\");' , [true ] ], # String on next line\n\t\t[],\n\t\t# Empty strings\n\t\t['a=\"\"' , [true] ], # Empty string\n\t\t['a=\" \"' , [true] ], # Empty string\n\t\t['a=\" \"' , [true] ], # Empty string\n\t\t[],\n\t\t# String concatenation\n\t\t['foo=tr (\"moo\" \"bert\")' , [true, true] ], # String concatenation\n\t\t['foo=tr (\"moo\" \"bert\"), \"bar\"' , [true, true, false] ], # Missing after string concatenation\n\t\t[],\n\t\t# With multiple strings\n\t\t['foo (tr (\"moo\"), tr (\"bert\"));' , [true , true ] ],\n\t\t['foo ((\"moo\"), tr (\"bert\"));' , [false, true ] ],\n\t\t['foo (tr (\"moo\"), (\"bert\"));' , [true , false] ],\n\t\t['foo (tr (42), (\"bert\"));' , [false] ], # This tr may not be associated with that string\n\t].map { |x| if x==[] then ['', []] else x; end }\nend",
"def build_stripwell_table pcrs\n stripwells = pcrs.collect { |pcr| pcr[:stripwells] }.flatten\n stripwell_tab = [[\"Stripwell\", \"Wells to pipette\"]] + stripwells.map { |sw| [\"#{sw.id} (#{sw.num_samples <= 6 ? 6 : 12} wells)\", { content: sw.non_empty_string, check: true }] }\n end",
"def split_header(data)\n len = self.ihl.to_i * 4\n #remember to substitute with changed data array(checksum and new ip)\n header = data[0,len]\n # break header in words\n ret_header = []\n i = header.length/2\n (0..i - 1).each do |x| \n ret_header << header[x * 2] + header[x * 2 + 1]\n end\n ret_header\n\n end",
"def table_data(data)\n left, middle, right = [@chars[:ldb], @chars[:idb], @chars[:rdb]]\n a = []\n data.each_with_index do |item, x|\n a << (' ' + item.to_s.send(@align[x] || :ljust, @widths[x]) + ' ')\n end\n s = @chars.wrap(left) + a.join(@chars.wrap(middle)) + @chars.wrap(right) + \"\\n\"\n s\n end",
"def phs(data)\n ifnt, attrs = data.unpack('vv')\n attrs = Unxls::BitOps.new(attrs)\n\n ph_type = attrs.value_at(0..1)\n ph_type_d = {\n 0x0 => :narrow_katakana,\n 0x1 => :wide_katakana,\n 0x2 => :hiragana,\n 0x3 => :any # Use any type of characters as phonetic string\n }[ph_type]\n\n alc_h = attrs.value_at(2..3)\n alc_h_d = {\n 0x0 => :general, # General alignment\n 0x1 => :left, # Left aligned\n 0x2 => :center, # Center aligned\n 0x3 => :distributed # Distributed alignment\n }[alc_h]\n\n {\n ifnt: ifnt, # ifnt (2 bytes): A FontIndex structure that specifies the font.\n phType: ph_type, # A - phType (2 bits): An unsigned integer that specifies the type of the phonetic information.\n phType_d: ph_type_d,\n alcH: alc_h, # B - alcH (2 bits): An unsigned integer that specifies the alignment of the phonetic string.\n alcH_d: alc_h_d\n # unused (12 bits): Undefined and MUST be ignored.\n }\n end"
] | {
"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 \"hikimashita\"\n @trans_array << \"をひきました\"\n @say_it_array << \"o hikimashita\"\n when \"shiteimasu\"\n @trans_array << \"をしています\"\n @say_it_array << \"o shite imasu\"\n when \"shimasu\"\n @trans_array << \"がします\"\n @say_it_array << \"ga shimasu\"\n when \"arimasu\"\n @trans_array << \"があります\"\n @say_it_array << \"ga arimasu\"\n when \"desu\"\n @trans_array << \"です\"\n @say_it_array << \"desu\"\n when \"dekiteimasu\"\n @trans_array << \"ができています\"\n @say_it_array << \"ga dekite imasu\"\n when \"demasu\"\n @trans_array << \"がでます\"\n @say_it_array << \"ga demasu\"\n end\n \n end\n end\nend",
"def <<(phrases)\n phrases.each do |phrase| \n @phrases << phrase.dup\n end \n end",
"def add_translations(translations)\n translations.each { |translation| @result.add_translation(@result.term, translation) }\n end",
"def add_phrase(method_name, args)\n key = method_name.to_s.sub(/^add_/, '')\n phrase = args.join(', ')\n @all_phrases[key] = phrase\n puts \"#{super_phrase} The phrase '#{key}' successfully added!\"\n end",
"def upsert(locale, key, value) # rubocop:disable Metrics/MethodLength\n I18n.with_locale(locale) do\n # when an array has to be inserted with a default value, it needs to\n # be done like:\n # I18n.t('foo', default: [['bar', 'baz']])\n # because without the double array, array items are treated as fallback keys\n # - then, the last array element is the final fallback; so in this case we\n # don't specify fallback keys and only specify the final fallback, which\n # is the array\n val = value.is_a?(Array) ? [value] : value\n I18n.t(key, default: val)\n\n # this indicates that this translation already exists\n existing_translation =\n Lit::Localization.joins(:locale, :localization_key)\n .find_by('localization_key = ? and locale = ?', key, locale)\n\n return unless existing_translation\n\n if @raw\n existing_translation.update(default_value: value)\n else\n existing_translation.update(translated_value: value, is_changed: true)\n lkey = existing_translation.localization_key\n lkey.update(is_deleted: false) if lkey.is_deleted\n end\n end\n end",
"def translation! phrase, language_id\n translations.where({:phrase => phrase, :language_id => language_id}).first or\n translations.create!({:phrase => phrase, :language_id => language_id})\n end",
"def add_translation(translation)\n check_duplication! translation\n\n translations[translation.name] = translation\n\n locales.add(translation.locale)\n key = init_key(translation)\n init_category(key)\n end",
"def add words, value = true\n words.each { |word| self[word] = value }\n self\n end",
"def add_translation(translation)\n translations.add(translation)\n end",
"def append(key, value); end",
"def add_words new_dict\n @dictionary = @dictionary.inject(new_dict) do |dict, (k,v)|\n dict.merge({ k.upcase => v }) \n end\n end",
"def merge_translations locale, translations\n locale = locale.to_s\n if translations.blank?\n @dictionary[locale] ||= {}\n return\n end\n @dictionary[locale] = (@dictionary[locale] || {}).merge(translations)\n end",
"def merge_translations locale, translations\n locale = locale.to_s\n if translations.blank?\n @dictionary[locale] ||= {}\n return\n end\n @dictionary[locale] = (@dictionary[locale] || {}).merge(translations)\n end",
"def add_result(key, text)\n if @result[key]\n if @result[key].is_a? Array\n @result[key].push(text)\n else\n @result[key] = [@result[key], text]\n end\n else\n @result[key] = text\n end\n end",
"def add entry\n existing_entry = @entries[entry.msgid]\n if existing_entry\n entry = existing_entry.merge(entry)\n end\n @entries[entry.msgid] = entry\n end",
"def create\n # Try not to duplicate anything here. If the translation already exists,\n # ignore the request. If the translated phrase exists but isn't associated\n # with the native phrase, create an association.\n @phrase = Phrase.find(params[:phrase_id])\n puts params[:translation].inspect\n @translation = @phrase.translation!(\n params[:translation]['phrase'],\n params[:translation]['language_id']\n )\n @translation.categories = params[:tags]\n\n respond_to do |format|\n if @translation.save\n format.html {redirect_to @phrase, notice: 'Translation added successfully.' }\n format.json { render json: @translation, status: :created, location: @translation }\n format.js { render :partial => 'phrases/translation_listing', :content_type => 'text/html', :locals => { :translation => @translation } }\n else\n format.html { render json: @translation.errors, status: :unprocessable_entity }\n format.json { render json: @phrase.errors, status: :unprocessable_entity }\n format.js { render 'common/errors', :locals => { :errors => @translation.errors } }\n end\n end\n end",
"def append2_to_hash (key, intermediatekey, value )\n if not self.has_key?(key)\n self[key] = Hash.new(Array.new)\n end\n self[key].append(intermediatekey,value)\n end",
"def add_values(tag, *values)\n return if values.empty?\n\n prepare_tag tag\n @hash[tag.upcase].merge(values)\n\n self\n end",
"def merge_texts!(hash, element)\n unless element.has_text?\n hash\n else\n # must use value to prevent double-escaping\n texts = +\"\"\n element.texts.each { |t| texts << t.value }\n merge!(hash, CONTENT_KEY, texts)\n end\n end"
] | {
"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_lines_from_file(filename)\n lines.each { |words| database << get_words_from_line(words) }\n database\nend",
"def loadDB\n input_data = File.read( $fn )\n $cd_arr = YAML::load( input_data )\nend",
"def file2db(string_file)\n def parse_hash(dict, locale, prefix = \"\")\n res = []\n dict.keys.each do |x|\n if dict[x].kind_of?(Hash)\n res += parse_hash(dict[x], locale, \"#{prefix}#{x}.\")\n else\n res << Interpret::Translation.create!(:locale => locale, :key => \"#{prefix}#{x}\", :value => dict[x])\n end\n end\n res\n end\n\n hash = YAML.load string_file\n lang = hash.keys.first\n parse_hash(hash.first[1], lang).map{|x| x.save!}\nend",
"def build_db(db_file)\n root = Hash.new\n File.open(db_file, \"r\") do |f|\n \tf.each_line do |line|\n \t parts = line.split(\",\")\n \t student = {\"name\" => parts[0], \"gender\" => parts[1], \"age\" => parts[2], \"studies\" => parts[3], \"year\" => parts[4]}\n \t insert_node(root, student)\n \tend\n end\n root\nend",
"def load_from_file(path = nil)\n path ||= \"db/#{table_name}.yml\"\n\n self.destroy_all\n\n if connection.respond_to?(:reset_pk_sequence!)\n connection.reset_pk_sequence!(table_name)\n end\n\n records = YAML.load(File.open(File.expand_path(path, Rails.root)))\n records.each do |record|\n record_copy = self.new(record.attributes)\n record_copy.id = record.id\n\n # For Single Table Inheritance\n klass_col = record.class.inheritance_column.to_sym\n if record[klass_col]\n record_copy.type = record[klass_col]\n end\n\n record_copy.save\n end\n\n if connection.respond_to?(:reset_pk_sequence!)\n connection.reset_pk_sequence!(table_name)\n end\n end",
"def initialize(database, file_path)\n @file_path = file_path\n @entries = database.entries\n validate_csv_header\n end",
"def initialize\n\n\t\t# list all files in the database: all files should have the .txt extension\n\t\t@files = Dir.glob(\"./db/*.txt\")\n\n\t\t# create a hash containing topics as keys, and all word arrays as values\n\t\t@db = Hash.new\n\t\t@files.each {|f|\n\t\t\t# topic name are merely database file main filename\n\t\t\ttopic = File.basename(f, \".txt\").upcase\n\n\t\t\t# load file as an array of strings\n\t\t\t@db[topic] = File.readlines(f).collect {|w| w.chomp}\n\t\t}\n\tend",
"def load_db(filename)\n loadDB(filename)\nend",
"def initialize( file )\n @path = file.path\n @foodbase = Hash.new\n\n # for each line in the file\n # add the food/recipe object\n # to the database\n file.each do | line |\n\n line.chomp!\n sline = line.split(',')\n\n name = sline[0]\n case sline[1]\n when 'b'\n add( 'b', name, sline[2])\n when 'r'\n fList = []\n sline[2..-1].each { | food | fList += [@foodbase[food]] }\n add( 'r', name, fList )\n end\n\n end\n @save_check = true\n end",
"def initialize filename, create = false, optimize = true\n raise NonexistantDB if not create and not File.exists? filename\n\n @filename = filename\n @db = SQLite::Database.new filename\n create_names_table if @db.table_info(NamesTable).empty?\n enable_optimizations if optimize\n prepare_statements\n self\n end",
"def initialize(file)\n raise ArgumentError unless File.readable? file\n\n @file = file\n\n @db = SQLite3::Database.new(file)\n\n install unless installed?\n end",
"def import\n\n output = ''\n\n country_src = 'tmp/Countries.txt'\n \n rs = File.open(country_src)\n rs.gets # <-- remove first line (columns header) \"CountryID:Title\"\n countries = {}\n City.delete_all\n Region.delete_all\n Country.delete_all\n\n while (row = rs.gets) \n row = row.split(':')\n row[0].gsub!(/\\n/, '')\n row[1].gsub!(/\\n/, '')\n countries[row[0]] = {:name => row[1], :regions => {}, :model => nil}\n c = Country.new\n c.iso = row[0]\n c.name = row[1]\n c.save\n countries[row[0]][:model] = c\n end\n\n regions_src = 'tmp/Regions.txt'\n \n rs = File.open(regions_src)\n rs.gets # <-- remove the 1st line (header row) #CountryID:RegionID:Title\n while (row = rs.gets) \n row = row.split(':')\n row[0].gsub!(/\\n/, '')\n row[1].gsub!(/\\n/, '')\n row[2].gsub!(/\\n/, '')\n c = countries[row[0]][:model]\n r = Region.new\n r.iso = row[1]\n r.country_id = c.id\n\n # magic trick to ignore UTF-8 chars for now.\n ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')\n r.name = ic.iconv(row[2] + ' ')[0..-2]\n r.save\n countries[row[0]][:regions][row[1]] = r\n\n end\n\n cities_src = 'tmp/Cities.txt'\n \n rs = File.open(cities_src)\n rs.gets # <-- remove 1st row (header) #CountryID:RegionID:Title:Latitude:Longitude\n while(row = rs.gets)\n row = row.split(':')\n row[1].gsub!(/\\n/, '')\n row[2].gsub!(/\\n/, '')\n row[3].gsub!(/\\n/, '')\n row[4].gsub!(/\\n/, '')\n \n r = countries[row[0]][:regions][row[1]]\n if (!r.nil?) \n c = City.new\n ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')\n c.name = ic.iconv(row[2] + ' ')[0..-2] \n c.region_id = r.id\n c.lat = row[3]\n c.lng = row[4]\n c.save\n end\n end\n\n output += '<h1>Import complete</h1>'\n render(:text => output, :layout => false)\n end",
"def import\n @imports.each do |item|\n source = @sources[item['source']] || {}\n source_dir = source['path']\n source_files = item['files'] || []\n target = @targets[item['target']] || {}\n table_name = target['table']\n \n file_list = build_file_list(source_dir, source_files)\n transform = @transforms[item['transform']] || {}\n \n file_list.each do |file_name|\n columns = parse_file(file_name, source_dir, transform)\n \n create_table(target, columns)\n \n data_file_name = File.basename(file_name, '.*') + '.dat'\n data_file_path = File.full_path(@working_dir, data_file_name)\n error_file_name = File.basename(file_name, '.*') + '.err'\n error_file_path = File.full_path(@error_dir, error_file_name)\n \n bcp_file(table_name, data_file_path, error_file_path, target)\n end\n end\n end",
"def import_cities\n City.destroy_all\n print_title('importing cities')\n File.open 'db/data/2_sql_insert_city.sql', 'r' do |file|\n while row = file.gets\n row.strip!\n columns = /.+\\(\\d+,'(\\d+)','(.+)','(\\d+)'\\)/.match(row)\n code = columns[1]\n name = columns[2]\n province_code = columns[3]\n city = City.create(code: code, name: name, province_code: province_code)\n print_content \"imported city: #{city.id}, #{city.code}, #{city.name}, #{city.province_code}\"\n end\n end\n print_summary \"total imported cities count: #{City.count}\"\nend",
"def import_cities\n City.destroy_all\n print_title('importing cities')\n File.open 'db/2_sql_insert_city.sql', 'r' do |file|\n while row = file.gets\n row.strip!\n columns = /.+\\(\\d+,'(\\d+)','(.+)','(\\d+)'\\)/.match(row)\n code = columns[1]\n name = columns[2]\n province_code = columns[3]\n city = City.create(code: code, name: name, province_code: province_code)\n print_content \"imported city: #{city.id}, #{city.code}, #{city.name}, #{city.province_code}\"\n end\n end\n print_summary \"total imported cities count: #{City.count}\"\nend",
"def init # should eventually take configuration options (hash || block)\n if ActiveRecord::Base.connection.tables.include? 'aux_codes'\n aux_codes_yml = File.join 'config', 'aux_codes.yml'\n if File.file? aux_codes_yml\n load_file aux_codes_yml\n create_classes!\n end\n end\n end",
"def init(dbdir)\n\n end"
] | {
"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 <=> x.length }
ary[0] # The longest element is the first
end | [
"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 end\n end\n end\n\n nil\n end",
"def longest_phrase(phrases, words)\n phrases.select do |phrase|\n phrase_words = phrase.gsub(/([.,;])/, ' \\1 ').split\n phrase_words.all? {|phrase_word| words.include? phrase_word}\n end.max_by {|phrase| phrase.length}.to_s\n end",
"def largest_hidden_word words, word_to_clean\n words.each_with_object([]) do |word, arr|\n arr << word.split(//).keep_if do |c|\n word_to_clean.include? c\n end\n end.sort_by do |e|\n e.count\n end.last.join\nend",
"def premature?(row)\n row.last.downcase == 'premature'\n end",
"def top_scoring_words\n @dictionary.each_with_object([]) do |cur_word, words_found|\n return words_found if words_found.length >= WORDS_TO_FIND\n\n words_found << cur_word if letters_present_for cur_word\n end\n end",
"def remove_w_words(sentence)\n result = []\n sentence.split.each do |word|\n if \",?\".include?(word[-1])\n result << word[-1]\n elsif word.downcase.include?(\"w\")\n result << \"\"\n else\n result << word\n end\n end\n result.join(\" \")\nend",
"def save_ambigious_file(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 tag_strings = ['unkjent_ord'] if tag_strings.count == 0\n f.puts w.norm_string + \"\\t\" + tag_strings.sort.join(\"\\t\")\n end\n\n f.puts\n end\n end\n\n nil\n end",
"def words_after(word)\n shakespeare = File.read(File.dirname(__FILE__) + '/Shakespeare.txt')\n shakespeare.scan(Regexp.new(word + ' (\\w+)')).uniq.flatten\nend",
"def save_cleaned_cor_file(file_name)\n File.open(file_name, 'w') do |f|\n sentences.each do |s|\n s.words.each do |w|\n if w.ambigious? and w.clean_tag_ambiguity?\n w.remove_clean_tag_ambiguity\n elsif w.ambigious? and w.noun_gender_ambiguity?\n w.remove_noun_gender_ambiguity\n end\n f.puts '\"<' + w.string + '>\"'\n\n w.tags.each do |t|\n f.puts \"\\t\\\"#{t.lemma}\\\" #{t.string} \" + (t.correct ? \"\\t<Correct!>\" : \"\")\n end\n end\n end\n end\n\n nil\n end",
"def phrases; end",
"def preserve_best_sentences(data)\n puts \"For each word with multiple examples below, choose the best selection:\"\n\n total_words = data.count { |d| d[:sentences].size > 1 }\n curr_word = 0\n data.select { |d| d[:sentences].size > 1 }.map! do |d|\n curr_word += 1\n puts \"#{curr_word} of #{total_words}: #{d[:word]} (#{d[:pronounciation]})\"\n d[:sentences].each_with_index do |s, i|\n puts \"#{i + 1}.\\t#{s[0]}\"\n puts \"\\t#{s[1]}\"\n end\n n = get_selection_number(\"Best sentence: \", 1, d[:sentences].size)\n selection = d[:sentences][n - 1]\n d[:sentences] = [ [ selection[0], selection[1] ] ]\n d\n end\n\n puts \"\\nDone.\"\nend",
"def case_corrector\n orig = @query.split\n latest = @message.split\n orig.each_with_index do |original_word,j|\n if i = latest.index(original_word.downcase)\n latest[i] = original_word\n end\n end\n @message = latest.join(\" \")\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_matches?(token) # token was not transformed earlier\n @to_match << token\n unmatched_db[token] = @processor.original_text\n end\n end\n unmatched_db.close\n end",
"def remove_bad_words(report_model = nil)\n all_words = Word.all_words\n contain_bad_words = false\n res = self.gsub(/\\b\\w+\\b/) do |word|\n if all_words.include?(word.downcase)\n contain_bad_words = true\n '***'\n else\n word\n end\n end.squeeze(' ')\n Report.where(description: 'Contain bad words', target: report_model).first_or_create if contain_bad_words\n res\n end",
"def you_just_deleted_the_first_word_in_hash\n\t\t@word_index.values.max == nil\n\tend",
"def filter_message(text)\n #for now the words are split by a space. If any word matches with any of the popular english curse words then the word is simply replaced with an empty string\n words = text.split(\" \") #words are split by a space\n words.delete_if {|word| @profanity_words_array.include?(word)}\n text = words.join(\" \")\n end",
"def best_word\n words = []\n possible_words.each do |word|\n word.possible_positions(@board).each do |position|\n value = @board.try(word,position[:origin],position[:orientation],self)\n words << {:word => word, :origin => position[:origin],:orientation => position[:orientation],:value => value.to_i}\n end\n end \n words.max {|a,b| a[:value] <=> b[:value]}\n end",
"def grab_antiwords(key)\n antiwords = DailyMessengerUtils.get_antiwords(key)\n if antiwords\n return antiwords.gsub(',', ', ')\n else\n return \"\"\n end\n end",
"def most_significant\n most_sig = []\n # if !description.nil?\n # if tags.any?\n # most_sig = tags.select {|tag| self.description.downcase.include?(tag)}.collect {|tag| tag.singularize }\n # else\n # most_sig = word_frequency.keys.select {|tag| self.description.downcase.include?(tag)}.collect {|tag| tag.singularize }\n # end\n # end\n\n description.to_s.split.each do |word|\n self.word_frequency[word] ||= 0\n self.word_frequency[word] += 1\n end\n\n if most_sig.empty?\n most_sig = self.word_frequency.reject {|k,v| v < 3}.keys\n most_sig.flatten!\n end\n\n if description && tags.any?\n tags.each do |tag|\n if description.include?(tag)\n most_sig << tag.singularize\n end\n end\n end\n \n most_sig.uniq!\n\n self.validate_lang\n\n if SiteClassifier.translate_tags?\n begin\n if self.lang == \"auto\"\n @lang = EasyTranslate.detect(most_sig.first, key: SiteClassifier.configuration.google_translate_api_key)\n end\n EasyTranslate.translate(most_sig, from: self.lang, to: :en, key: SiteClassifier.configuration.google_translate_api_key)\n rescue\n return most_sig\n end\n else\n return most_sig\n end\n end"
] | {
"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
# Skip lines starting with blanks, because these are already
# translations and they don't belong to the matching line.
next
end
else
match_line_found = false
end
if line.downcase =~ /#{query}/
puts line
match_line_found = true
end
end
end
end
end | [
"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 end",
"def matching_lines(regex); end",
"def search_words\n begin\n regex = Regexp.new(@pattern)\n rescue RegexpError => msg\n error_msg(msg)\n rescue NameError => msg\n error_msg(msg)\n end\n @results = DICT.select do |word|\n regex =~ word\n end\n @num_results = @results.length\n format_results\n display_results\n end",
"def pre_match() end",
"def find_all_matching(text, &block)\n matches = []\n pos = 0\n text_len = text.length\n \n while pos < text_len do\n container = @trie\n len = 0\n \n pos.upto(text_len - 1) do |i|\n b = text[i]\n break unless container[b] \n container = container[b]\n len += 1\n end\n \n if container[0] # Match\n if block\n block.call(pos, len)\n else\n matches << [pos, len]\n end\n pos += len # Skip over word\n else \n pos += 1\n end\n end\n \n matches\n end",
"def match\n @results = Word.word_match(params[:pattern].gsub(/_|-/, '?')).map(&:upcase)\n end",
"def textmatch(text, terms)\n terms.all? { |term| text =~ /#{term}/i }\nend",
"def on_regexp(node); end",
"def search_for_regexes(tagged_words, size, regexes)\n tagged_words.each_cons(size).map do |t|\n if focal_word && t.none? { |w| w.start_with?(\"#{focal_word.downcase}/\") }\n next\n end\n\n gram = t.join(' ')\n next unless regexes.any? { |r| gram =~ r }\n\n stripped = gram.gsub(%r{/(JJ[^\\s]?|NN[^\\s]{0,2}|IN)(\\s+|\\Z)}, '\\2')\n\n result[stripped] ||= 0\n result[stripped] += 1\n end\n end",
"def regex_searcher(pattern, string)\n\tis_match_helper(pattern, string, 0, 0)\nend",
"def prefer_for_regular_expression_match; end",
"def matched_keyword; end",
"def match(tokens, definitions); end",
"def regexp_source; end"
] | {
"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 @callbacks[:on_headers_complete] = cb\n @settings[:on_headers_complete] = cb\n end",
"def process_with_headers(&block)\n @headers = HeadersParser.new\n @headers.process do |headers|\n failsafe do\n yield headers\n\n if_present(@selected_backend) do\n setup_server(@selected_backend)\n relay_to_servers(@headers.buffer)\n end\n end\n end\n end",
"def processed_headers; end",
"def handle_headers_complete(headers)\n @code = @parser.status_code.to_i\n if @code != 200\n receive_error(\"invalid status code: #{@code}.\")\n end\n self.headers = headers\n @state = :stream\n end",
"def on_chunk_header(&block)\n cb = Callback.new(&block)\n @callbacks[:on_message_complete] = cb\n @settings[:on_message_complete] = cb\n end",
"def execute_headers_callbacks(response)\n (Typhoeus.on_headers + on_headers).map do |callback|\n callback.call(response)\n end\n end",
"def process_header_lines(lines, &block)\n return unless block\n\n state = \"before_header\"\n lines.each do |line|\n case state\n when \"before_header\" then (state = \"in_header\" if line =~ /^[=+]^.*$/ || yield(line))\n when \"in_header\" then (state = \"done\" if line =~ /^\\s*$/ || yield(line))\n when \"done\" then break\n end\n end\n end",
"def define_headers\n yield headers if block_given?\n\n headers\n end",
"def handle_preconditions\n @headers[\"Authorization\"] = \"Token token=\\\"#{connect!}\\\"\"\n puts @headers\n yield\n end",
"def on_headers_complete(headers)\n @headers = headers\n end",
"def parse\n parse_request_line\n while (line = next_line) != nil do\n if !line.empty? \n parse_header(line)\n else break\n end\n end\n while (line = next_line) != nil do\n parse_body(line)\n end\n end",
"def process_with_header(key, &block)\n process_with_headers do |headers|\n if_present(headers[key]) do\n yield headers[key]\n end\n end\n end",
"def on_header_value(&block)\n @settings[:on_header_value] = DataCallback.new(&block)\n end",
"def parse(data)\n if @parser.finished? # Header finished, can only be some more body\n body << data\n else # Parse more header using the super parser\n @data << data\n @nparsed = @parser.execute(@env, @data, @nparsed)\n end\n \n if finished? # Check if header and body are complete\n @data = nil\n @body.rewind\n true # Request is fully parsed\n else\n false # Not finished, need more data\n end\n end",
"def process_header_lines(lines)\n state = \"before_header\"\n lines.each do |line|\n case state\n when \"before_header\" then (state = \"in_header\" if line =~ /^[=+]^.*$/ || yield(line))\n when \"in_header\" then (state = \"done\" if line =~ /^\\s*$/ || yield(line))\n when \"done\" then break\n end\n end\n end",
"def parseHeaders(request) \n headers = {};\n\n # Loop through headers\n request.lines[1..-1].each do |line|\n # If we are moving to the next line, return what we currently have\n return headers if line == \"\\r\\n\"\n\n # Structure data\n header, value = line.split\n header = header.gsub(\":\", \"\").downcase.to_sym\n headers[header] = value\n end\nend",
"def on_headers(headers)\n log.info { \">> headers (#{headers.size})\" }\n headers.each {|h| @node.queue.push([:block, h])}\n end"
] | {
"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
end
item = items[current_row]
main.draw_item item, current: true
main.display current_page
header_l.draw_current_file_info item
@current_row
end | [
"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 yield if block_given?\n output.print NEWLINE\n @first_render = false\n else\n lines_up = (@multibar.rows + 1) - @row\n output.print TTY::Cursor.save\n output.print TTY::Cursor.up(lines_up)\n yield if block_given?\n output.print TTY::Cursor.restore\n end\n end\n else\n yield if block_given?\n end\n end",
"def select_row(row_number = 0)\n set_cursor(Gtk::TreePath.new(row_number), nil, false)\n end",
"def scroll_to row\n height = Curses.lines - 2\n\n if row < @current_row then\n @current_row = row\n elsif row > @current_row + height then\n @current_row = row\n end\n\n noutrefresh\n end",
"def next_row\n @rows+=1\n set RGhost::Cursor.next_row\n end",
"def goto_row!(row)\n step { @selected = row - 1 if row.positive? && row <= filtered_items }\n end",
"def set_cursor_position(row, col)\n\t\tinvalid_rows = [@cursor_row, row]\n\t\t@cursor_row, @cursor_col = row, col\n\t\tif @cursor_row < first_line_in_view\n\t\t\tset_contents_pos(0, line_num_to_coord(@cursor_row))\n\t\t\temit_changed(nil)\n\t\telsif @cursor_row > last_line_in_view\n\t\t\tset_contents_pos(0, line_num_to_coord(@cursor_row - num_lines_in_view))\n\t\t\temit_changed(nil)\n\t\tend\n\tend",
"def goto_next_selection\n return if selected_rows().length == 0 \n row = selected_rows().sort.find { |i| i > @obj.current_index }\n row ||= @obj.current_index\n #@obj.current_index = row\n @obj.goto_line row\n end",
"def edit_row_path(row, **opt)\n row = positive(row)\n page = row && positive((row - 1) / grid_page_size)\n opt[:id] ||= object.manifest_id\n opt[:page] ||= page + 1 if page\n opt[:anchor] ||= \"#{model_type}-item-#{row}\" if row\n h.edit_manifest_path(**opt)\n end",
"def cursor_move_up\n\t\tif @cursor[1] > min_row\n\t\t\tcursor_move(SUB_UP)\n\t\t\treprint\n\t\tend\n\tend",
"def next_row\n @current_row += 1\n end",
"def position_cursor( row, column )\r\n STDOUT.write \"\\e[#{ row };#{ column }H\"\r\n end",
"def current_row\n @row_offset\n end",
"def render_nth_row(row)\n start = row * per_row\n stop = (row + 1) * per_row\n files_this_row = files_to_render_this_page[start...stop] || []\n if files_this_row.empty?\n Html::Div.new(:class => 'row') << Html::Comment.new << \"No files in this row.\"\n else\n render_row(files_this_row)\n end\n end",
"def update_head_horizontal_location(column)\n locate_head[1] = column\n end",
"def cursor_pageup\n if top_row > 0\n Sound.play_cursor\n self.top_row -= page_row_max\n self.index = [@index - page_item_max, 0].max\n end\n end",
"def move_to(row, col)\n @row, @col = wrap(row, col)\n end",
"def row_seek(n)\n ret = @index\n @index = n\n ret\n end"
] | {
"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 : reverse order by ctime u : order by atime ur : reverse order by atime e : order by extname er : reverse order by extname | 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 parent before sorting, keep at top\n first = @entries.delete_at(0) if @entries[0]==\"..\"\n #key ||= @sort_key\n sort_keys = { 'Name' => :name, 'Modified' => :mtime, \"Size\" => :size, \"<Order_by_Extension>\" => :ext, 'Attr' => :attr, \"Accessed\" => :atime }\n key = sort_keys[key] if sort_keys.has_key? key\n #if key == @sort_key\n #reverse = true\n #end\n cdir=@current_path+\"/\"\n case key\n when :size\n @entries.sort! {|x,y| xs = File.stat(cdir+x); ys = File.stat(cdir+y); \n if reverse\n xs.size <=> ys.size \n else\n ys.size <=> xs.size \n end\n }\n when :mtime\n @entries.sort! {|x,y| xs = File.stat(cdir+x); ys = File.stat(cdir+y); \n if reverse\n xs.mtime <=> ys.mtime \n else\n ys.mtime <=> xs.mtime \n end\n }\n when :atime\n @entries.sort! {|x,y| xs = File.stat(cdir+x); ys = File.stat(cdir+y); \n if reverse\n xs.atime <=> ys.atime \n else\n ys.atime <=> xs.atime \n end\n }\n when :name\n @entries.sort! {|x,y| x <=> y \n if reverse\n x <=> y\n else\n y <=> x\n end\n }\n when :ext\n @entries.sort! {|x,y| \n if reverse\n File.extname(cdir+x) <=> File.extname(cdir+y) \n else\n File.extname(cdir+y) <=> File.extname(cdir+x) \n end\n }\n when :attr\n @entries.sort! {|x,y| xs = File.stat(cdir+x); ys = File.stat(cdir+y); \n x = xs.directory? ? \"d\" : \"D\"\n y = ys.directory? ? \"d\" : \"D\"\n if reverse\n x <=> y\n else\n y <=> x\n end\n }\n end\n @sort_key = key\n @entries.insert 0, first unless first.nil? # keep parent on top\n populate @entries\n end",
"def sort!\n folders.each do |name, folder|\n folder.sort!\n end\n end",
"def sort_direction(direction)\n %w[asc desc].include?(direction) ? direction : 'asc'\n end",
"def sort!\n #N Without this, the immediate sub-directories won't get sorted\n dirs.sort_by! {|dir| dir.name}\n #N Without this, files contained immediately in this directory won't get sorted\n files.sort_by! {|file| file.name}\n #N Without this, files and directories contained within sub-directories of this directory won't get sorted\n for dir in dirs\n #N Without this, this sub-directory won't have its contents sorted\n dir.sort!\n end\n end",
"def list_files dir='*', sorto=@sorto, hidden=@hidden, _filter=@filterstr\n dir += '/*' if File.directory?(dir)\n dir = dir.gsub('//', '/')\n\n # decide sort method based on second character\n # first char is o or O (reverse)\n # second char is macLn etc (as in zsh glob)\n so = sorto ? sorto[1] : nil\n func = case so\n when 'm'\n :mtime\n when 'a'\n :atime\n when 'c'\n :ctime\n when 'L'\n :size\n when 'n'\n :path\n when 'x'\n :extname\n end\n\n # sort by time and then reverse so latest first.\n sorted_files = if hidden == 'D'\n Dir.glob(dir, File::FNM_DOTMATCH) - %w[. ..]\n else\n Dir.glob(dir)\n end\n\n # WARN: crashes on a deadlink since no mtime\n if func\n sorted_files = sorted_files.sort_by do |f|\n if File.exist? f\n File.send(func, f)\n else\n sys_stat(func, f)\n end\n end\n end\n\n sorted_files.sort! { |w1, w2| w1.casecmp(w2) } if func == :path && @ignore_case\n\n # zsh gives mtime sort with latest first, ruby gives latest last\n sorted_files.reverse! if sorto && sorto[0] == 'O'\n\n # add slash to directories\n sorted_files = add_slash sorted_files\n # return sorted_files\n @files = sorted_files\n calculate_bookmarks_for_dir # we don't want to override those set by others\nend",
"def files_search_results(search_result, direction)\n files, files_in_folders = search_result.compact.partition { |v| v[:file_path] == \"/\" }\n\n folders_result = files_map(files_in_folders)\n sorted_folders = []\n folders_result.\n group_by { |k| [k[:path]] }.\n sort_by { |k, _| k[0].downcase }.\n each { |_, v| sorted_folders << v }\n sorted_folders.flatten!\n\n files_result = files_map(files)\n sorted_files = files_result.sort_by { |k| k[:title].downcase }\n\n if direction == \"desc\"\n sorted_folders = sorted_folders.reverse\n sorted_files = sorted_files.reverse\n end\n sorted_folders + sorted_files\n end",
"def sort_search_results(column, direction)\n case column\n when 'likes'\n reorder(:cached_votes_up => direction)\n when 'hates'\n reorder(:cached_votes_down => direction)\n when 'date'\n reorder(:created_at => direction)\n else\n reorder(:cached_votes_up => direction)\n end\n end",
"def upcasing_sort_direction(direction = @paginable_params[:sort_direction])\n directions = ['asc', 'desc', 'ASC', 'DESC']\n return directions.include?(direction) ? direction.upcase : 'ASC'\n end",
"def sorting_info(s_item, s_direction)\n\n file_link_dir = mtime_link_dir = sortby_link_dir = \"ascending\"\n s_item_display = s_direction_display = \"\"\n \n case s_item\n when \"file\"\n s_item_display = \"alphabetically\"\n case s_direction\n when \"ascending\"\n s_direction_display = \"\"\n file_link_dir = \"descending\"\n when \"descending\"\n s_direction_display = \"reversed\"\n file_link_dir = \"ascending\"\n end\n when \"mtime\"\n s_item_display = \"by modification date\"\n case s_direction\n when \"ascending\"\n s_direction_display = \"oldest to newest\"\n mtime_link_dir = \"descending\"\n when \"descending\"\n s_direction_display = \"newest to oldest\"\n mtime_link_dir = \"ascending\"\n end\n when \"size\"\n s_item_display = \"by size\"\n case s_direction\n when \"ascending\"\n s_direction_display = \"smallest to largest\"\n sortby_link_dir = \"descending\"\n when \"descending\"\n s_direction_display = \"largest to smallest\"\n sortby_link_dir = \"ascending\"\n end\n end\n \n return \"?sortby=file&direction=#{file_link_dir}\",\n \"?sortby=mtime&direction=#{mtime_link_dir}\",\n \"?sortby=size&direction=#{sortby_link_dir}\",\n s_item_display,\n s_direction_display\n \n end",
"def sort_direction\n # karakter kontrol yapiliyor security icin \n %w[asc desc].include?(params[:direction]) ? params[:direction] : \"asc\" \n end",
"def sort_by_path_column ( to_sort, order_dir )\n to_sort.sort { |x,y| sort(x,y, order_dir ) }\n end",
"def sort_by_path_column! ( to_sort, order_dir )\n to_sort.sort! { |x,y| sort(x,y, order_dir ) }\n end",
"def sort_direction\n params[\"order\"][\"0\"][\"dir\"] == \"desc\" ? \"desc\" : \"asc\"\n end",
"def sort_by(tree, col, direction)\n tree.children(nil).map!{|row| [tree.get(row, col), row.id]} .\n sort(&((direction)? proc{|x, y| y <=> x}: proc{|x, y| x <=> y})) .\n each_with_index{|info, idx| tree.move(info[1], nil, idx)}\n\n tree.heading_configure(col, :command=>proc{sort_by(tree, col, ! direction)})\nend",
"def sort(column, direction)\n clone_and_set {|params|\n c = symbol_to_name(column)\n params['sort'] = (direction == :desc ? \"-#{c}\" : c)\n }\n end",
"def normalize_direction(direction)\n (direction =~ DIRECTION_DESC) ? 'DESC' : 'ASC'\n end",
"def sort_html_class(direction)\n direction == 'asc' ? 'up' : 'down'\n end"
] | {
"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",
"def chmod(file, mode)\n if File.stat(file).mode != mode\n FileUtils.chmod(mode, file, :verbose => verbose?) \n end\n end",
"def lchmod(mode)\n File.lchmod(mode, @path)\n end",
"def chmod(path, mode, log_status=true)\n path = File.expand_path(path, root)\n say_status :chmod, relative_to_absolute_root(path), log_status\n FileUtils.chmod_R(mode, path) unless options[:pretend]\n end",
"def fs_chmod(mode, file = '/')\n FileUtils.chmod_R(mode, File.join(self.git_dir, file))\n end",
"def chmod(mode, list, noop: nil, verbose: nil)\n list = fu_list(list)\n fu_output_message sprintf('chmod %s %s', mode_to_s(mode), list.join(' ')) if verbose\n return if noop\n list.each do |path|\n Entry_.new(path).chmod(fu_mode(mode, path))\n end\n end",
"def chmod(mode, list, options = {})\r\n fu_check_options options, :noop, :verbose\r\n list = fu_list(list)\r\n fu_output_message sprintf('chmod %o %s', mode, list.join(' ')) if options[:verbose]\r\n return if options[:noop]\r\n File.chmod mode, *list\r\n end",
"def set_mode(mode, path, protected = true)\n owner_sid = get_owner(path)\n group_sid = get_group(path)\n well_known_world_sid = Win32::Security::SID::Everyone\n well_known_nobody_sid = Win32::Security::SID::Nobody\n\n owner_allow = STANDARD_RIGHTS_ALL | FILE_READ_ATTRIBUTES | FILE_WRITE_ATTRIBUTES\n group_allow = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES | SYNCHRONIZE\n other_allow = STANDARD_RIGHTS_READ | FILE_READ_ATTRIBUTES | SYNCHRONIZE\n nobody_allow = 0\n\n MODE_TO_MASK.each do |k,v|\n if ((mode >> 6) & k) == k\n owner_allow |= v\n end\n if ((mode >> 3) & k) == k\n group_allow |= v\n end\n if (mode & k) == k\n other_allow |= v\n end\n end\n\n if (mode & S_ISVTX).nonzero?\n nobody_allow |= FILE_APPEND_DATA;\n end\n\n isdir = File.directory?(path)\n\n if isdir\n if (mode & (S_IWUSR | S_IXUSR)) == (S_IWUSR | S_IXUSR)\n owner_allow |= FILE_DELETE_CHILD\n end\n if (mode & (S_IWGRP | S_IXGRP)) == (S_IWGRP | S_IXGRP) and (mode & S_ISVTX) == 0\n group_allow |= FILE_DELETE_CHILD\n end\n if (mode & (S_IWOTH | S_IXOTH)) == (S_IWOTH | S_IXOTH) and (mode & S_ISVTX) == 0\n other_allow |= FILE_DELETE_CHILD\n end\n end\n\n # if owner and group the same, then map group permissions to the one owner ACE\n isownergroup = owner_sid == group_sid\n if isownergroup\n owner_allow |= group_allow\n end\n\n # if any ACE allows write, then clear readonly bit, but do this before we overwrite\n # the DACl and lose our ability to set the attribute\n if ((owner_allow | group_allow | other_allow ) & FILE_WRITE_DATA) == FILE_WRITE_DATA\n remove_attributes(path, FILE_ATTRIBUTE_READONLY)\n end\n\n set_acl(path, protected) do |acl|\n #puts \"ace: owner #{owner_sid}, mask 0x#{owner_allow.to_s(16)}\"\n add_access_allowed_ace(acl, owner_allow, owner_sid)\n\n unless isownergroup\n #puts \"ace: group #{group_sid}, mask 0x#{group_allow.to_s(16)}\"\n add_access_allowed_ace(acl, group_allow, group_sid)\n end\n\n #puts \"ace: other #{well_known_world_sid}, mask 0x#{other_allow.to_s(16)}\"\n add_access_allowed_ace(acl, other_allow, well_known_world_sid)\n\n #puts \"ace: nobody #{well_known_nobody_sid}, mask 0x#{nobody_allow.to_s(16)}\"\n add_access_allowed_ace(acl, nobody_allow, well_known_nobody_sid)\n\n # add inherit-only aces for child dirs and files that are created within the dir\n if isdir\n inherit = INHERIT_ONLY_ACE | CONTAINER_INHERIT_ACE\n add_access_allowed_ace(acl, owner_allow, Win32::Security::SID::CreatorOwner, inherit)\n add_access_allowed_ace(acl, group_allow, Win32::Security::SID::CreatorGroup, inherit)\n\n inherit = INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE\n add_access_allowed_ace(acl, owner_allow & ~FILE_EXECUTE, Win32::Security::SID::CreatorOwner, inherit)\n add_access_allowed_ace(acl, group_allow & ~FILE_EXECUTE, Win32::Security::SID::CreatorGroup, inherit)\n end\n end\n\n nil\n end",
"def chmod(path, mode, options={})\n check_options(options, OPT_TABLE['SETPERMISSION'])\n res = operate_requests('PUT', path, 'SETPERMISSION', options.merge({'permission' => mode}))\n res.code == '200'\n end",
"def mode=(value)\n self.class.send_log(:debug, \"call mode=(#{value})\")\n File.chmod(Integer(\"0\" + value), @resource[:name])\n end",
"def mode=(value)\n File.chmod(Integer(\"0\" + value), @resource[:name])\n end",
"def mode=(value)\n File.chmod(Integer(\"0\" + value), @resource[:name])\n end",
"def mode=(value)\n File.chmod(Integer(\"0#{value}\"), @resource[:name])\n end",
"def set_mode(mode, path, protected = true, managing_owner = false, managing_group = false)\n sd = get_security_descriptor(path)\n well_known_world_sid = Puppet::Util::Windows::SID::Everyone\n well_known_nobody_sid = Puppet::Util::Windows::SID::Nobody\n well_known_system_sid = Puppet::Util::Windows::SID::LocalSystem\n\n owner_allow = FILE::STANDARD_RIGHTS_ALL |\n FILE::FILE_READ_ATTRIBUTES |\n FILE::FILE_WRITE_ATTRIBUTES\n # this prevents a mode that is not 7 from taking ownership of a file based\n # on group membership and rewriting it / making it executable\n group_allow = FILE::STANDARD_RIGHTS_READ |\n FILE::FILE_READ_ATTRIBUTES |\n FILE::SYNCHRONIZE\n other_allow = FILE::STANDARD_RIGHTS_READ |\n FILE::FILE_READ_ATTRIBUTES |\n FILE::SYNCHRONIZE\n nobody_allow = 0\n system_allow = 0\n\n MODE_TO_MASK.each do |k,v|\n if ((mode >> 6) & k) == k\n owner_allow |= v\n end\n if ((mode >> 3) & k) == k\n group_allow |= v\n end\n if (mode & k) == k\n other_allow |= v\n end\n end\n\n # With a mode value of '7' for group / other, the value must then include\n # additional perms beyond STANDARD_RIGHTS_READ to allow DACL modification\n if ((mode & S_IRWXG) == S_IRWXG)\n group_allow |= FILE::DELETE | FILE::WRITE_DAC | FILE::WRITE_OWNER\n end\n if ((mode & S_IRWXO) == S_IRWXO)\n other_allow |= FILE::DELETE | FILE::WRITE_DAC | FILE::WRITE_OWNER\n end\n\n if (mode & S_ISVTX).nonzero?\n nobody_allow |= FILE::FILE_APPEND_DATA;\n end\n\n isownergroup = sd.owner == sd.group\n\n # caller is NOT managing SYSTEM by using group or owner, so set to FULL\n if ! [sd.owner, sd.group].include? well_known_system_sid\n # we don't check S_ISYSTEM_MISSING bit, but automatically carry over existing SYSTEM perms\n # by default set SYSTEM perms to full\n system_allow = FILE::FILE_ALL_ACCESS\n else\n # It is possible to set SYSTEM with a mode other than Full Control (7) however this makes no sense and in practical terms\n # should not be done. We can trap these instances and correct them before being applied.\n if (sd.owner == well_known_system_sid) && (owner_allow != FILE::FILE_ALL_ACCESS)\n # If owner and group are both SYSTEM but group is unmanaged the control rights of system will be set to FullControl by\n # the unmanaged group, so there is no need for the warning\n if managing_owner && (!isownergroup || managing_group)\n #TRANSLATORS 'SYSTEM' is a Windows name and should not be translated\n Puppet.warning _(\"Setting control rights for %{path} owner SYSTEM to less than Full Control rights. Setting SYSTEM rights to less than Full Control may have unintented consequences for operations on this file\") % { path: path }\n elsif managing_owner && isownergroup\n #TRANSLATORS 'SYSTEM' is a Windows name and should not be translated\n Puppet.debug { _(\"%{path} owner and group both set to user SYSTEM, but group is not managed directly: SYSTEM user rights will be set to FullControl by group\") % { path: path } }\n else\n #TRANSLATORS 'SYSTEM' is a Windows name and should not be translated\n Puppet.debug { _(\"An attempt to set mode %{mode} on item %{path} would result in the owner, SYSTEM, to have less than Full Control rights. This attempt has been corrected to Full Control\") % { mode: mode.to_s(8), path: path } }\n owner_allow = FILE::FILE_ALL_ACCESS\n end\n end\n\n if (sd.group == well_known_system_sid) && (group_allow != FILE::FILE_ALL_ACCESS)\n # If owner and group are both SYSTEM but owner is unmanaged the control rights of system will be set to FullControl by\n # the unmanaged owner, so there is no need for the warning.\n if managing_group && (!isownergroup || managing_owner)\n #TRANSLATORS 'SYSTEM' is a Windows name and should not be translated\n Puppet.warning _(\"Setting control rights for %{path} group SYSTEM to less than Full Control rights. Setting SYSTEM rights to less than Full Control may have unintented consequences for operations on this file\") % { path: path }\n elsif managing_group && isownergroup\n #TRANSLATORS 'SYSTEM' is a Windows name and should not be translated\n Puppet.debug { _(\"%{path} owner and group both set to user SYSTEM, but owner is not managed directly: SYSTEM user rights will be set to FullControl by owner\") % { path: path } }\n else\n #TRANSLATORS 'SYSTEM' is a Windows name and should not be translated\n Puppet.debug { _(\"An attempt to set mode %{mode} on item %{path} would result in the group, SYSTEM, to have less than Full Control rights. This attempt has been corrected to Full Control\") % { mode: mode.to_s(8), path: path } }\n group_allow = FILE::FILE_ALL_ACCESS\n end\n end\n end\n\n # even though FILE_DELETE_CHILD only applies to directories, it can be set on files\n # this is necessary to do to ensure a file ends up with (F) FullControl\n if (mode & (S_IWUSR | S_IXUSR)) == (S_IWUSR | S_IXUSR)\n owner_allow |= FILE::FILE_DELETE_CHILD\n end\n if (mode & (S_IWGRP | S_IXGRP)) == (S_IWGRP | S_IXGRP) && (mode & S_ISVTX) == 0\n group_allow |= FILE::FILE_DELETE_CHILD\n end\n if (mode & (S_IWOTH | S_IXOTH)) == (S_IWOTH | S_IXOTH) && (mode & S_ISVTX) == 0\n other_allow |= FILE::FILE_DELETE_CHILD\n end\n\n # if owner and group the same, then map group permissions to the one owner ACE\n if isownergroup\n owner_allow |= group_allow\n end\n\n # if any ACE allows write, then clear readonly bit, but do this before we overwrite\n # the DACl and lose our ability to set the attribute\n if ((owner_allow | group_allow | other_allow ) & FILE::FILE_WRITE_DATA) == FILE::FILE_WRITE_DATA\n FILE.remove_attributes(path, FILE::FILE_ATTRIBUTE_READONLY)\n end\n\n isdir = File.directory?(path)\n dacl = Puppet::Util::Windows::AccessControlList.new\n dacl.allow(sd.owner, owner_allow)\n unless isownergroup\n dacl.allow(sd.group, group_allow)\n end\n dacl.allow(well_known_world_sid, other_allow)\n dacl.allow(well_known_nobody_sid, nobody_allow)\n\n # TODO: system should be first?\n flags = !isdir ? 0 :\n Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE |\n Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE\n dacl.allow(well_known_system_sid, system_allow, flags)\n\n # add inherit-only aces for child dirs and files that are created within the dir\n inherit_only = Puppet::Util::Windows::AccessControlEntry::INHERIT_ONLY_ACE\n if isdir\n inherit = inherit_only | Puppet::Util::Windows::AccessControlEntry::CONTAINER_INHERIT_ACE\n dacl.allow(Puppet::Util::Windows::SID::CreatorOwner, owner_allow, inherit)\n dacl.allow(Puppet::Util::Windows::SID::CreatorGroup, group_allow, inherit)\n\n inherit = inherit_only | Puppet::Util::Windows::AccessControlEntry::OBJECT_INHERIT_ACE\n # allow any previously set bits *except* for these\n perms_to_strip = ~(FILE::FILE_EXECUTE + FILE::WRITE_OWNER + FILE::WRITE_DAC)\n dacl.allow(Puppet::Util::Windows::SID::CreatorOwner, owner_allow & perms_to_strip, inherit)\n dacl.allow(Puppet::Util::Windows::SID::CreatorGroup, group_allow & perms_to_strip, inherit)\n end\n\n new_sd = Puppet::Util::Windows::SecurityDescriptor.new(sd.owner, sd.group, dacl, protected)\n set_security_descriptor(path, new_sd)\n\n nil\n end",
"def chmod(path, mode = nil, &block)\n add Config::Patterns::Chmod do |p|\n p.path = path\n p.mode = mode if mode\n yield p if block_given?\n end\n end",
"def chmod(file)\n mode = options[:mode]\n return unless mode\n\n FileUtils.chmod(mode, file)\n end",
"def set_modes(dir)\n Dir.glob(\"#{dir}/**/*\", File::FNM_DOTMATCH).each do |path|\n next if File.basename(path) == '.'\n\n if File.directory? path\n File.chmod(0755, path)\n else\n File.chmod(0644, path)\n end\n end\nend"
] | {
"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, destination_path\n end",
"def set_owner\n user = @conf['user'] || Process.uid\n group = @conf['group'] || Process.gid\n\n begin\n FileUtils.chown_R(user, group, @location)\n rescue StandardError => err\n Pemlogger.logit(err, :fatal)\n raise(err)\n end\n end",
"def chown(parameters)\n params_desc = {\n :files => { :mandatory => true, :type => :string_or_array },\n :user => { :mandatory => false, :type => :string_or_integer },\n :group => { :mandatory => false, :type => :string_or_integer },\n :recursive => { :mandatory => false, :type => :boolean,\n :default => false }\n }\n check_parameters(parameters, params_desc)\n files = parameters['files']\n user = parameters['user']\n group = parameters['group']\n recursive = parameters['recursive']\n files = Dir.glob(files)\n if files.length > 0\n puts \"Changing owner of #{files.length} file(s) to '#{user}/#{group}'\"\n begin\n if recursive\n FileUtils.chown_R(user, group, files)\n else\n FileUtils.chown(user, group, files)\n end\n rescue Exception\n error \"Error changing owner: #{$!}\"\n end\n end\n end",
"def chown(owner, group)\n File.chown(owner, group, @path)\n end",
"def chown( owner, group ) File.chown( owner, group, expand_tilde ) end",
"def chown(owner, group) File.chown(owner, group, path) end",
"def check_file_owner(options,file_name,uid)\n test_uid = File.stat(file_name).uid\n if test_uid != uid.to_i\n message = \"Information:\\tChanging ownership of \"+file_name+\" to \"+uid.to_s\n if file_name.to_s.match(/^\\/etc/)\n command = \"sudo chown #{uid.to_s} #{file_name}\"\n else\n command = \"chown #{uid.to_s} #{file_name}\"\n end\n execute_command(options,message,command)\n end\n return\nend",
"def chown(file, user)\n user = user.to_s\n # who is the current owner?\n @uids ||= {}\n @uids[user] ||= Etc.getpwnam(user).uid\n uid = @uids[user]\n if File.stat(file).uid != uid\n run \"chown #{user}:#{user} '#{file}'\" \n end\n end",
"def chown_mod(owner, group, mode, options = {})\n\t\tself.each() { |filename|\n\t\t\tCfruby::FileOps.chown_mod(filename, owner, group, mode, options)\n\t\t}\n\tend",
"def user_run_chown( *args )\n flags, paths = args.partition { |a| a =~ /^-/ }\n sudo( 'chown', flags, \"#{user_run}:#{user_run_group}\", paths )\n end",
"def change_owner(target_user_id)\n if (@project == nil or target_user_id == nil or target_user_id.blank?)\n @user_id_err = true #user selected \"none\" or error\n return false\n end\n if (target_user_id.blank? or target_user_id == nil)\n @user_id_err = true #user selected \"none\" or error\n return false\n end\n \n target_user = User.find(target_user_id) #finds selected user\n @project.collections.each do |collection|\n docs = Document.where(\"collection_id = ?\", collection.id) #gets an array of documents with the given project ID\n \n docs.each do |doc|\n doc.update_attributes(:user_id => target_user.id) #changes user ID of documents to target user \n end\n collection.update_attributes(:user_id => target_user.id) #changes user ID of collections to target user\n end\n @project.update_attributes(:user_id => target_user.id) #changes current project's user ID to target user's ID\n\n @user_id_err = false\n return true\n end",
"def set_owner(owner_sid, path)\n old_sid = get_owner(path)\n\n change_sid(old_sid, owner_sid, OWNER_SECURITY_INFORMATION, path)\n end",
"def chown(user, group, list, noop: nil, verbose: nil)\n list = fu_list(list)\n fu_output_message sprintf('chown %s %s',\n (group ? \"#{user}:#{group}\" : user || ':'),\n list.join(' ')) if verbose\n return if noop\n uid = fu_get_uid(user)\n gid = fu_get_gid(group)\n list.each do |path|\n Entry_.new(path).chown uid, gid\n end\n end",
"def check_dir_owner(options,dir_name,uid)\n if dir_name.match(/^\\/$/) or dir_name == \"\"\n handle_output(options,\"Warning:\\tDirectory name not set\")\n quit(options)\n end\n test_uid = File.stat(dir_name).uid\n if test_uid.to_i != uid.to_i\n message = \"Information:\\tChanging ownership of \"+dir_name+\" to \"+uid.to_s\n if dir_name.to_s.match(/^\\/etc/)\n command = \"sudo chown -R #{uid.to_s} \\\"#{dir_name}\\\"\"\n else\n command = \"chown -R #{uid.to_s} \\\"#{dir_name}\\\"\"\n end\n execute_command(options,message,command)\n message = \"Information:\\tChanging permissions of \"+dir_name+\" to \"+uid.to_s\n if dir_name.to_s.match(/^\\/etc/)\n command = \"sudo chmod -R u+w \\\"#{dir_name}\\\"\"\n else\n command = \"chmod -R u+w \\\"#{dir_name}\\\"\"\n end\n execute_command(options,message,command)\n end\n return\nend",
"def oo_chown_R(user, group, list, options = {})\n user = pu_get_uid(user)\n group = pu_get_gid(group)\n\n FileUtils.chown_R(user, group, list, options)\n end",
"def set_owner(new_owner)\n @owner = new_owner\n end",
"def set_owner(owner_sid, path)\n sd = get_security_descriptor(path)\n\n if owner_sid != sd.owner\n sd.owner = owner_sid\n set_security_descriptor(path, sd)\n end\n end"
] | {
"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)),
load_item(dir: current_dir, name: '..', stat: File.stat(File.dirname(current_dir)))]
zf = Zip::File.new current_dir
zf.each {|entry|
next if entry.name_is_directory?
stat = zf.file.stat entry.name
@items << load_item(dir: current_dir, name: entry.name, stat: stat)
}
end
end | [
"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 end",
"def fetch\n clean_load_dir\n pull_from_remote_buckets(@remote_buckets)\n pull_from_local_dirs(@local_dirs)\n load_dir_json_files\n end",
"def fetch_files_from host\n\t\tfetcher = host[:fetcher]\n\t\tswitches = host[:switches]\n\t\tbase_path = host[:base_path]\n\t\tlist_files = {}\n\t\tfetcher.connect do\n\t\tswitches.each do |s|\n\t\t\tpath = base_path + \"/\" + s.to_s + \"/\"\n\t\t\tlist_files[s] = fetcher.list_files_from path\n\t\tend\n\t\tend\n\t\tlist_files\n\tend",
"def get_current_files\n get_files(OcflTools::Utils.version_string_to_int(@head))\n end",
"def retrive_files_from_git_index!\n self.files = Git.new(self.base_path).ls_files\n end",
"def download_files(cmd, files)\n return if files.nil? or files.empty?\n\n local_path = cmd.bundle_dir\n digest = cmd.load_digest\n files.each do |f|\n\n fetch = true\n if not digest then\n fetch = true\n elsif df = digest[\"files\"].find{ |h| h[\"file\"] == f[\"file\"] } then\n # compare digest w/ stored one if we have it\n fetch = (df[\"digest\"] != f[\"digest\"])\n else\n fetch = true\n end\n\n if not fetch then\n logger.debug { \"skipping: #{f}\" }\n next\n end\n\n logger.debug { \"fetching: #{f}\"}\n\n filename = File.join(local_path, f['file'])\n path = File.dirname(filename)\n if not File.exist? path then\n FileUtils.mkdir_p(path)\n end\n\n Bixby::Repository.fetch_file(cmd, f['file'], filename)\n if f['file'] =~ /^bin/ then\n # correct permissions for executables\n FileUtils.chmod(0755, filename)\n end\n end # files.each\n end",
"def list_files\n remote_files\n end",
"def retrieve_files\r\n if RUBY_PLATFORM =~ /win32|win64/i then\r\n $help_file = File.read('C:\\files\\BJHelp.txt')\r\n $welcome_file = File.read('C:\\files\\BJWelcome.txt')\r\n $credits_file = File.read('C:\\files\\BJCredits.txt')\r\n else\r\n $help_file = File.read('files/BJHelp.txt')\r\n $welcome_file = File.read('files/BJWelcome.txt')\r\n $credits_file = File.read('files/BJCredits.txt')\r\n end\r\n end",
"def files(*args)\r\n LocalDirectory.current.files(*args)\r\n end",
"def monolithic_files\n get_files_in_dir(@monolithic_dir)\n end",
"def grab_the_zips()\n\n url = \"http://feed.omgili.com/5Rh5AMTrc4Pv/mainstream/posts/\"\n Dir.mkdir(\"files/\") unless File.exists?(\"files/\")\n http = Curl.get(url)\n zip_strings = http.body_str.scan(/([0-9]+.zip)+/)\n formatted_strings = zip_strings.flatten.map {|item| \"#{url}#{item}\"}\n download_the_zips(formatted_strings, zip_strings)\nend",
"def download_response_files!\n files_downloaded = []\n File.makedirs(cache_location + '/returns')\n with_ftp do |ftp|\n files = ftp.list('*.csv')\n files.each do |filels|\n size, file = filels.split(/ +/)[4], filels.split(/ +/)[8..-1].join(' ')\n ftp.get(file, cache_location + '/returns/' + user_suffix + '_' + file)\n files_downloaded << file\n end\n end\n files_downloaded\n end",
"def list_files\n [].tap do |files|\n remote_files do |file|\n files << file\n end\n end\n end",
"def fetch\n logger.debug \"Fetching #{fetch_path}\"\n @fetched_path = Downlow.get(fetch_path, tmp_path, :tmp_dir => tmp_root)\n logger.debug \"Fetched #{@fetched_path}\"\n @fetched_path\n end",
"def files\n results\n rescue ApiStruct::EntityError\n result\n end",
"def retrieve_github_files(url)\n\n #create a virtual browser with a Chrome Windows Agent\n agent = Mechanize.new\n agent.user_agent = CHROME_USER_AGENT\n\n #retrieve the page and report if page not found (404)\n begin\n page = agent.get(url)\n rescue Exception => e\n #REPORT THE ERROR\n end\n\n #recursively download all content\n get_files_from_github_page(page)\n\n end",
"def download\n download_file\n unzip\n downloaded_file_paths\n end",
"def fetch_files(name)\n @files = Dir.glob(\"./workspace/*#{name}*.txt\")\n .select { |v| /\\d+-\\d+-\\d+_[[:alpha:]]+\\.txt$/.match v }\n\n throw RuntimeError if @files.empty?\n @files\n end"
] | {
"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 item, current_dir.join(name) if item.name != name
end
else
Zip::File.open(current_zip) do |zip|
selected_items.each do |item|
name = item.name.gsub from, to
zip.rename item.name, name
end
end
end
ls
end | [
"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, 'w') do |outfile|\n infile.each do |line|\n outfile.write(line.sub(pattern, replacement, &b))\n end\n end\n end\n File.rename(tmp_path, path)\nend",
"def replace_path(path, name=nil)\n name ||= File.basename path\n self.replace_pattern path, name\n end",
"def find2replace (old_word,new_word)\n Dir.glob(\"*.txt\").each do |file|\n old_filename = File.basename(file)\n if old_filename.include?(old_word)\n new_filename = File.basename(file).gsub(old_word,new_word)\n File.rename(file, new_filename)\n puts \"Renamed #{file} to #{new_filename}\"\n end\n end\nend",
"def pattern=(pattern)\n @pattern = pattern\n substitute_variables! # TODO: Remove this call\n end",
"def setPattern=(pattern)\n @pattern = pattern\n end",
"def do_renames\n @content.scan(/\\s*%rename\\s*\\(\\s*\"?([\\w=]+)\"?\\s*\\)\\s*(\\w+)\\s*\\(?([\\w,\\*\\s]+)?\\s*\\)?;/) do\n |new_name, old_name, args|\n @renames[old_name] = [new_name, args]\n end\n end",
"def add_file_pattern(name, pattern_string)\n if name.to_s !~ FILE_PATTERN_NAME_REGEX\n raise ArgumentError.new(\"A file pattern name must match this regex: #{ FILE_PATTERN_NAME_REGEX.inspect }\")\n end\n @file_patterns[name.to_sym] = pattern_string.to_s\n end",
"def regex_replace(find_str, replace_str, dry_run, replace_mode, files_folders)\n raise ArgumentError, 'Parameter find_str must be provided.' if find_str.nil?\n raise ArgumentError, 'No files or folders provided for renaming.' unless files_folders.has_data?\n unless files_folders.any? { |path| File.exist?(path) }\n raise ArgumentError, 'Neither of provided files or folders exists.'\n end\n\n find_str = Regexp.new(find_str.sub(%r{^/}, '').sub(%r{/$}, ''))\n paths = get_paths(replace_mode, files_folders)\n\n puts \"Find pattern `#{find_str.source}` in names and replace it with `#{replace_str}`.\"\n rename_files(paths, dry_run) do |curr_path, _|\n curr_name = curr_path.basename.to_s\n curr_name.gsub(find_str, replace_str)\n end\n end",
"def gsub(pat, rep)\n inject(FileList.new) { |res, fn| res << fn.gsub(pat,rep) }\n end",
"def glob_match (filenames, pattern)\n\t# Escape the '*', '?', and '.' characters\n\tpattern.gsub!(/[\\*\\?\\.]/, '*' => '.*', '?' => '.', '.' => '\\.') \t\n\tregex = Regexp.new(pattern)\n\t#select returns a new array\n\tfilenames.select do |filename|\n\t\tfilename =~ regex\n\tend\nend",
"def naming_pattern=(v)\n segment_naming.pattern = v\n end",
"def sub(pattern, replacement)\n if pattern.is_a?(::Symbol)\n # BUG\n # Shouldn't replace :gdb in 'gdb-as', but it does\n pattern = /^#{pattern.to_s}\\b/\n end\n @subs << [pattern, replacement]\n end",
"def glob_match(string, pattern)\n File.fnmatch(pattern, string, File::FNM_PATHNAME)\n end",
"def rename_files(format:)\n require 'pp'\n child_items.each_with_index do |child, index|\n new_name = sprintf(format, index+1)\n extname = child.path.extname\n dirname = child.path.dirname.to_s\n new_filename = dirname + \"/\" + new_name + extname\n FileManager.rename(from_file: child.path.to_s, to_file: new_filename)\n end\n end",
"def moveFiles(source=nil, destination=nil, regexPattern=nil)\n acceptedInput = ['y', 'yes', 'n', 'no']\n src, dst, rgx = source, destination, regexPattern\n input = \"\"\n\n begin\n #Ask for the path of folder A and B from the user\n while (!acceptedInput.include?(input))\n puts \"Are the files in the same directory as this program? (y/n)\"\n input = gets.chomp.downcase\n end\n\n if (input=='y' || input=='yes')\n src = Dir.pwd\n puts \"Files will be moved from: #{src}\"\n elsif (input=='n' || input=='no')\n while (input!='y' && input!='yes' && src==nil) #src received from function or stdin\n puts \"Please specify the complete path of the folder containing the files to be moved (the path will appear\nwhen the folder is dragged into the Terminal app): \"\n src = gets.chomp\n puts \"Is this path correct? (y/n)\"\n puts src\n input = gets.chomp.downcase\n end\n end\n\n begin\n if (dst != nil) then break end #dst received from function or stdin\n puts \"Please specify the path of the destination folder, which the files will be moved to: \"\n dst = gets.chomp\n puts \"Is this path correct? (y/n)\"\n puts dst\n input = gets.chomp.downcase\n end while (input!='y' && input!='yes')\n end\n\n rgx = getRegexOptions()\n\n Dir.glob(src + \"/*\").each do |f| #Select and sort all files in the source folder\n filename = File.basename(f) #Gets each filename, including the file extension\n if (rgx==nil)\n FileUtils.mv(f, dst + \"/\" + filename)\n else\n if (filename =~ rgx) #If the filename matches the regex pattern\n FileUtils.mv(f, dst + \"/\" + filename)\n end\n end\n end\n end",
"def rewrite pattern, newpath\n on_request do |request, vhost|\n request.path = request.path.gsub(pattern, newpath)\n end\n end",
"def test_files_pattern=(pattern)\n warn 'test_files_pattern= is deprecated in QUnited rake task config, use test_files= with a pattern'\n @test_files = pattern\n end"
] | {
"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(path, timestamp)\n File.utime(timestamp, timestamp, path)\n record_access_timestamp(path, timestamp)\n record_changed_timestamp(path, timestamp)\n end",
"def update(timestamp, text, keep_stamp = false)\n raise EmptyTextError if text.empty?\n raise MissingTimestampError, timestamp unless exist?(timestamp)\n\n # does nothing if given text is the same in the repository one\n return timestamp if read(timestamp) == text\n\n stamp = keep_stamp ? timestamp : Timestamp.new(Time.now)\n write_text(abspath(stamp), text)\n FileUtils.remove_file(abspath(timestamp)) unless keep_stamp\n\n stamp\n end",
"def timestamp=(timestamp)\n raise(\"Error: User: Null timestamp in token.\") unless timestamp\n timestamp = timestamp.to_i\n raise(\"Error: User: Invalid timestamp: #{timestamp}\") if (timestamp <= 0)\n @timestamp = Time.at timestamp\n end",
"def record_access_timestamp(path, timestamp)\n # Hook method: Already stored with File.utime\n end",
"def update_timestamp(records, timestamp)\n records.each { |e| e.updated_at = timestamp }\n end",
"def change_file_cmdts(a_string, a_datetime)\n tt = Time.parse a_datetime.to_s\n File.utime(tt,tt,a_string)\nend",
"def timestamp=(ts)\n @timestamp = ts.to_i\n end",
"def update( timestamp )\n @timestamp = timestamp\n @count += 1\n end",
"def record_creation_timestamp(path, timestamp)\n # Hook method: Linux filesystems doesn't store creation datetime\n end",
"def set(timestamp)\n super(timestamp.utc.iso8601)\n end",
"def set_timestamp(filename)\n File.open(filename.to_s, \"w\") do |file|\n file << Time.now.strftime(\"%Y/%m/%d %H:%M:%S\") << \"\\n\"\n end\n end",
"def modify_timestamp(entry)\n # first modify the creation datetime\n modify_creation_timestamp(entry)\n # after modify the modification datetime\n modify_modification_timestamp(entry)\n end",
"def create(timestamp, text)\n abs = abspath(timestamp)\n raise DuplicateTimestampError, timestamp if FileTest.exist?(abs)\n raise EmptyTextError if text.nil? || text.empty?\n\n write_text(abs, text)\n timestamp\n end",
"def set_Timestamp(value)\n set_input(\"Timestamp\", value)\n end",
"def set_date\n return if self.filename.nil? || self.date\n match = self.filename.match(TIMESTAMP_MATCH)\n date = match[1]\n time = match[2]\n # convert the timestamp in the filname to a Ruby Time object\n self.date = Time.parse(date + ' ' + time)\n end",
"def timestamp_files\n all_files.each {|path| set_file_timestamp_hash(path, file_timestamp(path)) } if @watch_all_modifications\n end"
] | {
"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, name: "#{item.basename}_#{i}#{item.extname}", stat: item.stat
break unless File.exist? new_item.path
end
FileUtils.cp_r item, new_item
else
FileUtils.cp_r item, current_dir
end
end
end
ls
end
end | [
"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",
"def skeleton\n puts \"Copying skeleton ...\"\n system(\"cp -Rf skeleton/* #{@dir}/\")\n end",
"def dropback\n #the abowl has Classes, and the app has classes\n #get all abowl classes and copy them over if they do not exist in the app_path\n #do the same for views...\n\n # handle artwork if any\n files = Dir[\"#{abowl_path}/Artwork/*\"]\n if files&&files.size>0\n #remove original artwork\n FileUtils.rm_rf \"#{app_path}/Artwork\"\n #copy this bowls artworks\n FileUtils.cp_r \"#{abowl_path}/Artwork\", \"#{app_path}/\"\n end\n\n # handle transends if any\n files = Dir[\"#{abowl_path}/Transends/*\"]\n if files&&files.size>0\n #remove original transends\n FileUtils.rm_rf \"#{app_path}/Transends\"\n #copy this bowls transends\n FileUtils.cp_r \"#{abowl_path}/Transends\", \"#{app_path}/\"\n end\n\n #copy from abowl.classes to app.classes if abowl.classes.file not in app.classes\n `cp -rn '#{abowl_path}/Classes' '#{app_path}/';cp -rn '#{abowl_path}/Views' '#{app_path}/'`\n\n end",
"def copy_skel_files(exclude = [])\n full_path = File.join(File.dirname(__FILE__), @skel)\n excluded = exclude.map {|x| \"#{full_path}/#{x}\" }\n Dir.glob(\"#{full_path}/**/*\").select {|x| File.directory?(x)}.each do |f|\n relative_path = f.gsub(/#{full_path}\\//, '')\n FileUtils.mkdir_p relative_path\n end\n (\n Dir.glob(\"#{full_path}/**/*\") + Dir.glob(\"#{full_path}/**/.*\") - excluded\n )\n .select {|x| File.file?(x)}.each do |f|\n next if f =~ /\\.gitkeep/\n relative_path = f.gsub(/#{full_path}\\//, '')\n FileUtils.cp f, relative_path\n end\n end",
"def copy_source_files_to_scratch\n source_directories.each do |dir|\n Origen.file_handler.resolve_files(dir) do |file|\n subdir = file.relative_path_from(Pathname.new(dir)).dirname.to_s\n cpydir = \"#{ungenerated_dir}/#{subdir}\"\n FileUtils.mkdir_p(cpydir) unless File.exist?(cpydir)\n FileUtils.copy(file, cpydir)\n end\n end\n end",
"def populate_source_directory_with_hidden_files\n _define_basic_files_and_directories\n @hidden_dirs = [\".dir3\"]\n @hidden_dirs.each {|dir| @dirs.push(dir)}\n @hidden_files = ['.file4', \"#{@dirs[1]}/.file5\", \"#{@dirs[3]}/file6\"]\n @hidden_files.each {|file| @files.push(file)}\n _create_directories_and_files\n end",
"def copy_content\n @tocopy.each do |pair|\n src = pair[0]\n dst = File.expand_path(File.join(@temp_path, pair[1] || ''))\n dstdir = File.dirname(dst)\n FileUtils.mkpath(dstdir) unless File.exist?(dstdir)\n FileUtils.cp_r(src, dst)\n end\n\n # clear out the list of things to copy so that snippets can\n # re-load it and call copy_content again if needed\n @tocopy = []\n end",
"def concat(dir_dest)\n\tDir.chdir(dir_dest)\n\tdvs_all = File.open(\"DVS_ALL.txt\", \"a\")\n\tDir.glob(\"*.{pre,PRE}*\").each do |f|\n\t\tdvs_files = File.open(f,'r')\n\t\tdvs_files.each_line{|line| dvs_all.puts line}\n\tend\n\tDir.glob(\"*.{tab,TAB}*\").each do |f|\n\t\tdvs_files = File.open(f,'r')\n\t\tdvs_files.each_line{|line| dvs_all.puts line}\n\tend\n\tdvs_all.close\nend",
"def copy_skeleton(options)\n skeleton_path = File.dirname(__FILE__) + '/generate/'\n provider = File.read(skeleton_path + 'provider.rb').gsub('yoursystem', options[:provider].downcase)\n create_file(options, options[:provider_dir] + '.rb', provider)\n skeleton_path << 'provider/'\n provider = File.read(skeleton_path + 'provider.rb').gsub('Yoursystem', options[:provider].capitalize).gsub('yoursystem', options[:provider].downcase)\n create_file(options, 'provider/' + options[:provider].downcase + '.rb', provider)\n %w(project.rb ticket.rb comment.rb).each do |p|\n provider = File.read(skeleton_path + p).gsub('Yoursystem', options[:provider].capitalize).gsub('yoursystem', options[:provider].downcase)\n create_file(options, 'provider/' + p, provider)\n end\nend",
"def insert_all(dir)\n insert_all_helper(dir, \"\")\n end",
"def copy_files_to_current_path()\n require 'fileutils'\n @files.each do |f|\n FileUtils::cp(f,'./')\n end\n end",
"def copyAuxFiles\r\n\t\tDir.chdir(@curDir)\r\n\t\tFile.copy(@dtreeJSFile, @destDir)\r\n\t\tFile.copy(@dtreeCSSFile, @destDir)\r\n\r\n\t\t@destDirImg = File.expand_path(@destDirImg)\r\n\t\tDir.chdir(@dtreeImgDir)\r\n\t\tDir.foreach('.'){|f|\r\n\t\t\tFile.copy(f, @destDirImg) unless (f==\".\" || f==\"..\")\r\n\t\t}\r\n\tend",
"def rearrange\n rootpath = \"#{$paths.restore_path}/Student_Records_D20130520/Student_Records\"\n Dir.entries(rootpath).each{|entry|\n if !entry.gsub(/\\.|rb/,\"\").empty?\n Dir.chdir(\"#{rootpath}/#{entry}/SY_2012-2013\")\n if !File.directory?(\"#{rootpath}/#{entry}/SY_2012-2013/Withdrawal\")\n Dir.mkdir(\"#{rootpath}/#{entry}/SY_2012-2013/Withdrawal\")\n end\n Dir.glob('WD_**') do |file|\n #puts File.expand_path(file)\n oldpath = File.expand_path(file)\n FileUtils.mv(\"#{oldpath}\",\"#{rootpath}/#{entry}/SY_2012-2013/Withdrawal\")\n end\n end\n }\n end",
"def pack_otherfiles\n basedir='/home/seb/mp3cache'\n outdir=File.join(basedir,self.outdir_name)\n # puts \"scrivo in: #{outdir}\"\n Dir.mkdir(outdir) if !File.exists?(outdir)\n topdir=self.top_directory\n return nil if topdir.nil?\n\n # Creazione delle dir necessarie a contenere i files:\n self.directories.each do |dir|\n puts \"nel loop: #{dir}\"\n destdir=File.join(outdir,dir)\n puts \"creazione dir #{destdir}\"\n Dir.mkdir(destdir) if !File.exists?(destdir)\n end\n puts outdir\n okfiles=['image/jpeg','text/plain']\n self.files.each do |f|\n next if !okfiles.include?(f.mime_type)\n target_filename=File.join(outdir,f.filepath)\n puts \"#{f.mime_type}: #{target_filename}\"\n if !File.exists?(target_filename)\n puts \"file copy: #{f.fname}\"\n File.copy(f.fname,target_filename)\n end\n end\n outdir\n end",
"def copy_other_files\n Dir.glob(\"./source/**/*\").each do |path|\n extensions_to_ignore = [\"slim\", \"coffee\", \"css\", \"js\", \"sass\"]\n next if extensions_to_ignore.any? { |ext| path.split(\".\")[-1].eql?(ext) }\n dest_path = path.gsub(\"source/\", \"dist/\")\n dest_folder = dest_path.split(\"/\")[0..-2].join(\"/\")\n `mkdir -p #{dest_folder}`\n `cp \"#{path}\" \"#{dest_path}\"`\n end\n end",
"def paste\n check_tmux\n\n # There will always be exactly one stray newline, so remove it\n File.read(\"#{ ENV['HOME'] }/.tripboard-buffer.txt\")[0..-2]\n end",
"def copy_tftpboot_files\n Dir.glob(@tftpboot_src_path) do |dir|\n info(\"Copying tftpboot PXE image files from '#{dir}' into #{@type} env\".cyan)\n os_info = dir.split('/')[-5..-3]\n dst_dirname = os_info.map(&:downcase).join('-')\n dst_path = File.join(@tftpboot_dest_path, dst_dirname)\n copy_skeleton_files(dir, dst_path, 'nobody')\n # change perms to world readable or tftp fails\n Dir.chdir(dst_path) do\n FileUtils.chmod(0644, Dir.entries(dst_path) - %w[. ..])\n end\n\n\n # create major OS version link\n os_info[1] = os_info[1].split('.').first\n Dir.chdir(@tftpboot_dest_path) do\n FileUtils.ln_s(dst_dirname, os_info.map(&:downcase).join('-'))\n end\n end\n end",
"def copy_data_dir_here\n copy_all from: content, to: current_dir\nend",
"def enhance_file_list\n return unless $enhanced_mode\n # if only one entry and its a dir\n # get its children and maybe the recent mod files a few\n \n # zsh gives errors which stick on stdscr and don't get off!\n # Rather than using N I'll try to convert to ruby, but then we lose\n # similarity to cetus and its tough to redo all the sorting stuff.\n if $files.size == 1\n # its a dir, let give the next level at least\n if $files.first[-1] == \"/\"\n d = $files.first\n #f = `zsh -c 'print -rl -- #{d}*(omM)'`.split(\"\\n\")\n f = get_file_list d\n if f && f.size > 0\n $files.concat f\n $files.concat get_important_files(d)\n return\n end\n else\n # just a file, not dirs here\n return\n end\n end\n # \n # check if a ruby project dir, although it could be a backup file too,\n # if so , expand lib and maby bin, put a couple recent files\n #\n if $files.index(\"Gemfile\") || $files.grep(/\\.gemspec/).size > 0\n # usually the lib dir has only one file and one dir\n flg = false\n $files.concat get_important_files(Dir.pwd)\n if $files.index(\"lib/\")\n f = `zsh -c 'print -rl -- lib/*(om[1,5]MN)'`.split(\"\\n\")\n if f && f.size() > 0\n insert_into_list(\"lib/\", f)\n flg = true\n end\n dd = File.basename(Dir.pwd)\n if f.index(\"lib/#{dd}/\")\n f = `zsh -c 'print -rl -- lib/#{dd}/*(om[1,5]MN)'`.split(\"\\n\")\n if f && f.size() > 0\n insert_into_list(\"lib/#{dd}/\", f)\n flg = true\n end\n end\n end\n if $files.index(\"bin/\")\n f = `zsh -c 'print -rl -- bin/*(om[1,5]MN)'`.split(\"\\n\")\n insert_into_list(\"bin/\", f) if f && f.size() > 0\n flg = true\n end\n return if flg\n\n # lib has a dir in it with the gem name\n\n end\n return if $files.size > 15\n\n ## first check accessed else modified will change accessed\n moda = `zsh -c 'print -rn -- *(/oa[1]MN)'`\n if moda && moda != \"\"\n modf = `zsh -c 'print -rn -- #{moda}*(oa[1]MN)'`\n if modf && modf != \"\"\n insert_into_list moda, modf\n end\n modm = `zsh -c 'print -rn -- #{moda}*(om[1]MN)'`\n if modm && modm != \"\" && modm != modf\n insert_into_list moda, modm\n end\n end\n ## get last modified dir\n modm = `zsh -c 'print -rn -- *(/om[1]MN)'`\n if modm != moda\n modmf = `zsh -c 'print -rn -- #{modm}*(oa[1]MN)'`\n insert_into_list modm, modmf\n modmf1 = `zsh -c 'print -rn -- #{modm}*(om[1]MN)'`\n insert_into_list(modm, modmf1) if modmf1 != modmf\n else\n # if both are same then our options get reduced so we need to get something more\n # If you access the latest mod dir, then come back you get only one, since mod and accessed\n # are the same dir, so we need to find the second modified dir\n end\nend"
] | {
"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(self)\n pipe.close_write\n end\n when /darwin/\n self.public_send('|', 'pbcopy')\n else\n raise 'Unkown platform, cannot copy to clipboard'\n end\n self\n end",
"def pbcopy(text)\n `osascript -e 'set the clipboard to \"#{text}\"'`\n #IO.popen(\"osascript -e 'set the clipboard to do shell script \\\"cat\\\"'\",\"w+\") {|pipe| pipe << text}\nend",
"def filecopy(input)\n\tosascript <<-END\n\t\tdelay #{@moreimage}\n\t\tset the clipboard to POSIX file (\"#{input}\")\n\t\ttell application \"Copied\"\n\t\t\tsave clipboard\n\t\tend tell\n\tEND\nend",
"def do_clipboard_paste\n dat = if Wx::PLATFORM == \"WXMAC\" \n # XXX i feel dirty\n `pbpaste`\n else\n dobj=RawDataObject.new\n Wx::Clipboard.open {|clip| clip.fetch dobj}\n dobj.raw_data\n end\n\n self.gui_set_value(self.cur_pos, dat) if dat and dat.size > 0\n end",
"def copy(string)\n IO.popen('xsel -i --clipboard', 'w') { |f| f << string.to_s.strip }\n string\nend",
"def copyFromClipboard \n \"copyFromClipboard\" \n end",
"def copy(item)\n copy_command = darwin? ? \"pbcopy\" : \"xclip -selection clipboard\"\n\n Kernel.system(\"echo '#{item.value.gsub(\"\\'\",\"\\\\'\")}' | tr -d \\\"\\n\\\" | #{copy_command}\")\n\n \"Boom! We just copied #{item.value} to your clipboard.\"\n end",
"def copy\n str = selection_text\n Clipboard.copy str unless str.empty?\n end",
"def pbcopy(text)\n # work around, ' wrecks havoc on command line, but also caused some weird regexp substitution\n rtf = text.index('{\\rtf1')\n File.open(\"/tmp/script.scpt\", 'w') do |f|\n if rtf\n f << text\n else\n f << \"set the clipboard to \\\"#{text}\\\"\"\n end\n end\n if rtf\n `cat /tmp/script.scpt | pbcopy -Prefer rtf`\n else\n `osascript /tmp/script.scpt`\n end\nend",
"def paste link\n clipboard = %w{\n /usr/bin/pbcopy\n /usr/bin/xclip\n }.find { |path| File.exist? path }\n\n if clipboard\n IO.popen clipboard, 'w' do |io| io.write link end\n end\n end",
"def cop\n last_value = IRB.CurrentContext.last_value\n %x[echo '#{last_value}' | pbcopy]\n \"copied \\`#{last_value}' to your clipboard\"\nend",
"def copy(text)\n\t\t@clip.copy(text)\n\t\tglobalDisplay(\"/copy \" + text) if(text != nil)\t\n\tend",
"def on_menu_copy(evt)\n @editor.do_clipboard_copy()\n end",
"def paste_clipboard\n return nil if @clipboard.empty?\n select_list = []\n pos = @column.currentItem\n pos = @column.numItems if pos < 0\n @clipboard.each do |pkt_text|\n if pos == @column.numItems\n @column.appendItem(pkt_text)\n else\n @column.insertItem(pos, FXListItem.new(pkt_text))\n end\n select_list << pos\n pos += 1\n end\n\n # Now go back and highlight all the new items\n set_selected(select_list)\n end",
"def cp(string)\n `echo \"#{string}\" | pbcopy`\n puts \"copied in clipboard\"\nend",
"def pbpaste\n a = IO.popen(\"osascript -e 'the clipboard as unicode text' | tr '\\r' '\\n'\", 'r+').read\n a.strip.force_encoding(\"UTF-8\")\nend",
"def cp(string)\n `echo \"#{string} | pbcopy`\n puts 'copied to clipboard'\nend",
"def clicked\n\npath=`osascript <<END\n tell application \"Finder\"\n \tset theSelection to the selection\n \ttry\n \t\tset theSelection to theSelection as string\n \t\tset finder_path to POSIX path of theSelection\n \ton error\n \t\tset finder_path to null\n \tend try\n end tell\n if finder_path is not null then return finder_path\nEND`\n\n if (path == nil or path == \"\")\n $dz.finish(\"Nothing selected\")\n $dz.url(false)\n else \n $dz.finish(\"Path copied\")\n $dz.url(path)\n end\n \nend"
] | {
"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|
FileUtils.mkdir_p File.join(item.basename, File.dirname(entry.to_s))
zip.extract(entry, File.join(item.basename, entry.to_s)) { true }
end
end
end
gzs.each do |item|
Zlib::GzipReader.open(item) do |gz|
Gem::Package::TarReader.new(gz) do |tar|
dest_dir = current_dir.join (gz.orig_name || item.basename).sub(/\.tar$/, '')
tar.each do |entry|
dest = nil
if entry.full_name == '././@LongLink'
dest = File.join dest_dir, entry.read.strip
next
end
dest ||= File.join dest_dir, entry.full_name
if entry.directory?
FileUtils.mkdir_p dest, mode: entry.header.mode
elsif entry.file?
FileUtils.mkdir_p dest_dir
File.open(dest, 'wb') {|f| f.print entry.read}
FileUtils.chmod entry.header.mode, dest
elsif entry.header.typeflag == '2' # symlink
File.symlink entry.header.linkname, dest
end
unless Dir.exist? dest_dir
FileUtils.mkdir_p dest_dir
File.open(File.join(dest_dir, gz.orig_name || item.basename), 'wb') {|f| f.print gz.read}
end
end
end
end
end
else
Zip::File.open(current_zip) do |zip|
zip.select {|e| selected_items.map(&:name).include? e.to_s}.each do |entry|
FileUtils.mkdir_p File.join(current_zip.dir, current_zip.basename, File.dirname(entry.to_s))
zip.extract(entry, File.join(current_zip.dir, current_zip.basename, entry.to_s)) { true }
end
end
end
ls
end | [
"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",
"def unzip\n cmd = \"unzip #{zip_folder} -d #{unzipped_target_folder}\"\n system cmd\n end",
"def extract\n # If no paths specified, then no include/exclude patterns\n # specified. Nothing will happen unless we include all files.\n if @paths.empty?\n @paths[nil] = FromPath.new(self, nil)\n end\n\n # Otherwise, empty unzip creates target as a file when touching.\n mkpath target.to_s\n if zip_file.to_s.match /\\.t?gz$/\n #un-tar.gz\n Zlib::GzipReader.open(zip_file.to_s) { |tar|\n Archive::Tar::Minitar::Input.open(tar) do |inp|\n inp.each do |tar_entry|\n @paths.each do |path, patterns|\n patterns.map([tar_entry]).each do |dest, entry|\n next if entry.directory?\n dest = File.expand_path(dest, target.to_s)\n trace \"Extracting #{dest}\"\n mkpath File.dirname(dest) rescue nil\n File.open(dest, 'wb', entry.mode) {|f| f.write entry.read}\n File.chmod(entry.mode, dest)\n end\n end\n end\n end\n }\n else\n Zip::File.open(zip_file.to_s) do |zip|\n entries = zip.collect\n @paths.each do |path, patterns|\n patterns.map(entries).each do |dest, entry|\n next if entry.directory?\n dest = File.expand_path(dest, target.to_s)\n trace \"Extracting #{dest}\"\n mkpath File.dirname(dest) rescue nil\n entry.restore_permissions = true\n entry.extract(dest) { true }\n end\n end\n end\n end\n # Let other tasks know we updated the target directory.\n touch target.to_s\n end",
"def unpack\n self.dir = Rails.root + 'tmp' + SecureRandom.hex(20)\n FileUtils.mkdir(dir)\n\n dirs = []\n files = []\n\n Zip::Archive.open(file_path) do |archive|\n archive.each do |file|\n next if file.name =~ /__MACOSX/ or file.name =~ /\\.DS_Store/\n destination = dir + file.name\n name = Pathname.new(file.name).cleanpath.to_s\n\n if file.directory?\n FileUtils.mkdir_p(destination)\n dirs << name\n else\n dirname = File.dirname(file.name)\n FileUtils.mkdir_p(dirname) unless File.exist?(dirname)\n open(destination, 'wb') {|f| f << file.read}\n files << name\n end\n end\n end\n\n [dirs, files]\n end",
"def extract_archive(*files)\n cmd = \"#{@tar_program} xf #{@archive_name}\"\n cmd = \"#{cmd} #{files.join(' ')}\" unless files.empty?\n\n Open3.popen3(cmd) do |_ain, _aout, aerr|\n err = aerr.gets\n raise Error, err.chomp if err\n end\n\n self\n end",
"def extract_files_into(dir)\n @installer.unpack(dir)\n end",
"def unzip( zipfile, targetdir, *files )\n require 'zip/zip'\n require 'pathname'\n targetdir = Pathname( targetdir )\n raise \"No such directory: #{targetdir}\" unless targetdir.directory?\n\n Zip::ZipFile.foreach( zipfile ) do |entry|\n $stderr.puts \" entry is: %p, looking for: %p\" % [ entry.name, files ]\n next unless files.empty? || files.include?( entry.name )\n target_path = targetdir + entry.name\n $stderr.puts \" extracting: %s\" % [ target_path ]\n entry.extract( target_path ) { true }\n files.delete( entry.name )\n break if files.empty?\n end\n\n raise \"Couldn't unzip: %p: not found in %s\" % [ files, zipfile ] unless files.empty?\nend",
"def unzip\n return unless file.path.end_with? '.zip'\n\n `unzip -qq -o #{file.path} -d #{File.dirname(file.path)}`\n end",
"def unzip_folder\n all_files = Array.new\n Dir.entries(\"#{Rails.root}/public/temp/unzip_082916120916/IDV/ziploan2/documents\").each do |f| \n all_files << f \n end\n abort(\"#{all_files.inspect}\")\n\n\n FileUtils.rm_rf(\"#{Rails.root}/public/temp/unzip_filesd\")\n abort(\"gss\")\n require 'zip'\n\n ############################ Read Directory Code #############################\n\n $dir_target = \"#{Rails.root}/public/temp/unzip_filesd/IDV\"\n dirList = Array.new\n Dir.entries(\"#{$dir_target}\").each do |f| \n \n dirList << f\n # if File.directory?(f)\n # puts \"#{f}\\n\"\n # end\n end\n abort(\"#{dirList.inspect}\")\n\n ############################ End Read Directory Code #########################\n\n\n\n\n file_name = \"#{Rails.root}/public/temp/IDV.zip\"\n all_files = Array.new\n Zip::File.open(\"#{file_name}\") do |zipfile|\n zipfile.each do |zfile|\n all_files << zfile.inspect\n end\n end\n \n abort(\"#{all_files.inspect}\")\n end",
"def unzip_files\n # Checks if file is really a zip file\n if on_windows?\n Rails.logger.info(\"[file] Unzipping is not compatible with windows\")\n return false\n end\n \n return false unless self.mime_type.match(\"zip\")\n file = self.data.path\n # Then proceed if it's a zip file\n require 'zip/zip'\n destination = Dir.tmpdir\n extracted_files = []\n Zip::ZipFile.open(file) { |zip_file|\n zip_file.each { |f|\n if f.file? && !f.name.downcase.match(/(\\.ds_store|thumbs\\.db)/)\n logger.info(\"[file] Processing #{f.name} from ZIP file\")\n f_path=File.join(destination, f.name)\n FileUtils.mkdir_p(File.dirname(f_path))\n zip_file.extract(f, f_path) unless File.exist?(f_path)\n extracted_files << f_path\n else\n logger.info(\"[file] Skipping #{f.name} from ZIP file\")\n end\n }\n }\n # Array with zip files\n extracted_files\n end",
"def archive( group_name, files )\n make_destination_dir\n archive_path = File.join( @destination, \"archive-#{group_name}.tar.gz\")\n paths = files.map { |file| File.join( @source, file ) }\n\n if File.exists?( archive_path ) then\n update_archive( archive_path, paths )\n else\n create_archive( archive_path, paths )\n end\n\n File.delete( *paths )\n puts \"Removing #{files.size} source files that have been archived.\" if @verbose\n end",
"def unzip_archive(archive, dest)\n # Adapted from examples at...\n # https://github.com/rubyzip/rubyzip\n # http://seenuvasan.wordpress.com/2010/09/21/unzip-files-using-ruby/\n Zip::File.open(archive) do |zf|\n zf.each do |f|\n f_path = File.join(dest, f.name)\n FileUtils.mkdir_p(File.dirname(f_path))\n zf.extract(f, f_path) unless File.exist?(f_path) # No overwrite\n end\n end\nend",
"def unzip_archive(archive, dest)\n # Adapted from examples at...\n # https://github.com/rubyzip/rubyzip\n # http://seenuvasan.wordpress.com/2010/09/21/unzip-files-using-ruby/\n ::Zip::File.open(archive) do |zf|\n zf.each do |f|\n f_path = File.join(dest, f.name)\n ::FileUtils.mkdir_p(File.dirname(f_path))\n zf.extract(f, f_path) unless File.exist?(f_path) # No overwrite\n end\n end\nend",
"def extract(directory = nil)\n require 'rubygems/package'\n directory = parent.dir(basename) unless directory\n read_binary do |io|\n reader = Gem::Package::TarReader.new(io)\n reader.each do |entry|\n full_name = entry.full_name\n if (entry.file?)\n directory.file(full_name).write_binary do |output|\n CottaFile.copy_io(entry, output)\n end\n elsif (entry.directory?)\n directory.dir(full_name).mkdirs\n end\n end\n end\n directory\n end",
"def perform\n log system_messages[:archiving]; log system_messages[:compressing]\n run \"tar -czf #{File.join(tmp_path, compressed_file)} #{exclude_files} #{tar_files}\"\n end",
"def upload_files (files)\n @@container.archive_in files, '.'\n end",
"def update_archive(*files)\n raise Error, 'there must be at least one file specified' if files.empty?\n\n cmd = \"#{@tar_program} uf #{@archive_name} #{files.join(' ')}\"\n\n Open3.popen3(cmd) do |_ain, _aout, aerr|\n err = aerr.gets\n raise Error, err.chomp if err\n end\n\n self\n end",
"def extract\n base.say_status 'extract', @file\n if @zip_file\n base.exec(\"cd #{@temp_dir} ; unzip #{@file}\")\n else\n base.exec(\"cd #{@temp_dir} ; tar xvfpz #{@file}\")\n end\n \n # Remove the file\n base.destination_files.rm_rf(@file_path)\n end",
"def archive_files(source, target)\n create_dir(target)\n Dir.glob(File.join(source, \"**\", \"*.xml\")).each do |file|\n loginfo(\"Archiving #{file} to archive directory...\", 1)\n FileUtils.mv(file, target)\n loginfo(\"Done.\\n\", 1)\n end\nend"
] | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |