anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
Return start time for this element, relative to the beginning of the production. | def t1
_absolute(enter)
end |
sorted by how they should be displayed | def users
self.triples.map(&:first)
end |
add info in the json file | def add(class_name, object)
@data = get_all()
@data[class_name].push(object.to_hash())
save()
end |
SHOW GIFTS (ALL OF THEM) | def index
@occasion = Occasion.find params[:occasion_id]
@gifts = Gift.all
end |
Use for_model instead of instatiating a record directly. | def initialize(model_class)
@model_class = model_class
@records = []
end |
Permitted params for the model | def permitted_params
params.require(params[:asset_type].underscore.gsub('/', '_').to_sym).permit(
:name,
:filename,
:body,
:content_type,
:width,
:height,
:asset_type,
:ratio
)
end |
start by buliding array | def anna_3_5
annas_counter = 0 #variable used inside the function
a = (1..100).to_a #building array of a hundred elements
while annas_counter < 100
annas_counter += 1
if annas_counter % 3 == 0 && annas_counter % 5 == 0 #way to do both 3 and 5 together(15 a factor of both)
a[annas_counter -1] = "minedminds"
... |
two edge cases pawn can go two moves at first pawn can move diagonally to take another piece | def take(current_position)
if direction == 1
diagonals(current_position, 1)[0..1]
elsif direction == 2
diagonals(current_position, 1)[1...-1]
end
end |
global alias so we can write 'df.world.units.all[0]' | def df
DFHack
end |
Populate the response with content. Set the response's content type to the given type. Raise an error if the developer tries to double render. | def render_content(content, type)
raise "already built response" if already_built_response?
self.session.store_session(@res)
self.flash.store_flash(@res)
@res.content_type = type
@res.body = content
@already_built_response = true
end |
GET /step_commands/1 GET /step_commands/1.json | def show
end |
GET /actionables GET /actionables.json | def index
@actionables = Actionable.all
end |
Returns the framework input paths for the given framework paths | def embed_frameworks_input_paths(framework_paths, xcframeworks)
input_paths = framework_paths.map(&:source_path)
# Only include dynamic xcframeworks as the input since we will not be copying static xcframework slices
xcframeworks.select { |xcf| xcf.build_type.dynamic_framework? }.eac... |
Prints a list of links for the Main Menu | def print_link_list(items)
linkString = ""
if(!items.empty? && items[0].is_a?(Category))
linkString += "<tr><td>#{link_to "New Category", new_category_url, {:style=>'color:#FF8000'}}</td></tr>"
linkString += "<tr><td>#{main_menu_accord(all_category_hash)}</td></tr>"
elsif(!items.empty? && ite... |
PATCH/PUT /promulher_forms/1 PATCH/PUT /promulher_forms/1.json | def update
respond_to do |format|
if @promulher_form.update(promulher_form_params)
format.html { redirect_to @promulher_form, notice: 'Promulher form was successfully updated.' }
format.json { render :show, status: :ok, location: @promulher_form }
else
format.html { render :edit ... |
Use the connection from the connection class | def connection
@connection_class.connection
end |
> compress [1, 1, 2, 3, 3, 3] => [1, 2, 3] | def compress(array)
array.uniq
end |
:registerable dragonfly_accessor :last_sign_in_ip image_accessor :last_sign_in_ip | def send_survey
Message.send_survey_to(self)
end |
Example: foo(42) ^^^ foo 42 ^^^ | def spot_fcall_for_name
mid, _nd_args = @node.children
fetch_line(@node.first_lineno)
if @snippet.match(/(#{ Regexp.quote(mid) })/, @node.first_column)
@beg_column = $~.begin(1)
@end_column = $~.end(1)
end
end |
Note: These tests assume a default storage class with a dynamic provisioner and 'Immediate' bind | def test_pvc
pvname = "local0001"
storage_class_name = "k8s-deploy-test"
assert_deploy_success(deploy_global_fixtures_non_namespaced("pvc",
subset: ["wait_for_first_consumer_storage_class.yml"]))
TestProvisioner.prepare_pv(pvname, storage_class_name: storage_class_name)
assert_deploy_success... |
Get response for sending KYC deny email Author: Mayur Date: 14/12/2018 Reviewed By: | def email_kyc_deny(data_to_format)
{}
end |
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 |
method called to check status of player | def status
"#{@name}: #{@lives}/3 "
end |
Get the top 10 popular contents over the last 14 days | def top_paths(repo, options = {})
opts = ensure_api_media_type(:traffic, options)
get "#{Repository.path repo}/traffic/popular/paths", opts
end |
GET /ches GET /ches.json | def index
@ches = Ch.all
end |
List L2 Bridge Endpoint Profiles List all L2 bridge profiles | def list_l2_bridge_profiles_with_http_info(site_id, enforcement_point_id, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: PolicyNetworkingConnectivitySegmentsEdgeBridgeProfilesApi.list_l2_bridge_profiles ...'
end
# verify the required parameter 'site_id... |
PATCH/PUT /questions/1 PATCH/PUT /questions/1.json | def update
check_delete_flg
respond_to do |format|
if @question.update_attributes(question_params)
format.html { redirect_to @question, notice: 'Question was successfully updated.' }
format.json { render :show, status: :ok, location: @question }
else
format.html { render :edi... |
Register this field with the class, overriding a previous one if needed. | def add_field(field_defn, method_conflict_warning: field_defn.method_conflict_warning?)
# Check that `field_defn.original_name` equals `resolver_method` and `method_sym` --
# that shows that no override value was given manually.
if method_conflict_warning &&
CONFLICT_FIELD_NA... |
PATCH/PUT /solicitacao_tipos/1 PATCH/PUT /solicitacao_tipos/1.json | def update
respond_to do |format|
if @solicitacao_tipo.update(solicitacao_tipo_params)
format.html { redirect_to @solicitacao_tipo, notice: 'Solicitacao tipo was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.js... |
attr_reader :threads2frames Hash[thread_id] > top_frame | def adjust_frame(frame_num, absolute_pos)
frame, frame_num = get_frame(frame_num, absolute_pos)
if frame
@frame = frame
@frame.index = frame_num
prefix = "--> ##{frame_num} "
unless @settings[:traceprint]
msg("#{prefix}%s" %
@frame.describe(:basename => settings[:b... |
Only allow a trusted parameter "white list" through. | def bulk_action_params
params.require(:bulk_action).permit(
:action_type,
:description,
:pids,
manage_release: [:tag, :what, :who, :to],
set_governing_apo: [:new_apo_id],
manage_catkeys: [:catkeys]
)
end |
Test if crew is not missing methods | def test( crew )
[ 'board', 'step', 'event', 'identifier' ].each do | method |
if not crew.respond_to?( method )
raise "Crew should respond to #{method}"
end
end
end |
This calculates and stores the offset at which each column starts. Used when going to next column or doing a find for a string in the table. | def _calculate_column_offsets
total = 0
coffsets = []
ctr = 0
## ix will have gaps in between for hidden fields
each_column { | c, ix|
v = c.width
coffsets[ctr] = total
ctr += 1
total += v + 2 ## blank space plus separator
}
... |
PUT /contract_doc_categories/1 PUT /contract_doc_categories/1.json | def update
@contract_doc_category = ContractDocCategory.find(params[:id])
respond_to do |format|
if @contract_doc_category.update_attributes(params[:contract_doc_category])
format.html { redirect_to @contract_doc_category, notice: 'Contract doc category was successfully updated.' }
format... |
remove leading and trailing whitespace from expression | def trim_whitespace
@expression.strip!
end |
PATCH/PUT /admin_panels/1 PATCH/PUT /admin_panels/1.json | def update
respond_to do |format|
if @admin_panel.update(admin_panel_params)
format.html { redirect_to @admin_panel, notice: 'Admin panel was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @a... |
POST /citizens POST /citizens.json | def create
@citizen = Citizen.new(citizen_params)
@citizen.credits = 1000
unless current_user
@user = User.new(email: params[:email], password: params[:password], password_confirmation: params[:password_confirmation])
unless @user.save
respond_to do |format|
format.html { ren... |
Simulates the user pressing the alt key and hold it down until do_alt_up() is called or a new page is loaded. | def alt_key_down
command 'altKeyDown'
end |
Returns the delay in seconds | def delay
if @delay_den != 0
@delay_num/@delay_den
else
@delay_num/100
end
end |
end test Test that the graph class will not let you to_s on an incomplete graph | def test_graph_to_s_incomplete
sut_graph = Graph.new
sut_graph.name="test_graph"
#sut_graph.type=:digraph
sut_graph.node_style=:ellipse
sut_graph.add_edge("TEST1" , "TEST2" , "take_me_to_test_2")
assert_raises RuntimeError do
returned_obj = sut_graph.to_s
end # end asser... |
Checks the to +v+ component. | def check_to(v)
return true unless v
return true if v.size == 0
v.split(/[,;]/).each do |addr|
# check url safety as path-rootless
if /\A(?:%\h\h|[!$&-.0-;=@-Z_a-z~])*\z/ !~ addr
raise InvalidComponentError,
"an address in 'to' is invalid as URI #{addr.dump}"
... |
Contstructor method Parameters String name_player1 Name for player 1 String name_player2 Name for player 2 | def initialize(name_player1, name_player2)
@current_player = :player1
@player1 = Player.new(name_player1, PLAYER_MARKS[:player1], 1)
@player2 = Player.new(name_player2, PLAYER_MARKS[:player2], 2)
@game_array = [[nil, nil, nil],
[nil, nil, nil],
[nil, nil, nil]]
e... |
rubocop: enable MethodLength rubocop: enable AbcSize | def tpl_name
"monit_check_#{new_resource.name}"
end |
trying to set CORS response headers in controller actions | def cors_set_access_control_headers
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
headers['Access-Control-Allow-Headers'] = 'Content-Type'
headers['Access-Control-Max-Age'] = "1728000"
end |
Never trust parameters from the scary internet, only allow the white list through. | def work_article_params
params.require(:work_article).permit(:name)
end |
======================================================================== followers attacks engine | def fo_tool
return actor.equips[0] if actor.primary_use == 1
return actor.equips[1] if actor.primary_use == 2
return actor.assigned_item if actor.primary_use == 3
return actor.assigned_item2 if actor.primary_use == 4
return actor.assigned_item3 if actor.primary_use == 5
return ac... |
Construct a SQL literal. This is useful for sql that is too complex for Arel. | def sql_literal(value)
Arel::Nodes::SqlLiteral.new(value)
end |
create a paid up member with a given company number, make a payment with the expire date. | def create_co_and_payment(company_number, payment_exp_date, member_pay_expires: Time.zone.today + 1.year, payment_create_date: Time.zone.now)
u = create(:member_with_membership_app, company_number: company_number)
u.shf_application.update(created_at: payment_create_date, updated_at: payment_create_date)
c... |
GET /admin/interviews/new GET /admin/interviews/new.json | def new
@admin_interview = Interview.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @admin_interview }
end
end |
GET /schmos GET /schmos.json | def index
@schmos = Schmo.all
@notes = Note.all
end |
primary access control point: returns all tenant permissions for user currently not used as user will only have one tenant with current implementation | def current_tenant_permissions
if current_or_guest_user
current_or_guest_user.tenant_ids
else
nil
end
end |
recursive fun for the same | def fiboRec(no)
if no == 0
return [0]
elsif no == 1
return fiboRec(0).push(1)
else
arr = fiboRec(no-1)
return arr.push(arr[no-1] + arr[no-2])
end
end |
=begin This function opens the file, converts it into nokogiri. Then uses xpath to sort the xml into an array. That array becomes the instance variables for an email data type above. Then the email data type gets pushed into an array. It also has a error check, to make sure there is actually a file in the location sent... | def openFile(emaillist,emailXML)
begin
emails = Nokogiri::XML(File.open(emailXML))
emails.xpath("//record").each { |f| emaillist.push(Email.new(f.css(
'id//text()','first_name//text()','last_name//text()',
'email//text()','gender//text()','ip_address//text()',
'send_date//text()','email_body//text()','ema... |
This gets a game cliche from a list of cliches in a text file | def get_game_cliche
#initialize variable
chosen_line = nil
#Get the cliche
File.foreach("game_cliches.txt").each_with_index do |line, number|
chosen_line = line if rand < 1.0/(number+1)
end
return chosen_line.chomp
end |
Wait for the UI to finish processing an action | def wait_for_ui_to_update
sleep(UI_UPDATE_DELAY)
end |
PATCH/PUT /expenses/1 PATCH/PUT /expenses/1.json | def update
respond_with Expense.update(params[:id], expense_params), status: 204
end |
(This method is generated in Translator_defaultbuildImpl) | def api_deserialize_impl(r)
@is_new = (r).nil?
r = {} if @is_new
@is_incomplete = false
if Saklient::Util::exists_path(r, 'ID')
@m_id = (Saklient::Util::get_by_path(r, 'ID')).nil? ? nil : Saklient::Util::get_by_path(r, 'ID').to_s
else
@m_id = nil... |
Execute the Choreo using the specified InputSet as parameters, wait for the Choreo to complete and return a ResultSet containing the execution results. | def execute(input_set = nil)
resp = super(input_set)
results = AddURLResultSet.new(resp)
return results
end |
Estimate the cardinality of the union of several sets | def union(counter_names, time=0)
union_helper(counter_names, time)
end |
Authorization number (only if completed?). | def auth_id
params['TxAuthNo']
end |
end initialize randomly determine if this room will have an enemy | def assign_enemy
@has_enemy = rand(1..2)==1 ? true : false
#need an enemy value for the room.
end |
custom validation for custom message without standard attribute prefix | def presence_of_subject_relationship_other
if subject_relationship_other.blank?
errors.add(:subject_relationship_other, ActiveRecord::Error.new(
self, :base, :blank, {
:message => "You must specify a relationship with 'other relationship' is selected." } ) )
end
end |
Is this dependency simply asking for the latest version of a gem? | def latest_version?
@requirement.none?
end |
Returns array of: Pixel xdimension Pixel ydimension unit (see png spec) | def get_data
xd = @data[0..3].unpack("C*")
xd = Shared::interpret_bytes_4(xd)
yd = @data[4..7].unpack("C*")
yd = Shared::interpret_bytes_4(yd)
unit = @data[8].unpack("C*")[0]
if !(unit == 0 || unit == 1)
warn "Unrecognised unit value for pHYs chunk: #{unit}."
... |
Trigger auto approve update rescue task Author: Aniket Date: 06/07/2018 Reviewed By: | def trigger_auto_approve_update_rescue_task(user_extended_details_id)
BgJob.enqueue(
AutoApproveUpdateJob,
{
client_id: @client_id,
reprocess: 1,
user_extended_details_id: user_extended_details_id
}
)
Rails.logger.info("---- enqueue_job AutoApprove... |
Never trust parameters from the scary internet, only allow the white list through. | def profile_params
params.require(:profile).permit(:id, :name, :description, :cpf, :services, :mobile, :zipcode, :address, :number, :complement, :neighborhood, :city, :state, :profile)
end |
PUT /chores/1 PUT /chores/1.json | def update
# TODO: Add cron_str updating
respond_to do |format|
if @chore.update_attributes(params[:chore])
format.html { redirect_to @chore, notice: 'Chore was successfully updated.' }
format.json { head :no_content }
else
format.html { render :edit }
format.json { r... |
GET /nursing_times/1 GET /nursing_times/1.json | def show
@nursing_time = NursingTime.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @nursing_time }
end
end |
Update organization units cache table if records are more than one day old | def update_organization_units
oldest_update = AdOrganizationUnit.order('created_at').last
if bind && (oldest_update.nil? || oldest_update.created_at<1.day.ago)
filter = Net::LDAP::Filter.eq("objectClass", "organizationalunit")
results = @connection.search(:base =>"ou=Sync,"+base_distinguished_name... |
Compares the value of +self+ with the value of +other+. | def <=>(other)
other = other.value if other.is_a? self.class
return value <=> other
end |
The class of the resource that the controller handles | def controller_resource
ProjectEvaluation
end |
A method for building pair role | def mk_pair_role rpair, plural=false
suffix = plural ? 's' : ''
"#{rpair.join(UBAR)}_pair#{suffix}"
end |
Triggers an event, moving record to associated state, if permitted Returns false if event not permitted | def trigger(event, metadata={})
if (event_permitted(event) || User.is_admin?(metadata[:user_id])) &&
required_metadata_present?(event, metadata)
to_state = self.event_to_state(event)
callback_metadata = metadata.clone
transition_to(to_state, metadata)
if respond_to?(:even... |
=> Produit le pdf et l'ouvre | def generate_pdf
begin
raise( :lilyfile_does_not_exists ) unless File.exists?( path_lily_file )
`lilypond --output='#{path_affixe_file}' '#{path_lily_file}'`
`open '#{path_pdf_file}'`
rescue Exception => e
fatal_error e.message
end
end |
POST /faqs POST /faqs.json | def create
@faq = Helpdesk::Faq.new(faq_params)
respond_to do |format|
if @faq.save
format.html { redirect_to admin_faqs_url, notice: 'Faq was successfully created.' }
format.json { render json: @faq, status: :created, location: @faq }
else
format.html { render action: "new"... |
actions to register a account | def new
@user = User.new
end |
Update an account by a given account_number | def update_account(account_number, account_form)
# the base uri for api requests
query_builder = Configuration.base_uri.dup
# prepare query string for API call
query_builder << '/accounts/{account_number}'
# process optional query parameters
query_builder = APIHelper.append... |
End of N3_PR Segment Details Start of TRN Segment Details | def originating_company_id_trace(*options)
'1000000009'
end |
must follow any before filters | def parse_values_from_ui
unless self.period_value.blank? and self.period_units.blank?
p = self.period_value.to_i
self.period = p.send(self.period_units).to_i
end
unless self.breach_duration_value.blank? and self.breach_duration_units.blank?
p = self.breach_duration_value.to_i
self.breach_duration = p.... |
Procedure to place button on the screen | def place_button(x, y, message)
Gosu.draw_rect(x, y, 70, 45, Gosu::Color::GREEN, ZOrder::MIDDLE, mode=:default)
@button_font.draw_text(message, x+5, y+10, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)
end |
Cleans up nokogiri search results | def cleanup(results)
results.map { |r| r.value.strip }.reject(&:empty?).uniq
end |
Serves the asset at the path in +req+ for +generator_name+ via +res+. | def asset generator_name, req, res
asset_dir = @asset_dirs[generator_name]
asset_path = File.join asset_dir, req.path
if_modified_since req, res, asset_path
res.body = File.read asset_path
res.content_type = case req.path
when /\.css\z/ then 'text/css'
... |
do eth protocol handshake and return status | def send_handshake(network_id, total_difficulty, head_hash, genesis_hash)
status = Status.new(protocol_version: 63, network_id: network_id,
total_difficulty: total_difficulty, current_block: head_hash, genesis_block: genesis_hash)
@context.send_data(Status::CODE, status.rlp_e... |
:nodoc: Return a expanded path to repository mirror build with information from configuration for repository. Replace keywords (:keyword) with value matched by it pattern. | def mirror_path(repository_owner, repository_name)
mirror_path = repository_info(repository_owner, repository_name).path || raise(GithubMirrorError, "Path for repository '#{repository_owner}/#{repository_name}' doesn\'t exist in config")
mirror_patterns = repository_info(repository_owner, repository_name).patte... |
runs an external executable, returns true on success | def run_executable(full_commandline)
log.debug "running #{full_commandline}"
Process.wait(Process.spawn(full_commandline))
$CHILD_STATUS.exitstatus == 0
end |
Initialize reservations object Holds growing and shrinking list of ticket reservations | def initialize
@reservations = {}
@lockers = Lockerz::Lockers.new
end |
GET /fotos_empresas GET /fotos_empresas.json | def index
@fotos_empresas = FotosEmpresa.all
end |
GET /frbr_manifestations/new GET /frbr_manifestations/new.json | def new
screen_name("Admin-Nuevo-Manifestacion-FRBR")
@frbr_manifestation = FrbrManifestation.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @frbr_manifestation }
end
end |
DELETE /sofas/1 DELETE /sofas/1.xml | def destroy
@sofa = Sofa.find(params[:id])
@sofa.destroy
respond_to do |format|
format.html { redirect_to(sofas_url) }
format.xml { head :ok }
end
end |
Test if we can add a comment to a post | def test_add_comment_to_post
nc = @normal_post.number_of_comments
@normal_post.comments << @comment
assert_equal(nc + 1, @normal_post.number_of_comments)
end |
Given a project's id (`pid`), get the project's name. | def project_name(pid)
Nokogiri::HTML(pivotal_tracker(project_url(pid)).content).css('project > name').text.split(' ').join
end |
DELETE /guacs/1 DELETE /guacs/1.json | def destroy
@guac.destroy
respond_to do |format|
format.html { redirect_to guacs_url, notice: 'Guac was successfully destroyed.' }
format.json { head :no_content }
end
end |
Converts +document+ to text and writes it to the pager | def display document
page do |io|
f = formatter(io)
f.width = @width if @width and f.respond_to?(:width)
text = document.accept f
io.write text
end
end |
Diagonal Top right to bottom left approach | def right_to_diagonal_left_approach
largest_prod = 0
for each_row in (0..15)
for col in (0..19)
each_col = 19 - col
a = $grid_of_numbers[each_row][each_col]
b = $grid_of_numbers[each_row+1][each_col-1]
c = $grid_of_numbers[each_row+2][each_col-2]
d = $grid_of_numbers[each_row+3][e... |
GET /entity GET /entity.json | def index
@search = @klass.search(params[:q])
@entities = @search.result.includes(@klass::ADMIN_INCLUDES).page(params[:page])
@count = @search.result.count
@search.build_condition
respond_to do |format|
format.html # index.html.erb
format.json { render json: @entities }
end
end |
takes a hash of question IDs (keys) and answers (values) | def set_answers!(params)
SurveyQuestion.with_question.find_all_by_survey_id(survey_id).each do |question| # iterate through all survey questions
if params[question.id.to_s].blank? # if the question hasn't been answered
remove_answer(question.id)
else
set_answer(question, params[question.... |
Returns the endpoint of this URL e.g. the bit after the host with any slashes included. For example: Wgit::Url.new(" returns "/about.html/". See Wgit::Urlto_path if you don't want the slashes. | def to_endpoint
endpoint = @uri.path
endpoint = '/' + endpoint unless endpoint.start_with?('/')
Wgit::Url.new(endpoint)
end |
The "type" of dependencies this manager manages. This can be the language, tool, etc. | def type
raise LicenseScout::Exceptions::Error.new("All DependencyManagers must have a `#type` method")
end |
Check if params DEVICE_CODE, DATA is present in JSON send | def has_not_mandatory_params?
!params[:email].present? || !params[:password].present?
end |
is Encoding callseq: Stringiseuc > obj or nil Returns whether self's encoding is EUCJP or not. Note don't expect this return value is MatchData. | def iseuc; Kconv.iseuc(self) end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.