anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
Humanize. to_s returns "false". | def to_human
"no"
end |
test_designer_home Description: This method does the functional testing for the designer methods | def test_designer_home
post('index', {}, {})
assert_response(:success)
assert_template('tracker/index')
post('index', {}, bob_designer_session)
assert_response(:success)
assert_template('tracker/designer_home')
end |
cached gem specification path, if one exists | def gemspec_cached_path(spec_file_name)
paths = Bundler.rubygems.spec_cache_dirs.map {|dir| File.join(dir, spec_file_name) }
paths.find {|path| File.file? path }
end |
Bonus 1: What is the purpose of the number % divisor == 0 ? it is the solution to finding the factors of the number that was passed into the method as an argument if number modulo by the divisor is equal to 0, then it is a factor of number is is pushed into the array 'factors' Bonus 2: What is the purpose of the second... | def rolling_buffer1(buffer, max_buffer_size, new_element)
buffer << new_element
buffer.shift if buffer.size > max_buffer_size
buffer
end |
return pointer for use with pack('L') | def str_to_ptr(v)
[v].pack('p*').unpack('L')[0]
end |
Prime number if we have a remainder from divding by 2 if any number is less than or = to 1 its not a prime retrun false Check all numbers inside on int greater than with no 1 remainder if there are any numbers with a remainder = to 0 returns false. Anything else return true. | def prime?(int)
if int <= 1
return false
else
if (2...int).any? {|n| int % n == 0}
return false
else
return true
end
end
binding.pry
end |
DELETE /user_funs/1 DELETE /user_funs/1.json | def destroy
@user_fun = UserFun.find(params[:id])
@user_fun.destroy
respond_to do |format|
format.html { redirect_to user_funs_url }
format.json { head :no_content }
end
end |
def test_allowed_types_are_taken_from_config assert(PaymentOrder::ENABLED_METHODS.include? 'PaymentOrders::EveryPay') end def test_supported_method_returns_true_or_false assert(PaymentOrder.supported_method?(PaymentOrders::EveryPay)) end def test_payment_method_must_be_supported_for_the_object_to_be_valid payment_order... | def test_invoice_cannot_be_already_paid
payment_order = PaymentOrder.new
payment_order.invoices << @payable_invoice
payment_order.user = @user
payment_order.type = 'PaymentOrders::EveryPay'
assert(payment_order.valid?)
@payable_invoice.mark_as_paid_at(Time.zone.now)
assert_not(payment_or... |
Never trust parameters from the scary internet, only allow the white list through. | def mx_assessment_params
# params[:mx_assessment]
params.require(:mx_assessment).permit(:danger_yn, :drugs_last_changed,
:drugs_not_why, :drugs_change_why, :psychsoc_last_changed,
:psychsoc_not_why, :psychsoc_change_why... |
infiniteLoopWarning() This was written early in development incase I knew some logic at some point would cause an infinite loop. I'm keeping this method in here just in case logic is written that could accidentally cause an infinite loop Note to self: make this into a box using TTY | def infiniteLoopWarning(whereAmIFrom)
puts "______________________________________________________________________"
puts "|********************************************************************|"
puts "|********************************************************************|"
puts "|*************************... |
=begin Checking if the response was copied from google =end | def google_search_response(auto_metareview)
review_text_arr = auto_metareview.review_array
# require 'ruby-web-search'
count = 0
temp_array = Array.new
review_text_arr.each{
|rev_text|
if(!rev_text.nil?)
#placing the search text within quotes to search exact match for the complet... |
Fibonacci sequence here is considered to start at the zeroeth element (which is 0) fibo function returns the nth element of the Fibonacci sequence | def fibo(n)
a, b, c = 0, 0, 0
for i in 1..n
c, b = b, a
a = i== 1 ? 1 : b + c
end
return a
end |
Ensure type is present | def validate_presence_of(field_name, type)
type || raise(::ArgumentError, "Type is required for #{field_name}.")
end |
color a string according to current class COLORS hash | def color(string, hash = nil)
hash ||= self.class::COLORS
set_color(string, hash.fetch(string.to_sym, :yellow))
end |
Delete all carts items | def delete_items(account_number, cart_id)
# the base uri for api requests
query_builder = Configuration.base_uri.dup
# prepare query string for API call
query_builder << '/accounts/{account_number}/carts/{cart_id}/items'
# process optional query parameters
query_builder = A... |
To invalidate token upon logout | def invalidate_token
self.update_columns(auth_token: nil)
end |
GET /vehicle_fines GET /vehicle_fines.json | def index
@vehicle_fines = VehicleFine.all
end |
instance method to check if the password from login form is identical to the password saved during sign up | def authenticate(password)
BCrypt::Password.new(self.password_digest) == password
end |
get a dns record object | def get_record(fqdn, type)
matches = find_match(@dnss.records, fqdn, true)
if matches != nil
record = nil
matches.each do |record|
Puppet.debug "inspecting #{record.hash_type} == #{type}"
if record.hash_type.to_s == type.to_s
Puppet.notice "found... |
true if photoset named 'name' exists, false otherwise. | def photoset_exist? name
@flickr.photosets.getList.each do |x|
return true if x.title == name
end
return false
end |
Description Reloads the element if it's in conversion Mode Ajax | def check_conversion
@mes = []
params.keys.each do |key|
if key[0, 2] == 'me'
id = key[2, key.length - 2]
media_element_id = correct_integer?(id) ? id.to_i : 0
media_element = MediaElement.find_by_id media_element_id
ok = (media_element && current_user.id == media_element.u... |
DELETE /pm/nodes/1 DELETE /pm/nodes/1.json | def destroy
@pm_node.destroy
respond_to do |format|
format.html { redirect_to pm_nodes_url, notice: 'Node was successfully destroyed.' }
format.json { head :no_content }
end
end |
Get the identifier of the criteria, used elsewhere within the document for referencing | def id
attr_val('cda:act/cda:id/@root')
end |
GET /electronica_consejeros/1 GET /electronica_consejeros/1.json | def show
end |
Generate the repository dists | def generate_dists(pkg_hash)
pkg_hash.each do |origin_name, dists|
dists.each do |dist_name, dist_args|
dist_args[:components].each do |component_name, arches|
packages = arches.values.flatten.compact.map(&:values).flatten.compact.map(&:values).flatten.compact
p... |
Returns an array of Licensee::License instances | def licenses(options = {})
Licensee::License.all(options)
end |
Parses an RDoc::NormalModule in +container+ with +comment+ | def parse_module container, single, tk, comment
container, name_t, = get_class_or_module container
name = name_t[:text]
mod = container.add_module RDoc::NormalModule, name
mod.ignore unless container.document_children
record_location mod
read_documentation_modifiers mod, RDoc::CLASS_MODIFIERS... |
Preview the index page | def preview_index
preview_path = "#{PDF_PREVIEW_FOLDER}/preview_index-#{current_cookbook.id}_#{Time.now.to_i}.pdf"
session[:preview_filename] = preview_path
preview = CookbookPreviewWorker.new(
cookbook: current_cookbook,
filename: preview_path
)
preview.index
render "previews/previ... |
Set the Twitter user to find | def term=(term)
@term = term
@twitter_search = nil
load_words
end |
Verifies collection types match test data | def verify_collection_types(test_data)
types = test_data[CoreUseOfCollectionsData::COLLECTION_TYPE_LIST.name] || [{CoreUseOfCollectionsData::COLLECTION_TYPE.name => ''}]
types.each_with_index { |type, index| verify_values_match(type[CoreUseOfCollectionsData::COLLECTION_TYPE.name], element_value(collection_type_... |
=begin Script and functions for getting functions for ChemInfo. Given a directory containing JS function definition scripts Get all function definitions and names Place all in a JS script =end Function definitions Get entries in directory by extension regex | def dirExt(dir, ext = /\.js$/)
return(Dir.entries(dir).select{|e| e.match?(ext)})
end |
routines to add: is mysql even installed? is mysql process started? is mysql listening at all on remote node? check the cluster status on a remote node start the mysql service with the given address restart the mysql service cos the cluster is complete | def create
# this routine creates the cluster - if this runs, exists? has exited false
# first we check all the nodes to ensure mysql is listening, and if the
# wsrep_cluster_status is primary. If one is, we'll join it.
# array cluster_servers is the list of hosts to check
first_node = true
... |
on which event will be callback triggered | def event(event) # TODO args for events like keypress
@events << event
self
end |
input = gets.chomp.strip do puts display_board | def valid_move? (board, index)
if index.between?(0, 8) && !position_taken?(board, index)
true
end
end |
Enables or disables the generation of events in the Page domain. | def page_events=(new_page_events)
new_page_events = !!new_page_events
if new_page_events != page_events
@rpc.call(new_page_events ? 'Page.enable' : 'Page.disable')
@page_events = new_page_events
end
new_page_events
end |
DELETE /site/columns/1 DELETE /site/columns/1.json | def destroy
#先删除子节点
if @cms_column.parent_column.nil?
if Cms::Category.find_by_column_id(@cms_column.id)
flash[:error] = "该栏目还有类别,不可以删除"
else
@cms_column.destroy
end
else
flash[:error] = "子栏目不可以单独删除"
end
respond_to do |format|
format.html { ... |
Providing all the instruction to the user before starting the game | def draw
@background_image.bmp.draw(0, 0, ZOrder::BACKGROUND)
@function_UI.place_button((SCREEN_WIDTH/3) + 100, 300, "Start!")
@function_UI.big_font.draw_text("SPACE WAR", @function_UI.pos- 120, 30, ZOrder::TOP, 1.0, 1.0, Gosu::Color::YELLOW)
@function_UI.big_font.draw_text("Instructions: ", @fu... |
def displayNetwork network_controller = NetworkController.new network_controller.profile = profile self.navigationController.pushViewController(network_controller, animated: true) end | def displayWalletActions
manage_wallet_controller = ManageWalletController.new
manage_wallet_controller.profile = profile
self.navigationController.pushViewController(manage_wallet_controller, animated: true)
end |
returns average win percentage of all games for a team | def average_win_percentage(team_id)
team_id = team_id.to_i
team = @teams.select { |each_team| each_team.team_id == team_id }.first
team.total_win_percentage.round(2)
end |
Only allow a trusted parameter "white list" through. | def goal_params
params.require(:goal).permit(:futsal_game_id, :team_id, :goal_id, :own_goal, :assist_id, :goalkeeper_id, :time, :video_link, :picture)
end |
in params complete donation needed (with charity, amount, etc.) | def create
@donation = Donation.new(donation_params)
before_donation_creation @donation
if @donation.save
after_donation_creation @donation
set_after_create_flash_message
redirect_to donation_path(@donation)
else
redirect_to charities_path
end
end |
If the payment was successful, Cybersource will send us back a decision of 'ACCEPT' | def payment_success?
@fields['decision'] == 'ACCEPT'
end |
For all responses in this controller, return the CORS access control headers. | def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Max-Age'] = "1728000"
end |
Only allow a list of trusted parameters through. | def post_params
params.require(:post).permit(:title, :image, :description, :category, :ingredients, :method, :prep, :cook, :difficult)
end |
returns the property definitions for the project. | def property_definitions
set_attributes_for(PropertyDefinition)
PropertyDefinition.find(:all)
end |
takes player name and url params constructs url and uses Nokogiri to open connection with required parameters returns array of form [Games, AB, Runs, Hits, 2B, 3B, HR, RBI, BB, HBP, CS, SH, SF, GDP, BA, OBA, Slug%, OPS] | def scrape
player = params[:player]
url = params[:url]
endDate = params[:EndDate]
filler = '&GameType=all&PlayedFor=0&PlayedVs=0&Park=0&PlayerID='
id = Player.find_by_name(player).number.to_s
fullUrl = url + '&EndDate=' + endDate + filler + id
page = Nokogiri::HTML(open(fullUrl))
totalsAr... |
Array of all letters of the alphablet in uppercase | def alphabet_array
('A'..'Z').to_a
end |
Public: resolves a template file by looking in the template path. template the template name. extension the extension of the desired template. Returns a string with the full path of the template file, or nil if it is not found. | def which(template, extension)
template_with_extension = with_extension(template, extension)
path = absolute_paths.find do |path|
File.exists?(File.join(path, template_with_extension))
end
if path
File.join(path, template_with_extension)
end
end |
Deletes a pipeline on AWS Elastic Transcoder given an id | def delete_pipeline id
begin
@elastictranscoder.delete_pipeline(id: id)
rescue
#Raise informative exception
end
end |
PATCH/PUT /projects/1 PATCH/PUT /projects/1.json | def update
respond_to do |format|
if @project.update(project_params)
format.html { redirect_to @project, notice: 'Project was successfully updated.' }
format.json { render :show, status: :ok, location: @project }
else
format.html { render :edit }
format.json { render json... |
GET /commodities GET /commodities.json | def index
@commodities = Commodity.all
if params[:search].present?
@commodities = @commodities.query(params[:search].to_s)
end
@commodities = @commodities.page(params[:page])
respond_to do |format|
format.html
format.js {}
format.json {
render json: {:commodities =... |
Enlace que se muestra solo si el usuario ha ingresado al sistema | def link_usuario(titulo, enlace)
link_to titulo, enlace if not session[:usuario]
end |
Logs +message+ if verbose | def log(message)
$stderr.puts message if @verbose
ActionMailer::Base.logger.info "ar_sendmail: #{message}"
end |
Challenge IV: Adding Data adding operates on the shipping_manifest hash to add a key/value pair add 2 muskets to the shipping_manifest hash below add 4 gun powder to the shipping_manifest hash below return the shipping_manifest hash below | def adding
shipping_manifest = {"whale bone corsets" => 5, "porcelain vases" => 2, "oil paintings" => 3}
shipping_manifest["muskets"] = 2
shipping_manifest["gun powder"] = 4
shipping_manifest
end |
Notice how it's currently impossible to tell if a key is simply mistyped as a public or private key, or if it's a badly formatted key. Too bad. | def test_bogus_raise
bogus_key = "Oh hey I'm a key. Ok, not really."
assert_raise OpenSSL::PKey::PKeyError do
Net::SSH::Utils::Key.fingerprint(:data => bogus_key)
end
end |
Check exploit vulnerability basically // 'Appears' more convenient | def check
res = inject(Rex::Text.rand_text_alpha(1))
if res.code = "200" && res.headers['set-cookie'] =~ /JSESSIONID/
Exploit::CheckCode::Appears
else
Exploit::CheckCode::Safe
end
end |
Whether or not to disable Solr. Defaults to false. | def disabled?
@disabled ||= (user_configuration_from_key('disabled') || false)
end |
Adds a tag into the page with the desired url or content. | def add_script_tag(url: nil, path: nil, content: nil, type: '')
# param url [String]
# param type [String]
#
# return [Promise<HTMLElement>]
#
add_script_url = <<~JAVASCRIPT
async function addScriptUrl(url, type) {
const script = document.createElement('script');
... |
function for get the targets cttctt in the exons | def obtain_target_from_seq(bioseq_seq)
#we are going to keep all the targets from each gene,
#hash of hashes :)
targets=Hash.new
len_bioseq = bioseq_seq.length + 1
nstrand_targets = []
pstrand_targets = []
for i in (0..bioseq_seq.length-5)
if bioseq_seq.complement[i..i+5] == ... |
DELETE /coupons/1 DELETE /coupons/1.json | def destroy
if session[:coupon_code].present?
session[:coupon_code] = nil
@message = "Coupon Removed"
end
@cart_items = current_user.cart_items
@sub_total, @discount, @tax, @shipping_cost, @final_total = Coupon.destroy_coupon(@cart_items, session[:coupon_code])
respond_to do |format|
... |
Sets the restartNotificationSnoozeDurationInMinutes property value. The number of minutes to snooze the restart notification dialog when the snooze button is selected. | def restart_notification_snooze_duration_in_minutes=(value)
@restart_notification_snooze_duration_in_minutes = value
end |
returns the original title of the document or missing_title | def attachment_title
orig_title = super
orig_title.blank? ? missing_title : orig_title
rescue NoMethodError
missing_title
end |
Only allow a trusted parameter "white list" through. | def user_params
params.require(:user).permit(:id)
end |
Two tiles are equal when their vertixes are geometrically equal. | def ==(tile)
self.vtx == tile.vtx
end |
PATCH/PUT /student_app_cat_regnos/1 PATCH/PUT /student_app_cat_regnos/1.json | def update
respond_to do |format|
if @student_app_cat_regno.update(student_app_cat_regno_params)
format.html { redirect_to @student_app_cat_regno, notice: 'Student app cat regno was successfully updated.' }
format.json { render :show, status: :ok, location: @student_app_cat_regno }
else
... |
Never trust parameters from the scary internet, only allow the white list through. | def admin_banner_params
params.fetch(:banner).permit!
end |
Create a yearly recurrence. | def yearly(options = {})
branch options.merge(every: :year)
end |
min=arr.first arr.each do |x| nested_min = x arr.each do |y| next if x == y nested_min = y < x ? y : x end min = nested_min < min ? nested_min : min end min end | def my_min(arr)
min = arr.first
arr.each do |el|
min = el if el < min
end
min
end |
Never trust parameters from the scary internet, only allow the white list through. | def user_feedback_params
params.require(:user_feedback).permit(:email, :feedback)
end |
== Description Returns the full path for an HTTP request, as required by Net::HTTP::Get. If the URI contains a query, the full path is URIpath + '?' + URIquery. Otherwise, the path is simply URIpath. Example: uri = URI::HTTP.build(path: '/foo/bar', query: 'test=true') uri.request_uri => "/foo/bar?test=true" | def request_uri
return unless @path
url = @query ? "#@path?#@query" : @path.dup
url.start_with?(?/.freeze) ? url : ?/ + url
end |
The names of the nested fields as symbols if the type property is set to `RECORD`. Will be empty otherwise. | def headers
fields.map(&:name).map(&:to_sym)
end |
Parse sub methods like to_string, to_integer | def parse_sub_methods(line)
new_line = []
line.each do |token|
next unless token[:type] == :IDENTIFIER
arguments_size = 0
SUBMETHODS.each do |submethod|
next unless submethod[:ikea_name] == token[:value].to_sym
arguments_size = submethod[:arguments]
end
value = ... |
def inc_vote_count increment! :vote_count planet.inc_vote_count, self end def dec_vote_count decrement! :vote_count planet.dec_vote_count, self end | def add_vote_from_user(user)
votes.create(user: user)
end |
Tells the backend to load translations now. Used in situations like the Rails production environment. Backends can implement whatever strategy is useful. source://i18n//lib/i18n.rb90 | def eager_load!; end |
returns true if pkgname is an autoproj meta package | def is_metapackage?(package_name)
raise RuntimeError, "#{self.class} needs to overwrite is_metapackage?"
end |
Unregisters the event by name, effectively deleting the associated events bound with it also. | def unevent(name)
Events.remove(name)
end |
Finds a link reference for `label` and creates a new link to it with `content` as the link text. If `label` was not encountered in the referencegathering parser pass the label and content are reconstructed with the linking `text` (usually whitespace). | def link_to content, label = content, text = nil
raise ParseError, 'enable notes extension' if
content.start_with? '^' and label.equal? content
if ref = @references[label] then
"{#{content}}[#{ref}]"
elsif label.equal? content then
"[#{content}]#{text}"
else
"[#{content}]#{text}... |
GET /sites/:id GET /projects/:project_id/sites/:id | def show
do_load_resource
get_project_if_exists
do_authorize_instance
respond_to do |format|
format.html { @site }
format.json { respond_show }
end
end |
function7 ===> test no.7 | def stock_count(petshop)
return petshop[:pets].size()
end |
Returns a Boolean indicating whether this character is a hiragana or katakana character. (This string must contain only one character.) | def kana?
codepoint.kana?
end |
Get active positions return [Array] | def active_positions
authenticated_post("auth/positions").body
end |
Never trust parameters from the scary internet, only allow the white list through. | def activity_params
params.fetch(:activity, {}).permit(
:name,
:start,
:duration,
:activity_type_id
)
end |
Indicates whether its possible to capture the payment | def can_capture?(payment)
['checkout', 'pending'].include?(payment.state)
end |
Adds a single extension module +include+ from +store+ to +out+ | def add_extension_modules_single out, store, include # :nodoc:
name = include.name
path = store.friendly_path
out << RDoc::Markup::Paragraph.new("#{name} (from #{path})")
if include.comment then
out << RDoc::Markup::BlankLine.new
out << include.comment
end
end |
Physical ID of the resource created | def physical_resource_id
"#{self.class.name.split('::').last}-#{Carnivore.uuid}"
end |
PUT /definitions/1 PUT /definitions/1.json | def update
@definition = Definition.find(params[:id])
respond_to do |format|
if @definition.update_attributes(params[:definition])
format.html { redirect_to @definition, notice: 'Definition was successfully updated.' }
format.json { head :no_content }
else
format.html { rend... |
An initializer called by the framework once per billling cycle. Override this method if you need to perform highlatency operations, like network transactions, that should not be performed perresource. | def setup(resources) ; end |
Never trust parameters from the scary internet, only allow the white list through. | def project_params
params.require(:project).permit(:title, :image, :banner, :date, :description, :summary, :link, :status)
end |
Expecting string: "A1:hit B10:miss" Processes the result, marks the field appropriately, changes the sequence of shots accordingly. | def process_shot_result(shot_result)
shot_result.split(/:|\s/).each_slice(2) do |location, result|
field[location] = result.to_sym
has_hit(location) if field[location] == :hit
end
end |
Does a sanity check on the specification. Raises InvalidSpecificationException if the spec does not pass the checks. It also performs some validations that do not raise but print warning messages instead. | def validate(strict = false)
validate_required!
validate_optional(strict) if packaging || strict
true
end |
(Experimental) Embeds a "pure" (nonNetzke) Ext component into the view, e.g.: :panel, :html => "Simple Panel" | def ext(name, config = {}) #:doc:
comp = Netzke::ExtComponent.new(name, config)
content_for :netzke_on_ready, raw("#{comp.js_component_render}")
raw(comp.js_component_html)
end |
GET /rodzaj_pracownikas/1 GET /rodzaj_pracownikas/1.json | def show
end |
Synchronously upgrade an environment | def upgrade(job, environment, plugin, options = {})
worker = Worker.new(job, environment.freeze, plugin.freeze, options.freeze)
worker.run
ensure
worker.terminate if worker && worker.alive?
job.terminate if job && job.alive?
end |
Displays a specific tape. API Key Scope: tapes / show | def show_tape_by_pool(pool_id, tape_id, opts = {})
data, _status_code, _headers = show_tape_by_pool_with_http_info(pool_id, tape_id, opts)
data
end |
if all the digits are the same we dont need to compute since the number cant get bigger with permutations | def all_digits_are_the_same?(digits)
digits.uniq.length == 1
end |
Sends a chat message to the client. | def send_message(msg, from = nil)
msg = "#{msg} (@#{from})" unless from.nil?
@auth_required ? @after_auth.push({:m => msg}) : send_data({:m => msg})
end |
POST /guest_books POST /guest_books.xml | def create
@guest_book = GuestBook.new(params[:guest_book])
respond_to do |format|
if @guest_book.save
flash[:notice] = 'Thank you for signing the guestbook'
# format.html { redirect_to(@guest_book) }
format.html { render :action => "created" }
format.xml { render :xml =>... |
GET /cake_flavors/1 GET /cake_flavors/1.json | def show
end |
lexer rule t__25! (T__25) (in Ingredients.g) | def t__25!
# -> uncomment the next line to manually enable rule tracing
# trace_in( __method__, 18 )
type = T__25
channel = ANTLR3::DEFAULT_CHANNEL
# - - - - main rule block - - - -
# at line 34:9: 's'
match( 0x73 )
@state.type = type
@state.channel... |
POST /configuration_files POST /configuration_files.json | def create
@configuration_file = ConfigurationFile.new(configuration_file_params)
respond_to do |format|
if @configuration_file.save
format.html { redirect_to @configuration_file, notice: 'Configuration file was successfully created.' }
format.json { render :show, status: :created, locati... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.