anchor stringlengths 10 14.3k | positive stringlengths 10 14.9k |
|---|---|
def describe_backup_dbs(
self,
request: dds_20151201_models.DescribeBackupDBsRequest,
) -> dds_20151201_models.DescribeBackupDBsResponse:
runtime = util_models.RuntimeOptions()
return self.describe_backup_dbs_with_options(request, runtime) | Precautions You can call the [CreateDBInstance](~~61763~~) operation to restore a database for an ApsaraDB for MongoDB instance. For more information, see [Restore one or more databases of an ApsaraDB for MongoDB instance](~~112274~~). |
def eval_model(device, model, sampler, loss_compute, logit_modifier_fxn, token_sampler,
print_every, max_len, user_items_df, max_name_len=15, ingr_map=None,
base_save_dir='', pad_ingr=None, ppx_only=False, **tensor_kwargs):
start = datetime.now()
results_dicts = []
# Extract ... | Run a single epoch |
def update_commitments(commitment=None, external_to_remove=None,
external_to_add=None):
c = {}
if os.path.isfile(PODLE_COMMIT_FILE):
with open(PODLE_COMMIT_FILE, "rb") as f:
try:
c = json.loads(f.read())
except ValueError:
pr... | Optionally add the commitment commitment to the list of 'used', and optionally remove the available external commitment whose key value is the utxo in external_to_remove, persist updated entries to disk. |
def unpack(run=0, seqno=0, iraw=0):
if iraw == 0 and run == 0:
print("Usage: osgprod_bind.unpack(iraw=<iraw>)")
print(" or: osgprod_bind.unpack(run=<run>, seqno=<seqno>)")
return 0
if iraw:
with db_connection() as conn:
with conn.cursor() as curs:
curs.execute("""SEL... | Looks up rawdata id iraw and unpacks the job output tarballs from all jobs that completed successfully into a new directory named iraw under the pwd. If iraw is not known, alternatively one can supply the run number and sequence number of the raw data input file. |
def init_column_headers(self):
col_headers = {1: "bid", 2: "tricks", 3: "score"}
for player in range(1, 5):
ent_player_name = tk.Entry(self.master, font='courier 10 bold', fg='blue',
borderwidth=2, relief="groove")
ent_player_name.grid(... | player names and bid / trick / score headers |
def run_all():
db = DBInterface()
year = Config.get_property("league_year")
session = Session(bind=db.engine)
scraper.scrape_all(db, session, year)
session.commit()
bets.predict_all(db, session)
session.commit()
session.close() | Run the entire NBA_bet project. |
def intersection(line1, line2):
rho1, theta1 = line1
rho2, theta2 = line2
A = np.array([
[np.cos(theta1), np.sin(theta1)],
[np.cos(theta2), np.sin(theta2)]
])
b = np.array([[rho1], [rho2]])
x0, y0 = np.linalg.solve(A, b)
x0, y0 = int(np.round(x0)), int(np.round(y0))
retur... | Finds the intersection of two lines given in Hesse normal form. Returns closest integer pixel locations. |
def event_hub_connection_string(self) -> Optional[str]:
return pulumi.get(self, "event_hub_connection_string") | (Personalization Only) The flag to enable statistics of Bing Search. |
def replay(method: Callable) -> None:
counter_key = method.__qualname__
i_keys = method.__qualname__ + ':inputs'
o_keys = method.__qualname__ + ':outputs'
this = method.__self__
counter = this.get_str(counter_key)
history = list(zip(this.get_list(i_keys),
this.get_list(o_... | Ouput log of actions taken on method |
def get_ytm_discount_data(self):
ytm=Bootstrapping.get_ytm_dict(self)
data = pd.DataFrame()
for i in ytm.keys():
data.loc[i / 2, 'Yield to maturity'] = ytm[i]
data.loc[i / 2, 'discount_rate'] = Bootstrapping.P_Tn(self,ytm[i], i)
return data | This funtion is to get the dataframe of yield to maturity and discount rate value. |
def start(self) -> None:
cb = self._callback
if cb is not None:
self._callback = None
propagate(from_=ensure_future(cb()), to=self._future) | Actually invoke the underlying function (but only if it hasn't been invoked already). |
def get_rest_list(request):
if request.method == "GET":
rest_list = Package.objects.order_by('-location')
serializer = PackageSerializer(rest_list, many=True)
return JsonResponse(serializer.data, safe=False) | Returns Json list of all Packages |
def set_logger(save=False, log_path=None):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if not logger.handlers:
if save:
# Logging to a file
file_handler = logging.FileHandler(log_path)
file_handler.setFormatter(logging.Formatter('%(asctime)s:%(leve... | Set the logger to log info in terminal and file `log_path`. In general, it is useful to have a logger so that every output to the terminal is saved in a permanent file. Here we save it to `model_dir/train.log`. |
def choose_mi_best(self, R):
population = np.empty([self.P.shape[0] + R.shape[0], 2*self.d + 1])
i = 0
for individual in np.vstack([self.P, R]):
population[i, 0] = -self.J(individual[0:self.d], self.nCEC)
population[i, 1:] = individual
i = i+1
sorted_... | Method creates new population by choosing mi best individuals from children and current population |
def inner_product(pattern_one, pattern_two):
return np.sum(np.multiply(pattern_one, pattern_two)) | Calculate the inner product of the two patterns as a vecter. |
def list_of_medias(args, sourcedir, recursive):
files = list_of_files(sourcedir, recursive)
return [_ for _ in files if is_media_within_dates(_, args.dates)] | Return the list of full paths for pictures and movies in source directory |
def classify(self, verbose=True, print_scores=False):
if verbose:
print("%s: Training model ..." % self.clf_name)
self.clf.fit(self.X_train, self.y_train)
if verbose:
print("%s: Calculating probablities ... " % self.clf_name)
y_proba = self.clf.predict_proba(self... | Conduct classification and calculate metrics |
def mptcp_connections(self, pkts):
count = 0
#MPTCP_Capable = 0x0
#MPTCP_CapableACK ---> successful handshake
print "======================================================================"
print "Successful Handshake --- Look for Ack packets with MPTCP option Header"
print """Token = connectionID = SHA1(key... | Identify distinct MPTCP Connections that reached Successful handshake Look for Ack packets with MPTCP option Header For each MPTCP connection report Receiver's token value which acts as the connectionID |
def _logits_to_predictions(self, logits):
key = prediction_key.PredictionKey.SCORES
with ops.name_scope(None, "predictions", (logits,)):
if self.logits_dimension == 1:
logits = array_ops.squeeze(logits, squeeze_dims=(1,), name=key)
return {key: logits} | Returns a dict of predictions. |
def import_outcome_group_global(request_ctx, id, source_outcome_group_id, **request_kwargs):
path = '/v1/global/outcome_groups/{id}/import'
payload = {
'source_outcome_group_id' : source_outcome_group_id,
}
url = request_ctx.base_api_url + path.format(id=id)
response = client.post(request_c... | Creates a new subgroup of the outcome group with the same title and description as the source group, then creates links in that new subgroup to the same outcomes that are linked in the source group. Recurses on the subgroups of the source group, importing them each in turn into the new subgroup. Allows you to copy orga... |
def _get_weight(self):
return self.__weight | Getter method for weight, mapped from YANG variable /input/LocatorRecord/weight (uint8) |
def levenshtein(s1, s2):
if len(s1) < len(s2):
return levenshtein(s2, s1)
# len(s1) >= len(s2)
if len(s2) == 0:
return len(s1)
previous_row = range(len(s2) + 1)
for i, c1 in enumerate(s1):
current_row = [i + 1]
for j, c2 in enumerate(s2):
insertions = pr... | First Python implementation method of the Levenshtein distance between strings |
def find_mle_by_grad_descent(initial_sensor_loc,
obj_loc, distance, lr=0.001, num_iters = 1000):
sensor_loc = initial_sensor_loc
# Your code: finish the gradient descent
return sensor_loc | Compute the gradient of the loglikelihood function for part f. |
def save_config_file(self):
with open(self.config_file_name, 'w',encoding='utf-8') as outfile:
json.dump(self._config, outfile,indent=2) | Saves the config file |
def DeleteSetting(appname, section, key):
settings = _OptionsDB(appname)
settings.delete(section, key) | Delete a setting in the central setting file |
def rSeqFile(FilePath):
f=open(FilePath, 'r')
#check if file open
if f.mode == 'r':
return(f.read()) | Read file returns read file as string |
def remove_stop_words(tokens, language):
if not remove_stop_words_activated or language.__eq__("Catalan"):
return tokens
output = []
stop = stopwords.words(language.lower())
for token in tokens:
if token not in stop:
output.append(token)
return output | Method to remove the stop words used in get_left_right_lists() This method does not work for Catalan language. |
def num_accepts_ge(self, max_len: int, bound: Sequence[Text] = ()) -> int:
_, num_accepted_eq, num_accepted_gt = self.num_accepts(max_len, bound)
return num_accepted_eq + num_accepted_gt | Returns the number of sequences >= bound with len() <= max_len accepted by this NFA. |
def test_06_dt_to_milliseconds_str(self):
dt = datetime.datetime.utcnow()
ts = utils.dt_to_milliseconds_str(dt)
self.assertIsInstance(ts, str) | Should return Python datetime object. |
def nullHeuristic(state, problem=None):
return 0 | A heuristic function estimates the cost from the current state to the nearest goal in the provided SearchProblem. This heuristic is trivial. |
def rearrange_digits(input_list):
## Corner cases:
if len(input_list) == 0:
return [0, 0]
elif len(input_list) == 1:
return [input_list[0], 0]
# Sort an array using merge-sort
sorted_list = merge_sort(input_list)
# Create two empty array and pop largest number from an sorted_li... | Rearrange Array Elements so as to form two number such that their sum is maximum. |
def __init__(self, *args, **kwargs):
self.jsonp_callback = kwargs.pop('jsonp_callback', None)
super(JsonResponse, self).__init__(*args, **kwargs) | Supports an additional argument ``jsonp_callback``. If specified, the JSON serialized data string will be wrapped in parenthesis and prefixed by the value of ``jsonp_callback``. |
def plot_image_and_proj(image, title="", **kwargs):
fig = plt.figure()
gs = gridspec.GridSpec(3, 2, width_ratios=[3, 1], height_ratios=[0.2, 3, 1])
ax0 = plt.subplot(gs[1,0])
plt.title(title)
ims = plt.imshow(image, aspect="auto", **kwargs)
ax2 = plt.subplot(gs[2,0], sharex=ax0, )
plt.... | Plots an image and the projections (sums) of it on the x, y axes. |
def info(self, message):
if self.show_info:
print(message) | Print a message to the standard output, in case show_info is enabled. |
def _getCoordsFromRun(self, run_dict, bold=False):
run_dict = copy.deepcopy(run_dict)
run_dict = self._filterDictionaryBold(run_dict, bold=bold)
timeDictKey = ""
if "t" in run_dict:
timeDictKey = "t"
else:
for k in run_dict:
if k.startswith... | Find coordinates of a single run time, output and space dimensions. |
to check if the user is the owner of the lock. | def owner?(obj)
(self.id == RedisMutexer.config.redis.get(key(obj)).to_i)
end |
GET /spaceships/new GET /spaceships/new.json | def new
@spaceship = Spaceship.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @spaceship }
end
end |
Time complexity O(1) Space complexity O(1) | def get_first
return @head if @head.nil?
return @head.data
end |
:nodoc: Creates a new InstallerSet that will look for gems in +domain+. | def initialize(domain)
super()
@domain = domain
@f = Gem::SpecFetcher.fetcher
@always_install = []
@ignore_dependencies = false
@ignore_installed = false
@local = {}
@local_source = Gem::Source::Local.new
@remote_set = Gem::Resolver::BestSet.n... |
To render with the distance to | def setOrigin(origin)
@origin = origin
end |
POST /frontapp_support_sources POST /frontapp_support_sources.json | def create
@support_source = FrontappSupportSource.new(frontapp_support_source_params)
respond_to do |format|
if @support_source.save
format.html { redirect_to support_sources_path,
notice: 'Support source was successfully created.' }
format.json { render :show, status: :created... |
HELPER METHODS =========================================== The two drivers have slightly different ways of yielding hashes of results, so this method must be implemented to provide a uniform interface. | def each_hash(result) # :nodoc:
raise NotImplementedError
end |
get article table data from ga | def get_article_data(yesterday, view_id, domain_id, article_key)
date_range = @analytics::DateRange.new(start_date: yesterday, end_date: yesterday)
order_by = @analytics::OrderBy.new(field_name: 'ga:pageviews', sort_order: 'DESCENDING')
metric = @analytics::Metric.new(expression: 'ga:pageviews')
dimensions ... |
Checks that dependencies use requirements as we recommend. Warnings are issued when dependencies are openended or overly strict for semantic versioning. | def validate_dependencies # :nodoc:
warning_messages = []
@specification.dependencies.each do |dep|
prerelease_dep = dep.requirements_list.any? do |req|
Gem::Requirement.new(req).prerelease?
end
warning_messages << "prerelease dependency on #{dep} is not recommended" if
prer... |
Returns the name of the current directory. | def pwd
Dir.pwd
end |
sets the next unbonded node in nodes to node | def next=(node)
# you can only bond if it has unbonded sites
if !full?
nodes.each_index { |i|
if nodes.at(i) == nil
nodes[i] = node
break
end
}
return node
# unless it expands, in which case you can bond
elsif expands?
nodes << node
puts nodes
nodes.flatten!
... |
Subject can be set in your I18n file at config/locales/en.yml with the following lookup: en.user_mailer.password_reset.subject | def password_reset(user)
@user = user
@hostname = "http://creuroja.net"
@reset_password_link = "#{@hostname}#{edit_password_reset_path(@user.resettoken)}"
mail(to: @user.email, subject: 'Recuperació de contrasenya de Creu Roja a Catalunya')
end |
PATCH/PUT /organizations/1 PATCH/PUT /organizations/1.json | def update
respond_to do |format|
if @organization.update(organization_params)
format.html { redirect_to edit_admin_organization_path(@organization), notice: 'Organization was successfully updated.' }
format.json { head :no_content }
else
flash[:error] = "#{@organization.errors.f... |
Prepare the aggregation function for a model class and a field | def prepare(model, field_name = nil)
@model = model
@selection = Babik::Selection::Path::Factory.build(model, @aggregation_path)
@field_name = field_name || "#{self.table_alias}__#{SQL_OPERATION.downcase}"
self
end |
Set a term that is included for every chef_search call. | def chef_scope(field, term="*")
scopes = fetch(:chef_scopes) || []
scopes.delete_if { |scope| scope =~ /chef_environment/ }
set :chef_scopes, scopes << [field, term].join(":")
end |
forget user in persistent session | def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end |
POST /accession_location_entries POST /accession_location_entries.json | def create
@accession_location_entry = AccessionLocationEntry.new(params[:accession_location_entry])
respond_to do |format|
if @accession_location_entry.save
format.html { redirect_to @accession_location_entry, notice: 'Accession location entry was successfully created.' }
format.json { r... |
Constrain the distance between bob and anchor between min and max | def constrain_length(bob, minlen, maxlen)
dir = bob.location - @anchor
d = dir.mag
# Is it too short?
if d < minlen
dir.normalize!
dir *= minlen
# Reset location and stop from moving (not realistic physics)
bob.location = @anchor + dir
bob.velocity *= 0
elsif d > maxlen... |
Write a method that takes a positive integer, n, as an argument, and displays a right triangle whose sides each have n stars. The hypotenuse of the triangle (the diagonal side in the images below) should have one end at the lowerleft of the triangle, and the other end at the upperright. | def triangle(num)
spaces = num - 1
stars = 1
loop do
puts " "*spaces + "*"*stars
break if stars == num
spaces -= 1
stars += 1
end
end |
This method does the actual permalink escaping. | def escape(string)
result = ((translation_to && translation_from) ? Iconv.iconv(translation_to, translation_from, string) : string).to_s
result.gsub!(/[^\x00-\x7F]+/, '') # Remove anything non-ASCII entirely (e.g. diacritics).
result.gsub!(/[^\w_ \-]+/i, '') # Remove unwanted chars.
result.gsu... |
Only allow a list of trusted parameters through. | def foo38_params
params.require(:foo38).permit(:foo1, :foo2, :foo3, :foo4, :foo5)
end |
PUT /crossword_puzzles/1 PUT /crossword_puzzles/1.json | def update
@crossword_puzzle = CrosswordPuzzle.find(params[:id])
respond_to do |format|
if @crossword_puzzle.update_attributes(params[:crossword_puzzle])
format.html { redirect_to edit_crossword_puzzle_path(@crossword_puzzle), notice: 'Puzzle saved!' }
format.json { head :no_content }
... |
Return the missing translation placeholder | def missing_translation_placeholder field
evaluate_localization_option!(:placeholder, field)
end |
PATCH/PUT /discussions/1 PATCH/PUT /discussions/1.json DELETE /discussions/1 DELETE /discussions/1.json | def destroy
@discussion.destroy
flash[:success] = "Discussion was successfully deleted."
redirect_to discussions_path
end |
author ahmed jihad called to show answer view for questionnaires finds the selected questionnaire Args : | def answer_show
@questionnaire = Questionnaire.find(params[:id])
answer = @questionnaire.answer_questionnaires.build
render 'answer_show'
end |
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.