query
stringlengths 7
9.5k
| document
stringlengths 10
1.07M
| negatives
listlengths 19
19
| metadata
dict |
---|---|---|---|
returns team with highest average goals allowed
|
def worst_defense
@teams.max_by { |team| team.average_goals_allowed }.team_name
end
|
[
"def highest_scoring_visitor\n @teams.max_by { |team| team.average_away_goals }.team_name\n end",
"def most_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.max\n end",
"def most_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).max\n end",
"def average_goals_per_game\n total_goals = @teams.map {|team| team.total_goals_scored}.sum\n total_games = @teams.map {|team| team.home_games}.sum\n (total_goals.to_f / total_games.to_f).round(2)\n end",
"def highest_scoring_home_team\n @teams.max_by { |team| team.average_home_goals }.team_name\n end",
"def fewest_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.min\n end",
"def highest_scoring_home_team\n home_goals = Hash.new(0.00)\n #get sum of away_goals per home team (hash output)\n unique_home_teams_array_helper.each do |team_id|\n self.games.each_value do |game|\n home_goals[team_id] += (game.home_goals) if game.home_team_id == team_id\n end\n end\n\n #turn sum into average\n home_goals.merge!(total_home_games_helper) do |key, oldval, newval|\n (oldval / newval).round(2)\n end\n\n #return highest\n highest_avg_hash = home_goals.max_by do |k, v|\n v\n end\n\n team_name_finder_helper(highest_avg_hash[0])\n\n end",
"def winningest_team\n @teams.max_by { |team| team.total_win_percentage }.team_name\n end",
"def worst_loss(team_id)\n @games.map do |game|\n if game.away_team_id.to_s == team_id\n game.home_goals - game.away_goals\n elsif game.home_team_id.to_s == team_id\n game.away_goals - game.home_goals\n end\n end.compact.max\n end",
"def fewest_goals_scored(team_id)\n get_all_games_from_team(team_id).min_by do |game|\n game.goals\n end.goals\n end",
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end",
"def fewest_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).min\n end",
"def average_goals_per_game\n sum = 0.00\n self.games.each_value do |game|\n sum += (game.home_goals + game.away_goals)\n end\n\n (sum / self.games.length).round(2)\n end",
"def most_goals_scored(team_id)\n most_goals_scored_counter = 0\n int_team_id = team_id.to_i\n self.game_teams.each do |game_team_obj|\n if game_team_obj.team_id == int_team_id\n if game_team_obj.goals > most_goals_scored_counter\n most_goals_scored_counter = game_team_obj.goals\n end\n end\n end\n most_goals_scored_counter\n end",
"def get_team_average(team, scope_name = :is_male)\n result_count = @meeting.meeting_individual_results.for_team(team).send(scope_name.to_sym).has_points.count\n if result_count > 0\n standard_points_sum = @meeting.meeting_individual_results.for_team(team).send(scope_name.to_sym).has_points.sum(:standard_points)\n (standard_points_sum / result_count).round(2)\n else\n result_count\n end\n end",
"def goals_for(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.homeScore\n else\n return self.awayScore\n end\n else\n return 0\n end\n end",
"def avg_of_toryo_turn_max\n s = lose_scope\n s = s.joins(:battle)\n s = s.where(Swars::Battle.arel_table[:final_key].eq(\"TORYO\"))\n if v = s.average(Swars::Battle.arel_table[:turn_max])\n v.to_i\n end\n end",
"def worst_loss(team_id)\n\n #select games team lost and delete rest\n games = games_for_team_helper(team_id).select! do |game|\n if (game.away_team_id == team_id) && (game.away_goals < game.home_goals)\n true\n elsif (game.home_team_id == team_id) && (game.home_goals < game.away_goals)\n true\n else\n false\n end\n end\n\n max_game = games.max_by do |game|\n (game.home_goals - game.away_goals).abs\n end\n\n (max_game.home_goals - max_game.away_goals).abs\n\n end",
"def team_average\n # This version is implemented as a database AVG operation,\n # but it cannot be eager loaded so it results in an extra\n # database query for each project:\n #\n # avg = students_projects.select(:points).average :points\n # avg ? avg.round : 0\n\n # This version programmatically finds the average of the points:\n #self.reload\n no_of_students = self.students_projects.length\n return 0 if no_of_students == 0\n total = 0\n self.students_projects.each { |s| total += s.points }\n (total / no_of_students).round\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns team with highest average away goals
|
def highest_scoring_visitor
@teams.max_by { |team| team.average_away_goals }.team_name
end
|
[
"def most_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).max\n end",
"def highest_scoring_home_team\n home_goals = Hash.new(0.00)\n #get sum of away_goals per home team (hash output)\n unique_home_teams_array_helper.each do |team_id|\n self.games.each_value do |game|\n home_goals[team_id] += (game.home_goals) if game.home_team_id == team_id\n end\n end\n\n #turn sum into average\n home_goals.merge!(total_home_games_helper) do |key, oldval, newval|\n (oldval / newval).round(2)\n end\n\n #return highest\n highest_avg_hash = home_goals.max_by do |k, v|\n v\n end\n\n team_name_finder_helper(highest_avg_hash[0])\n\n end",
"def highest_scoring_home_team\n @teams.max_by { |team| team.average_home_goals }.team_name\n end",
"def average_goals_per_game\n total_goals = @teams.map {|team| team.total_goals_scored}.sum\n total_games = @teams.map {|team| team.home_games}.sum\n (total_goals.to_f / total_games.to_f).round(2)\n end",
"def worst_defense\n @teams.max_by { |team| team.average_goals_allowed }.team_name\n end",
"def most_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.max\n end",
"def worst_loss(team_id)\n @games.map do |game|\n if game.away_team_id.to_s == team_id\n game.home_goals - game.away_goals\n elsif game.home_team_id.to_s == team_id\n game.away_goals - game.home_goals\n end\n end.compact.max\n end",
"def winningest_team\n @teams.max_by { |team| team.total_win_percentage }.team_name\n end",
"def fewest_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.min\n end",
"def fewest_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).min\n end",
"def average_goals_per_game\n sum = 0.00\n self.games.each_value do |game|\n sum += (game.home_goals + game.away_goals)\n end\n\n (sum / self.games.length).round(2)\n end",
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end",
"def goals_for(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.homeScore\n else\n return self.awayScore\n end\n else\n return 0\n end\n end",
"def fewest_goals_scored(team_id)\n get_all_games_from_team(team_id).min_by do |game|\n game.goals\n end.goals\n end",
"def goals_against(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.awayScore\n else\n return self.homeScore\n end\n else\n return 0\n end\n end",
"def worst_loss(team_id)\n\n #select games team lost and delete rest\n games = games_for_team_helper(team_id).select! do |game|\n if (game.away_team_id == team_id) && (game.away_goals < game.home_goals)\n true\n elsif (game.home_team_id == team_id) && (game.home_goals < game.away_goals)\n true\n else\n false\n end\n end\n\n max_game = games.max_by do |game|\n (game.home_goals - game.away_goals).abs\n end\n\n (max_game.home_goals - max_game.away_goals).abs\n\n end",
"def most_goals_scored(team_id)\n most_goals_scored_counter = 0\n int_team_id = team_id.to_i\n self.game_teams.each do |game_team_obj|\n if game_team_obj.team_id == int_team_id\n if game_team_obj.goals > most_goals_scored_counter\n most_goals_scored_counter = game_team_obj.goals\n end\n end\n end\n most_goals_scored_counter\n end",
"def avg_of_toryo_turn_max\n s = lose_scope\n s = s.joins(:battle)\n s = s.where(Swars::Battle.arel_table[:final_key].eq(\"TORYO\"))\n if v = s.average(Swars::Battle.arel_table[:turn_max])\n v.to_i\n end\n end",
"def lowest_scoring_home_team\n foo = {}\n\n teams.each do |team|\n team_id = team['team_id']\n team_name = team['teamName']\n\n foo[team_name] = average_goals_home(team_id)\n end\n\n foo.max_by { |_k, v| -v }[0]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns team with highest average home goals
|
def highest_scoring_home_team
@teams.max_by { |team| team.average_home_goals }.team_name
end
|
[
"def highest_scoring_home_team\n home_goals = Hash.new(0.00)\n #get sum of away_goals per home team (hash output)\n unique_home_teams_array_helper.each do |team_id|\n self.games.each_value do |game|\n home_goals[team_id] += (game.home_goals) if game.home_team_id == team_id\n end\n end\n\n #turn sum into average\n home_goals.merge!(total_home_games_helper) do |key, oldval, newval|\n (oldval / newval).round(2)\n end\n\n #return highest\n highest_avg_hash = home_goals.max_by do |k, v|\n v\n end\n\n team_name_finder_helper(highest_avg_hash[0])\n\n end",
"def average_goals_per_game\n total_goals = @teams.map {|team| team.total_goals_scored}.sum\n total_games = @teams.map {|team| team.home_games}.sum\n (total_goals.to_f / total_games.to_f).round(2)\n end",
"def highest_scoring_visitor\n @teams.max_by { |team| team.average_away_goals }.team_name\n end",
"def lowest_scoring_home_team\n foo = {}\n\n teams.each do |team|\n team_id = team['team_id']\n team_name = team['teamName']\n\n foo[team_name] = average_goals_home(team_id)\n end\n\n foo.max_by { |_k, v| -v }[0]\n end",
"def most_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).max\n end",
"def average_goals_per_game\n sum = 0.00\n self.games.each_value do |game|\n sum += (game.home_goals + game.away_goals)\n end\n\n (sum / self.games.length).round(2)\n end",
"def goals_for(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.homeScore\n else\n return self.awayScore\n end\n else\n return 0\n end\n end",
"def worst_defense\n @teams.max_by { |team| team.average_goals_allowed }.team_name\n end",
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end",
"def lowest_scoring_home_team\n @teams.min_by { |team| team.average_home_goals }.team_name\n end",
"def goals_against(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.awayScore\n else\n return self.homeScore\n end\n else\n return 0\n end\n end",
"def most_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.max\n end",
"def winningest_team\n @teams.max_by { |team| team.total_win_percentage }.team_name\n end",
"def fewest_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).min\n end",
"def worst_loss(team_id)\n @games.map do |game|\n if game.away_team_id.to_s == team_id\n game.home_goals - game.away_goals\n elsif game.home_team_id.to_s == team_id\n game.away_goals - game.home_goals\n end\n end.compact.max\n end",
"def fewest_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.min\n end",
"def average_goals_by_season\n goals_by_season = @games.group_by { |game| game.season.to_s }\n goals_by_season.each do |season, games|\n season_goals = games.map { |game| game.home_goals + game.away_goals }.sum\n goals_by_season[season] = (season_goals.to_f / games.count.to_f).round(2)\n end\n end",
"def percentage_home_wins\n home_wins = @teams.map { |team| team.home_wins }.sum\n home_games = @teams.map { |team| team.home_games }.sum\n (home_wins.to_f / home_games.to_f).round(2)\n end",
"def percentage_home_wins\n home_wins = 0\n self.games.each_value do |object|\n if object.home_goals > object.away_goals\n home_wins += 1\n end\n end\n\n (home_wins / (self.games.length).to_f).round(2)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns team with lowest average home goals
|
def lowest_scoring_home_team
@teams.min_by { |team| team.average_home_goals }.team_name
end
|
[
"def lowest_scoring_home_team\n foo = {}\n\n teams.each do |team|\n team_id = team['team_id']\n team_name = team['teamName']\n\n foo[team_name] = average_goals_home(team_id)\n end\n\n foo.max_by { |_k, v| -v }[0]\n end",
"def lowest_total_score\n total_game_scores = games.map { |game| game.home_goals + game.away_goals}\n total_game_scores.min\n end",
"def highest_scoring_home_team\n home_goals = Hash.new(0.00)\n #get sum of away_goals per home team (hash output)\n unique_home_teams_array_helper.each do |team_id|\n self.games.each_value do |game|\n home_goals[team_id] += (game.home_goals) if game.home_team_id == team_id\n end\n end\n\n #turn sum into average\n home_goals.merge!(total_home_games_helper) do |key, oldval, newval|\n (oldval / newval).round(2)\n end\n\n #return highest\n highest_avg_hash = home_goals.max_by do |k, v|\n v\n end\n\n team_name_finder_helper(highest_avg_hash[0])\n\n end",
"def average_goals_per_game\n total_goals = @teams.map {|team| team.total_goals_scored}.sum\n total_games = @teams.map {|team| team.home_games}.sum\n (total_goals.to_f / total_games.to_f).round(2)\n end",
"def fewest_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).min\n end",
"def fewest_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.min\n end",
"def average_goals_per_game\n sum = 0.00\n self.games.each_value do |game|\n sum += (game.home_goals + game.away_goals)\n end\n\n (sum / self.games.length).round(2)\n end",
"def highest_scoring_home_team\n @teams.max_by { |team| team.average_home_goals }.team_name\n end",
"def team_average\n # This version is implemented as a database AVG operation,\n # but it cannot be eager loaded so it results in an extra\n # database query for each project:\n #\n # avg = students_projects.select(:points).average :points\n # avg ? avg.round : 0\n\n # This version programmatically finds the average of the points:\n #self.reload\n no_of_students = self.students_projects.length\n return 0 if no_of_students == 0\n total = 0\n self.students_projects.each { |s| total += s.points }\n (total / no_of_students).round\n end",
"def goals_for(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.homeScore\n else\n return self.awayScore\n end\n else\n return 0\n end\n end",
"def percentage_home_wins\n home_wins = @teams.map { |team| team.home_wins }.sum\n home_games = @teams.map { |team| team.home_games }.sum\n (home_wins.to_f / home_games.to_f).round(2)\n end",
"def fewest_goals_scored(team_id)\n get_all_games_from_team(team_id).min_by do |game|\n game.goals\n end.goals\n end",
"def average_goals_by_season\n goals_by_season = @games.group_by { |game| game.season.to_s }\n goals_by_season.each do |season, games|\n season_goals = games.map { |game| game.home_goals + game.away_goals }.sum\n goals_by_season[season] = (season_goals.to_f / games.count.to_f).round(2)\n end\n end",
"def percentage_home_wins\n home_wins = 0\n self.games.each_value do |object|\n if object.home_goals > object.away_goals\n home_wins += 1\n end\n end\n\n (home_wins / (self.games.length).to_f).round(2)\n end",
"def goals_against(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.awayScore\n else\n return self.homeScore\n end\n else\n return 0\n end\n end",
"def average_goals_by_season\n seasons_goals = Hash.new(0.00)\n\n unique_seasons_array_helper.each do |season|\n self.games.each_value do |game|\n seasons_goals[season] += (game.home_goals + game.away_goals) if game.season == season\n end\n end\n\n seasons_goals.merge!(count_of_games_by_season) do |key, oldval, newval|\n (oldval / newval).round(2)\n end\n\n end",
"def get_team_average(team, scope_name = :is_male)\n result_count = @meeting.meeting_individual_results.for_team(team).send(scope_name.to_sym).has_points.count\n if result_count > 0\n standard_points_sum = @meeting.meeting_individual_results.for_team(team).send(scope_name.to_sym).has_points.sum(:standard_points)\n (standard_points_sum / result_count).round(2)\n else\n result_count\n end\n end",
"def smallest_team\n self.teams.min{|t1,t2| t1.runners.size <=> t2.runners.size }\n end",
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns team with highest win percentage
|
def winningest_team
@teams.max_by { |team| team.total_win_percentage }.team_name
end
|
[
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end",
"def highest_scoring_visitor\n @teams.max_by { |team| team.average_away_goals }.team_name\n end",
"def highest_scoring_home_team\n @teams.max_by { |team| team.average_home_goals }.team_name\n end",
"def worst_defense\n @teams.max_by { |team| team.average_goals_allowed }.team_name\n end",
"def winning_score\n return 0 unless winning_team_game\n winning_team_game.total_score\n end",
"def best_season(team_id)\n team_id = team_id.to_i\n team = @teams.select { |each_team| each_team.team_id == team_id }.first\n team.season_win_percentages.max_by { |season, percentage| percentage }.first.to_s\n end",
"def most_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).max\n end",
"def winning_team\n brooklyn_players = team_player_info(\"Brooklyn Nets\")\n charlotte_players = team_player_info(\"Charlotte Hornets\")\n\n brooklyn_scores = brooklyn_players.map {|stats|\n stats[:points]}\n\n charlotte_scores = charlotte_players.map {|stats|\n stats[:points]}\n \n brooklyn_total = brooklyn_scores.sum\n charlotte_total = charlotte_scores.sum\n\n charlotte_total > brooklyn_total ? (return charlotte_total) : (return brooklyn_total)\nend",
"def most_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.max\n end",
"def average_win_percentage(team_id)\n team_id = team_id.to_i\n team = @teams.select { |each_team| each_team.team_id == team_id }.first\n team.total_win_percentage.round(2)\n end",
"def worst_season(team_id)\n team_id = team_id.to_i\n team = @teams.select { |each_team| each_team.team_id == team_id }.first\n team.season_win_percentages.min_by { |season, percentage| percentage }.first.to_s\n end",
"def find_best_score(total_per_player)\n best_score = 0\n winner = ''\n total_per_player.each do |player_name,total|\n\n if total > best_score\n best_score = total\n winner = player_name\n end\n end\n return winner\n end",
"def highest_player_score\n players.max_by{|player| player.score}.score\n end",
"def get_winner\n id_to_wins = calculate_outcomes\n #Finally, return the team with the most wins.\n winning_team_id = nil;\n id_to_wins.each { |id, wins| \n if(winning_team_id == nil) || id_to_wins[winning_team_id] < wins\n winning_team_id = id\n end \n }\n \n return winning_team_id;\n end",
"def worst_loss(team_id)\n @games.map do |game|\n if game.away_team_id.to_s == team_id\n game.home_goals - game.away_goals\n elsif game.home_team_id.to_s == team_id\n game.away_goals - game.home_goals\n end\n end.compact.max\n end",
"def winning_team\n if homeTeamPoints.sum > awayTeamPoints.sum\n \"Brooklyn Nets\"\n else\n \"Charlotte Hornets\"\n end\nend",
"def games_win_percentage(team_id, games)\n total = games.count\n won = 0\n games.each do |game|\n if (team_id == game.away_team_id) && game.outcome.match?(/away win/)\n won += 1\n elsif (team_id == game.home_team_id) && game.outcome.match?(/home win/)\n won += 1\n else\n won += 0\n end\n end\n won.to_f / total\n end",
"def winningest_coach(season)\n coach_win_percentage_hash = coach_win_percentage_helper(season)\n best_win_percentage = 0.0\n best_coach = \"\"\n\n coach_win_percentage_hash.each do |coach, win_percentage|\n if win_percentage > best_win_percentage\n best_win_percentage = win_percentage\n best_coach = coach\n end\n end\n best_coach\n end",
"def high_score\n if self.end_date < Date.today\n self.teams.max_by { |team| team.score }.score\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns the season with the highest win percentage for a team
|
def best_season(team_id)
team_id = team_id.to_i
team = @teams.select { |each_team| each_team.team_id == team_id }.first
team.season_win_percentages.max_by { |season, percentage| percentage }.first.to_s
end
|
[
"def worst_season(team_id)\n team_id = team_id.to_i\n team = @teams.select { |each_team| each_team.team_id == team_id }.first\n team.season_win_percentages.min_by { |season, percentage| percentage }.first.to_s\n end",
"def winningest_team\n @teams.max_by { |team| team.total_win_percentage }.team_name\n end",
"def worst_coach(season)\n coach_win_percentage_hash = coach_win_percentage_helper(season)\n worst_win_percentage = 2.0\n worst_coach = \"\"\n\n coach_win_percentage_hash.each do |coach, win_percentage|\n if win_percentage < worst_win_percentage\n worst_win_percentage = win_percentage\n worst_coach = coach\n end\n end\n worst_coach\n end",
"def winningest_coach(season)\n coach_win_percentage_hash = coach_win_percentage_helper(season)\n best_win_percentage = 0.0\n best_coach = \"\"\n\n coach_win_percentage_hash.each do |coach, win_percentage|\n if win_percentage > best_win_percentage\n best_win_percentage = win_percentage\n best_coach = coach\n end\n end\n best_coach\n end",
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end",
"def season_with_most_games\n seasons = @games.group_by { |game| game.season }\n seasons.max_by { |season, games| games.count }.first\n end",
"def highest_scoring_visitor\n @teams.max_by { |team| team.average_away_goals }.team_name\n end",
"def highest_scoring_home_team\n @teams.max_by { |team| team.average_home_goals }.team_name\n end",
"def worst_defense\n @teams.max_by { |team| team.average_goals_allowed }.team_name\n end",
"def get_winner\n id_to_wins = calculate_outcomes\n #Finally, return the team with the most wins.\n winning_team_id = nil;\n id_to_wins.each { |id, wins| \n if(winning_team_id == nil) || id_to_wins[winning_team_id] < wins\n winning_team_id = id\n end \n }\n \n return winning_team_id;\n end",
"def high_score\n if self.end_date < Date.today\n self.teams.max_by { |team| team.score }.score\n end\n end",
"def winning_score\n return 0 unless winning_team_game\n winning_team_game.total_score\n end",
"def season_with_fewest_games\n seasons = @games.group_by { |game| game.season }\n seasons.min_by { |season, games| games.count }.first\n end",
"def worst_loss(team_id)\n @games.map do |game|\n if game.away_team_id.to_s == team_id\n game.home_goals - game.away_goals\n elsif game.home_team_id.to_s == team_id\n game.away_goals - game.home_goals\n end\n end.compact.max\n end",
"def average_win_percentage(team_id)\n team_id = team_id.to_i\n team = @teams.select { |each_team| each_team.team_id == team_id }.first\n team.total_win_percentage.round(2)\n end",
"def get_team_worst_standard(team, scope_name = :is_male)\n if @meeting.meeting_individual_results.for_team(team).is_valid.send(scope_name.to_sym).has_points.count > 0\n @meeting.meeting_individual_results.for_team(team)\n .is_valid.send(scope_name.to_sym)\n .has_points.unscope(:order)\n .order('standard_points ASC').first\n .standard_points\n else\n 0.00\n end\n end",
"def highest_player_score\n players.max_by{|player| player.score}.score\n end",
"def most_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.max\n end",
"def worst_loss(team_id)\n foo = {}\n\n opponents(team_id).each do |opponent|\n opponent_name = opponent['teamName']\n\n foo[opponent_name] =\n game_score_difference(team_id, opponent, :loss) || 0\n end\n\n foo.min_by { |_k, v| -v }[1]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns the season with the lowest win percentage for a team
|
def worst_season(team_id)
team_id = team_id.to_i
team = @teams.select { |each_team| each_team.team_id == team_id }.first
team.season_win_percentages.min_by { |season, percentage| percentage }.first.to_s
end
|
[
"def best_season(team_id)\n team_id = team_id.to_i\n team = @teams.select { |each_team| each_team.team_id == team_id }.first\n team.season_win_percentages.max_by { |season, percentage| percentage }.first.to_s\n end",
"def lowest_scoring_home_team\n @teams.min_by { |team| team.average_home_goals }.team_name\n end",
"def season_with_fewest_games\n seasons = @games.group_by { |game| game.season }\n seasons.min_by { |season, games| games.count }.first\n end",
"def winningest_coach(season)\n coach_win_percentage_hash = coach_win_percentage_helper(season)\n best_win_percentage = 0.0\n best_coach = \"\"\n\n coach_win_percentage_hash.each do |coach, win_percentage|\n if win_percentage > best_win_percentage\n best_win_percentage = win_percentage\n best_coach = coach\n end\n end\n best_coach\n end",
"def worst_coach(season)\n coach_win_percentage_hash = coach_win_percentage_helper(season)\n worst_win_percentage = 2.0\n worst_coach = \"\"\n\n coach_win_percentage_hash.each do |coach, win_percentage|\n if win_percentage < worst_win_percentage\n worst_win_percentage = win_percentage\n worst_coach = coach\n end\n end\n worst_coach\n end",
"def winningest_team\n @teams.max_by { |team| team.total_win_percentage }.team_name\n end",
"def lowest_scoring_home_team\n foo = {}\n\n teams.each do |team|\n team_id = team['team_id']\n team_name = team['teamName']\n\n foo[team_name] = average_goals_home(team_id)\n end\n\n foo.max_by { |_k, v| -v }[0]\n end",
"def lowest_total_score\n total_game_scores = games.map { |game| game.home_goals + game.away_goals}\n total_game_scores.min\n end",
"def first_season\n seasons.inject { |a, b| a.index.to_i < b.index.to_i && a.index.to_i > 0 ? a : b }\n end",
"def minimum_rounds(driver)\n Algorithm::Swiss.minimum_rounds(driver.seeded_teams.length)\n end",
"def average_win_percentage(team_id)\n all_percents = []\n win_percent_per_season(team_id).each {|season, win_percentage| all_percents << win_percentage}\n all_percents.sum / all_percents.length\n end",
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end",
"def average_win_percentage(team_id)\n team_id = team_id.to_i\n team = @teams.select { |each_team| each_team.team_id == team_id }.first\n team.total_win_percentage.round(2)\n end",
"def winning_score\n return 0 unless winning_team_game\n winning_team_game.total_score\n end",
"def smallest_team\n self.teams.min{|t1,t2| t1.runners.size <=> t2.runners.size }\n end",
"def least_popular_venue\n venues = @games.group_by { |game| game.venue}\n venues.min_by { |venue, games| games.count }.first\n end",
"def get_team_best_standard(team, scope_name = :is_male)\n if @meeting.meeting_individual_results.for_team(team).is_valid.send(scope_name.to_sym).has_points.count > 0\n @meeting.meeting_individual_results.for_team(team).is_valid\n .send(scope_name.to_sym).has_points.unscope(:order)\n .order('standard_points DESC').first\n .standard_points\n else\n 0.00\n end\n end",
"def get_winner\n id_to_wins = calculate_outcomes\n #Finally, return the team with the most wins.\n winning_team_id = nil;\n id_to_wins.each { |id, wins| \n if(winning_team_id == nil) || id_to_wins[winning_team_id] < wins\n winning_team_id = id\n end \n }\n \n return winning_team_id;\n end",
"def score_per_winner\n number_of_winners = @players.select { |p| p.points == minimum_points }.count\n (total_score / number_of_winners.to_i)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
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
|
[
"def average_win_percentage(team_id)\n (total_games_won(team_id) / total_games_played(team_id)).round(2)\n end",
"def average_win_percentage(team_id)\n all_percents = []\n win_percent_per_season(team_id).each {|season, win_percentage| all_percents << win_percentage}\n all_percents.sum / all_percents.length\n end",
"def average_win_percentage(team_id)\n (total_wins_count_helper(team_id) / games_for_team_helper(team_id).length.to_f).round(2)\n end",
"def games_win_percentage(team_id, games)\n total = games.count\n won = 0\n games.each do |game|\n if (team_id == game.away_team_id) && game.outcome.match?(/away win/)\n won += 1\n elsif (team_id == game.home_team_id) && game.outcome.match?(/home win/)\n won += 1\n else\n won += 0\n end\n end\n won.to_f / total\n end",
"def average_goals_per_game\n total_goals = @teams.map {|team| team.total_goals_scored}.sum\n total_games = @teams.map {|team| team.home_games}.sum\n (total_goals.to_f / total_games.to_f).round(2)\n end",
"def percentage_home_wins\n home_wins = @teams.map { |team| team.home_wins }.sum\n home_games = @teams.map { |team| team.home_games }.sum\n (home_wins.to_f / home_games.to_f).round(2)\n end",
"def get_opponents_average_win_percentage\n opponents_win_percentages = 0.0\n opponent_ids = self.get_opponent_ids\n opponents_matchup_ids = self.get_opponents_matchup_ids\n opponent_ids.each do |i|\n opponents_win_count = Matchup.where({\"id\" => opponents_matchup_ids}, {\"winner_id\" => i}).count.to_f\n opponents_loss_count = Matchup.where({\"id\" => opponents_matchup_ids}, {\"loser_id\" => i}).count.to_f\n opponents_win_percent = opponents_win_count/(opponents_win_count + opponents_loss_count)\n opponents_win_percentages += opponents_win_percent\n end\n return opponents_win_percentages#/(opponent_ids.count)\n end",
"def percentage_visitor_wins\n visitor_wins = @teams.map { |team| team.away_wins }.sum\n visitor_games = @teams.map { |team| team.away_games }.sum\n (visitor_wins.to_f / visitor_games.to_f).round(2)\n end",
"def average_goals_per_game\n sum = 0.00\n self.games.each_value do |game|\n sum += (game.home_goals + game.away_goals)\n end\n\n (sum / self.games.length).round(2)\n end",
"def average_goals_by_season\n goals_by_season = @games.group_by { |game| game.season.to_s }\n goals_by_season.each do |season, games|\n season_goals = games.map { |game| game.home_goals + game.away_goals }.sum\n goals_by_season[season] = (season_goals.to_f / games.count.to_f).round(2)\n end\n end",
"def calculate_owp(games_by_team)\n if games.count > 0\n sum_owp = games.inject(0.0) do |sum, game|\n sked = opponent_schedule game.opponent, games_by_team\n ow = sked.inject(0) { |wins, og| wins + og.wins }\n sum + (sked.empty? ? 0.0 : (ow.to_f / sked.count.to_f))\n end\n @owp = sum_owp / games.count.to_f\n end\n end",
"def average_goals_by_season\n seasons_goals = Hash.new(0.00)\n\n unique_seasons_array_helper.each do |season|\n self.games.each_value do |game|\n seasons_goals[season] += (game.home_goals + game.away_goals) if game.season == season\n end\n end\n\n seasons_goals.merge!(count_of_games_by_season) do |key, oldval, newval|\n (oldval / newval).round(2)\n end\n\n end",
"def percent_wins(wins)\n ((wins.to_f / @num_games.to_f) * 100).round(4)\n end",
"def percentage_home_wins\n home_wins = 0\n self.games.each_value do |object|\n if object.home_goals > object.away_goals\n home_wins += 1\n end\n end\n\n (home_wins / (self.games.length).to_f).round(2)\n end",
"def calculate_winning_percentage\n games_played = self.won + self.lost\n if games_played == 0\n self.winning_percentage = 0.0\n else\n self.winning_percentage = (self.won*1.0)/games_played\n end\n end",
"def get_team_average(team, scope_name = :is_male)\n result_count = @meeting.meeting_individual_results.for_team(team).send(scope_name.to_sym).has_points.count\n if result_count > 0\n standard_points_sum = @meeting.meeting_individual_results.for_team(team).send(scope_name.to_sym).has_points.sum(:standard_points)\n (standard_points_sum / result_count).round(2)\n else\n result_count\n end\n end",
"def winning_score\n return 0 unless winning_team_game\n winning_team_game.total_score\n end",
"def opponent_avg_score win_condition\n score_array = opponent_score_array win_condition\n Stats.average score_array\n end",
"def doubles_wins\n total_wins = 0\n get_teams.each{ |team| total_wins += team.doubles_results.sum(:win)}\n total_wins\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns the highest number of goals a particular team has scored in a game
|
def most_goals_scored(team_id)
team_id = team_id.to_i
goals_per_game = @game_teams.map do |game|
if game.team_id == team_id
game.goals
end
end
goals_per_game.compact.max
end
|
[
"def most_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).max\n end",
"def most_goals_scored(team_id)\n most_goals_scored_counter = 0\n int_team_id = team_id.to_i\n self.game_teams.each do |game_team_obj|\n if game_team_obj.team_id == int_team_id\n if game_team_obj.goals > most_goals_scored_counter\n most_goals_scored_counter = game_team_obj.goals\n end\n end\n end\n most_goals_scored_counter\n end",
"def fewest_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.min\n end",
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end",
"def fewest_goals_scored(team_id)\n get_all_games_from_team(team_id).min_by do |game|\n game.goals\n end.goals\n end",
"def fewest_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).min\n end",
"def highest_scoring_visitor\n @teams.max_by { |team| team.average_away_goals }.team_name\n end",
"def worst_loss(team_id)\n @games.map do |game|\n if game.away_team_id.to_s == team_id\n game.home_goals - game.away_goals\n elsif game.home_team_id.to_s == team_id\n game.away_goals - game.home_goals\n end\n end.compact.max\n end",
"def winningest_team\n @teams.max_by { |team| team.total_win_percentage }.team_name\n end",
"def highest_scoring_home_team\n @teams.max_by { |team| team.average_home_goals }.team_name\n end",
"def worst_defense\n @teams.max_by { |team| team.average_goals_allowed }.team_name\n end",
"def goals_for(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.homeScore\n else\n return self.awayScore\n end\n else\n return 0\n end\n end",
"def goals_against(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.awayScore\n else\n return self.homeScore\n end\n else\n return 0\n end\n end",
"def find_higest_score(player)\n player.maximum(:score)\n end",
"def total_team_goals(equipo)\n @team.select { |player| player[:equipo] == equipo }.sum {|h| h[:goles].to_i }\n end",
"def winning_score\n return 0 unless winning_team_game\n winning_team_game.total_score\n end",
"def biggest_blowout\n difference = @game_instances.map do |game|\n (game.away_goals - game.home_goals).abs\n end\n difference.uniq.max\n end",
"def mostSteals\n players.max_by do|name, stats|\n stats[:steals]\n end\nend",
"def rebounds_for_largest_shoe_size(game)\n max_player = nil\n game.each do |team, team_hash|\n team_hash[:players].each do |player, player_hash|\n max_player ||= player_hash\n max_player = player_hash if player_hash[:shoe_size] > max_player[:shoe_size]\n end\n end\n\n max_player[:stats][:rebounds]\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns the lowest number of goals a particular team has scored in a game
|
def fewest_goals_scored(team_id)
team_id = team_id.to_i
goals_per_game = @game_teams.map do |game|
if game.team_id == team_id
game.goals
end
end
goals_per_game.compact.min
end
|
[
"def fewest_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).min\n end",
"def fewest_goals_scored(team_id)\n get_all_games_from_team(team_id).min_by do |game|\n game.goals\n end.goals\n end",
"def lowest_total_score\n total_game_scores = games.map { |game| game.home_goals + game.away_goals}\n total_game_scores.min\n end",
"def most_goals_scored(team_id)\n most_goals_scored_counter = 0\n int_team_id = team_id.to_i\n self.game_teams.each do |game_team_obj|\n if game_team_obj.team_id == int_team_id\n if game_team_obj.goals > most_goals_scored_counter\n most_goals_scored_counter = game_team_obj.goals\n end\n end\n end\n most_goals_scored_counter\n end",
"def most_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).max\n end",
"def most_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.max\n end",
"def lowest_scoring_home_team\n @teams.min_by { |team| team.average_home_goals }.team_name\n end",
"def minimum_match_count\n lowest = @set.length\n @possible_guesses.each do |possible|\n count = highest_match_count(possible)\n lowest = count if count < lowest\n end\n lowest\n end",
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end",
"def smallest_team\n self.teams.min{|t1,t2| t1.runners.size <=> t2.runners.size }\n end",
"def winning_score\n return 0 unless winning_team_game\n winning_team_game.total_score\n end",
"def lowest_scoring_home_team\n foo = {}\n\n teams.each do |team|\n team_id = team['team_id']\n team_name = team['teamName']\n\n foo[team_name] = average_goals_home(team_id)\n end\n\n foo.max_by { |_k, v| -v }[0]\n end",
"def goals_for(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.homeScore\n else\n return self.awayScore\n end\n else\n return 0\n end\n end",
"def winning_team\n brooklyn_players = team_player_info(\"Brooklyn Nets\")\n charlotte_players = team_player_info(\"Charlotte Hornets\")\n\n brooklyn_scores = brooklyn_players.map {|stats|\n stats[:points]}\n\n charlotte_scores = charlotte_players.map {|stats|\n stats[:points]}\n \n brooklyn_total = brooklyn_scores.sum\n charlotte_total = charlotte_scores.sum\n\n charlotte_total > brooklyn_total ? (return charlotte_total) : (return brooklyn_total)\nend",
"def goals_scored_by_team(team_id)\n goals_scored = []\n games_by_team(team_id).each do |game|\n if team_id == game.away_team_id\n goals_scored << game.away_goals.to_i\n else team_id == game.home_team_id\n goals_scored << game.home_goals.to_i\n end\n end\n goals_scored\n end",
"def winning_team\r\n total_points = 0\r\n win_team = ''\r\n game_hash.each do |home_away, keys|\r\n team_points = 0\r\n team_name = game_hash[home_away][:team_name]\r\n keys[:players].each do |player|\r\n points = player[:points]\r\n team_points += points\r\n end\r\n win_team, total_points = team_name, team_points if team_points > total_points\r\n end\r\n return win_team\r\nend",
"def percentage_home_wins\n home_wins = 0\n self.games.each_value do |object|\n if object.home_goals > object.away_goals\n home_wins += 1\n end\n end\n\n (home_wins / (self.games.length).to_f).round(2)\n end",
"def winningest_team\n @teams.max_by { |team| team.total_win_percentage }.team_name\n end",
"def goals_against(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.awayScore\n else\n return self.homeScore\n end\n else\n return 0\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
returns the biggest difference between team goals and opponent goals for a loss for the given team
|
def worst_loss(team_id)
@games.map do |game|
if game.away_team_id.to_s == team_id
game.home_goals - game.away_goals
elsif game.home_team_id.to_s == team_id
game.away_goals - game.home_goals
end
end.compact.max
end
|
[
"def worst_loss(team_id)\n\n #select games team lost and delete rest\n games = games_for_team_helper(team_id).select! do |game|\n if (game.away_team_id == team_id) && (game.away_goals < game.home_goals)\n true\n elsif (game.home_team_id == team_id) && (game.home_goals < game.away_goals)\n true\n else\n false\n end\n end\n\n max_game = games.max_by do |game|\n (game.home_goals - game.away_goals).abs\n end\n\n (max_game.home_goals - max_game.away_goals).abs\n\n end",
"def worst_loss(team_id)\n foo = {}\n\n opponents(team_id).each do |opponent|\n opponent_name = opponent['teamName']\n\n foo[opponent_name] =\n game_score_difference(team_id, opponent, :loss) || 0\n end\n\n foo.min_by { |_k, v| -v }[1]\n end",
"def winningest_team\n @teams.max_by { |team| team.total_win_percentage }.team_name\n end",
"def worst_defense\n @teams.max_by { |team| team.average_goals_allowed }.team_name\n end",
"def winning_team_game\n self.team_games.sort_by { |team_game| team_game.total_score }.last\n end",
"def goal_difference\n p1 = calculate_score(team1)\n p2 = calculate_score(team2)\n\n return 0 if p1.nil? or p2.nil?\n\n diff = p1 - p2\n\n diff_1 = diff\n diff_1 = 0 if diff_1 < 0\n\n # The goal difference for second team is the inverse\n diff_2 = -diff\n diff_2 = 0 if diff_2 < 0\n\n [diff_1, diff_2]\n end",
"def highest_scoring_visitor\n @teams.max_by { |team| team.average_away_goals }.team_name\n end",
"def goals_against(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.awayScore\n else\n return self.homeScore\n end\n else\n return 0\n end\n end",
"def most_goals_scored(team_id)\n (away_goals_scored(team_id) + home_goals_scored(team_id)).max\n end",
"def most_goals_scored(team_id)\n team_id = team_id.to_i\n goals_per_game = @game_teams.map do |game|\n if game.team_id == team_id\n game.goals\n end\n end\n goals_per_game.compact.max\n end",
"def goals_for(team)\n valid = ((team == self.home_team or team == self.away_team) and self.final)\n\n if (valid)\n if (self.home_team == team)\n return self.homeScore\n else\n return self.awayScore\n end\n else\n return 0\n end\n end",
"def goal_difference\n total_diff = 0\n\n wattball_matches_as_team1.each do |match|\n total_diff += match.goal_difference[0]\n end\n\n wattball_matches_as_team2.each do |match|\n total_diff += match.goal_difference[1]\n end\n \n total_diff\n end",
"def highest_scoring_home_team\n @teams.max_by { |team| team.average_home_goals }.team_name\n end",
"def ft_goal_difference(game)\n h_score = game[\"FTHG\"].to_i\n a_score = game[\"FTAG\"].to_i\n\n difference = (h_score - a_score).abs\n\n return difference\nend",
"def opponent_score(team_id)\n if team_id == self.away_nfl_team_id\n return self.home_score\n elsif team_id = self.home_nfl_team_id\n return self.away_score\n else\n return nil\n end\n end",
"def get_winner\n id_to_wins = calculate_outcomes\n #Finally, return the team with the most wins.\n winning_team_id = nil;\n id_to_wins.each { |id, wins| \n if(winning_team_id == nil) || id_to_wins[winning_team_id] < wins\n winning_team_id = id\n end \n }\n \n return winning_team_id;\n end",
"def doubles_losses\n total_wins = 0\n get_teams.each {|team| total_wins += team.doubles_results.sum(:loss)}\n total_wins\n end",
"def biggest_blowout\n difference = @game_instances.map do |game|\n (game.away_goals - game.home_goals).abs\n end\n difference.uniq.max\n end",
"def winning_team\r\n total_points = 0\r\n win_team = ''\r\n game_hash.each do |home_away, keys|\r\n team_points = 0\r\n team_name = game_hash[home_away][:team_name]\r\n keys[:players].each do |player|\r\n points = player[:points]\r\n team_points += points\r\n end\r\n win_team, total_points = team_name, team_points if team_points > total_points\r\n end\r\n return win_team\r\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /fault_books GET /fault_books.json
|
def index
@fault_books = FaultBook.where(:truck_fleet_id => current_user.truck_fleet.id)
@fault_books = FaultBook.belongs_to_truck_fleet(current_user.truck_fleet, @fault_books) if current_user.admin?
respond_to do |format|
format.html # index.html.erb
format.json { render json: @fault_books }
end
end
|
[
"def index\n if params[:book_id]\n @book_suggestions = find_book.book_suggestions\n render json: @book_suggestions\n else\n @book_suggestions = BookSuggestion.all\n render json: @book_suggestions\n end\n end",
"def fetch_books(term)\n response = RestClient.get(\"https://www.googleapis.com/books/v1/volumes?q=#{term}\")\n\n JSON.parse(response.body)\nend",
"def index\n @books = get_books()\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @books }\n end\n end",
"def index\n @provided_books = ProvidedBook.all\n end",
"def index\n @books = Book.get_avaible_books\n end",
"def get_bookflows(book_id)\n self.http_get('/api/books/' + book_id + '/bookflows')\n end",
"def index\n @faults = Fault.all\n end",
"def book\n fetch('harry_potter.books')\n end",
"def cmd_get_faults argv\n setup argv\n uuid = @hash['uuid']\n response = @api.get_faults(uuid)\n if response.is_a?(Array)\n response.each do | r |\n msg r\n end\n else\n msg response\n end\n return response\n end",
"def index\n @faults = Fault.all\n respond_to do |format|\n format.json {\n render :json => @faults.to_json(methods: :system_name)\n }\n end\n end",
"def getbook\n \n end",
"def show\n @library_book = LibraryBook.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @library_book }\n end\n end",
"def index\n render json: user_shelf.books\n end",
"def show\n @books_on_loan = BooksOnLoan.find(params[:id])\n respond_to do |format|\n format.json { render json: @books_on_loan }\n end\n end",
"def index\n @books = Book.all\n render json: @books\n end",
"def index\n @lendbooks = Lendbook.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @lendbooks }\n end\n end",
"def search_specifc_book(id_book,book_title,book_id,book_publishDate)\n @response = self.class.get(\"/Books/#{id_book}\",\n :headers => {\"Content-Type\": 'application/json; charset=utf-8; v=1.0', \"path\": \"#{$id_book}\"}) \n $book_title = @response[\"title\"]\n $book_id = @response[\"id\"]\n end",
"def index\n @death_record_books = DeathRecordBook.all\n @death_record_books = DeathRecordBook.order(params[:sort])\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @death_record_books }\n end\n end",
"def bible_books_helper\n res = {}\n req = Net::HTTP.get_response(URI.parse('https://getbible.net/index.php?option=com_getbible&task=bible.books&format=json&v=kjv'))\n JSON.parse(req.body[1...-2]).map{|book|\n req2 = Net::HTTP.get_response(URI.parse(\"https://getbible.net/index.php?option=com_getbible&task=bible.chapter&format=json&v=asv&nr=#{book['book_nr']}\"))\n book['chapters'] = JSON.parse(req2.body[1...-2]).count\n res[book['ref']] = book\n }\n res\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /fault_books POST /fault_books.json
|
def create
@fault_book = FaultBook.new(params[:fault_book])
@fault_book.truck_fleet_id = @fault_book.fleet.truck_fleet_id
respond_to do |format|
if @fault_book.save
s = Serviceable.find_by_fleet_id(params['fault_book']['fleet_id'])
s.next_service_date = @fault_book.fault_date
s.save
format.html { redirect_to @fault_book, notice: 'Fault book was successfully created.' }
format.json { render json: @fault_book, status: :created, location: @fault_book }
else
format.html { render action: "new" }
format.json { render json: @fault_book.errors, status: :unprocessable_entity }
end
end
end
|
[
"def create\n @fault = Fault.new(fault_params)\n\n respond_to do |format|\n if @fault.save\n format.html { redirect_to faults_url, notice: 'Fault was successfully created.' }\n format.json { render :index, status: :created, location: @fault }\n else\n format.html { render :new }\n format.json { render json: @fault.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @fault_books = FaultBook.where(:truck_fleet_id => current_user.truck_fleet.id)\n @fault_books = FaultBook.belongs_to_truck_fleet(current_user.truck_fleet, @fault_books) if current_user.admin?\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @fault_books }\n end\n end",
"def create\n @fault = Fault.new(fault_params)\n\n respond_to do |format|\n if @fault.save\n format.html { redirect_to @fault, notice: 'Fault was successfully created.' }\n format.json { render :show, status: :created, location: @fault }\n else\n format.html { render :new }\n format.json { render json: @fault.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @api_book = Api::Book.new(api_book_params)\n\n if @api_book.save\n render json: @api_book, status: :created, location: @api_book\n else\n render json: @api_book.errors, status: :unprocessable_entity\n end\n end",
"def create\n @provided_book = ProvidedBook.new(provided_book_params)\n\n respond_to do |format|\n if @provided_book.save\n format.html { redirect_to @provided_book, notice: 'Provided book was successfully created.' }\n format.json { render :show, status: :created, location: @provided_book }\n else\n format.html { render :new }\n format.json { render json: @provided_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n if params[:commit] == 'Salva'\n @desidered_book = DesideredBook.new(desidered_book_params)\n\n respond_to do |format|\n if @desidered_book.save\n format.html { redirect_to @desidered_book, notice: 'Desidered book was successfully created.' }\n format.json { render :show, status: :created, location: @desidered_book }\n else\n format.html { render :new }\n format.json { render json: @desidered_book.errors, status: :unprocessable_entity }\n end\n end\n else\n require 'open-uri'\n @data = JSON.parse(URI.parse('https://www.googleapis.com/books/v1/volumes?q=isbn:' + desidered_book_params[:ISBN]).read)\n if @data['totalItems'] > 0\n @b = @data['items'][0]['volumeInfo']\n p = { 'nome' => @b['title'],\n 'autore' => @b['authors'][0],\n 'genere' => desidered_book_params[:genere],\n 'anno' => @b['publishedDate'],\n 'ISBN' => desidered_book_params[:ISBN],\n 'user_id' => desidered_book_params[:user_id]}\n @desidered_book = DesideredBook.new(p)\n respond_to do |format|\n if @desidered_book.save\n format.html { redirect_to @desidered_book, notice: 'Proposed book was successfully created.' }\n format.json { render :show, status: :created, location: @desidered_book }\n else\n format.html { render :new }\n format.json { render json: @desidered_book.errors, status: :unprocessable_entity }\n end\n end\n else\n redirect_to root_path\n end\n end\n end",
"def create\n @book = Book.new(book_params)\n\n if @book.save\n render json: @book, status: :created, location: @book\n else\n render json: @book.errors, status: :unprocessable_entity\n end\n end",
"def update\n @fault_book = FaultBook.find(params[:id])\n\n respond_to do |format|\n if @fault_book.update_attributes(params[:fault_book])\n format.html { redirect_to @fault_book, notice: 'Fault book was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fault_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @books_on_loan = BooksOnLoan.new(params[:books_on_loan])\n respond_to do |format|\n if @books_on_loan.save\n format.json { render json: @books_on_loan, status: :created, \n location: @books_on_loan }\n else\n format.json { render json: @books_on_loan.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @lib_book = LibBook.new(lib_book_params)\n\n respond_to do |format|\n if @lib_book.save\n format.html { redirect_to university_library_lib_books_path, notice: 'Lib book was successfully created.' }\n format.json { render :show, status: :created, location: @lib_book }\n else\n format.html { render :new }\n format.json { render json: @lib_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @api_book = Api::Book.new(api_book_params)\n respond_to do |format|\n if @api_book.save\n format.html { redirect_to @api_book, notice: 'Book was successfully created.' }\n format.json { render :show, status: :created, location: @api_book }\n else\n format.html { render :new }\n format.json { render json: @api_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @book_det = BookDet.new(params[:book_det])\n respond_to do |format|\n if @book_det.save\n format.html { redirect_to @book_det, notice: 'Book det was successfully created.' }\n format.json { render json: @book_det, status: :created, location: @book_det }\n else\n format.html { render action: \"new\" }\n format.json { render json: @book_det.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @instance_fault = InstanceFault.new(params[:instance_fault])\n\n respond_to do |format|\n if @instance_fault.save\n format.html { redirect_to @instance_fault, notice: 'Instance fault was successfully created.' }\n format.json { render json: @instance_fault, status: :created, location: @instance_fault }\n else\n format.html { render action: \"new\" }\n format.json { render json: @instance_fault.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_book(book_title)\n @books << {\n title: book_title,\n rental_details: {\n student_name: \"\",\n date: \"\"\n }\n }\n end",
"def create\n @historical_fiction_book = current_user.historical_fiction_books.build(historical_fiction_book_params)\n\n respond_to do |format|\n if @historical_fiction_book.save\n format.html { redirect_to @historical_fiction_book, notice: \"Historical fiction review was successfully created.\" }\n format.json { render :show, status: :created, location: @historical_fiction_book }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @historical_fiction_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @drank_book = DrankBook.new(drank_book_params)\n\n params[:drank_book][:recipes].each do |recipe_id|\n next if recipe_id.to_i == 0\n @drank_book.recipes << Recipe.find(recipe_id.to_i)\n end\n\n respond_to do |format|\n if @drank_book.save\n format.html { redirect_to @drank_book, notice: 'Drank book was successfully created.' }\n format.json { render action: 'show', status: :created, location: @drank_book }\n else\n format.html { render action: 'new' }\n format.json { render json: @drank_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n if params[:commit] == 'Salva'\n @proposed_book = ProposedBook.new(proposed_book_params)\n\n respond_to do |format|\n if @proposed_book.save\n format.html { redirect_to @proposed_book, notice: 'Proposed book was successfully created.' }\n format.json { render :show, status: :created, location: @proposed_book }\n else\n format.html { render :new }\n format.json { render json: @proposed_book.errors, status: :unprocessable_entity }\n end\n end\n else\n require 'open-uri'\n @data = JSON.parse(URI.parse('https://www.googleapis.com/books/v1/volumes?q=isbn:' + proposed_book_params[:ISBN]).read)\n if @data['totalItems'] > 0\n @b = @data['items'][0]['volumeInfo']\n @g = ''\n if @b.key?('categories')\n @g = @b['categories'][0]\n else \n @g = proposed_book_params[:genere]\n end\n p = { 'nome' => @b['title'],\n 'autore' => @b['authors'][0],\n 'genere' => @g,\n 'anno' => @b['publishedDate'],\n 'stato' => proposed_book_params[:stato],\n 'ISBN' => proposed_book_params[:ISBN],\n 'user_id' => proposed_book_params[:user_id]}\n @proposed_book = ProposedBook.new(p)\n respond_to do |format|\n if @proposed_book.save\n format.html { redirect_to @proposed_book, notice: 'Proposed book was successfully created.' }\n format.json { render :show, status: :created, location: @proposed_book }\n else\n format.html { render :new }\n format.json { render json: @proposed_book.errors, status: :unprocessable_entity }\n end\n end\n else\n redirect_to root_path\n end\n end\n end",
"def create\n @tags_book = TagsBook.new(tags_book_params)\n\n @books = Book.all\n @tags = Tag.all\n\n respond_to do |format|\n if @tags_book.save\n format.html { redirect_to @tags_book, notice: \"Tags book was successfully created.\" }\n format.json { render :show, status: :created, location: @tags_book }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @tags_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @cook_book = CookBook.new(params[:cook_book])\n\n respond_to do |format|\n if @cook_book.save\n format.html { redirect_to @cook_book, notice: 'Cook book was successfully created.' }\n format.json { render json: @cook_book, status: :created, location: @cook_book }\n else\n format.html { render action: \"new\" }\n format.json { render json: @cook_book.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PUT /fault_books/1 PUT /fault_books/1.json
|
def update
@fault_book = FaultBook.find(params[:id])
respond_to do |format|
if @fault_book.update_attributes(params[:fault_book])
format.html { redirect_to @fault_book, notice: 'Fault book was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @fault_book.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n @api_book = Api::Book.find(params[:id])\n\n if @api_book.update(api_book_params)\n head :no_content\n else\n render json: @api_book.errors, status: :unprocessable_entity\n end\n end",
"def update\n @book = Book.find(params[:id])\n\n respond_to do |format|\n if @book.update_attributes(params[:book])\n \n format.json { render json: @book, status: :created, location: @book }\n else\n \n format.json { render json: @book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @fault_book = FaultBook.new(params[:fault_book])\n @fault_book.truck_fleet_id = @fault_book.fleet.truck_fleet_id\n \n respond_to do |format|\n if @fault_book.save\n s = Serviceable.find_by_fleet_id(params['fault_book']['fleet_id'])\n s.next_service_date = @fault_book.fault_date \n s.save\n format.html { redirect_to @fault_book, notice: 'Fault book was successfully created.' }\n format.json { render json: @fault_book, status: :created, location: @fault_book }\n else\n format.html { render action: \"new\" }\n format.json { render json: @fault_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @fault.update(fault_params)\n format.html { redirect_to faults_url, notice: 'Fault was successfully updated.' }\n format.json { render :index, status: :ok, location: @fault }\n else\n format.html { render :edit }\n format.json { render json: @fault.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to_update({thing: @book})\n end",
"def update\n respond_to do |format|\n if @fault.update(fault_params)\n format.html { redirect_to @fault, notice: 'Fault was successfully updated.' }\n format.json { render :show, status: :ok, location: @fault }\n else\n format.html { render :edit }\n format.json { render json: @fault.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @provided_book.update(provided_book_params)\n format.html { redirect_to @provided_book, notice: 'Provided book was successfully updated.' }\n format.json { render :show, status: :ok, location: @provided_book }\n else\n format.html { render :edit }\n format.json { render json: @provided_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @cookbook = Cookbook.find(params[:id])\n\n respond_to do |format|\n if @cookbook.update_attributes(params[:cookbook])\n format.html { redirect_to @cookbook, notice: 'Cookbook was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cookbook.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @request_book.update(request_book_params)\n format.html { redirect_to @request_book, notice: 'Request book was successfully updated.' }\n format.json { render :show, status: :ok, location: @request_book }\n else\n format.html { render :edit }\n format.json { render json: @request_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n params[:book_shelf]['user'] = User.where(:id => params[:book_shelf]['user']).first\n params[:book_shelf]['book'] = Book.where(:id => params[:book_shelf]['book']).first\n @book_shelf = BookShelf.find(params[:id])\n respond_to do |format|\n if @book_shelf.update_attributes(params[:book_shelf])\n format.html { redirect_to @book_shelf, notice: 'Book shelf was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @book_shelf.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n book = @bookalope.http_get(@url)['book']\n @name = book['name']\n @bookflows = Array.new\n book['bookflows'].each do |bookflow|\n @bookflows << Bookflow.new(@bookalope, book, bookflow)\n end\n end",
"def update\n respond_to do |format|\n if @historical_fiction_book.update(historical_fiction_book_params)\n format.html { redirect_to @historical_fiction_book, notice: \"Historical fiction review was successfully updated.\" }\n format.json { render :show, status: :ok, location: @historical_fiction_book }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @historical_fiction_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @lib_book.update(lib_book_params)\n format.html { redirect_to university_library_lib_books_path, notice: 'Lib book was successfully updated.' }\n format.json { render :show, status: :ok, location: @lib_book }\n else\n format.html { render :edit }\n format.json { render json: @lib_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @book = Book.find(params[:id])\n \n respond_to do |format|\n if @book.update_attributes_and_index(params[:book])\n flash[:notice] = 'Book was successfully updated.'\n format.html { redirect_to(@book) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @book.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @books_on_loan = BooksOnLoan.find(params[:id])\n respond_to do |format|\n if @books_on_loan.update_attributes(params[:books_on_loan])\n format.json { head :no_content }\n else\n format.json { render json: @books_on_loan.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_with Biblebook.update(params[:id], params[:biblebook])\n end",
"def update\n respond_to do |format|\n data = api_book_params\n logger.info data\n if @api_book.update(data)\n format.html { redirect_to @api_book, notice: 'Book was successfully updated.' }\n format.json { render :show }\n else\n format.html { render :edit }\n format.json { render json: @api_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @add_book.update(add_book_params)\n format.html { redirect_to @add_book, notice: 'Add book was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @add_book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @fault_books = FaultBook.where(:truck_fleet_id => current_user.truck_fleet.id)\n @fault_books = FaultBook.belongs_to_truck_fleet(current_user.truck_fleet, @fault_books) if current_user.admin?\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @fault_books }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
number: Accepts 3 parameters name, twilio, and area code. twilio determines if Twilio will be used to generate a real phone number. Name is used when setting the friendly name of a Twilio phone number. Area code is used when search for local Twilio numbers. End result a phone number.
|
def number(twilio=false, name=nil, area_code=nil)
if twilio
# Check if twilio configuration exists. If not throw and errors because twilio was passed as true.
if !@config[:configuration][:twilio].blank? and (!@config[:configuration][:twilio][:account_id].blank? and !@config[:configuration][:twilio][:api_key].blank?)
account = @config[:configuration][:twilio][:account_id]
key = @config[:configuration][:twilio][:api_key]
# Initialize twilio client.
twilio = Twilio::REST::Client.new account, key
# If any area code is provide look for local numbers, if not get a toll free.
if area_code.blank?
available_numbers = twilio.account.available_phone_numbers.get('US').toll_free.list
else
available_numbers = twilio.account.available_phone_numbers.get('US').local.list(area_code: area_code) unless area_code.blank?
end
# Select the first number available.
available_number = available_numbers.first
# If available numbers is blank throw an error because something went wrong.
if available_numbers.blank?
raise StandardError, "No Available Numbers"
else
# Convert the phone number into something a artificial voice can say.
phone_number = available_number.phone_number.gsub("+1","")
phone_number = "#{phone_number[0..2]}-#{phone_number[3..5]}-#{phone_number[6..10]}"
# Setting the transciption email
# email = @config[:configuration][:twilio][:transcription_email].blank? ? "developers%40level.agency" : @config[:configuration][:twilio][:transcription_email]
email = "developers%40level.agency"
# Put together the voicemail Twimil.
voice_message = "http://twimlets.com/voicemail?Email=#{email}&Message=You%20reached%20the%20voicemail%20box%20of%20#{phone_number}.%20%20Please%20leave%20a%20message%20after%20the%20beep.&Transcribe=true&"
# Here we buy the number, set the voice_url to the voicemail Twimil and set the
# sms_url to echo so Twilio will capture the message but not reply to it.
number = twilio.account.incoming_phone_numbers.create({
phone_number: available_number.phone_number,
friendly_name: name,
voice_url: voice_message,
voice_method: "GET",
sms_url: "http://twimlets.com/echo?Twiml=%3CResponse%3E%3C%2FResponse%3E",
sms_method: "GET"
})
# If number is blank throw and error because something went wrong.
if number.blank?
raise StandardError, "Unable to allocate Twilio number"
else
number.phone_number
end
end
else
raise ArgumentError, "Cannot find Twilio Account ID and API key in configuration"
end
else
Faker::PhoneNumber.phone_number
end
end
|
[
"def set_twilio_number(area_code, forward_to, name, inboundno)\n return false if area_code.blank? || forward_to.blank? || name.blank? || inboundno.blank?\n job_status = JobStatus.create(:name => \"Campaign.set_twilio_number\")\n \n begin\n # CALL URLS ############################################ \n phone_number_md5 = Base64.encode64(inboundno)\n url_friendly_num = CGI.escape(phone_number_md5)\n call_url = \"http://#{APP_CONFIG[:host]}/api/v1/calls/#{url_friendly_num}/connect\"\n fallback_url = \"http://#{APP_CONFIG[:host]}/api/v1/calls/#{url_friendly_num}/connect\"\n status_url = \"http://#{APP_CONFIG[:host]}/api/v1/calls/#{url_friendly_num}/complete\"\n sms_url = \"http://#{APP_CONFIG[:host]}/api/v1/calls/#{url_friendly_num}/sms_collect\"\n fallback_sms_url = \"http://#{APP_CONFIG[:host]}/api/v1/calls/#{url_friendly_num}/sms_collect\"\n \n # Set up the parameters we will be sending into Twilio, we are requesting the provision of inboundno in this case\n d = { 'Name' => self.name,\n 'PhoneNumber' => inboundno,\n 'VoiceUrl' => \"#{call_url}\",\n 'VoiceMethod' => 'POST',\n 'VoiceFallbackUrl' => \"#{fallback_url}\",\n 'VoiceFallbackMethod' => 'POST',\n 'StatusCallback' => \"#{status_url}\",\n 'StatusCallbackMethod' => 'POST',\n 'SmsUrl' => \"#{sms_url}\",\n 'SmsMethod' => 'POST',\n 'SmsFallbackUrl' => \"#{fallback_sms_url}\",\n 'SmsFallbackMethod' => 'POST',\n 'VoiceCallerIdLookup' => true\n }\n \n # We want to make sure we have a twilio_id on this account before we call anytype of API request\n self.account.create_twilio_subaccount if self.account.twilio_id.blank? || Account.get_active_twilio_subaccounts.none?{|account| account['sid'] == self.account.twilio_id}\n \n # Make API call to twilio, requesting the param[:inboundno]\n resp = Twilio::RestAccount.new(ACCOUNT_SID, ACCOUNT_TOKEN).request(\"/#{API_VERSION}/Accounts/#{self.account.twilio_id}/IncomingPhoneNumbers.json\", 'POST', d)\n \n # Catch it if it is no 200/201\n raise unless resp.kind_of? Net::HTTPSuccess\n \n # Grab the twilio response and parse it out\n r = JSON.parse(resp.body)\n \n # This is to check if the number you requested was actually provisioned\n if r['sid'].present? && r['phone_number'].gsub(\"+\", \"\") == inboundno\n new_phone_number = self.phone_numbers.build\n new_phone_number.twilio_id = r['sid']\n new_phone_number.inboundno = r['phone_number'].gsub(\"+\", \"\")\n new_phone_number.forward_to = forward_to\n new_phone_number.name = self.name\n new_phone_number.descript = self.name\n new_phone_number.twilio_version = API_VERSION\n new_phone_number.id_callers = true\n new_phone_number.record_calls = true\n new_phone_number.transcribe_calls = false\n new_phone_number.text_calls = false\n new_phone_number.active = true\n new_phone_number.save!\n return true\n else\n return false\n end\n rescue Exception => ex\n job_status.finish_with_errors(ex)\n raise\n end\n end",
"def phone_to(phone_number, name = T.unsafe(nil), html_options = T.unsafe(nil), &block); end",
"def phone_number\n element_with_value('PhoneNumber', opts[:phone_number][0..14])\n end",
"def set_PhoneNumber(value)\n set_input(\"PhoneNumber\", value)\n end",
"def add_tel(s=nil, number: s)\n @to_s = 'tel:' + number\n end",
"def phone_number=(value)\n @phone_number = value\n end",
"def number(phone_number, send_digits: nil, url: nil, method: nil, status_callback_event: nil, status_callback: nil, status_callback_method: nil, **keyword_args)\n append(Number.new(phone_number, send_digits: send_digits, url: url, method: method, status_callback_event: status_callback_event, status_callback: status_callback, status_callback_method: status_callback_method, **keyword_args))\n end",
"def get_phone_number\n @phone_number ||= params[\"phoneNumber\"]\n end",
"def makecall\n if !params['number']\n redirect_to({ :action => '.', 'msg' => 'Invalid phone number' })\n return\n end\n\n # parameters sent to Twilio REST API\n d = {\n 'Caller' => CALLER_ID,\n 'Called' => params['number'],\n 'Url' => BASE_URL + '/reminder',\n }\n begin\n account = Twilio::RestAccount.new(ACCOUNT_SID, ACCOUNT_TOKEN)\n resp = account.request(\n \"/#{API_VERSION}/Accounts/#{ACCOUNT_SID}/Calls\",\n 'POST', d)\n resp.error! unless resp.kind_of? Net::HTTPSuccess\n rescue StandardError => bang\n redirect_to({ :action => '.', 'msg' => \"Error #{ bang }\" })\n return\n end\n\n redirect_to({ :action => '',\n 'msg' => \"Calling #{ params['number'] }...\" })\n end",
"def phone_number\n respond_to?(:phoneNumber) ? phoneNumber : ''\n end",
"def match_phone_number(number)\n /\\A\\s*\\(?\\s*?(?<area_code>\\d{3})\\s*\\)?[-.\\s]*(?<exchange>\\d{3})[-.\\s]*(?<number>\\d{4})([xX\\s]*(?<ext>\\d+))?\\s*\\z/\n .match(number)\n end",
"def makecall\n p params\n p \"1---\" * 10\n unless params['number']\n p params['number']\n p \"2---\" * 10\n redirect_to :action => '.', 'msg' => 'Invalid phone number'\n return\n end\n\n # parameters sent to Twilio REST API\n data = {\n :from => CALLER_NUM,\n :to => params['number'],\n :url => BASE_URL + '/reminder',\n }\n\n begin\n p \"3---\" * 10\n p client = Twilio::REST::Client.new(ACCOUNT_SID, ACCOUNT_TOKEN)\n p \"4---\" * 10\n p client.account.calls.create data\n p \"5---\" * 10\n rescue StandardError => bang\n redirect_to :action => '.', 'msg' => \"Error #{bang}\"\n return\n end\n\n render :nothing => true, :status => 200, :content_type => 'text/html'\n end",
"def phone_number\n\t\t\trecipient.phone_number\n\t\tend",
"def driver\n num = Number.new\n puts num.number_to_phone(\"1234567890\")\n end",
"def mobile_phone_number\n build_phone_number(country_code, mobile_phone_prefix)\n end",
"def number(phone_number, send_digits: nil, url: nil, method: nil, status_callback_event: nil, status_callback: nil, status_callback_method: nil, byoc: nil, machine_detection: nil, amd_status_callback_method: nil, amd_status_callback: nil, machine_detection_timeout: nil, machine_detection_speech_threshold: nil, machine_detection_speech_end_threshold: nil, machine_detection_silence_timeout: nil, **keyword_args)\n append(Number.new(phone_number, send_digits: send_digits, url: url, method: method, status_callback_event: status_callback_event, status_callback: status_callback, status_callback_method: status_callback_method, byoc: byoc, machine_detection: machine_detection, amd_status_callback_method: amd_status_callback_method, amd_status_callback: amd_status_callback, machine_detection_timeout: machine_detection_timeout, machine_detection_speech_threshold: machine_detection_speech_threshold, machine_detection_speech_end_threshold: machine_detection_speech_end_threshold, machine_detection_silence_timeout: machine_detection_silence_timeout, **keyword_args))\n end",
"def mobile_phone=(n)\n pull unless @details\n pn = Quickbooks::Model::TelephoneNumber.new\n pn.free_form_number = n\n @details.mobile_phone = pn\n #update our locally stored number too\n update_mobile_phone_number\n end",
"def create_vanity_number!(opts)\n check_for_parameters([:area_code, :subscriber_id], opts)\n\n resp = with_client_and_defaults do |client, defaults|\n handle_response_errors do\n client.assign_b_number do |soap| \n soap.body = add_soap_prefix do \n { \n \"partner_id\" => @partner_id,\n \"partner_password\" => @partner_password,\n \"subscriber_id\" => getp(:subscriber_id, opts),\n \"subscriber_ndc\" => getp(:area_code, opts)\n }\n end\n end\n end\n end\n \n handle_response_hash(get_response_hash(resp, [:assign_b_numberResponse, \n :assign_b_numberResult])) do |hsh|\n d = hsh[:data]\n # Not being a Telco person myself:\n # NDC - National Destination Code\n # SN - Subscriber Number\n { :country_code => d[:cc], :area_code => d[:ndc], :vanity_number => d[:sn] }\n end\n end",
"def telephone_number\n @telephone_number\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return 1st 3 words of content and ellipsis
|
def preview
self.content.split(' ')[0...5].join(' ') + '...'
end
|
[
"def first_n_words( n , text )\n words = text.split[0...n]\n words.join(' ') + if words.size == n then '...' else '' end\n end",
"def snippet(text, wordcount, omission)\n text.split[0..(wordcount-1)].join(\" \") + (text.split.size > wordcount ? \" \" + omission : \"\")\n end",
"def content_title\n question.size > 24 ? question[0..10] + '...' + question[-10..-1] : question\n end",
"def extract(text, length = 80)\n words = text.gsub(/<.+?>/, '').split\n return text if words.length <= length\n words[0..(length-1)].join(' ') + '...'\n end",
"def summarize_content (char_num)\n if self.content.length <= char_num\n return self.content\n else return self.content[0..(char_num-1)] + \"...\"\n end\n end",
"def first_x_words(str,n=20,finish='…')\n str.split(' ')[0,n].inject{|sum,word| sum + ' ' + word} + finish\nend",
"def the_excerpt(content=nil, length=100)\n if node = content || @content || Content.get(params[:id])\n \n # First, we convert the text to html and strip it\n # (remember it's stored as markdown)\n text = Maruku.new(\"#{node.body}\").to_html.gsub(/<\\/?[^>]*>/, \"\")\n \n # Next, we truncate it\n text = text.split(\" \")[0..length].join(\" \")\n \n # Add ellipse if anything was actually shortened\n text += \"...\" unless node.body.split(\" \").length < length\n \n return text\n \n else\n \"<strong>Error:</strong> No content could be found\" unless ENV['RACK_ENV'] == 'production'\n end\n end",
"def short_text(txt, len)\n text = (len - 4) > 0 ? txt[0..(len - 4)]+\"...\" : \"\"\n end",
"def smart_truncate(opts = {})\n opts = {:words => 12}.merge(opts)\n if opts[:sentences]\n return self.split(/\\.(\\s|$)+/).reject{ |s| s.strip.empty? }[0, opts[:sentences]].map{|s| s.strip}.join('. ') + '...'\n end\n a = self.split(/\\s/) # or /[ ]+/ to only split on spaces\n n = opts[:words]\n a[0...n].join(' ') + (a.size > n ? '...' : '')\n end",
"def lede(word_count = 25)\n doc = self.hpricot_body\n #wipe images\n doc.search(\"img\").remove\n paras = doc.search(\"//p\")\n text = \"\" \n while paras.size > 0 && text.split(\" \").size < word_count\n text += paras.shift.to_html\n end\n if (arr = text.split(\" \")).size > word_count\n return arr[0..word_count].join(\" \") + \" ...\"\n else \n return arr.join(\" \")\n end\n end",
"def truncate\n @para.truncate_words(4, omission: \"...Read More\")\n end",
"def preview(text, length=400)\n text.split(/\\s/).inject(\"\") do |out, chunk|\n if (out.size + 1 + chunk.size) <= length\n out + \" \" + chunk\n else\n return out + \" ...\"\n end\n end\n end",
"def text_summary\n summary = self.text\n summary = summary[(summary.index(\" \") + 1)...summary.length] if self.text[0...1] == \"@\"\n summary = (summary.length > 30 ? \"#{summary[0..30]}...\" : summary[0..30])\n summary\n end",
"def excerpt(text, start = 0, stop = 20, padding = \"...\")\n return \"\" if text.nil?\n \n (padding if start > 0).to_s + text[start..(start + stop)] + padding\n end",
"def short_text(text, max_length)\n short = text\n if text.present? && text.length > max_length\n short_array = text.slice(0, max_length).split(' ')\n short_array.pop\n short = short_array.join(' ') + ' ...'\n end\n short\n end",
"def truncate_sentences(text, limit=3)\n text.scan(/.*?[.!?]|.*?$/m).first(limit).join + \"... (continued)\"\n end",
"def summarize_title (char_num)\n if self.title.length <= char_num\n return self.title\n else return self.title[0..(char_num-1)] + \"...\"\n end\n end",
"def shorten(text)\n if text.length > 50\n text[0...50] + '...'\n else\n text\n end\n end",
"def shrink_text(text, num_words=5)\n text = text.split[0..(num_words-1)].join(\" \") + (text.split.size > num_words ? \"...\" : \"\")\n return text\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
This blocks anyone posting a link from paypal in chat
|
def no_paypal_content
errors.add_to_base("Please, no thirdparty websites.") if content =~ /paypal/i
end
|
[
"def garantir_link\n if link.present?\n link_params = link\n _link = link_params.split('/').reject { |l| l.blank? || l == 'http:' }\n _link[0].sub!(/s.|[^.]*.|\\s./, '') if _link[0].split('.').length == 3\n if ['herokuapp.com', 'codepen.io'].include? _link[0]\n link_params.gsub!('/' + _link[2] + '/', '/debug/')\n link_params.remove!('?' + _link[-1].split('?')[-1])\n elsif !_link[0]['.com'].try(:presence?)\n # sem link\n link_params.sub!('/', '') if _link[0] == '/'\n else\n errors.add(:link, 'Não é permitido.')\n return false\n end\n self.link = link_params\n end\n end",
"def ssl_allowed?\n # Need to override because of the ApplicationController#ssl_allowed?\n [ :plans, :thanks, :cancelled, :paypal ].include?(self.action_name.to_sym) || super\n end",
"def reject_social_links(attributes)\n attributes[\"url\"].blank? && !self.social_links.where(site: attributes[\"site\"]).exists?\n end",
"def share_non_member(notebook, sharer, emails, message, url)\n @notebook = notebook\n @url = url.chomp('/')\n @sharer = sharer\n @message = message\n @email_needs_to_be_simplified = need_to_simplify_email?(@notebook, @message)\n mail(\n bcc: emails,\n subject: \"NBGallery notebook shared with you\"\n )\n end",
"def reject(link)\n if not_valid_uri?(link) || not_same_domain?(link) || already_spidered?(link)\n return true\n else\n return false\n end\n end",
"def request_declined me \n @amount = me.amount\n @me = me\n @currency = me.account.currency\n subjects = \"Money request declined by recipient!\"\n mail to: me.sender.email, subject: subjects\n end",
"def email_deny(params)\n http_helper.send_post_request(\"#{@url_prefix}/#{get_user_id!(params)}/email/deny\", params)\n end",
"def not_paid(email, name)\n @name = name\n \tbegin\n mail(:to => email, :subject => \"Pay4Me request rejected\") do |format|\n format.text\n format.html\n end\n rescue => e\n logger.info(e)\n end\n\n end",
"def form_url\n\t\t@use_sandbox ? 'https://www.sandbox.paypal.com/cgi-bin/webscr' : 'https://www.paypal.com/cgi-bin/webscr'\n\tend",
"def filter_spam\n if !params[:contact][\"spam_checker\"].blank?\n redirect_to root_path\n return false\n end\n end",
"def notify_admins_link(title, body, link)\n require 'net/http'\n require \"uri\"\n uri = URI.parse('https://api.pushbullet.com/v2/pushes')\n request = Net::HTTP::Post.new(uri.to_s, {\n \"Content-Type\" => \"application/json\",\n \"Authorization\" => \"Bearer #{ENV['PUSHBULLET_API_KEY']}\"\n })\n request.set_form_data({\n 'target': \"#{ENV['PUSHBULLET_USERNAME']}\",\n 'type': 'link',\n 'title': \"#{title}\",\n 'body': \"#{body}\",\n 'url': \"#{root_url + link}\"\n })\n http = Net::HTTP.new(uri.host, uri.port)\n http.use_ssl = true\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n http.request(request)\n end",
"def skip_invitation; end",
"def tag_comment_as_spam_link(comment) \n if comment.approved\n link_to('Spam', reject_comment_path(comment), :method => :put)\n else\n link_to('Not Spam', approve_comment_path(comment), :method => :put)\n end\n end",
"def idv_phone_send_link_rate_limited(phone_number:)\n track_event(\n :idv_phone_send_link_rate_limited,\n phone_number: phone_number,\n )\n end",
"def share_confirm(sharer_id, receiver_id, share_amount)\n @receiver = User.find(receiver_id)\n @user = User.find(sharer_id)\n @share_amount = share_amount\n mail :to => recipient(@user.email), :subject => \"#{@receiver.display_name} has accepted your shared tips\"\n end",
"def tweet_rejected_by_advertiser(tweet)\n @tweet = tweet\n\n set_attachments\n\n mail(to: tweet.influencer.user.email, subject: \"Notificaciones @ Social Target - Una propuesta de tweet que has modificado, ha sido rechazada por el anunciante\")\n end",
"def old_notify_user (listing, sender, receiver)\n send_as :notification\n from sender.facebook_session.user \n recipients receiver.facebook_session.user\n #fbml \"<a href='#{FB_APP_HOME_URL}/listings/#{listing.id}'><b>#{listing.title}</b></a> has been approved.\"\n fbml \"Your listing: <a href='#{listings_path(listing.id)}}'><b>#{listing.title}</b></a> has been approved.\"\n end",
"def tag_comment_as_spam_link(comment)\n \n if comment.approved\n \"(\" + link_to('Spam', reject_comment_path(comment), :method => :put) + \")\"\n else\n \"(\" + link_to('Not Spam', approve_comment_path(comment), :method => :put) + \")\"\n end\n end",
"def single_use_link_request?\n return false\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
assembles one string argument into cmd
|
def test_assembles_one_string_argument_into_cmd
Crd::Flex::Command.new 'mxmlc' do |s|
s.output = 'Main.swf'
cmd = s.to_cmd.split( /\s+/ )
assert_equal( 'mxmlc', cmd.shift )
assert( cmd.include?( '-output=Main.swf' ), 'Could not find argument in to_cmd' )
end
end
|
[
"def build_command(cmd)\n cmd\n end",
"def build_command(command, *args)\n \"#{command} #{escape_arguments(args)}\".strip\n end",
"def cmdarg; end",
"def cmd(*args)\n\n cmd_args = []\n \n for arg in args\n \n case arg\n \n when Array\n cmd_literals = arg.shift.split(/\\s+/)\n \n for cmd_literal in cmd_literals\n if cmd_literal == \"?\"\n raise \"Not enough substitution arguments\" unless cmd_args.any?\n cmd_args << arg.shift\n else\n cmd_args << cmd_literal\n end\n end\n \n raise \"More parameters than ?'s in cmd string\" if arg.any?\n \n when String\n cmd_args << arg\n \n else\n cmd_args << arg.to_s\n \n end\n \n end \n\n p [:cmd_args, cmd_args] if $DEBUG\n \n system(*cmd_args) \nend",
"def cmd(*args)\n\n cmd_args = []\n\n for arg in args\n\n case arg\n\n when Array\n cmd_literals = arg.shift.split(/\\s+/)\n\n for cmd_literal in cmd_literals\n if cmd_literal == \"?\"\n raise \"Not enough substitution arguments\" unless cmd_args.any?\n cmd_args << arg.shift\n else\n cmd_args << cmd_literal\n end\n end\n\n raise \"More parameters than ?'s in cmd string\" if arg.any?\n\n when String\n cmd_args << arg\n\n else\n cmd_args << arg.to_s\n\n end\n\n end\n\n p [:cmd_args, cmd_args] if $DEBUG\n\n system(*cmd_args)\nend",
"def parse_cmd(input)\n input = input.split\n cmd = input[0]\n args = input[1..-1]\n\n return cmd, args\n end",
"def test_assembles_two_string_arguments_into_cmd\n Crd::Flex::Command.new 'mxmlc' do |s|\n s.output = 'Main.swf'\n s.static_link_runtime_shared_libraries = true\n cmd = s.to_cmd.split( /\\s+/ )\n assert_equal( 'mxmlc', cmd.shift )\n assert( cmd.include?( '-output=Main.swf' ), 'Could not find argument in to_cmd' )\n assert( cmd.include?( '-static-link-runtime-shared-libraries=true' ), 'Could not find argument in to_cmd' )\n end\n end",
"def prepare_command(cmd, *args)\n args &&= [args].flatten.compact\n found_cmd = Rye.which(cmd)\n raise CommandNotFound.new(cmd || '[unknown]') unless found_cmd\n # Symbols to switches. :l -> -l, :help -> --help\n args.collect! do |a|\n a = \"-#{a}\" if a.is_a?(Symbol) && a.to_s.size == 1\n a = \"--#{a}\" if a.is_a?(Symbol)\n a\n end\n Rye.escape(@safe, found_cmd, *args)\n end",
"def arg_string; end",
"def command_arg(command)\n command[2]\n end",
"def command_for(name, *args)\n command_str_for(*(COMMANDS[name] + args))\n end",
"def command_builder(cmd, opts = {})\n enable = opts.fetch(:enable, true)\n default = opts.fetch(:default, false)\n cmd << \" #{opts[:value]}\" if opts[:value]\n return \"default #{cmd}\" if default\n return \"no #{cmd}\" unless enable\n cmd\n end",
"def parse_string_argument(key)\n if @opts[key].nil? and s=@argv.shift\n @opts[key] = s.dup \n end\n end",
"def argument_string(*args) # TODO: This assumes all arguments are strings, that's stupid.\n args.join('\", \"').prepend('\"') + '\"'\n end",
"def command(*args)\n opts.command(*args)\n end",
"def cmd\n c = ['git commit']\n c << '-a' if all?\n c << %(-m \"#{options.message}\") if message?\n c << %(-m \"#{message}\") unless story_ids.empty?\n c << argument_string(unknown_options) unless unknown_options.empty?\n c.join(' ')\n end",
"def retrieve_command_name(args); end",
"def quote_cmd cmd\n cmd = [*cmd].join(\" \")\n \"'#{cmd.gsub(/'/){|s| \"'\\\\''\"}}'\"\n end",
"def make_command executable, parameters\n raise ArgumentError, \"executable is nil\" if executable.nil?\n params = parameters.collect{|p| '\"' + p + '\"'}.join ' '\n exe = normalise_slashes executable\n %Q{\"#{exe}\" #{params}}\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
assembles two string arguments into cmd
|
def test_assembles_two_string_arguments_into_cmd
Crd::Flex::Command.new 'mxmlc' do |s|
s.output = 'Main.swf'
s.static_link_runtime_shared_libraries = true
cmd = s.to_cmd.split( /\s+/ )
assert_equal( 'mxmlc', cmd.shift )
assert( cmd.include?( '-output=Main.swf' ), 'Could not find argument in to_cmd' )
assert( cmd.include?( '-static-link-runtime-shared-libraries=true' ), 'Could not find argument in to_cmd' )
end
end
|
[
"def run2(*args)\n args.map!(&:to_s)\n command = args.join(' ')\n if include_meta_character?(command)\n run(command)\n else\n run(*args)\n end\n end",
"def pipe_to(command1, command2) \n command1 + ' | ' + command2 \n end",
"def test_assembles_two_array_arguments_into_cmd\n Crd::Flex::Command.new 'mxmlc' do |s|\n s.source_path << 'src'\n s.source_path << 'lib/src'\n s.library_path << 'lib/bin'\n cmd = s.to_cmd.split( /\\s+/ )\n assert_equal( 'mxmlc', cmd.shift )\n assert( cmd.include?( '-source-path+=src,lib/src' ), 'Could not find argument in to_cmd' )\n assert( cmd.include?( '-library-path+=lib/bin' ), 'Could not find argument in to_cmd' )\n end\n end",
"def combine_args(*args)\n return args[0] if args.length == 1\n\n args.map do |arg|\n if arg =~ /[ \\t\\n\\v\"]/\n arg = arg.gsub(/(\\\\*)\"/, '\\1\\1\\\"') # interior quotes with N preceeding backslashes need 2N+1 backslashes\n arg = arg.sub(/(\\\\+)$/, '\\1\\1') # trailing N backslashes need to become 2N backslashes\n \"\\\"#{arg}\\\"\"\n else\n arg\n end\n end.join(\" \")\n end",
"def build_command(command, *args)\n \"#{command} #{escape_arguments(args)}\".strip\n end",
"def cmd(*args)\n\n cmd_args = []\n \n for arg in args\n \n case arg\n \n when Array\n cmd_literals = arg.shift.split(/\\s+/)\n \n for cmd_literal in cmd_literals\n if cmd_literal == \"?\"\n raise \"Not enough substitution arguments\" unless cmd_args.any?\n cmd_args << arg.shift\n else\n cmd_args << cmd_literal\n end\n end\n \n raise \"More parameters than ?'s in cmd string\" if arg.any?\n \n when String\n cmd_args << arg\n \n else\n cmd_args << arg.to_s\n \n end\n \n end \n\n p [:cmd_args, cmd_args] if $DEBUG\n \n system(*cmd_args) \nend",
"def test_assembles_one_string_argument_into_cmd\n Crd::Flex::Command.new 'mxmlc' do |s|\n s.output = 'Main.swf'\n cmd = s.to_cmd.split( /\\s+/ )\n assert_equal( 'mxmlc', cmd.shift )\n assert( cmd.include?( '-output=Main.swf' ), 'Could not find argument in to_cmd' )\n end\n end",
"def cmd(*args)\n\n cmd_args = []\n\n for arg in args\n\n case arg\n\n when Array\n cmd_literals = arg.shift.split(/\\s+/)\n\n for cmd_literal in cmd_literals\n if cmd_literal == \"?\"\n raise \"Not enough substitution arguments\" unless cmd_args.any?\n cmd_args << arg.shift\n else\n cmd_args << cmd_literal\n end\n end\n\n raise \"More parameters than ?'s in cmd string\" if arg.any?\n\n when String\n cmd_args << arg\n\n else\n cmd_args << arg.to_s\n\n end\n\n end\n\n p [:cmd_args, cmd_args] if $DEBUG\n\n system(*cmd_args)\nend",
"def shell_commands( cmd, args )\n cmdline = [ cmd.to_s.shellsplit ]\n cmdline << args.flatten.collect{ |a| a.to_s }\n return commandline_normalize( cmdline )\n end",
"def cmd_concat_operator\n \" & \"\n end",
"def parse_cmd(input)\n input = input.split\n cmd = input[0]\n args = input[1..-1]\n\n return cmd, args\n end",
"def command_line(head_arguments='', tail_arguments='')\n args = [head_arguments, default_args, tail_arguments].flatten.compact.select { |s| s.length > 0 }.join ' '\n \"#{executable} #{args}\"\n end",
"def two_strings str1, str2\n\t\"#{str1} and #{str2}\"\nend",
"def split_arguments!(arguments)\n \n if arguments.any? { |arg| arg.strip == 'of' }\n command = arguments.delete('of')\n elsif arguments.any? { |arg| arg.strip == 'convert' }\n command = arguments.delete('convert')\n end\n \n command\nend",
"def prepare_command(cmd, *args)\n args &&= [args].flatten.compact\n found_cmd = Rye.which(cmd)\n raise CommandNotFound.new(cmd || '[unknown]') unless found_cmd\n # Symbols to switches. :l -> -l, :help -> --help\n args.collect! do |a|\n a = \"-#{a}\" if a.is_a?(Symbol) && a.to_s.size == 1\n a = \"--#{a}\" if a.is_a?(Symbol)\n a\n end\n Rye.escape(@safe, found_cmd, *args)\n end",
"def cmdarg; end",
"def dist_cmd(*args)\r\n\r\n\t\t# Convince distccd that this is a compile\r\n\t\targs.concat(%w{# -c main.c -o main.o})\r\n\r\n\t\t# Set distcc 'magic fairy dust' and argument count\r\n\t\tres = \"DIST00000001\" + sprintf(\"ARGC%.8x\", args.length)\r\n\r\n\t\t# Set the command arguments\r\n\t\targs.each do |arg|\r\n\t\t\tres << sprintf(\"ARGV%.8x%s\", arg.length, arg)\r\n\t\tend\r\n\r\n\t\treturn res\r\n\tend",
"def cmd_concat_operator\n\t\t\" & \"\n\tend",
"def shell_commands(cmd, args); end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
assembles one array argument into cmd
|
def test_assembles_one_array_argument_into_cmd
Crd::Flex::Command.new 'mxmlc' do |s|
s.source_path << 'src'
s.source_path << 'lib/src'
cmd = s.to_cmd.split( /\s+/ )
assert_equal( 'mxmlc', cmd.shift )
assert( cmd.include?( '-source-path+=src,lib/src' ), 'Could not find argument in to_cmd' )
end
end
|
[
"def parse_cmd(array)\n array.collect do |e|\n if e.chars.to_a.include? ' '\n '\"' + e + '\"'\n else\n e\n end\n end.join(' ')\nend",
"def test_assembles_two_array_arguments_into_cmd\n Crd::Flex::Command.new 'mxmlc' do |s|\n s.source_path << 'src'\n s.source_path << 'lib/src'\n s.library_path << 'lib/bin'\n cmd = s.to_cmd.split( /\\s+/ )\n assert_equal( 'mxmlc', cmd.shift )\n assert( cmd.include?( '-source-path+=src,lib/src' ), 'Could not find argument in to_cmd' )\n assert( cmd.include?( '-library-path+=lib/bin' ), 'Could not find argument in to_cmd' )\n end\n end",
"def convert_command(array_command)\n length = array_command.length\n string_command = ''\n (0..length-1).each {|i| string_command = string_command + ' ' + array_command[i]}\n string_command\nend",
"def cmd(*args)\n\n cmd_args = []\n \n for arg in args\n \n case arg\n \n when Array\n cmd_literals = arg.shift.split(/\\s+/)\n \n for cmd_literal in cmd_literals\n if cmd_literal == \"?\"\n raise \"Not enough substitution arguments\" unless cmd_args.any?\n cmd_args << arg.shift\n else\n cmd_args << cmd_literal\n end\n end\n \n raise \"More parameters than ?'s in cmd string\" if arg.any?\n \n when String\n cmd_args << arg\n \n else\n cmd_args << arg.to_s\n \n end\n \n end \n\n p [:cmd_args, cmd_args] if $DEBUG\n \n system(*cmd_args) \nend",
"def cmd(*args)\n\n cmd_args = []\n\n for arg in args\n\n case arg\n\n when Array\n cmd_literals = arg.shift.split(/\\s+/)\n\n for cmd_literal in cmd_literals\n if cmd_literal == \"?\"\n raise \"Not enough substitution arguments\" unless cmd_args.any?\n cmd_args << arg.shift\n else\n cmd_args << cmd_literal\n end\n end\n\n raise \"More parameters than ?'s in cmd string\" if arg.any?\n\n when String\n cmd_args << arg\n\n else\n cmd_args << arg.to_s\n\n end\n\n end\n\n p [:cmd_args, cmd_args] if $DEBUG\n\n system(*cmd_args)\nend",
"def mk_cmd(env, cmd, options)\n [env, cmd.shellsplit, options].flatten\n end",
"def parse_command(cmd)\n if cmd&.is_a?(Array)\n cmd\n else\n Shellwords.split(cmd.to_s)\n end\n end",
"def cmd_with_targets(cmd_array, target, extras)\n final_arr = cmd_array\n final_arr.concat(['-target', target]) unless target.nil?\n # rubocop:disable Style/SafeNavigation\n extras.each { |e| final_arr.concat(['-target', e]) } unless extras.nil?\n # rubocop:enable Style/SafeNavigation\n final_arr.join(' ')\n end",
"def make_command_line_unix(ary)\n ary.collect { |str| escape_shell_unix(str) }.join(\" \")\n end",
"def arg_spec_array args\n ArrayArgSpec.new args\n end",
"def shell_commands( cmd, args )\n cmdline = [ cmd.to_s.shellsplit ]\n cmdline << args.flatten.collect{ |a| a.to_s }\n return commandline_normalize( cmdline )\n end",
"def array_to_bash array\n quoted_array = array.map {|item| \"'\" + item + \"'\"}\n \"(\" + quoted_array.join(\" \") + \")\"\n end",
"def build_command(command, *args)\n \"#{command} #{escape_arguments(args)}\".strip\n end",
"def add_hash_arguments_to_command! command_array, h\n h.each_pair do |k,v|\n if k.to_s.match /^\\-/\n command_array << k\n elsif k.to_s.length >= 2\n command_array << \"--#{k}\"\n else\n command_array << \"-#{k}\"\n end\n unless v === true # switch, no value required\n command_array << if v.kind_of? String\n %/\"#{v}\"/\n else\n v\n end\n end\n end\n end",
"def to_exec(args = self)\n Array(executable) + args\n end",
"def cmdarg; end",
"def string_from_args\n if @args.is_a?(Array)\n @args.join(\" \")\n else\n @args\n end\n end",
"def to_exec(args = self)\n Array(@executable) + args\n end",
"def arrayize_arguments(args)\n # Go through trailing arguments and suck them in if they don't seem\n # to have an owner.\n array = []\n until args.empty? || args.first.match(/^-/)\n array << args.shift\n end\n array\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
assembles two array arguments into cmd
|
def test_assembles_two_array_arguments_into_cmd
Crd::Flex::Command.new 'mxmlc' do |s|
s.source_path << 'src'
s.source_path << 'lib/src'
s.library_path << 'lib/bin'
cmd = s.to_cmd.split( /\s+/ )
assert_equal( 'mxmlc', cmd.shift )
assert( cmd.include?( '-source-path+=src,lib/src' ), 'Could not find argument in to_cmd' )
assert( cmd.include?( '-library-path+=lib/bin' ), 'Could not find argument in to_cmd' )
end
end
|
[
"def test_assembles_one_array_argument_into_cmd\n Crd::Flex::Command.new 'mxmlc' do |s|\n s.source_path << 'src'\n s.source_path << 'lib/src'\n cmd = s.to_cmd.split( /\\s+/ )\n assert_equal( 'mxmlc', cmd.shift )\n assert( cmd.include?( '-source-path+=src,lib/src' ), 'Could not find argument in to_cmd' )\n end\n end",
"def cmd_with_targets(cmd_array, target, extras)\n final_arr = cmd_array\n final_arr.concat(['-target', target]) unless target.nil?\n # rubocop:disable Style/SafeNavigation\n extras.each { |e| final_arr.concat(['-target', e]) } unless extras.nil?\n # rubocop:enable Style/SafeNavigation\n final_arr.join(' ')\n end",
"def cmd(*args)\n\n cmd_args = []\n \n for arg in args\n \n case arg\n \n when Array\n cmd_literals = arg.shift.split(/\\s+/)\n \n for cmd_literal in cmd_literals\n if cmd_literal == \"?\"\n raise \"Not enough substitution arguments\" unless cmd_args.any?\n cmd_args << arg.shift\n else\n cmd_args << cmd_literal\n end\n end\n \n raise \"More parameters than ?'s in cmd string\" if arg.any?\n \n when String\n cmd_args << arg\n \n else\n cmd_args << arg.to_s\n \n end\n \n end \n\n p [:cmd_args, cmd_args] if $DEBUG\n \n system(*cmd_args) \nend",
"def run2(*args)\n args.map!(&:to_s)\n command = args.join(' ')\n if include_meta_character?(command)\n run(command)\n else\n run(*args)\n end\n end",
"def test_assembles_two_string_arguments_into_cmd\n Crd::Flex::Command.new 'mxmlc' do |s|\n s.output = 'Main.swf'\n s.static_link_runtime_shared_libraries = true\n cmd = s.to_cmd.split( /\\s+/ )\n assert_equal( 'mxmlc', cmd.shift )\n assert( cmd.include?( '-output=Main.swf' ), 'Could not find argument in to_cmd' )\n assert( cmd.include?( '-static-link-runtime-shared-libraries=true' ), 'Could not find argument in to_cmd' )\n end\n end",
"def shell_commands( cmd, args )\n cmdline = [ cmd.to_s.shellsplit ]\n cmdline << args.flatten.collect{ |a| a.to_s }\n return commandline_normalize( cmdline )\n end",
"def merge_args(extra_args)\n all_args = (@args + extra_args).uniq\n options = all_args.select { |arg| arg.start_with? '-' }\n files = extra_args.select(&File.method(:exists?))\n command = (@args - options - files).first\n\n [command, *options, *files]\n end",
"def cmd(*args)\n\n cmd_args = []\n\n for arg in args\n\n case arg\n\n when Array\n cmd_literals = arg.shift.split(/\\s+/)\n\n for cmd_literal in cmd_literals\n if cmd_literal == \"?\"\n raise \"Not enough substitution arguments\" unless cmd_args.any?\n cmd_args << arg.shift\n else\n cmd_args << cmd_literal\n end\n end\n\n raise \"More parameters than ?'s in cmd string\" if arg.any?\n\n when String\n cmd_args << arg\n\n else\n cmd_args << arg.to_s\n\n end\n\n end\n\n p [:cmd_args, cmd_args] if $DEBUG\n\n system(*cmd_args)\nend",
"def ruby_command_args(*args)\n return Array(args) unless Licensed::Shell.tool_available?(bundler_exe)\n [bundler_exe, \"exec\", *args]\n end",
"def combine_args(*args)\n return args[0] if args.length == 1\n\n args.map do |arg|\n if arg =~ /[ \\t\\n\\v\"]/\n arg = arg.gsub(/(\\\\*)\"/, '\\1\\1\\\"') # interior quotes with N preceeding backslashes need 2N+1 backslashes\n arg = arg.sub(/(\\\\+)$/, '\\1\\1') # trailing N backslashes need to become 2N backslashes\n \"\\\"#{arg}\\\"\"\n else\n arg\n end\n end.join(\" \")\n end",
"def pipe_to(command1, command2) \n command1 + ' | ' + command2 \n end",
"def parse_cmd(array)\n array.collect do |e|\n if e.chars.to_a.include? ' '\n '\"' + e + '\"'\n else\n e\n end\n end.join(' ')\nend",
"def mk_cmd(env, cmd, options)\n [env, cmd.shellsplit, options].flatten\n end",
"def add_hash_arguments_to_command! command_array, h\n h.each_pair do |k,v|\n if k.to_s.match /^\\-/\n command_array << k\n elsif k.to_s.length >= 2\n command_array << \"--#{k}\"\n else\n command_array << \"-#{k}\"\n end\n unless v === true # switch, no value required\n command_array << if v.kind_of? String\n %/\"#{v}\"/\n else\n v\n end\n end\n end\n end",
"def shell_commands(cmd, args); end",
"def build_command(command, *args)\n \"#{command} #{escape_arguments(args)}\".strip\n end",
"def commands\n args.commands.map do |cmd|\n if cmd.respond_to?(:join)\n cmd.map { |c| c.index(' ') ? \"'#{c}'\" : c }.join(' ')\n else\n cmd.to_s\n end\n end\n end",
"def convert_command(array_command)\n length = array_command.length\n string_command = ''\n (0..length-1).each {|i| string_command = string_command + ' ' + array_command[i]}\n string_command\nend",
"def win32_prepare_args(args)\n args = args.map do |arg|\n # Quote args that contain whitespace\n arg = \"\\\"#{arg}\\\"\" if arg =~ /\\s/\n\n # Escape cmd.exe metacharacters\n arg.gsub(/[()%!^\"<>&|]/, '^\\0')\n end\n\n %w[cmd.exe /c] + [args.join(' ')]\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
found returns true for commands found in path
|
def test_found_returns_true_for_commands_found_in_path
Crd::Flex::Command.new 'mxmlc' do |s|
assert_equal( true, s.found? )
end
end
|
[
"def command?(path)\n !!(%r{\\A/(v(.*)/|)man\\/(.*)\\z} =~ path)\n end",
"def command_in_path?(command)\n found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p|\n File.exist?(File.join(p, command))\n end\n found.include?(true)\n end",
"def command_in_path?(command)\n found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p|\n File.exist?(File.join(p, command))\n end\n found.include?(true)\n end",
"def test_found_returns_false_for_commands_not_found_in_path\n Crd::Flex::Command.new 'madeupcommandname' do |s|\n assert_equal( false, s.found? )\n end\n end",
"def command_available?(command)\n find = Releasy.win_platform? ? \"where\" : \"which\"\n # Call this Kernel version of `` so it can be mocked in testing.\n result = Kernel.`(\"#{find} #{command}\")\n return false unless $? == 0\n result\n end",
"def command_exists?(command)\n line(\"which\", \"{command}\").pass(command: command) != \"\"\n end",
"def has_executable(path)\n # Be smart: If the path includes a forward slash, we're checking\n # an absolute path. Otherwise, we're checking a global executable\n if path.include?('/')\n @commands << \"test -x #{path}\"\n else\n @commands << \"[ -n \\\"`echo \\\\`which #{path}\\\\``\\\" ]\"\n end\n end",
"def command_exists?\n File.exists? self.command_file\n end",
"def command_exist?(command)\r\n basename = File.basename(command)\r\n path = +\"\"\r\n print \"Checking #{basename}: \"\r\n begin\r\n if open(\"| which #{command} 2>/dev/null\") { |f| path = f.gets.strip }\r\n puts \"detected [#{path}]\"\r\n path.strip\r\n elsif open(\"| which #{basename} 2>/dev/null\") { |f| path = f.gets.strip }\r\n puts \"detected [#{path}]\"\r\n path.strip\r\n else\r\n puts \"#{basename} not found\"\r\n false\r\n end\r\n rescue StandardError\r\n puts \"#{basename} not found\"\r\n false\r\n end\r\n end",
"def command_exists?(command)\n !line(\"which\", \"{command}\").pass(command: command).nonzero_exit?\n end",
"def search_command(command, macroname, force, abort)\n path = @macros[macroname]\n\n if (!path) or path == '' or force\n if path = File .which(command)\n\t@macros[macroname] = path\n end\n end\n\n if path and File .executable?(path)\n print \"#{command} is .. #{path}\\n\"\n else\n search_abort(command, macroname) if abort\n return nil\n end\n end",
"def command?(path)\n p = Pathname.new(path)\n p.relative? && p.basename == p\n end",
"def command_exists?\n COMMANDS.include? @command\n end",
"def command_exists?(name)\n @commands[name.to_s]\n end",
"def installed?(cmd)\n !Garcon::FileHelper.which(cmd).nil?\n end",
"def command_exists? name\n @commands[name.to_s]\n end",
"def exist?(mask)\n recurse!(false)\n # Replace all back-slashes with two back-slashes\n # Due to back reference of .gsub we have to escape them twice\n mask.gsub! '\\\\', '\\\\\\\\\\\\\\\\' unless @options[:version] == 1\n execute('ls', mask, false)[0]\n end",
"def command_exists?(command)\n ENV['PATH'].split(File::PATH_SEPARATOR).any? {|d| File.exists? File.join(d, command) }\nend",
"def has_executable_with_version(path, version, get_version = '-v')\n if path.include?('/')\n @commands << \"[ -x #{path} -a -n \\\"`#{path} #{get_version} 2>&1 | egrep -e \\\\\\\"#{version}\\\\\\\"`\\\" ]\"\n else\n @commands << \"[ -n \\\"`echo \\\\`which #{path}\\\\``\\\" -a -n \\\"`\\\\`which #{path}\\\\` #{get_version} 2>&1 | egrep -e \\\\\\\"#{version}\\\\\\\"`\\\" ]\"\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
found returns false for commands not found in path
|
def test_found_returns_false_for_commands_not_found_in_path
Crd::Flex::Command.new 'madeupcommandname' do |s|
assert_equal( false, s.found? )
end
end
|
[
"def command_exists?\n File.exists? self.command_file\n end",
"def command_exists?(command)\n line(\"which\", \"{command}\").pass(command: command) != \"\"\n end",
"def test_found_returns_true_for_commands_found_in_path\n Crd::Flex::Command.new 'mxmlc' do |s|\n assert_equal( true, s.found? )\n end\n end",
"def command_exists?(command)\n !line(\"which\", \"{command}\").pass(command: command).nonzero_exit?\n end",
"def command?(path)\n !!(%r{\\A/(v(.*)/|)man\\/(.*)\\z} =~ path)\n end",
"def command_in_path?(command)\n found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p|\n File.exist?(File.join(p, command))\n end\n found.include?(true)\n end",
"def command_available?(command)\n find = Releasy.win_platform? ? \"where\" : \"which\"\n # Call this Kernel version of `` so it can be mocked in testing.\n result = Kernel.`(\"#{find} #{command}\")\n return false unless $? == 0\n result\n end",
"def command_in_path?(command)\n found = ENV['PATH'].split(File::PATH_SEPARATOR).map do |p|\n File.exist?(File.join(p, command))\n end\n found.include?(true)\n end",
"def command_exist?(command)\r\n basename = File.basename(command)\r\n path = +\"\"\r\n print \"Checking #{basename}: \"\r\n begin\r\n if open(\"| which #{command} 2>/dev/null\") { |f| path = f.gets.strip }\r\n puts \"detected [#{path}]\"\r\n path.strip\r\n elsif open(\"| which #{basename} 2>/dev/null\") { |f| path = f.gets.strip }\r\n puts \"detected [#{path}]\"\r\n path.strip\r\n else\r\n puts \"#{basename} not found\"\r\n false\r\n end\r\n rescue StandardError\r\n puts \"#{basename} not found\"\r\n false\r\n end\r\n end",
"def has_executable(path)\n # Be smart: If the path includes a forward slash, we're checking\n # an absolute path. Otherwise, we're checking a global executable\n if path.include?('/')\n @commands << \"test -x #{path}\"\n else\n @commands << \"[ -n \\\"`echo \\\\`which #{path}\\\\``\\\" ]\"\n end\n end",
"def installed?(cmd)\n !Garcon::FileHelper.which(cmd).nil?\n end",
"def command_exists?(name)\n @commands[name.to_s]\n end",
"def command_exists?\n COMMANDS.include? @command\n end",
"def command_exists? name\n @commands[name.to_s]\n end",
"def command_exists?(command)\n ENV['PATH'].split(File::PATH_SEPARATOR).any? {|d| File.exists? File.join(d, command) }\nend",
"def search_command(command, macroname, force, abort)\n path = @macros[macroname]\n\n if (!path) or path == '' or force\n if path = File .which(command)\n\t@macros[macroname] = path\n end\n end\n\n if path and File .executable?(path)\n print \"#{command} is .. #{path}\\n\"\n else\n search_abort(command, macroname) if abort\n return nil\n end\n end",
"def command?(path)\n p = Pathname.new(path)\n p.relative? && p.basename == p\n end",
"def command?(name)\n !which(name).nil?\n end",
"def system_command_available?(cmd)\n has_it = false\n begin\n cmd = cmd.strip.gsub(\"'\",'')\n system(\"which '#{cmd}' > /dev/null 2>&1\")\n has_it = $?.success?\n rescue => e\n raise e\n end\n return has_it\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /latstraps1s GET /latstraps1s.json
|
def index
@latstraps1s = Latstraps1.all
end
|
[
"def index\n @latstraps2s = Latstraps2.all\n end",
"def index\n @latstraps4s = Latstraps4.all\n end",
"def index\n @latstrapshome1s = Latstrapshome1.all\n end",
"def create\n @latstraps1 = Latstraps1.new(latstraps1_params)\n\n respond_to do |format|\n if @latstraps1.save\n format.html { redirect_to @latstraps1, notice: 'Latstraps1 was successfully created.' }\n format.json { render :show, status: :created, location: @latstraps1 }\n else\n format.html { render :new }\n format.json { render json: @latstraps1.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @latstrapshome4s = Latstrapshome4.all\n end",
"def index\n @latstrapshome2s = Latstrapshome2.all\n end",
"def index\n @splatts = Splatt.all\n\n render json: @splatts\n end",
"def index\n @latstrapshome3s = Latstrapshome3.all\n end",
"def update\n respond_to do |format|\n if @latstraps1.update(latstraps1_params)\n format.html { redirect_to \"/latstraps1s\"}\n format.json { render :show, status: :ok, location: @latstraps1 }\n else\n format.html { render :edit }\n format.json { render json: @latstraps1.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @straps = Strap.all\n\n end",
"def create\n @latstraps2 = Latstraps2.new(latstraps2_params)\n\n respond_to do |format|\n if @latstraps2.save\n format.html { redirect_to @latstraps2, notice: 'Latstraps2 was successfully created.' }\n format.json { render :show, status: :created, location: @latstraps2 }\n else\n format.html { render :new }\n format.json { render json: @latstraps2.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @lift_sets = LiftSet.all\n\n render json: @lift_sets\n end",
"def create\n @latstraps4 = Latstraps4.new(latstraps4_params)\n\n respond_to do |format|\n if @latstraps4.save\n format.html { redirect_to @latstraps4, notice: 'Latstraps4 was successfully created.' }\n format.json { render :show, status: :created, location: @latstraps4 }\n else\n format.html { render :new }\n format.json { render json: @latstraps4.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @laws = Law.ordered_roots\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @laws }\n end\n end",
"def index\n @start_bootstraps = StartBootstrap.all\n end",
"def show\n @splatt = Splatt.find(params[:id])\n\n render json: @splatt\n end",
"def create\n @latstrapshome1 = Latstrapshome1.new(latstrapshome1_params)\n\n respond_to do |format|\n if @latstrapshome1.save\n format.html { redirect_to @latstrapshome1, notice: 'Latstrapshome1 was successfully created.' }\n format.json { render :show, status: :created, location: @latstrapshome1 }\n else\n format.html { render :new }\n format.json { render json: @latstrapshome1.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @freelaws = Freelaw.ordered_roots\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @freelaws }\n end\n end",
"def index\n @gs1_masters = Gs1Master.page(params[:page])\n # @gs1_masters = Gs1Master.all\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /latstraps1s POST /latstraps1s.json
|
def create
@latstraps1 = Latstraps1.new(latstraps1_params)
respond_to do |format|
if @latstraps1.save
format.html { redirect_to @latstraps1, notice: 'Latstraps1 was successfully created.' }
format.json { render :show, status: :created, location: @latstraps1 }
else
format.html { render :new }
format.json { render json: @latstraps1.errors, status: :unprocessable_entity }
end
end
end
|
[
"def create\n @latstraps2 = Latstraps2.new(latstraps2_params)\n\n respond_to do |format|\n if @latstraps2.save\n format.html { redirect_to @latstraps2, notice: 'Latstraps2 was successfully created.' }\n format.json { render :show, status: :created, location: @latstraps2 }\n else\n format.html { render :new }\n format.json { render json: @latstraps2.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @latstraps4 = Latstraps4.new(latstraps4_params)\n\n respond_to do |format|\n if @latstraps4.save\n format.html { redirect_to @latstraps4, notice: 'Latstraps4 was successfully created.' }\n format.json { render :show, status: :created, location: @latstraps4 }\n else\n format.html { render :new }\n format.json { render json: @latstraps4.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @latstrapshome1 = Latstrapshome1.new(latstrapshome1_params)\n\n respond_to do |format|\n if @latstrapshome1.save\n format.html { redirect_to @latstrapshome1, notice: 'Latstrapshome1 was successfully created.' }\n format.json { render :show, status: :created, location: @latstrapshome1 }\n else\n format.html { render :new }\n format.json { render json: @latstrapshome1.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @latstraps1s = Latstraps1.all\n end",
"def create\n @strap = Strap.new(strap_params)\n\n respond_to do |format|\n if @strap.save\n format.html { redirect_to @strap, notice: \"Strap was successfully created.\" }\n format.json { render :show, status: :created, location: @strap }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @strap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @splatt = Splatt.new(splatts_params(params))\n\n if @splatt.save\n render json: @splatt, status: :created, location: @splatt\n else\n render json: @splatt.errors, status: :unprocessable_entity\n end\n end",
"def create\n @latstrapshome4 = Latstrapshome4.new(latstrapshome4_params)\n\n respond_to do |format|\n if @latstrapshome4.save\n format.html { redirect_to @latstrapshome4, notice: 'Latstrapshome4 was successfully created.' }\n format.json { render :show, status: :created, location: @latstrapshome4 }\n else\n format.html { render :new }\n format.json { render json: @latstrapshome4.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @latstraps1.update(latstraps1_params)\n format.html { redirect_to \"/latstraps1s\"}\n format.json { render :show, status: :ok, location: @latstraps1 }\n else\n format.html { render :edit }\n format.json { render json: @latstraps1.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @latstrapshome2 = Latstrapshome2.new(latstrapshome2_params)\n\n respond_to do |format|\n if @latstrapshome2.save\n format.html { redirect_to @latstrapshome2, notice: 'Latstrapshome2 was successfully created.' }\n format.json { render :show, status: :created, location: @latstrapshome2 }\n else\n format.html { render :new }\n format.json { render json: @latstrapshome2.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @latstrapshome3 = Latstrapshome3.new(latstrapshome3_params)\n\n respond_to do |format|\n if @latstrapshome3.save\n format.html { redirect_to @latstrapshome3, notice: 'Latstrapshome3 was successfully created.' }\n format.json { render :show, status: :created, location: @latstrapshome3 }\n else\n format.html { render :new }\n format.json { render json: @latstrapshome3.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @latstraps2s = Latstraps2.all\n end",
"def index\n @latstraps4s = Latstraps4.all\n end",
"def index\n @latstrapshome1s = Latstrapshome1.all\n end",
"def create\n @bootstrap = Bootstrap.new(params[:bootstrap])\n\n respond_to do |format|\n if @bootstrap.save\n format.html { redirect_to @bootstrap, notice: 'Bootstrap was successfully created.' }\n format.json { render json: @bootstrap, status: :created, location: @bootstrap }\n else\n format.html { render action: \"new\" }\n format.json { render json: @bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @start_bootstrap = StartBootstrap.new(start_bootstrap_params)\n\n respond_to do |format|\n if @start_bootstrap.save\n format.html { redirect_to @start_bootstrap, notice: \"Start bootstrap was successfully created.\" }\n format.json { render :show, status: :created, location: @start_bootstrap }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @start_bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @splatts = Splatt.all\n\n render json: @splatts\n end",
"def create\n @bootstrap = Bootstrap.new(bootstrap_params)\n\n respond_to do |format|\n if @bootstrap.save\n format.html { redirect_to @bootstrap, notice: 'Bootstrap was successfully created.' }\n format.json { render :show, status: :created, location: @bootstrap }\n else\n format.html { render :new }\n format.json { render json: @bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @smallmap = Smallmap.new(params[:smallmap])\n\n respond_to do |format|\n if @smallmap.save\n format.html { redirect_to @smallmap, notice: 'Smallmap was successfully created.' }\n format.json { render json: @smallmap, status: :created, location: @smallmap }\n else\n format.html { render action: \"new\" }\n format.json { render json: @smallmap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @latstraps2.update(latstraps2_params)\n format.html { redirect_to \"/latstraps2s\"}\n format.json { render :show, status: :ok, location: @latstraps2 }\n else\n format.html { render :edit }\n format.json { render json: @latstraps2.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PATCH/PUT /latstraps1s/1 PATCH/PUT /latstraps1s/1.json
|
def update
respond_to do |format|
if @latstraps1.update(latstraps1_params)
format.html { redirect_to "/latstraps1s"}
format.json { render :show, status: :ok, location: @latstraps1 }
else
format.html { render :edit }
format.json { render json: @latstraps1.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n respond_to do |format|\n if @latstrapshome1.update(latstrapshome1_params)\n format.html { redirect_to \"/latstrapshome1s\"}\n format.json { render :show, status: :ok, location: @latstrapshome1 }\n else\n format.html { render :edit }\n format.json { render json: @latstrapshome1.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @latstraps2.update(latstraps2_params)\n format.html { redirect_to \"/latstraps2s\"}\n format.json { render :show, status: :ok, location: @latstraps2 }\n else\n format.html { render :edit }\n format.json { render json: @latstraps2.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @latstraps4.update(latstraps4_params)\n format.html { redirect_to \"/latstraps4s\"}\n format.json { render :show, status: :ok, location: @latstraps4 }\n else\n format.html { render :edit }\n format.json { render json: @latstraps4.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @latstrapshome2.update(latstrapshome2_params)\n format.html { redirect_to \"/latstrapshome2s\"}\n format.json { render :show, status: :ok, location: @latstrapshome2 }\n else\n format.html { render :edit }\n format.json { render json: @latstrapshome2.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @latstrapshome4.update(latstrapshome4_params)\n format.html { redirect_to \"/latstrapshome4s\"}\n format.json { render :show, status: :ok, location: @latstrapshome4 }\n else\n format.html { render :edit }\n format.json { render json: @latstrapshome4.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @latstrapshome3.update(latstrapshome3_params)\n format.html { redirect_to \"/latstrapshome3s\"}\n format.json { render :show, status: :ok, location: @latstrapshome3 }\n else\n format.html { render :edit }\n format.json { render json: @latstrapshome3.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @strap.update(strap_params)\n format.html { redirect_to @strap, notice: \"Strap was successfully updated.\" }\n format.json { render :show, status: :ok, location: @strap }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @strap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @bootstrap = Bootstrap.find(params[:id])\n\n respond_to do |format|\n if @bootstrap.update_attributes(params[:bootstrap])\n format.html { redirect_to @bootstrap, notice: 'Bootstrap was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @example_lift_req.update(example_lift_req_params)\n format.html { redirect_to @example_lift_req, notice: 'Example lift req was successfully updated.' }\n format.json { render :show, status: :ok, location: @example_lift_req }\n else\n format.html { render :edit }\n format.json { render json: @example_lift_req.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(data, options={})\n raise NotImplementedError, \"We only patchs to singular resources.\" if count > 1\n first.patch(data, options)\n end",
"def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end",
"def update\n respond_to do |format|\n if @gs1_master.update(gs1_master_params)\n format.html { redirect_to @gs1_master, notice: UPDATE_NOTICE }\n format.json { render :show, status: :ok, location: @gs1_master }\n else\n format.html { render :edit }\n format.json { render json: @gs1_master.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @smallmap = Smallmap.find(params[:id])\n\n respond_to do |format|\n if @smallmap.update_attributes(params[:smallmap])\n format.html { redirect_to @smallmap, notice: 'Smallmap was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @smallmap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @bootstrap.update(bootstrap_params)\n format.html { redirect_to @bootstrap, notice: 'Bootstrap was successfully updated.' }\n format.json { render :show, status: :ok, location: @bootstrap }\n else\n format.html { render :edit }\n format.json { render json: @bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @start_bootstrap.update(start_bootstrap_params)\n format.html { redirect_to @start_bootstrap, notice: \"Start bootstrap was successfully updated.\" }\n format.json { render :show, status: :ok, location: @start_bootstrap }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @start_bootstrap.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @boot = Boot.find(params[:id])\n\n respond_to do |format|\n if @boot.update_attributes(params[:boot])\n flash[:success] = \"Updated successfully \"\n format.html { redirect_to boots_path, notice: 'Boot was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @boot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch *args\n make_request :patch, *args\n end",
"def update\n respond_to do |format|\n if @sizzlingplate.update(sizzlingplate_params)\n format.html { redirect_to @sizzlingplate, notice: 'Sizzlingplate was successfully updated.' }\n format.json { render :show, status: :ok, location: @sizzlingplate }\n else\n format.html { render :edit }\n format.json { render json: @sizzlingplate.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @slit_spec = SlitSpec.find(params[:id])\n\n respond_to do |format|\n if @slit_spec.update_attributes(params[:slit_spec])\n format.html { redirect_to @slit_spec, notice: 'Slit spec was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @slit_spec.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /latstraps1s/1 DELETE /latstraps1s/1.json
|
def destroy
@latstraps1.destroy
respond_to do |format|
format.html { redirect_to latstraps1s_url, notice: 'Latstraps1 was successfully destroyed.' }
format.json { head :no_content }
end
end
|
[
"def destroy\n @latstrapshome1.destroy\n respond_to do |format|\n format.html { redirect_to latstrapshome1s_url, notice: 'Latstrapshome1 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @latstraps2.destroy\n respond_to do |format|\n format.html { redirect_to latstraps2s_url, notice: 'Latstraps2 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @latstraps4.destroy\n respond_to do |format|\n format.html { redirect_to latstraps4s_url, notice: 'Latstraps4 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @strap.destroy\n respond_to do |format|\n format.html { redirect_to straps_url, notice: \"Strap was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @gs1_master.destroy\n respond_to do |format|\n format.html { redirect_to gs1_masters_url, notice: DELETE_NOTICE }\n format.json { head :no_content }\n end\n end",
"def destroy\n @latstrapshome4.destroy\n respond_to do |format|\n format.html { redirect_to latstrapshome4s_url, notice: 'Latstrapshome4 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @latstrapshome3.destroy\n respond_to do |format|\n format.html { redirect_to latstrapshome3s_url, notice: 'Latstrapshome3 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @json.destroy\n\n head :no_content\n end",
"def destroy\n @latstrapshome2.destroy\n respond_to do |format|\n format.html { redirect_to latstrapshome2s_url, notice: 'Latstrapshome2 was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_floor_plan(args = {}) \n delete(\"/files.json/floorplan/images\", args)\nend",
"def destroy\n @bootstrap = Bootstrap.find(params[:id])\n @bootstrap.destroy\n\n respond_to do |format|\n format.html { redirect_to bootstraps_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @splat = Splat.find(params[:id])\n @splat.destroy\n\n respond_to do |format|\n format.html { redirect_to splats_url }\n format.json { head :no_content }\n end\n end",
"def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"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\r\n @client1.destroy\r\n respond_to do |format|\r\n format.html { redirect_to client1s_url }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @smallmap = Smallmap.find(params[:id])\n @smallmap.destroy\n\n respond_to do |format|\n format.html { redirect_to smallmaps_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @kota_stone.destroy\n respond_to do |format|\n format.html { redirect_to kota_stones_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @seed_flat.destroy\n respond_to do |format|\n format.html { redirect_to seed_flats_basic_index_path, notice: 'Seed flat was successfully destroyed.' }\n format.json { head :no_content }\n end\n\n end",
"def destroy\n @json_datum.destroy\n respond_to do |format|\n format.html { redirect_to json_data_url }\n format.json { head :no_content }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns unique array in which records are sorted by occurrence within array (Descending)
|
def sort_by_occurrence(records)
count = Hash.new(0)
records.each {|element| count[element] += 1}
records = records.uniq.sort {|x,y| count[y] <=> count[x]}
return records
end
|
[
"def consolidate_by_frequency(array)\n array.group_by{|x| x}.values.sort_by{|group| group.count}.reverse.flatten(1).uniq\nend",
"def remove_approve_duplicates(array)\n return array.flatten.uniq.sort\n end",
"def sort_by_frequency(arr)\n arr.sort_by {|e| [-arr.count(e), e]}\nend",
"def remove_reject_duplicates(array)\n return array.flatten.uniq.sort\n end",
"def duplicates_subarray(arr)\n new_arr = []\n arr.each do |elm|\n duplicate = false\n new_arr.each do |sub_arr|\n if sub_arr.include?(elm)\n sub_arr << elm\n duplicate = true\n end\n end\n new_arr << [elm] unless duplicate\n end\n new_arr.sort_by {|sub_arr| sub_arr[0].ord }\nend",
"def get_sorted_array\n @data.sort_by { |key, count| count }\n end",
"def sorted_and_unique_favorite_numbers\n occurences.map {|key, value| key}.sort\n end",
"def sort_by_frequency_with_details\n histogram = inject(Hash.new(0)) { |hash, x| hash[x] += 1; hash}\n histogram.to_a.map { |arr| [arr[1], arr[0]] }.sort_by {|arr| arr[0]}.reverse\n end",
"def reduce_array(arr)\n seen = Hash.new(0)\n\n arr.each do |nested|\n nested.each do |el|\n seen[el] += el\n end\n end\n\n seen.values.sort\nend",
"def bucketize(arr)\n output = []\n (0..arr.size).each do |ind|\n output_item = arr.select { |item| arr.count(item) == ind }.uniq.sort\n output_item.empty? ? output << nil : output << output_item\n end\n output\nend",
"def sort_array\n @data.sorted_by.inject([]) do |memo, (key, value)|\n memo << [@data.columns.index(key), value == 'descending' ? 0 : 1]\n end\n end",
"def unfreq_list(historical_array,topitems)\r\n historical_array=historical_array\r\n answer= Array.new\r\n for i in 0...historical_array.length\r\n oneorder= historical_array[i]\r\n remaining_array = oneorder.clone-topitems\r\n if remaining_array.length < oneorder.length #it means that it contains item in top item list\r\n #push the item in the remaining array into the answer\r\n for j in 0...remaining_array.length\r\n item = remaining_array[j]\r\n if !answer.include?(item)\r\n #if the item is not in the list, push it into the list\r\n answer << item\r\n end\r\n end\r\n end\r\n end\r\n return answer\r\nend",
"def using_uniq(array)\n\n \nend",
"def sorted_array_unique_views\n total_unique_views_per_file_path.sort { |a, b| b[1] <=> a[1] }\n end",
"def get_unique(array,index)\n a = array.sort_by { |x| x[index] }\n return a.inject([]) do |result,item| \n result << item if !result.last||result.last[index]!=item[index]\n result\n end\nend",
"def top_three(array)\n el_count = {}\n array.each do |h|\n el_count.has_key?(h) ? el_count[h] += 1 : el_count[h] = 1\n end\n array.uniq.sort_by { |h| el_count[h] }.reverse.shift(3)\nend",
"def using_uniq (array)\n\tarray.uniq\nend",
"def mode(array)\n sort_hash = Hash.new(0)\n\n array.each do |element|\n sort_hash[element] += 1\n end\n\n result = []\n highest_freq = 0\n p sort_hash\n sort_hash.each_key do |key|\n if (sort_hash[key] == highest_freq)\n result << key\n elsif (sort_hash[key] > highest_freq)\n result.clear\n result << key\n highest_freq = sort_hash[key]\n end\n end\n p result\nend",
"def get_common_elements (passed_array, needle)\n temparray = passed_array.pluck('DISTINCT ' + needle)\n count_array = Array.new()\n count = 0\n\n\n temparray.each do |t|\n\n count_array.push( [t, passed_array.where(needle => t).count] )\n #count = count + 1\n end\n\n\n \n ordered = count_array.sort_by(&:last).reverse\n\n if ordered.fourth != nil\n ordered = ordered.first + ordered.second + ordered.third + ordered.fourth \n end\n \n return ordered\n\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns unique hash in which records are sorted by "record" => "occurrence" (Descending)
|
def sort_by_occurrence_h(input)
output = input.each_with_object(Hash.new(0)){ |tag, counts| counts[tag] += 1 }
output = Hash[output.sort_by{ |tags, counts| counts}.reverse]
return output
end
|
[
"def sort_by_occurrence(records)\n count = Hash.new(0)\n records.each {|element| count[element] += 1}\n records = records.uniq.sort {|x,y| count[y] <=> count[x]}\n return records\n end",
"def unique_visit\n parsed_result.each do |result|\n visit_hash[result.first] = result.last.uniq.count\n end\n visit_hash.sort_by{|k,v| v}.reverse.to_h\n end",
"def sort_by_frequency_with_details\n histogram = inject(Hash.new(0)) { |hash, x| hash[x] += 1; hash}\n histogram.to_a.map { |arr| [arr[1], arr[0]] }.sort_by {|arr| arr[0]}.reverse\n end",
"def sorted_and_unique_favorite_numbers\n occurences.map {|key, value| key}.sort\n end",
"def sort_and_get_uniques\n @seq_hash = @seq_hash.sort.to_h\n @seq_hash = @seq_hash.select {|seq, word| word.count == 1}\n puts \n end",
"def hash_to_hist(hhash)\n hhash.map{ |k,v| [k, v.size] }.to_h.sort_by{|k,v| v}.reverse.to_h\n end",
"def sort_by_frequency\n histogram = inject(Hash.new(0)) { |hash, x| hash[x] += 1; hash}\n sort_by { |x| [histogram[x], x] }\n end",
"def sort_by_occurrence(list)\n map = {}\n count = [999, list.length].min\n for word in list\n word = word.downcase\n map[word] ||= count\n map[word] += 1000\n count -= 1 if count > 0\n end\n map.to_a.sort_by {|x| -x.last}.map {|x| x.first}\n end",
"def db_sort_and_save\n fingerprints = db(true).sort_by { |_path, fp| fp.values.select { |v| v.size == 1 }.size }.reverse.to_h\n\n fingerprints.each_value do |hashes|\n hashes.each_value { |versions| versions.sort! { |a, b| compare_version(a, b) } }\n end\n\n save_db(fingerprints)\n end",
"def freq_list\n freq_hash = each_with_object(Hash.new(0)) { |v, h| h[v] += 1 }\n freq_hash.sort_by { |k, v| -v }\n end",
"def login_occurrence_user\n\n file = '/Users/sneha/Documents/count_number_of_users_login'\n f = open file\n hash = Hash.new()\n\n f.each_line do |line|\n words = line.split\n words.each do |word|\n w = word.downcase()\n w = clear_word(w)\n if hash[w]\n hash[w] = hash[w] + 1\n else\n hash[w] = 1\n end\n end\n end\n\n hash.sort.map.each do |key,val|\n puts \"#{key} => #{val}\"\n end\n\nend",
"def most_used(some_hash)\n\treference = some_hash.first\n\tsome_hash.each do |compare|\n\t\tif compare[1] > reference[1]\n\t\t\treference = compare\n\t\tend\n\tend\n\treference\nend",
"def sort_and_print(hash, type=\"visits\")\n new_hash = hash.sort_by { |page, visits| -visits}.to_h\n # Print into console to check\n new_hash.each do |page, number_of_visits|\n print page + \" \" + number_of_visits.to_s + \" \" + type + \" \"\n end\n # Return sorted hash\n return new_hash\nend",
"def build_freqs str\n # Build hash of byte => count\n counts = Hash.new 0\n str.each_byte { |byte| counts[byte.chr] += 1 }\n\n # Build SortedSet of [freq, byte] pairs (lower freqs first).\n freqs = SortedSet[]\n counts.each { |bc| freqs << bc.reverse }\n freqs\nend",
"def consolidate_by_frequency(array)\n array.group_by{|x| x}.values.sort_by{|group| group.count}.reverse.flatten(1).uniq\nend",
"def calculate_unique_page_views\n ip_frequency_per_page = calculate_ip_frequency_per_page\n ip_frequency_per_page.transform_values { |value| value.uniq.length }.sort_by { |_key, value| value }.reverse.to_h\n end",
"def unique_entries_by_(key) \n seen = Set.new()\n entries.select { |e|\n k = e.send(key)\n seen.add?(k)\n }.sort{|a, b| a.range.low <=> b.range.low }\n end",
"def get_last_element_sorted_by_value(element)\n Hash[get_last_element_of_hash(element).sort_by{|k, v| v}.reverse]\n end",
"def hash\n excl = @exclude_end ? 1 : 0\n hash = excl\n hash ^= @first.hash << 1\n hash ^= @last.hash << 9\n hash ^= excl << 24;\n return hash\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Register this class for the given +id+. Example: class MyPlugin < PluginHost::BaseClass register_for :my_id ... end See PluginHost.register.
|
def register_for id
@plugin_id = id
plugin_host.register self, id
end
|
[
"def register_for(id); end",
"def register plugin, id\n plugin_hash[validate_id(id)] = plugin\n end",
"def register(plugin, id); end",
"def register(id, klass)\n ETL.logger.debug(\"Registering job class with manager: #{id} => #{klass}\")\n if @job_classes.has_key?(id)\n ETL.logger.warn(\"Overwriting previous registration of: #{id} => #{@job_classes[id]}\")\n end\n @job_classes[id] = klass\n end",
"def register(identifier, klass)\n @klasses[identifier] = klass\n end",
"def register( id, handler )\n @requests[ id ] = handler\n end",
"def register_identifier(klass, identifier)\n Emittance::EventLookup::Registry.register_identifier klass: klass, identifier: identifier\n end",
"def []=(plugin_id, plugin_class)\n if @plugins.key?(plugin_id)\n log_warn \"[ #{@plugins_type} ] - A plugin of type #{@plugins_type} named #{plugin_id} is already registered. Can't overwrite #{@plugins[plugin_id]} with #{plugin_class.name}. Will ignore #{plugin_class.name}.\"\n else\n # Set the logger in the class so that we can use it in class methods\n plugin_class.logger = @logger\n plugin_class.logger_stderr = @logger_stderr\n if plugin_class.valid?\n log_debug \"[ #{@plugins_type} ] - Register #{plugin_id} to #{plugin_class.name}.\"\n @plugins[plugin_id] = @init_plugin.nil? ? plugin_class : @init_plugin.call(plugin_class)\n else\n log_error \"[ #{@plugins_type} ] - The plugin #{plugin_id} (#{plugin_class.name}) is missing some dependencies to be activated. Will ignore it.\"\n end\n end\n end",
"def register_plugin klass\n self.plugins << klass\n end",
"def register(identifier, klass)\n if @klasses[identifier]\n raise DuplicateEntry, :registry => @name,\n :identifier => identifier.inspect\n else\n @klasses[identifier] = klass\n end\n end",
"def register(object); end",
"def register_engine(id, &block)\n conf = Confstruct::Configuration.new(&block)\n conf.id = id.to_s\n \n raise ArgumentError.new(\"Must supply an `engine` class name\") unless conf.engine\n \n @registered_engine_confs[id] = conf \n end",
"def register_object(obj,id)\n\t\tunless @objects[id]\n\t\t\t@objects[id] = obj\n\t\tend\n\tend",
"def register(obj)\n registry[obj.fullname] = obj\n end",
"def register(config, base_path)\n config.configuration = self\n config.base_path = base_path\n if config.kind_of? SubsystemConfiguration\n config.each_plugin {|plugin_config| register(plugin_config, base_path)}\n return\n end\n @plugins[config.name] = config if config.autoload?\n end",
"def id(id)\n class_eval <<-RUBY, __FILE__, __LINE__+1\n def tag_id\n #{id.to_s.inspect}\n end\n RUBY\n end",
"def register(id, klass, klass_factory=nil)\n id_str = id.to_s\n ETL.logger.debug(\"Registering job class with manager: #{id_str} => #{klass}\")\n if @job_classes.has_key?(id)\n ETL.logger.warn(\"Overwriting previous registration of: #{id_str} => #{@job_classes[id_str]}\")\n end\n\n if !klass_factory.nil?\n ETL.logger.debug(\"Registering job class factory with manager: #{id_str}\")\n if @job_classes.has_key?(id_str)\n ETL.logger.warn(\"Overwriting previous registration of job factory: #{id_str}\")\n end\n @job_class_factories[id_str] = klass_factory\n end\n\n @job_classes[id_str] = klass\n end",
"def registered?(id)\n @definitions.has_key? id\n end",
"def register_callback(id, &block)\n callback = block\n @registered_callbacks[id] = callback\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
The PluginHost for this Plugin class.
|
def plugin_host host = nil
if host.is_a? PluginHost
const_set :PLUGIN_HOST, host
end
self::PLUGIN_HOST
end
|
[
"def instance\n unless @plugin_instance\n @plugin_instance = FreeBASE::Plugin.new(@configuration.core, self)\n end\n @plugin_instance\n end",
"def plugin_host(host = T.unsafe(nil)); end",
"def plugin\n # $stderr.puts \"#{self.class.name} #{id || 'new'} plugin\"\n @plugin ||=\n (content_type ? \n content_type.plugin_instance :\n ContentType.null_plugin_instance\n ).mix_into_object(self)\n end",
"def host\r\n return for_context(nil, false) { |c| c.host }\r\n end",
"def plugins\n logger.info \"Creating plugin manager for #{description}\"\n Derelict::Plugin::Manager.new(self)\n end",
"def host\n configure\n locations[self][:host] || DEFAULT_LOCATION[:host]\n end",
"def host_components\n return @host_components\n end",
"def hosts_service\n @hosts_service ||= ExternalHostsService.new(self, 'hosts')\n end",
"def host\n active_backend.host\n end",
"def host\n ctx.host\n end",
"def manager\n @plugin.manager\n end",
"def hosts_service\n @hosts_service ||= HostsService.new(self, 'hosts')\n end",
"def external_host_provider\n @external_host_provider\n end",
"def host\n @host ||= Babushka::SystemProfile.for_host\n end",
"def plugins\n @plugins ||= Plugins.new\n end",
"def get_host\n @host\n end",
"def plugin_manager\n @plugin_manager ||=\n begin\n @@plugin_manager ||=\n Plugin::Manager.factory.new(:main => self)\n x = @@plugin_manager # .dup\n x.main = self\n x\n end\n end",
"def host_namespace\n self\n end",
"def host\n @node.host\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Calculates the zone outdoor airflow requirement and divides by the zone area.
|
def outdoor_airflow_rate_per_area()
tot_oa_flow_rate_per_area = 0.0
# Find total area of the zone
sum_floor_area = 0.0
self.spaces.sort.each do |space|
sum_floor_area += space.floorArea
end
# Get the OA flow rate
tot_oa_flow_rate = outdoor_airflow_rate
# Calculate the per-area value
tot_oa_flow_rate_per_area = tot_oa_flow_rate / sum_floor_area
OpenStudio::logFree(OpenStudio::Info, "openstudio.Standards.Model", "For #{self.name}, OA per area = #{tot_oa_flow_rate_per_area.round(8)} m^3/s*m^2.")
return tot_oa_flow_rate_per_area
end
|
[
"def area_wrt_ground ()\n \n end",
"def fare\n total = 0\n zone_price = (@journey[:start].zone - @journey[:end].zone).abs\n total = @@MIN_FARE + zone_price\n end",
"def calculate_fare(start_zone=nil, end_zone=nil)\n start_zone ||= 1\n end_zone ||= 1\n fare = ZONE_FARES[start_zone - 1][end_zone - 1]\n end",
"def zone_for(px, pz, sz_bot, sz_top)\n # puts \"calculating zone: #{px}, #{pz}, #{sz_bot}, #{sz_top}\"\n zone = [-0.70833, -0.23611, 0.23611, 0.70833, 100].index{|lower_bound| lower_bound > px} + 1\n zone += 5 * [sz_top, (2*sz_top/3 + sz_bot/3), (2*sz_bot/3 + sz_top/3), sz_bot, -100].index{|bound| bound < pz}\n # puts zone\n return zone\n end",
"def calculate_area\n\n \tarea = 3.14*@radius*@radius\n\n end",
"def percent_zcta_land_area\n land_area / zcta.land_area\n end",
"def get_area()\n # Finds the floor and space parents and assigns them to @floor and @space \n # variables to be used later\n begin\n floor = get_floor()\n space = get_space()\n # Get the keyword value for location\n location = get_keyword_value(\"LOCATION\")\n # Get the keyword value for polygon\n polygon_id = get_keyword_value(\"POLYGON\")\n rescue\n end\n \n \n # if the polygon_id keyword value was nil and the location value was nil, then \n # the height and width are directly defined within the \"exteriorWall\" command\n \n if ( location == \"BOTTOM\" || location == \"TOP\") && (space.get_shape != \"BOX\")\n return space.polygon.get_area \n \n elsif ( location == nil && polygon_id == nil )\n height = get_keyword_value(\"HEIGHT\")\n width = get_keyword_value(\"WIDTH\")\n #puts \"Direct:\" + height + \" times \" + width\n height = height.to_f\n width = width.to_f\n \n return height * width\n elsif ( location == nil && polygon_id != nil)\n return space.polygon.get_area\n \n \n # if the location was defined as \"SPACE...\", it is immediately followed by a\n # vertex, upon which lies the width of the exteriorwall\n elsif location.match(/SPACE.*/)\n location = location.sub( /^(.{6})/, \"\")\n width = space.polygon.get_length(location)\n if space.check_keyword?(\"HEIGHT\")\n height = space.get_height\n else\n height = floor.get_space_height\n end\n #puts floor.utype\n #puts \"Space:\" + height.to_s + \" times \" + width.to_s\n return width * height\n # if the shape was a box, the width and height would be taken from the\n # \"SPACE\" object\n elsif ( space.get_shape == \"BOX\" ) \n width = space.get_width\n height = space.get_height\n return width * height\n \n \n else\n raise \"The area could not be evaluated\"\n end\n end",
"def calculate_final_fare(origin_station, destination_station)\n zones = Zone.new(origin_station, destination_station).perform\n if zones[:check_zone_one]\n send(\"#{zones[:count_zone]}_zone_higher_fare\".to_sym)\n else\n send(\"#{zones[:count_zone]}_zone_standard_fare\".to_sym)\n end\n end",
"def apply_multizone_vav_outdoor_air_sizing()\n \n OpenStudio::logFree(OpenStudio::Info, 'openstudio.model.Model', 'Started applying HVAC efficiency standards.')\n \n # Multi-zone VAV outdoor air sizing\n self.getAirLoopHVACs.sort.each {|obj| obj.apply_multizone_vav_outdoor_air_sizing} \n\n end",
"def get_floor_area\n return @total_floor_area\n end",
"def calc_zone_residual_demand(operator_id, req_type, zone_id)\n res = Yarray.new(year, arr: @requirements[req_type][zone_id])\n if @competitor_production[operator_id].has_key? zone_id # TODO: e se fossero più di una?\n res -= Yarray.new(year, arr: @competitor_production[operator_id][zone_id])\n end\n if @imports.has_key? zone_id # TODO: e se fossero più di una?\n res -= Yarray.new(year, arr: @imports[zone_id])\n end\n @limits.fetch(zone_id, {}).each_pair do |from_zone_id, v|\n res -= Yarray.new(year, arr: v)\n end\n res\n end",
"def handling_cost(aircraft = nil)\n # mtow = aircraft.mtow\n # mtow = 0.0 if mtow.nil?\n # self.landing_rate_per_tonne * mtow\n\n cost = 0.0\n cost = aircraft.aircraft_type.aircraft_category.handling_cost_grids.where(city_id: self.city_id).first.cost if aircraft.aircraft_type.aircraft_category.handling_cost_grids.where(city_id: self.city_id).present?\n cost\n end",
"def percent_zcta_total_area\n total_area / zcta.total_area\n end",
"def percent_place_land_area\n land_area / place.land_area\n end",
"def option_airports\n RouteCalculator.new(orig: origin).calculate_destinations\n end",
"def zone\n if @zone\n @zone\n elsif !self[Place.zone_predicate].empty?\n @zone = Zone.find(self[Place.zone_predicate].first)\n else\n nil\n end\n end",
"def zone_number\n end",
"def get_area\n\n # get the keyword for the shape of the floor\n case get_keyword_value(\"SHAPE\")\n\n # if the keyword value is \"BOX\", the width and depth values are defined\n when \"BOX\"\n return get_keyword_value(\"WIDTH\").to_f * get_keyword_value(\"DEPTH\").to_f\n\n # if the keyword value is \"POLYGON\", the get_area is defined as the area of the\n # given polygon\n when \"POLYGON\"\n return @polygon.get_area\n\n # if the keyword value of the floor is \"No-SHAPE\", the get_area is given as the\n # get_area keyword value\n when \"NO-SHAPE\"\n return get_keyword_value(\"AREA\").to_f\n else\n raise \"Error: The area could not be evaluated. Please check inputs\\n \"\n end\n end",
"def area\n matrix = Matrix[[@p2.x - @p1.x, @p2.y - @p1.y], [@p3.x - @p1.x, @p3.y - @p1.y]]\n (0.5 * matrix.det).abs\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Function for testing a preprocessor
|
def test_preprocessor(preprocessor,input,expected)
# Prepare the output and the input streams
puts "Preparing the input and ouput streams..."
output = StringIO.new("")
# Process the input and exepected arguments.
if !input.respond_to?(:each_line) or input.is_a?(String) then
# input is actually a file name, open it.
input = File.open(input.to_s,"r")
end
if !expected.respond_to?(:each_line) or expected.is_a?(String) then
# expected is actually a file name, open it.
expected = StringIO.new(File.read(expected.to_s))
end
# Apply the preprocessor
puts "Applying the preprocessor..."
preprocessor.preprocess(input,output)
# Check the result
puts "Checking the result..."
output.rewind
check = output.string == expected.read
unless check
puts "*Error*: invalid expansion result."
iline = output.string.each_line
expected.rewind
expected.each_line.with_index do |exp_line,i|
line = iline.next
puts "exp_line=#{exp_line}"
puts "line=#{line}"
if exp_line != line then
puts "Expected line #{i+1}:\n#{exp_line}"
puts "got:\n#{line}"
end
end
return false
end
return true
end
|
[
"def preprocessors; end",
"def test_preprocessor_exception(preprocessor,string,exception)\n input = StringIO.new(string)\n output = StringIO.new(\"\")\n begin\n $ppr.preprocess(input,output)\n puts \"*Error*: preprocessed without exception.\"\n return false\n rescue Exception => e\n if e.to_s.include?(exception.to_s) then\n puts \"Got exception: <#{e}> as expected.\"\n return true\n else\n puts \"*Error*: unexpected exception.\", \n \"Got <#{e}> but expecting <#{exception}>.\"\n return false\n end\n end\nend",
"def cppSettingsTest(concreteSettings)\n \"#if \" + concreteSettings.to_a.collect{\n | pair |\n (if pair[1]\n \"\"\n else\n \"!\"\n end) + \"OFFLINE_ASM_\" + pair[0]\n }.join(\" && \")\nend",
"def register_preprocessor(*args, &block); end",
"def preprocess_conditional_inclusion directive, target, delimiter, text\n # must have a target before brackets if ifdef or ifndef\n # must not have text between brackets if endif\n # don't honor match if it doesn't meet this criteria\n # QUESTION should we warn for these bogus declarations?\n if ((directive == 'ifdef' || directive == 'ifndef') && target.empty?) ||\n (directive == 'endif' && !text.nil?)\n return false\n end\n\n if directive == 'endif'\n stack_size = @conditional_stack.size\n if stack_size > 0\n pair = @conditional_stack.last\n if target.empty? || target == pair[:target]\n @conditional_stack.pop\n @skipping = @conditional_stack.empty? ? false : @conditional_stack.last[:skipping]\n else\n warn \"asciidoctor: ERROR: #{line_info}: mismatched macro: endif::#{target}[], expected endif::#{pair[:target]}[]\"\n end\n else\n warn \"asciidoctor: ERROR: #{line_info}: unmatched macro: endif::#{target}[]\"\n end\n return true\n end\n\n skip = false\n unless @skipping\n # QUESTION any way to wrap ifdef & ifndef logic up together?\n case directive\n when 'ifdef'\n case delimiter\n when nil\n # if the attribute is undefined, then skip\n skip = !@document.attributes.has_key?(target)\n when ','\n # if any attribute is defined, then don't skip\n skip = !target.split(',').detect {|name| @document.attributes.has_key? name }\n when '+'\n # if any attribute is undefined, then skip\n skip = target.split('+').detect {|name| !@document.attributes.has_key? name }\n end\n when 'ifndef'\n case delimiter\n when nil\n # if the attribute is defined, then skip\n skip = @document.attributes.has_key?(target)\n when ','\n # if any attribute is undefined, then don't skip\n skip = !target.split(',').detect {|name| !@document.attributes.has_key? name }\n when '+'\n # if any attribute is defined, then skip\n skip = target.split('+').detect {|name| @document.attributes.has_key? name }\n end\n when 'ifeval'\n # the text in brackets must match an expression\n # don't honor match if it doesn't meet this criteria\n if !target.empty? || !(expr_match = text.strip.match(REGEXP[:eval_expr]))\n return false\n end\n\n lhs = resolve_expr_val expr_match[1]\n # regex enforces a restrict set of math-related operations\n op = expr_match[2]\n rhs = resolve_expr_val expr_match[3]\n\n skip = !(lhs.send op.to_sym, rhs)\n end\n end\n\n # conditional inclusion block\n if directive == 'ifeval' || text.nil?\n @skipping = true if skip\n @conditional_stack << {:target => target, :skip => skip, :skipping => @skipping}\n # single line conditional inclusion\n else\n unless @skipping || skip\n # FIXME slight hack to skip past conditional line\n # but keep our synthetic line marked as processed\n conditional_line = peek_line true\n replace_line \"#{text.rstrip}#{::Asciidoctor::EOL}\"\n unshift conditional_line\n return true\n end\n end\n\n true\n end",
"def preprocess_conditional_inclusion(directive, target, delimiter, text)\n # must have a target before brackets if ifdef or ifndef\n # must not have text between brackets if endif\n # don't honor match if it doesn't meet this criteria\n if ((directive == 'ifdef' || directive == 'ifndef') && target.empty?) ||\n (directive == 'endif' && !text.nil?)\n @next_line_preprocessed = true\n return false\n end\n\n if directive == 'endif'\n stack_size = @conditionals_stack.size\n if stack_size > 0\n pair = @conditionals_stack.last\n if target.empty? || target == pair[:target]\n @conditionals_stack.pop\n @skipping = @conditionals_stack.empty? ? false : @conditionals_stack.last[:skipping]\n else\n puts \"asciidoctor: ERROR: line #{@lineno + 1}: mismatched macro: endif::#{target}[], expected endif::#{pair[:target]}[]\"\n end\n else\n puts \"asciidoctor: ERROR: line #{@lineno + 1}: unmatched macro: endif::#{target}[]\"\n end\n advance\n return preprocess_next_line.nil? ? nil : true\n end\n\n skip = false\n if !@skipping\n case directive\n when 'ifdef'\n case delimiter\n when nil\n # if the attribute is undefined, then skip\n skip = !@document.attributes.has_key?(target)\n when ','\n # if any attribute is defined, then don't skip\n skip = !target.split(',').detect {|name| @document.attributes.has_key? name }\n when '+'\n # if any attribute is undefined, then skip\n skip = target.split('+').detect {|name| !@document.attributes.has_key? name }\n end\n when 'ifndef'\n case delimiter\n when nil\n # if the attribute is defined, then skip\n skip = @document.attributes.has_key?(target)\n when ','\n # if any attribute is undefined, then don't skip\n skip = !target.split(',').detect {|name| !@document.attributes.has_key? name }\n when '+'\n # if any attribute is defined, then skip\n skip = target.split('+').detect {|name| @document.attributes.has_key? name }\n end\n when 'ifeval'\n # the text in brackets must match an expression\n # don't honor match if it doesn't meet this criteria\n if !target.empty? || !(expr_match = text.strip.match(REGEXP[:eval_expr]))\n @next_line_preprocessed = true\n return false\n end\n\n lhs = resolve_expr_val(expr_match[1])\n op = expr_match[2]\n rhs = resolve_expr_val(expr_match[3])\n\n skip = !lhs.send(op.to_sym, rhs)\n end\n end\n advance\n # single line conditional inclusion\n if directive != 'ifeval' && !text.nil?\n if !@skipping && !skip\n unshift_line \"#{text.rstrip}\\n\"\n return true\n end\n # conditional inclusion block\n else\n if !@skipping && skip\n @skipping = true\n end\n @conditionals_stack << {:target => target, :skip => skip, :skipping => @skipping}\n end\n return preprocess_next_line.nil? ? nil : true\n end",
"def is_compiler_file contents\n contents.lines.each do |l|\n next if l =~ /^\\s*(\"|$)/; # skip blank lines and comments\n # afaict 'if exists(\"current_compiler\")' on the first line means compiler plugin\n return l =~ /^\\s*if\\s*\\(?\\s*exists\\s*\\(\\s*[\"']current_compiler[\"']\\s*\\)/\n end\n return false\nend",
"def test_comment\n assert_equal( @assembler.is_comment?(\"\"), nil )\n assert_equal( @assembler.is_comment?(\"token\"), nil )\n assert_equal( @assembler.is_comment?(\";\"), \";\" )\n assert_equal( @assembler.is_comment?(\";This\"), \";This\" )\n assert_equal( @assembler.is_comment?(\"token;\"), nil )\n end",
"def formatPreprocessor(theLines)\n\n\talignEndifs(\t\ttheLines);\n\talignUndefineDefine(theLines);\n\talignDefineValue(\ttheLines);\n\talignContinuations(\ttheLines);\n\n\treturn theLines;\n\nend",
"def test_include_flags()\n\t\tflags = @cc.include_flags( [ 'include', 'lib', 'test' ] )\n\t\tassert_equal( ' -Iinclude -Ilib -Itest', flags )\n\tend",
"def mock_defines(mock_config)\n family = mock_el_family(mock_config)\n version = mock_el_ver(mock_config)\n defines = \"\"\n if version =~ /^(4|5)$/ or family == \"sles\"\n defines = %(--define \"dist .#{family}#{version}\" \\\n --define \"_source_filedigest_algorithm 1\" \\\n --define \"_binary_filedigest_algorithm 1\" \\\n --define \"_binary_payload w9.gzdio\" \\\n --define \"_source_payload w9.gzdio\" \\\n --define \"_default_patch_fuzz 2\")\n end\n defines\nend",
"def testDefaultEmbeddingRubyUncomment2F\n RCodeLeveler::set_level(2)\n $CondVar = false\n requireFile('DefaultEmbeddingRuby')\n assert_equal(nil,$Var1)\n assert_equal(nil,$Var2)\n end",
"def preprocess_next_line\n # this return could be happening from a recursive call\n return nil if @eof || (next_line = @lines.first).nil?\n if next_line.include?('::') && (next_line.include?('if') || next_line.include?('endif')) && (match = next_line.match(REGEXP[:ifdef_macro]))\n if next_line.start_with? '\\\\'\n @next_line_preprocessed = true\n @unescape_next_line = true\n false\n else\n preprocess_conditional_inclusion(*match.captures)\n end\n elsif @skipping\n advance\n # skip over comment blocks, we don't want to process directives in them\n skip_comment_lines :include_blank_lines => true, :preprocess => false\n preprocess_next_line.nil? ? nil : true\n elsif next_line.include?('include::') && match = next_line.match(REGEXP[:include_macro])\n if next_line.start_with? '\\\\'\n @next_line_preprocessed = true\n @unescape_next_line = true\n false\n else\n preprocess_include(match[1], match[2].strip)\n end\n else\n @next_line_preprocessed = true\n false\n end\n end",
"def assertConfiguration(concreteSettings)\n $output.puts cppSettingsTest(concreteSettings)\n $output.puts \"#else\"\n $output.puts \"#error \\\"Configuration mismatch.\\\"\"\n $output.puts \"#endif\"\nend",
"def process_defined(exp)\n thing = process exp.shift\n return t(:defined, thing, CType.bool)\n end",
"def macros\n config.macros\n end",
"def debug_include\n'#ifndef NDEBUG\n#include <iostream>\n#endif'\n end",
"def unregister_preprocessor(*args); end",
"def pre_processors\n @pre_processors ||= []\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Function for testing a preprocessor on +string+ which should raise an +exception+ string.
|
def test_preprocessor_exception(preprocessor,string,exception)
input = StringIO.new(string)
output = StringIO.new("")
begin
$ppr.preprocess(input,output)
puts "*Error*: preprocessed without exception."
return false
rescue Exception => e
if e.to_s.include?(exception.to_s) then
puts "Got exception: <#{e}> as expected."
return true
else
puts "*Error*: unexpected exception.",
"Got <#{e}> but expecting <#{exception}>."
return false
end
end
end
|
[
"def exception(string)\n #This is a stub, used for indexing\n end",
"def mk_exc(_message)\n assert false\nrescue => err\n err\nend",
"def check_and_raise_error(exception, message)\n fail exception unless exception.message.include?(message)\n end",
"def exception(string = nil)\n return self if string.nil? or string.equal? self\n return self.class.exception(string)\n end",
"def test_exception_with_string()\r\n\r\n # Perform the API call through the SDK function\r\n assert_raise('ExceptionWithStringException'){ \r\n result = self.class.controller.get_exception_with_string()\r\n }\r\n\r\n # Test response code\r\n assert_equal(@response_catcher.response.status_code, 444)\r\n end",
"def test_msg_exception\n # 2.1 check exception\n ex = assert_raises RuntimeError do\n raise 'you are the best.'\n end\n # 2.2 check msg exception\n assert_equal('you are the best.', ex.message)\n end",
"def test_error_message_invalid_il\n warning_regexp = Regexp.new(\"Error reported by IL parser: Encountered \\\" <IDENTIFIER> \\\"\" +\n \"compact_string_to_single_term\\\"\\\" at line 5, column 57.\")\n begin\n deploy_app(SearchApp.new.sd(selfdir+\"invalid_il_expression_name.sd\"))\n assert(false)\n rescue ExecuteError => ee\n assert_match(warning_regexp, ee.output)\n end\n end",
"def test_gen_strings_bad_exclude_type\n assert_raises TypeError do\n RFauxFactory.gen_strings(exclude: 'string as exclude')\n end\n end",
"def test_Add_Should_ThrowException_When_CalledWithInputContainsUnsupportedSeparatorWithCustomSeparatorDeclaration9\n # Arrange.\n @inputValue = '//[sep]\\n1|2'\n @errorMessage = \"'sep' expected but '|' found at position 1.\"\n\n # Act.\n @error = assert_raises Exception do\n self.act_Add(@inputValue)\n end\n\n # Assert.\n assert_equal(@errorMessage, @error.message)\n end",
"def error(string); end",
"def rescue_symbol?\n @rescue_symbol\n end",
"def ruby_code?(str)\n checker = FoodCritic::ErrorChecker.new(str)\n checker.parse\n ! checker.error?\n end",
"def assert_matches(expression, string, message='')\n if(expression.is_a?(String))\n expresion = /#{expression}/\n end\n if(!string.match(expression))\n fail \"#{message} - '#{string}' should include '#{expression}'\"\n end\n end",
"def rescue_clause; end",
"def test_Add_Should_ThrowException_When_CalledWithInputContainsUnsupportedSeparatorWithCustomSeparatorDeclaration16\n # Arrange.\n @inputValue = '//[sep1][sep2]\\n1del2'\n @errorMessage = \"'sep1' or 'sep2' expected but 'del' found at position 1.\"\n\n # Act.\n @error = assert_raises Exception do\n self.act_Add(@inputValue)\n end\n\n # Assert.\n assert_equal(@errorMessage, @error.message)\n end",
"def raise_error(*args)\n args.pop if !args.empty? && args.last.sexp_type == :str\n matcher(:raise_error, *args)\n end",
"def ruby_code?(str)\n str = str.to_s\n return false if str.empty?\n checker = FoodCritic::ErrorChecker.new(str)\n checker.parse\n ! checker.error?\n end",
"def test_Add_Should_ThrowException_When_CalledWithInputContainsTwoOrMoreSeparatorsNextWithCustomSeparatorDeclaration108\n # Arrange.\n @inputValue = '//[sep1][sep2][sep3]\\nsep21sep32'\n @errorMessage = \"Number expected but 'sep2' found at position 0.\"\n\n # Act.\n @error = assert_raises Exception do\n self.act_Add(@inputValue)\n end\n\n # Assert.\n assert_equal(@errorMessage, @error.message)\n end",
"def ruby_code?(str)\n str = str.to_s\n return false if str.empty?\n\n checker = FoodCritic::ErrorChecker.new(str)\n checker.parse\n !checker.error?\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Write a statement that allows a member to be updated by their name and age. This should take in the attributes of name, age and id.
|
def update()
sql = "UPDATE members SET (name, age) = ($1, $2) WHERE id = $3"
values = [@name, @age, @id]
SqlRunner.run(sql, values)
end
|
[
"def update()\n sql = \"UPDATE merchants\n SET (name) = ($1)\n WHERE id = $2\"\n values = [@name, @id]\n SqlRunner.run( sql, values )\n end",
"def update\n expose Member.update(@oauth_token, params[:membername], params)\n end",
"def update_member(params)\n connection.call_method('lists.update_member', params.merge(id_params))\n end",
"def update\n sql = \"UPDATE students SET name = ?, grade = ? WHERE id = ?\"\n DB[:conn].execute(sql, self.name, self.grade, self.id)\nend",
"def update_person_field(id:, **args)\n params = parameters(args) do\n required_params :name\n optional_params :name, :options\n end\n request(:put, \"personFields/#{id}\", params)\n end",
"def update(first_name, id)\n @conn.exec(\"UPDATE students SET first_name = '#{first_name}' WHERE id = '#{id}';\")\nend",
"def update\n sql = \"UPDATE students SET name = ?, grade = ? WHERE id = ?\"\n DB[:conn].execute(sql, self.name, self.grade, self.id)\n end",
"def update\n sql = <<-SQL\n UPDATE students SET name = ?, grade = ? WHERE id = ?\n SQL\n\n DB[:conn].execute(sql, self.name, self.grade, self.id)\n end",
"def update_age(new_age)\n DATABASE.execute(\"UPDATE cats SET age = #{new_age} WHERE id = #{@id};\")\n end",
"def update_info(db_connection, full_name, email)\n sql = <<~SQL\n UPDATE users\n SET name = $1,\n email = $2\n WHERE id = $3;\n SQL\n db_connection.exec_params(sql, [ full_name, email, id ])\n @name = full_name\n @email = email\n end",
"def update_member(id, email, merge_vars, email_type='', replace_interests=true)\n _params = {:id => id, :email => email, :merge_vars => merge_vars, :email_type => email_type, :replace_interests => replace_interests}\n return @master.call 'lists/update-member', _params\n end",
"def update(name,id)\n DATABASE.execute(\"UPDATE #{@loc_cat} SET name = '#{name}' WHERE id = #{id}\")\n end",
"def update_member_by_name(name, total)\n @CONNECTION.execute(\"UPDATE 'members' SET total = #{total} WHERE name = '#{name}';\")\n end",
"def edit_staff_member_name(selected)\n\ts = StaffMember.find(selected)\n\tprint \"\\nTo edit the staff member name please enter here: \"\n\tname = gets.chomp\n\ts.update_attributes(name: name)\nend",
"def update\n puts params[:fields]\n expose Participant.update(@oauth_token, params[:membername].strip,\n params[:challenge_id].strip, params[:fields])\n end",
"def update\n attrs = prompt_attrs\n DB.exec(\"UPDATE superheroes\n SET\n superhero_name = '#{attrs[0]}',\n alter_ego = '#{attrs[1]}',\n has_cape = #{attrs[2]},\n power = '#{attrs[3]}',\n arch_nemesis = '#{attrs[4]}'\n WHERE superhero_name = '#{attrs[0].split.map(&:capitalize).join(' ')}';\")\nend",
"def update\n sql = \"UPDATE contacts SET name = ?, phone_number = ?, address = ?, email = ? WHERE id = ?\"\n DB[:conn].execute(sql, name, phone_number, address, email, id)\n end",
"def update(id:, roles:)\n id_check(:id, id)\n non_empty_array_check(:roles, roles)\n\n data = {roles: roles}\n\n cf_patch(path: \"/organizations/#{org_id}/members/#{id}\", data: data)\n end",
"def update!\n @authorize = nil\n update_plan! &&\n resp = put(\"/users/#{username}.xml\", {\n :user_key => apikey,\n \"user[first_name]\" => first_name,\n \"user[last_name]\" => last_name\n })\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /layers POST /layers.json
|
def create
@layer = Layer.new(layer_params)
respond_to do |format|
if @layer.save
format.html { redirect_to @layer, notice: 'Layer was successfully created.' }
format.json { render :show, status: :created, location: @layer }
else
format.html { render :new }
format.json { render json: @layer.errors, status: :unprocessable_entity }
end
end
end
|
[
"def create\n @layer = @map.layers.build(params[:layer])\n\n respond_to do |format|\n if @layer.save\n format.html { redirect_to([@layer.map, @layer], :notice => 'Layer was successfully created.') }\n format.json { render :json => @layer, :status => :created, :location => [@layer.map, @layer] }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @layer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @layer = Layer.new(params[:layer])\n\n respond_to do |format|\n if @layer and @layer.save\n @layers = Layer.all\n format.html { redirect_to layers_path, notice: 'Layer was successfully created.' }\n format.json { render json: {layers: @layers.map {|layer| {id: layer.id, name:layer.name, number_of_polygons: layer.areas.count}}} }\n else\n format.html { render action: \"new\" }\n format.json { render json: @layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def post_layer(index)\n parent = index.positive? ? @layers.fetch(index - 1) : \"\"\n digest = @layers.fetch(index)\n\n uri, req = get_request(\"/v1/layers\", \"post\")\n req.body = layer_body(digest, parent).to_json\n\n begin\n res = get_response_token(uri, req, clair_timeout)\n rescue *::Portus::Errors::NET => e\n Rails.logger.tagged(\"clair.post\") { Rails.logger.debug e.message }\n return\n end\n\n handle_response(res, digest, \"clair.post\")\n end",
"def new\n @layer = @map.layers.build\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @layer }\n end\n end",
"def create\n @geojson_layer = @organization.geojson_layers.build(geojson_layer_params)\n\n respond_to do |format|\n if @geojson_layer.save\n format.html { redirect_to edit_organization_geojson_layer_path(@organization, @geojson_layer), notice: 'Layer was successfully created.' }\n format.json { render action: 'show', status: :created, location: @geojson_layer }\n format.js { render text: \"document.location = '#{edit_organization_geojson_layer_path(@organization, @geojson_layer)}'\"}\n else\n format.html { render action: 'new' }\n format.json { render json: @geojson_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @layer = Layer.find(params[:id])\n\n respond_to do |format|\n if @layer.update_attributes(params[:layer])\n @layers = Layer.all\n format.html { redirect_to @layer, notice: 'Layer was successfully updated.' }\n format.json { render json: {layers: @layers.map {|layer| {id: layer.id, name:layer.name, number_of_polygons: layer.areas.count}}} }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @view_layer = @view.view_layers.build(view_layer_params)\n\n respond_to do |format|\n if @view_layer.save\n ActionCable.server.broadcast \"workspaces:workspace_#{@workspace.id}_#{@view.id}\",\n command: 'ws.layers.add',\n name: @view_layer.layer.name,\n url: workspace_view_view_layer_path(@workspace, @view, @view_layer)\n\n format.js { head :created, location: workspace_view_view_layer_path(@workspace, @view, @view_layer) }\n format.html { redirect_to [@workspace, @view, @view_layer], notice: 'View layer was successfully created.' }\n format.json { render :show, status: :created, location: @view_layer }\n else\n format.html { render :new }\n format.json { render json: @view_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @layer_type = LayerType.new(layer_type_params)\n\n respond_to do |format|\n if @layer_type.save\n format.html { redirect_to @layer_type, notice: 'Layer type was successfully created.' }\n format.json { render :show, status: :created, location: @layer_type }\n else\n format.html { render :new }\n format.json { render json: @layer_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_layer(attributes = {})\n query = {:query => attributes}\n GeoIQ.post(\"#{path}/layers.json\", query)\n # GeoIQ::Layer.new(GeoIQ.post(\"#{path}/layers.json\", query).parsed_response.merge('map_id' => id))\n end",
"def create\n @map_layer = MapLayer.new(params[:map_layer])\n\n respond_to do |format|\n if @map_layer.save\n flash[:notice] = 'Map Layer was successfully created.'\n format.html { redirect_to(@map_layer) }\n format.xml { render :xml => @map_layer, :status => :created, :location => @map_layer }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @map_layer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @attribute_layer = AttributeLayer.new(params[:attribute_layer])\n puts \"---------------------------------------------\"\n respond_to do |format|\n if @attribute_layer.save\n format.html { redirect_to @attribute_layer, notice: 'Attribute layer was successfully created.' }\n format.json { render json: @attribute_layer, status: :created, location: @attribute_layer }\n else\n format.html { render action: \"new\" }\n format.json { render json: @attribute_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def layers=(layers)\n Validator.validate_layers(layers)\n @parameters[:layers] = layers\n end",
"def create\n @attribute_layer = @palette.attribute_layers.new(attribute_layer_params)\n\n respond_to do |format|\n if @attribute_layer.save\n format.html { redirect_to [@palette, @attribute_layer], notice: 'Attribute layer was successfully created.' }\n format.json { render action: 'show', status: :created, location: @attribute_layer }\n else\n format.html { render action: 'new' }\n format.json { render json: @attribute_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @map = Map.find(params[:map_id])\n @layers = @map.layers\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @layers }\n end\n end",
"def create\n @wms_layer = @organization.wms_layers.build(wms_layer_params)\n\n respond_to do |format|\n if @wms_layer.save\n format.html { redirect_to edit_organization_wms_layer_path(@organization, @wms_layer), notice: 'Wms layer was successfully created.' }\n format.json { render action: 'show', status: :created, location: @wms_layer }\n format.js { render text: \"turbolinks.visit('#{edit_wms_layer_path(@wms_layer)}')\"}\n else\n format.html { render action: 'new' }\n format.json { render json: @wms_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @layer = Layer.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @layer }\n end\n end",
"def destroy\n @layer = @map.layers.find(params[:id])\n @layer.destroy\n\n respond_to do |format|\n format.html { redirect_to map_layers_url(@map) }\n format.json { head :ok }\n end\n end",
"def update\n @layer = Layer.find params[:id]\n @layer.update_attributes params[:layer]\n respond_with(@layer) do |format|\n format.json {\n if @layer.valid?\n render json: @layer\n else\n render json: @layer.errors, status: :unprocessable_entity\n end\n }\n end\n\n end",
"def create\n @baselayer = Baselayer.new(baselayer_params)\n\n respond_to do |format|\n if @baselayer.save\n format.html { redirect_to @baselayer, notice: 'Baselayer was successfully created.' }\n format.json { render action: 'show', status: :created, location: @baselayer }\n else\n format.html { render action: 'new' }\n format.json { render json: @baselayer.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PATCH/PUT /layers/1 PATCH/PUT /layers/1.json
|
def update
respond_to do |format|
if @layer.update(layer_params)
format.html { redirect_to @layer, notice: 'Layer was successfully updated.' }
format.json { render :show, status: :ok, location: @layer }
else
format.html { render :edit }
format.json { render json: @layer.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n @layer = @map.layers.find(params[:id])\n\n respond_to do |format|\n if @layer.update_attributes(params[:layer])\n format.html { redirect_to([@layer.map, @layer], :notice => 'Layer was successfully updated.') }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @layer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @layer = Layer.find params[:id]\n @layer.update_attributes params[:layer]\n respond_with(@layer) do |format|\n format.json {\n if @layer.valid?\n render json: @layer\n else\n render json: @layer.errors, status: :unprocessable_entity\n end\n }\n end\n\n end",
"def update\n @layer = Layer.find(params[:id])\n\n respond_to do |format|\n if @layer.update_attributes(params[:layer])\n @layers = Layer.all\n format.html { redirect_to @layer, notice: 'Layer was successfully updated.' }\n format.json { render json: {layers: @layers.map {|layer| {id: layer.id, name:layer.name, number_of_polygons: layer.areas.count}}} }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @layer = Layer.find(params[:id])\n\n respond_to do |format|\n if @layer.update_attributes(params[:layer])\n format.html { redirect_to(@layer, :notice => 'Layer was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @layer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @attribute_layer = AttributeLayer.find(params[:id])\n\n respond_to do |format|\n if @attribute_layer.update_attributes(params[:attribute_layer])\n format.html { redirect_to @attribute_layer, notice: 'Attribute layer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @attribute_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @geojson_layer.update(geojson_layer_params)\n format.html { redirect_to edit_organization_geojson_layer_path(@organization, @geojson_layer), notice: 'Layer was successfully updated.' }\n format.json { head :no_content }\n format.js {\n if @geojson_layer.previous_changes['file_uid']\n render js: \"document.location='#{edit_organization_geojson_layer_path(@organization, @geojson_layer)}';\"\n end\n }\n else\n format.html { render action: 'edit' }\n format.json { render json: @geojson_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @layer = Layer.find(params[:id])\n\n respond_to do |format|\n if @layer.update_attributes(params[:layer])\n flash[:notice] = 'Layer was successfully updated.'\n format.html { redirect_to(@layer) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @layer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @cabinet_map_layer.update(create_params)\n format.html { redirect_to cabinet_map_layers_path, notice: I18n.t('updated') }\n format.json { render :show, status: :ok, location: @cabinet_map_layer }\n else\n format.html { render :edit }\n format.json { render json: @cabinet_map_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n # @attribute_layer = @palette.attribute_layers.find(attribute_layer_params[:id])\n respond_to do |format|\n if @attribute_layer.update(attribute_layer_params)\n format.html { redirect_to [@palette, @attribute_layer], notice: 'Attribute layer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @attribute_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @baselayer.update(baselayer_params)\n format.html { redirect_to @baselayer, notice: 'Baselayer was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @baselayer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end",
"def update\n respond_to do |format|\n if @layer_type.update(layer_type_params)\n format.html { redirect_to @layer_type, notice: 'Layer type was successfully updated.' }\n format.json { render :show, status: :ok, location: @layer_type }\n else\n format.html { render :edit }\n format.json { render json: @layer_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch *args\n make_request :patch, *args\n end",
"def update\n respond_to do |format|\n if @tbl_layer.update(tbl_layer_params)\n format.html { redirect_to @tbl_layer, notice: 'Tbl layer was successfully updated.' }\n format.json { render :show, status: :ok, location: @tbl_layer }\n else\n format.html { render :edit }\n format.json { render json: @tbl_layer.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @overlay = Overlay.find(params[:id])\n\n respond_to do |format|\n if @overlay.update_attributes(params[:overlay])\n format.html { redirect_to @overlay, notice: 'Overlay was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @overlay.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(path, params: {}, headers: {})\n request_json :patch, path, params, headers\n end",
"def update\n respond_to do |format|\n if @ogrgeojson.update(ogrgeojson_params)\n format.html { redirect_to ogrgeojsons_path, notice: 'Ogrgeojson was successfully updated.' }\n format.json { render :show, status: :ok, location: @ogrgeojson }\n else\n format.html { render :edit }\n format.json { render json: @ogrgeojson.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @api_v1_post_flag = PostFlag.find(params[:id])\n\n respond_to do |format|\n if @api_v1_post_flag.update_attributes(params[:api_v1_post_flag])\n format.html { redirect_to @api_v1_post_flag, notice: 'Post flag was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @api_v1_post_flag.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @map_layer = MapLayer.find(params[:id])\n\n respond_to do |format|\n if @map_layer.update_attributes(params[:map_layer])\n flash[:notice] = 'MapLayer was successfully updated.'\n format.html { redirect_to(@map_layer) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @map_layer.errors, :status => :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /itineraries/new GET /itineraries/new.xml
|
def new
@travel = Travel.find(params[:travel_id])
@itinerary = Itinerary.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @itinerary }
end
end
|
[
"def new\n @itinerary = Itinerary.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @itinerary }\n end\n end",
"def new\n @liner = Liner.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @liner }\n end\n end",
"def new\n @rubyist = Rubyist.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @rubyist }\n end\n end",
"def new\n @trail = Trail.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @trail }\n end\n end",
"def new\n @itinerary = Itinerary.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @itinerary }\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @ontology }\n end\n end",
"def new\n @itenerary = Itenerary.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @itenerary }\n end\n end",
"def new\n @county = County.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @county }\n end\n end",
"def new\n @renewal = Renewal.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @renewal }\n end\n end",
"def new\n @interest = Interest.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @interest }\n end\n end",
"def new\n @irtd = Irtd.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @irtd }\n end\n end",
"def new\n @r_i = RI.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @r_i }\n end\n end",
"def new\n \n @request = Request.new\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @request }\n end\n end",
"def new\n @newstuff = Newstuff.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @newstuff }\n end\n end",
"def new\n @index = Indice.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @index }\n end\n end",
"def new_rest\n @item = Item.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @item }\n end\n end",
"def new\n @lookup = Lookup.new\n\n @new_key = \" \"\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @lookup }\n end\n end",
"def new\n @inlist = Inlist.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @inlist }\n end\n end",
"def new\n @it_reservation = ItReservation.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @it_reservation }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /itineraries POST /itineraries.xml
|
def create
@travel = Travel.find(params[:travel_id])
@itinerary = @travel.itineraries.new(itinerary_param)
respond_to do |format|
if @itinerary.save
format.html { redirect_to(admin_travel_itineraries_url(@travel), :notice => 'Itinerary was successfully created.') }
format.xml { render :xml => @itinerary, :status => :created, :location => @itinerary }
else
format.html { render :action => "new" }
format.xml { render :xml => @itinerary.errors, :status => :unprocessable_entity }
end
end
end
|
[
"def create\n itinerary = current_user.itineraries.create!(itinerary_params)\n itinerary_id = current_user.itineraries.last\n \n events = params[:events]\n events.each do |event|\n itinerary_id = current_user.itineraries.last[:id]\n EventsItinerary.create(itinerary_id: itinerary_id, event_id: event[\"id\"])\n end\n render json: itinerary, status: 201 # , location: [:api, itineraries]\n end",
"def create\n @itinerary = Itinerary.new(params[:itinerary])\n\n respond_to do |format|\n if @itinerary.save\n format.html { redirect_to(@itinerary, :notice => 'Itinerary was successfully created.') }\n format.xml { render :xml => @itinerary, :status => :created, :location => @itinerary }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @itinerary.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n\t\t@itinerary = Itinerary.create(itin_params)\n\t\n\t\tredirect_to \"/\"\n\tend",
"def create\n @itinerary = Itinerary.new(itinerary_params)\n\n respond_to do |format|\n if @itinerary.save\n format.html { redirect_to @itinerary, notice: \"Itinerary was successfully created.\" }\n format.json { render :show, status: :created, location: @itinerary }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @itinerary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @itinerary = Itinerary.new(itinerary_params)\n\n respond_to do |format|\n if @itinerary.save\n format.html { redirect_to @itinerary, notice: 'Itinerary was successfully created.' }\n format.json { render :show, status: :created, location: @itinerary }\n else\n format.html { render :new }\n format.json { render json: @itinerary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @itinerary = Itinerary.new(params[:itinerary])\n\n respond_to do |format|\n if @itinerary.save\n format.html { redirect_to @itinerary, notice: 'Itinerary was successfully created.' }\n format.json { render json: @itinerary, status: :created, location: @itinerary }\n else\n format.html { render action: \"new\" }\n format.json { render json: @itinerary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @admin_itinerary = Itinerary.new(admin_itinerary_params)\n\n respond_to do |format|\n if @admin_itinerary.save\n format.html { redirect_to session['previous_url'] || admin_itineraries_url, notice: 'Itinerari è stato creato con successo.' }\n format.json { render :show, status: :created, location: @admin_itinerary }\n else\n format.html { render :new }\n format.json { render json: @admin_itinerary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user_itinerary = UserItinerary.new(user_itinerary_params)\n\n respond_to do |format|\n if @user_itinerary.save\n format.html { redirect_to @user_itinerary, notice: 'User itinerary was successfully created.' }\n format.json { render :show, status: :created, location: @user_itinerary }\n else\n format.html { render :new }\n format.json { render json: @user_itinerary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @itinerary_attraction = ItineraryAttraction.new(itinerary_attraction_params)\n\n respond_to do |format|\n if @itinerary_attraction.save\n format.html { redirect_to @itinerary_attraction, notice: 'Itinerário de atracção criado com sucesso.' }\n format.json { render action: 'show', status: :created, location: @itinerary_attraction }\n else\n format.html { render action: 'new' }\n format.json { render json: @itinerary_attraction.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @itineraries = Itinerary.all\n end",
"def scrape_itineraries\n @doc = Nokogiri::HTML(open(URL))\n #@doc = Nokogiri::HTML(open(URL, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE)) # use if security certificate is expired\n @doc.css('div.view-itineraries span.field-content').each do |it|\n itinerary = BalboaParkItineraryIdeas::Itinerary.new\n\n itinerary.title = it.css('a').text\n itinerary.url = URL + it.css('a').attribute(\"href\").value\n itinerary.attractions = []\n\n itinerary.save\n end\n end",
"def create\n @trip = Trip.find_by_id(params[:trip_id])\n @folder = @trip.folders.find_by_id(params[:folder_id])\n @itenary = @folder.itenaries.create(itenary_params)\n\n respond_to do |format|\n if @itenary.save\n format.html { redirect_to trip_folder_itenaries_path(:trip_id => @trip.name, :folder_id => @folder.name), notice: 'Itenary was successfully created.' }\n format.json { render :show, status: :created, location: trip_folder_itenaries_path(:trip_id => @trip.name, :folder_id => @folder.name) }\n else\n format.html { render :new }\n format.json { render json: @itenary.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @itinerary_type = ItineraryType.new(itinerary_type_params)\n respond_to do |format|\n if @itinerary_type.save\n format.html { redirect_to @itinerary_type, notice: 'Tipo de itinerário criado com sucesso.' }\n format.json { render action: 'show', status: :created, location: @itinerary_type }\n else\n format.html { render action: 'new' }\n format.json { render json: @itinerary_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_itineraries_st\n Rails.logger.info \"Creating itineraries single-threaded\"\n trip_parts.each do |trip_part|\n trip_part.create_itineraries\n end\n\n\n\n end",
"def create\n @committee = Committee.find(params[:committee_id])\n @instalment = @committee.instalments.create(instalment_params)\n\n respond_to do |format|\n if @instalment\n format.json { render json: @instalment.to_json, status: :created}\n else\n format.json { render json: @instalment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @itineraries = current_user.itineraries\n render json: @itineraries\n end",
"def create_itineraries(params)\n\n transit_response = nil\n Rails.logger.info \"CREATE: \" + params[:modes].collect {|m| m.code}.join(\",\")\n # remove_existing_itineraries\n itins = []\n \n params[:modes].each do |mode|\n\n Rails.logger.info('CREATING ITINERARIES FOR TRIP PART ' + self.id.to_s)\n Rails.logger.info(mode)\n case mode\n # start with the non-OTP modes\n when Mode.taxi\n timed \"taxi\" do\n taxi_itineraries = TaxiItinerary.get_taxi_itineraries(self, [from_trip_place.location.first, from_trip_place.location.last],[to_trip_place.location.first, to_trip_place.location.last], trip_time, trip.user)\n itins << taxi_itineraries if taxi_itineraries.length > 0\n itins.flatten!\n end\n when Mode.paratransit\n timed \"paratransit\" do\n itins += ParatransitItinerary.get_itineraries(self)\n end\n when Mode.rideshare\n timed \"rideshare\" do\n itins += create_rideshare_itineraries\n end\n when Mode.ride_hailing \n timed \"ride_hailing\" do\n itins += RideHailingItinerary.get_itineraries(self)\n end\n else\n # OTP modes\n if (!mode.otp_mode.blank?)\n # Transit modes + Bike, Drive,\n timed \"fixed\" do\n start = Time.now\n new_itins, response = create_fixed_route_itineraries({otp_mode: mode.otp_mode, mode: mode.code, walk_mph: params[:walk_speed], max_walk_miles: params[:max_walk_miles], max_walk_seconds: params[:max_walk_seconds], optimize: params[:optimize], num_itineraries: params[:num_itineraries], min_transfer_time: params[:min_transfer_time], max_transfer_time: params[:max_transfer_time], banned_routes: params[:banned_routes], preferred_routes: params[:preferred_routes]})\n\n if mode.code == \"mode_transit\"\n transit_response = response\n end\n\n puts 'CREATE FIXED_ ROUTE ITINERARIES ###'\n puts Time.now - start\n non_duplicate_itins = []\n start = Time.now\n new_itins.each do |itin|\n unless self.check_for_duplicates(itin, self.itineraries + itins)\n non_duplicate_itins << itin\n end\n end\n puts 'Check for Duplicates ###'\n puts Time.now - start\n\n itins += non_duplicate_itins\n end\n end\n end\n end\n #self.itineraries << itins\n return itins, transit_response\n end",
"def new\n @itinerary = Itinerary.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @itinerary }\n end\n end",
"def create\n unless params[:cust_iti_request][:destinations].nil?\n params[:cust_iti_request][:destinations].reject! { |c| c.empty? }\n end\n params[:cust_iti_request][:no_of_children] = 0 unless params[:cust_iti_request][:no_of_children].present?\n @cust_iti_request = CustItiRequest.new(cust_iti_request_params)\n respond_to do |format|\n if @cust_iti_request.save\n format.html { redirect_to @cust_iti_request, notice: 'Cust iti request was successfully created.' }\n format.json { render action: 'show', status: :created, location: @cust_iti_request }\n else\n format.html { render action: 'new' }\n # format.html { redirect_to user_unwinders_path(:cust_iti_request => @cust_iti_request.attributes), notice: 'Cust iti request was successfully created.' }\n format.json { render json: @cust_iti_request.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
This is where we pull the route out of the submitted slack command eg /tram 96 or tram route 96 will pull out '96' defaults to Route 109 (Montague St)
|
def determine_requested_route(slack_query)
submitted_text = slack_query.to_s
return STOP_INFO[:'96'] if submitted_text.include? '96'
STOP_INFO[:'109']
rescue NoMethodError
STOP_INFO[:'109']
end
|
[
"def get_route\n self.route\n end",
"def format_route route\n route.first.split('')\n end",
"def route\n @route\n end",
"def get_route\n data = {\n visits: visits,\n fleet: fleet\n }\n\n data[:options] = options if options\n result = Util.send_request(\"POST\", \"vrp\", Routific.token, data)\n RoutificApi::Route.parse(result)\n end",
"def route_for(**url_details)\n @routes.select { |rt| url_details <= rt.url_details }.first\n end",
"def route\n blank, *route = request.path_info.split(\"/\").collect {|arg| unescape(arg) }\n route\n end",
"def bus_api_getdirections(route)\n url_safe_route = URI.encode(route)\n apiKey = \"UPGw2J5PBxNnF967CAMyHygeB\"\n apiLink = \"http://www.ctabustracker.com/bustime/api/v1/getdirections?key=#{apiKey}&rt=#{url_safe_route}\"\n apiResults = open(apiLink).read\n return Hash.from_xml(apiResults)\n end",
"def getRoute(route_type: \"vrp\")\n data = {\n visits: visits,\n fleet: fleet\n }\n\n data[:options] = options if options\n Routific.getRoute(data, token, route_type)\n end",
"def route\n puts current_message.inspect\n bot_type = get_bot_type(current_message)\n get_current_bot(bot_type, current_message)\n end",
"def route_by_long_name(route_long_name)\n get \"/gtfs/routes/routeLongName/#{route_long_name}\"\n end",
"def match_route(type, channel, command)\n # go through the list of channel mappings to find a matching route\n @routing_map.mappings.each do |route|\n return route if route.match(type, channel, command)\n end\n\n nil\n end",
"def build_route\n start_point = address\n end_point = address\n waypoints = []\n orders.each do |order|\n # Go to the company first.\n waypoints << order.company.address\n # Go to the client after\n waypoints << order.address\n end\n direction_hash = {\n \"direction\" => {\n \"data\" => { \"from\" => start_point, \"to\" => end_point}\n }\n }\n if waypoints.length > 0\n direction_hash[\"direction\"][\"options\"] = {\"waypoints\" => waypoints, \"display_panel\" => true, \"panel_id\" => \"instructions\"}\n end\n direction_hash\n end",
"def route\n return @route if @route\n routes.router.recognize(request) do |r, params|\n @route = r\n end\n @route\n end",
"def route(route_id)\n data = request(\"routes/#{route_id}\")\n data[\"route\"]\n end",
"def find_nearest_route(path_parts)\n\t\t\twhile path_parts.size >= 0\n\t\t\t\troute = find_route(path_parts: path_parts)\n\t\t\t\tbreak if route || path_parts.empty?\n\t\t\t\tpath_parts.pop\n\t\t\tend\n\t\t\troute\n\t\tend",
"def get_optimal_route\n # prepare starting [x,y] for API request\n prep_start_point\n # prepare destinations for API request\n prep_destinations\n # combines start_point and destinations into a query string\n build_query_string\n # sends formatted GET Request to Traveling Salesman Endpoint of HERE API\n @res = HTTParty.get(@query_string, format: :plain)\n\n return @res\n end",
"def get_route()\n Route.find(@route_id)\n end",
"def route(context, entry)\n command_name, *arguments = entry.split\n command = @commands[command_name]\n if command == nil\n return :not_found, nil\n end\n\n parameters = command.extract arguments.join(' ')\n\n if parameters == :no_match\n return :wrong_arguments, command.full_command\n end\n\n command.action(context, *parameters)\n end",
"def route_by_short_name(route_short_name)\n get \"/gtfs/routes/routeShortName/#{route_short_name}\"\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
calls 'choose_hero' to display all the cards to the user, and assigns their choice to 'card' TTY prompt for the yes/no menu if 'yes', creates a new row in the card table for that specific user_id, assigning them that card_id asks if user wants to select another card, if they do it calls on itself to offer the choices again (and so on)
|
def choose_and_add_card_to_user_deck
prompt = TTY::Prompt.new
card = choose_hero
response = prompt.select('Do you want to add this card to your collection?', %w(Yes No))
if response == "Yes"
added_card = UserCard.create(user_id: self.id, card_id: card.id)
puts "#{added_card.card.name.upcase} was added to your collection."
sleep(1)
end
system('clear')
title
response = prompt.select('Do you want to look for another card?', %w(Yes No))
if response == "Yes"
self.choose_and_add_card_to_user_deck
end
end
|
[
"def choose_hero\n prompt = TTY::Prompt.new\n names = Card.all.map {|cards| cards[\"name\"]}\n selected_name = prompt.select('Choose a character', names, filter: true, cycle: true, help: \"(Start typing to filter results)\",help_color: :green, active_color: :yellow, per_page: 20)\n hero = Card.find_by(name: selected_name)\n display_card_details(hero)\n hero\nend",
"def choose_hero\n prompt = TTY::Prompt.new\n names = Cards.all.map {|cards| cards[\"name\"]}\n selected_name = prompt.select('Choose a character', names, filter: true, cycle: true, help: \"(Start typing to filter results)\",help_color: :green, active_color: :yellow)\n hero = Cards.find_by(name: selected_name)\n display_card_details(hero)\n hero\nend",
"def choose_hero\n buffer\n display_heros\n buffer\n line\n puts \"Choose a Hero by typing the number they are labeled with into your console.\"\n line\n choice = gi_integer - 1\n if choice <= Hero.all.length\n buffer\n line\n puts \"You chose: #{Hero.all[choice].alter_ego}\"\n line\n hero = Hero.all[choice]\n generate_hero_nemesis(hero)\n else line\n puts \"Your choice does not exist. Press 1 to rechoose, Press 2 to generate a Hero, Press 3 to go back.\"\n line\n choice = gi_integer\n if choice == 1\n choose_hero\n elsif choice == 2\n generate_hero_name\n elsif choice == 3\n hero_setup\n end\n end\n end",
"def hero_setup\n line\n puts \"Press 1 to choose a Hero. Press 2 to generate your own Hero. Press 3 to go back.\"\n line\n choice = gi_integer\n if choice == 1\n choose_hero\n elsif choice == 2\n generate_hero_name\n elsif choice == 3\n greeting\n else line\n puts \"Sorry, please enter either 1, 2, or 3.\"\n hero_setup\n line\n end\n \n end",
"def purchase_card(turn)\n own_money = turn.player.money\n keep_repeating = true\n while keep_repeating == true do\n keep_repeating = false \n @@cli.say \"Now it is time to purchase a card; you have <%= color('#{own_money}', BOLD) %> money.\"\n # Create a hash for the cards in the town\n town_cards = Hash[ @mk.town.deck.map {|e| [\"#{e[1]} x #{e[0].attribute[:name]} (#{e[0].attribute[:cost]})\", [:establishment, e[0], e[0].attribute[:cost]]]} ]\n card_name_list = town_cards.sort_by { |key, val| val[1].attribute[:from_roll] }.to_h\n # add the landmarks\n card_name_list.merge!(Hash[ turn.player.unbuilt_landmarks.map {|l| [\"#{l.name} (#{l.cost})\", [:landmark, l, l.cost]]} ])\n @@cli.choose do |menu|\n menu.prompt = \"Which card to do you want to buy? \"\n menu.choices(*card_name_list.keys) do |chosen|\n @@cli.say \"You have chosen <%= color('#{chosen}', BOLD) %>. \"\n if own_money < card_name_list[chosen][2]\n @@cli.say \"You can't afford that! It costs #{card_name_list[chosen][2]} but you only have #{own_money}\"\n keep_repeating = true\n else\n process_purchase_of_card(turn, card_name_list[chosen])\n end\n end\n menu.choice(:none, {:text => \"NOTHING TO ME, AH VIENNA\"}) { @@cli.say \"OK, you have chosen to not purchase any card.\"}\n menu.choice(:databank) { databank_menu; keep_repeating = true}\n end\n end\n end",
"def create_card\n # If there are no lists then warn the user\n if $state[\"current board\"].lists.empty?\n puts \"You must create a list before you can add cards\".colorize(:red)\n return\n end\n\n # Prompt the user to create cards and add them to lists\n add_card = $prompt.select(\n \"Would you like to add some cards to your lists?\", \n {\"Yes\" => true, \"No\" => false})\n\n while add_card\n # Check which list to add the card to\n lists = $state[\"current board\"].lists.keys\n add_to_list = $prompt.select(\"Which list would you like to add the card to?\", lists)\n \n # Prompt the user for a description of their card\n card_desc = $prompt.ask(\"Enter a description for your card: \")\n \n # Create the card and add it to the given list\n card = Card.new(card_desc)\n $state[\"current board\"].lists[add_to_list].add_card(card)\n add_card = $prompt.select(\"Would you like to add some cards to your lists?\", {\"Yes\" => true, \"No\" => false})\n end\n\nend",
"def display_and_add_a_superhero\n #binding.pry\n user.reload\n system 'clear'\n choices=iterator_heros\n puts \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n puts \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n puts \"\n \n ████████╗██╗ ██╗███████╗ ██╗ ██╗███████╗██████╗ ██████╗ ███████╗\n ╚══██╔══╝██║ ██║██╔════╝ ██║ ██║██╔════╝██╔══██╗██╔═══██╗██╔════╝\n ██║ ███████║█████╗ ███████║█████╗ ██████╔╝██║ ██║███████╗\n ██║ ██╔══██║██╔══╝ ██╔══██║██╔══╝ ██╔══██╗██║ ██║╚════██║\n ██║ ██║ ██║███████╗ ██║ ██║███████╗██║ ██║╚██████╔╝███████║\n ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝\n \n \".colorize(:yellow)\n choosen_superhero=prompt.select(\"Choose A Superhero Please\", choices )\n userSup= UserSuperhero.create(user_id: self.user.id, superhero_id: choosen_superhero)\n # binding.pry\n system 'clear'\n self.main_menu()\n \n end",
"def delete_card\n prompt = TTY::Prompt.new\n your_cards = self.cards\n card_names = your_cards.map { |card| card[\"name\"] }\n selected_card_name = prompt.select('Choose a character to delete', card_names, filter: true, cycle: true, help: \"(Start typing to filter results)\", help_color: :green, active_color: :yellow)\n selected_card = Card.find_by(name: selected_card_name)\n choice = UserCard.find_by user_id: self.id, card_id: selected_card.id\n response = prompt.select(\"Are you sure you want to delete #{selected_card_name.upcase}?\", %w(Yes No))\n if response == \"Yes\"\n choice.destroy\n bar = TTY::ProgressBar.new(\"Deleting #{selected_card_name.upcase} [:bar]\", total: 30)\n 30.times do\n sleep(0.05)\n bar.advance(1)\n end\n puts \"#{choice.card.name.upcase} was deleted from your collection!\"\n sleep(1)\n system('clear')\n title\n else\n check_collection\n end\n end",
"def draw_card\n waiting_to_pick_pile = true\n\n invalid_pile = nil\n while waiting_to_pick_pile\n DisplayManager.prepare_ingame_display\n show_state\n\n puts \"Do you want to draw a new card, or use the top discarded card?\"\n puts InputManager.input_options({ affirmative: 'Draw New Card', negative: 'Take Last Discarded Card' }, invalid_pile)\n invalid_pile = nil\n \n response = InputManager.get\n\n # If player picks the draw pile\n # draw the top card from that pile\n if InputManager.affirmative?(response)\n choose_new_card\n waiting_to_pick_pile = false\n\n # If player picks from discard pile\n # draw top card from that pile\n # player cannot discard this card\n elsif InputManager.negative?(response)\n choose_discard\n waiting_to_pick_pile = false\n else\n invalid_pile = response\n end\n end\n end",
"def list_hand_cards(card_array) \n user_choice = \"\"\n while user_choice != \"⬅️ BACK ⬅️\" && user_choice != \"🗑 DELETE READING 🗑\" do\n user_choice = prompt.select(\"🔮 #{self.user.name}, Select a card to see more details.\") do |menu|\n card_emoji_string = \"🂠\"\n crystal_ball_emoji_string = \"🔮\"\n card_array.map do |handCard|\n string=\" 🂠 TAROT #{crystal_ball_emoji_string} 🂠 \"\n menu.choice \" 🂠 TAROT #{crystal_ball_emoji_string} 🂠 \", -> {reading_card(handCard.card, card_array,string); \" 🂠 TAROT #{crystal_ball_emoji_string} 🂠 \"}\n card_emoji_string += \"🂠\"\n crystal_ball_emoji_string += \" 🔮\"\n end\n menu.choice \"🗑 DELETE READING 🗑\", -> {self.delete_reading(card_array); \"🗑 DELETE READING 🗑\"}\n menu.choice \"⬅️ BACK ⬅️\", -> {self.main_menu;\"⬅️ BACK ⬅️\"}\n end \n end \n end",
"def generate_hero_hp(hero)\n buffer\n line\n puts \"Your hero's hp is being calculated...\"\n buffer\n hp = rand(500..1000)\n hero.hp = hp\n puts \"Your hero's health point are #{hero.hp}\"\n puts \"Is this enough health? Press 1 if it is enough, press 2 to re-roll power level.\"\n line\n choice = gi_integer\n if choice == 1\n generate_hero_gender(hero)\n elsif choice == 2\n generate_hero_hp(hero)\n else line\n puts \"Your input was not recognized. Please begin this step again.\"\n line\n generate_hero_hp(hero)\n end\n end",
"def superhero_choosen?\n\n if self.user.superheros.empty?\n puts \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n puts \"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\"\n puts\"\n \n ██████╗ ██████╗ ██████╗ ██████╗ ██████╗ ██████╗ ███████╗██╗\n ██╔═══██╗██╔═══██╗██╔═══██╗██╔═══██╗██╔═══██╗██╔══██╗██╔════╝██║\n ██║ ██║██║ ██║██║ ██║██║ ██║██║ ██║██████╔╝███████╗██║\n ██║ ██║██║ ██║██║ ██║██║ ██║██║ ██║██╔═══╝ ╚════██║╚═╝\n ╚██████╔╝╚██████╔╝╚██████╔╝╚██████╔╝╚██████╔╝██║ ███████║██╗\n ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝\n \n \n \".colorize(:red)\n \n puts \"\\n\\nYou have no Superheros yet! Select option 2 in main menu!\"\n \n \n sleep 3\n self.main_menu()\n end\n end",
"def create_new_hero\n puts \"Are you sure you want to change your class?\\n\"\n puts \"Your stats will reset and you will lose all of your current weapons, armor and dungeon accomplishments!\\n\"\n case choose_array_option %w(yes no), true\n when 1\n new_hero = create\n puts \"Congratulations! You're class has changed to #{new_hero.main_class}!\"\n new_hero\n else\n puts \"Good! I thought the #{@main_class} was better anyway.\"\n end\n end",
"def choose_cards(turn, player)\n if turn.turn_card_on_deck?\n rand_num = rand(2)\n list_of_cards = case\n when rand_num == 0: Array.new.push(turn.turn_get_a_card_from_deck)\n when rand_num == 1: turn.turn_get_cards_from_stack(1)\n end\n else\n list_of_cards = turn.turn_get_cards_from_stack(1)\n end\n list_of_cards.concat(turn.turn_get_cards_from_stack(1))\n end",
"def pick_player_card\n # TODO: Use Random to get a new random card\n rand(1..11)\nend",
"def deal_card(gd, which_player, is_face_up = true, face = nil, suit = nil)\n # for test cards only\n if (face) \n cards = gd[:deck].select { |card| card[:face] == face}\n # if no suit is specified, pick a random card with the specified face value\n if suit\n card = cards.select { |card| card[:suit] == suit}.sample\n else\n card = cards.sample\n end\n else # normal random card selection\n card = get_card(gd)\n end \n\n card[:is_face_up] = is_face_up\n which_player[:hand][:cards].push(card)\n update_hand_value(gd, which_player)\n draw(gd)\nend",
"def setupCards\n\t\t#shuffle all of the individual decks of cards\n\t\t@suspects = @suspects.shuffle\n\t\t@locations = @locations.shuffle\n\t\t@weapons = @weapons.shuffle\n\n\t\t#choose the winning guess\n\t\t@suspectAnswer = @suspects.delete_at(0)\n\t\t@locationAnswer = @locations.delete_at(0)\n\t\t@weaponAnswer = @weapons.delete_at(0)\n\n\t\t#move all of the remaining cards together and shuffle them\n\t\t@suspects.concat(@locations.concat(@weapons))\n\t\t@suspects = @suspects.shuffle\n\n\t\t#distribute all of the remaining cards evenly between all of the players\n\t\t(@suspects.length).times{ |i| @players[i % @numPlayers].setCard(@suspects[i]) }\n\tend",
"def canAnswer( playerIndex, guess )\n \n cardsFound = Array.new(0) # to store the cards that are in the guess and are reveived by the this player.\n indexOfCardToShow = -1 # index of the card that to be shown to the player who made a guess in the array above.\n cardToShow = nil # the paticular card that is about to be shown.\n \n puts \"Asking player #{@indexOfCurrentPlayer}. \"\n \n # iterate all cards this player owns to find those in the guess.\n for i in 0...@cardsInHand.length\n if( @cardsInHand[i].type() == :person )\n if(guess.person().value() == @cardsInHand[i].value())\n cardsFound.push(@cardsInHand[i])\n end\n elsif( @cardsInHand[i].type() == :place )\n if(guess.place().value() == @cardsInHand[i].value())\n cardsFound.push(@cardsInHand[i])\n end\n elsif( @cardsInHand[i].type() == :weapon )\n if(guess.weapon().value() == @cardsInHand[i].value())\n cardsFound.push(@cardsInHand[i])\n end\n end #if\n end #for\n \n # if there IS any cards found, which means that the player can answer the guess.\n if(cardsFound.length != 0 ) \n # if there is only one card, just show it.\n if(cardsFound.length == 1)\n puts \"Player #{playerIndex} asked you about guess: #{guess.person.value} in #{guess.place.value} with the #{guess.weapon.value}, you only have one card, #{cardsFound[0].value}, showed it to them.\"\n cardToShow = cardsFound[0]\n # otherwise, ask the human player to choose a card to show.\n else \n puts \"Player #{playerIndex} asked you about guess: #{guess.person.value} in #{guess.place.value} with the #{guess.weapon.value}, Which do you show? \"\n \n for i in 0... cardsFound.length\n puts \"#{i}: #{cardsFound[i].value}\" \n end\n \n indexOfCardToShow = gets.chomp.to_i\n \n while( indexOfCardToShow < 0 || indexOfCardToShow > cardsFound.length - 1 )\n puts \"Invalid number. Please enter again. \"\n indexOfCardToShow = gets.chomp.to_i\n end\n \n cardToShow = cardsFound[indexOfCardToShow]\n end\n # if there is no card found, then this player can not answer this guess.\n else\n puts \"Player #{playerIndex} asked you about guess: #{guess.person.value} in #{guess.place.value} with the #{guess.weapon.value}, but you couldn't answer. \"\n end\n \n return cardToShow \n end",
"def process_card(index, players)\n view.render_track(game.racer.board)\n\n view.display_player(players[index].player_name)\n card = game.get_current_card\n view.render_question(card.question)\n input = view.get_answer\n if card.compare(input)\n view.render_correct_answer\n game.update_score(index)\n game.racer.advance_player(index)\n else\n view.render_wrong_answer(card.answer)\n end\n view.render_score(players[index].player_score)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
get 5 random cards from the cards table, add them to the user's collection
|
def open_pack
cards = Card.all.sample(5)
cards.each { |card| UserCard.create(user_id: self.id, card_id: card.id)}
names = cards.map { |card| card.name }
puts "#{names.join(", ").upcase} ...were added to your collection!"
sleep(3)
end
|
[
"def generate_cards(user)\n rand(1..3).times do\n c = CreditCard.new\n c.number = Faker::Business.credit_card_number\n c.expiration_month = rand(1..12)\n c.expiration_year = rand(2016..2020)\n c.csv_code = rand(100..999)\n c.default_billing = true\n c.user_id = user.id\n\n c.save!\n end\n end",
"def generate_cards(user)\n rand(1..3).times do\n c = CreditCard.new\n c.number = Faker::Business.credit_card_number\n c.expiration_month = rand(1..12)\n c.expiration_year = rand(2016..2018)\n c.security_code = rand(100..9999)\n c.default_billing = true\n c.user_id = user.id\n\n c.save!\n end\n end",
"def collect_five\n @thefive = @hand.cards.dup\n @thefive << @turncard\n @thefive.sort_by!( &:rank )\n end",
"def get_random_user_list \n @users = user_list.sample(5).insert(rand(5), {name: \"ME\", bot: false})\n end",
"def pick_player_card\n # TODO: Use Random to get a new random card\n rand(1..11)\nend",
"def random\n card_dealt = @possible_cards.sample\n end",
"def random_card\n @cards[(@random.rand * @cards.length).floor]\n end",
"def deal_random_card\r\n return @cards.sample\r\n end",
"def flush\n suit = [\"clubs\", \"spades\", \"diamonds\", \"hearts\"].sample\n Card.where(suit: suit).sample(5)\nend",
"def deal_five()\n cards = DECKS.deck.shift(5)\n cards.sort_by! { |card| card.rank[0] }.reverse!\n\n return cards\n end",
"def populate\n ((1..8).to_a * 2).shuffle\n .map {|num| Card.new(num)}\n end",
"def initialize_cards\n cards = []\n 4.times { cards += (2..14).to_a }\n cards.sample(52)\n end",
"def random_flush\n suit = [\"♠\", \"♣\", \"♡\", \"♢\"].sample\n Card.where(suit: suit).sample(5)\nend",
"def insert_random(card)\n @cards.insert(Random.new().rand(0...@cards.count), card)\n end",
"def random_user\n\t\tUser.find([*1..40].sample)\n\tend",
"def deal5cards (n)",
"def cards_for_player player, deck\n\t1.upto(7){ |i| \n\t random_card = deck.sample\n\t player.push_card_to_hand(random_card)\n\t deck.delete_if{ |card| card.rank == random_card.rank and card.color == random_card.color }\n\t }\n end",
"def add_random_available_cards_to_displayed(cards_available, cards_displayed, numCards)\r\n\tfor i in 0...numCards\r\n\t\tadd_random_card_available_displayed(cards_available, cards_displayed)\r\n\tend\r\nend",
"def pick_random_card\n random_card = @all_cards.sample\n remove_card(random_card)\n return random_card\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
iterates over all the cards for that user, passes resulting array of names to TTY prompt to display choices. choice from the list of names is stored in selected_card_name the card object for that choice is stored in selected_card the UserCard object from that specific user's collection is stored in choice choice is destroyed if the user chooses yes, confirmation message displayed. if user decides not to delete, check_collection is called to return to users card list
|
def delete_card
prompt = TTY::Prompt.new
your_cards = self.cards
card_names = your_cards.map { |card| card["name"] }
selected_card_name = prompt.select('Choose a character to delete', card_names, filter: true, cycle: true, help: "(Start typing to filter results)", help_color: :green, active_color: :yellow)
selected_card = Card.find_by(name: selected_card_name)
choice = UserCard.find_by user_id: self.id, card_id: selected_card.id
response = prompt.select("Are you sure you want to delete #{selected_card_name.upcase}?", %w(Yes No))
if response == "Yes"
choice.destroy
bar = TTY::ProgressBar.new("Deleting #{selected_card_name.upcase} [:bar]", total: 30)
30.times do
sleep(0.05)
bar.advance(1)
end
puts "#{choice.card.name.upcase} was deleted from your collection!"
sleep(1)
system('clear')
title
else
check_collection
end
end
|
[
"def list_hand_cards(card_array) \n user_choice = \"\"\n while user_choice != \"⬅️ BACK ⬅️\" && user_choice != \"🗑 DELETE READING 🗑\" do\n user_choice = prompt.select(\"🔮 #{self.user.name}, Select a card to see more details.\") do |menu|\n card_emoji_string = \"🂠\"\n crystal_ball_emoji_string = \"🔮\"\n card_array.map do |handCard|\n string=\" 🂠 TAROT #{crystal_ball_emoji_string} 🂠 \"\n menu.choice \" 🂠 TAROT #{crystal_ball_emoji_string} 🂠 \", -> {reading_card(handCard.card, card_array,string); \" 🂠 TAROT #{crystal_ball_emoji_string} 🂠 \"}\n card_emoji_string += \"🂠\"\n crystal_ball_emoji_string += \" 🔮\"\n end\n menu.choice \"🗑 DELETE READING 🗑\", -> {self.delete_reading(card_array); \"🗑 DELETE READING 🗑\"}\n menu.choice \"⬅️ BACK ⬅️\", -> {self.main_menu;\"⬅️ BACK ⬅️\"}\n end \n end \n end",
"def choose_and_add_card_to_user_deck\n prompt = TTY::Prompt.new\n card = choose_hero\n response = prompt.select('Do you want to add this card to your collection?', %w(Yes No))\n if response == \"Yes\"\n added_card = UserCard.create(user_id: self.id, card_id: card.id)\n puts \"#{added_card.card.name.upcase} was added to your collection.\"\n sleep(1)\n end\n system('clear')\n title\n response = prompt.select('Do you want to look for another card?', %w(Yes No))\n if response == \"Yes\"\n self.choose_and_add_card_to_user_deck\n end\n end",
"def reading_card(card_obj, card_array, card_string)\n system \"clear\"\n puts card_string\n user_choice = \"\"\n while user_choice != \"⬅️ BACK ⬅️\" do\n user_choice = prompt.select(\"🔮 #{self.user.name}, please choose from the list below.\") do |menu|\n menu.choice \"🔮 READ TYPE 🔮\", -> {card_obj.display_type}\n menu.choice \"🔮 READ NAME 🔮\", -> {card_obj.display_name}\n menu.choice \"🔮 READ VALUE 🔮\", -> {card_obj.display_value}\n menu.choice \"🔮 READ DESCRIPTION 🔮\", -> {card_obj.display_description}\n menu.choice \"⬅️ BACK ⬅️\", -> {self.list_hand_cards(card_array); \"⬅️ BACK ⬅️\"}\n end\n end\n end",
"def choose_hero\n prompt = TTY::Prompt.new\n names = Card.all.map {|cards| cards[\"name\"]}\n selected_name = prompt.select('Choose a character', names, filter: true, cycle: true, help: \"(Start typing to filter results)\",help_color: :green, active_color: :yellow, per_page: 20)\n hero = Card.find_by(name: selected_name)\n display_card_details(hero)\n hero\nend",
"def choose_hero\n prompt = TTY::Prompt.new\n names = Cards.all.map {|cards| cards[\"name\"]}\n selected_name = prompt.select('Choose a character', names, filter: true, cycle: true, help: \"(Start typing to filter results)\",help_color: :green, active_color: :yellow)\n hero = Cards.find_by(name: selected_name)\n display_card_details(hero)\n hero\nend",
"def get_user_cards\n\tloop do\n\t\tprint \"\\nEnter your set or type 'help': \"\n\t\tcase user_array = gets.chomp.downcase.split(\",\")\n\t\twhen [\"help\"]\n\t\t\tsystem('clear'); system('cls')\n\t\t\tputs \"Command list:\" +\n\t\t\t\"\\n\\thelp\\tRedisplay this help menu.\" +\n\t\t\t\"\\n\\thint\\tDisplay a correct set. Removes one hint from the hint counter.\" +\n\t\t\t\"\\n\\tquit\\tQuit to main menu without saving.\" +\n\t\t\t\"\\n\\tsave\\tSave the game. Game continues.\" +\n\t\t\t\"\\n\\tshow\\tRedisplay the current hand. Useful if screen is full.\"\n\t\t\tputs \"Valid set:\" +\n\t\t\t\"\\n\\tInteger,Integer,Integer\" +\n\t\t\t\"\\n\\tInteger must be between min and max card number in hand to be valid.\"\n\t\t\tputs \"\\nHit enter to continue.\"\n\t\t\tgets\n\t\t\tshow_hand\n\t\twhen [\"hint\"]\n\t\t\tputs get_hint # returns hint (+ number left) or \"No more hints available.\"\n\t\twhen [\"quit\"]\n\t\t\t# setting up conditions to allow for quiting\n\t\t\t@top_card = 81\n\t\t\t@hand = []\n\t\t\treturn [\"quit\"]\n\t\twhen [\"save\"]\n\t\t\tsave_game\n\t\twhen [\"show\"]\n\t\t\tshow_hand\n\t\telse\n\t\t\tif good_set_syntax? user_array\n\t\t\t\t# return user defined set in ascending card order\n\t\t\t\treturn user_array.map {|card_num| card_num.to_i}.sort\n\t\t\tend\n\t\t\tputs \"Invalid command or set syntax.\"\n\t\tend\n\tend\nend",
"def getUsersCardInput\n\t\t@userChoice.clear\n\t\twhile @userChoice.length < 3 do\n\t\t\tputs \"Enter a card number between 1 and \" + @table.length.to_s + \" or enter 0 for a hint (0 will also clear your prior choices) :\"\n\t\t\tchoice = gets.chomp!\n\t\t\tif (1..@table.length) === choice.to_i and !@userChoice.include?(choice.to_i)\n\t\t\t\t@userChoice.push(choice.to_i)\n\t\t\telse\n\t\t\t\tif choice == \"0\"\n\t\t\t\t\tfindSet.printCard\n\t\t\t\telse\n\t\t\t\t\tputs \"Invalid input! Please try again.\"\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\t\treturn @userChoice\n\tend",
"def askForCard\n n=0\n until @player_set.length == 3\n print \"Player please choose a card number(H/h for help and R/r for Restart and Q/q for Quit and D/d to delete last card from your selection): \"\n choice=gets.chomp\n while (!(1..@dealing_decks.play.length).include?choice.to_i)||(@player_set.include?(@dealing_decks.play[choice.to_i-1]))\n if choice.downcase ==\"r\"\n return 1\n elsif choice.downcase ==\"q\"\n return 2\n elsif choice.downcase == \"d\"\n del = @player_set.pop\n puts \"Nothing to delete from selection!\", n += 1 if del == nil\n n -= 1\n @player_set.each do |card|\n print \"#{@player_set.index(card)+1}: \"\n print_a_card(card)\n end\n print \"Please enter a card number (H/h for help and R/r for Restart and Q/q for Quit and D/d to delete last card from your selection): \"\n choice=gets.chomp\n elsif choice.downcase == \"h\"\n print_rules\n print \"Please enter a card number (H/h for help and R/r for Restart and Q/q for Quit and D/d to delete last card from your selection): \"\n choice=gets.chomp\n else\n print \"ERROR not a valid card number! Please enter a card (H/h for help and R/r for Restart and Q/q for Quit and D/d to delete last card from your selection): \"\n choice=gets.chomp\n end\n end\n @player_set[n]=@dealing_decks.play[choice.to_i-1]\n #Printing out choice set\n @player_set.each do |card|\n print \"#{@player_set.index(card)+1}: \"\n print_a_card(card)\n end\n n+=1\n end\n\n end",
"def selection_cards cards\n puts 'Please select 3 cards for your chosen set or enter \\'q\\' as your first card to quit.'\n print 'First card: '\n card_one = gets.chomp\n if card_one.eql? 'q'\n puts 'Quiting current game...'\n return ['q']\n else\n print 'Second card: '\n card_two = gets.chomp\n printf 'Third card: '\n card_three = gets.chomp\n card_one, card_two, card_three = *(dupes card_one, card_two, card_three)\n validRng = 0...cards.size\n until (validRng.cover? card_one) && (validRng.cover? card_two) && (validRng.cover? card_three)\n puts 'A card choice was found to be invalid. Please select 3 new cards.'\n print 'First card: '\n card_one = gets.chomp\n print 'Second card: '\n card_two = gets.chomp\n print 'Third card: '\n card_three = gets.chomp\n card_one, card_two, card_three = *(dupes card_one, card_two, card_three)\n end\n end\n [cards[card_one], cards[card_two], cards[card_three]]\nend",
"def removeCards\n\t\t@userChoice.each do |card1|\n\t\t\t@table.each do |card2|\n\t\t\t\tif card1.path == card2.path\n\t\t\t\t\t@table.delete(card2)\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\tend\n\tend",
"def create_card\n # If there are no lists then warn the user\n if $state[\"current board\"].lists.empty?\n puts \"You must create a list before you can add cards\".colorize(:red)\n return\n end\n\n # Prompt the user to create cards and add them to lists\n add_card = $prompt.select(\n \"Would you like to add some cards to your lists?\", \n {\"Yes\" => true, \"No\" => false})\n\n while add_card\n # Check which list to add the card to\n lists = $state[\"current board\"].lists.keys\n add_to_list = $prompt.select(\"Which list would you like to add the card to?\", lists)\n \n # Prompt the user for a description of their card\n card_desc = $prompt.ask(\"Enter a description for your card: \")\n \n # Create the card and add it to the given list\n card = Card.new(card_desc)\n $state[\"current board\"].lists[add_to_list].add_card(card)\n add_card = $prompt.select(\"Would you like to add some cards to your lists?\", {\"Yes\" => true, \"No\" => false})\n end\n\nend",
"def purchase_card(turn)\n own_money = turn.player.money\n keep_repeating = true\n while keep_repeating == true do\n keep_repeating = false \n @@cli.say \"Now it is time to purchase a card; you have <%= color('#{own_money}', BOLD) %> money.\"\n # Create a hash for the cards in the town\n town_cards = Hash[ @mk.town.deck.map {|e| [\"#{e[1]} x #{e[0].attribute[:name]} (#{e[0].attribute[:cost]})\", [:establishment, e[0], e[0].attribute[:cost]]]} ]\n card_name_list = town_cards.sort_by { |key, val| val[1].attribute[:from_roll] }.to_h\n # add the landmarks\n card_name_list.merge!(Hash[ turn.player.unbuilt_landmarks.map {|l| [\"#{l.name} (#{l.cost})\", [:landmark, l, l.cost]]} ])\n @@cli.choose do |menu|\n menu.prompt = \"Which card to do you want to buy? \"\n menu.choices(*card_name_list.keys) do |chosen|\n @@cli.say \"You have chosen <%= color('#{chosen}', BOLD) %>. \"\n if own_money < card_name_list[chosen][2]\n @@cli.say \"You can't afford that! It costs #{card_name_list[chosen][2]} but you only have #{own_money}\"\n keep_repeating = true\n else\n process_purchase_of_card(turn, card_name_list[chosen])\n end\n end\n menu.choice(:none, {:text => \"NOTHING TO ME, AH VIENNA\"}) { @@cli.say \"OK, you have chosen to not purchase any card.\"}\n menu.choice(:databank) { databank_menu; keep_repeating = true}\n end\n end\n end",
"def pick_a_set\n cards = []\n (1..3).each do |i|\n print \"Choose card #{i}: \"\n answer = gets.to_i\n until answer.between?(1, @board.length) && !cards.include?(@board[answer - 1])\n print \"Try again! Choose card #{i}: \"\n answer = gets.to_i\n end\n cards << @board[answer - 1]\n end\n cards\n end",
"def box_choice(available_boxes_names)\n puts \"\\n#{@name}, your turn to chose the Box where you want to add #{@symbol} : \"\n puts \"the remaining boxes are : #{available_boxes_names}\"\n hit = \"\"\n #récupération de l'input de l'utilisateur, en vérifiant que la case choisie est vide\n while !available_boxes_names.include?(hit) \n hit = gets.chomp.capitalize\n if !available_boxes_names.include?(hit)\n puts \"This box is not available, please choose an empty box\"\n end \n end\n #stockage du choix de l'utilisateur dans son hit box : \n @hit_box_array << hit\n return hit \n end",
"def play_cards\n get_game\n selection = params[:cards].split(\",\")\n selection_cards = selection.map {|str_indx| @game.flat_field[str_indx.to_i] }\n if (selection_cards.compact.length != 3)\n render :json => {\n :state => :bad_move,\n :error => 'You did not select three cards.'\n }\n return true\n end\n @found_set = @game.make_set_selection(@current_player, *selection_cards)\n unless @found_set\n render :json => {\n :state => :bad_move,\n :error => 'The three cards you selected are not a set.'\n }\n return true\n end\n if update_field\n return get_field\n end\n render :json => {:state => :finished}\n end",
"def selection(playing_cards)\n\n if !@chosen_cards_indexes.include? @current_card_index\n @chosen_cards_indexes.push @current_card_index\n @chosen_cards.push playing_cards[@current_card_index]\n else\n @chosen_cards_indexes.delete @current_card_index\n @chosen_cards.delete playing_cards[@current_card_index]\n end\n end",
"def review_list_choices\n system \"clear\"\n if @crud.get_review.size == 0\n @art.no_movie\n if @prompt.yes? (\"Would you like to add a review to the list?\")\n add_review\n else\n review_menu\n end\n\n else\n movie_reviews_table\n input = @prompt.select(\" Please select an option\", cycle: true) do |menu|\n puts \"\"\n menu.choice \" Select a review to read\", 1\n menu.choice \" Go back\", 2\n end\n\n case input\n when 1\n reads_review\n when 2\n review_menu\n end\n end\n end",
"def recipe_cards\n Recipecard.all.select do |rc|\n rc.user == self\n end\n end",
"def cards(options = { :filter => :open })\n return @cards if @cards\n @cards = Client.get(\"/members/#{username}/cards\", options).json_into(Card)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
finds the users cards, removes any duplicates and subtracts that number from total cards (160) Displays message showing how many cards user still needs to complete colletion.
|
def cards_left_to_collect
card_ids = UserCard.select {|card| card["user_id"] == self.id}
remaining = Card.all.count - card_ids.map { |card| card["card_id"] }.uniq.count
if remaining == 0
puts "====================================================================="
puts "Congratulations, you have completed the Superhero card album!!"
puts "====================================================================="
else
puts "====================================================================="
puts "You still have #{remaining} cards left to collect..."
puts "====================================================================="
end
end
|
[
"def removeCards\n\t\t@userChoice.each do |card1|\n\t\t\t@table.each do |card2|\n\t\t\t\tif card1.path == card2.path\n\t\t\t\t\t@table.delete(card2)\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\tend\n\tend",
"def full_dance_card\n\t\tif @card.length > 5\n\t\t\tputs \"Your dance card is full! You have to dance with #{@card[0]} before you can add #{@card[-1]}\"\n\t\t\t@card.delete_at(-1)\n\t\tend\n\t\t@card\n\tend",
"def subtract_aces(card_values)\n sum = sum(card_values)\n while card_values.include?(11) && over_limit?(card_values)\n\n sum -= 10\n card_values.delete_at(card_values.index(11) || card_values.length)\n end\n sum\nend",
"def track_gift_cards_used\n \n #update any gift cards used on the order\n self.gift_cards.sort! {|x,y| x.current_amount <=> y.current_amount} #sort smallest amount first\n \n gc_ids = []\n gc_total = self.total_gift_cards\n\n #alter the gc balances on used cards\n self.gift_cards.each do |card|\n \n gc_ids << card.id\n\n if gc_total.cents > 0\n\n #adjust amount as necessary\n if gc_total >= card.current\n gc_total -= card.current\n card.current_amount = 0\n else\n card.current_amount -= gc_total\n gc_total = 0\n end\n\n card.save! #save the adjustments to the current_amount\n\n end #end if gc_total > 0\n\n end #end card.gift_cards.each\n\n end",
"def update_user_collection\n traded_cards.includes(:trade).each do |traded_card|\n owned_card = traded_card.to_corresponding_owned_card\n\n owned_card.number += traded_card.number\n if owned_card.number < 1\n owned_card.destroy if owned_card.persisted?\n else\n owned_card.save\n end\n end\n end",
"def destroy_solely_owned_cards\n all_my_cards = self.cards\n owned_cards = all_my_cards.select do |card|\n cards.users.length == 1\n end\n owned_cards.each &:destroy!\n end",
"def deal5cards (n)",
"def delete_card\n prompt = TTY::Prompt.new\n your_cards = self.cards\n card_names = your_cards.map { |card| card[\"name\"] }\n selected_card_name = prompt.select('Choose a character to delete', card_names, filter: true, cycle: true, help: \"(Start typing to filter results)\", help_color: :green, active_color: :yellow)\n selected_card = Card.find_by(name: selected_card_name)\n choice = UserCard.find_by user_id: self.id, card_id: selected_card.id\n response = prompt.select(\"Are you sure you want to delete #{selected_card_name.upcase}?\", %w(Yes No))\n if response == \"Yes\"\n choice.destroy\n bar = TTY::ProgressBar.new(\"Deleting #{selected_card_name.upcase} [:bar]\", total: 30)\n 30.times do\n sleep(0.05)\n bar.advance(1)\n end\n puts \"#{choice.card.name.upcase} was deleted from your collection!\"\n sleep(1)\n system('clear')\n title\n else\n check_collection\n end\n end",
"def deal_board_cards(n)\n\t\t\tself.board_cards += pe.get_random_cards_not_in_str(all_cards_used, n)\n\t\tend",
"def remove\n UserCard.where(user_id: current_user.id, debit_card_id: params[:id]).first.destroy\n redirect_to root_path, notice: \"Card removed.\"\n end",
"def remaining_cards\r\n @deck_of_cards.each do |card|\r\n card.output_card\r\n end\r\n end",
"def attack\n selected_card = lowest_card(non_trump_cards)\n selected_card = lowest_card(trump_cards) if selected_card.nil?\n @cards.delete(selected_card)\n selected_card\n end",
"def deal_cards\n MAX_CARDS.times do |d|\n @player_manager.players.each do |player| \n player.rack.add_card(@decks_manager.draw_pile.draw_card)\n end\n end\n\n # prep the discard pile with one card from the top of the draw pile\n @decks_manager.discard_top_card\n end",
"def remove_cards\n\t\t@cards.slice!(0,2)\n\tend",
"def removeCard\n card = @deck[@top_of_deck]\n @top_of_deck += 1\n if @top_of_deck == @deck.length\n shuffle\n end\n card\n end",
"def deal_hand no_of_cards\r\n @card_list.deal_hand no_of_cards\r\n end",
"def removeCards\n\t\t@cards.slice!(0,2)\n\tend",
"def xremove_from_initial_cc_list\n\n details = flash[:details]\n @reviewers = details[:reviewers]\n user = User.find(params[:id])\n\n # Update the database\n details[:design].board.users.delete(user)\n\n # Update the history\n if 1 == 2\n # Deal with the cc_list_history\n end\n\n # Update the display lists\n details[:copied].delete_if { |u| u.id == user.id }\n\n not_copied = details[:not_copied]\n user[:name] = user.name\n not_copied.push(user)\n details[:not_copied] = not_copied.sort_by { |u| u.last_name }\n\n @users_copied = details[:copied]\n @users_not_copied = details[:not_copied]\n\n flash[:details] = details\n flash[:ack] = \"Removed #{user.name} from the CC list\"\n\n render(:layout=>false)\n\n end",
"def removeCards\n @cards.slice!(0,2)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Unit + balance text
|
def units_balance
return "#{@unit} balance" if @unit.present?
'Balance'
end
|
[
"def output_balance\n '£' + '%.2f' % @balance\n end",
"def print_balance\n \"Your balance is now: £#{self.balance}\"\n end",
"def display_balance\n \"Your balance is $#{@balance}.\"\n end",
"def prt_balance\n b = self.balance\n return \"#{'-' if b.cents<0}#{b.currency.symbol}#{b.abs.to_s}\"\n end",
"def output_amount\n '£' + '%.2f' % @amount\n end",
"def amount_in_words\n return \"VOID\" if void\n # Wrap cents in string before calling numwords to avoid\n # SafeBuffer cannot modify string in place error\n cents = \"#{self.cents}\".en.numwords\n\n \"#{dollars.en.numwords} Dollars and #{cents} Cents\".titleize\n end",
"def test_t_amt\n assert_equal @v.t_amt(\"Rachel>Joey(100)\"), \"100\"\n end",
"def unit_s\n self.unit.to_s if self.unit\n end",
"def print_amount_type\n print_amount 'gold', @gold\n print_amount 'silver', @silver\n puts '.'\n end",
"def pending_balance_display\n number_to_currency(pending_balance)\n end",
"def account_name_balance\n name + ' (' + current_balance_display + ')'\n end",
"def buy_output\n '%.2f' % buy\n end",
"def current_balance_display\n number_to_currency(current_balance)\n end",
"def unit\n unitchoice = current_user.trade_unit\n if unitchoice == 1\n @unit = \"pips\"\n elsif unitchoice == 2\n @unit = \"points\"\n elsif unitchoice == 3\n @unit = \"dollars\"\n elsif unitchoice == 4\n @unit = \"percent\"\n elsif unitchoice == 5\n @unit = \"R\"\n else\n @unit = \"undefined\"\n end\n end",
"def output_overdraft\n '£' + '%.2f' % @overdraft \n end",
"def unit_t\n I18n.t \"#{self.unit_s}\", :count => 1\n end",
"def total_balance_text_field\r\n @browser.text_field(:id, 'txt_ttl_val')\r\n end",
"def debt\n subtotal - _normed_balance\n end",
"def display_current_balance\n change_two_decimals\n return \"Your current balance is $#{@balance}.\"\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /purchase_templates/1 GET /purchase_templates/1.json
|
def show
@purchase_template = PurchaseTemplate.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @purchase_template }
end
end
|
[
"def templates\n response = get \"storage/template\"\n data = JSON.parse response.body\n data\n end",
"def templates\n response = get \"storage/template\"\n data = JSON.parse response.body\n data\n end",
"def details\n response = get \"/templates/#{template_id}.json\", {}\n Hashie::Mash.new(response)\n end",
"def details\n response = CreateSend.get \"/templates/#{template_id}.json\", {}\n Hashie::Mash.new(response)\n end",
"def new\n @purchase_template = PurchaseTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @purchase_template }\n end\n end",
"def index\n @one_table_templates =\n @one_table.\n one_table_templates.\n by_user(current_user)\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @one_table_templates }\n end\n end",
"def get_product_templates_support_data\n @client.raw('get', '/ecommerce/product-templates/support-data')\n end",
"def get_report_template(args = {}) \n get(\"/reports.json/template/#{args[:templateId]}\", args)\nend",
"def get_templates(limit = 100, offset = 0)\n params = { limit: limit, offset: offset }\n\n request :get,\n '/v3/templates.json',\n params\n end",
"def list\n @client.make_request :get, templates_path\n end",
"def index\n @inventory_templates = InventoryTemplate.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @inventory_templates }\n end\n end",
"def index\n @exercise_templates = ExerciseTemplate.all\n render json: @exercise_templates\n end",
"def show\n @ticket_template = @current_account.ticket_templates.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ticket_template }\n end\n end",
"def retrieve_single_template( template_id )\n puts \"Retrieving template id #{template_id}.\"\n\n uri = URI(@config['endpoint'] + '/' + template_id)\n\n # Retrieve templates\n http = Net::HTTP.new( uri.host,uri.port )\n http.use_ssl = true\n request = Net::HTTP::Get.new( uri.request_uri )\n request.basic_auth(@primary_username, @primary_password)\n\n response = http.request( request )\n template = JSON.parse( response.body )\n end",
"def show\n @one_table_template =\n @one_table.\n one_table_templates.\n by_user(current_user).\n find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @one_table_template }\n end\n end",
"def index\n @product_templates = ProductTemplate.all\n end",
"def show\n @invoice_template = InvoiceTemplate.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @invoice_template }\n end\n end",
"def template_details(guid)\n get \"/api/templates/#{guid}.xml\", {}\n end",
"def license_templates(options = {})\n get('/templates/licenses', query: options)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /purchase_templates/new GET /purchase_templates/new.json
|
def new
@purchase_template = PurchaseTemplate.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @purchase_template }
end
end
|
[
"def new\n @ticket_template = @current_account.ticket_templates.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @ticket_template }\n end\n end",
"def new\n @template = Template.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @template }\n end\n end",
"def new\n @template = Template.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @template }\n end\n end",
"def new\n @inventory_template = InventoryTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @inventory_template }\n end\n end",
"def new\n @invoice_template = InvoiceTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @invoice_template }\n end\n end",
"def create\n @purchase_template = PurchaseTemplate.new(params[:purchase_template])\n\n respond_to do |format|\n if @purchase_template.save\n format.html { redirect_to @purchase_template, notice: 'Purchase template was successfully created.' }\n format.json { render json: @purchase_template, status: :created, location: @purchase_template }\n else\n format.html { render action: \"new\" }\n format.json { render json: @purchase_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @breadcrumb = 'create'\n @contract_template = ContractTemplate.new\n @towns = towns_dropdown\n @provinces = provinces_dropdown\n @regions = Region.order(:name)\n @countries = Country.order(:name)\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contract_template }\n end\n end",
"def new\n @admin_template_type = TemplateType.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @admin_template_type }\n end\n end",
"def new\n @admin_template_source = TemplateSource.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @admin_template_source }\n end\n end",
"def new\n @project_template = ProjectTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project_template }\n end\n end",
"def new\n @template_type = TemplateAuthor.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @template_type }\n end\n end",
"def new\n @breadcrumb = 'create'\n @contract_template_term = ContractTemplateTerm.new\n \n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @contract_template_terms }\n end\n end",
"def new\n @set_template = SetTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @set_template }\n end\n end",
"def new\n @usertemplate = Usertemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @usertemplate }\n end\n end",
"def new\n @page_template = PageTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @page_template }\n end\n end",
"def new\n @phase_template = PhaseTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @phase_template }\n end\n end",
"def new\n @email_template = EmailTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @email_template }\n end\n end",
"def new\n @_template = @site.templates.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @_template }\n end\n end",
"def new\n @inventory_template = InventoryTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.js\n format.json { render json: @inventory_template }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /purchase_templates POST /purchase_templates.json
|
def create
@purchase_template = PurchaseTemplate.new(params[:purchase_template])
respond_to do |format|
if @purchase_template.save
format.html { redirect_to @purchase_template, notice: 'Purchase template was successfully created.' }
format.json { render json: @purchase_template, status: :created, location: @purchase_template }
else
format.html { render action: "new" }
format.json { render json: @purchase_template.errors, status: :unprocessable_entity }
end
end
end
|
[
"def create(options)\n API::request(:post, 'subscription_agreement_templates', options)\n end",
"def add_report_template(args = {}) \n post(\"/reports.json/template\", args)\nend",
"def create(values)\n @client.call(method: :post, path: 'templates', body_values: values)\n end",
"def create\n @ticket_template = @current_account.ticket_templates.new(params[:ticket_template])\n\n respond_to do |format|\n if @ticket_template.save\n format.html { redirect_to @ticket_template, notice: 'Ticket template was successfully created.' }\n format.json { render json: @ticket_template, status: :created, location: @ticket_template }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ticket_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @purchase_template = PurchaseTemplate.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @purchase_template }\n end\n end",
"def create_templates(json_response)\n json_response.map do |t|\n obj = Template.new(t)\n end\n end",
"def create\n @invoice_template = InvoiceTemplate.new(params[:invoice_template])\n\n respond_to do |format|\n if @invoice_template.save\n format.html { redirect_to @invoice_template, notice: 'Invoice template was successfully created.' }\n format.json { render json: @invoice_template, status: :created, location: @invoice_template }\n else\n format.html { render action: \"new\" }\n format.json { render json: @invoice_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @yamato_logistic_order_template = YamatoLogisticOrderTemplate.new(yamato_logistic_order_template_params)\n\n if @yamato_logistic_order_template.save\n render :show, status: :created, location: @yamato_logistic_order_template\n else\n render json: @yamato_logistic_order_template.errors, status: :unprocessable_entity\n end\n end",
"def templates\n response = get \"storage/template\"\n data = JSON.parse response.body\n data\n end",
"def create\n @inventory_template = InventoryTemplate.new(params[:inventory_template])\n\n respond_to do |format|\n if @inventory_template.save\n format.html { redirect_to @inventory_template, notice: 'Inventory template was successfully created.' }\n format.json { render json: @inventory_template, status: :created, location: @inventory_template }\n else\n format.html { render action: \"new\" }\n format.json { render json: @inventory_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @logistic_order_template = LogisticOrderTemplate.new(logistic_order_template_params)\n\n if @logistic_order_template.save\n render :show, status: :created, location: @logistic_order_template\n else\n render json: @logistic_order_template.errors, status: :unprocessable_entity\n end\n end",
"def create\n @transaction_template = TransactionTemplate.new(transaction_template_params)\n\n respond_to do |format|\n if @transaction_template.save\n format.html { redirect_to transaction_templates_url, notice: 'Transaction template was successfully created.' }\n format.json { render :show, status: :created, location: @transaction_template }\n else\n format.html { render :new }\n format.json { render json: @transaction_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @order_template = OrderTemplate.new(order_template_params)\n\n respond_to do |format|\n if @order_template.save\n format.html { redirect_to @order_template, notice: 'Order template was successfully created.' }\n format.json { render :show, status: :created, location: @order_template }\n else\n format.html { render :new }\n format.json { render json: @order_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def save_template(template_name, template_fields)\n data = template_fields\n data[:template] = template_name\n api_post(:template, data)\n end",
"def save_template(template_name, template_fields)\n data = template_fields\n data[:template] = template_name\n self.api_post(:template, data)\n end",
"def create\n @exercise_template = ExerciseTemplate.new(exercise_template_params)\n\n if @exercise_template.save\n render json: @exercise_template, status: :created, location: @exercise_template\n else\n render json: @exercise_template.errors, status: :unprocessable_entity\n end\n end",
"def create\n @label_template = Spree::LabelTemplate.new(params[:label_template])\n\n respond_to do |format|\n if @label_template.save\n format.html { redirect_to @label_template, notice: 'Label template was successfully created.' }\n format.json { render json: @label_template, status: :created, location: @label_template }\n else\n format.html { render action: \"new\" }\n format.json { render json: @label_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @item_template = ItemTemplate.new(item_template_params)\n\n respond_to do |format|\n if @item_template.save\n format.html { redirect_to @item_template, notice: 'Item template was successfully created.' }\n format.json { render :show, status: :created, location: @item_template }\n else\n format.html { render :new }\n format.json { render json: @item_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_template(options={})\n ios = create_file_ios(options[:files])\n file_params = create_file_params(ios)\n\n post_body = {\n emailBlurb: \"#{options[:email][:body] if options[:email]}\",\n emailSubject: \"#{options[:email][:subject] if options[:email]}\",\n documents: get_documents(ios),\n recipients: {\n signers: get_signers(options[:signers], template: true)\n },\n envelopeTemplateDefinition: {\n description: options[:description],\n name: options[:name],\n pageCount: 1,\n password: '',\n shared: false\n }\n }.to_json\n\n uri = build_uri(\"/accounts/#{acct_id}/templates\")\n http = initialize_net_http_ssl(uri)\n\n request = initialize_net_http_multipart_post_request(\n uri, post_body, file_params, headers(options[:headers])\n )\n\n response = http.request(request)\n JSON.parse(response.body)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PUT /purchase_templates/1 PUT /purchase_templates/1.json
|
def update
@purchase_template = PurchaseTemplate.find(params[:id])
respond_to do |format|
if @purchase_template.update_attributes(params[:purchase_template])
format.html { redirect_to @purchase_template, notice: 'Purchase template was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @purchase_template.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update_report_template(args = {}) \n put(\"/reports.json/template/#{args[:templateId]}\", args)\nend",
"def create\n @purchase_template = PurchaseTemplate.new(params[:purchase_template])\n\n respond_to do |format|\n if @purchase_template.save\n format.html { redirect_to @purchase_template, notice: 'Purchase template was successfully created.' }\n format.json { render json: @purchase_template, status: :created, location: @purchase_template }\n else\n format.html { render action: \"new\" }\n format.json { render json: @purchase_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @template = templates_keystore_params[:source_type] == 'Templates::Template' ? Templates::Template.find(templates_keystore_params[:source_id]) : Templates::Page.find(templates_keystore_params[:source_id]).try(:template)\n\n respond_to do |format|\n if @templates_keystore.update(templates_keystore_params)\n format.html { redirect_to @template, notice: 'Keystore was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @templates_keystore.errors, status: :unprocessable_entity }\n end\n end\n end",
"def ajax_update_template_info\n\n # Access current template being edited\n template = EmailTemplate.find(params[:template_id])\n\n template.name = params[:name]\n template.description = params[:description]\n template.email_subject = params[:email_subject]\n\n template.put('', {\n :name => template.name,\n :description => template.description,\n :email_subject => template.email_subject\n })\n\n\n response = {\n :success => true\n }\n\n # Return JSON response\n render json: response\n\n\n end",
"def update\n @invoice_template = InvoiceTemplate.find(params[:id])\n\n respond_to do |format|\n if @invoice_template.update_attributes(params[:invoice_template])\n format.html { redirect_to @invoice_template, notice: 'Invoice template was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @invoice_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @one_table_template =\n @one_table.\n one_table_templates.\n by_user(current_user).\n find(params[:id])\n\n respond_to do |format|\n if @one_table_template.update_attributes(params[:one_table_template])\n format.html { redirect_to [@one_table, @one_table_template], notice: t(:one_table_template_updated) }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @one_table_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_email_template(email_template_id, request)\n start.uri('/api/email/template')\n .url_segment(email_template_id)\n .body_handler(FusionAuth::JSONBodyHandler.new(request))\n .put()\n .go()\n end",
"def update(name, description)\n res = client.put(\"#{domain}/templates/#{name}\", description: description)\n res.to_h\n rescue Mailgun::CommunicationError\n false\n end",
"def update\n @inventory_template = InventoryTemplate.find(params[:id])\n\n respond_to do |format|\n if @inventory_template.update_attributes(params[:inventory_template])\n format.html { redirect_to @inventory_template, notice: 'Inventory template was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @inventory_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @order_template.update(order_template_params)\n format.html { redirect_to @order_template, notice: 'Order template was successfully updated.' }\n format.json { render :show, status: :ok, location: @order_template }\n else\n format.html { render :edit }\n format.json { render json: @order_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @template = current_site.templates.find(params[:id])\n params[:template].delete(:name) unless @template.is_deletable?\n respond_to do |format|\n if @template.update_attributes(params[:template])\n format.html { redirect_to(edit_admin_template_url(@template), :notice => t('templates.notices.updated', :default=>'Template was successfully updated.')) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def destroy\n @purchase_template = PurchaseTemplate.find(params[:id])\n @purchase_template.destroy\n\n respond_to do |format|\n format.html { redirect_to purchase_templates_url }\n format.json { head :no_content }\n end\n end",
"def update\n @ticket_template = TicketTemplate.find(params[:id])\n\n respond_to do |format|\n if @ticket_template.update_attributes(params[:ticket_template])\n format.html { redirect_to @ticket_template, notice: 'Ticket template was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ticket_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @label_template = Spree::LabelTemplate.find(params[:id])\n\n respond_to do |format|\n if @label_template.update_attributes(params[:label_template])\n format.html { redirect_to @label_template, notice: 'Label template was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @label_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @set_template = SetTemplate.find(params[:id])\n\n respond_to do |format|\n if @set_template.update_attributes(params[:set_template])\n format.html { redirect_to @set_template, :notice => 'Set template was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @set_template.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @inventory_template = InventoryTemplate.find(params[:id])\n # @inventory_template.restaurant = current_owner.restaurant\n\n respond_to do |format|\n if @inventory_template.update_attributes(params[:inventory_template])\n format.html { redirect_to @inventory_template, notice: 'Inventory template was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @inventory_template.errors, status: :unprocessable_entity }\n end\n end\n end",
"def save_template(template_name, template_fields)\n data = template_fields\n data[:template] = template_name\n api_post(:template, data)\n end",
"def update\n @exercise_template = ExerciseTemplate.find(params[:id])\n\n if @exercise_template.update(exercise_template_params)\n head :no_content\n else\n render json: @exercise_template.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @item_template.update(item_template_params)\n format.html { redirect_to @item_template, notice: 'Item template was successfully updated.' }\n format.json { render :show, status: :ok, location: @item_template }\n else\n format.html { render :edit }\n format.json { render json: @item_template.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /purchase_templates/1 DELETE /purchase_templates/1.json
|
def destroy
@purchase_template = PurchaseTemplate.find(params[:id])
@purchase_template.destroy
respond_to do |format|
format.html { redirect_to purchase_templates_url }
format.json { head :no_content }
end
end
|
[
"def delete\n response = CreateSend.delete \"/templates/#{template_id}.json\", {}\n end",
"def destroy\n @invoice_template = InvoiceTemplate.find(params[:id])\n @invoice_template.destroy\n\n respond_to do |format|\n format.html { redirect_to invoice_templates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @item_template.destroy\n respond_to do |format|\n format.html { redirect_to item_templates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @one_table_template =\n @one_table.\n one_table_templates.\n by_user(current_user).\n find(params[:id])\n @one_table_template.destroy\n\n respond_to do |format|\n format.html { redirect_to one_table_one_table_templates_url(@one_table) }\n format.json { head :no_content }\n end\n end",
"def delete(options={})\n DNSimple::Client.delete \"templates/#{id}\", options\n end",
"def destroy\n @inventory_template = InventoryTemplate.find(params[:id])\n @inventory_template.destroy\n\n respond_to do |format|\n format.html { redirect_to inventory_templates_url }\n format.json { head :no_content }\n end\n end",
"def delete_report_template(args = {}) \n body_delete(\"/reports.json/template\", args[:array_of_ids])\nend",
"def destroy\n @express_template.destroy\n\n respond_to do |format|\n format.html { redirect_to shop_admin_express_templates_path(current_shop.name) }\n format.json { head :no_content }\n end\n end",
"def delete_course_template(org_unit_id)\n path = \"/d2l/api/lp/#{$lp_ver}/coursetemplates/#{org_unit_id}\"\n _delete(path)\n puts '[+] Course template data deleted successfully'.green\nend",
"def trash_template(guid)\n delete \"/api/templates/#{guid}.xml\"\n end",
"def destroy\n @customtemplate.destroy\n respond_to do |format|\n format.html { redirect_to customtemplates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @affiche_template.destroy\n\n respond_to do |format|\n format.html { redirect_to affiche_templates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @induction_template.destroy\n respond_to do |format|\n format.html { redirect_to induction_templates_url, notice: 'Induction template was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @template.destroy\n\n respond_to do |format|\n format.html { redirect_to templates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @template.destroy\n respond_to do |format|\n format.html { redirect_to templates_templates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @spree_admin_template.destroy\n respond_to do |format|\n format.html { redirect_to :back }\n format.json { head :no_content }\n end\n end",
"def delete(name)\n r = request('DeleteTemplate', { :name => name })\n return r['status'] == ' ok ' \n end",
"def destroy\n @template_type.destroy\n\n respond_to do |format|\n format.html { redirect_to templates_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @gift_template = GiftTemplate.find(params[:id])\n @gift_template.destroy\n\n respond_to do |format|\n format.html { redirect_to gift_templates_path }\n format.json { head :no_content }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /serie_detalles POST /serie_detalles.json
|
def create
@serie_detalle = SerieDetalle.new(serie_detalle_params)
respond_to do |format|
if @serie_detalle.save
format.html { redirect_to @serie_detalle, notice: 'Serie detalle was successfully created.' }
format.json { render :show, status: :created, location: @serie_detalle }
else
format.html { render :new }
format.json { render json: @serie_detalle.errors, status: :unprocessable_entity }
end
end
end
|
[
"def create\n @detalle = Detalle.new(params[:detalle])\n\n respond_to do |format|\n if @detalle.save\n format.html { redirect_to @detalle, notice: 'Detalle was successfully created.' }\n format.json { render json: @detalle, status: :created, location: @detalle }\n else\n format.html { render action: \"new\" }\n format.json { render json: @detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @registro_cliente_servicio_detalle = Registro::ClienteServicioDetalle.new(registro_cliente_servicio_detalle_params)\n\n respond_to do |format|\n if @registro_cliente_servicio_detalle.save\n format.html { redirect_to @registro_cliente_servicio_detalle, notice: 'Cliente servicio detalle was successfully created.' }\n format.json { render :show, status: :created, location: @registro_cliente_servicio_detalle }\n else\n format.html { render :new }\n format.json { render json: @registro_cliente_servicio_detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @detalle = Detalle.new(detalle_params)\n\n respond_to do |format|\n if @detalle.save\n format.html { redirect_to @detalle, notice: 'Detalle was successfully created.' }\n format.json { render :show, status: :created, location: @detalle }\n else\n format.html { render :new }\n format.json { render json: @detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @venta_detalle = VentaDetalle.new(params[:venta_detalle])\n\n respond_to do |format|\n if @venta_detalle.save\n format.html { redirect_to @venta_detalle, notice: 'Venta detalle was successfully created.' }\n format.json { render json: @venta_detalle, status: :created, location: @venta_detalle }\n else\n format.html { render action: \"new\" }\n format.json { render json: @venta_detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @proceso_detalle = ProcesoDetalle.new(proceso_detalle_params)\n\n respond_to do |format|\n if @proceso_detalle.save\n format.html { redirect_to @proceso_detalle, notice: 'Proceso detalle was successfully created.' }\n format.json { render :show, status: :created, location: @proceso_detalle }\n else\n format.html { render :new }\n format.json { render json: @proceso_detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @detalles = Detalle.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @detalles }\n end\n end",
"def create\n\n @pedidodetalle = Pedidodetalle.new(params[:pedidodetalle])\n\n @pedidodetalles = Pedidodetalle.all\n\n respond_to do |format|\n if @pedidodetalle.save\n format.html { redirect_to pedidodetalles_url, notice: 'Guardado!' }\n else\n render :action => 'index'\n end\n end\n end",
"def create\n @estudiante = Estudiante.new(params[:estudiante])\n\n if @estudiante.save\n render json: @estudiante, status: :created, location: @estudiante\n else\n render json: @estudiante.errors, status: :unprocessable_entity\n end\n end",
"def new\n @detalle = Detalle.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @detalle }\n end\n end",
"def create\n @detalle_pedido = DetallePedido.new(detalle_pedido_params)\n\n respond_to do |format|\n if @detalle_pedido.save\n format.html { redirect_to @detalle_pedido, notice: 'Detalle pedido was successfully created.' }\n format.json { render :show, status: :created, location: @detalle_pedido }\n else\n format.html { render :new }\n format.json { render json: @detalle_pedido.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @detalleorden = Detalleorden.new(detalleorden_params)\n\n respond_to do |format|\n if @detalleorden.save\n format.html { redirect_to @detalleorden, notice: 'Detalleorden was successfully created.' }\n format.json { render :show, status: :created, location: @detalleorden }\n else\n format.html { render :new }\n format.json { render json: @detalleorden.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @pedidodetalle = Pedidodetalle.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @pedidodetalle }\n end\n end",
"def destroy\n @serie_detalle.destroy\n respond_to do |format|\n format.html { redirect_to serie_detalles_url, notice: 'Serie detalle was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def create\n\n @notadedebito = Notadedebito.find(params[:notadedebito_id])\n @renglon_ndddetalle = @notadedebito.renglon_ndddetalles.create(params[:renglon_ndddetalle])\n\n respond_to do |format|\n if @renglon_ndddetalle.save\n format.html { redirect_to @notadedebito, notice: 'Renglon ndddetalle was successfully created.' }\n format.json { render json: @renglon_ndddetalle }\n else\n format.html { render action: \"new\" }\n format.json { render json: @renglon_ndddetalle.errors }\n end\n end\n end",
"def create\n @objeto = DetallePedido.new(detalle_pedido_params)\n\n respond_to do |format|\n if @objeto.save\n set_redireccion\n format.html { redirect_to @redireccion, notice: 'Detalle pedido was successfully created.' }\n format.json { render :show, status: :created, location: @objeto }\n else\n format.html { render :new }\n format.json { render json: @objeto.errors, status: :unprocessable_entity }\n end\n end\n end",
"def scraping\n\n\tdepute = Deput.new(\"\",\"\",\"\",\"\",\"\")\n\turl = \"http://www2.assemblee-nationale.fr/deputes/liste/tableau\"\n\thtml = URI.open(\"#{url}\").read\n\tnokogiri_doc = Nokogiri::HTML(html)\n\tdepute_array = []\n\ti = 1\n\tnokogiri_doc.xpath(\"//td\").each_with_index do |element,index|\n\t if i === 3 \n\t \tdepute_array << depute\n\t\tdepute = Deput.new(\"\" ,\"\",\"\",\"\",\"\")\n\t\ti=1\n\t elsif i === 2 \n\t depute.setdep(element.text) \n\t\ti = i+1\n\t else\n\t\tl= element.css('a').map { |link| link['href'] }\n\t\tl.each do |e|\n\t\t\tdepute.seturl(url[0,34]+e.strip)\n\t\tend\n\t\tl = element.text.strip.split(\" \")\n\t\tdepute.setprenom(l[1])\n\t depute.setnom(l[2])\n\t\tdepute.setgenre(l[0])\n\t\ti= i+1\t\n\t end\n\tend\n\t\n\n\tFile.open(\"data2.json\",\"w\") do |f|\n\t f.write( depute_array.map { |item| {:nom => item.nom,:prenom => item.prenom, :departement => item.departement,:genre => item.genre,:url => item.url} }.to_json) \n\tend \t\n\t\nend",
"def create\n @detalleapuestum = Detalleapuestum.new(params[:detalleapuestum])\n\n respond_to do |format|\n if @detalleapuestum.save\n format.html { redirect_to @detalleapuestum, notice: 'Detalleapuestum was successfully created.' }\n format.json { render json: @detalleapuestum, status: :created, location: @detalleapuestum }\n else\n format.html { render action: \"new\" }\n format.json { render json: @detalleapuestum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @venta_detalle = VentaDetalle.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @venta_detalle }\n end\n end",
"def create\n @presupuesto_detalle = PresupuestoDetalle.new(presupuesto_detalle_params)\n\n respond_to do |format|\n if @presupuesto_detalle.save\n format.html { redirect_to @presupuesto_detalle, notice: 'Presupuesto detalle was successfully created.' }\n format.json { render :show, status: :created, location: @presupuesto_detalle }\n else\n format.html { render :new }\n format.json { render json: @presupuesto_detalle.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PATCH/PUT /serie_detalles/1 PATCH/PUT /serie_detalles/1.json
|
def update
respond_to do |format|
if @serie_detalle.update(serie_detalle_params)
format.html { redirect_to @serie_detalle, notice: 'Serie detalle was successfully updated.' }
format.json { render :show, status: :ok, location: @serie_detalle }
else
format.html { render :edit }
format.json { render json: @serie_detalle.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n respond_to do |format|\n if @registro_cliente_servicio_detalle.update(registro_cliente_servicio_detalle_params)\n format.html { redirect_to @registro_cliente_servicio_detalle, notice: 'Cliente servicio detalle was successfully updated.' }\n format.json { render :show, status: :ok, location: @registro_cliente_servicio_detalle }\n else\n format.html { render :edit }\n format.json { render json: @registro_cliente_servicio_detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @detalle = Detalle.find(params[:id])\n\n respond_to do |format|\n if @detalle.update_attributes(params[:detalle])\n format.html { redirect_to @detalle, notice: 'Detalle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @safra_verdoso = SafraVerdoso.find(params[:id])\n\n respond_to do |format|\n if @safra_verdoso.update_attributes(params[:safra_verdoso])\n format.html { redirect_to \"/safra_produtos/#{@safra_verdoso.safra_produto_id}/descontos\"}\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @safra_verdoso.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @detalle.update(detalle_params)\n format.html { redirect_to @detalle, notice: 'Detalle was successfully updated.' }\n format.json { render :show, status: :ok, location: @detalle }\n else\n format.html { render :edit }\n format.json { render json: @detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @venta_detalle = VentaDetalle.find(params[:id])\n\n respond_to do |format|\n if @venta_detalle.update_attributes(params[:venta_detalle])\n format.html { redirect_to @venta_detalle, notice: 'Venta detalle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @venta_detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @estudiante = Estudiante.find(params[:id])\n\n if @estudiante.update(params[:estudiante])\n head :no_content\n else\n render json: @estudiante.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @objeto.update(detalle_pedido_params)\n set_redireccion\n format.html { redirect_to @redireccion, notice: 'Detalle pedido was successfully updated.' }\n format.json { render :show, status: :ok, location: @objeto }\n else\n format.html { render :edit }\n format.json { render json: @objeto.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @salle = Salle.find(params[:id])\n\n respond_to do |format|\n if @salle.update_attributes(params[:salle])\n format.html { redirect_to @salle, notice: 'Salle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @salle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @visite_protocolaire_equipement.update(visite_protocolaire_equipement_paramspermit(:idtype_potentiel,:valeur_potentiel,:idtype_equipement,:Nom,:tolerance,:commentaire))\n format.html { redirect_to @visite_protocolaire_equipement, notice: 'la Visite protocolaire équipement a été mis à jour.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @visite_protocolaire_equipement.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @compra_detalle = CompraDetalle.find(params[:id])\n\n respond_to do |format|\n if @compra_detalle.update_attributes(params[:compra_detalle])\n format.html { redirect_to @compra_detalle, notice: 'Compra detalle was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @compra_detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\r\n @salle = Salle.find(params[:id])\r\n\r\n respond_to do |format|\r\n if @salle.update_attributes(params[:salle])\r\n format.html { redirect_to @salle, notice: 'Salle was successfully updated.' }\r\n format.json { head :ok }\r\n else\r\n format.html { render action: \"edit\" }\r\n format.json { render json: @salle.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def update\n @detalle_compra = DetalleCompra.find(params[:id])\n\n respond_to do |format|\n if @detalle_compra.update_attributes(params[:detalle_compra])\n format.html { redirect_to @detalle_compra, notice: 'Detalle compra was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @detalle_compra.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @serienum.update(serienum_params)\n format.html { redirect_to edit_produto_path(@serienum.produto), notice: 'Serie alterada com sucesso.' }\n format.json { render :show, status: :ok, location: @serienum }\n else\n format.html { render :edit }\n format.json { render json: @serienum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @salle.update(salle_params)\n format.html { redirect_to salles_url, notice: 'Salle was successfully updated.' }\n format.json { render :show, status: :ok, location: @salle }\n else\n format.html { render :edit }\n format.json { render json: @salle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @servico.update(servico_params)\n format.html { redirect_to admin_pessoa_servicos_path(@pessoa), notice: 'Serviço foi atualizada com sucesso.' }\n format.json { head :no_content }\n else\n get_dependencies\n format.html { render action: 'edit' }\n format.json { render json: @servico.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n request = RestClient.put File.join(API_SERVER,\"rest-api/departments\"), { \n 'id' => params['id'], \n 'name' => params['department']['name'], \n 'description' => params['department']['description'] }.to_json, :content_type => :json, :accept => :json\n\n redirect_to :action => :index\n end",
"def update\n respond_to do |format|\n if @sivic_discipulo.update(sivic_discipulo_params_netested)\n format.html { redirect_to @sivic_discipulo, notice: 'Registro alterado com sucesso.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @sivic_discipulo.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @inventario_producto_detalle.update(inventario_producto_detalle_params)\n format.html { redirect_to @inventario_producto_detalle, notice: 'Producto detalle was successfully updated.' }\n format.json { render :show, status: :ok, location: @inventario_producto_detalle }\n else\n format.html { render :edit }\n format.json { render json: @inventario_producto_detalle.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @detalle_compra.update(detalle_compra_params)\n format.html { redirect_to @compra, notice: 'Detalle compra was successfully updated.' }\n format.json { render :show, status: :ok, location: @detalle_compra }\n else\n format.html { render :edit }\n format.json { render json: @detalle_compra.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /serie_detalles/1 DELETE /serie_detalles/1.json
|
def destroy
@serie_detalle.destroy
respond_to do |format|
format.html { redirect_to serie_detalles_url, notice: 'Serie detalle was successfully destroyed.' }
format.json { head :no_content }
end
end
|
[
"def destroy\n @detalle = Detalle.find(params[:id])\n @detalle.destroy\n\n respond_to do |format|\n format.html { redirect_to detalles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @venta_detalle = VentaDetalle.find(params[:id])\n @venta_detalle.destroy\n\n respond_to do |format|\n format.html { redirect_to venta_detalles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @detalle.destroy\n respond_to do |format|\n format.html { redirect_to detalles_url, notice: 'Detalle was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @salle = Salle.find(params[:id])\n @salle.destroy\n\n respond_to do |format|\n format.html { redirect_to salles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @seguidore = Seguidore.find(params[:id])\n @seguidore.destroy\n\n respond_to do |format|\n format.html { redirect_to seguidores_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @registro_cliente_servicio_detalle.destroy\n respond_to do |format|\n format.html { redirect_to registro_cliente_servicio_detalles_url, notice: 'Cliente servicio detalle was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @datosgenerale.destroy\n respond_to do |format|\n format.html { redirect_to datosgenerales_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @estatuto = Estatuto.find(params[:id])\n @estatuto.destroy\n\n respond_to do |format|\n format.html { redirect_to estatutos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @estacion = Estacion.find(params[:id])\n @estacion.destroy\n\n respond_to do |format|\n format.html { redirect_to estaciones_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @detalleapuestum = Detalleapuestum.find(params[:id])\n @detalleapuestum.destroy\n\n respond_to do |format|\n format.html { redirect_to detalleapuesta_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @estudiante = Estudiante.find(params[:id])\n @estudiante.destroy\n\n respond_to do |format|\n format.html { redirect_to estudiantes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @serasa.destroy\n respond_to do |format|\n format.html { redirect_to serasas_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @detalle_reserva.destroy\n respond_to do |format|\n format.html { redirect_to detalle_reservas_url, notice: 'Registro eliminado exitosamente.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @detallefactura = Detallefactura.find(params[:id])\n @detallefactura.destroy\n\n respond_to do |format|\n format.html { redirect_to detallefacturas_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @compra_detalle = CompraDetalle.find(params[:id])\n @compra_detalle.destroy\n\n respond_to do |format|\n format.html { redirect_to compra_detalles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @estudiante.destroy\n respond_to do |format|\n format.html { redirect_to estudiantes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @detalle_dia.destroy\n respond_to do |format|\n format.html { redirect_to detalle_dias_url, notice: 'Detalle dia was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @detalle_aula.destroy\n respond_to do |format|\n format.html { redirect_to detalle_aulas_url, notice: 'Detalle aula was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @safra_verdoso = SafraVerdoso.find(params[:id])\n @safra_verdoso.destroy\n\n respond_to do |format|\n format.html { redirect_to \"/safra_produtos/#{@safra_verdoso.safra_produto_id}/descontos\"}\n format.json { head :no_content }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /task_stats/1 GET /task_stats/1.json
|
def show
@task_stat = TaskStat.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @task_stat }
end
end
|
[
"def stats\n get 'stats', format: 'json'\n end",
"def stats\n # find project\n @project = Project.find(params[:id])\n # check user is manager of project\n if (!@superuser_is_superadmin && !(superuser_is_part_of_project? @project))\n flash[:warning] = \"You can't see stats for this project\"\n redirect_to lato_core.root_path and return false\n end\n # find datas\n @tasks = Task.where(project_id: @project.id).order('end_date ASC')\n @wait_tasks = @tasks.where(status: 'wait')\n @develop_tasks = @tasks.where(status: 'develop')\n @test_tasks = @tasks.where(status: 'test')\n @completed_tasks = @tasks.where(status: 'completed')\n @collaborators = @project.collaborators\n end",
"def statistics_task_by_status_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_status ...'\n end\n # resource path\n local_var_path = '/statistics/task_by_status'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskStatusFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_status\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def stats\n request :get, \"_stats\"\n end",
"def show\n @task_metric = TaskMetric.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @task_metric }\n end\n end",
"def task_summary(task_name)\n path = \"/projects/#{project.name}/instances/#{name}\"\n query = { instancesummary: true, taskname: task_name }\n client.get(path, query: query).parsed_response\n end",
"def tasks_stats\n output_examples_total unless options[:report_only_tasks]\n output_task_totals\n end",
"def activity_statistics\n get(\"/user/#{@user_id}/activities.json\")\n end",
"def show\n @progress = @task.progresses.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @progress }\n end\n end",
"def execution_statistics\r\n params = {\r\n method: :get,\r\n url: '/project/execution-statistics',\r\n params: {\r\n prjUUID: @uuid\r\n }\r\n }\r\n @session.request(params).perform!\r\n end",
"def get_summary(task_name)\n res = ODPS.conn.get \"projects/#{ODPS.current_project}/instances/#{self.name}?instancesummary&taskname=#{task_name}\"\n obj = JSON.parse res.body\n if obj.has_key? 'Instance'\n self.json_summary = obj['Instance']['JsonSummary']\n self.summary = obj['Instance']['Summary']\n end\n obj['Instance']\n end",
"def index\n \n @task_times = @task.task_times.order(\"stopped_at desc\")\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @task_times }\n end\n end",
"def stats\n @log.debug(\"Controller: Stats Called\")\n res = {\n :producers => producer_stats,\n :consumers => consumer_stats,\n :tasks => task_stats\n }\n end",
"def statistics_task_by_status(opts = {})\n data, _status_code, _headers = statistics_task_by_status_with_http_info(opts)\n data\n end",
"def statistics_task_by_workflow_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_workflow ...'\n end\n # resource path\n local_var_path = '/statistics/task_by_workflow'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskWorkflowFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_workflow\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def statistics_task_by_storage_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_storage ...'\n end\n # resource path\n local_var_path = '/statistics/task_by_storage'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskStorageFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_storage\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def statistics_task_by_metadata_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_metadata ...'\n end\n allowable_values = [\"count\", \"tasks_count\", \"to_process_size_sum\", \"processed_size_sum\", \"to_process_files_sum\", \"processed_files_sum\", \"finalized_files_sum\", \"bandwidth_avg\", \"bandwidth_count\"]\n if @api_client.config.client_side_validation && opts[:'sort'] && !allowable_values.include?(opts[:'sort'])\n fail ArgumentError, \"invalid value for \\\"sort\\\", must be one of #{allowable_values}\"\n end\n # resource path\n local_var_path = '/statistics/task_by_metadata'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n query_params[:'sort'] = opts[:'sort'] if !opts[:'sort'].nil?\n query_params[:'limit'] = opts[:'limit'] if !opts[:'limit'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskMetadataFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_metadata\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def manager_stats_by_hour\n get '/manager/stats/hourly'\n end",
"def stats\n perform_get('/stats', Neows::Models::Stat)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /task_stats/new GET /task_stats/new.json
|
def new
@task_stat = TaskStat.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @task_stat }
end
end
|
[
"def create\n @task_stat = TaskStat.new(params[:task_stat])\n\n respond_to do |format|\n if @task_stat.save\n format.html { redirect_to @task_stat, notice: 'Task stat was successfully created.' }\n format.json { render json: @task_stat, status: :created, location: @task_stat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @task_stat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @progress = @task.progresses.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @progress }\n end\n end",
"def new\r\n @status_task = StatusTask.new\r\n\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.json { render json: @status_task }\r\n end\r\n end",
"def new\n @task = tasks.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end",
"def new\n @task_metric = TaskMetric.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @task_metric }\n end\n end",
"def new\n\n\n\n @task = Task.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end",
"def new\n # raise params.inspect\n @task = Task.new \n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end",
"def new\n @system_task_statu = SystemTaskStatu.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @system_task_statu }\n end\n end",
"def new\n @analysis_task = AnalysisTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @analysis_task }\n end\n end",
"def new\n @stat = Stat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @stat }\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task_list }\n end\n end",
"def new\n @task_run = TaskRun.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task_run }\n end\n end",
"def new\n @stat = Stat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @stat }\n end\n end",
"def new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task_list }\n end\n end",
"def new\n @template_task = TemplateTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @template_task }\n end\n end",
"def new\n @task_activity = TaskActivity.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task_activity }\n end\n end",
"def new\n @daily_task = DailyTask.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @daily_task }\n end\n end",
"def new\n @task = Checklists::Task.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end",
"def new\n @task = @user.tasks.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /task_stats POST /task_stats.json
|
def create
@task_stat = TaskStat.new(params[:task_stat])
respond_to do |format|
if @task_stat.save
format.html { redirect_to @task_stat, notice: 'Task stat was successfully created.' }
format.json { render json: @task_stat, status: :created, location: @task_stat }
else
format.html { render action: "new" }
format.json { render json: @task_stat.errors, status: :unprocessable_entity }
end
end
end
|
[
"def statistics_task_by_status_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_status ...'\n end\n # resource path\n local_var_path = '/statistics/task_by_status'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskStatusFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_status\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def tasks_stats\n output_examples_total unless options[:report_only_tasks]\n output_task_totals\n end",
"def statistics_task_by_metadata_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_metadata ...'\n end\n allowable_values = [\"count\", \"tasks_count\", \"to_process_size_sum\", \"processed_size_sum\", \"to_process_files_sum\", \"processed_files_sum\", \"finalized_files_sum\", \"bandwidth_avg\", \"bandwidth_count\"]\n if @api_client.config.client_side_validation && opts[:'sort'] && !allowable_values.include?(opts[:'sort'])\n fail ArgumentError, \"invalid value for \\\"sort\\\", must be one of #{allowable_values}\"\n end\n # resource path\n local_var_path = '/statistics/task_by_metadata'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n query_params[:'sort'] = opts[:'sort'] if !opts[:'sort'].nil?\n query_params[:'limit'] = opts[:'limit'] if !opts[:'limit'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskMetadataFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_metadata\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def statistics_task_by_workflow_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_workflow ...'\n end\n # resource path\n local_var_path = '/statistics/task_by_workflow'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskWorkflowFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_workflow\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def write_thread_stats\n request({req: 'writethreadstats'})\n end",
"def stats\n # find project\n @project = Project.find(params[:id])\n # check user is manager of project\n if (!@superuser_is_superadmin && !(superuser_is_part_of_project? @project))\n flash[:warning] = \"You can't see stats for this project\"\n redirect_to lato_core.root_path and return false\n end\n # find datas\n @tasks = Task.where(project_id: @project.id).order('end_date ASC')\n @wait_tasks = @tasks.where(status: 'wait')\n @develop_tasks = @tasks.where(status: 'develop')\n @test_tasks = @tasks.where(status: 'test')\n @completed_tasks = @tasks.where(status: 'completed')\n @collaborators = @project.collaborators\n end",
"def statistics_task_by_storage_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_storage ...'\n end\n # resource path\n local_var_path = '/statistics/task_by_storage'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskStorageFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_storage\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def statistics_task_by_status(opts = {})\n data, _status_code, _headers = statistics_task_by_status_with_http_info(opts)\n data\n end",
"def stats\n @log.debug(\"Controller: Stats Called\")\n res = {\n :producers => producer_stats,\n :consumers => consumer_stats,\n :tasks => task_stats\n }\n end",
"def execution_statistics\r\n params = {\r\n method: :get,\r\n url: '/project/execution-statistics',\r\n params: {\r\n prjUUID: @uuid\r\n }\r\n }\r\n @session.request(params).perform!\r\n end",
"def save\n\n # Creates an array of hashes containing data about each task\n tasks = JSON.parse(params[:task_list][\"other\"])[\"tasks\"]\n\n # Iterating through all the task hashes\n tasks.each do |task_params|\n\n # Look up the correct task from the database\n task = Task.find(task_params[\"id\"])\n\n # Update it with new data\n task.update!({\n name: task_params[\"name\"],\n start: Date.parse(task_params[\"start\"]),\n finish: Date.parse(task_params[\"end\"]),\n progress: task_params[\"progress\"].to_i\n })\n end\n end",
"def task_status\n @log.debug(\"Controller: Task Status Called\")\n res = {}\n @tasks.each do |key, value|\n res[key] = value.status\n end\n res\n end",
"def trips_stats \n @all = current_user.trip_requests.trips.count\n @completed = current_user.trip_requests.trips.completed.count\n @cancelled = current_user.trip_requests.trips.cancelled.count\n @pending = current_user.trip_requests.trips.pending.count\n @on_going = current_user.trip_requests.trips.on_going.count\n @active = current_user.trip_requests.trips.active.count\n @monthly_successful = current_user.trip_requests.completed.trips.group_by_month(:created_at, format: \"%b\", reverse:true).count\n @monthly_pending = current_user.trip_requests.pending.trips.group_by_month(:created_at, format: \"%b\", reverse:true).count\n @response = { all: @all, completed: @completed, cancelled: @cancelled, active: @active, monthly_pending:@monthly_pending, monthly_successful:@monthly_successful, pending: @pending, on_going: @on_going }\n json_response(@response)\n end",
"def task_summary(task_name)\n path = \"/projects/#{project.name}/instances/#{name}\"\n query = { instancesummary: true, taskname: task_name }\n client.get(path, query: query).parsed_response\n end",
"def new\n @task_stat = TaskStat.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @task_stat }\n end\n end",
"def stats\n stats = {\n :servers => {}, \n :results => 0, \n :taken_tasks => 0, \n :untaken_tasks => 0,\n :taken_master_tasks => 0,\n :taken_task_tasks => 0, \n :untaken_master_tasks => 0,\n :untaken_task_tasks => 0,\n :failed_tasks => 0,\n :untaken_future_tasks => 0,\n :time => Time.now.to_f,\n }\n\n stats[:untaken_future_tasks] = SkynetWorkerQueue.connection.select_value(%{\n SELECT count(id)\n FROM #{message_queue_table}\n WHERE expire_time > #{Time.now.to_i} and tasktype = 'task' and payload_type = 'master' \n })\n\n stat_rows = SkynetWorkerQueue.connection.select_all(%{\n SELECT tasktype, payload_type, iteration, count(id) as number_of_tasks, expire_time\n FROM #{message_queue_table} \n WHERE expire_time <= #{Time.now.to_i} \n GROUP BY tasktype, payload_type, iteration \n }) \n stat_rows.each do |row|\n if row[\"tasktype\"] == \"result\" or row[\"payload_type\"] == \"result\"\n stats[:results] += row[\"number_of_tasks\"].to_i\n elsif row[\"tasktype\"] == \"task\" \n type_of_tasks = nil\n if row[\"payload_type\"] == \"master\"\n type_of_tasks = :master_tasks\n elsif row[\"payload_type\"] == \"task\"\n type_of_tasks = :task_tasks\n end\n if row[\"iteration\"].to_i == 0\n stats[\"untaken_#{type_of_tasks}\".to_sym] += row[\"number_of_tasks\"].to_i \n stats[:untaken_tasks] += row[\"number_of_tasks\"].to_i\n elsif row[\"expire_time\"].to_i < Time.now.to_i\n stats[:failed_tasks] += row[\"number_of_tasks\"].to_i \n else\n stats[\"taken_#{type_of_tasks}\".to_sym] += row[\"number_of_tasks\"].to_i \n stats[:taken_tasks] += row[\"number_of_tasks\"].to_i\n end\n end\n end\n\n stats[:time] = Time.now.to_f - stats[:time]\n stats\n end",
"def stats\n get 'stats', format: 'json'\n end",
"def create\n @task_metric = TaskMetric.new(params[:task_metric])\n\n respond_to do |format|\n if @task_metric.save\n format.html { redirect_to @task_metric, :notice => 'Task metric was successfully created.' }\n format.json { render :json => @task_metric, :status => :created, :location => @task_metric }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @task_metric.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def staff_post_task\n staff = params[:user_id].present? ? User.where(:id => params[:user_id]).first : current_user\n tasks = staff.tasks.map{|t| {\n id: t.id, \n title: t.event, \n start_year: get_year(t.start_date),\n start_month: get_month(t.start_date) - 1,\n start_day: get_day(t.start_date),\n start_hour: get_hour(t.start_date),\n start_minute: get_minute(t.start_date),\n end_year: get_year(t.end_date),\n end_month: get_month(t.end_date) - 1,\n end_day: get_day(t.end_date),\n end_hour: get_hour(t.end_date),\n end_minute: get_minute(t.end_date)\n }}\n render json: tasks.to_json\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PUT /task_stats/1 PUT /task_stats/1.json
|
def update
@task_stat = TaskStat.find(params[:id])
respond_to do |format|
if @task_stat.update_attributes(params[:task_stat])
format.html { redirect_to @task_stat, notice: 'Task stat was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @task_stat.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n if @task.update(task_param)\n render json: get_task_hash(@task)\n else\n render json: @task.errors.full_messages\n end\n end",
"def update\n @task_metric = TaskMetric.find(params[:id])\n\n respond_to do |format|\n if @task_metric.update_attributes(params[:task_metric])\n format.html { redirect_to @task_metric, :notice => 'Task metric was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @task_metric.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def save\n\n # Creates an array of hashes containing data about each task\n tasks = JSON.parse(params[:task_list][\"other\"])[\"tasks\"]\n\n # Iterating through all the task hashes\n tasks.each do |task_params|\n\n # Look up the correct task from the database\n task = Task.find(task_params[\"id\"])\n\n # Update it with new data\n task.update!({\n name: task_params[\"name\"],\n start: Date.parse(task_params[\"start\"]),\n finish: Date.parse(task_params[\"end\"]),\n progress: task_params[\"progress\"].to_i\n })\n end\n end",
"def update\n @progress = @task.progresses.find(params[:id])\n\n respond_to do |format|\n if @progress.update_attributes(params[:progress])\n format.html { redirect_to task_progress_path(@task, @progress), notice: 'Progress was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @progress.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @jmeter_task.update(jmeter_task_params)\n format.html { redirect_to @jmeter_task, notice: 'Jmeter task was successfully updated.' }\n format.json { render :show, status: :ok, location: @jmeter_task }\n else\n format.html { render :edit }\n format.json { render json: @jmeter_task.errors, status: :unprocessable_entity }\n end\n end\n end",
"def statistics_task_by_status_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_status ...'\n end\n # resource path\n local_var_path = '/statistics/task_by_status'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskStatusFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_status\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def update\n respond_to do |format|\n if @api_v1_task.update(api_v1_task_params)\n format.html { redirect_to @api_v1_task, notice: 'Task was successfully updated.' }\n format.json { render :show, status: :ok, location: @api_v1_task }\n else\n format.html { render :edit }\n format.json { render json: @api_v1_task.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(options: {}, **data)\n\n refresh_with(parse(client.put(\"/tasks/#{gid}\", body: data, options: options)).first)\n end",
"def perform(project_id, statistics = [])\n project = Project.find_by(id: project_id)\n\n Projects::UpdateStatisticsService.new(project, nil, statistics: statistics).execute\n end",
"def destroy\n @task_stat = TaskStat.find(params[:id])\n @task_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to task_stats_url }\n format.json { head :no_content }\n end\n end",
"def create\n @task_stat = TaskStat.new(params[:task_stat])\n\n respond_to do |format|\n if @task_stat.save\n format.html { redirect_to @task_stat, notice: 'Task stat was successfully created.' }\n format.json { render json: @task_stat, status: :created, location: @task_stat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @task_stat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_statistics\n HTTP.post(\"/video/#{@id}/stats\")\n true\n end",
"def update \n\t logger.debug \"Params --------------------------------------- #{params}\"\n\n\t logger.debug \"task params --------------------------------------#{task_params}\"\n\t format_task_attributes(task_params)\n\t \n\t logger.debug \"-------------------------------------------------------------\"\n\t logger.debug \"Updated Params #{@updated_params}\"\n\t @updated_params[:id]=params[:id]\n\t @task = Task.find(@updated_params[:id])\n\t logger.debug \"#########################\"\n\t logger.debug \"Task found \"\n\t \n\t @task.assign_attributes(@updated_params)\n\t authorize! :update, @task\n\t @task.is_completed=false\n\t save_task\n\tend",
"def statistics_task_by_metadata_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: StatisticsApi.statistics_task_by_metadata ...'\n end\n allowable_values = [\"count\", \"tasks_count\", \"to_process_size_sum\", \"processed_size_sum\", \"to_process_files_sum\", \"processed_files_sum\", \"finalized_files_sum\", \"bandwidth_avg\", \"bandwidth_count\"]\n if @api_client.config.client_side_validation && opts[:'sort'] && !allowable_values.include?(opts[:'sort'])\n fail ArgumentError, \"invalid value for \\\"sort\\\", must be one of #{allowable_values}\"\n end\n # resource path\n local_var_path = '/statistics/task_by_metadata'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'q'] = opts[:'q'] if !opts[:'q'].nil?\n query_params[:'fq'] = @api_client.build_collection_param(opts[:'fq'], :pipe) if !opts[:'fq'].nil?\n query_params[:'sort'] = opts[:'sort'] if !opts[:'sort'].nil?\n query_params[:'limit'] = opts[:'limit'] if !opts[:'limit'].nil?\n\n # header parameters\n header_params = opts[: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 = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'ByTaskMetadataFacet' \n\n # auth_names\n auth_names = opts[:auth_names] || ['BasicAuth', 'BearerAuth']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: StatisticsApi#statistics_task_by_metadata\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def update(task_number, task)\n\t\t@all_tasks[task_number-1] = task\n\tend",
"def update\n @stat = Stat.find(params[:id])\n\n if @stat.update(stat_params)\n head :no_content\n else\n render json: @stat.errors, status: :unprocessable_entity\n end\n end",
"def update\n # raise params.to_yaml\n @task = Task.find(params[:id])\n \n respond_to do |format|\n if @task.update_attributes(params[:task])\n flash[:notice] = 'Task was successfully updated.'\n format.html { redirect_to(@task) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @task.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @task_status.update(task_status_params)\n format.html { redirect_to task_status_url(@task_status), notice: \"Task status was successfully updated.\" }\n format.json { render :show, status: :ok, location: @task_status }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @task_status.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @task_entry.update(task_entry_params)\n format.json { head :no_content }\n else\n format.json { render json: @task_entry.errors, status: :unprocessable_entity }\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /task_stats/1 DELETE /task_stats/1.json
|
def destroy
@task_stat = TaskStat.find(params[:id])
@task_stat.destroy
respond_to do |format|
format.html { redirect_to task_stats_url }
format.json { head :no_content }
end
end
|
[
"def destroy\n @task_metric = TaskMetric.find(params[:id])\n @task_metric.destroy\n\n respond_to do |format|\n format.html { redirect_to task_metrics_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @system_task_statu = SystemTaskStatu.find(params[:id])\n @system_task_statu.destroy\n\n respond_to do |format|\n format.html { redirect_to system_task_status_url }\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @status_task = StatusTask.find(params[:id])\r\n @status_task.destroy\r\n\r\n respond_to do |format|\r\n format.html { redirect_to status_tasks_url }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @jmeter_task.destroy\n respond_to do |format|\n format.html { redirect_to jmeter_tasks_url, notice: 'Jmeter task was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @progress = @task.progresses.find(params[:id])\n @progress.destroy\n\n respond_to do |format|\n format.html { redirect_to task_progresses_url(@task) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @task_entry.destroy\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @file_stat = FileStat.find(params[:id])\n @file_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to file_stats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @task1 = Task1.find(params[:id])\n @task1.destroy\n\n respond_to do |format|\n format.html { redirect_to task1s_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @api_v1_task.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_tasks_url, notice: 'Task was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @visit_stat = VisitStat.find(params[:id])\n @visit_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to(scaffold_visit_stats_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @analysis_task = AnalysisTask.find(params[:id])\n @analysis_task.destroy\n\n respond_to do |format|\n format.html { redirect_to analysis_tasks_url }\n format.json { head :no_content }\n end\n end",
"def delete_task id\n request :delete, \"tasks/#{id}\"\n nil\n end",
"def destroy\n @task_status = TaskStatus.find(params[:id])\n @task_status.destroy\n\n respond_to do |format|\n format.html { redirect_to(task_statuses_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to stats_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @stat = Stat.find(params[:id])\n @stat.destroy\n\n respond_to do |format|\n format.html { redirect_to stats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @task_time = @task.task_times.find(params[:id])\n @task_time.destroy\n\n respond_to do |format|\n format.html { redirect_to task_times_url(@task) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @api_task.destroy\n end",
"def destroy\n @active_stat = ActiveStat.find(params[:id])\n @active_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to active_stats_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @email_stat = EmailStat.find(params[:id])\n @email_stat.destroy\n\n respond_to do |format|\n format.html { redirect_to email_stats_url }\n format.json { head :ok }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
initialize the 'verse with empty hash to add planets to
|
def initialize(verse)
@the_verse = verse
@planets = {}
end
|
[
"def initialize(h = {})\n @vector = Hash.new(0)\n @vector = @vector.merge!(h)\n end",
"def initialize(market_hash)\n @id = market_hash[:id]\n @name = market_hash[:name]\n @address = market_hash[:address]\n @city = market_hash[:city]\n @county = market_hash[:county]\n @state = market_hash[:state]\n @zip = market_hash[:zip]\n end",
"def add_planets(planet_hash)\n planet_hash.each do |planet, planet_info|\n @planets[planet] = planet_info\n end\n end",
"def initialize(solar_system_hash)\n @name = solar_system_hash[:name]\n @age = solar_system_hash[:age]\n @planets = {}\n end",
"def initialize()\r\n\t\t@available_set_list = Hash.new\r\n\tend",
"def initialize\n @vertices = {}\n end",
"def initialize(num_seeds = 6)\n @stores = Array.new(NUM_HOUSES * 2 + 2, num_seeds)\n @stores[STORE_INDEX_P1] = 0\n @stores[STORE_INDEX_P2] = 0\n @history = Array.new\n @current_player = :P1\n @num_seeds = num_seeds\n end",
"def initialize(hash=nil)\n @store = Storage.new( symbol_hash(hash || {}) )\n @inner_hash = @store.octothorpe_store\n end",
"def initialize(hero_hash) \n\t\tsuper\n\t\t@builds = []\n\t\t@abilities = []\n\tend",
"def initialize\n\t\t@portfolio = Hash.new\n\tend",
"def initialize()\n super() do |h,from_vertex|\n DirectedGraph::new_lower_hash(h,from_vertex)\n end\n end",
"def initialize\n # Create a hash table to hold the symbol table, each key will be the hash of an object\n # each value will be the object(s) tbat hashed to that index\n @symbol_table = Hash.new {|h,k| h[k] = []}\n end",
"def initialize\n @balances = Hash.new\n end",
"def init_stage_caches\n @best_edge = rantwijk_array(nil)\n @blossom_best_edges.fill(nil, @nvertex)\n @tight_edge = Array.new(@edges.length, false)\n end",
"def initialize\n @@shelf_iterator += 1\n @shelf_number = @@shelf_iterator\n\n # Letters equal slots in the shelf, each shelf has space for 5 books.\n @shelf_hash = {\n a: 'empty',\n b: 'empty',\n c: 'empty',\n d: 'empty',\n e: 'empty'\n }\n end",
"def initialize(hash={})\n super(hash||{})\n @next = {}\n end",
"def new_hash\n\t{}\nend",
"def initialize(planet_hash)\n @name = planet_hash[:name]\n @moons = planet_hash[:moons]\n @rings = planet_hash[:rings]\n @diameter = planet_hash[:diameter]\n @species = planet_hash[:species]\n # Give each planet a rate of solar rotation\n @solar_rotation = planet_hash[:solar_rotation]\n # Give each planet a @distance_from_the_sun attribute\n @distance_from_sun = planet_hash[:distance_from_sun]\n end",
"def initialize()\n\t\tsuper(:adventure, :none)\n\t\t@adventureInfo= Levels.new\n\t\t@overAllStarsHash={}\n\t\t@overAllStars = 0\n\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
method to add new planets to the hash, adding name as key
|
def new_planet(planet)
@planets[planet.name] = planet
end
|
[
"def add_planets(planet_hash)\n planet_hash.each do |planet, planet_info|\n @planets[planet] = planet_info\n end\n end",
"def add_one_planet(planet, planet_info)\n @planets[planet] = planet_info\n end",
"def add new_planet\n @planets << new_planet\n end",
"def add_planet (planet)\n @planets << planet\n end",
"def add_planets(planets)\n planets.each do |planet|\n @planets.push(planet)\n end\n end",
"def add_new_planet(new_planet)\n @planets.push(new_planet) if !has_planet?(new_planet.name)\n end",
"def add_planet_by_name(name)\n planet = get_space_body_by_name(name)[0]\n Planet.new(planet)\n end",
"def add_planet(new_planet)\n add_new_planet(new_planet) if new_planet.class == Planet\n end",
"def add_planets(planet_list)\n @planets += planet_list\n end",
"def mash_planets(planets)\n Planet.new(\n 'id' => planets.map(&:id).join(\"\\n\"),\n 'type' => planets.map(&:type).join(\"\\n\"),\n 'name' => planets.map(&:name).join(\"\\n\")\n )\n end",
"def add_new_season_and_holiday_with_supplies(holiday_hash, season, holiday_name, supply_array)\n holiday_hash[season] = {holiday_name => supply_array} # the new echelon being created is to the left of the equals sign.\n holiday_hash\nend",
"def add_planet(planet)\n planet_names = @planets.map { |p| p.name.downcase }\n if (planet_names.include?(planet.name.downcase))\n raise ArgumentError.new(\"This planet already exists in the solar system\")\n end\n @planets << planet\n end",
"def add_new_planet(planet)\n @solar_system << planet\n end",
"def planet_add(planet)\n @planets.push(planet)\n return @planets\n end",
"def update_planet match, state\n # Make attributes hash based on match size (4 possible constructors\n hash = case match.size\n when 13 # Your Planet/ * Planet\n prod_name = match[8]\n prod_key = state[:race] ? state[:race].name + '.' + prod_name : nil \n product = Product.lookup(prod_name)\n product ||= Product.lookup(prod_key) if prod_key \n product.planets << self if product\n {:num=>match[0].to_i, :x=>match[1].to_f, :y=>match[2].to_f, :name=>match[3], :size=>match[4].to_f, \n :pop=>match[5].to_f, :ind=>match[6].to_f, :res=>match[7].to_f, :cap=>match[9].to_f, \n :mat=>match[10].to_f, :col=>match[11].to_f, :l=>match[12].to_f}\n \n when 8 # Uninhabited Planet\n {:num=>match[0].to_i, :x=>match[1].to_f, :y=>match[2].to_f, :name=>match[3], :size=>match[4].to_f, \n :res=>match[5].to_f, :cap=>match[6].to_f, :mat=>match[7].to_f}\n \n when 6 # Ships In Production\n total_mass = match[3].to_f / 10 # Mass values given in \"Material units\", divide by 10\n produced_mass = match[4].to_f / 10\n percentage = produced_mass/total_mass # Calculate ship production progress\n {:progress=>percentage}\n \n when 3 # Unidentified Planet\n {:num=>match[0].to_i, :x=>match[1].to_f, :y=>match[2].to_f}\n \n when 2 # Battle/Bombing generated Planet (known num and name)\n if state[:section] = 'Battle_planets'\n self.battles = state[:battles] = self.battles ? self.battles + 1 : 1 \n state[:planet] = self\n end\n {:num=>match[0].to_i, :name=>match[1]}\n \n when 1 # Route/Fleet/Bombing generated Planet (given EITHER #num or name)\n match[0][0,1] == '#' ? \n {:num=>match[0][1..-1].to_s} : \n {:name=>match[0]}\n \n when 0 # All init data given in a state hash\n state \n else {}\n end \n # Set all the attributes given in hash \n hash.each do |key, value| \n setter = key.to_s.concat('=').to_sym\n if self.respond_to? setter then self.send setter, value else raise ArgumentError end\n end\n state[:race].planets << self if state[:race]\n num ? add(numkey) : add if self.class.dataset # Add instantiated/updated model to dataset if dataset established\n @created_by = state[:created_by]\n self\n end",
"def add_planet_list (planet_list)\n @planets += planet_list\n end",
"def add_planets(new_planet_array)\n @planets.concat(new_planet_array)\n end",
"def add_initial_planets(solar_system)\n earth = Planet.new('Earth', 'blue-green', 5.972e24, 1.496e16, 'Only planet known to support life')\n cyborg = Planet.new('Cyborg', 'neon green', 10.993e24, 2.496e90, 'Humans have not yet discovered this planet' )\n mars = Planet.new('Mars', 'red', 9.972e24, 2.496e16, 'This planet was named after the Roman god of war')\n solar_system.add_planet(earth)\n solar_system.add_planet(cyborg)\n solar_system.add_planet(mars)\nend",
"def new\n \t@planets = Planet.create\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Register one or more Interceptors which will be called before SMS is sent.
|
def register_interceptors(*interceptors)
interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }
end
|
[
"def register_interceptors(*interceptors); end",
"def register_interceptors(*interceptors)\n interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }\n end",
"def unregister_interceptors(*interceptors); end",
"def register_interceptor(interceptor)\r\n delivery_interceptor = case interceptor\r\n when String, Symbol\r\n interceptor.to_s.camelize.constantize\r\n else\r\n interceptor\r\n end\r\n\r\n Sms.register_interceptor(delivery_interceptor)\r\n end",
"def prepend_before_invocation(*interceptors, &block)\n conditions = extract_conditions!(interceptors)\n interceptors << block if block_given?\n add_interception_conditions(interceptors, conditions)\n prepend_interceptors_to_chain(\"before\", interceptors)\n end",
"def register_actors!\n self.class.actors.each { |actor| register_actor(actor) }\n end",
"def prepend_after_invocation(*interceptors, &block)\n conditions = extract_conditions!(interceptors)\n interceptors << block if block_given?\n add_interception_conditions(interceptors, conditions)\n prepend_interceptors_to_chain(\"after\", interceptors)\n end",
"def register_interceptor(interceptor)\n Mail.register_interceptor(observer_class_for(interceptor))\n end",
"def register_preview_interceptors(*interceptors)\n interceptors.flatten.compact.each { |interceptor| register_preview_interceptor(interceptor) }\n end",
"def use_middleware(*middlewares)\n Emittance::Middleware.register middlewares\n end",
"def register( *objects )\n objects.each do |object|\n append_hook( :owner => object, \n :trigger => YesTrigger.new, \n :action => MethodAction.new(:handle) )\n end\n end",
"def finalize_interceptions\n @intercept_handlers.each(&:call)\n case intercept_resolution_state.action\n when 'abort'\n abort_impl(**@abort_error_reason)\n when 'respond'\n respond_impl(**@response_for_request)\n when 'continue'\n continue_impl(@continue_request_overrides)\n end\n end",
"def register( *objects )\n objects.each do |object|\n append_hook( :owner => object,\n :trigger => YesTrigger.new,\n :action => MethodAction.new(:handle) )\n end\n end",
"def called!(interactor)\n _called << interactor\n end",
"def register_preview_interceptors(*interceptors); end",
"def set_request_interception(patterns:)\n {\n method: \"Network.setRequestInterception\",\n params: { patterns: patterns }.compact\n }\n end",
"def register_interceptor(interceptor)\n delivery_interceptor = (interceptor.is_a?(String) ? interceptor.constantize : interceptor)\n Mail.register_interceptor(delivery_interceptor)\n end",
"def list_interceptors\n @interceptors.list\n end",
"def add_to_instances\n # Store only those interceptions that are not marked to be used for existing methods only\n return if options[:existing_methods_only]\n\n interceptions_storage = context.instance_variable_get(:@interceptions_storage)\n unless interceptions_storage\n interceptions_storage = InterceptionsStorage.new\n context.instance_variable_set(:@interceptions_storage, interceptions_storage)\n end\n interceptions_storage << self\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Register an Observer which will be notified when SMS is delivered. Either a class, string or symbol can be passed in as the Observer. If a string or symbol is passed in it will be camelized and constantized.
|
def register_observer(observer)
delivery_observer = case observer
when String, Symbol
observer.to_s.camelize.constantize
else
observer
end
Sms.register_observer(delivery_observer)
end
|
[
"def register_observer(observer)\n delivery_observer = (observer.is_a?(String) ? observer.constantize : observer)\n Mail.register_observer(delivery_observer)\n end",
"def register_observer(observer)\n Mail.register_observer(observer_class_for(observer))\n end",
"def register_observer(observer, cmd_name=nil)\n codes= []\n if cmd_name\n codes << Protocol.find_cmd_by_name(cmd_name).code\n else\n codes+= CMDS_BY_CODE.keys\n end\n codes.each {|code|\n list= @observers[code]\n if list.nil?\n @observers[code]= list= []\n end\n list.push(observer)\n }\n end",
"def register_observer(observer_class)\n self.observer_classes ||= []\n self.observer_classes.push observer_class\n end",
"def register_observer_class(observer_class)\n @observer_mutex.synchronize do\n return if @observed_models.include?(observer_class)\n @observed_models << observer_class\n log \"EventListener: registering observer class #{observer_class}\"\n observer_queue.bind(models_exchange, routing_key: \"#{Isimud.model_watcher_schema}.#{observer_class.base_class.name}.*\")\n end\n end",
"def add_observer(observer=nil, &block)\n raise ArgumentError, \"Must provide a block or an object to receive messages.\" unless observer || block\n observer = assert_observer(observer)\n observers[observer] = block_given? ? block : observer\n observer\n end",
"def subscribe(observer)\n @list_of_observers << observer\n end",
"def register_interceptor(interceptor)\r\n delivery_interceptor = case interceptor\r\n when String, Symbol\r\n interceptor.to_s.camelize.constantize\r\n else\r\n interceptor\r\n end\r\n\r\n Sms.register_interceptor(delivery_interceptor)\r\n end",
"def add_observer object, func = :update\n unless ::DRb.thread && ::DRb.thread.alive?\n ::DRb.start_service\n end\n\n proxy = Proxy.new object, func\n @subscribers[object] = proxy\n @bus.watch channel, proxy\n end",
"def add_observer(name, obs)\n @observ_list[name] = obs\n end",
"def add_observer(*args, &block)\n return super unless block_given?\n observer = Observer.new(&block)\n add_observer(observer)\n observer\n end",
"def register_observer(notification_name, observer)\n observers = @observer_map[notification_name]\n if observers.nil?\n @observer_map[notification_name] = observer\n else\n observers = Array(@observer_map[notification_name])\n observers << observer\n @observer_map[notification_name] = observers\n end\n end",
"def add_observer (observer, callback = nil, &block)\n @observers ||= {}\n @observers[observer] = callback || block\n observer\n end",
"def add_observer(observer) \n unless observer.respond_to? :update\n raise NoMethodError, \"observer, #{observer}, needs to respond to #update\" \n end\n LOG.debug \"#{self} is attempting to add an observer, #{observer}.\"\n @observers << observer\n LOG.debug \"#{observer} is now listening for events on #{self}.\"\n end",
"def register_interceptor(interceptor)\n Mail.register_interceptor(observer_class_for(interceptor))\n end",
"def register_interceptor(interceptor)\n delivery_interceptor = (interceptor.is_a?(String) ? interceptor.constantize : interceptor)\n Mail.register_interceptor(delivery_interceptor)\n end",
"def add_observer(observer)\n @observers << observer\n puts \"#{observer.name} is now watching #{self.name}\"\n end",
"def add_observer(&block)\n super(Observer.new(block))\n end",
"def add(*observer)\n if observer.respond_to?(:each)\n @observers = observer.each\n else\n @observers << observer\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Register an Interceptor which will be called before SMS is sent. Either a class, string or symbol can be passed in as the Interceptor. If a string or symbol is passed in it will be camelized and constantized.
|
def register_interceptor(interceptor)
delivery_interceptor = case interceptor
when String, Symbol
interceptor.to_s.camelize.constantize
else
interceptor
end
Sms.register_interceptor(delivery_interceptor)
end
|
[
"def register_interceptor(interceptor)\n delivery_interceptor = (interceptor.is_a?(String) ? interceptor.constantize : interceptor)\n Mail.register_interceptor(delivery_interceptor)\n end",
"def register_interceptor(interceptor)\n Mail.register_interceptor(observer_class_for(interceptor))\n end",
"def register_interceptors(*interceptors); end",
"def insert_interceptor_before(before_class, interceptor_class, opts = {})\n raise ServerAlreadyStartedError if @started\n\n @interceptors.insert_before(before_class, interceptor_class, opts)\n end",
"def add_interceptor\n if block_given?\n return ::Vertx::Util::Utils.safe_create(@j_del.java_method(:addInterceptor, [Java::IoVertxCore::Handler.java_class]).call((Proc.new { |event| yield(::Vertx::Util::Utils.safe_create(event,::Vertx::SendContext)) })),::Vertx::EventBus)\n end\n raise ArgumentError, \"Invalid arguments when calling add_interceptor()\"\n end",
"def use(interceptor_class, options = {})\n interceptors_mutex do\n @registry << {\n klass: interceptor_class,\n options: options\n }\n end\n end",
"def register_interceptors(*interceptors)\n interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }\n end",
"def register_interceptors(*interceptors)\r\n interceptors.flatten.compact.each { |interceptor| register_interceptor(interceptor) }\r\n end",
"def register_observer(observer)\r\n delivery_observer = case observer\r\n when String, Symbol\r\n observer.to_s.camelize.constantize\r\n else\r\n observer\r\n end\r\n\r\n Sms.register_observer(delivery_observer)\r\n end",
"def register_middleware(**mappings); end",
"def before_intercept(&block)\n @before_intercept = block if block_given?\n \n @before_intercept\n end",
"def register(processor)\n self.pre_processors += [processor]\n end",
"def intercept(intercepted_class)\n result = Interception.new(intercepted_class)\n @flexmock_interceptors ||= []\n @flexmock_interceptors << result\n result\n end",
"def prepend_before_invocation(*interceptors, &block)\n conditions = extract_conditions!(interceptors)\n interceptors << block if block_given?\n add_interception_conditions(interceptors, conditions)\n prepend_interceptors_to_chain(\"before\", interceptors)\n end",
"def register(klass)\n @processors << klass\n end",
"def register_preview_interceptor(interceptor)\n preview_interceptor = interceptor_class_for(interceptor)\n\n unless preview_interceptors.include?(preview_interceptor)\n preview_interceptors << preview_interceptor\n end\n end",
"def unregister_interceptor(interceptor); end",
"def mole_before(opts={}, &interceptor) \n raise \"Missing :feature option\" if opts[:feature].nil? or opts[:feature].to_s.empty?\n opts[:interceptor] ||= interceptor\n opts[:method] ||= :call\n feature = opts[:feature].to_s\n if before_mole_filters[feature].empty?\n wrap feature \n before_mole_filters[feature] << [opts[:interceptor], opts[:method]]\n end\n end",
"def register(cb_sym, meth, klass)\n self[klass.to_s.make_key][cb_sym] << meth\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns the name of current carrier. If this is an anonymous carrier, this method will return +anonymous+ instead.
|
def carrier_name
@carrier_name ||= anonymous? ? "anonymous" : name.underscore
end
|
[
"def carrier_name\r\n self.class.carrier_name\r\n end",
"def carrier_name\n carrier.name unless carrier.blank?\n end",
"def carrier_code\n @raw_data[:CarrierCode]\n end",
"def get_carrier\n return self.sendcmd(\"modem.get_carrier\")\n end",
"def carrier=(carrier)\n @carrier = carrier&.to_sym\n end",
"def carrierName(number)\n\t\twebpage = \"http://www.whitepages.com/phone/#{number}\"\n\n\t\t# Get a Nokogiri::HTML::Document for the page we're interested in...\n\t\thtml_doc = Nokogiri::HTML(open(webpage))\n\n\t\tcarrier_name = String.new\n\t\t# Look for the 'description' class because this contains the carrier name\n\t\thtml_doc.xpath('//span[@class=\"description\"]').each do |method_span|\n\t\t\tcarrier_name = method_span.content\n\t\tend\n\n\t\t# Convert to lowercase to make it easier to determine the carrier\n\t\tcarrier_name = carrier_name.downcase\n\n\t\t# Split string into arrays by word to make it easier to determine the carrier\n\t\tcarrier_name_word_array = carrier_name.split(' ')\n\n\t\t# The carrier name is the first element of the array\n\t\treturn carrier_name_word_array[0]\n\tend",
"def carrier_named(str)\n format(str, @carrier)\n end",
"def carrier=(carrier)\n @carrier = carrier && carrier.to_sym\n end",
"def carrier_code\n @raw_data[:AirCarrierCode]\n end",
"def subscriber_carrier\n return @subscriber_carrier\n end",
"def carrier_named(str)\n format(str, carrier)\n end",
"def af_name\n return self.class.name\n end",
"def carrier_by_value(carrier)\n phone_carrier = case carrier.class.to_s\n when 'Symbol', 'String' then find_by_name(carrier)\n when \"#{self.class.to_s}\" then carrier\n when 'Fixnum' then find_by_id(carrier)\n else nil\n end\n end",
"def carrier\r\n CarrierController.instance\r\n end",
"def federation_brand_name\n return @federation_brand_name\n end",
"def carrier_ip\n data[:carrier_ip]\n end",
"def sender_number\n if self.respond_to? :carrier\n return self[:number]\n else \n return self[:from]\n end\n end",
"def receiver_name\n\t\tif self.receiver_type == \"User\"\n\t\t\tself.receiver.full_name\n\t\telse\n\t\t\tself.receiver.name\n\t\tend\n\tend",
"def country_name\n cc = carmen_country\n\n cc ? \"#{cc.name}\" : ''\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Wraps an SMS delivery inside of ActiveSupport::Notifications instrumentation. This method is actually called by the Sms object itself through a callback when you call :deliver on the Sms, calling +deliver_sms+ directly and passing a Sms will do nothing except tell the logger you sent the SMS.
|
def deliver_sms(sms) #:nodoc:
ActiveSupport::Notifications.instrument("deliver.sms_carrier") do |payload|
set_payload_for_sms(payload, sms)
yield # Let Sms do the delivery actions
end
end
|
[
"def deliver\n #inform_interceptors\n if delivery_handler\n delivery_handler.deliver_sms(self) { do_delivery }\n else\n do_delivery\n end\n inform_observers\n self\n end",
"def deliver(sms)\n new.deliver!(sms)\n end",
"def deliver_sms(options={})\n#puts \"**** Message#deliver_sms; options=#{options}\"\n sms_gateway = options[:sms_gateway] || SmsGateway.default_sms_gateway\n @phones ||= options[:phone_numbers] || sent_messages.map {|sm| sm.phone}.compact.uniq\n @phones = @phones.split(',') if @phones.is_a? String \n if @phones.empty?\n AppLog.create(:code => 'Message.deliver_sms', :severity=> 'warning', \n :description => \"Attempting to send SMS for message ##{self.id} but no phone numbers found\")\n return\n end\n assemble_sms()\n#puts \"**** sms_gateway.deliver #{sms_gateway} w #{phone_numbers}: #{sms_only}\"\n #******* CONNECT TO GATEWAY AND DELIVER MESSAGES \n gateway_reply = sms_gateway.deliver(@phones, sms_only, self.id)\n#puts \"**** sms_gateway=#{sms_gateway}\"\n#puts \"**** gateway_reply=#{gateway_reply}\"\n #******* PROCESS GATEWAY REPLY (INITIAL STATUSES OF SENT MESSAGES) \n update_sent_messages_w_status(gateway_reply) if options[:news_update].nil? && gateway_reply # The IF is there just to make testing simpler.\n # In production, a reply will always be present?\n end",
"def deliver\n Outbound.deliver(delivery_options.merge(:conditions => ['sms_service_provider_id = ?', self.provider_id]))\n end",
"def notify_sms (c, order)\r\n\r\n # notify only if not already done! \r\n unless already_notified order\r\n #dump_order = MultiJson.dump order, :pretty => true\r\n \r\n # log order data\r\n @logger.info \"NEW ORDER: #{order[\"order_id\"]} (num products: #{order[\"num_products\"]}, \\\r\nprice: #{order[\"price\"]} #{order[\"currency_code\"]}, current state: #{order[\"current_state\"]})\" \r\n\r\n # format SMS text with order details \r\n message = compose_sms_with_order_details c, order\r\n\r\n # send SMS through Skuby API (interfacing Skebby Gateway)\r\n sms_sent = send_sms(message, @seller_cell_number, @logger) if @send_sms\r\n\r\n @logger.info \"SMS SENT:\\n#{message}\" # if sms_sent #logger.debug\r\n \r\n # if SMS TX is disable, mark as notified anyway (debug)\r\n set_notified! order if (sms_sent || !@send_sms)\r\n\r\n # return status (success/error)\r\n sms_sent\r\n else\r\n true\r\n end\r\nend",
"def deliver sms\n response = nexmo.send_message(\n from: sms.from,\n to: sms.to,\n text: sms.text\n )\n\n # If sending the SMS was a success then store\n # the message ID on the SMS record\n if response['messages'].first['status'] == '0'\n sms.update_attributes(\n message_id: response['messages'].first['message-id']\n )\n end\n end",
"def deliver(message, options = {})\n to = self.recipient.respond_to?(:call) ? self.recipient.call(message) : self.recipient\n ActionMailerSMSMailer.forward_sms(to, message).deliver\n end",
"def send_sms(msg)\n\t\t\ts = msg.recipient.phone_number\n\t\t\tt = msg.text\n\t\t\t\n\t\t\t# allow RubySMS to notify the router\n\t\t\t# this is a giant ugly temporary hack\n\t\t\tsuper\n\t\t\t\n\t\t\t# init the message log for\n\t\t\t# this session if necessary\n\t\t\t@msg_log[s] = []\\\n\t\t\t\tunless @msg_log.has_key?(s)\n\t\t\t\n\t\t\t# add the outgoing message to the log\n\t\t\tmsg_id = @msg_log[s].push\\\n\t\t\t\t[t.object_id.abs.to_s, \"out\", t]\n\t\tend",
"def send_sms(phone, text, _args = {})\n @logger.send(@severity, \"[SMS] #{phone}: #{text}\")\n respond_with_status :success\n end",
"def delivery_sms_messages!\n phone_numbers.each do |phone_number|\n InfobipService.send_message_to(phone_number, message, from)\n end\n end",
"def send_later\n @request << Voltron::SmsJob.set(default_options.merge(job_options)).send(job_method, self)\n after_deliver\n end",
"def deliver(message, options = {})\n options = options.reverse_merge default_options\n to = recipient.respond_to?(:call) ? recipient.call(message) : recipient\n message.body message.body.encode(options[:charset]) if options[:charset].presence\n ActionMailerSMSMailer.forward_sms(to, message, options.compact).deliver_now\n message.to\n end",
"def send_sms!\n msg = \"You have a new message in HereStay: #{mobile_booking_messages_url(self.booking_id, :host => ActionMailer::Base.default_url_options[:host])}\"\n if recipient\n recipient.deliver_message!(msg) if !recipient.online? and recipient.available_by_phone?\n end\n end",
"def send_sms\n Sms.new(self)\n end",
"def send_sms(sms, options={})\n send_to_phone(sms.phone_number, sms.actual_message, options)\n end",
"def deliver_now!\n processed_smser.handle_exceptions do\n message.deliver!\n end\n end",
"def deliver_message_via_carrier(text, to, from)\n SMS_CARRIER.deliver_message(text, to, from)\nend",
"def on_delivery_notification(&blk)\n @on_delivery_notification = blk\n end",
"def perform(mailer, options)\n mailer = mailer.constantize\n mailer.send('send_notification', options) if mailer.respond_to?('send_notification')\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns the name of the carrier object.
|
def carrier_name
self.class.carrier_name
end
|
[
"def carrier_name\n carrier.name unless carrier.blank?\n end",
"def carrier_name\r\n @carrier_name ||= anonymous? ? \"anonymous\" : name.underscore\r\n end",
"def getName()\n return @obj_name\n end",
"def carrier_named(str)\n format(str, @carrier)\n end",
"def object_name\n @factory.object_name.to_sym\n end",
"def celestial_object_name\n self.object_name\n end",
"def get_carrier\n return self.sendcmd(\"modem.get_carrier\")\n end",
"def carrier_code\n @raw_data[:CarrierCode]\n end",
"def af_name\n return self.class.name\n end",
"def name\n return nil unless model\n\n model.name\n end",
"def name\n @name || object_id.to_s\n end",
"def object_name\n return @object_name if @object_name\n if @options[:object_name]\n @object_name = @options[:object_name]\n elsif object.respond_to? :model_name\n @object_name = object.model_name.singular\n else\n @object_name = nil\n end\n @object_name\n end",
"def name\n puts(object.class.name)\n end",
"def carrier_named(str)\n format(str, carrier)\n end",
"def carrierName(number)\n\t\twebpage = \"http://www.whitepages.com/phone/#{number}\"\n\n\t\t# Get a Nokogiri::HTML::Document for the page we're interested in...\n\t\thtml_doc = Nokogiri::HTML(open(webpage))\n\n\t\tcarrier_name = String.new\n\t\t# Look for the 'description' class because this contains the carrier name\n\t\thtml_doc.xpath('//span[@class=\"description\"]').each do |method_span|\n\t\t\tcarrier_name = method_span.content\n\t\tend\n\n\t\t# Convert to lowercase to make it easier to determine the carrier\n\t\tcarrier_name = carrier_name.downcase\n\n\t\t# Split string into arrays by word to make it easier to determine the carrier\n\t\tcarrier_name_word_array = carrier_name.split(' ')\n\n\t\t# The carrier name is the first element of the array\n\t\treturn carrier_name_word_array[0]\n\tend",
"def carrier=(carrier)\n @carrier = carrier&.to_sym\n end",
"def carrier_by_value(carrier)\n phone_carrier = case carrier.class.to_s\n when 'Symbol', 'String' then find_by_name(carrier)\n when \"#{self.class.to_s}\" then carrier\n when 'Fixnum' then find_by_id(carrier)\n else nil\n end\n end",
"def object_name\n controller_name.singularize\n end",
"def getFamilyDetailsObjName\r\n\t\t\treturn \"mfiforce__Family_Details__c\"\r\n\t\tend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
The main method that creates the message and renders the SMS templates. There are two ways to call this method, with a block, or without a block. It accepts a headers hash. This hash allows you to specify the most used headers in an SMS message, these are: +:to+ Who the message is destined for, can be a string of addresses, or an array of addresses. +:from+ Who the message is from You can set default values for any of the above headers (except +:date+) by using the ::default class method: class Notifier Sms ready to call :deliver on to send. For example: class Notifier < SmsCarrier::Base
|
def sms(options = {})
return @_message if @_sms_was_called && options.blank?
m = @_message
# Call all the procs (if any)
default_values = {}
self.class.default.each do |k,v|
default_values[k] = v.is_a?(Proc) ? instance_eval(&v) : v
end
# Handle defaults
options = options.reverse_merge(default_values)
# Set configure delivery behavior
wrap_delivery_behavior!(options.delete(:delivery_method), options.delete(:delivery_method_options))
# Assign all options except body, template_name, and template_path
assignable = options.except(:body, :template_name, :template_path)
assignable.each { |k, v| m[k] = v }
# Render the templates and blocks
m.body = response(options)
@_sms_was_called = true
m
end
|
[
"def generate_message(&block)\n require 'net/smtp'\n require 'smtp_tls'\n require 'mail'\n mail = Mail.new(&block)\n mail.delivery_method(*smtp_settings)\n mail\n end",
"def makemsg\n # if this is a nagios template, use the ENV vars to build the template\n # else just use whatever message was passed to the object\n if @msgmode =~ /^nagios-(.+)/\n type = $1\n templatefile = \"#{Angelia::Util.config.templatedir}/#{recipient.protocol}-#{type}.erb\"\n Angelia::Util.debug(\"Creating message body based on template #{templatefile}\")\n\n # create a binding and inject the NAGIOS_* vars into it, we'll use the binding\n # later on in the template so the template has access to these variables without\n # needing to do @vars[HOSTNAME] for example, just HOSTNAME would work\n b = binding\n @vars.each do |k, v|\n eval(\"#{k} = @vars[\\\"#{k}\\\"]\", b)\n end\n\n\n if File.exists? templatefile\n template = File.readlines(templatefile).join\n renderer = ERB.new(template, 0, \"<>\")\n @message = renderer.result(b)\n else\n raise(Angelia::CorruptMessage, \"Cannot find template #{templatefile}\")\n end\n end\n end",
"def mail(headers = {}, &block)\n \n # Extra tracking data can be passed via :tracking_data in the headers\n tracking_data = headers.delete(:tracking_data) || {}\n \n # Store the mailer as the current class name underscored\n tracking_data[:mailer] ||= self.class.name.underscore\n \n # Store the action as the method that has called mail()\n # This can be overriden by passing :action as part of tracking_data\n tracking_data[:action] ||= caller[0][/`([^']*)'/, 1]\n \n tracking_data[:subject] ||= headers[:subject]\n \n # Call the original method and add the tracking_data\n message = mail_without_tracking(headers, &block)\n message.tracking_data = tracking_data\n message\n end",
"def message template\n message_template = ERB.new File.new($path_to_messages + \"/\"+ template ).read\n @body = message_template.result(binding)\n message = {:to => @contact,\n :subject => @subject, \n :body => @body}\n end",
"def create_message( template_name, template_id=nil, recipient=nil, zza_xdata=nil )\n\n # Load the appropriate template either the production version or the given id (for testing)\n if template_id\n @template = EmailTemplate.find( template_id )\n else\n @template = Email.find_by_name!( template_name ).production_template\n end\n\n #check subscription preferences\n Subscriptions.wants_email!( recipient, @template.email )\n\n #Process recipient ( decide if it is an address or a user, build address and clean the double bytes)\n if recipient.is_a?(User)\n encoded_name = Mail::Encodings::decode_encode( recipient.actual_name, :encode )\n if encoded_name.blank?\n @to_address = Mail::Address.new(\"#{recipient.email}\")\n else\n @to_address = Mail::Address.new(\"\\\"#{encoded_name}\\\" <#{recipient.email}>\")\n end\n else\n @to_address = Mail::Address.new( recipient.to_slug.to_ascii.to_s )\n end\n\n # Add unsubscribe links and headers see http://www.list-unsubscribe.com/\n @unsubscribe_url = unsubscribe_url( @unsubscribe_token = Subscriptions.unsubscribe_token( recipient ) )\n @unsubscribe_email = Mail::Address.new( \"#{@unsubscribe_token}@unsubscribe.#{Server::Application.config.album_email_host}\" ).address\n sendgrid_headers.merge!( @template.sendgrid_category )\n\n # add zzv_id to sendgrid header so that we can receive in\n # open, click, etc callbacks and forward on to mixpoanel\n # the params set here are collected again the the\n # sendgrid_controller#events action\n if recipient.is_a?(User)\n if !recipient.automatic?\n sendgrid_headers[:unique_args] = {\n :zzv_id => recipient.zzv_id,\n :user_id => recipient.id\n }\n else\n # don't set user_id in this case because not a real user yet\n sendgrid_headers[:unique_args] = {\n :zzv_id => ZzvIdManager.generate_zzv_id_for_email(recipient.email)\n }\n end\n else\n sendgrid_headers[:unique_args] = {\n :zzv_id => ZzvIdManager.generate_zzv_id_for_email(recipient)\n }\n end\n\n headers['X-SMTPAPI'] = sendgrid_headers.to_json #set sendgrid API headers\n headers['X-ZZSubscription-Id'] = @unsubscribe_token\n headers['List-Unsubscribe'] = \"<mailto:#{@unsubscribe_email}>,<#{@unsubscribe_url}>,\"\n\n #send zza event\n ZZA.new.track_event(\"#{template.category}.send\", zza_xdata )\n\n #add log entry\n log_entry = \"EMAIL_SENT === #{template_name} to #{@to_address}\"\n log_entry += \" Triggered by #{@user.username} (#{@user.id})\" if @user\n log_entry += \" About album #{@album.name} (#{@album.id})\" if @album\n log_entry += \" UploadBatch (#{@batch.id}) with #{@batch.photos.count} photos\" if @batch\n logger.info log_entry\n\n #create message\n mail( :to => @to_address.format,\n :from => @template.formatted_from,\n :reply_to => ERB.new( @template.formatted_reply_to).result( binding()),\n :subject => ERB.new( @template.subject).result(binding())\n ) do |format|\n format.text { render :inline => @template.text_content }\n format.html { render :inline => @template.html_content }\n end\n end",
"def create!(method_name, *parameters) #:nodoc:\n initialize_defaults(method_name)\n __send__(method_name, *parameters)\n\n unless @message === String\n template_exists ||= template_root[\"#{mailer_name}/#{@template}\"]\n @message = render_message(@template, @message) if template_exists\n end\n\n create_sms_message\n end",
"def generate_mail(template, context={})\n log.debug \"Constructing a mail message based on the '#{template}' template.\"\n factory = TemplateFactory.new(@directory.path, log)\n content = factory.manufacture(template, context)\n MailMessage.new({server: @server, via: @via}.merge(content))\n end",
"def generate_and_send(recipient_sms_numbers: nil)\n generate\n\n if email?\n NotificationMailer.send_message_notification(self, logger: logger).deliver_now\n elsif sms?\n sms = Messaging::NotificationSms.new\n sms.send_now(self, recipient_sms_numbers: recipient_sms_numbers, generated_text: generated_text,\n importance: importance, logger: logger)\n else\n raise FphsException, \"No recognized message type for message notification: #{message_type}\"\n end\n end",
"def send_message message_template\n # return if sequence in progress is false\n return {error: false,message: \"Message Sequence is stopped by user.\"} unless self.sequence_in_progress\n \n next_template = MessageTemplate.next_template(message_template)\n recipents = [self.phone]\n content = message_template.template\n response = Message.send_sms(recipents,content,self.restaurant,'text_ready')\n if next_template.present? and !response[:error]\n # schedule next message, if next template exists\n next_scheduled_time = Time.now + next_template.next_delay.to_i.minutes\n self.delay(run_at: next_scheduled_time).send_message(next_template)\n else\n self.broadcast_stop_sequence\n end\n response\n end",
"def instantiate(context = {})\n mail, args = self.dup, context.unsymbolize_keys\n mail.subject = mail.subject.wlang(args, dialect)\n mail.body = mail.body.wlang(args, dialect)\n mail.date = Time.now\n mail\n end",
"def build\n set_header(\"Mail-From\", \"#{ENV[\"USER\"]}@localhost ENVID=#{envelope_id}\")\n set_header(\"Date\", Time.now.rfc2822)\n set_header(\"Message-ID\", \"<#{Time.now.to_f}.#{Process.pid}@#{get_header(\"from\").to_s.split(\"@\", 2)[1]}>\")\n\n if multipart?\n set_header(\"Mime-Version\", \"1.0\")\n if attachments?\n set_header(\"Content-Type\", \"multipart/mixed; boundary=\\\"#{attachment_boundary}\\\"\")\n else\n set_header(\"Content-Type\", \"multipart/alternative; boundary=\\\"#{body_boundary}\\\"\")\n end\n end\n\n build_headers + build_body\n end",
"def send_template_to(params)\n user = User.find(params['user_id'])\n recipient = recipients_from_user(user)\n @mailer = Mailer.setup(subject: 'CodeScrum Invitation',\n from_name: default_from_name,\n from_email: default_from_email,\n template: 'rails_girls_template',\n global_merge_vars: default_global_merge_vars)\n @mailer.send_one!(recipient)\n end",
"def send(opts = {}, &block)\n unless block_given?\n mailer.send(:mail, opts.merge(:subject => subject || opts[:subject])) do |format|\n format.html { mailer.render :text => content }\n end\n else\n yield content\n end\n end",
"def prepare_message(options)\n to_message\n end",
"def message\n {\n subject: subject,\n from_name: Constants::MANDRILL_FROM_NAME,\n to: recipients,\n from_email: Constants::MANDRILL_FROM_EMAIL,\n global_merge_vars: [\n {\n name: 'HTML_URL',\n content: html_url\n }\n ]\n }\n end",
"def initialize(options = {})\n options = {\n :message_id => nil,\n :senders => [],\n :recipients => [],\n :cc_recipients => [],\n :bcc_recipients => [],\n :subject => \"\",\n :body => \"\",\n :date => nil\n }.merge(options)\n self.message_id = options[:message_id]\n self.senders = options[:senders]\n self.recipients = options[:recipients]\n self.cc_recipients = options[:cc_recipients]\n self.bcc_recipients = options[:bcc_recipients]\n self.subject = options[:subject]\n self.body = options[:body]\n self.date = options[:date]\n end",
"def mandrill_template(template_name, block_name = nil)\n set_mandrill_header 'X-MC-Template', [template_name, block_name].compact.join('|')\n end",
"def initialize(headertext=nil, sender=nil, recipient=nil)\n @from = sender\n @to = recipient\n @headers = Hash.new(nil)\n\n if Hash === headertext\n @headers_changed = true\n headertext.each_key do |key|\n\n headername = key.to_s.gsub(\"_\",\"-\")\n\n header=Header.new(headername, headertext[key])\n @headers[header.name] ||= HeaderBag.new\n @headers[header.name].push(header)\n end\n else\n if headertext\n @unix_from, @headertext = figure_out_from_line headertext\n parse_headers if @headertext\n\n if sender # then don't believe the mbox separator\n @from = sender\n @unix_from=\"From \"+self.from+\" \"+Time.new.to_s\n else\n guess_sender\n end\n end\n end\n end",
"def create_basic_message(phone_number, message, options={})\n #validate phone number\n { :PhoneNumberToDial => phone_number,\n :TextToSay => message,\n :LicenseKey => @license_key,\n :CallerID => options[:caller_id_number] || '1-866-665-4386',\n :CallerIDname => options[:caller_id_name] || 'CDYNE Notify',\n :VoiceID => options[:voice_id] || 2 }\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /weapons/1 GET /weapons/1.json
|
def show
@weapon = Weapon.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @weapon }
end
end
|
[
"def index\n @weapons = Weapon.all\n\n render json: @weapons\n end",
"def show\n @weapons_type = WeaponsType.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @weapons_type }\n end\n end",
"def show\n respond_to do |format|\n format.json { render json: Weapon.all, status: :created }\n end\n end",
"def index\n @weapons = Weapon.all\n end",
"def show\n @weapon_kind = WeaponKind.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @weapon_kind }\n end\n end",
"def index\n @weapons = Weapon.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @weapons }\n end\n end",
"def index\n @weapons_types = WeaponsType.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @weapons_types }\n end\n end",
"def show\n render json: @weapon_type\n end",
"def index\n @weapon_types = WeaponType.all\n\n render json: @weapon_types\n end",
"def weapon\n fetch('games.elder_scrolls.weapon')\n end",
"def new\n @weapon = Weapon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weapon }\n end\n end",
"def weapon\n fetch('supernatural.weapon')\n end",
"def get_weapons\n weapons = [{name: \"fists\", level: 1, damage: 2, cost: 0}, {name: \"iron sword\", level: 2, damage: 2, cost: 20}, {name: \"chainsword\", level: 3, damage: 3, cost: 30}, \n {name: \"power sword\", level: 4, damage: 4, cost: 40}, {name: \"war axe\", level: 5, damage: 5, cost: 50}, \n {name: \"power fist\", level: 6, damage: 6, cost: 60}, {name: \"mega hammer\", level: 7, damage: 7, cost: 70}, {name: \"crozius\", level: 8, damage: 8, cost: 80},\n {name: \"traffic cone\", level: 9, damage: 9, cost: 90}, {name: \"great sword\", level: 10, damage: 10, cost: 100}]\n return weapons\n end",
"def show\n @weapon = Weapon.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @weapon }\n end\n end",
"def melee_weapon\n fetch('dnd.melee_weapons')\n end",
"def update\n @weapon = Weapon.find(params[:id])\n\n if @weapon.update(weapon_params)\n head :no_content\n else\n render json: @weapon.errors, status: :unprocessable_entity\n end\n end",
"def weapons\r\r\n @battler_ref.weapons \r\r\n end",
"def new\n @weapons_type = WeaponsType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weapons_type }\n end\n end",
"def show\n @equipment = Equipment.find(params[:id])\n\n render json: @equipment\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
GET /weapons/new GET /weapons/new.json
|
def new
@weapon = Weapon.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @weapon }
end
end
|
[
"def new\n @weapons_type = WeaponsType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weapons_type }\n end\n end",
"def new\n @weapon_kind = WeaponKind.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weapon_kind }\n end\n end",
"def new\n @weapon = Weapon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @weapon }\n end\n end",
"def create\n @weapon = Weapon.new(params[:weapon])\n\n respond_to do |format|\n if @weapon.save\n format.html { redirect_to @weapon, notice: 'Weapon was successfully created.' }\n format.json { render json: @weapon, status: :created, location: @weapon }\n else\n format.html { render action: \"new\" }\n format.json { render json: @weapon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @weapon = Weapon.new(weapon_params)\n\n if @weapon.save\n render json: @weapon, status: :created, location: @weapon\n else\n render json: @weapon.errors, status: :unprocessable_entity\n end\n end",
"def new\n @equipment = Equipment.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @equipment }\n end\n end",
"def new\n @equipment = Equipment.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @equipment }\n end\n end",
"def create\n @weapon = Weapon.new(weapon_params)\n\n respond_to do |format|\n if @weapon.save\n format.html { redirect_to @weapon, notice: 'Weapon was successfully created.' }\n format.json { render :show, status: :created, location: @weapon }\n else\n format.html { render :new }\n format.json { render json: @weapon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n weapon_names = Weapon.all\n @weapon_names = {}\n weapon_names.each do |name|\n @weapon_names[name.name] = name.id\n end\n \n ship = Ship.find(params[:ship_id])\n @weapon_card = WeaponCard.new(:ship_id => ship.id)\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weapon_card }\n end\n end",
"def create\n @weapons_type = WeaponsType.new(params[:weapons_type])\n\n respond_to do |format|\n if @weapons_type.save\n format.html { redirect_to @weapons_type, notice: 'Weapons type was successfully created.' }\n format.json { render json: @weapons_type, status: :created, location: @weapons_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @weapons_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @weapon_info = WeaponInfo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @weapon_info }\n end\n end",
"def new\n @tower = Tower.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render :json => @tower }\n end\n end",
"def new\n @equipmenttype = Equipmenttype.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @equipmenttype }\n end\n end",
"def new\n @gold = gold_type.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @gold }\n end\n end",
"def new\n @loot_type = LootType.new\n respond_with @loot_type\n end",
"def new\n @lost_pet = LostPet.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @lost_pet }\n end\n end",
"def new\n @equipo = Equipo.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @equipo }\n end\n end",
"def new\n @tags_of_novel = TagsOfNovel.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @tags_of_novel }\n end\n end",
"def new\n @new_item = NewItem.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @new_item }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
POST /weapons POST /weapons.json
|
def create
@weapon = Weapon.new(params[:weapon])
respond_to do |format|
if @weapon.save
format.html { redirect_to @weapon, notice: 'Weapon was successfully created.' }
format.json { render json: @weapon, status: :created, location: @weapon }
else
format.html { render action: "new" }
format.json { render json: @weapon.errors, status: :unprocessable_entity }
end
end
end
|
[
"def create\n @weapon = Weapon.new(weapon_params)\n\n if @weapon.save\n render json: @weapon, status: :created, location: @weapon\n else\n render json: @weapon.errors, status: :unprocessable_entity\n end\n end",
"def create\n @weapon = Weapon.new(weapon_params)\n\n respond_to do |format|\n if @weapon.save\n format.html { redirect_to @weapon, notice: 'Weapon was successfully created.' }\n format.json { render :show, status: :created, location: @weapon }\n else\n format.html { render :new }\n format.json { render json: @weapon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @character = Character.find(params[:character_id])\n @weapon = @character.weapons.create(weapon_params)\n redirect_to character_path(@character)\n end",
"def create\n @weapon_type = WeaponType.new(weapon_type_params)\n\n if @weapon_type.save\n render json: @weapon_type, status: :created, location: @weapon_type\n else\n render json: @weapon_type.errors, status: :unprocessable_entity\n end\n end",
"def create\n @weapons_type = WeaponsType.new(params[:weapons_type])\n\n respond_to do |format|\n if @weapons_type.save\n format.html { redirect_to @weapons_type, notice: 'Weapons type was successfully created.' }\n format.json { render json: @weapons_type, status: :created, location: @weapons_type }\n else\n format.html { render action: \"new\" }\n format.json { render json: @weapons_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @weapons = Weapon.all\n\n render json: @weapons\n end",
"def create\n @weapon_type = WeaponType.new(weapon_type_params)\n\n respond_to do |format|\n if @weapon_type.save\n format.html { redirect_to @weapon_type, notice: 'Weapon type was successfully created.' }\n format.json { render :show, status: :created, location: @weapon_type }\n else\n format.html { render :new }\n format.json { render json: @weapon_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @weapon = Weapon.new(params[:weapon])\n\n respond_to do |format|\n if @weapon.save\n format.html { redirect_to(@weapon, :notice => 'Weapon was successfully created.') }\n format.xml { render :xml => @weapon, :status => :created, :location => @weapon }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @weapon.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def add_weapon item ; add item, @weapons; end",
"def new\n @weapon = Weapon.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weapon }\n end\n end",
"def create\n @weapon_status = WeaponStatus.new(weapon_status_params)\n\n respond_to do |format|\n if @weapon_status.save\n format.html { redirect_to @weapon_status, notice: 'Weapon status was successfully created.' }\n format.json { render :show, status: :created, location: @weapon_status }\n else\n format.html { render :new }\n format.json { render json: @weapon_status.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @weapon_kind = WeaponKind.new(params[:weapon_kind])\n\n respond_to do |format|\n if @weapon_kind.save\n format.html { redirect_to @weapon_kind, notice: 'Weapon kind was successfully created.' }\n format.json { render json: @weapon_kind, status: :created, location: @weapon_kind }\n else\n format.html { render action: \"new\" }\n format.json { render json: @weapon_kind.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @ship_weapon = ShipWeapon.new(ship_weapon_params)\n\n respond_to do |format|\n if @ship_weapon.save\n format.html { redirect_to @ship_weapon, notice: 'Ship weapon was successfully created.' }\n format.json { render :show, status: :created, location: @ship_weapon }\n else\n format.html { render :new }\n format.json { render json: @ship_weapon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @weapon_slot = WeaponSlot.new(weapon_slot_params)\n\n respond_to do |format|\n if @weapon_slot.save\n format.html { redirect_to @weapon_slot, notice: 'Weapon slot was successfully created.' }\n format.json { render :show, status: :created, location: @weapon_slot }\n else\n format.html { render :new }\n format.json { render json: @weapon_slot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @weapon = Weapon.find(params[:id])\n\n if @weapon.update(weapon_params)\n head :no_content\n else\n render json: @weapon.errors, status: :unprocessable_entity\n end\n end",
"def create\n @weapon_set = WeaponSet.new(weapon_set_params)\n\n respond_to do |format|\n if @weapon_set.save\n format.html { redirect_to @weapon_set, notice: 'Weapon set was successfully created.' }\n format.json { render :show, status: :created, location: @weapon_set }\n else\n format.html { render :new }\n format.json { render json: @weapon_set.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n @weapons_type = WeaponsType.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @weapons_type }\n end\n end",
"def create\n @weapon_subtype = WeaponSubtype.new(weapon_subtype_params)\n\n respond_to do |format|\n if @weapon_subtype.save\n format.html { redirect_to @weapon_subtype, notice: 'Weapon subtype was successfully created.' }\n format.json { render :show, status: :created, location: @weapon_subtype }\n else\n format.html { render :new }\n format.json { render json: @weapon_subtype.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @weapons = Weapon.all\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
PUT /weapons/1 PUT /weapons/1.json
|
def update
@weapon = Weapon.find(params[:id])
respond_to do |format|
if @weapon.update_attributes(params[:weapon])
format.html { redirect_to @weapon, notice: 'Weapon was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @weapon.errors, status: :unprocessable_entity }
end
end
end
|
[
"def update\n @weapon = Weapon.find(params[:id])\n\n if @weapon.update(weapon_params)\n head :no_content\n else\n render json: @weapon.errors, status: :unprocessable_entity\n end\n end",
"def update\n @weapon_type = WeaponType.find(params[:id])\n\n if @weapon_type.update(weapon_type_params)\n head :no_content\n else\n render json: @weapon_type.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @weapon.update(weapon_params)\n format.html { redirect_to @weapon, notice: 'Weapon was successfully updated.' }\n format.json { render :show, status: :ok, location: @weapon }\n else\n format.html { render :edit }\n format.json { render json: @weapon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @weapons_type = WeaponsType.find(params[:id])\n\n respond_to do |format|\n if @weapons_type.update_attributes(params[:weapons_type])\n format.html { redirect_to @weapons_type, notice: 'Weapons type was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @weapons_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @weapon = Weapon.find(params[:id])\n\n respond_to do |format|\n if @weapon.update_attributes(params[:weapon])\n format.html { redirect_to(@weapon, :notice => 'Weapon was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @weapon.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @weapon = Weapon.find(params[:id])\n\n respond_to do |format|\n if @weapon.update_attributes(params[:weapon])\n flash[:notice] = 'Weapon was successfully updated.'\n format.html { redirect_to(@weapon) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @weapon.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @weapon_kind = WeaponKind.find(params[:id])\n\n respond_to do |format|\n if @weapon_kind.update_attributes(params[:weapon_kind])\n format.html { redirect_to @weapon_kind, notice: 'Weapon kind was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @weapon_kind.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @weapon_type.update(weapon_type_params)\n format.html { redirect_to @weapon_type, notice: 'Weapon type was successfully updated.' }\n format.json { render :show, status: :ok, location: @weapon_type }\n else\n format.html { render :edit }\n format.json { render json: @weapon_type.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @equipment = Equipment.find(params[:id])\n\n if @equipment.update(equipment_params)\n head :no_content\n else\n render json: @equipment.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @weapon_status.update(weapon_status_params)\n format.html { redirect_to @weapon_status, notice: 'Weapon status was successfully updated.' }\n format.json { render :show, status: :ok, location: @weapon_status }\n else\n format.html { render :edit }\n format.json { render json: @weapon_status.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @weapon_set.update(weapon_set_params)\n format.html { redirect_to @weapon_set, notice: 'Weapon set was successfully updated.' }\n format.json { render :show, status: :ok, location: @weapon_set }\n else\n format.html { render :edit }\n format.json { render json: @weapon_set.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @weapon_slot.update(weapon_slot_params)\n format.html { redirect_to @weapon_slot, notice: 'Weapon slot was successfully updated.' }\n format.json { render :show, status: :ok, location: @weapon_slot }\n else\n format.html { render :edit }\n format.json { render json: @weapon_slot.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @weapon_info = WeaponInfo.find(params[:id])\n\n respond_to do |format|\n if @weapon_info.update_attributes(params[:weapon_info])\n flash[:notice] = 'WeaponInfo was successfully updated.'\n format.html { redirect_to(@weapon_info) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @weapon_info.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @ship_weapon.update(ship_weapon_params)\n format.html { redirect_to @ship_weapon, notice: 'Ship weapon was successfully updated.' }\n format.json { render :show, status: :ok, location: @ship_weapon }\n else\n format.html { render :edit }\n format.json { render json: @ship_weapon.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\r\n @usertable = Usertable.find(params[:id])\r\n\r\n respond_to do |format|\r\n if @usertable.update_attributes(params[:usertable])\r\n format.html { redirect_to @usertable, notice: 'Your mood was successfully updated.' }\r\n format.json { head :ok }\r\n else\r\n format.html { render action: \"edit\" }\r\n format.json { render json: @usertable.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def update\n @fleet = Fleet.find(params[:id])\n\n respond_to do |format|\n if @fleet.update_attributes(params[:fleet])\n format.html { redirect_to @fleet, notice: 'Fleet was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @fleet.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @thief_talent = ThiefTalent.find(params[:id])\n\n if @thief_talent.update(thief_talent_params)\n head :no_content\n else\n render json: @thief_talent.errors, status: :unprocessable_entity\n end\n end",
"def add_weapon item ; add item, @weapons; end",
"def update\n update_resource @vehicle, vehicle_params\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
DELETE /weapons/1 DELETE /weapons/1.json
|
def destroy
@weapon = Weapon.find(params[:id])
@weapon.destroy
respond_to do |format|
format.html { redirect_to weapons_url }
format.json { head :no_content }
end
end
|
[
"def destroy\n @weapons_type = WeaponsType.find(params[:id])\n @weapons_type.destroy\n\n respond_to do |format|\n format.html { redirect_to weapons_types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @weapon = Weapon.find(params[:id])\n @weapon.destroy\n\n respond_to do |format|\n format.html { redirect_to(weapons_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @weapon_type.destroy\n\n head :no_content\n end",
"def destroy\n @weapon_kind = WeaponKind.find(params[:id])\n @weapon_kind.destroy\n\n respond_to do |format|\n format.html { redirect_to weapon_kinds_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @weapon_type.destroy\n respond_to do |format|\n format.html { redirect_to weapon_types_url, notice: 'Weapon type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @weapon_status.destroy\n respond_to do |format|\n format.html { redirect_to weapon_statuses_url, notice: 'Weapon status was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @ship_weapon.destroy\n respond_to do |format|\n format.html { redirect_to ship_weapons_url, notice: 'Ship weapon was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @weapon_set.destroy\n respond_to do |format|\n format.html { redirect_to weapon_sets_url, notice: 'Weapon set was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @weapon_info = WeaponInfo.find(params[:id])\n @weapon_info.destroy\n\n respond_to do |format|\n format.html { redirect_to(weapon_infos_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n the_name = @equipment_item.name\n @equipment_item.destroy\n respond_to do |format|\n format.html { redirect_to equipment_items_url, status: 303, notice: t('.delete_ok', item: the_name) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @weapon_slot.destroy\n respond_to do |format|\n format.html { redirect_to weapon_slots_url, notice: 'Weapon slot was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @equipment = Equipment.find(params[:id])\n @equipment.destroy\n\n respond_to do |format|\n format.html { redirect_to equipment_index_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @weapon_subtype.destroy\n respond_to do |format|\n format.html { redirect_to weapon_subtypes_url, notice: 'Weapon subtype was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def cmd_delete argv\n setup argv\n uuid = @hash['uuid']\n response = @api.delete(uuid)\n msg response\n return response\n end",
"def destroy\n @weapon_card = WeaponCard.find(params[:id])\n @weapon_card.destroy\n\n respond_to do |format|\n format.html { redirect_to weapon_cards_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @api_v1_item.destroy\n render json: {message: 'deletado com sucesso'}\n end",
"def destroy\n @inventory = @user.inventories.find(params[:id])\n @inventory.destroy\n\n respond_to do |format|\n format.html { redirect_to game_user_inventories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @raid_boss_loot_item.destroy\n respond_to do |format|\n format.html { redirect_to raid_boss_loot_items_url, notice: 'Raid boss loot item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @equipo = Equipo.find(params[:id])\n @equipo.destroy\n\n respond_to do |format|\n format.html { redirect_to equipos_url }\n format.json { head :no_content }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Opens google analytics for given date range
|
def analytics_day(start_date=nil, end_date=nil)
start_date = start_date ? Date.parse("#{start_date}/2010") : Date.today
start_date = start_date.strftime("%Y%m%d")
end_date ||= start_date
"https://www.google.com/analytics/reporting/?reset=1&id=14680769&pdr=#{start_date}-#{end_date}"
end
|
[
"def campaigns_daily_report show_id, date_range, format\n \n params = {\n :show_id => show_id,\n :date_range => date_range,\n :format => format\n }\n \n response = connection.do_get(construct_url(\"analytics\", \"request_campaigns_daily_report\"), params)\n \n # Convert to a hash\n return parse_token_response(response)\n end",
"def reports_campaigns date_from:, date_until:, cID: nil\n call_adglare_api 'reports_campaigns', {date_from: date_from, date_until: date_until, cID: cID}\n end",
"def query(start_date, end_date, metrics, dimensions,\n filters, sort, max)\n service = Google::Apis::AnalyticsV3::AnalyticsService.new\n service.authorization = Signet::OAuth2::Client.new(\n {\n issuer: ENV['GSA_CLIENT_EMAIL'],\n scope: 'https://www.googleapis.com/auth/analytics.readonly',\n token_credential_uri: 'https://www.googleapis.com/oauth2/v3/token',\n audience: 'https://www.googleapis.com/oauth2/v3/token',\n signing_key: OpenSSL::PKey::RSA.new(\n ENV['GSA_PRIVATE_KEY'].gsub(\"\\\\n\", \"\\n\")),\n })\n service.authorization.fetch_access_token!\n service.get_ga_data(ENV['GA_PROFILE_ID'],\n start_date,\n end_date,\n metrics,\n dimensions: dimensions,\n filters: filters,\n sort: sort,\n max_results: max) do |result, err|\n if err\n return nil\n elsif result.rows.nil?\n return []\n else\n return result.rows\n end\n end\n end",
"def send_request_to_google_analytics(utm_url)\n options = {\n \"method\" => \"GET\",\n \"user_agent\" => ENV[\"HTTP_USER_AGENT\"],\n \"header\" => \"Accepts-Language: #{ENV[\"HTTP_ACCEPT_LANGUAGE\"]}\"\n }\n if $cgi[\"utmdebug\"] == \"\"\n OpenURI::open_uri(utm_url, options)\n else\n OpenURI::open_uri(utm_url, options) {|f| warn f.read }\n end\nend",
"def query(dimension, metric, sort, start_date, end_date)\n @client.execute(:api_method => @api.data.ga.get,\n :parameters => {\n 'ids' => \"ga:\" + ENV['GOOGLE_PROFILE_ID'],\n 'start-date' => start_date,\n 'end-date' => end_date,\n 'dimensions' => dimension,\n 'metrics' => metric,\n 'sort' => sort })\n end",
"def list_global_audit_logs_for_date_range(args = {}) \n get(\"/auditlog.json/global\", args)\nend",
"def google_analytics\n code = <<-eos\n <script type=\"text/javascript\">\n\n var _gaq = _gaq || [];\n _gaq.push(['_setAccount', 'UA-298928-15']);\n _gaq.push(['_trackPageview']);\n\n (function(){\n var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;\n ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';\n var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);\n })();\n </script>\n eos\n code.html_safe\n end",
"def record_analytics\n if Rails.env.production?\n ga_id = 'UA-12801815-42'\n domain = 'lari.jumpstart.ge'\n\n g = Gabba::Gabba.new(ga_id, domain)\n g.referer(request.env['HTTP_REFERER'])\n g.ip(request.remote_ip)\n # page view format is (title, url)\n g.page_view(\"api:v1:#{params[:action]}\", request.fullpath)\n end\n end",
"def default_date_range\n \"#{Hyrax.config.analytics_start_date},#{Time.zone.today + 1.day}\"\n end",
"def activities_in_date_range(from_date, to_date)\n from_date = format_date from_date\n to_date = format_date to_date\n\n @dealing_platform.gather \"history/activity/#{from_date}/#{to_date}\", :activities, AccountActivity\n end",
"def activity_on_date_range(activity, start, finish)\n get(\"/user/#{@user_id}/activities/#{activity}/date/#{format_date(start)}/#{format_date(finish)}.json\")\n end",
"def date_range(data)\n # Returns the minimum activity start time and the maximum activity end time\n # from the active entities response. These dates are modified in the following\n # way. The hours (and minutes and so on) are removed from the start and end\n # times and a *day* is added to the end time. These are the dates that should\n # be used in the subsequent analytics request.\n\n start_time = data.map { |entity| Time.parse(entity[:activity_start_time]) }.min\n end_time = data.map { |entity| Time.parse(entity[:activity_end_time]) }.max\n\n start_time = Time.new(\n start_time.year,\n start_time.month,\n start_time.day,\n start_time.hour,\n 0,\n 0,\n '+00:00')\n\n end_time = Time.new(\n end_time.year,\n end_time.month,\n end_time.day,\n end_time.hour,\n 0,\n 0,\n '+00:00') + (60 * 60 * 24) # +1 day\n\n [start_time, end_time]\nend",
"def episode_daily_report show_id, episode_id, date_range, format\n \n params = {\n :show_id => show_id,\n :date_range => date_range,\n :id => episode_id,\n :format => format\n }\n \n response = connection.do_get(construct_url(\"analytics\", \"request_episode_daily_report\"), params)\n \n # Convert to a hash\n return parse_token_response(response)\n end",
"def abuse_reports(campaign_id, start = 0, limit = 500, since = \"2000-01-01 00:00:00\") \n call(\"campaignAbuseReports\", campaign_id, start, limit, since)\n end",
"def generate_daily_report(start_date, end_date)\n\n array_of_days = []\n\n (start_date..end_date).each do |day|\n start_of_day = day\n end_of_day = day + 1\n array_of_days << {:start => start_of_day, :end => end_of_day}\n end\n\n return generate_report(array_of_days)\n end",
"def sendRequestToGoogleAnalytics(utmUrl)\n uri = URI.parse(utmUrl)\n req = Net::HTTP::Get.new(uri.request_uri)\n req['user_agent'] = @request.env[\"HTTP_USER_AGENT\"]\n req['Accepts-Language:'] = @request.env[\"HTTP_ACCEPT_LANGUAGE\"]\n \n res = Net::HTTP.start(uri.host, uri.port) {|http|\n http.request(req)\n }\n res\n end",
"def set_grid date\n @grid = DailyTrackingsGrid.new(params.fetch(:daily_trackings_grid, {}).merge(has_ads_group: @campaign.has_ads_group?)) do\n @campaign.daily_trackings.where(:date => date).page(params[:page])\n end\n end",
"def get_daily(start_date, count = 4)\n date = Usercycle::Cohort::FormatDate.new(start_date).get\n @client.class.get(\"/cohorts/daily/#{date}.json?count=#{count}\", @client.options)\n end",
"def send_request_to_google_analytics(utm_url)\n uri = URI.parse(utm_url)\n req = Net::HTTP::Get.new(\"#{uri.path}?#{uri.query}\")\n req.add_field 'User-Agent', @request.user_agent.blank? ? \"\" : @request.user_agent\n req.add_field 'Accepts-Language', @request.accept_language.blank? ? \"\" : @request.accept_language\n res = Net::HTTP.new(uri.host, uri.port).start { |http| http.request(req) }\n\n warn res.body unless @url_params[\"utmdebug\"].blank?\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Builds an array of FileName Objects (array of files), and prints to console how many files scanned iterates through each item in the cwd, determines if it's a file if it's a file push it to the an array of FileName objects and print every time it scans another 100 items or it's a directory, cd into dir and recursively call itself
|
def buildArray(localObjCache, increase)
localDirContents=[] #Array of all items in the cwd
localDirContents=Dir[Dir.pwd+"/*"] #Builds the array of items in cwd
localDirContents.each do |item|
if File.file?(item)
fileObj = FileName.new(item)
localObjCache.push(fileObj)
n = increase.call #printing every 100 files scanned
if n % 100 == 0
puts n
end
elsif File.directory?(item)
Dir.chdir(item)
buildArray(localObjCache, increase)
end
end
return localObjCache
end
|
[
"def run_through_directory\n@file_array = []\n Dir.foreach('text_files') do |item|\n next if item == '.' or item == '..'\n @file_array << item\n end\nend",
"def process_files( aDir )\n\tunless FileTest.directory?(aDir)\n\t\tputs \"Error. Invalid input for report directory: #{aDir}.\"\n\t\texit\n\tend # unless\n\n\t@@files = []\n\t@@directories = []\n\n\t##\n\t# The actual bit that does the recursing through the dir tree\n\n\tdef process_files_recurse(aDir) \n\t\t@@tempFiles = []\n\n\t\tDir.foreach( aDir ) { |f|\n\t\t\tmyPath = \"#{aDir}\\/#{f}\"\n\t\t\tif FileTest.directory?(myPath) and f != '.' and f != '..' and f != 'zz_archive'\n\t\t\t\t process_files_recurse(myPath)\n\t\t\telse\n\t\t\t\t@@tempFiles.push(myPath) if f.match(/\\.yaml\\Z/)\n\t\t\tend\n\t\t} # Find.find( aDir ) { |f|\n\n\t\tsortedTempFiles = @@tempFiles.sort \n\t\t\n\t\t@@files.push(sortedTempFiles)\n\t\t@@directories.push([aDir[/[^\\/]+$/],sortedTempFiles[sortedTempFiles.length - 1]])\n\n\tend # def process_files_recurse (aDir) \n\n\tprocess_files_recurse(aDir)\n\n\tfiles = @@files.sort.flatten\n\tdirectories = @@directories[0..(@@directories.length - 2)].sort_by { |e| e.nil? ? 'z' : e[0] } \n\n\treturn files,directories\n\nend",
"def scan(option = {})\n filesystem = option[:filesystem] || \"/\"\n Find.find(filesystem) do |path|\n if File.directory?(path)\n if File.basename(path)[0] == ?.\n Find.prune # Don't look any further into this directory.\n else\n next\n end\n else\n #if not File.symlink?(path)\n @number_files += 1\n file_size = File.size(path)\n @total_size += file_size\n @file_array << [path, file_size]\n #end\n end\n end\n\n # Debug\n puts \"Number of files: #{@number_files}\"\n puts \"Total size: #{@total_size}\"\n puts \"File array: \"\n #@file_array.each {|file,size| puts \" #{file}: #{size}\"}\n end",
"def scan\n results = []\n dirs.each do |dir|\n files_in_dir = Dir.glob(File.join(dir,'**','*'))\n results.concat(files_in_dir)\n end\n @known_files = results\n end",
"def scan(dir, buffer)\n puts \"Scan started at #{Time.now}.\"\n @skipped = []\n arr = list_one_deep(dir)\n clear = \"\\r\" + \" \" * 45 + \"\\r\"\n arr.each do |path|\n if is_dir?(path)\n print clear\n message = \"\\rScanning #{path} ...\"\n clear = \"\\r\" + \" \" * message.length + \"\\r\"\n print message\n Dir.chdir(path)\n count = Dir.glob(\"**/**\").count\n count += Dir.glob(\"**/.*\").count\n count += Dir.glob(\".*/.*\").count\n this_hash = {\n path: path,\n count: count\n }\n buffer << this_hash\n end\n end\n puts \"\\rScan completed at #{Time.now}.\"\nend",
"def scan_dirs\n @scan_files = Array.new\n Dir.entries(@scan_dir).each do |scan|\n next if File.directory?(@scan_dir + '/' + scan)\n @scan_files << @scan_dir + '/' + scan\n end\n end",
"def perform_initial_scan\n\t\t\troot_folder = Dir.pwd\n\t\t\tputs \"From: #{root_folder}\"\n\n\t\t\t@base_dirs.each do |dir|\n\n\t\t\t\tputs \"Scanning #{dir}\"\n\n\t\t\t\tDir.chdir(dir)\n\t\t\t\tDir.glob(\"**/*.rb\") do |file|\n\t\t\t\t\tload \"./#{file}\"\n\t\t\t\tend\n\n\t\t\t\tDir.chdir(root_folder)\n\t\t\tend\t\t\n\t\tend",
"def count_number_of_lines(change_to_dir)\n Dir.chdir(change_to_dir)\n puts Dir.pwd.blue \n content = Dir.glob(\"*\")\n cur_dirs = []\n content.each do |file|\n file = \"#{Dir.pwd}/#{file}\"\n\n if File.directory?(file)\n cur_dirs << file\n else\n n = File.readlines(file).size\n print \"#{file} \"\n print \" #{n} lines\\n\".green\n end\n end\n cur_dirs.each do |dir| \n count_number_of_lines(dir)\n end\n\nend",
"def findPaths (conf)\n puts aktTime()+' collecting files...'\n STDOUT.flush #write out immediately\n\tconf[:saveDirs].each do |d|\n\t\tif File.directory?(d)\n\t\t\tDir.chdir(d)\n\t\t\tgetFiles(conf)\n\t\telse\n\t\t\tputs \"\\nWarning: Directory: \\n\"+d+\" **not** found !\"\n\t\tend\n\tend\nend",
"def walk\n FileTreeProfiler.monitor_report(:profile, :dir, path)\n @children = []\n Dir.foreach(path) do |entry|\n next if (entry == '..' || entry == '.')\n full_path = ::File.join(path, entry)\n if ::File.directory?(full_path)\n children.push DirFile.new(self, entry)\n else\n children.push DataFile.new(self, entry)\n end\n end\n end",
"def search_files(dir, key, f_extn)\n#puts \"dir is: \" + dir\nputs \"############################################################\"\nputs \"Val of pwd: \" + Dir.pwd\n\t# For each file in this directory...\n\tfor i in Dir.entries(\"#{dir}\")\n\t\t# Print the current directory\n#puts \"Current working directory: \" + Dir.pwd + \"/\" + dir\n\t\n\t\t# Is this file a regular file?\n\t\tif File.file?(i)\nputs \"==>\t\tCurrently enumerating file: \" + i\n\t\t\t# Yes. Print out its filename.\n#\t\t\tputs \"The file name is #{i}\"\n#puts \"File extension of current file is: \" + File.extname(i)\n\t\t\t\n\t\t\t# Enumerate each file type that shall be processed.\n\t\t\tfor j in f_extn\n#\t\t\t\tputs \"Currently enumerating file extension: #{j}\"\n\t\t\t\t# Does the file extension of this file match the\n\t\t\t\t# currently enumerated file extension?\n\t\t\t\tif (File.extname(i)).eql?(j)\n\t\t\t\t\tputs \"------------------------------------------------------------\"\n#\t\t\t\t\tputs \"Enumerating file extension: #{j}\"\n\t\t\t\t\t#system(\"cat -n #{dir}/#{i} | wc -l\")\n\t\t\t\t\tsystem(\"cat -n #{dir}#{i} | grep #{key}\")\n\t\t\t\tend\n\t\t\t\t# Enumerate the next file extension.\n\t\t\t\tj = (j.to_i+1).to_s\n\t\t\tend\n\t\t# Is this file a directory?\n\t\telsif File.directory?(i)\n\t\t\t# Yes. If this directory does not refer to the current or\n\t\t\t# previous directory, and is a subdirectory, recursively\n\t\t\t# search files in this subdirectory.\n#puts \"Current directory: #{i}\"\n#\t\t\tif (!i.eql?(\".\")) and (!i.eql?(\"./\")) and (!i.eql?(\"..\"))\n\t\t\tif !(i.eql?(\".\") or i.eql?(\"./\") or i.eql?(\"..\"))\n\t\t\t\t# Enter recursive research...\nputs \"==>\t\tRecursively search: \" + Dir.pwd + \"/\" + i\n#puts \"Value of i for recursive research: \" + i\n\t\t\t\t# Change to working directory to subdirectory\n#\t\t\t\tDir.chdir(Dir.pwd + \"/\" + i)\n\t\t\t\tDir.chdir(\"./\" + i)\n#puts \"--\tChanged current working dir to: \" + Dir.pwd\n#\t\t\t\tsearch_files(i, key, f_extn)\n#\t\t\t\tsearch_files(\"./\" + i, key, f_extn)\n\t\t\t\tsearch_files(\"./\", key, f_extn)\n\t\t\t\t# Return to original working directory\n\t\t\t\tDir.chdir(\"../\")\n#puts \"--\tReturned current working dir to: \" + Dir.pwd\n\t\t\tend\n\t\t\t\n\t\t# Else, don't process files that aren't regular nor directories.\n\t\tend\n\tend\nend",
"def CountFiles\n\t\tchildrenFiles = []\n\t\tcwd = File.dirname(__FILE__) # get parent directory from our script\n\t\tchildrenFiles = Dir.glob(cwd + '/**/*').select{ |e| File.file? e }\n\n\t\tchildrenFiles.each do |file|\n\t\t\tif File.extname(file).empty?\n\t\t\t\t@count += 1\n\t\t\t\t@files.push(file)\n\t\t\tend\n\t\tend\n\tend",
"def LoteDeCarga()\n print \" #=============================================================================#\\n\"\n print \"\\tLote de carga en ejecucion...\\n\"\n print \" #-----------------------------------------------------------------------------#\\n\"\n print \"\\tDetectando Cuits...\\n\"\n print \" #-----------------------------------------------------------------------------#\\n\"\n aux = []\n cont = 0\n Dir.chdir(\"C:\\\\SFTP\\\\Tickets\")\n Dir.foreach('.') do |item|\n next if item == '.' or item == '..'\n if File.directory?(item)\n print \"\\tCuit encontrado -> \" + item + \"...\\n\"\n aux[cont] = item\n cont += 1\n end\n end\n return aux\nend",
"def scan\n Dir.glob(File.join(dir, '*')) { |path|\n next if IGNORE.include?(path)\n \n if FileTest.directory?(path)\n subdirs << path\n else\n filename = File.basename(path)\n next if filename == INDEX_HTML\n filenames << filename\n end\n }\n end",
"def files(rootDir)\n Dir.foreach(rootDir) do |dir|\n if dir != \".\" && dir != \"..\"\n puts \"Processing \" + dir\n Dir.foreach(rootDir + \"/\" + dir) do |file|\n if file != \".\" && file != \"..\"\n open(rootDir + \"/\" + dir + \"/\" + file) do |f|\n yield(f)\n end\n end\n end\n end\n end\nend",
"def find_sauce_files(cwd=@opts[:basedir], depth=@opts[:search_depth], file_ext=@opts[:sauce_file_extension])\n files = []\n (0..depth).each do |i|\n prefix = \"*/\"*i\n files << Dir.glob(File.join(cwd, \"#{prefix}*#{file_ext}\"))\n end\n return files.flatten.uniq\n end",
"def traverse (directory)\n Dir.chdir(directory) do\n Dir.glob(\"**/*\") do |f|\n file = File.stat(f)\n check_file f if file.file? && File.extname(f) == '.rb'\n end\n end\nend",
"def traverse_directories # :doc:\n\t\tstring = \"\"\n\t\t#ep 'traversing', Dir.pwd\n\t\tif FileTest.exist?(\"code_runner_info.rb\") or FileTest.exist?(\"CODE_RUNNER_INPUTS\") or FileTest.exist?(\"README\") or @heuristic_analysis and (Dir.entries(Dir.pwd).find{|file| not [\".\",\"..\",\"data.txt\"].include? file and File.file? file} and not Dir.entries(Dir.pwd).include? '.CODE_RUNNER_IGNORE_THIS_DIRECTORY') \n\t\t#i.e. if there are some files in this directory (not just directories)\n\t\t\teprint '.' if @write_status_dots\n\t\t\tbegin\n\n\t\t\t\traise CRMild.new(\"must recalc all\") if @recalc_all or @reprocess_all #must recalculate the run results, not load them if @@recalc_all\n\t\t\t\trun = @run_class.load(Dir.pwd, self) #NB this doesn't always return an object of class run_class - since the run may actually be from a different code\n\t\t\t\traise CRMild.new(\"not complete: must recalc\") unless run.status == :Complete or run.status == :Failed\n\t\t\t\traise CRMild.new(\"Not the right directory, must recalc\") unless run.directory == Dir.pwd\n\t\t\trescue ArgumentError, CRMild => err \n\t\t\t\tif err.class == ArgumentError\n\t\t\t\t\tunless err.message =~ /marshal data too short/\n\t\t\t\t\t\t#puts err\n\t\t\t\t\t\t#puts err.backtrace\n\t\t\t\t\t\traise err\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tlog(err)\n# \t\t\t\tputs err.class\n\t\t\t\tbegin\n\t\t\t\t\t#interrupted = false; \n\t\t\t\t\t#old_trap2 = trap(2){}\n\t\t\t\t\t#old_trap2 = trap(2){eputs \"Interrupt acknowledged...#{Dir.pwd} finishing folder analyis. Interrupt again to override (may cause file corruption).\"; interrupted = true}\n\n\t\t\t\t\t# Here we make sure we are creating a run object of the right class for this folder\n\t\t\t\t\tif FileTest.exist?('code_runner_info.rb') and File.read('code_runner_info.rb') =~ /Classname:.*?(?<class>[A-Z][\\w:]+)/\n\t\t\t\t\t\tclassname = $~[:class]\n\t\t\t\t\t\tbegin \n\t\t\t\t\t\t\trun_cls = Object.recursive_const_get(classname)\n\t\t\t\t\t\trescue NameError=>err\n\t\t\t\t\t\t\tep err, err.message\n\t\t\t\t\t\t\tself.class.repair_marshal_run_class_not_found_error(StandardError.new(classname))\n\t\t\t\t\t\t\trun_cls = Object.recursive_const_get(classname)\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\trun_cls = @run_class\n\t\t\t\t\tend\n\n\t\t\t\t \trun = run_cls.new(self).process_directory #NB this doesn't always return an object of class run_class - since the run may actually be from a different code\n\t\t\t\t\t#trap(2, old_trap2)\n\t\t\t\t\t#(eputs \"Calling old interrupt #{Dir.pwd}\"; Process.kill(2, 0)) if interrupted\n\t\t\t\trescue => err\n\t\t\t\t\tlog(err)\n\t\t\t\t\tunless @heuristic_analysis and (err.class == CRMild or err.class == CRError)\n# \t\t\t\t\t\tputs Dir.pwd\n\t\t\t\t\t\tlogd\n\t\t\t\t\t\teputs Dir.pwd\n\t\t\t\t\t\teputs err.class\n\t\t\t\t\t\teputs err\n# \t\t\t\t\t\teputs err.backtrace\n\t\t\t\t\t\teputs \"----Only allowed to fail processing a directory if a heuristic analysis is being run\"\n\t\t\t\t\t\traise err\n\t\t\t\t\tend\n# \t\t\t\t\tputs err.class\n\t\t\t\t\trun = nil\n# \t\t\t\t\tputs @requests\n\t\t\t\tend\n\t\t\tend\n\t\t\tcheck = false\n\t\t\tif run\n# \t\t\t\tputs run.id, @run_list[run.id]; gets\n# \t\t\t\traise CRFatal.new(\"\\n\\n-----Duplicate run ids: #{run.directory} and #{@run_list[run.id].directory}----\") if @run_list[run.id]\n\t\t\t\tif @run_list[run.id] \n\t\t\t\t\tcheck = true\n\t\t\t\t\t\traise <<EOF \nDuplicate run ids:\nNew: #{run.run_name} #{run.status} in #{run.directory}\nOld: #{@run_list[run.id].run_name} #{@run_list[run.id].status} in #{@run_list[run.id].directory}\nEOF\n\t\t\t\t\tchoice = Feedback.get_choice(\"Which do you want to keep, new or old? (The other folder will be deleted. Press Ctrl+C to cancel and sort the problem out manually)\", [\"New\", \"Old\"])\n\t\t\t\t\tcase choice\n\t\t\t\t\twhen /New/\n\t\t\t\t\t\traise \"Aborting... this function has not been fully tested\"\n\t\t\t\t\t\tFileUtils.rm_r(@run_list[run.id].directory)\n\t\t\t\t\twhen /Old/\n\t\t\t\t\t\traise \"Aborting... this function has not been fully tested\"\n\t\t\t\t\t\tFileUtils.rm_r(run.directory)\n\t\t\t\t\t\trun = nil\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\tif run\n\t\t\t\t(puts \"you shouldn't see this if you chose old\"; gets) if check\n\t\t\t\trun.save\n\t\t\t\t@run_list[run.id] = run\n\t\t\t\t@ids.push run.id\t\t\n\t\t\t\t@ids = @ids.uniq.sort\n\t\t\t\t@max_id = @max_id>run.id ? @max_id : run.id\n\t\t\tend\n\t\t\tif @heuristic_analysis\n\t\t\t\tDir.foreach(Dir.pwd)do |directory|\n\t\t\t\t\tnext if [\".\",\"..\"].include? directory or File.file? directory or directory =~ /\\.rb/ or @run_class.rcp.excluded_sub_folders.include? directory \n\t\t# \t\t\tbegin\t\t\t\n\t\t\t\t\t\tDir.chdir(directory) do \t\n\t\t\t\t\t\t\ttraverse_directories\n\t\t\t\t\t\tend\t\n\t\t# \t\t\trescue Errno::ENOENT\n\t\t# \t\t\t\tlog Dir.entries\n\t\t# \t\t\t\tputs directory + \" was not a directory\"\n\t\t# \t\t\tend\n\t\t\t\tend\n\t\t\tend\n\n\t\telse\n\t\t\tDir.foreach(Dir.pwd)do |directory|\n\t\t\t\tnext if [\".\",\"..\"].include? directory or File.file? directory or directory =~ /\\.rb/ or @run_class.rcp.excluded_sub_folders.include? directory \n\t# \t\t\tbegin\t\t\t\n\t\t\t\t\tDir.chdir(directory) do \t\n\t\t\t\t\t\ttraverse_directories\n\t\t\t\t\tend\t\n\t# \t\t\trescue Errno::ENOENT\n\t# \t\t\t\tlog Dir.entries\n\t# \t\t\t\tputs directory + \" was not a directory\"\n\t# \t\t\tend\n\t\t\tend\n\t\tend\n\tend",
"def scan!\n Dir.chdir(@path) do\n Find.find('.') do |file|\n next if file == '.'\n\n # ignore the ./\n file = file[2..-1]\n name = File.basename(file)\n\n # ignore certain files/directories\n Find.prune if IGNORE.include?(name)\n\n if File.directory?(file)\n @directories << file\n elsif File.file?(file)\n src = File.join(@path,file)\n\n case File.extname(name)\n when '.erb'\n # erb template\n if name.start_with?('_')\n # partial template\n template_dir = File.dirname(file)\n template_name = name[1..-1].chomp('.erb').to_sym\n\n @includes[template_dir][template_name] = src\n else\n dest = file.chomp('.erb')\n\n @templates[dest] = src\n end\n else\n # static file\n @files[file] = src\n end\n end\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Compares each fileObj's md5sum against all But first, if it's empty write to push it to a blanks array However, if equal create a hash of the files and
|
def findDups(objArray, dupsHashArray, emptyFileArray)
objArray.each_with_index do |obj, idx1|
if obj.is_empty?
emptyFileArray.push(obj.fileName)
next
end
objArray.each_with_index do |obj2, idx2|
next if idx1 >= idx2
if obj.md5 === obj2.md5
foundDupHash= {:filePath => obj.fileName, :duplicatePath => obj2.fileName}
dupsHashArray.push(foundDupHash)
end
end
end
end
|
[
"def md5_duplicates\n CfsFile.where(md5_sum: md5_sum).where('id != ?', id).to_a\n end",
"def digest_md5(*files)\n files.flatten.collect { |file| \n File.exists?(file) ? Digest::MD5.hexdigest(File.read(file)) : nil\n }\n end",
"def calculate_md5\n @files.each do |f|\n @md5[f] = Digest::MD5.hexdigest(File.read(@start_dir + \"/\" + f))\n end\n end",
"def md5_checksums\n @md5_checksums ||= begin\n # Parses the md5 manifest into an array of 2-element\n # arrays, where the first element is the md5, and the 2nd element is\n # the file path.\n entries = File.readlines(md5_manifest_path).map(&:chomp).map{ |entry| entry.split(/\\s+/) }\n md5_values = entries.map(&:first)\n file_paths = entries.map(&:last)\n Hash[file_paths.zip(md5_values)]\n end\n end",
"def get_md5_sums(basenames)\n \n h = Hash.new\n basenames.each do |f|\n \n h[\"#{f}\"] = `#{MD5_CMD} #{f}`\n \n end\n \n return h\n \n \n end",
"def compare (mem_list)\n memberdata_dir = '/htapps/mwarin.babel/phdb_scripts/data/memberdata';\n ht00x_dir = '/htapps/mwarin.babel/phdb_scripts/data/loadfiles';\n md_files = {};\n ht_files = {};\n # Compare files.\n mem_list.each do |member_id|\n Dir.entries(memberdata_dir + '/' + member_id).each do |e|\n if e =~ /HT\\d+_#{member_id}.(mono|multi|serial).tsv/ then\n md_files[e] = %x(md5sum #{memberdata_dir + '/' + member_id}/#{e}).split()[0];\n end\n end\n Dir.entries(ht00x_dir).each do |e|\n if e =~ /HT\\d+_#{member_id}\\.(mono|multi|serial)\\.tsv$/ then\n ht_files[e] = %x(md5sum #{ht00x_dir}/#{e}).split()[0];\n end\n end\n end\n\n # Display results.\n allkeys = (Set.new [md_files.keys, ht_files.keys].flatten).to_a;\n puts \"same?\\tname\\t#{memberdata_dir}\\t#{ht00x_dir}\";\n allkeys.sort.each do |k|\n md = md_files[k] || 'N/A';\n ht = ht_files[k] || 'N/A';\n same = false;\n if (md == ht) then\n same = true;\n end\n puts \"#{same}\\t#{k}\\t#{md}\\t#{ht}\";\n end\nend",
"def create_hash_results\n \n @folders.each do |folder|\n Dir.foreach(folder) do |item|\n begin\n next if item == '.' or item == '..'\n fullfilename = File.expand_path(folder, item)\n the_hash = Digest::MD5.hexdigest(File.read(File.join(File.expand_path(folder), item.downcase)))\n @file_data << {:filename=>item, :folder=>folder, :filehash => the_hash}\n rescue\n @error_data << {:error=>\"Skipped#{File.expand_path(folder, item)}\"}\n end\n end\n end\n end",
"def test_003_md5_in_zipfilesystem_works\n file1 = Zip::ZipFile.open(@reference)\n file2 = Zip::ZipFile.open(@identical)\n directory_list1, file_list1 = ZipContentComparator.get_files_and_dirs_list(file1, '.')\n directory_list2, file_list2 = ZipContentComparator.get_files_and_dirs_list(file2, '.')\n assert_equal MD5.md5(file1.file.read(file_list1[0])),\n MD5.md5(file2.file.read(file_list2[0]))\n end",
"def create_chksum_manifest\n chksum_manifest = {}\n files = Dir['*'].select{ |f| File.file? f }\n files.each do |file|\n chksum_manifest[file] = Digest::MD5.file(file).hexdigest\n end\n chksum_manifest\n end",
"def digest_sha1(*files)\n files.flatten.collect { |file| \n File.exists?(file) ? Digest::SHA1.hexdigest(File.read(file)) : nil\n }\n end",
"def files_digest(paths)\n self.digest(paths.map { |path| self.file_digest(path) })\n end",
"def detect\n hexes = {}\n puts \"scanning #{filenames.size} files...\"\n self.filenames.each do |filename|\n hex = Digest::MD5.hexdigest(File.read(filename))\n hexes[hex] = [] unless hexes.has_key?(hex)\n hexes[hex] << filename\n end\n\n hexes.each do |hex, files|\n if files.size > 1\n puts \"\\nduplicates found @ #{hex}:\"\n files.each{ |file| puts \"\\t#{file}\" }\n end\n end\n puts \"scanned #{filenames.size} files\"\n end",
"def final_hash_match\n unless @final_hash_match\n errors.add :file_hash,\n \"of the file does not match the MD5 hash the client calculated. Something didn't transfer correctly.\"\n end\n @final_hash_match\n end",
"def remove_matching_md5s_from_hash\n preapproved_images = @build.preapproved_images_for_branch\n @build.base_images.find_each(batch_size: 500) do |image|\n @build.image_md5s.delete_if do |key, value|\n # Delete the image if the md5, filename match and if there aren't preapprovals pending. If there are, the image needs to be\n # uploaded because it could create diffs -- see handle_pull_request_preapproval_case in test_images_controller\n preapprovals = preapproved_images[image.test_key]\n if found_matching_md5_and_filename(key, value, image) && preapprovals.blank?\n @build.successful_tests.push(image)\n next true\n end\n next false\n end\n end\n end",
"def compute_digest file\n return nil unless File.exist? file\n dig = Digest::MD5.new\n File.foreach(file){|l| dig << l}\n dig.hexdigest\n end",
"def files_digest(paths); end",
"def compare\n\t\t\t\n\t\t\tDir.foreach(@folder1) do |item|\n\t\t\t\tbegin\n \t\t\t\tnext if item == '.' or item == '..'\n \t\t\t\tfullfilename = File.expand_path(@folder1, item)\n \t\t\t\tthe_hash = Digest::MD5.hexdigest(File.read(File.join(File.expand_path(@folder1), item)))\n \t\t\t\titem = item.downcase\n \t\t\t\tfiledata = FileHashResults.new(item, the_hash, nil)\n \t\t\t\t@filehash[item] = filedata\n \t\t\trescue\n \t\t\t #puts \"Skipped:#{item.inspect}\"\n \t\t\tend\n\t\t\tend\n\n\t\t\tDir.foreach(@folder2) do |item|\n\t\t\t begin\n \t\t\t\tnext if item == '.' or item == '..'\n \t\t\t\tthe_hash = Digest::MD5.hexdigest(File.read(File.join(@folder2, item)))\n \t\t\t\titem = item.downcase\n if(@filehash[item]==nil)\n \t\t\t\t\tfiledata = FileHashResults.new(item, nil, the_hash)\n \t\t\t\t\t@filehash[item] = filedata\n \t\t\t\t\tnext\n \t\t\t\tend\n \t\t\t\t@filehash[item.downcase].file_hash2 = the_hash\n \t\t\trescue\n #puts \"Skipped:#{item.inspect}\"\n end\t\n\t\t\tend\n\t\tend",
"def iddupe_files(options = {})\r\n required_input_files :scan_index, :analysis\r\n required_output_files :iddupe_files, :sha256_cache\r\n\r\n # load up the analysis, so we know which file-sizes may have duplicates\r\n analysis = File.open(input_file(:analysis)){|f| JSON.load(f)}\r\n file_sizes = analysis['file_sizes']\r\n\r\n # create a list of file sizes that should be inspected more carefully\r\n collection_by_file_size = {} # { file_size => { sha256 => [path1, path2, ...]} }\r\n file_sizes.each do |size, num|\r\n size_i = size.to_i\r\n if size_i > 0 && num > 1\r\n collection_by_file_size[size_i] = {} # this hash will collect SHA256 checksums for all files of this size\r\n end\r\n end\r\n\r\n sha256_by_path = {} # { path => sha256 }\r\n\r\n\r\n # read the index file\r\n IndexFile::Reader.new(input_file(:scan_index)) do |index_file|\r\n # state objects, updated during parsing\r\n dirscan = {}\r\n dir = {}\r\n\r\n # iterate over all the entries\r\n while not index_file.eof? do\r\n object = index_file.read_object\r\n\r\n case object[:type].to_sym\r\n\r\n when :dirscan\r\n dirscan = object\r\n when :dir\r\n dir = object\r\n when :file\r\n file = object\r\n size = file[:size]\r\n collection = collection_by_file_size[size]\r\n if collection\r\n # puts \"dirscan[:scan_root] = #{dirscan[:scan_root]}\"\r\n # puts \"dir[:path] = #{dir[:path]}\"\r\n # puts \"file[:name] = #{file[:name]}\"\r\n full_path = File.join(dir[:path], file[:name])\r\n sha256 = FileHash.sha256(full_path)\r\n if sha256\r\n collection[sha256] ||= []\r\n collection[sha256] << full_path\r\n\r\n sha256_by_path[full_path] = sha256\r\n end\r\n end\r\n end\r\n end\r\n\r\n # remove sha256-arrays with only a single entry (i.e. only one file has a given sha256)\r\n collection_by_file_size.each do |file_size, collection|\r\n collection.keys.each do |sha256|\r\n if collection[sha256].size == 1\r\n collection.delete(sha256)\r\n end\r\n end\r\n end\r\n # remove empty collections (file-sizes without any duplicates)\r\n collection_by_file_size.keys.each do |file_size|\r\n if collection_by_file_size[file_size].empty?\r\n collection_by_file_size.delete(file_size)\r\n end\r\n end\r\n\r\n result = {\r\n :collection_by_file_size => collection_by_file_size,\r\n }\r\n\r\n # write the text file\r\n File.open(output_file(:iddupe_files), 'w') do |text_file|\r\n text_file.write JSON.pretty_generate(result) + \"\\n\"\r\n end\r\n\r\n if output_file(:sha256_cache, {default: nil})\r\n cache_data = {\r\n :sha256_by_path => sha256_by_path,\r\n }\r\n File.open(output_file(:sha256_cache), 'w') do |cache_file|\r\n cache_file.write JSON.pretty_generate(cache_data)\r\n end\r\n end\r\n \r\n return result\r\n end\r\n end",
"def get_md5sum(file)\n get_sum(file, 'md5')\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Print all blanks to a file
|
def printEmpty(emptyFileArray)
puts "Writing blanks to: /tmp/blanks.txt"
File.open("/tmp/blanks.txt", "w") do |f|
emptyFileArray.each { |element| f.puts(element)}
end
end
|
[
"def write_empty\r\n write_line('')\r\n end",
"def blank_line\n output \"\"\n end",
"def write_white_space\r\n #@file.write String.new.rjust(@indentation)\r\n @file.write(' ' * @indentation)\r\n end",
"def print_blanks_array\n @blanks_array.join(' ')\n end",
"def output(char, file)\n if (file != nil) \n file.write(char) \n else\n print(char)\n end\n end",
"def print_to_file\n each_info do |place, team, score, ending|\n write_line \"#{place} #{team}, #{score} #{ending}\"\n end\n end",
"def empty_line\r\n puts \"\\n\"\r\n end",
"def blank\n open('about:blank')\n end",
"def empty_line(num=1)\n num.times { info(\"\") }\n end",
"def print_all(f)\n # writes the contents of f to standard output with a trailing new line.\n puts f.read\n# ends the definition of print_all.\nend",
"def print_blank_line\n\t\t\tuser_output.prompting(false)\n\t\t\tuser_output.print_line\n\t\tend",
"def skip_blank\n while @lines.any? && @lines.first.strip.empty?\n @lines.shift\n end\n\n nil\n end",
"def write_blank row, idx\n write_cell :blank, row, idx\n end",
"def write_separator\n @stream.puts('')\n end",
"def clean_output_file\n file = File.open(OUTPUT_FILE, \"a+\")\n file.truncate(0)\n end",
"def make_blanks\r\n\t#make an array with \"_ \" pushed in the length times. Every time its printed use join method\r\n\t\t@wordlength.times do |x|\r\n\t\t\t@blanks << \"_ \"\r\n\t\tend\r\n\tend",
"def write_null_parsnp_clean_nwk(filename, clusters)\n seq_name = get_single_seq_name(filename, clusters)\n File.open(filename, \"w\") do |f|\n f.write \"(#{seq_name}:0);\\n\"\n end\nend",
"def empty_line\n end",
"def print_file_products_ascii\n\t$report_file.puts products_ascii\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Write all dups to a file
|
def printDups(dupsHashArray)
puts "Writing duplicates to: /tmp/duplicates.txt"
File.open("/tmp/duplicates.txt","w") do |f|
dupsHashArray.each { |element| f.puts(element[:filePath] + " : " + element[:duplicatePath]) }
end
end
|
[
"def remove_duplicate_entries\n File.open(\"#{output_directory_path}unique_ucf_lists.txt\", \"w+\") { |file|\n file.puts File.readlines(single_bad_ucf_file).uniq\n }\n end",
"def reopen_logs\n to_reopen = []\n append_flags = File::WRONLY | File::APPEND\n\n ObjectSpace.each_object(File) do |fp|\n begin\n if !fp.closed? && fp.stat.file? && fp.sync && (fp.fcntl(Fcntl::F_GETFL) & append_flags) == append_flags\n to_reopen << fp\n end\n rescue IOError, Errno::EBADF\n end\n end\n\n nr = 0\n to_reopen.each do |fp|\n orig_st = begin\n fp.stat\n rescue IOError, Errno::EBADF\n next\n end\n\n begin\n b = File.stat(fp.path)\n next if orig_st.ino == b.ino && orig_st.dev == b.dev\n rescue Errno::ENOENT\n end\n\n begin\n File.open(fp.path, 'a') { |tmpfp| fp.reopen(tmpfp) }\n fp.sync = true\n nr += 1\n rescue IOError, Errno::EBADF\n # not much we can do...\n end\n end\n nr\n end",
"def write_save\n open(@save_path, 'a') do |f|\n @metric_counter.each_pair do |extended_name, metric|\n f.puts \"#{extended_name}:#{metric.count}\"\n @metric_counter.delete(extended_name)\n end\n end\n end",
"def write(file)\n self.files.each { |l| file.puts l }\n end",
"def reopen_logs\n nr = 0\n\n ObjectSpace.each_object(File) do |fp|\n is_log?(fp) or next\n orig_st = fp.stat\n begin\n b = File.stat(fp.path)\n next if orig_st.ino == b.ino && orig_st.dev == b.dev\n rescue Errno::ENOENT\n end\n\n open_arg = 'a'\n if fp.respond_to?(:external_encoding) && enc = fp.external_encoding\n open_arg << \":#{enc.to_s}\"\n enc = fp.internal_encoding and open_arg << \":#{enc.to_s}\"\n end\n fp.reopen(fp.path, open_arg)\n fp.sync = true\n new_st = fp.stat\n if orig_st.uid != new_st.uid || orig_st.gid != new_st.gid\n fp.chown(orig_st.uid, orig_st.gid)\n end\n nr += 1\n end # each_object\n nr\n end",
"def storeFromHash (fileName,hash,dupes=false)\n lineCount = 0\n file = File.new(fileName, \"w+\")\n hash.each do |k,v|\n if dupes\n file.puts \" #{k} repeated #{v} times\" if v > 1\n else\n file.puts k\n end\n lineCount += 1\n end \n file.close\n puts \" #{lineCount} lines written to #{file.path}\"\n return file.path, lineCount\n end",
"def write_to_file\n FileUtils.mkdir_p(File.dirname @filename)\n file = File.open(@filename, \"wb\")\n @blocks.each do |block|\n file.write block\n end\n file.close\n #clear the blocks to save RAM\n @blocks = []\n end",
"def write_file\n\n # file_edited is false when there was no match in the whole file and thus no contents have changed.\n if file_edited\n backup_pathname = original_pathname + \".old\"\n FileUtils.cp(original_pathname, backup_pathname, :preserve => true)\n File.open(original_pathname, \"w\") do |newfile|\n contents.each do |line|\n newfile.puts(line)\n end\n newfile.flush\n end\n end\n self.file_edited = false\n end",
"def create_trip_dup_report\n puts \"Creating trip-duplicate report (#{File.basename(FNAME_TRIP_DUP_CSV)}) ...\"\n\n File.open(FNAME_TRIP_DUP_CSV, 'w'){|fh|\n fh.puts \"trip,files_with_duplicate_trip\"\t# CSV header line\n\n @files_by_sorted_trip.each{|trip,list|\n next unless list.length > 1\n fh.puts \"#{trip},#{list.join(\"|\")}\"\t# CSV data line\n }\n }\n end",
"def write_files\n puts \"Writing #{pluralize('file', site_files.size)}:\" if @verbose\n files_to_invalidate = []\n site_files.each do |file|\n s3_filename = remote_path(file)\n o = @bucket.objects[s3_filename]\n file_with_options = get_file_with_metadata(file, s3_filename);\n\n begin\n s3sum = o.etag.tr('\"','') if o.exists?\n rescue AWS::S3::Errors::NoSuchKey\n s3sum = \"\"\n end\n\n if @incremental && (s3sum == Digest::MD5.file(file).hexdigest)\n if @verbose\n puts \"= #{remote_path(file)}\"\n else\n progress('=')\n end\n else \n o.write(file_with_options)\n files_to_invalidate.push(file)\n if @verbose\n puts \"+ #{remote_path(file)}\"\n else\n progress('+')\n end\n end\n end\n\n invalidate_cache(files_to_invalidate) unless @distro_id.nil?\n end",
"def find_uniques_in_file(src, options={})\n dest_name = options[:dest_name] || \"outfile.txt\"\n set = Set.new\n outfile = nil\n\n # read line by line (avoid slurping)\n File.foreach(src) do |line| \n if add_unique(set, line)\n outfile ||= File.open(dest_name, \"w+\") \n outfile << line\n end\n end\n outfile\n\n ensure\n outfile.close if outfile\n end",
"def writeSeqToList outfile, output\n # Check if file already open and wait until is closed\n while ! %x[lsof -F n].split(\"\\n\").grep(/#{outfile}/).empty?\n sleep 2\n end\n # Write output to outfile\n File.open(\"#{outfile}\", \"a\") do |final|\n final.write(\"#{output}\\n\")\n end\nend",
"def write_log_file(log, file_name)\n return unless log.count.positive?\n\n File.delete(file_name) if File.file?(file_name)\n\n File.open(file_name, 'a') do |file|\n log.each do |log_line|\n file.puts(\"#{log_line.level} #{log_line.timestamp} #{log_line.message}\")\n end\n end\n end",
"def write\n File.open(@fname, 'w') do |file|\n file.flock File::LOCK_EX\n\n UserInfoFile.put_header(file)\n\n @content.names.each_key do |id|\n file.puts @content.build_line(id)\n end\n end\n # 例外は小さい単位で捕捉する\n rescue SystemCallError => e\n puts \"#{e} in write\"\n rescue IOError => e\n puts \"#{e} in write\"\n end",
"def duplicate_original_file\n didWrite = false\n if (File.writable?(\"#{XML_FILE}\"))\n file = File.open(\"#{XML_FILE}\")\n linesArr = File.readlines(file)\n if (linesArr != nil)\n File.open(\"#{XML_FILE}.orig\", 'w') do |f|\n linesArr.each { |element| f.puts(element) }\n end\n didWrite = true\n end\n file.close\n end\n \n if didWrite\n puts \"original file copied to: #{XML_FILE}.orig\"\n end\nend",
"def incremental_write(content)\n File.incremental_write(self, content)\n end",
"def write_checksum\n File.write(checksum_file, checksum)\n puts \"Created #{checksum_file}\"\n end",
"def overwrite(filename)\n res = -1\n File.open(filename, 'w+') do | file | \n p file \n res = write_to_file(file) \n end \n return res\n end",
"def save\n entries = []\n entries << '#'\n entries << '# This file is managed by Chef, using the hostsfile cookbook.'\n entries << '# Editing this file by hand is highly discouraged!'\n entries << '#'\n entries << '# Comments containing an @ sign should not be modified or else'\n entries << '# hostsfile will be unable to guarantee relative priority in'\n entries << '# future Chef runs!'\n entries << '#'\n entries << ''\n entries += unique_entries.map(&:to_line)\n entries << ''\n\n contents = entries.join(\"\\n\")\n contents_sha = Digest::SHA512.hexdigest(contents)\n\n # Only write out the file if the contents have changed...\n if contents_sha != current_sha\n ::File.open(hostsfile_path, 'w') do |f|\n f.write(contents)\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Returns the string representation of the angle (default unit: radians).
|
def to_s(unit = :radians)
case unit
when :degrees, :deg then "#{@degrees}°"
when :radians, :rad then "#@radians rad"
else
raise InvalidArgumentsError, "Unit should be :degrees, :deg, :radians ord :rad."
end
end
|
[
"def format_angle(value, unit)\n value + case unit\n when :degree then '\\degree'\n when :gon then '\\unit{gon}'\n when :radian then '\\unit{radian}'\n end\n end",
"def format_angle(value, unit)\n if unit == :degree\n value + '°'\n else\n value + ' gon'\n end\n end",
"def to_s\n \"#{@degrees.round(2)} #{@scale}\"\n end",
"def to_s\r\n \"#{@degrees.round(2)} #{@scale}\"\r\n end",
"def to_s\n return \"atan(#{self.arg.to_s})\"\n end",
"def angle\n @angle\n end",
"def angle(path)\n io_for(path).angle\n end",
"def angle_unit=(unit)\n unless unit == :deg || unit == :rad\n raise ArgumentError, \"Unknown angle unit '#{unit}'\"\n end\n\n @angle_unit = unit\n end",
"def printAngle(num: nil)\n printGds2Record(type: 'ANGLE', data: posAngle(num)) if num\n end",
"def radians_to_degrees(); end",
"def to_radians_tex\n unless @seconds == 0.0 and @minutes == 0\n return '$%0.*f$' % [@@precision, to_radians]\n end\n\n # This gets deg to 0 <= x <= 360, even for negative\n # values of @degrees\n deg = @degrees.divmod(360)[1]\n case deg\n when 0\n '$0$'\n when 30\n '$\\\\pi/6$'\n when 60\n '$\\\\pi/3$'\n when 90\n '$\\\\pi/2$'\n when 120\n '$2\\\\pi/2$'\n when 150\n '$5\\\\pi/6$'\n when 180\n '$\\\\pi$'\n when 210\n '$7\\\\pi/6$'\n when 240\n '$4\\\\pi/3$'\n when 270\n '$3\\\\pi/2$'\n when 300\n '5\\\\pi/3$'\n when 330\n '11\\\\pi/6$'\n when 360\n '$2\\\\pi$'\n else\n '$%0.*f$' % [@@precision, to_radians]\n end\n end",
"def degrees_to_radians(angle)\n angle * Math::PI / 180\n end",
"def to_degrees\n self / Math::PI.fdiv(180)\n end",
"def to_s\n \"#{@x} #{@y} #{@orientation}\"\n end",
"def to_rad(angle)\n angle * Math::PI / 180\n end",
"def radians\n Science::Angle.new(self, :radians)\n end",
"def rotate(angle)\n primitive 'rotate ' + sprintf('%g', angle)\n end",
"def get_orientation_string()\n case self.orientation\n when 0\n return \"East\"\n when 90\n return \"South\"\n when 180\n return \"West\"\n when 270\n return \"North\"\n else\n return \"Invalid\" # If the robot orientation is not included in [0 90 180 270] the orientation is invalid\n end\n end",
"def dms(num)\n angle_str = %()\n num_ary = num.to_s.partition('.')\n \n #degree\n \n angle_str << (num_ary[0] + DEGREE)\n \n minutes_seconds_ary = ((num_ary[-1].to_f * 60.0) / 10**(num_ary[-1].size).to_f).to_s.partition('.')\n \n #minutes\n \n if minutes_seconds_ary[0].size <= 1\n angle_str << ('0' + minutes_seconds_ary[0] + \"'\")\n else\n angle_str << minutes_seconds_ary[0] + \"'\"\n end\n \n # seconds\n \n seconds = ((minutes_seconds_ary[-1].to_f * 60)/(10**(minutes_seconds_ary[-1].size))).round.to_s\n \n if seconds.size <= 1\n angle_str << ('0' + seconds)\n else\n angle_str << seconds\n end\n \n angle_str + %(\"\\\"\")\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Normalize the angle (in degrees) and converts it in radians.
|
def convert_and_normalize_degrees(angle)
@degrees = normalize_angle(angle, 360)
@radians = deg_to_rad(@degrees)
end
|
[
"def convert_and_normalize_radians(angle)\n @radians = normalize_angle(angle, (2 * Math::PI))\n @degrees = rad_to_deg(@radians)\n end",
"def norm_angle(angle)\n while angle < 0; angle += Const::PI2; end\n while angle > Const::PI2; angle -= Const::PI2; end\n return angle\n rescue => e\n raise\n end",
"def normalize_angle(angle)\n if angle > Math::PI\n angle - 2 * Math::PI\n elsif angle < -Math::PI\n angle + 2 * Math::PI\n else\n angle\n end\nend",
"def to_rad(angle)\n angle * Math::PI / 180\n end",
"def degrees_to_radians(angle)\n angle * Math::PI / 180\n end",
"def normalize_angle(angle, range)\n (angle + range) % range\n end",
"def degrees_to_radians(); end",
"def radians_to_degrees(); end",
"def normalize_bearing(angle)\n \t return ((angle + Math::PI) % (2 * Math::PI)) - Math::PI\n \tend",
"def calculate_radians\n if x_length == 0 || y_length == 0\n angle_to_start_of_quadrant\n else\n case angle_to_end_of_quadrant\n when DEGREES_90\n angle_ignoring_quadrant\n when DEGREES_180\n DEGREES_180 - angle_ignoring_quadrant\n when DEGREES_270\n DEGREES_180 + angle_ignoring_quadrant\n else\n DEGREES_360 - angle_ignoring_quadrant\n end\n end\n end",
"def degrees_to_radians(degrees)\n degrees * DEG_TO_RAD\n end",
"def degrees_to_radians(deg)\n\t\tdeg * Math::PI / 180\n\tend",
"def invert_angle(angle)\n if angle >= 180\n angle - 180\n else\n angle + 180\n end\n end",
"def angle\n @angle\n end",
"def to_degrees\n self / Math::PI.fdiv(180)\n end",
"def radians\n Science::Angle.new(self, :radians)\n end",
"def to_degrees(radians)\n (radians * 180.0) / Math::PI\n end",
"def normalize_degrees(degrees)\n degrees += 360.0 while degrees < 0.0\n degrees % 360.0\n end",
"def to_radians(*args)\n args = args.first if args.first.is_a?(Array)\n if args.size == 1\n args.first * (Math::PI / 180)\n else\n args.map{ |i| to_radians(i) }\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Normalize the angle (in radians) and converts it in degrees.
|
def convert_and_normalize_radians(angle)
@radians = normalize_angle(angle, (2 * Math::PI))
@degrees = rad_to_deg(@radians)
end
|
[
"def convert_and_normalize_degrees(angle)\n @degrees = normalize_angle(angle, 360)\n @radians = deg_to_rad(@degrees)\n end",
"def normalize_angle(angle)\n if angle > Math::PI\n angle - 2 * Math::PI\n elsif angle < -Math::PI\n angle + 2 * Math::PI\n else\n angle\n end\nend",
"def norm_angle(angle)\n while angle < 0; angle += Const::PI2; end\n while angle > Const::PI2; angle -= Const::PI2; end\n return angle\n rescue => e\n raise\n end",
"def normalize_angle(angle, range)\n (angle + range) % range\n end",
"def degrees_to_radians(angle)\n angle * Math::PI / 180\n end",
"def to_degrees\n self / Math::PI.fdiv(180)\n end",
"def radians_to_degrees(); end",
"def normalize_degrees(degrees)\n degrees += 360.0 while degrees < 0.0\n degrees % 360.0\n end",
"def to_degrees(radians)\n (radians * 180.0) / Math::PI\n end",
"def normalize_bearing(angle)\n \t return ((angle + Math::PI) % (2 * Math::PI)) - Math::PI\n \tend",
"def invert_angle(angle)\n if angle >= 180\n angle - 180\n else\n angle + 180\n end\n end",
"def to_rad(angle)\n angle * Math::PI / 180\n end",
"def degrees_to_radians(); end",
"def to_degrees(*args)\n args = args.first if args.first.is_a?(Array)\n if args.size == 1\n (args.first * 180.0) / Math::PI\n else\n args.map{ |i| to_degrees(i) }\n end\n end",
"def angle_from_degrees(alpha)\n d = floor(alpha)\n m = floor(60 * (alpha % 1))\n s = (alpha * 60 * 60) % 60\n degrees_minutes_seconds(d, m, s)\n end",
"def angle\n @angle\n end",
"def arcsin_degrees(x)\n degrees(Math.asin(x).to_degrees)\n end",
"def angle=(value)\r\n if value < 0\r\n value = 360+value\r\n elsif value > 360\r\n value = value-360\r\n end\r\n @angle = value\r\n end",
"def angle=(value)\r\n if value < 0\r\n value = 360+value\r\n elsif value > 360\r\n value = value-360\r\n end\r\n @angle = value\r\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Instantiates a new Science::Angle with the unit "radians".
|
def radians
Science::Angle.new(self, :radians)
end
|
[
"def angle_unit=(unit)\n unless unit == :deg || unit == :rad\n raise ArgumentError, \"Unknown angle unit '#{unit}'\"\n end\n\n @angle_unit = unit\n end",
"def rotate(radians)\n sin = Math.sin radians\n cos = Math.cos radians\n Vector.new cos * @x - sin * @y, sin * @x + cos * @y\n end",
"def radians_to_degrees(); end",
"def initialize(x:, y:, heading:, length:)\n self.x = x\n self.y = y\n self.heading = heading\n self.length = length\n rads = to_rad(heading)\n self.x1 = Math.cos(rads) * length + x\n self.y1 = Math.sin(rads) * length + y\n rads = to_rad(heading + 120)\n self.x2 = Math.cos(rads) * length + x\n self.y2 = Math.sin(rads) * length + y\n rads = to_rad(heading - 120)\n self.x3 = Math.cos(rads) * length + x\n self.y3 = Math.sin(rads) * length + y\n end",
"def angle_deg=( angle_deg )\n self.angle = angle_deg * DEG_TO_RAD\n self\n end",
"def radians=(rads)\n @degrees = 180.0*rads/Math::PI\n self\n end",
"def angle_a\n Angle.new(\n self,\n :a,\n (\n (\n Math.acos((b**2 + c**2 - a**2) / (2.0 * b * c)) * 180\n ) / Math::PI\n )\n )\n end",
"def degrees_to_radians(); end",
"def degrees_to_radians(angle)\n angle * Math::PI / 180\n end",
"def calculate_radians\n if x_length == 0 || y_length == 0\n angle_to_start_of_quadrant\n else\n case angle_to_end_of_quadrant\n when DEGREES_90\n angle_ignoring_quadrant\n when DEGREES_180\n DEGREES_180 - angle_ignoring_quadrant\n when DEGREES_270\n DEGREES_180 + angle_ignoring_quadrant\n else\n DEGREES_360 - angle_ignoring_quadrant\n end\n end\n end",
"def angle=(angle)\n # Use modulo operator to keep angle within 360 degrees\n # Also turns negatives into correct value, e.g -90 % 360 = 270\n @angle = angle % 360\n end",
"def angle_c\n Angle.new(\n self,\n :c,\n (\n (\n Math.acos((a**2 + b**2 - c**2) / (2.0 * a * b)) * 180\n ) / Math::PI\n )\n )\n end",
"def view_angle\n ViewAngle.new(view_phi, view_lambda)\n end",
"def to_degrees\n self / Math::PI.fdiv(180)\n end",
"def rotate!(radians)\n sin = Math.sin radians\n cos = Math.cos radians\n prev_x = @x\n @x = cos * @x - sin * @y\n @y = sin * prev_x + cos * @y\n end",
"def angle=(a)\n\t\tm = self.magnitude\n\t\t@x, @y = Math.cos(a)*m, Math.sin(a)*m\n\t\tcleanUp()\n\tend",
"def angle=(value)\r\n if value < 0\r\n value = 360+value\r\n elsif value > 360\r\n value = value-360\r\n end\r\n @angle = value\r\n end",
"def angle\n @angle\n end",
"def angle=(value)\r\n if value < 0\r\n value = 360+value\r\n elsif value > 360\r\n value = value-360\r\n end\r\n @angle = value\r\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return symbol name for supported digest algorithms and string name for custom ones.
|
def digest_algorithm
@digester.symbol || @digester.digest_name
end
|
[
"def signature_digest_algorithm\n @sign_digester.symbol || @sign_digester.digest_name\n end",
"def name\n # See function: c_digest_name(...) in ext/sha3/_digest.c\n end",
"def name\n name_ptr = FFI::MemoryPointer.new(:pointer)\n result = @handle.interface[:md_name].call(@handle.container, name_ptr)\n raise_on_error(\"Error while obtaining digest name\", result)\n\n name_ptr.read_pointer.get_string(0)\n end",
"def digest_short_name(name)\n Digest::SHA2.hexdigest(name)[0..24]\n end",
"def digest_instance algorithm\n case algorithm.to_s.strip.downcase\n when /\\Asha-?1\\z/\n Digest::SHA1.new\n when /\\Asha-?256\\z/\n Digest::SHA256.new\n when /\\Asha-?512\\z/\n Digest::SHA512.new\n when /\\Asha-?384\\z/\n Digest::SHA384.new\n when /\\Amd-?5\\z/\n Digest::MD5.new\n else\n raise ArgumentError, \"Unknown digest type: #{algorithm}\"\n end\n end",
"def derive_name(data)\n Digest::SHA1.hexdigest(data)\n end",
"def symbol_name\n section.elf.symtab.symbols[symbol_index].name\n end",
"def openssl_name\n CipherSuites::OPENSSL_NAMES[rfc_name]\n end",
"def name\n [@n.to_s + character.to_s, symmetry].reject{|p| p == \"\"}.join(\"_\")\n end",
"def key_algorithm\n if self.rsa?\n \"RSA\"\n elsif self.dsa?\n \"DSA\"\n elsif self.ec?\n \"EC\"\n end\n end",
"def to_sym\n @name\n end",
"def signing_algorithm\n signing_key.is_a?(String) ? \"HS256\" : \"RS256\"\n end",
"def key_algorithm\n if @req.public_key.is_a? OpenSSL::PKey::RSA\n \"RSA\"\n elsif @req.public_key.is_a? OpenSSL::PKey::DSA\n \"DSA\"\n elsif @req.public_key.is_a? OpenSSL::PKey::EC\n \"EC\"\n end\n end",
"def algorithm_name\n raise NotImplementedError\n end",
"def tag_dispatching_name(symbols, prefix = \"_tag\")\n symbols = symbols.chars unless symbols.is_a?(Array)\n chars = symbols.map{|s| s.ord}.join(\"_\")\n \"#{prefix}_#{chars}\".to_sym\n end",
"def to_sym\n @name.to_sym\n end",
"def sym(name)\n SymEngine::Symbol.new(name)\nend",
"def digest_class; end",
"def algorithm\n attributes.fetch(:algorithm) do\n Ably::Util::Crypto::DEFAULTS.fetch(:algorithm)\n end.downcase\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Allows to change algorithm for node digesting (default is SHA1). You may pass either a one of +:sha1+, +:sha256+ or +:gostr3411+ symbols or +Hash+ with keys +:id+ with a string, which will denote algorithm in XML Reference tag and +:digester+ with instance of class with interface compatible with +OpenSSL::Digest+ class.
|
def digest_algorithm=(algorithm)
@digester = Kiji::Digester.new(algorithm)
end
|
[
"def digest_instance algorithm\n case algorithm.to_s.strip.downcase\n when /\\Asha-?1\\z/\n Digest::SHA1.new\n when /\\Asha-?256\\z/\n Digest::SHA256.new\n when /\\Asha-?512\\z/\n Digest::SHA512.new\n when /\\Asha-?384\\z/\n Digest::SHA384.new\n when /\\Amd-?5\\z/\n Digest::MD5.new\n else\n raise ArgumentError, \"Unknown digest type: #{algorithm}\"\n end\n end",
"def digest_algorithm\n @digester.symbol || @digester.digest_name\n end",
"def hash expr, algo = 'sha1'\n Expression.new(\"digest(#{expr}, '#{algo}')\", MM::DataType::TYPE_Binary, expr.is_mandatory, expr.is_array)\n end",
"def digest(string, algorithm)\n Base64.encode64 digester(algorithm).digest(string)\n end",
"def generate_digest(element, algorithm)\n element = document.at_xpath(element, namespaces) if element.is_a? String\n xml = canonicalize(element)\n digest(xml, algorithm).strip\n end",
"def algorithm=(alg)\n @algorithm = begin\n case alg.to_s\n when 'hmac-sha-1'\n OpenSSL::Digest::SHA1.new\n when 'hmac-sha-256'\n OpenSSL::Digest::SHA256.new\n else\n raise(ArgumentError, 'Unsupported algorithm')\n end\n end\n end",
"def digester(type=nil)\n require 'openssl'\n case type.to_s.downcase\n when 'md5'\n require 'digest/md5'\n ::Digest::MD5\n when 'sha128', 'sha1'\n require 'digest/sha1' #need?\n OpenSSL::Digest::SHA1\n when 'sha256'\n require 'digest/sha1' #need?\n OpenSSL::Digest::SHA256\n when 'sha512'\n require 'digest/sha1' #need?\n OpenSSL::Digest::SHA512\n else\n raise \"unsupported digest #{type}\"\n end\n end",
"def Digest(algo)\n Botan::Digest.const_get(algo)\n end",
"def digest_class\n Digest::SHA256\n end",
"def hash expr, algo = 'SHA1'\n Expression.new(\"CONVERT(BINARY(32), HASHBYTES('#{algo}', #{expr}), 2)\", MM::DataType::TYPE_Binary, expr.is_mandatory)\n end",
"def signature_digest_algorithm=(algorithm)\n @sign_digester = Kiji::Digester.new(algorithm)\n end",
"def digest_class; end",
"def digest=( new_digest )\n @digest = new_digest.to_sym\n rehash\n @digest\n end",
"def crypto_hash(name, digest_class)\n digest_length = digest_class.digest('').length\n\n defines = Proc.new do \n define_method :\"#{name}\" do |data|\n data = data.pack 'C*' unless data.kind_of? String\n digest_class.digest(data).unpack 'C*'\n end\n define_method(:\"#{name}_digest_class\") { digest_class }\n define_method(:\"#{name}_length\") { digest_length }\n end\n \n @target.class_eval(&defines)\n (class << @target; self; end).module_eval(&defines) \n end",
"def hash expr, algo = nil\n Expression.new(\"UNHEX(SHA1(#{expr}))\", MM::DataType::TYPE_Binary, expr.is_mandatory)\n end",
"def calculate_hash!\n prefix = PREFIX_NAME_LOOKUP[self.type]\n # add special cases for refs\n self.hash_id = NodeId.sha1(\"#{prefix} #{self.size}\\0#{self.content}\")\n end",
"def default_hash_function(plain_token)\n ::Digest::SHA256.hexdigest plain_token\n end",
"def digest(*) end",
"def digest_a1(h, s)\n # TODO: check for known algorithm values (look out for the IE algorithm quote bug)\n if h[:algorithm] == 'MD5-sess'\n digest_h digest_concat(\n h[:digest] || htdigest(h[:username], h[:realm], h[:password]),\n h[:nonce],\n h[:cnonce]\n )\n else\n h[:digest] || htdigest(h[:username], h[:realm], h[:password])\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return symbol name for supported digest algorithms and string name for custom ones.
|
def signature_digest_algorithm
@sign_digester.symbol || @sign_digester.digest_name
end
|
[
"def digest_algorithm\n @digester.symbol || @digester.digest_name\n end",
"def name\n # See function: c_digest_name(...) in ext/sha3/_digest.c\n end",
"def name\n name_ptr = FFI::MemoryPointer.new(:pointer)\n result = @handle.interface[:md_name].call(@handle.container, name_ptr)\n raise_on_error(\"Error while obtaining digest name\", result)\n\n name_ptr.read_pointer.get_string(0)\n end",
"def digest_short_name(name)\n Digest::SHA2.hexdigest(name)[0..24]\n end",
"def digest_instance algorithm\n case algorithm.to_s.strip.downcase\n when /\\Asha-?1\\z/\n Digest::SHA1.new\n when /\\Asha-?256\\z/\n Digest::SHA256.new\n when /\\Asha-?512\\z/\n Digest::SHA512.new\n when /\\Asha-?384\\z/\n Digest::SHA384.new\n when /\\Amd-?5\\z/\n Digest::MD5.new\n else\n raise ArgumentError, \"Unknown digest type: #{algorithm}\"\n end\n end",
"def derive_name(data)\n Digest::SHA1.hexdigest(data)\n end",
"def symbol_name\n section.elf.symtab.symbols[symbol_index].name\n end",
"def openssl_name\n CipherSuites::OPENSSL_NAMES[rfc_name]\n end",
"def name\n [@n.to_s + character.to_s, symmetry].reject{|p| p == \"\"}.join(\"_\")\n end",
"def key_algorithm\n if self.rsa?\n \"RSA\"\n elsif self.dsa?\n \"DSA\"\n elsif self.ec?\n \"EC\"\n end\n end",
"def to_sym\n @name\n end",
"def signing_algorithm\n signing_key.is_a?(String) ? \"HS256\" : \"RS256\"\n end",
"def key_algorithm\n if @req.public_key.is_a? OpenSSL::PKey::RSA\n \"RSA\"\n elsif @req.public_key.is_a? OpenSSL::PKey::DSA\n \"DSA\"\n elsif @req.public_key.is_a? OpenSSL::PKey::EC\n \"EC\"\n end\n end",
"def algorithm_name\n raise NotImplementedError\n end",
"def tag_dispatching_name(symbols, prefix = \"_tag\")\n symbols = symbols.chars unless symbols.is_a?(Array)\n chars = symbols.map{|s| s.ord}.join(\"_\")\n \"#{prefix}_#{chars}\".to_sym\n end",
"def to_sym\n @name.to_sym\n end",
"def sym(name)\n SymEngine::Symbol.new(name)\nend",
"def digest_class; end",
"def algorithm\n attributes.fetch(:algorithm) do\n Ably::Util::Crypto::DEFAULTS.fetch(:algorithm)\n end.downcase\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Allows to change digesting algorithm for signature creation. Same as +digest_algorithm=+
|
def signature_digest_algorithm=(algorithm)
@sign_digester = Kiji::Digester.new(algorithm)
end
|
[
"def signature_digest_algorithm\n @sign_digester.symbol || @sign_digester.digest_name\n end",
"def digest_algorithm=(algorithm)\n @digester = Kiji::Digester.new(algorithm)\n end",
"def digest_instance algorithm\n case algorithm.to_s.strip.downcase\n when /\\Asha-?1\\z/\n Digest::SHA1.new\n when /\\Asha-?256\\z/\n Digest::SHA256.new\n when /\\Asha-?512\\z/\n Digest::SHA512.new\n when /\\Asha-?384\\z/\n Digest::SHA384.new\n when /\\Amd-?5\\z/\n Digest::MD5.new\n else\n raise ArgumentError, \"Unknown digest type: #{algorithm}\"\n end\n end",
"def digest_algorithm\n @digester.symbol || @digester.digest_name\n end",
"def algorithm=(alg)\n @algorithm = begin\n case alg.to_s\n when 'hmac-sha-1'\n OpenSSL::Digest::SHA1.new\n when 'hmac-sha-256'\n OpenSSL::Digest::SHA256.new\n else\n raise(ArgumentError, 'Unsupported algorithm')\n end\n end\n end",
"def digest(string, algorithm)\n Base64.encode64 digester(algorithm).digest(string)\n end",
"def signature_algorithm(*) end",
"def digest_class\n Digest::SHA256\n end",
"def digest_class; end",
"def signing_algorithm\n signing_key.is_a?(String) ? \"HS256\" : \"RS256\"\n end",
"def digest\n case @signature_method\n when \"HMAC-SHA256\" then OpenSSL::Digest.new(\"sha256\")\n when \"HMAC-SHA1\" then OpenSSL::Digest.new(\"sha1\")\n else\n fail InvalidSignatureMethodError\n end\n end",
"def digest(*) end",
"def checksum_algorithm=(algorithm)\n @checksum_algorithm = algorithm\n end",
"def default_hash_function(plain_token)\n ::Digest::SHA256.hexdigest plain_token\n end",
"def getAlgo(opts)\n digestAlgo=opts[:hash-algo] if opts\n digestAlgo=\"sha-256\" unless digestAlgo # there must be a better idiom for that...\nend",
"def make_digest(string)\n string = remove_extensions(string)\n Digest::SHA512.hexdigest(string)\n end",
"def generate_digest(element, algorithm)\n element = document.at_xpath(element, namespaces) if element.is_a? String\n xml = canonicalize(element)\n digest(xml, algorithm).strip\n end",
"def digest=( new_digest )\n @digest = new_digest.to_sym\n rehash\n @digest\n end",
"def signature_algorithm\n data = OpenSSL::ASN1.decode(self.to_der)\n data.entries[1].value.entries[0].value\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Receives certificate for signing and tries to guess a digest algorithm for signature creation. Will change +signature_digest_algorithm+ and +signature_algorithm_id+ for known certificate types and reset to defaults for others.
|
def cert=(certificate)
@cert = certificate
# Try to guess a digest algorithm for signature creation
case @cert.signature_algorithm
when 'GOST R 34.11-94 with GOST R 34.10-2001'
self.signature_digest_algorithm = :gostr3411
self.signature_algorithm_id = 'http://www.w3.org/2001/04/xmldsig-more#gostr34102001-gostr3411'
# Add clauses for other types of keys that require other digest algorithms and identifiers
else # most common 'sha1WithRSAEncryption' type included here
set_default_signature_method! # Reset any changes as they can become malformed
end
end
|
[
"def signature_digest_algorithm=(algorithm)\n @sign_digester = Kiji::Digester.new(algorithm)\n end",
"def signature_digest_algorithm\n @sign_digester.symbol || @sign_digester.digest_name\n end",
"def digest\n case @signature_method\n when \"HMAC-SHA256\" then OpenSSL::Digest.new(\"sha256\")\n when \"HMAC-SHA1\" then OpenSSL::Digest.new(\"sha1\")\n else\n fail InvalidSignatureMethodError\n end\n end",
"def signature_algorithm\n data = OpenSSL::ASN1.decode(self.to_der)\n data.entries[1].value.entries[0].value\n end",
"def verify_signature signature, data, chain, time = Time.now\n Gem.ensure_ssl_available\n cert_class = OpenSSL::X509::Certificate\n exc = Gem::Security::Exception\n chain ||= []\n\n chain = chain.map{ |str| cert_class.new(str) }\n signer, ch_len = chain[-1], chain.size\n opt = Gem::Security::OPT.merge(@opt)\n\n # make sure signature is valid\n if @verify_data\n # get digest algorithm (TODO: this should be configurable)\n dgst = opt[:dgst_algo]\n\n # verify the data signature (this is the most important part, so don't\n # screw it up :D)\n v = signer.public_key.verify(dgst.new, signature, data)\n raise exc, \"Invalid Gem Signature\" unless v\n\n # make sure the signer is valid\n if @verify_signer\n # make sure the signing cert is valid right now\n v = signer.check_validity(nil, time)\n raise exc, \"Invalid Signature: #{v[:desc]}\" unless v[:is_valid]\n end\n end\n\n # make sure the certificate chain is valid\n if @verify_chain\n # iterate down over the chain and verify each certificate against it's\n # issuer\n (ch_len - 1).downto(1) do |i|\n issuer, cert = chain[i - 1, 2]\n v = cert.check_validity(issuer, time)\n raise exc, \"%s: cert = '%s', error = '%s'\" % [\n 'Invalid Signing Chain', cert.subject, v[:desc]\n ] unless v[:is_valid]\n end\n\n # verify root of chain\n if @verify_root\n # make sure root is self-signed\n root = chain[0]\n raise exc, \"%s: %s (subject = '%s', issuer = '%s')\" % [\n 'Invalid Signing Chain Root',\n 'Subject does not match Issuer for Gem Signing Chain',\n root.subject.to_s,\n root.issuer.to_s,\n ] unless root.issuer.to_s == root.subject.to_s\n\n # make sure root is valid\n v = root.check_validity(root, time)\n raise exc, \"%s: cert = '%s', error = '%s'\" % [\n 'Invalid Signing Chain Root', root.subject, v[:desc]\n ] unless v[:is_valid]\n\n # verify that the chain root is trusted\n if @only_trusted\n # get digest algorithm, calculate checksum of root.subject\n algo = opt[:dgst_algo]\n path = Gem::Security::Policy.trusted_cert_path(root, opt)\n\n # check to make sure trusted path exists\n raise exc, \"%s: cert = '%s', error = '%s'\" % [\n 'Untrusted Signing Chain Root',\n root.subject.to_s,\n \"path \\\"#{path}\\\" does not exist\",\n ] unless File.exist?(path)\n\n # load calculate digest from saved cert file\n save_cert = OpenSSL::X509::Certificate.new(File.read(path))\n save_dgst = algo.digest(save_cert.public_key.to_s)\n\n # create digest of public key\n pkey_str = root.public_key.to_s\n cert_dgst = algo.digest(pkey_str)\n\n # now compare the two digests, raise exception\n # if they don't match\n raise exc, \"%s: %s (saved = '%s', root = '%s')\" % [\n 'Invalid Signing Chain Root',\n \"Saved checksum doesn't match root checksum\",\n save_dgst, cert_dgst,\n ] unless save_dgst == cert_dgst\n end\n end\n\n # return the signing chain\n chain.map { |cert| cert.subject }\n end\n end",
"def fingerprint(algorithm='sha1')\n message_digest = R509::MessageDigest.new(algorithm)\n md = message_digest.digest\n md.update(@cert.to_der)\n md.to_s\n end",
"def fingerprint(algorithm = 'sha256')\n message_digest = R509::MessageDigest.new(algorithm)\n md = message_digest.digest\n md.update(@cert.to_der)\n md.to_s\n end",
"def signature_algorithm(*) end",
"def verify_signature\n verify_with_certificates []\n end",
"def issue_certificate(signature_algo: nil, **kwargs)\n Certificate.new(**kwargs).tap { |c| c.sign(self, algo: signature_algo) }\n end",
"def signature_algorithm\n @signature_algorithm ||= @node.at('signatureAlgorithm').inner_text\n end",
"def signing_algorithm\n signing_key.is_a?(String) ? \"HS256\" : \"RS256\"\n end",
"def computed_signature\n @computed_signature ||=\n Base64.strict_encode64(\n OpenSSL::HMAC.digest('sha256', @event.subscriber.secret_key, payload)\n )\n end",
"def cert_digest\n Digest::SHA1.hexdigest(@cert.to_der)\n end",
"def create_signature_hash\n # user = User.find_by_username_and_store_id(self.sign_username, Thread.current['user'].store_id)\n if user = User.authenticate(self.sign_username, self.sign_password, Thread.current['user'].domain)\n self.signer = user\n self.digital_signature_hash = Digest::SHA1.hexdigest(\"--#{user.social_security_number}--#{self.instance.created_at}--\")\n self.digital_signature_date = Time.now\n self.save_status = self.save_status.to_s + \" Signature accepted. Reload this page to see the digital fingerprint.\"\n else\n logger.info \"Couldn't authenticate #{self.sign_username} with password '#{self.sign_password}'\"\n end\n end",
"def verify_gem(signature, data, chain, time = Time.now)\n\tGem.ensure_ssl_available\n cert_class = OpenSSL::X509::Certificate\n exc = Gem::Security::Exception\n chain ||= []\n\n chain = chain.map{ |str| cert_class.new(str) }\n signer, ch_len = chain[-1], chain.size\n\n # make sure signature is valid\n if @verify_data\n # get digest algorithm (TODO: this should be configurable)\n dgst = @opt[:dgst_algo]\n\n # verify the data signature (this is the most important part,\n # so don't screw it up :D)\n v = signer.public_key.verify(dgst.new, signature, data)\n raise exc, \"Invalid Gem Signature\" unless v\n \n # make sure the signer is valid\n if @verify_signer\n # make sure the signing cert is valid right now\n v = signer.check_validity(nil, time)\n raise exc, \"Invalid Signature: #{v[:desc]}\" unless v[:is_valid]\n end\n end\n\n # make sure the certificate chain is valid\n if @verify_chain\n # iterate down over the chain and verify each certificate\n # against it's issuer\n (ch_len - 1).downto(1) do |i|\n issuer, cert = chain[i - 1, 2]\n v = cert.check_validity(issuer, time)\n raise exc, \"%s: cert = '%s', error = '%s'\" % [\n 'Invalid Signing Chain', cert.subject, v[:desc] \n ] unless v[:is_valid]\n end\n\n # verify root of chain\n if @verify_root\n # make sure root is self-signed\n root = chain[0]\n raise exc, \"%s: %s (subject = '%s', issuer = '%s')\" % [\n 'Invalid Signing Chain Root', \n 'Subject does not match Issuer for Gem Signing Chain',\n root.subject.to_s,\n root.issuer.to_s,\n ] unless root.issuer.to_s == root.subject.to_s\n\n # make sure root is valid\n v = root.check_validity(root, time)\n raise exc, \"%s: cert = '%s', error = '%s'\" % [\n 'Invalid Signing Chain Root', root.subject, v[:desc] \n ] unless v[:is_valid]\n\n # verify that the chain root is trusted\n if @only_trusted\n # get digest algorithm, calculate checksum of root.subject\n algo = @opt[:dgst_algo]\n path = Gem::Security::Policy.trusted_cert_path(root, @opt)\n\n # check to make sure trusted path exists\n raise exc, \"%s: cert = '%s', error = '%s'\" % [\n 'Untrusted Signing Chain Root',\n root.subject.to_s,\n \"path \\\"#{path}\\\" does not exist\",\n ] unless File.exists?(path)\n\n # load calculate digest from saved cert file\n save_cert = OpenSSL::X509::Certificate.new(File.read(path))\n save_dgst = algo.digest(save_cert.public_key.to_s)\n\n # create digest of public key\n pkey_str = root.public_key.to_s\n cert_dgst = algo.digest(pkey_str)\n\n # now compare the two digests, raise exception\n # if they don't match\n raise exc, \"%s: %s (saved = '%s', root = '%s')\" % [\n 'Invalid Signing Chain Root',\n \"Saved checksum doesn't match root checksum\",\n save_dgst, cert_dgst,\n ] unless save_dgst == cert_dgst\n end\n end\n\n # return the signing chain\n chain.map { |cert| cert.subject } \n end\n end",
"def sign(keypair, sign_algorithm=algorithm, sign_version=proto_version)\n header_hash = {\n \"X-Ops-Sign\" => \"algorithm=#{sign_algorithm};version=#{sign_version};\",\n \"X-Ops-Userid\" => user_id,\n \"X-Ops-Timestamp\" => canonical_time,\n \"X-Ops-Content-Hash\" => hashed_body,\n }\n string_to_sign = canonicalize_request(sign_algorithm, sign_version)\n Mixlib::Authentication::Log.debug \"String to sign: '#{string_to_sign}'\\nHeader hash: #{header_hash.inspect}\"\n \n # Sign\n if sign_version <= '1.1'\n signature = Base64.encode64(keypair.private_encrypt(string_to_sign)).chomp\n elsif sign_version == '1.2'\n case sign_algorithm\n when 'sha1'\n if keypair.private?\n Mixlib::Authentication::Log.debug \"Private key supplied, signing with SHA1 digester.\"\n signature = Base64.encode64(keypair.sign(OpenSSL::Digest::SHA1.new, string_to_sign)).chomp\n else # the SSH2 Protocol implicitely uses a SHA1 digester\n Mixlib::Authentication::Log.debug \"No private key supplied, attempt to sign with ssh-agent.\"\n begin\n agent = Net::SSH::Authentication::Agent.connect\n rescue => e\n raise AuthenticationError, \"Could not connect to ssh-agent. Make sure the SSH_AUTH_SOCK environment variable is set properly!\"\n end\n begin\n ssh2_signature = agent.sign(keypair.public_key, string_to_sign)\n rescue => e\n raise AuthenticationError, \"Ssh-agent could not sign your request. Make sure your key is loaded with ssh-add! (#{e.class.name}: #{e.message})\"\n end\n # extract signature from SSH Agent response => skip first 15 bytes for RSA keys\n # (see http://api.libssh.org/rfc/PROTOCOL.agent for details)\n signature = Base64.encode64(ssh2_signature[15..-1]).chomp\n end\n end\n end\n\n # Our multiline hash for authorization will be encoded in multiple header\n # lines - X-Ops-Authorization-1, ... (starts at 1, not 0!)\n signature_lines = signature.split(/\\n/)\n signature_lines.each_index do |idx|\n key = \"X-Ops-Authorization-#{idx + 1}\"\n header_hash[key] = signature_lines[idx]\n end\n\n header_hash\n rescue => e\n Mixlib::Authentication::Log.debug \"Failed to sign request: #{e.class.name}: #{e.message}\"\n raise e\n end",
"def detect_digest_class(bytes); end",
"def response_fingerprint\n response = request.params[\"SAMLResponse\"]\n response = (response =~ /^</) ? response : Base64.decode64(response)\n document = XMLSecurity::SignedDocument::new(response)\n cert_element = REXML::XPath.first(document, \"//ds:X509Certificate\", { \"ds\"=> 'http://www.w3.org/2000/09/xmldsig#' })\n base64_cert = cert_element.text\n cert_text = Base64.decode64(base64_cert)\n cert = OpenSSL::X509::Certificate.new(cert_text)\n Digest::SHA1.hexdigest(cert.to_der).upcase.scan(/../).join(':')\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Digests some +target_node+, which integrity you wish to track. Any changes in digested node will invalidate signed message. All digest should be calculated before signing. Available options: [+:id+] Id for the node, if you don't want to use automatically calculated one [+:inclusive_namespaces+] Array of namespace prefixes which definitions should be added to node during canonicalization [+:enveloped+] Example of XML that will be inserted in message for call like digest!(node, inclusive_namespaces: ['soap']): aeqXriJuUCk4tPNPAGDXGqHj6ao=
|
def digest!(target_node, options = {})
wsu_ns = namespace_prefix(target_node, WSU_NAMESPACE)
current_id = target_node["#{wsu_ns}:Id"] if wsu_ns
id = options[:id] || current_id || "_#{Digest::SHA1.hexdigest(target_node.to_s)}"
# if id.to_s.size > 0
# wsu_ns ||= namespace_prefix(target_node, WSU_NAMESPACE, 'wsu')
# target_node["#{wsu_ns}:Id"] = id.to_s
# end
target_canon = canonicalize(target_node, options[:inclusive_namespaces])
# target_digest = Base64.encode64(@digester.digest(target_canon)).strip
target_digest = @digester.base64(target_canon)
reference_node = Nokogiri::XML::Node.new('Reference', document)
reference_node['URI'] = !id.to_s.empty? ? encode_ja(id) : ''
signed_info_node.add_child(reference_node)
transforms_node = Nokogiri::XML::Node.new('Transforms', document)
reference_node.add_child(transforms_node)
transform_node = Nokogiri::XML::Node.new('Transform', document)
transform_node['Algorithm'] = if options[:enveloped]
'http://www.w3.org/2000/09/xmldsig#enveloped-signature'
else
# transform_node['Algorithm'] = 'http://www.w3.org/2001/10/xml-exc-c14n#'
'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'
end
if options[:inclusive_namespaces]
inclusive_namespaces_node = Nokogiri::XML::Node.new('ec:InclusiveNamespaces', document)
inclusive_namespaces_node.add_namespace_definition('ec', transform_node['Algorithm'])
inclusive_namespaces_node['PrefixList'] = options[:inclusive_namespaces].join(' ')
transform_node.add_child(inclusive_namespaces_node)
end
transforms_node.add_child(transform_node)
digest_method_node = Nokogiri::XML::Node.new('DigestMethod', document)
digest_method_node['Algorithm'] = @digester.digest_id
reference_node.add_child(digest_method_node)
digest_value_node = Nokogiri::XML::Node.new('DigestValue', document)
digest_value_node.content = target_digest
reference_node.add_child(digest_value_node)
self
end
|
[
"def digest(*args)\n options = args.extract_options!\n ::Klarna::API.digest(*[(self.store_id unless options[:store_id] == false), args, self.store_secret].compact.flatten)\n end",
"def generate_digest(element, algorithm)\n element = document.at_xpath(element, namespaces) if element.is_a? String\n xml = canonicalize(element)\n digest(xml, algorithm).strip\n end",
"def checksum!\n # Get a deep copy of hash to compare with\n @_original_hash = Marshal.load(Marshal.dump(to_hash))\n # create a copy of basic elements\n base = self.dup\n base.delete('_id')\n base.delete('_rev')\n base.delete('couchrest-hash')\n flatten =\n lambda {|r|\n (recurse = lambda {|v|\n if v.is_a?(Hash) || v.is_a?(CouchRest::Document)\n v.to_a.map{|p| recurse.call(p)}.flatten\n elsif v.is_a?(Array)\n v.flatten.map{|p| recurse.call(p)}\n else\n v.to_s\n end\n }).call(r)\n }\n self['couchrest-hash'] = Digest::MD5.hexdigest(flatten.call(base).sort.join(''))\n end",
"def target_shasum\n @target_shasum ||= digest_directory(project_dir, :sha256, source_options)\n end",
"def checksum!\n # Get a deep copy of hash to compare with\n @_original_hash = Marshal.load(Marshal.dump(to_hash))\n # create a copy of basic elements\n base = self.reject { |k,_| ['_id', '_rev', 'couchrest-hash'].include? k.to_s }\n\n result = nil\n\n flatten =\n lambda {|r|\n (recurse = lambda {|v|\n if v.is_a?(Hash) || v.is_a?(CouchRest::Document)\n v.to_a.map{|v| recurse.call(v)}.flatten\n elsif v.is_a?(Array)\n v.flatten.map{|v| recurse.call(v)}\n else\n v.to_s\n end\n }).call(r)\n }\n self['couchrest-hash'] = Digest::MD5.hexdigest(flatten.call(base).sort.join(''))\n end",
"def digest(obj)\n build_digest(obj).digest\n end",
"def assoc_sha(source, target)\n case target\n when source then source\n when empty_sha then source\n else target\n end\n end",
"def digest(obj); end",
"def digest\n query = Ox::Element.new(\"query\").tap do |element|\n element[:xmlns] = \"jabber:iq:auth\"\n\n digest_password = self.class.generate_digest(stream_id, password)\n\n element << (Ox::Element.new(\"username\") << jid.node)\n element << (Ox::Element.new(\"digest\") << digest_password)\n element << (Ox::Element.new(\"resource\") << jid.resource)\n end\n\n build_iq(query)\n end",
"def calculate_hash!\n prefix = PREFIX_NAME_LOOKUP[self.type]\n # add special cases for refs\n self.hash_id = NodeId.sha1(\"#{prefix} #{self.size}\\0#{self.content}\")\n end",
"def compute_checksum(h)\n begin\n signed_h = h.dup.with_indifferent_access\n CLEAR_OPTIONS.map{|o| signed_h.delete(o) }\n marshaled = ActionController::Routing::Route.new.build_query_string(signed_h)\n marshaled = marshaled.gsub(/^\\?/, '').split(/&/).sort.join('&')\n digest.call(self, Base64.encode64(marshaled.to_s.reverse)).to_s\n ensure\n end\n end",
"def digest(*) end",
"def digest_63bit(payload)\n configure_default_algo\n send(\"#{algorithm.downcase}63_digest\", payload)\n end",
"def sha\n Digest::SHA2.new.update(source).to_s\n end",
"def digest(data)\n OpenSSL::HMAC.digest(digest_class.new, key, data)[0,mac_length]\n end",
"def sign!(options = {})\n binary_security_token_node if options[:security_token]\n x509_data_node if options[:issuer_serial]\n\n if options[:inclusive_namespaces]\n c14n_method_node = signed_info_node.at_xpath('ds:CanonicalizationMethod', ds: 'http://www.w3.org/2000/09/xmldsig#')\n inclusive_namespaces_node = Nokogiri::XML::Node.new('ec:InclusiveNamespaces', document)\n inclusive_namespaces_node.add_namespace_definition('ec', c14n_method_node['Algorithm'])\n inclusive_namespaces_node['PrefixList'] = options[:inclusive_namespaces].join(' ')\n c14n_method_node.add_child(inclusive_namespaces_node)\n end\n\n signed_info_canon = canonicalize(signed_info_node, options[:inclusive_namespaces])\n\n signature = private_key.sign(@sign_digester.digester, signed_info_canon)\n signature_value_digest = Base64.encode64(signature).delete(\"\\n\")\n\n signature_value_node = Nokogiri::XML::Node.new('SignatureValue', document)\n signature_value_node.content = signature_value_digest\n signed_info_node.add_next_sibling(signature_value_node)\n self\n end",
"def digest_value(xml)\n canonical = xml.canonicalize(Nokogiri::XML::XML_C14N_EXCLUSIVE_1_0)\n digest = OpenSSL::Digest::SHA256.new.digest canonical\n Base64.encode64(digest)\n end",
"def digest\n @__digest__ ||= Util::TaskDigest.generate(rule.package_id, rule.name, inputs, param_set)\n end",
"def hexdigest(obj); end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Sign document with provided certificate, private key and other options This should be very last action before calling +to_xml+, all the required nodes should be digested with +digest!+ before signing. Available options: [+:security_token+] Serializes certificate in DER format, encodes it with Base64 and inserts it within ++ tag [+:issuer_serial+] [+:inclusive_namespaces+] Array of namespace prefixes which definitions should be added to signed info node during canonicalization
|
def sign!(options = {})
binary_security_token_node if options[:security_token]
x509_data_node if options[:issuer_serial]
if options[:inclusive_namespaces]
c14n_method_node = signed_info_node.at_xpath('ds:CanonicalizationMethod', ds: 'http://www.w3.org/2000/09/xmldsig#')
inclusive_namespaces_node = Nokogiri::XML::Node.new('ec:InclusiveNamespaces', document)
inclusive_namespaces_node.add_namespace_definition('ec', c14n_method_node['Algorithm'])
inclusive_namespaces_node['PrefixList'] = options[:inclusive_namespaces].join(' ')
c14n_method_node.add_child(inclusive_namespaces_node)
end
signed_info_canon = canonicalize(signed_info_node, options[:inclusive_namespaces])
signature = private_key.sign(@sign_digester.digester, signed_info_canon)
signature_value_digest = Base64.encode64(signature).delete("\n")
signature_value_node = Nokogiri::XML::Node.new('SignatureValue', document)
signature_value_node.content = signature_value_digest
signed_info_node.add_next_sibling(signature_value_node)
self
end
|
[
"def canonicalized_signed_info\n\n parametros = ActiveSupport::OrderedHash.new\n parametros[\"xmlns\"] = \"http://www.w3.org/2000/09/xmldsig#\"\n parametros[\"xmlns:xsd\"] = \"http://www.w3.org/2001/XMLSchema\"\n parametros[\"xmlns:xsi\"] = \"http://www.w3.org/2001/XMLSchema-instance\"\n \n @builder = Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml|\n xml.SignedInfo(parametros) do\n\n xml.CanonicalizationMethod({'Algorithm' => \"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"}) do\n xml.TEST\n end\n \n xml.SignatureMethod({'Algorithm' => \"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"}) do\n xml.TEST\n end\n \n xml.Reference({'URI' => \"\"}) do\n \n xml.Transforms do\n xml.Transform({ 'Algorithm' => \"http://www.w3.org/2000/09/xmldsig#enveloped-signature\" }) do\n xml.TEST\n end\n end\n \n xml.DigestMethod({ 'Algorithm' => \"http://www.w3.org/2000/09/xmldsig#sha1\" }) do\n xml.TEST\n end\n \n xml.DigestValue(self.digested_canonicalized_data)\n \n end\n \n end\n end\n\n return @builder.to_xml(:save_with => Nokogiri::XML::Node::SaveOptions::AS_XML | Nokogiri::XML::Node::SaveOptions::NO_DECLARATION)\n \n end",
"def sign_metadata(metadata_xml, keypair, xmlsectool_path = nil)\n puts(\"Signing metadata locally with cert #{keypair.cert.subject}\")\n in_tmp_dir('proxy_node_meta') do |dir|\n cert_file = create_file('metadata.crt', keypair.cert.to_pem)\n key_file = create_file('metadata.key', keypair.key.to_der)\n metadata_file = create_file('metadata.xml', metadata_xml)\n\n cmd = <<~EOS\n #{xmlsectool_path} \\\n --sign \\\n --inFile #{dir}/metadata.xml \\\n --outFile #{dir}/metadata_signed.xml \\\n --certificate #{dir}/metadata.crt \\\n --key #{dir}/metadata.key \\\n --digest SHA-256\n EOS\n\n cmd_out = `#{cmd}`\n puts (cmd_out)\n File.open('metadata_signed.xml').read\n end\nend",
"def digest!(target_node, options = {})\n wsu_ns = namespace_prefix(target_node, WSU_NAMESPACE)\n current_id = target_node[\"#{wsu_ns}:Id\"] if wsu_ns\n id = options[:id] || current_id || \"_#{Digest::SHA1.hexdigest(target_node.to_s)}\"\n # if id.to_s.size > 0\n # wsu_ns ||= namespace_prefix(target_node, WSU_NAMESPACE, 'wsu')\n # target_node[\"#{wsu_ns}:Id\"] = id.to_s\n # end\n target_canon = canonicalize(target_node, options[:inclusive_namespaces])\n # target_digest = Base64.encode64(@digester.digest(target_canon)).strip\n target_digest = @digester.base64(target_canon)\n\n reference_node = Nokogiri::XML::Node.new('Reference', document)\n reference_node['URI'] = !id.to_s.empty? ? encode_ja(id) : ''\n signed_info_node.add_child(reference_node)\n\n transforms_node = Nokogiri::XML::Node.new('Transforms', document)\n reference_node.add_child(transforms_node)\n\n transform_node = Nokogiri::XML::Node.new('Transform', document)\n transform_node['Algorithm'] = if options[:enveloped]\n 'http://www.w3.org/2000/09/xmldsig#enveloped-signature'\n else\n # transform_node['Algorithm'] = 'http://www.w3.org/2001/10/xml-exc-c14n#'\n 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'\n end\n if options[:inclusive_namespaces]\n inclusive_namespaces_node = Nokogiri::XML::Node.new('ec:InclusiveNamespaces', document)\n inclusive_namespaces_node.add_namespace_definition('ec', transform_node['Algorithm'])\n inclusive_namespaces_node['PrefixList'] = options[:inclusive_namespaces].join(' ')\n transform_node.add_child(inclusive_namespaces_node)\n end\n transforms_node.add_child(transform_node)\n\n digest_method_node = Nokogiri::XML::Node.new('DigestMethod', document)\n digest_method_node['Algorithm'] = @digester.digest_id\n reference_node.add_child(digest_method_node)\n\n digest_value_node = Nokogiri::XML::Node.new('DigestValue', document)\n digest_value_node.content = target_digest\n reference_node.add_child(digest_value_node)\n self\n end",
"def to_xml(xml=Builder::XmlMarkup.new)\n attributes = {}\n attributes['Id'] = id unless id.nil?\n attributes['xmlns:ds'] = \"http://www.w3.org/2000/09/xmldsig#\"\n xml.tag!('ds:Signature', attributes) {\n xml << signed_info.to_xml if signed_info\n xml.tag!('ds:SignatureValue')\n xml << key_info.to_xml if key_info\n }\n end",
"def sign!\n @signed_date_time = Time.now.utc.strftime('%Y-%m-%dT%H:%M:%SZ')\n @signature = Cybersource::Security.generate_signature(signed_data)\n\n self\n end",
"def sign(private_key, algo: nil)\n @ca_key = private_key.public_key\n @signature = private_key.sign(signed_data, algo: algo)\n end",
"def sign_cert\n @ca_cert.sign @ca_key, OpenSSL::Digest::SHA256.new\n end",
"def upload_signing_certificate(certificate, options = {})\n request({\n 'Action' => 'UploadSigningCertificate',\n 'CertificateBody' => certificate,\n :parser => Fog::Parsers::AWS::IAM::UploadSigningCertificate.new\n }.merge!(options))\n end",
"def sign_request(options)\n options.merge!(:pub => @api_key)\n options.merge!(:key => Digest::MD5.hexdigest(@api_secret + @api_key))\n end",
"def sign_metadata_hsm(metadata_xml, signing_cert, xmlsectool_path = nil)\n puts(\"TODO: Signing metadata using HSM with cert #{signing_cert.subject}\")\n return metadata_xml\nend",
"def calculate_signature(doc, node)\n sha1 = OpenSSL::Digest::SHA1.new\n node = doc.at_css(node)\n canon_signed_info_node = canonicalize_exclusively(node)\n signature = @signing_private_key.sign(sha1, canon_signed_info_node)\n\n encode(signature).gsub(/\\s+/, \"\")\n end",
"def sign(options={})\n options = convert_hash(options)\n options[:expiration_start] ||= Time.now\n options[:expiry] ||= DEFAULT_POLICY_EXPIRY\n\n policy = {\n 'call' => options[:call]\n }\n\n # Restrict the scope of the operation to either the specified file or the path\n if options[:handle]\n policy['handle'] = options[:handle]\n elsif options[:path]\n policy['path'] = (options[:path] + '/').gsub(/\\/+/, '/') # ensure path has a single, trailing '/'\n end\n\n if options[:min_size]\n policy['minsize'] = options[:min_size].to_i\n end\n\n if options[:max_size]\n policy['maxsize'] = options[:max_size].to_i\n end\n\n # Set expiration for <expiry> seconds from expiration start\n policy['expiry'] = (options[:expiration_start] + options[:expiry]).to_i.to_s\n\n # Generate policy in URL safe base64 encoded JSON\n encoded_policy = Base64.urlsafe_encode64(policy.to_json)\n\n # Sign policy using our API secret\n signature = OpenSSL::HMAC.hexdigest('sha256', @api_secret, encoded_policy)\n\n return convert_hash(\n policy: convert_hash(policy),\n encoded_policy: encoded_policy,\n signature: signature\n )\n end",
"def sign csr, org_id, opts = {}\n opts[:days] ||= opts[:years] * 365 unless opts[:years].nil?\n csr = Varanus::SSL::CSR.new(csr) unless csr.is_a?(Varanus::SSL::CSR)\n cert_type_id = opts_to_cert_type_id opts, csr\n args = {\n orgId: org_id,\n csr: csr.to_s,\n subjAltNames: csr.subject_alt_names.join(','),\n certType: cert_type_id,\n term: opts_to_term(opts, cert_type_id),\n serverType: -1,\n comments: opts[:comments].to_s[0, 1024],\n externalRequester: opts[:external_requester].to_s[0, 512]\n }\n post('ssl/v1/enroll', args)['sslId']\n end",
"def create_envelope_from_document(options={})\n ios = create_file_ios(options[:files])\n file_params = create_file_params(ios)\n\n post_body = {\n emailBlurb: \"#{options[:email][:body] if options[:email]}\",\n emailSubject: \"#{options[:email][:subject] if options[:email]}\",\n documents: get_documents(ios),\n recipients: {\n signers: get_signers(options[:signers])\n },\n status: \"#{options[:status]}\",\n customFields: options[:custom_fields]\n }.to_json\n\n uri = build_uri(\"/accounts/#{acct_id}/envelopes\")\n\n http = initialize_net_http_ssl(uri)\n\n request = initialize_net_http_multipart_post_request(\n uri, post_body, file_params, headers(options[:headers])\n )\n\n response = http.request(request)\n JSON.parse(response.body)\n end",
"def sign_certs(ca, root)\n FileUtils.cd(root) do |d|\n conf = \"-config #{@conf}\"\n ext = \"-extfile #{@conf}\"\n key = \"-keyfile #{@prv_key}\"\n ca_cert = \"-cert #{@cert}\" \n cert = \"-out ../#{ca}/#{@cert}\"\n req = \"-in ../#{ca}/#{@csr_file}\"\n puts \"openssl ca -batch #{conf} #{key} #{ca_cert} #{ext} -extensions v3_ca #{req} #{cert}\"\n `openssl ca -batch #{conf} #{key} #{ca_cert} #{ext} -extensions v3_ca #{req} #{cert}`\n end\n end",
"def initialize(options = {})\n if options[:data]\n @x509_csr = OpenSSL::X509::Request.new(options[:data])\n\n else\n # generate the subject name\n subjectX509 = OpenSSL::X509::Name.parse options[:subject]\n\n # save the key pair which was used for that\n @key_pair = options[:key]\n\n # generate the csr\n @x509_csr = OpenSSL::X509::Request.new\n @x509_csr.version = 0\n @x509_csr.subject = subjectX509\n @x509_csr.public_key = @key_pair.to_x509.public_key\n @x509_csr = @x509_csr.sign @key_pair.to_x509, OpenSSL::Digest::SHA1.new\n end\n end",
"def sign!(cert)\n openssl_cert = cert.cert # because model -> OpenSSL object\n openssl_cert.serial = self.next_serial\n cert.serial = self.next_serial\n openssl_cert.issuer = ca_cert.subject\n openssl_cert.sign private_key, OpenSSL::Digest::SHA1.new\n self.next_serial = self.next_serial + 1\n self.save\n nil\n end",
"def SignPDF()\n infile = '../../TestFiles/doc_to_sign.pdf';\n outfile = '../../TestFiles/Output/signed_doc.pdf';\n certfile = '../../TestFiles/pdftron.pfx';\n imagefile = '../../TestFiles/signature.jpg';\n result = true;\n \n begin\n puts('Signing PDF document: \"' + infile + '\".');\n # Open an existing PDF\n doc = PDFDoc.new(infile);\n\n # Add an StdSignatureHandler instance to PDFDoc, making sure to keep track of it using the ID returned.\n sigHandlerId = doc.AddStdSignatureHandler(certfile, 'password')\n \n # Obtain the signature form field from the PDFDoc via Annotation\n sigField = doc.GetField('Signature1')\n widgetAnnot = Widget.new(sigField.GetSDFObj())\n \n # Tell PDFNetC to use the SignatureHandler created to sign the new signature form field.\n sigDict = sigField.UseSignatureHandler(sigHandlerId);\n\n # Add more information to the signature dictionary.\n sigDict.PutName('SubFilter', 'adbe.pkcs7.detached');\n sigDict.PutString('Name', 'PDFTron');\n sigDict.PutString('Location', 'Vancouver, BC');\n sigDict.PutString('Reason', 'Document verification.');\n\n # Add the signature appearance.\n apWriter = ElementWriter.new\n apBuilder = ElementBuilder.new\n apWriter.Begin(doc.GetSDFDoc())\n sigImg = Image.Create(doc.GetSDFDoc(), imagefile)\n w = sigImg.GetImageWidth()\n h = sigImg.GetImageHeight()\n apElement = apBuilder.CreateImage(sigImg, 0, 0, w, h)\n apWriter.WritePlacedElement(apElement);\n apObj = apWriter.End()\n apObj.PutRect('BBox', 0, 0, w, h)\n apObj.PutName('Subtype', 'Form')\n apObj.PutName('Type', 'XObject')\n apWriter.Begin(doc.GetSDFDoc())\n apElement = apBuilder.CreateForm(apObj)\n apWriter.WritePlacedElement(apElement)\n apObj = apWriter.End()\n apObj.PutRect('BBox', 0, 0, w, h)\n apObj.PutName('Subtype', 'Form')\n apObj.PutName('Type', 'XObject')\n\n widgetAnnot.SetAppearance(apObj)\n widgetAnnot.RefreshAppearance()\n \n # Save the PDFDoc. Once the method below is called, PDFNetC will also sign the document using the information\n # provided.\n doc.Save(outfile, 0);\n\n puts('Finished signing PDF document.');\n rescue Exception => e\n puts(e.message)\n puts(e.backtrace.inspect)\n result = false;\n end\n \n return result;\nend",
"def envelope_submit_operation(args={})\n user_name , document_name , order_number , expiration_date ,\n password , culture , sign_device_support , envelope_id ,\n template_id , parameters =\n args[:user_name] , args[:document_name] , args[:order_number] , args[:expiration_date] ,\n args[:password] , args[:culture] , args[:sign_device_support] , args[:envelope_id] ,\n args[:template_id] , args[:parameters]\n\n envelope = construct_envelope do |xml|\n xml.Submit(\"xmlns\" => \"https://www.assuresign.net/Services/DocumentNOW/Submit\") do\n xml.Documents do\n xml.Document(\"ContextIdentifier\" => Starapi.assure_context_identifier) do\n xml.Metadata(\"UserName\" => user_name,\n \"DocumentName\" => document_name,\n \"OrderNumber\" => order_number,\n \"ExpirationDate\" => expiration_date,\n \"Password\" => password,\n \"Culture\" => culture,\n \"SignatureDeviceSupportEnabled\" => sign_device_support) do\n xml.TermsAndConditions do\n xml.AdditionalComplianceStatement \" AdditionalComplianceStatement \"\n xml.AdditionalAgreementStatement \" AdditionalAgreementStatement \"\n xml.AdditionalExtendedDisclosures \"AdditionalExtendedDisclosures \"\n end\n end\n xml.Template(\"Id\" => template_id) do\n xml.Parameters do\n parameters.each do |key, value|\n xml.Parameter(\"Name\" => key, \"Value\" => value)\n end\n end\n end\n end\n end\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Searches in namespaces, defined on +target_node+ or its ancestors, for the +namespace+ with given URI and returns its prefix. If there is no such namespace and +desired_prefix+ is specified, adds such a namespace to +target_node+ with +desired_prefix+
|
def namespace_prefix(target_node, namespace, desired_prefix = nil)
ns = target_node.namespaces.key(namespace)
if ns
ns.match(/(?:xmlns:)?(.*)/) && Regexp.last_match(1)
elsif desired_prefix
target_node.add_namespace_definition(desired_prefix, namespace)
desired_prefix
end
end
|
[
"def namespace_prefix(target_node, namespace, desired_prefix = nil)\n ns = target_node.namespaces.key(namespace)\n if ns\n ns.match(/(?:xmlns:)?(.*)/) && $1\n elsif desired_prefix\n target_node.add_namespace_definition(desired_prefix, namespace)\n desired_prefix\n end\n end",
"def get_namespace(node, prefix); end",
"def get_namespace_prefix(ns_uri)\n # a namespace might be given as a URI or as a reference to a previously defined namespace.\n # E.g. like this:\n # <tag1 xmlns:android=\"http://schemas.android.com/apk/res/android\">\n # <tag2 xmlns:n0=\"android\" />\n # </tag1>\n\n # Walk recursively through the namespaces to\n # transitively resolve URIs that just pointed to previous namespace prefixes\n current_uri = ns_uri\n @namespaces.reverse.each do |ns|\n if ns[:prefix] == current_uri\n # we found a previous namespace declaration that was referenced to by\n # the current_uri. Proceed with this namespace’s URI and try to see if this\n # is also just a reference to a previous namespace\n current_uri = ns[:uri]\n end\n end\n\n # current_uri now contains the URI of the topmost namespace declaration.\n # We’ll take the prefix of this and return it.\n @namespaces.reverse.each do |ns|\n return ns[:prefix] if ns[:uri] == current_uri\n end\n raise \"Could not resolve URI #{ns_uri} to a namespace prefix\"\n end",
"def prefix_for(ns_uri)\n if namespaces_by_uri().has_key?(ns_uri)\n namespaces_by_uri()[ns_uri].prefix || \"\" # namespace.prefix returns nil if there is no prefix defined (default prefix)\n end\n end",
"def lookup_namespace(prefix)\n #This is a stub, used for indexing\n end",
"def get_namespace( node, prefix )\n if @namespaces\n return @namespaces[prefix] || ''\n else\n return node.namespace( prefix ) if node.node_type == :element\n return ''\n end\n end",
"def lookup_namespace_uri( prefix )\n # TODO\n nil\n end",
"def namespace_uri(prefix)\r\n @namespaces[prefix]\r\n end",
"def namespace(prefix)\n easy = Curl::Easy.new\n easy.url = self.uri + \"/namespaces/\" + easy.escape(prefix)\n easy.http_get\n\n raise(SesameException.new(easy.body_str)) unless easy.response_code == 200\n\n ns = easy.body_str\n ns =~ /^Undefined prefix:/ ? nil : ns\n end",
"def register_namespace(prefix, uri)\n #This is a stub, used for indexing\n end",
"def default_prefix=(prefix)\r\n # Find default prefix\r\n ns = find_by_prefix(nil)\r\n raise(ArgumentError, \"No default namespace was found\") unless ns\r\n Namespace.new(self.node, prefix, ns.href)\r\n end",
"def namespace(prefix=nil)\n if prefix.nil?\n prefix = prefix()\n end\n if prefix == ''\n prefix = \"xmlns\"\n else\n prefix = \"xmlns:#{prefix}\" unless prefix[0,5] == 'xmlns'\n end\n ns = attributes[ prefix ]\n ns = parent.namespace(prefix) if ns.nil? and parent\n ns = '' if ns.nil? and prefix == 'xmlns'\n return ns\n end",
"def add_namespace(ns, prefix = \"unknown#{rand 65536}\")\n return nil if ns.nil? || ns.empty?\n unless namespaces.key? ns\n namespaces[ns] = prefix\n return prefix\n end\n end",
"def find_namespace_uri(ns_stack, prefix, uri_check=nil)\n tns = ns_stack.reverse.find{|ns| ns.has_key?(prefix)}\n uri = tns[prefix] if tns\n raise \"prefix: '#{prefix}' is bound to uri: '#{uri}', but should be '#{uri_check}'\" if uri_check && uri && uri!=uri_check\n uri\n end",
"def namespace_prefix=(prefix)\n old_namespace = namespace\n @namespace = ::XML::MappingExtensions::Namespace.new(uri: old_namespace.uri, schema_location: old_namespace.schema_location, prefix: prefix)\n end",
"def register_ns(prefix, uri)\n #This is a stub, used for indexing\n end",
"def prefix=(uri)\n @prefix = uri\n @source ||= uri\n end",
"def namespace_prefix(prefix)\n @namespace_prefix = prefix\n end",
"def namespace_matches?(xml_node, ns)\n return false unless xml_node.respond_to?(:namespace)\n\n unless (query_uri = @query_namespaces[ns])\n raise ::OgaNs::UnspecifiedPrefixException.new(\"Unspecified namespace prefix: '#{ns}'\")\n end\n\n return (ns == '*') || (xml_node.namespace && xml_node.namespace.uri == query_uri)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
TODO: Given an array of integers, find the two subsequences that are disjoint and contiguous such that the difference of their sums is maximized.
|
def disjoint_attempt(arr)
part = [0]
maxPrev = [0]
maxLeft = []
minPrev = [0]
minLeft = []
max = 0
# main idea: subsequence sum is partial sum at end minus partial
# sum at start. Max score is thus either
# maxLeft[i] + maxPrev[i] - 2 * part[i] or
# - minLeft[i] - minPrev[i] + 2 * part[i]
# for some i
# calculate partial sums up to each index in the array
# calculate max of these seen so far at each index
arr.each_with_index do |el, i|
k = i + 1
part[k] = part[i] + el
maxPrev[k] = [maxPrev[i], part[k]].max
minPrev[k] = [minPrev[i], part[k]].min
end
maxLeft[arr.size] = part[arr.size]
minLeft[arr.size] = part[arr.size]
# calculate max partial sum remaining at each index
# now that we have enough info, update max score
arr.size.downto(1) do |i|
k = i - 1
maxLeft[k] = [maxLeft[i], part[k]].max
minLeft[k] = [minLeft[i], part[k]].min
max = [max, maxLeft[i] + maxPrev[i] - 2 * part[i],
0 - minLeft[i] - minPrev[i] + 2 * part[i]].max
end
# loop doesn't catch this
max = [max, maxLeft[0] + maxPrev[0] - 2 * part[0],
0 - minLeft[0] - minPrev[0] + 2 * part[0]].max
return max
end
|
[
"def largest_continuous_subsum(arr)\n sub_sets = []\n arr.each_with_index do |el1, i|\n arr.each_with_index do |el2, j|\n sub_sets << arr[i..j] if j >= i\n end\n end\n large_sum = sub_sets[0].reduce(:+)\n sub_sets.each do |set|\n sum = set.reduce(:+)\n large_sum = sum if large_sum < sum\n end\n\n p sub_sets\n large_sum\nend",
"def largest_subsequence_sum(arr)\n #result[i] = sum of the constiguous subsequence with maximum sum for array[0...i]\n result = Array.new(arr.count, 0)\n\n (0 ... arr.count).each do |i|\n prev_result = i > 0 ? result[i-1] : 0\n result[i] = [prev_result + arr[i], arr[i]].max\n end\n \n result.max\nend",
"def max_sum_sequence_dc(array)\n if array.size == 1\n return array.first\n end\n mid = array.size/2\n # Get the max subsequence sum of left half\n left_max_sum = max_sum_sequence_dc(array[0..mid-1])\n # Get the max subsequence sum of right half\n right_max_sum = max_sum_sequence_dc(array[mid..-1])\n left_sum = -999\n right_sum = -999\n # Get the best possible sum of left half\n sum = 0\n (mid-1).downto(0) do |i| # To have the count backwards\n sum = sum + array[i] \n left_sum = [left_sum,sum].max\n end\n # Get the bset possible sum of right half\n sum = 0\n (mid..array.size-1).each do |i|\n sum = sum + array[i]\n right_sum = [right_sum, sum].max\n end\n # Return the maximum of three possible sub sequences\n return [left_max_sum, right_max_sum, left_sum+right_sum].max\nend",
"def largest_contiguous_subsum_slow(arr)\n res = arr.first\n (0...arr.length - 1).each do |i|\n (i+1...arr.length).each do |j|\n tmp_sum = arr[i..j].reduce(:+)\n res = tmp_sum if tmp_sum > res\n end\n end\n return res\nend",
"def phase2_largest_contiguous_subsum(list)\n subarr = []\n list.each_index do |idx|\n subarr << list[idx..-1]\n subarr << [list[idx]] unless list[idx] == list[-1]\n if idx == list.length - 1\n subarr << list[0..-2] \n end\n end\n\n sums = subarr.map { |sub| sub.reduce(:+) }.max \n\nend",
"def contig_subsum(array)\n sub_arrays = []\n i = 0\n j = 0\n while i < array.length do\n while j < array.length do\n sub_arrays << array[i..j]\n j += 1\n end\n i += 1\n j = i\n end\n\n max_sum = 0\n arr = []\n\n sub_arrays.each do |sub|\n arr << sub.inject(:+)\n end\n\n arr.uniq.sort.last\n\nend",
"def maxSequence(arr)\n \n return [] if arr.empty?\n return 0 if arr.all? { |num| num.negative? }\n size = arr.size\n max_sum = 0\n 0.upto(size - 1) do |start_idx|\n start_idx.upto(size - 1) do |end_idx|\n if arr[start_idx..end_idx].sum > max_sum\n max_sum = arr[start_idx..end_idx].sum\n end\n end\n end\n max_sum \nend",
"def largest_contiguous_subsum(list)\n sums = []\n \n list.length.times do |i|\n (i+1..list.length - 1).each do |j|\n sums << list[i..j].reduce(:+)\n end\n end\n \n sums.max\nend",
"def largest_contiguous_subsum2(other_list)\n largest = other_list.first\n other_list.inject(0) do |current, ele|\n current = current + ele\n\n if current > largest\n largest = current\n elsif current < 0\n\n 0\n else\n current\n end\n end\n largest\nend",
"def sub_sum2(array)\n arr = []\n sum = 0\n array.each do |el|\n arr << [el] \n end\n array.each do |el|\n array.shift\n arr << array\n end\n # p arr\n result = 0\n arr.each do |set|\n if set.reduce(:+) > result\n result = set.reduce(:+)\n end \n end \n result\nend",
"def maxSubsetSum(arr)\n n = arr.size\n return arr[0] if n == 1\n return arr.max if n == 2\n \n dp = Array.new(n, -Float::INFINITY)\n dp[0] = arr[0]\n dp[1] = [arr[0], arr[1]].max\n (2...n).each do |i|\n dp[i] = [dp[i-1], dp[i], dp[i-2]+arr[i], arr[i]].max\n end\n dp[n-1]\nend",
"def solution(a)\n return 0 if a.length < 3\n\n # Find minimum 2-slice and its index - min_2 = [a, b], idx\n min_2 = a.each_cons(2).each_with_index.reduce do |i, j|\n i[0].sum() <= j[0].sum() ? i : j\n end\n\n # Find minimum 3-slice and its index - min_3 = [a, b], idx\n min_3 = a.each_cons(3).each_with_index.reduce do |i, j|\n i[0].sum() <= j[0].sum() ? i : j\n end\n\n # Integer cross multiply instead of float divide for average\n min_2[0] = min_2[0].sum() * 3\n min_3[0] = min_3[0].sum() * 2\n \n # Return index of smaller slice\n min_2[0] <= min_3[0] ? min_2[1] : min_3[1]\nend",
"def maxSubsetSum(arr)\n n = arr.length\n result = []\n result[0] = [arr[0], 0].max\n result[1] = [arr[0], arr[1], 0].max\n 2.upto(n-1) do |i|\n result[i] = [result[i-2]+arr[i], result[i-1]].max\n end\n return result[n-1]\nend",
"def max_sequence(arr)\n if arr.length == 0 || contains_only_negative_nums?(arr)\n return 0\n end\n\n if contains_only_positive_nums?(arr)\n return arr.sum\n end\n\n sums = []\n\n arr.each_with_index do |number, idx|\n sums << get_contig_sum(arr, idx)\n end\n\n sums.flatten.max\nend",
"def smart_largest_contiguous_subsum(list)\n larget_sum = list[0]\n i = 1\n while i < list.length\n if larget_sum > 0\n if larget_sum + list[i] > 0\n larget_sum += list[i]\n else\n larget_sum = list[i+1]\n i += 1\n end\n else\n larget_sum = list[i] if list[i] > larget_sum\n end\n i += 1\n end\n larget_sum\nend",
"def max_subarray_sum(array)\n sum = 0\n sum_to_here = 0\n\n array.each do |num|\n # if num is a max, we reset the sequence. otherwise, it keeps growing!\n # the max is either the current element or the current element COMBINED with the rest of em!\n sum_to_here = [num, sum_to_here + num].max # local maxim\n # the sum will only update if the growing sequence is a new max.\n sum = [sum, sum_to_here].max\n end\n\n sum # the last sequential sum is the greatest contiguous sum!\nend",
"def solution(a)\n min_index = nil\n max_index = nil\n\n a.each_with_index do |num, index|\n if index < a.length-1\n if num > a[index + 1]\n min_index = index\n break\n end\n end\n end\n\n reversed_array = a.reverse\n\n reversed_array.each_with_index do |num, index|\n if index < reversed_array.length-1\n if num < reversed_array[index + 1]\n max_index = a.length - index - 1\n break\n end\n end\n end\n\n if min_index.nil? && max_index.nil?\n return 0\n end\n\n until a.sort == a[0...min_index] + a[min_index..max_index].sort + a[max_index+1..-1]\n minimum_in_sub = a[min_index..max_index].sort.first\n maximum_in_sub = a[min_index..max_index].sort.last\n\n new_min_index = a[0...min_index].reverse.index(a[0...min_index].reverse.find{|n| n >= minimum_in_sub})\n\n if new_min_index\n min_index = min_index - new_min_index - 1\n end\n\n new_max_index = a[max_index+1..-1].index(a[max_index+1..-1].find{|n| n <= maximum_in_sub})\n\n if new_max_index\n max_index = max_index + new_max_index + 1\n end\n end\n\n max_index - min_index + 1\nend",
"def max_sequence(arr)\n return arr.sum if arr.all? {|num| num >= 0}\n return 0 if arr.all? {|num| num <= 0}\n \n highest_subarr_sum = 0\n \n loop do\n break if arr.empty?\n \n arr.each_with_index do |num, index|\n slice_sum = arr.slice(0..index).to_a.sum \n highest_subarr_sum = slice_sum if slice_sum > highest_subarr_sum\n end\n \n arr.shift\n \n end\n \n highest_subarr_sum\n \nend",
"def max_sub_array\n (0...self.size).inject([self.first]) do |max_sub,i|\n (i...self.size).each do |j|\n if max_sub.int_sum < self[i..j].int_sum\n max_sub = self[i..j]\n end\n end\n max_sub\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
time to parse some lisp input: string with newlines and tabs output: parens around function blocks iterate through characters in the string there are several states the parser can be in the token counting state, where line tokens are counted up and tabs are counted the tab counting state, where tabs are being read to determine the structure of the following line the ("[ state, where a stack is built up, newlines, tabs, and spaces are ignored, and only one token is being created the backslash state, where the following character is ignored
|
def parse_lisp(str)
# TODO: handle the tab tree and resulting token structure
depth_stack = [] # can have (, ", and [
current_token = nil
state_stack = []
state = "token counting"
tab_count = 0
str.each_char do |char|
current_token << char
if state == "tab counting" && char != "\t"
# do stuff with tabs and structure
tab_count = 0
end
if char == "\\"
state = "backslash"
else
case state
when "token counting"
when "tab counting"
when "within paren, quote, or bracket"
case char
when ")"
depth_stack.pop if depth_stack[-1] == '('
when "]"
depth_stack.pop if depth_stack[-1] == '['
when '"'
depth_stack.pop if depth_stack[-1] == '"'
else
if "([".include?(char)
depth_stack << char
else
end
end
when "backslash"
state = state_stack.pop
end
end
end
puts pre_parse
end
|
[
"def cooktime\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 5 )\n value = nil\n cooktime_start_index = @input.index\n lineorstop10 = nil\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 value\n end\n # at line 92:5: ( 'C' | 'c' ) ( 'O' | 'o' ) ( 'O' | 'o' ) ( 'K' | 'k' ) ( 'I' | 'i' ) ( 'N' | 'n' ) ( 'G' | 'g' ) ( WS )+ ( 'T' | 't' ) ( 'I' | 'i' ) ( 'M' | 'm' ) ( 'E' | 'e' ) ':' ( WS )+ lineorstop STOP EOL\n if @input.peek( 1 ).between?( T__18, T__19 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__20, T__21 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__20, T__21 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__22, T__23 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__24, T__25 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__26, T__27 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__28, T__29 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n # at file 98:13: ( WS )+\n match_count_14 = 0\n while true\n alt_14 = 2\n look_14_0 = @input.peek( 1 )\n\n if ( look_14_0 == WS )\n alt_14 = 1\n\n end\n case alt_14\n when 1\n # at line 0:0: WS\n match( WS, TOKENS_FOLLOWING_WS_IN_cooktime_394 )\n\n else\n match_count_14 > 0 and break\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n eee = EarlyExit(14)\n\n\n raise eee\n end\n match_count_14 += 1\n end\n\n if @input.peek( 1 ).between?( T__30, T__31 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__24, T__25 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__32, T__33 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__12, T__13 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n match( T__34, TOKENS_FOLLOWING_T__34_IN_cooktime_429 )\n # at file 102:17: ( WS )+\n match_count_15 = 0\n while true\n alt_15 = 2\n look_15_0 = @input.peek( 1 )\n\n if ( look_15_0 == WS )\n look_15_1 = @input.peek( 2 )\n\n if ( syntactic_predicate?( :synpred32_Recipes ) )\n alt_15 = 1\n\n end\n\n end\n case alt_15\n when 1\n # at line 0:0: WS\n match( WS, TOKENS_FOLLOWING_WS_IN_cooktime_431 )\n\n else\n match_count_15 > 0 and break\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n eee = EarlyExit(15)\n\n\n raise eee\n end\n match_count_15 += 1\n end\n\n @state.following.push( TOKENS_FOLLOWING_lineorstop_IN_cooktime_434 )\n lineorstop10 = lineorstop\n @state.following.pop\n match( STOP, TOKENS_FOLLOWING_STOP_IN_cooktime_436 )\n match( EOL, TOKENS_FOLLOWING_EOL_IN_cooktime_438 )\n # syntactic predicate action gate test\n if @state.backtracking == 0\n # --> action\n value = ( lineorstop10 && @input.to_s( lineorstop10.start, lineorstop10.stop ) )\n # <-- action\n end\n\n success = true\n\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__, 5 )\n memoize( __method__, cooktime_start_index, success ) if @state.backtracking > 0\n\n end\n \n return value\n end",
"def analyze(string, equal = true) \n @i = 0\n state = 0\n return false if string == \"\"\n @@string = string if string.is_a? String\n unless string.is_a? Array\n unless balanced_brackets? string\n puts \"Sintax Error: unbalanced brackets\"\n return false \n end\n end\n token = @lexer.tokenize(string) unless string.is_a? Array\n token = string if string.is_a? Array\n while @i < token.size\n \n case state\n # beginning state\n when 0\n case token[@i].attribute\n when \"SUM_OPERATOR\"\n state = 1\n when \"VARIABLE\"\n state = 2\n when \"NUMBER\"\n state = 2\n when \"L_BRACE\"\n sizer = Sizer.new\n return false unless sizer.analyze(token[(@i+1)...token.size])\n @i += sizer.count + 1\n state = 2\n when \"KEYWORD\"\n case token[@i].me\n when \"mx:\"\n state = 6\n when \"integ:\"\n state = 7\n when \"shwvar:\"\n unless equal\n PrintError.reduced(token[@i],@@string)\n return false\n end\n state = 5\n when \"solve:\"\n state = 8\n when \"f:\"\n state = 4\n else\n if [\"t:\",\"det:\",\"norm:\",\"id_mx:\",\"shw:\"].include? token[@i].me then\n unless equal or token[@i].me != \"shw:\"\n PrintError.reduced(token[@i],@@string)\n return false\n end\n state = 3\n elsif not Tool.keys.include? token[@i].me then\n PrintError.unknown(token[@i],@@string)\n return false\n else\n PrintError.reduced(token[@i],@@string)\n return false\n end\n end\n else\n PrintError.default(token[@i],@@string)\n return false\n end\n \n # expecting numbers,variables, keywords, (\n when 1\n case token[@i].attribute\n when \"NUMBER\"\n state = 2\n when \"VARIABLE\"\n state = 2\n when \"L_BRACE\"\n sizer = Sizer.new\n return false unless sizer.analyze(token[(@i+1)...token.size])\n @i += sizer.count + 1\n state = 2\n when \"KEYWORD\"\n case token[@i].me\n when \"mx:\"\n state = 6\n when \"integ:\"\n state = 7\n when \"shwvar:\"\n state = 5\n when \"solve:\"\n state = 8\n when \"f:\"\n state = 4\n else\n if [\"t:\",\"det:\",\"norm:\",\"id_mx:\"].include? token[@i].me then\n state = 3\n elsif not Tool.keys.include? token[@i].me then\n PrintError.unknown(token[@i],@@string)\n return false\n else\n PrintError.reduced(token[@i],@@string)\n return false\n end\n end\n else\n PrintError.default(token[@i],@@string)\n return false\n end\n \n # expecting operators, )\n when 2\n case token[@i].attribute\n when \"OPERATOR\"\n state = 1\n when \"SUM_OPERATOR\"\n state = 1\n when \"EQUAL_OP\"\n if equal\n unless @i + 1 >= token.size\n sizer = Sizer.new\n return sizer.analyze(token[(@i+1)...token.size],false)\n end\n PrintError.missing_expression_after_equal(@i+1,@@string)\n return false\n else\n PrintError.default(token[@i],@@string)\n return false\n end\n when \"TO_FILE_OP\"\n unless equal\n PrintError.default(token[@i],@@string)\n return false\n end\n state = 4\n when \"R_BRACE\"\n return true\n else\n PrintError.default(token[@i],@@string)\n return false\n end\n \n # expecting only variables or numbers\n when 3\n case token[@i].attribute\n when \"VARIABLE\"\n state = 2\n when \"NUMBER\"\n state = 2\n else\n PrintError.default(token[@i],@@string)\n return false\n end\n state = 5 if token[@i-1].me == \"shw:\"\n \n # expects blocks (full chek) than nothing\n when 4\n return false unless check_block(token)\n state = 5\n \n # expects nothing\n when 5\n PrintError.default(token[@i],@@string)\n return false\n \n # checking mx arguments (full check)\n when 6\n case token[@i].attribute\n when \"KEYWORD\"\n if token[@i].me == \"from:\" then\n @i += 1\n unless @i < token.size\n PrintError.missing(token[@i-1],@@string)\n return false\n end\n return false unless check_block(token)\n state = 2\n else\n PrintError.missmatch(token[@i],@@string,\"keyword 'from:' or block\")\n return false\n end\n when \"QUOTES\"\n return false unless check_block(token)\n unless @i+1 >= token.size\n if token[@i+1].attribute == \"KEYWORD\" then\n @i += 1\n# unless @i < token.size\n# PrintError.missing(token[@i-1],@@string)\n# return false\n# end\n unless token[@i].me == \"as:\"\n PrintError.missmatch(token[@i],@@string,\"keyword 'as:' or operator\")\n return false\n end\n @i += 1\n unless @i < token.size\n PrintError.missing_general_string(token[@i-1].position+token[@i-1],@@string)\n return false\n end\n if token[@i].attribute == \"QUOTES\"\n return false unless check_block(token)\n else\n unless token[@i].attribute == \"VARIABLE\"\n PrintError.default(token[@i],@@string)\n return false \n end\n end\n end\n end\n state = 2\n end\n \n # checking integ arguments (full check)\n when 7 \n unless @i < token.size\n PrintError.missing(token[@i-1],@@string)\n return false\n end \n if token[@i].attribute == \"QUOTES\" then\n return false unless check_block(token)\n elsif token[@i].attribute != \"VARIABLE\" then\n PrintError.missmatch(token[@i],@@string,\"variable or block\")\n return false\n end\n @i += 1\n unless @i < token.size\n PrintError.missing_integ_range(token[@i-1].position+1,@@string)\n return false\n end\n return false unless check_block(token)\n @i += 1\n unless @i < token.size\n PrintError.numPoint_missing(token[@i-1].position+1,@@string)\n return false\n end\n unless @i + 1 >= token.size\n if token[@i+1].attribute == \"QUOTES\" then\n @i += 1\n return false unless check_block(token)\n end\n end\n state = 2\n \n # checking solve args (full check) \n when 8\n inner_state = 0\n while !(token[@i].attribute == \"EQUALS_TO\") and @i < token.size\n case inner_state \n when 0\n if token[@i].attribute == \"VARIABLE\" or token[@i].attribute == \"NUMBER\" then\n inner_state = 1\n elsif token[@i].attribute == \"L_BRACE\"\n sizer = Sizer.new\n return false unless sizer.analyze(token[(@i+1)...token.size])\n @i += sizer.count + 1\n else\n PrintError.unexpected_token_in_solve(token[@i],@@string)\n return false\n end\n when 1\n if token[@i].attribute == \"OPERATOR\" then\n inner_state = 0\n else\n PrintError.unexpected_token_in_solve(token[@i],@@string)\n return false\n end\n end\n @i += 1\n end \n state = 1 \n end\n @i += 1\n end\n \n unless state == 2 or state == 5 \n if token[@i-1].attribute == \"R_BRACE\" then\n tk = token[@i-2]\n else\n tk = token[@i-1]\n end \n PrintError.missing(tk,@@string)\n return false\n end\n return true\n end",
"def speed_benchmark(string, n)\n initialize()\n bm(15) do |test|\n test.report(\"reverse markdown:\") { n.times do; parse_string(string); initialize(); end; }\n end\n end",
"def chunk_char!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 14 )\n\n \n # - - - - main rule block - - - -\n # at line 68:3: (~ ( '>' | '<' | '#' | '`' | '\\\"' | '\\\\'' | '|' | '(' | ')' | '$' | ';' | ' ' | '?' | '*' | '~' | '\\\\\\\\' | '\\\\t' | '{' | '}' | '\\\\n' | '\\\\r' ) | '\\\\\\\\' . )\n alt_23 = 2\n look_23_0 = @input.peek( 1 )\n\n if ( look_23_0.between?( 0x0, 0x8 ) || look_23_0.between?( 0xb, 0xc ) || look_23_0.between?( 0xe, 0x1f ) || look_23_0 == 0x21 || look_23_0.between?( 0x25, 0x26 ) || look_23_0.between?( 0x2b, 0x3a ) || look_23_0 == 0x3d || look_23_0.between?( 0x40, 0x5b ) || look_23_0.between?( 0x5d, 0x5f ) || look_23_0.between?( 0x61, 0x7a ) || look_23_0.between?( 0x7f, 0xffff ) )\n alt_23 = 1\n elsif ( look_23_0 == 0x5c )\n alt_23 = 2\n else\n raise NoViableAlternative( \"\", 23, 0 )\n end\n case alt_23\n when 1\n # at line 68:5: ~ ( '>' | '<' | '#' | '`' | '\\\"' | '\\\\'' | '|' | '(' | ')' | '$' | ';' | ' ' | '?' | '*' | '~' | '\\\\\\\\' | '\\\\t' | '{' | '}' | '\\\\n' | '\\\\r' )\n if @input.peek( 1 ).between?( 0x0, 0x8 ) || @input.peek( 1 ).between?( 0xb, 0xc ) || @input.peek( 1 ).between?( 0xe, 0x1f ) || @input.peek(1) == 0x21 || @input.peek( 1 ).between?( 0x25, 0x26 ) || @input.peek( 1 ).between?( 0x2b, 0x3a ) || @input.peek(1) == 0x3d || @input.peek( 1 ).between?( 0x40, 0x5b ) || @input.peek( 1 ).between?( 0x5d, 0x5f ) || @input.peek( 1 ).between?( 0x61, 0x7a ) || @input.peek( 1 ).between?( 0x7f, 0xff )\n @input.consume\n else\n mse = MismatchedSet( nil )\n recover mse\n raise mse\n end\n\n\n\n when 2\n # at line 70:5: '\\\\\\\\' .\n match( 0x5c )\n match_any\n\n end\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 14 )\n\n end",
"def chunk_char!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in(__method__, 13)\n\n \n # - - - - main rule block - - - -\n # at line 62:3: (~ ( '>' | '<' | '#' | '`' | '\\\"' | '\\\\'' | '|' | '(' | ')' | '$' | ';' | ' ' | '?' | '*' | '~' | '\\\\\\\\' | '\\\\t' | '{' | '}' | '\\\\n' | '\\\\r' ) | '\\\\\\\\' . )\n alt_20 = 2\n look_20_0 = @input.peek(1)\n\n if (look_20_0.between?(0x0000, ?\\b) || look_20_0.between?(0x000B, ?\\f) || look_20_0.between?(0x000E, 0x001F) || look_20_0 == ?! || look_20_0.between?(?%, ?&) || look_20_0.between?(?+, ?:) || look_20_0 == ?= || look_20_0.between?(?@, ?[) || look_20_0.between?(?], ?_) || look_20_0.between?(?a, ?z) || look_20_0.between?(0x007F, 0xFFFF)) \n alt_20 = 1\n elsif (look_20_0 == ?\\\\) \n alt_20 = 2\n else\n nvae = NoViableAlternative(\"\", 20, 0)\n raise nvae\n end\n case alt_20\n when 1\n # at line 62:5: ~ ( '>' | '<' | '#' | '`' | '\\\"' | '\\\\'' | '|' | '(' | ')' | '$' | ';' | ' ' | '?' | '*' | '~' | '\\\\\\\\' | '\\\\t' | '{' | '}' | '\\\\n' | '\\\\r' )\n if @input.peek(1).between?(0x0000, ?\\b) || @input.peek(1).between?(0x000B, ?\\f) || @input.peek(1).between?(0x000E, 0x001F) || @input.peek(1) == ?! || @input.peek(1).between?(?%, ?&) || @input.peek(1).between?(?+, ?:) || @input.peek(1) == ?= || @input.peek(1).between?(?@, ?[) || @input.peek(1).between?(?], ?_) || @input.peek(1).between?(?a, ?z) || @input.peek(1).between?(0x007F, 0x00FF)\n @input.consume\n else\n mse = MismatchedSet(nil)\n recover(mse)\n raise mse\n end\n\n\n\n when 2\n # at line 64:5: '\\\\\\\\' .\n match(?\\\\)\n match_any\n\n end\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out(__method__, 13)\n\n end",
"def parse_line(line)\n # If the previous line didn't and a logical line, we're not going to start one. If it did,\n # we're indeed going to start a new logical line\n @state[:ll_start] = @state[:ll_end]\n\n # We will start with the assumption that we're going to end the current logical line. We may layer\n # find out that we did not, in fact, do so.\n @state[:ll_end] = true\n\n # Reset the line continuator flag the the last line may have set to true\n @state[:line_continuator] = false\n\n # Find the first non-(space/tab) character\n index = 0\n while index < line.length && [\" \", \"\\t\"].include?(line[index])\n index += 1\n end\n @state[:indent_string] = line[0...index]\n\n # Iterate over the line's characters as long as there are any. We use different iteration\n # methods depending on whether we're inside a string or not\n index = 0\n while index < line.length\n if @state[:in_string].nil?\n index = parse_characters_normal(line, index)\n else\n index = parse_characters_in_string(line, index)\n end\n end\n\n # We have reached the end of the line. Decide whether or not the logical line ends here.\n @state[:ll_end] = @state[:in_string].nil? && @state[:open_braces] == 0 && !@state[:line_continuator]\n end",
"def parse(string)\n#`stack` will hold the intermediate representation\n#the first element is the acctual representation, every new scope created by a nested pair of brackets is then added afterwards while the parser is in it. Thus we can allways append our tokens to `stack.last` and return to the parent scope by `stack.pop`.\n stack = [[]]\n#Remove all non-brainfuck instruction characters (they are considered to be comments in brainfuck)\n string = string.gsub(/[^\\[\\]\\-+,.<>]/,\"\")\n string.split(\"\").each do |tok|\n case tok\n #When we see an opening bracket we create a new scope and add it to the current scope\n when \"[\"\n new_scope = []\n stack.last << new_scope\n #Then we make this scope the current by appending it to the stack\n stack.push(new_scope)\n #When we see a closing bracket we return to the last scope by removing the current scope from the stack\n when \"]\"\n stack.pop\n #All other characters are simply added to the current scope\n else\n stack.last << tok\n end\n end\n #return the outmost scope\n return stack.first\n end",
"def tokenize(str)\n state = @start_state\n lexeme = ''\n tokens = []\n # Append our end of file marker to the string to be tokenized\n str += \"%c\" % @lex_eof\n str.each_byte do\n |char|\n char_as_str = \"%c\" % char\n loop do\n match = @charsets.find {\n |id, match|\n (match.kind_of? Regexp) ? \\\n (match =~ char_as_str) : (match.include? char)\n } || [@others_key, @charsets[@others_key]] or \\\n raise InvalidLexeme\n\n # Look for the action matching our current state and the\n # character set id for our current char.\n action = @s_trans[state][match.first] or raise LexerFailure\n\n # If found, action contains our hash of actions, e.g.\n # {:next_s_backtrack => :s_operator, :token => :tok_int}\n puts \"#{char==@lex_eof?'<eof>':char_as_str}: \" \\\n \"#{state.inspect} - #{action.inspect}\" if $DEBUG == 1\n\n # Build up the lexeme unless we're backtracking or skipping\n lexeme << char_as_str if action.has_key? :next_s\n\n tokens << [action[:token], lexeme.dup] && lexeme = '' if \\\n action.has_key? :token\n\n # Set the next state, or - when there is no specified next\n # state - we've finished, so return the tokens.\n state = action[:next_s] || action[:next_s_skip] ||\n action[:next_s_backtrack] or\n return tokens << [:tok_end, nil]\n\n break unless action.has_key? :next_s_backtrack\n end\n end\n tokens\n end",
"def parse_input (input_string)\n lines = input_string.split(/\\n/)\n\n state = :reading_map\n\n rover_x_start = 0\n rover_y_start = 0\n rover_facing_start = 0\n\n lines.each do |line|\n # drop empty lines\n next unless /(\\w)+/ =~ line\n\n case state\n when :reading_map\n match = /^\\s*(\\d+)\\s+(\\d+)\\s*$/.match(line)\n raise ArgumentError.new(\"Invalid map data >>#{line}<<\") unless match\n\n x_size = $1.to_i\n y_size = $2.to_i\n\n # the format is not the size, it's the greatest valid index\n init_map(x_size,y_size)\n\n state = :reading_rover_init\n\n when :reading_rover_init\n match = /^\\s*(\\d+)\\s+(\\d+)\\s+([NSWE])\\s*$/.match(line)\n # match = line.match /^\\s*(\\d+)\\s+(\\d+)\\s+([NSWE])\\s*$/\n raise ArgumentError.new(\"Invalid rover init >>#{line}<<\") unless match\n\n rover_x_start = $1.to_i\n rover_y_start = $2.to_i\n rover_facing_start = $3\n\n state = :reading_rover_instructions\n when :reading_rover_instructions\n match = /^\\s*([LRM]+)\\s*$/.match(line)\n raise ArgumentError.new(\"Invalid rover init >>#{line}<<\") unless match\n\n rover_instructions = $1\n\n add_rover(rover_x_start,rover_y_start,rover_facing_start,rover_instructions)\n\n state = :reading_rover_init\n end\n end\n\n end",
"def lex(expr)\n tokens = []\n i = -1\n while i < expr.size - 1\n tok ||= \"\"\n i += 1\n\n case expr[i].chr\n when '[', ']', '{', '}', ':', ','\n tokens << tok if tok.size > 0\n tokens << expr[i].chr\n tok = \"\"\n # String processing\n when '\"'\n raise \"Unexpected quote\" if tok.size > 0\n len = 1\n escaped = false\n while (len + i) < expr.size\n break if expr[len + i].chr == '\"' and not escaped\n if escaped\n case expr[len + i].chr\n when '\"', '/', '\\\\', 'b', 'f', 'n', 'r', 't', 'u'\n else\n raise \"Unable to escape #{expr[len + i].chr}\"\n end\n end\n escaped = expr[len + i].chr == \"\\\\\"\n len += 1\n end\n raise \"No matching endquote for string\" if (len + i) > expr.size\n tokens << convert_unicode(expr.slice(i, len+1))\n i += len\n # Number processing\n when '-', /[0-9]/\n len = 0\n while (len + i) < expr.size and /[0-9eE+-.]/.match(expr[len + i].chr)!= nil\n len += 1\n end\n num = expr.slice(i, len)\n\n # Verify syntax of the number using the JSON state machine\n raise \"Invalid number #{num}\" if /[-]?([1-9]|(0\\.))[0-9]*[eE]?[+-]?[0-9]*/.match(num) == nil\n\n tokens << num\n i += len - 1\n # Skip whitespace\n when ' ', '\\t'\n else\n tok << expr[i].chr\n end\n end\n tokens << tok if tok.size > 0\n tokens\n end",
"def parse(addr)\n state = :nextline\n bytes = []\n line = []\n token = ''\n\n @basic.upcase.each_char do |c|\n if c == \"\\n\"\n state = :nextline\n next\n end\n\n if state == :nextline\n unless token.empty?\n token.codepoints.each{|p| bytes += [PETSCII[p]]}\n token = ''\n end\n\n unless bytes.empty?\n bytes += [0]\n addr += 1\n end\n\n addr += 2\n bytes += [addr.ls_byte, addr.ms_byte]\n state = :linenum\n end\n\n if state == :linenum\n if c.match(/\\d/)\n token += c\n addr += 1\n else\n raise BasicError, 'Each line has to start with a line number' if token.empty?\n\n lineno = token.to_i\n raise BasicError, 'Line number out of range' unless (lineno >= 0 and lineno <= 65535)\n\n bytes += [lineno.ls_byte, lineno.ms_byte]\n addr += 2\n state = :out\n token = ''\n\n next if c == ' '\n end\n end\n\n if state == :out\n if c == '\"'\n bytes += [PETSCII['\"'.ord]]\n addr += 1\n state = :in\n\n next\n elsif c == ' '\n unless token.empty?\n token.codepoints.each{|p| bytes += [PETSCII[p]]}\n token = ''\n end\n\n bytes += [PETSCII[' '.ord]]\n addr += 1\n elsif BASIC.has_key? c\n token.codepoints.each{|p| bytes += [PETSCII[p]]} unless token.empty?\n bytes += [BASIC[c]]\n addr += 1\n token = ''\n else\n raise BasicError, 'Unknown character' unless PETSCII.has_key? c.codepoints.to_a.first\n\n token += c\n addr += 1\n\n if BASIC.has_key? token\n bytes += [BASIC[token]]\n token = ''\n end\n end\n end\n\n if state == :in\n raise BasicError, 'Unknown character' unless PETSCII.has_key? c.codepoints.to_a.first\n\n token += c\n addr += 1\n state = :out if c == '\"'\n end\n end\n\n unless token.empty?\n token.codepoints.each{|p| bytes += [PETSCII[p]]}\n bytes += [0]\n end\n\n bytes += [0, 0]\n end",
"def nextToken\n valid = false\n while !valid\n valid = true\n whitespace = false\n if @input[@index] == \"\\n\" || @index >= @input.length - 1\n @input = gets\n if @input == nil\n return Token.new(Token::EOF, \"END OF PROGRAM\")\n else\n @input.chomp.strip\n end\n @index = 0\n else\n @index +=1\n while(@input[@index] == \" \")\n @index +=1\n end\n end\n current_char = @input[@index]\n\n #check lcurly\n if (current_char =~ /{/)\n token = Token.new(LCURLY, current_char)\n #check rcurly\n elsif (current_char =~ /}/)\n token = Token.new(RCURLY, current_char)\n #check semi\n elsif (current_char =~ /;/)\n token = Token.new(SEMI, current_char)\n #check lbrack\n elsif (current_char =~ /[\\[]/)\n token = Token.new(LBRACK, current_char)\n #check rbrack\n elsif (current_char =~ /[\\]]/)\n token = Token.new(RBRACK, current_char)\n #check arrow\n elsif (current_char =~ /-/)\n #NOT DONE\n token = Token.new(ARROW, @input[@index] + @input[@index+1])\n @index +=1\n #check equals\n elsif (current_char =~ /=/)\n token = Token.new(EQUALS, current_char)\n #check comma\n elsif (current_char =~ /,/)\n token = Token.new(COMMA, current_char)\n #is_int\n elsif (current_char =~ /[0-9]/)\n token = Token.new(INT, current_char)\n #is_string\n elsif (current_char =~ /\"/)\n token = read_string\n #is_id or digraph or subgraph\n elsif (current_char =~ /[a-zA-Z]/)\n token = read_id\n #is_whitespace\n elsif (current_char =~ /[\\s\\t\\r\\n\\f]/)\n valid = false\n white_space = true\n #Illegal char\n else\n valid = false\n end\n if valid\n return token\n else\n if !white_space\n puts \"illegal char: #{current_char}\"\n end\n end\n end\n end",
"def parse_string string, variables={}, verbose=false\n s = string.dup\n recounter = 0\n while /\\(\\S|\\S\\)/.match(s)\n s.gsub!(/([()])([A-Zn(]{1})/, \"\\\\1 \\\\2\")\n s.gsub!(/([A-Zt)]{1})([()])/, \"\\\\1 \\\\2\")\n if (recounter += 1) >= 5\n puts \"Can't parse in less than 5 steps. Try entering the formula with spaces between parentheses\"\n raise ArgumentError\n end\n end\n operators = {\"not\" => Not.new(), \"or\" => Or.new(), \"and\" => And.new(), \"->\" => If.new(), \"<->\" => Iff.new(), \"(\" => LeftParen.new()}\n sentinel = Sentinel.new\n output_queue = OutputQueue.new()\n operator_stack = [sentinel]\n# wff_stack = []\n# vars = []\n elements = s.split\n elements.each do |e|\n if (\"A\"..\"Z\").include? e\n variables[e] = Variable.new(e) unless variables.has_key? e\n output_queue << variables[e]\n# print \"Vars after adding #{e}: \\t\" + output_queue.to_s + \"\\n\"\n elsif [\"not\", \"and\", \"or\", \"->\", \"<->\"].include? e\n while (not operator_stack[-1].is_a? Sentinel) and operator_stack[-1] > operators[e]\n output_queue << operator_stack.pop\n end\n operator_stack << operators[e]\n# print \"OP after adding #{e}: \\t\" + operator_stack.to_s + \"\\n\"\n elsif e == \"(\"\n operator_stack << operators[e]\n elsif e == \")\"\n until operator_stack[-1].is_a? LeftParen or operator_stack[-1].is_a? Sentinel\n output_queue << operator_stack.pop\n end\n# print \"After paren\"\n operator_stack.pop\n# print operator_stack.to_s + \"\\n\"\n else\n raise ArgumentError\n end\n end\n# print operator_stack\n# print output_queue\n until operator_stack[-1].is_a? Sentinel\n x = operator_stack.pop\n if x.is_a? LeftParen\n raise MismatchedParenthesis\n else\n output_queue << x\n end\n end\n\n# print \"\\n\" + output_queue.map{|x| x.to_s}.join(\"\\t\") + \"\\n\"\n\n return variables, output_queue.get_wff\n\nend",
"def minutes\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 25 )\n minutes_start_index = @input.index\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 \n end\n # at line 304:10: ( 'M' | 'm' ) ( 'I' | 'i' ) ( 'N' | 'n' ) ( 'U' | 'u' ) ( 'T' | 't' ) ( 'E' | 'e' ) ( 'S' | 's' )\n if @input.peek( 1 ).between?( T__40, T__41 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__24, T__25 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__34, T__35 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__14, T__15 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__16, T__17 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__28, T__29 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n if @input.peek( 1 ).between?( T__38, T__39 )\n @input.consume\n @state.error_recovery = false\n else\n @state.backtracking > 0 and raise( ANTLR3::Error::BacktrackingFailed )\n\n mse = MismatchedSet( nil )\n raise mse\n end\n\n\n\n success = true\n\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__, 25 )\n memoize( __method__, minutes_start_index, success ) if @state.backtracking > 0\n\n end\n \n return \n end",
"def parse_line\n s0 = @scanner.pos\n match_spaces\n s2 = parse_te\n if s2 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n match_spaces\n s4 = @scanner.pos\n s5 = parse_fugou\n if s5 == :failed\n @scanner.pos = s4\n s4 = :failed\n else\n s6 = parse_from\n if s6 == :failed\n @scanner.pos = s4\n s4 = :failed\n else\n @reported_pos = s4\n s4 = transform_teban_fugou_from(s2, s5, s6)\n end\n end\n if s4 == :failed\n s4 = @scanner.pos\n s5 = []\n s6 = match_regexp(/[^\\r\\n ]/)\n while s6 != :failed\n s5 << s6\n s6 = match_regexp(/[^\\r\\n ]/)\n end\n @reported_pos = s4\n s4 = s5.join\n end\n if s4 == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n match_spaces\n s6 = parse_time\n s6 = nil if s6 == :failed\n match_str('+')\n if parse_nl == :failed\n @scanner.pos = s0\n s0 = :failed\n else\n @reported_pos = s0\n s0 = { 'move' => s4, 'time' => s6 }\n end\n end\n end\n s0\n end",
"def run str\n\t\t@input ||= ''\n\t\t@level += str.scan(LEVEL_UP).length\n\t\t@level -= str.scan(/(^|\\s)end($|\\s)/).length # Will probably fail with a character chain\n\t\t@input += str + \"\\n\"\n\t\tif @level <= 0\t\n\t\t\ttmp = input\n\t\t\treset\n\t\t\teval tmp, context \n\t\tend\n\tend",
"def parse(source_buffer); end",
"def run(source, until_token = :invalid, token_count = nil)\n @at_end = false\n @source = source\n @reader = source.each_char\n\n read_next\n\n while token_count == nil || token_count > 0\n skip_whitespace\n current = @marker.character\n break unless current\n\n token = Token.new\n token.kind = :invalid\n token.from = @marker.source_index\n token.position = @marker.position.dup\n\n case current\n when '\"', '\\''\n read_string(token)\n\n when '0'\n case peek_next\n when 'x', 'X', 'b', 'B' then read_base_number(token)\n else read_number(token)\n end\n\n when '1', '2', '3', '4', '5', '6', '7', '8', '9'\n read_number(token)\n\n # dot, double dot, triple dot, and floats beginning with a dot\n when '.'\n token.kind = :dot\n case peek_next\n when '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' then read_number(token)\n when '.'\n read_next\n token.kind = :double_dot\n\n if peek_next == '.'\n read_next\n token.kind = :triple_dot\n end\n\n token.value = Token::DESCRIPTORS[token.kind]\n else\n token.value = Token::DESCRIPTORS[token.kind]\n end\n\n when '_', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',\n 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',\n 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'\n read_word(token)\n\n when \"\\n\"\n token.value = current\n token.kind = :newline\n\n when '?', '#', '@', '$', '%', '(', ')', '[', ']', '{', '}', '^', '~', '`', ',', ';'\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n\n when '=', '|', '&', ':', '+', '*'\n current << read_next if peek_next == current\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n\n when '!'\n current << read_next if peek_next == '='\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n\n when '>', '<'\n case peek_next\n when '=', current then current << read_next\n end\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n\n when '-'\n case peek_next\n when '>', current then current << read_next\n # when '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'\n # read_number(token)\n # token.value = '-' + token.value\n end\n # if token.kind == :invalid\n token.value = current\n token.kind = PUNCTUATION_STRINGS[current]\n # end\n\n when '/'\n case peek_next\n when '/' then read_line_comment(token)\n when '*' then read_block_comment(token)\n else\n token.value = Token::DESCRIPTORS[token.kind = :slash]\n read_next\n end\n\n end # case current\n\n token.to = @marker.source_index\n last_kind = token.kind\n unless (@skip_comments && token.comment?) || (@skip_newlines && token.newline?)\n if last_kind != :invalid\n @tokens << token\n yield token if block_given?\n else\n raise RuntimeError, \"#{token.position} Invalid token: #{token.inspect}\"\n end\n end\n\n break if until_token == last_kind\n\n read_next\n token_count -= 1 unless token_count.nil?\n end # while current && token_count > 0\n\n @source = nil\n @reader = nil\n\n self\n end",
"def tokenize( text, current_line_number = 0 )\n return '' if (@line_timeout > 0) && (current_line_number > @line_timeout)\n token = ''\n sidx = get_start_index( text )\n if ( sidx && (text.size >= sidx.to_i) )\n eidx = get_end_index( text )\n token = ( text[ sidx .. eidx ] ).strip if eidx\n end\n# DEBUG\n# puts \"-- after tokenize: \" << (@computed_start ? \"cached: (#{@computed_start}..\" : 'cached: (nil..') << (@computed_end ? \"#{@computed_end})\" : 'nil)')\n token\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the number of atoms in a sequence. If type is given, return the number of specific atoms in a sequence.
|
def total_atoms(type=nil)
if !type.nil?
type = type.to_sym
if /^(?:C|H|O|N|S){1}$/ !~ type.to_s
raise ArgumentError, "type must be C/H/O/N/S/nil(all)"
end
end
num_atom = {:C => 0,
:H => 0,
:O => 0,
:N => 0,
:S => 0}
each_aa do |aa|
ATOM[aa].each do |t, num|
num_atom[t] += num
end
end
num_atom[:H] = num_atom[:H] - 2 * (amino_acid_number - 1)
num_atom[:O] = num_atom[:O] - (amino_acid_number - 1)
if type.nil?
num_atom.values.inject(0){|prod, num| prod += num }
else
num_atom[type]
end
end
|
[
"def count_with_type(type)\n with_type(type).length\n end",
"def amount(type)\n return list(type).length\n end",
"def countAtoms(seq)\n\t\t\t\to = 0\n\t\t\t\tn = 0\n\t\t\t\tc = 0\n\t\t\t\th = 0\n\t\t\t\ts = 0\n\t\t\t\tp = 0\n\t\t\t\tse = 0\n\t\t\t\tseq.each_char do |aa|\n\t\t\t\t\to = o + MS::Feature::AA::ATOM_COUNTS[aa][:o]\n\t\t\t\t\tn = n + MS::Feature::AA::ATOM_COUNTS[aa][:n]\n\t\t\t\t\tc = c + MS::Feature::AA::ATOM_COUNTS[aa][:c]\n\t\t\t\t\th = h + MS::Feature::AA::ATOM_COUNTS[aa][:h]\n\t\t\t\t\ts = s + MS::Feature::AA::ATOM_COUNTS[aa][:s]\n\t\t\t\t\tp = p + MS::Feature::AA::ATOM_COUNTS[aa][:p]\n\t\t\t\t\tse = se + MS::Feature::AA::ATOM_COUNTS[aa][:se]\n\t\t\t\tend\n\t\t\t\treturn o,n,c,h,s,p,se\n\t\t\tend",
"def count(type, state)\n sum = 0\n @jiras.count { |j| next unless j.type == type && j.state == state; sum += 1 }\n sum\n end",
"def count_items(type = Item)\n self.count { |x| x.kind_of? type }\n end",
"def number_of(type)\n game_entities.select{|entity| entity.class == type }.size\n end",
"def count_sections(type = nil)\n if type\n sections.all.select { |section| section.type == type }.size\n else\n sections.size\n end\n end",
"def inviters_count_by_type(type)\n self.inviters.by_type(type).count\n end",
"def abi_size_of(type)\n C.abi_size_of_type(self, type)\n end",
"def get_job_count(type='scanner')\n job_count = 0\n framework.jobs.each do |k, j|\n if j.name =~ /#{type}/\n job_count = job_count + 1\n end\n end\n return job_count\n end",
"def howmany(type)\n @meals.each do |meal|\n if meal.type == type\n return meal.quantity\n end\n end\n return 0\n end",
"def count_tokens(type)\n token_tuples(type).count\nend",
"def _get_job_count(type='scanner')\n job_count = 0\n framework.jobs.each do |k, j|\n if j.name =~ /#{type}/\n job_count = job_count + 1\n end\n end\n return job_count\n end",
"def count_element_types\n remainder = denominator = 0\n @sequence.each do |element|\n element == @sequence.last ? remainder += 1 : denominator += 1\n end\n return remainder, denominator\n end",
"def invitees_count_by_type(type)\n self.invitees.by_type(type).count\n end",
"def acidic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n ACIDIC_AMINO_ACIDS.each do |acidic|\n if comp[acidic]\n count += comp[acidic]\n end\n end\n return count\n end",
"def count\n @type_variants.values.reduce(0) { |m, o| m + o.size }\n end",
"def bit_size_of(type)\n C.size_of_type_in_bits(self, type)\n end",
"def size\n atoms.size\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the number of nitrogens.
|
def num_nitro
@num_nitro ||= total_atoms :N
end
|
[
"def number_of_occurrences\n return @number_of_occurrences\n end",
"def number_of_concept_genres(login=nil)\n count_by_frbr(login, :has_as_its_genre, :how_many_concepts?) \n end",
"def n_itens\n n = 0\n self.produtos_quantidades.each { |c| n += c.qtd }\n return n\n end",
"def count\n count = 0\n\n each do |node|\n count += 1\n end\n\n return count\n end",
"def getNbRecompense\n return 0\n end",
"def number_of_improvisors(login=nil)\n count_by_frbr(login, :is_improvised_by, :how_many_roles?) \n end",
"def number_of_genred_resources(login=nil)\n count_by_frbr(login, :describes_the_genre_of, :how_many_resources?) \n end",
"def number_of_tickets()\n tickets_bought = self.tickets\n return tickets_bought.length\n end",
"def no_of_hops\n @hops\n end",
"def num_claims\n nclm = 0\n\n if b570 = @doc.at_xpath(\"//570\")\n b577 = b570.at_xpath(\".//577\")\n nc = extract_inner_text(b577)\n nclm = nc.to_i unless nc.empty?\n end\n\n nclm\n end",
"def reputation_count\n\t\t@repcount ||= self.reputations.size\n\tend",
"def count_no\n rsvp.no.count\n end",
"def number_of_bottles\n bottles = self.line_items.inject(0) {|bottles, line_item| bottles + line_item.quantity}\n end",
"def number_of_reviews\n recipe_reviews.size\n end",
"def count\n number_of_trees + number_of_networks\n end",
"def number_of_releasers(login=nil)\n count_by_frbr(login, :is_released_by, :how_many_roles?) \n end",
"def number_of_hops\n @hops\n end",
"def count_item\n count = 0\n @g_net.each do |followers|\n count += 1 unless !followers or followers.empty?\n end\n count\n end",
"def number_of_occurrences=(value)\n @number_of_occurrences = value\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the number of oxygens.
|
def num_oxygen
@num_oxygen ||= total_atoms :O
end
|
[
"def length\n number_of_otus\n end",
"def num_genotypes()\n @genotypes.size\n end",
"def number_of_occurrences\n return @number_of_occurrences\n end",
"def nb_opinions() opinion_ids.size end",
"def shape_count\r\n \r\n return @shapes.size\r\n\r\n end",
"def number_of_nodes\n @nodes.length\n end",
"def shape_count\n @shapes.size\n end",
"def class_count\n\t\t@osclasses.size\n\tend",
"def node_count\n @nodes.length\n end",
"def shape_count\n\t\treturn @shapes.length\n\tend",
"def num_nitro\n @num_nitro ||= total_atoms :N\n end",
"def num_gears\n num = 0\n group_instances.each { |g| num += g.gears.count}\n num\n end",
"def count_robots_on_world\n robots.count if robots\n end",
"def graph_count\n @hoGraphs.size\n end",
"def size\n @components.values.inject(0) { |component_count, attribute| component_count + attribute.size }\n end",
"def count\n return line_points.count\n end",
"def num_generations\n @generations.size - 1\n end",
"def count\n @atlas.count\n end",
"def size() \n return @n_objects\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return the number of sulphurs.
|
def num_sulphur
@num_sulphur ||= total_atoms :S
end
|
[
"def num_snps()\n @snps.size\n end",
"def spicy_count\n self.spicies.size\n end",
"def number_llamas\n count\n end",
"def no_of_hops\n @hops\n end",
"def noOfStones()\r\n no = 0\r\n @field.each{\r\n |i|\r\n if i == @turn\r\n no += 1\r\n end\r\n\r\n }\r\n return no\r\n end",
"def noOfStones()\r\n no = 0\r\n @field.each{\r\n |i|\r\n if i == @turn\r\n no += 1\r\n end\r\n\r\n }\r\n return no\r\n end",
"def num_shelf\n\t\tputs \"Library has #{@shelves.length} shelves\"\n\tend",
"def number_of_hops\n @hops\n end",
"def count\n @lights.reduce(0) { |memo, row| memo + row.count { |c| c } }\n end",
"def num_strands\n @size\n end",
"def count \n trips.length\n end",
"def smells_count\n smells.length\n end",
"def count\n 0\n end",
"def fish_count()\n return @fish.length()\n end",
"def state_count() @states.size end",
"def smells_count\n smells.length\n end",
"def fish_count\n return @fish_in_river.count\n end",
"def num_interns\n prev_interns = self.interns.count\n self.sponsor_four.nil? ? (prev_interns) : (prev_interns + self.sponsor_four)\n end",
"def size\n # gets only the seats from the first round\n starting_seats.select{ |s| s.round == 0 }.size\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Calculate molecular weight of an AA sequence. _Protein Mw is calculated by the addition of average isotopic masses of amino acids in the protein and the average isotopic mass of one water molecule._
|
def molecular_weight
@mw ||= begin
mass = WATER_MASS
each_aa do |aa|
mass += AVERAGE_MASS[aa.to_sym]
end
(mass * 10).floor().to_f / 10
end
end
|
[
"def get_prot_mass(prot_seq)\r\n weights = {\"A\" =>71.03711,\"C\" => 103.00919,\"D\" => 115.02694,\"E\" => 129.04259,\"F\" => 147.06841,\r\n \"G\" => 57.02146,\"H\" => 137.05891,\"I\" => 113.08406,\"K\" => 128.09496,\"L\" => 113.08406,\r\n \"M\" => 131.04049,\"N\" => 114.04293,\"P\" => 97.05276,\"Q\" => 128.05858,\"R\" => 156.10111,\r\n \"S\" => 87.03203,\"T\" => 101.04768,\"V\" => 99.06841,\"W\" => 186.07931,\"Y\" => 163.06333,\r\n \"H2O\" => 18.01056 }\r\n total_w = 0\r\n prot_seq.each_char do |ac|\r\n total_w += weights[ac]\r\n end\r\n return (total_w.round(3))\r\nend",
"def dsDNA_molecular_weight(length)\n length * AVG_MW_BP + 36.04\n end",
"def mass(weight)\n return weight / FREE_FALL_ACCELERATION\n end",
"def weight\n @weight ||= @combinations.inject(0) do |sum, combination|\n sum + combination.weight\n end\n end",
"def total_weight\n @total_weight ||= hypotheses.inject( 0 ) { |sum,h| sum + h.weight }\n end",
"def weight(text)\n weight = @emphasis[:multiplier]\n\n if text.length >= @emphasis[:long_words_threshold]\n weight *= @emphasis[:long_words]\n end\n\n if text[0,1] == text[0,1].upcase\n weight *= @emphasis[:upper_case]\n end\n\n weight += bonus(text)\n weight += vowels(text)\n weight + consonants(text)\n end",
"def word_weighted_average(word, type)\n basic_prob = word_prob(word, type)\n\n totals = total_word_count(word)\n\n (@weight * @assumed_prob + totals * basic_prob) / (@weight + totals)\n end",
"def weight_percentage( weight )\n (weight / self.bin_mass) * 100.0\n end",
"def weight(text)\n weight = @emphasis[:multiplier]\n\n if text.length >= @emphasis[:long_words_threshold]\n weight *= @emphasis[:long_words]\n end\n\n if text[0,1] == text[0,1].upcase\n weight *= @emphasis[:upper_case]\n end\n\n weight += vowels(text)\n weight += consonants(text)\n weight\n end",
"def weighted_average\n mzs.zip(intensities).inject(0.0) {|sum,pair| sum += pair[0]*pair[1] } / intensities.reduce(:+)\n end",
"def alpha_acid_mg_litre\n ((send(:alpha_acid_percentage)/100.0) * send(:weight_grams) * 1000.0) / send(:post_boil_volume_litres)\n end",
"def weighted_probability(word)\n word = (Word === word ? word : get(word))\n\n p = BigDecimal.new(1)\n p = p * probability(word)\n p = p * file_probability(word, 1)\n #p = p * lexicon_weight(word)\n #p = p * weight_length(word)\n #p = p * weight_stem(word)\n #p = p * weight_plural(word)\n p\n end",
"def weight\n # TODO: auto unit conversion\n measurement(8).try(:measurement)\n end",
"def weight\n count / name.length\n end",
"def proteinasCalculo()\n\n proteinas = 0\n index = 0\n sumaTotalGramos = 0\n @listaGramos.each { | gr | sumaTotalGramos += gr }\n @listaAlimentos.each do | x |\n index += 1\n y = @listaGramos.pos( index )\n proteinas += ( ( x.proteinas / 100 ) * y )\n end\n (proteinas * 100 / sumaTotalGramos).round()\n end",
"def weight\n weight = 0\n self.order_line_items.each do |item|\n weight += item.quantity * item.product.weight\n end\n return weight\n end",
"def calc_total_weight\n 0\n end",
"def total_weight\r\n\t\titems.inject(0.0) { |sum, i| sum + i.total_unit_weight * i.quantity }\r\n\tend",
"def mass\n convert(self, :length) * area * convert(material, :density)\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Claculate theoretical pI for an AA sequence with bisect algorithm. pK value by Bjelqist, et al. is used to calculate pI.
|
def theoretical_pI
charges = []
residue_count().each do |residue|
charges << charge_proc(residue[:positive],
residue[:pK],
residue[:num])
end
round(solve_pI(charges), 2)
end
|
[
"def p(i, j, k)\n state = pick_state(i)\n n = neighbours(i, k)\n if n.include?(j) then\n this_move_value = 0.0\n other_possible_moves_summed_value = 0.0\n state.transaction do\n this_move_value = state[:trails][[i, j]]\n other_possible_moves_summed_value = n.inject(0){|sum, n| sum + (state[:trails][[i, n]]**@alpha)*(heuristic_value(i, n)**@beta)}\n end\n probability = (this_move_value**@alpha)*(heuristic_value(i, j)**@beta)/ (other_possible_moves_summed_value)\n return probability\n else\n return 0.0\n end\n end",
"def p(i, j, k)\n n = neighbours(i, k)\n if n.include?(j) then\n this_move_value = 0.0\n other_possible_moves_summed_value = 0.0\n @state.transaction do\n this_move_value = @state[:trails][[i, j]]\n other_possible_moves_summed_value = n.inject(0){|sum, n| sum + (@state[:trails][[i, n]]**@alpha)*(heuristic_value(i, n)**@beta)}\n end\n probability = (this_move_value**@alpha)*(heuristic_value(i, j)**@beta)/ (other_possible_moves_summed_value)\n return probability\n else\n return 0.0\n end\n end",
"def k(p) (p[0]+1)*(p[1]+1) end",
"def pa(_a); Array.new(@k){|k| pka(k, _a) }.sum; end",
"def solve_pI charges\n state = {\n :ph => 0.0,\n :charges => charges,\n :pI => nil,\n :ph_prev => 0.0,\n :ph_next => 14.0,\n :net_charge => 0.0\n }\n error = false\n # epsilon means precision [pI = pH +_ E]\n epsilon = 0.001\n\n loop do\n # Reset net charge\n state[:net_charge] = 0.0\n # Calculate net charge\n state[:charges].each do |charge_proc|\n state[:net_charge] += charge_proc.call state[:ph]\n end\n\n # Something is wrong - pH is higher than 14\n if state[:ph] >= 14.0\n error = true\n break\n end\n\n # Making decision\n temp_ph = 0.0\n if state[:net_charge] <= 0.0\n temp_ph = state[:ph]\n state[:ph] = state[:ph] - ((state[:ph] - state[:ph_prev]) / 2.0)\n state[:ph_next] = temp_ph\n else\n temp_ph = state[:ph]\n state[:ph] = state[:ph] + ((state[:ph_next] - state[:ph]) / 2.0)\n state[:ph_prev] = temp_ph\n end\n\n if (state[:ph] - state[:ph_prev] < epsilon) &&\n (state[:ph_next] - state[:ph] < epsilon)\n state[:pI] = state[:ph]\n break\n end\n end\n\n if !state[:pI].nil? && !error\n state[:pI]\n else\n raise \"Failed to Calc pI: pH is higher than 14\"\n end\n end",
"def icc_1_k_ci(alpha=0.05)\n per=1-(0.5*alpha)\n fu=icc_1_f.f*Distribution::F.p_value(per, @df_wt, @df_bt)\n fl=icc_1_f.f.quo(Distribution::F.p_value(per, @df_bt, @df_wt))\n [1-1.quo(fl), 1-1.quo(fu)]\n end",
"def solution(a, b, k)\n first_dividend = a\n remainder = first_dividend%k\n\n while remainder != 0 && first_dividend <= b do\n first_dividend += 1\n remainder = first_dividend%k\n end\n\n remainder == 0 ? (b - first_dividend) / k + 1 : 0\nend",
"def p_value(pr,k)\n GSL::Cdf::chisq_Pinv(pr.to_f,k.to_i)\n end",
"def prob\r\n self.probability(self.k)\r\n end",
"def icc_1_1_ci(alpha=0.05)\n per=1-(0.5*alpha)\n \n fu=icc_1_f.f*Distribution::F.p_value(per, @df_wt, @df_bt)\n fl=icc_1_f.f.quo(Distribution::F.p_value(per, @df_bt, @df_wt))\n \n [(fl-1).quo(fl+k-1), (fu-1).quo(fu+k-1)]\n end",
"def get_AIBC(i)\n @@tam = @medidas.length\n if i >= @@tam\n return 0\n else\n return (((@medidas[i] - @medidas[0]) + (@medidas[i - 1] - @medidas[0])) / 24) + get_AIBC(i + 1)\n end\n end",
"def probability(*k)\r\n sum = 0\r\n karr = k.map{ |val| val.respond_to?(:to_a) ? val.to_a : val}\r\n karr.flatten!\r\n karr.each do |k_val| \r\n sum += self.coefficient(k_val) * ((self.p) ** (k_val)) * (1 - self.p) ** (n - k_val)\r\n end\r\n sum.to_f\r\n end",
"def p_value(pr,k)\n GSL::Cdf.tdist_Pinv(pr,k)\n end",
"def p(trigram)\n\n bigram = trigram[1..2]\n unigram = trigram[2..2]\n # see which case we fall into for this backoff scheme\n if @counts.include?(trigram)\n # p1 function, trigram exists\n return pML(trigram, @discount)\n else\n ngram = nil\n beta_gram = nil\n alpha = 0\n if @counts.include?(bigram)\n # p2 function, no trigram but bigram exists\n ngram = bigram\n beta_gram = trigram[0..1] # the words used to help generate a beta-set of zero-count trigram\n # alpha mass redistribution\n alpha = @weights[:p2] * (1 - pML(trigram, @discount))\n else\n # p3 function, no trigram or bigram\n ngram = unigram\n beta_gram = trigram[0..0] # the words used to help generate a beta-set of zero-count bigrams\n # alpha mass redistribution\n alpha = @weights[:p3] * (1 - pML(trigram, @discount))\n end\n\n numerator = pML(ngram) \n denominator = @beta_gram_cache.fetch(beta_gram, nil) \n if not denominator\n dgram = nil\n sum = 0\n @vocab.each do |v| # all permutations of vocab words\n dgram = beta_gram + [v]\n # that are zero-count ngrams of (w,w_i-1,w_i-2) or (w,w_i-1)\n if not @counts.include?(dgram)\n # should be part of the sum of pML(w|w_i-1) or pML(w)\n sum += pML(dgram.drop(1)) # drop w_i-2 or w_i-1 as needed\n end\n end\n\n @beta_gram_cache.store(beta_gram, sum)\n denominator = sum\n end\n\n if denominator == 0 then return 0 end\n return alpha * numerator / denominator\n end\n\n end",
"def binomial_coefficient(n, k); end",
"def proportional(error)\n return @kp*error\n end",
"def p(k)\n k = k.to_f\n output = 0.0\n if k == 1\n output = 1/@N\n else\n output = 1/(k*(k-1))\n end\n return output\n end",
"def p_value(pr,k)\n GSL::Cdf.tdist_Pinv(pr,k)\n end",
"def linear_probing(k, i, m)\n ( h(k, m) + i ) % m\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return estimated half_life of an AA sequence. _The halflife is a prediction of the time it takes for half of the amount of protein in a cell to disappear after its synthesis in the cell. ProtParam relies on the "Nend rule", which relates the halflife of a protein to the identity of its Nterminal residue; the prediction is given for 3 model organisms (human, yeast and E.coli)._
|
def half_life(species=nil)
n_end = @seq[0].chr.to_sym
if species
HALFLIFE[species][n_end]
else
{
:ecoli => HALFLIFE[:ecoli][n_end],
:mammalian => HALFLIFE[:mammalian][n_end],
:yeast => HALFLIFE[:yeast][n_end]
}
end
end
|
[
"def calculate(person, end_date = Synthea::Config.end_date)\n # Disability-Adjusted Life Year = DALY = YLL + YLD\n # Years of Life Lost = YLL = (1) * (standard life expectancy at age of death in years)\n # Years Lost due to Disability = YLD = (disability weight) * (average duration of case)\n # from http://www.who.int/healthinfo/global_burden_disease/metrics_daly/en/\n yll = 0\n yld = 0\n age = person[:age]\n birth_time = person.events.events[:birth][0].time\n age = ((end_date - birth_time) / 31_557_600).round if end_date != Synthea::Config.end_date\n\n if person.had_event?(:death)\n # life expectancy equation derived from IHME GBD 2015 Reference Life Table\n # 6E-5x^3 - 0.0054x^2 - 0.8502x + 86.16\n # R^2 = 0.99978\n l = (0.00006 * age**3) - (0.0054 * age**2) - (0.8502 * age) + 86.16\n yll = l\n end\n\n all_conditions = person.record_synthea.conditions\n (0...age).each do |year|\n year_start = birth_time + year.years\n year_end = birth_time + (year + 1).years\n conditions_in_year = conditions_in_year(all_conditions, year_start, year_end)\n\n conditions_in_year.each do |condition|\n dw = @disability_weights[condition['type'].to_s]['disability_weight']\n weight = weight(dw, year + 1)\n # duration is 1 year\n yld += weight\n end\n end\n\n daly = yll + yld\n qaly = age - yld\n\n person.record_synthea.observation(:DALY, end_date, daly, 'fhir' => :observation, 'ccda' => :no_action, 'category' => 'survey')\n person.record_synthea.observation(:QALY, end_date, qaly, 'fhir' => :observation, 'ccda' => :no_action, 'category' => 'survey')\n end",
"def optimal_height(my_arm_length)\n (my_arm_length * 50)/7\n end",
"def last_possible_defense_semester\n study_length * 2\n end",
"def predicted_correctly(h_team_elo, a_team_elo, result, leniency)\n predicted_correctly = false\n\n if result == \"H\" && h_team_elo > a_team_elo && (h_team_elo - a_team_elo).abs > leniency\n predicted_correctly = true\n elsif result == \"A\" && h_team_elo < a_team_elo && (h_team_elo - a_team_elo).abs > leniency\n predicted_correctly = true\n elsif result == \"D\" && (h_team_elo - a_team_elo).abs <= leniency\n predicted_correctly = true\n end\n\n return predicted_correctly\nend",
"def half_life(days)\n if days < $options[\"half-life-ignore\"]\n return 1.0\n else\n Math::exp(-0.693/$options[\"half-life\"]*(days-$options[\"half-life-ignore\"]))\n end\nend",
"def calculate_prediction_likelihood(away_team_goals_conceded, away_team_goals_scored, home_team_goals_conceded, home_team_goals_scored)\n delta = (home_team_goals_scored - away_team_goals_conceded).abs + (home_team_goals_conceded - away_team_goals_scored).abs\n DSHelpers.reverse_normalize_value(delta,0, 8.0,1.0)\n end",
"def predicted_deaths\n # predicted deaths is solely based on population density\n density = 200\n multiplier = 0.4\n until @population_density >= density\n if @population_density < 50\n return print \"#{@state} will lose #{(@population * 0.05).floor} people in this outbreak\"\n end\n density -= 50\n multiplier -= 0.1\n end\n number_of_deaths = (@population * multiplier).floor\n print \"#{@state} will lose #{number_of_deaths} people in this outbreak\"\n\n end",
"def calculate_height(confidence)\n confidence / 5.0 * (MAX_HEIGHT-1)\n end",
"def dampening_half_time\n return nil if dampening.nil? || dampening_routemap_configured?\n if dampening.is_a?(Array) && !dampening.empty?\n dampening[0].to_i\n else\n default_dampening_half_time\n end\n end",
"def fitness\n 0 - length_penalty - spelling_penalty\n end",
"def hps\n self.total_healing.to_f / self.encounter.duration_in_seconds\n end",
"def aic\n num_param = @fix_ef.length + self.theta.length + 1\n aic = self.deviance + 2.0 * num_param\n return aic\n end",
"def where_is_he(p, bef, aft)\n if (p - bef - aft > 1)\n aft + 1\n else\n p - bef\n end\nend",
"def target_number_of_ama_hearings(time_period)\n decisions_in_days = (time_period.to_f / 1.year) * nonpriority_decisions_per_year\n (decisions_in_days * docket_proportions[:hearing]).round\n end",
"def height\n 12 * effective_octave + \"C D EF G A B\".index(letter) + effective_accidental + transposition\n end",
"def fibs(n) ; PHI**n - PHA**n ; end",
"def grand_average_of_hydropathy\n hydrophopathy_profile.inject{|sum,x| sum + x }.to_f/seq.length\n end",
"def redetermine_eligibility_with_updated_values(family, params, hbxs, year)\n eligibility_redetermination_result = false\n latest_eligibility_determination = family.active_household.latest_active_tax_household_with_year(year).latest_eligibility_determination\n max_aptc = latest_eligibility_determination.max_aptc\n csr_percent_as_integer = latest_eligibility_determination.csr_percent_as_integer\n csr_percentage_param = params[:csr_percentage] == \"limited\" ? -1 : params[:csr_percentage].to_i # storing \"limited\" CSR as -1\n\n if !(params[:max_aptc].to_f == max_aptc && csr_percentage_param == csr_percent_as_integer) # If any changes made to MAX APTC or CSR\n effective_starting_on = family.active_household.latest_active_tax_household_with_year(year).effective_starting_on\n if effective_starting_on > TimeKeeper.date_of_record\n eligibility_date = effective_starting_on\n else\n eligibility_date = hbxs.present? ? find_enrollment_effective_on_date(TimeKeeper.datetime_of_record) : TimeKeeper.datetime_of_record # Follow 15th of month rule if active enrollment.\n end\n # If max_aptc / csr percent is updated, create a new eligibility_determination with a new \"determined_at\" timestamp and the corresponsing csr/aptc update.\n tax_household = family.active_household.latest_active_tax_household_with_year(year)\n tax_household.eligibility_determinations.build({\"determined_at\" => eligibility_date,\n \"determined_on\" => eligibility_date,\n \"csr_eligibility_kind\" => latest_eligibility_determination.csr_eligibility_kind,\n \"premium_credit_strategy_kind\" => latest_eligibility_determination.premium_credit_strategy_kind,\n \"csr_percent_as_integer\" => csr_percentage_param,\n \"max_aptc\" => params[:max_aptc].to_f,\n \"benchmark_plan_id\" => latest_eligibility_determination.benchmark_plan_id,\n \"e_pdc_id\" => latest_eligibility_determination.e_pdc_id,\n \"source\" => \"Admin\"\n }).save!\n eligibility_redetermination_result = true\n end\n eligibility_redetermination_result\n end",
"def life_range\n if birth\n if death\n birth..death # exact\n else\n birth..(birth + max_le) # estimation based on birth\n end\n elsif death\n (death - max_le)..death # estimation based on death\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Calculate instability index of an AA sequence. _The instability index provides an estimate of the stability of your protein in a test tube. Statistical analysis of 12 unstable and 32 stable proteins has revealed [7] that there are certain dipeptides, the occurence of which is significantly different in the unstable proteins compared with those in the stable ones. The authors of this method have assigned a weight value of instability to each of the 400 different dipeptides (DIWV)._
|
def instability_index
@instability_index ||=
begin
instability_sum = 0.0
i = 0
while @seq[i+1] != nil
aa, next_aa = [@seq[i].chr.to_sym, @seq[i+1].chr.to_sym]
if DIWV.key?(aa) && DIWV[aa].key?(next_aa)
instability_sum += DIWV[aa][next_aa]
end
i += 1
end
round((10.0/amino_acid_number.to_f) * instability_sum, 2)
end
end
|
[
"def aliphatic_index\n aa_map = aa_comp_map\n @aliphatic_index ||= round(aa_map[:A] +\n 2.9 * aa_map[:V] +\n (3.9 * (aa_map[:I] + aa_map[:L])), 2)\n end",
"def get_AIBC(i)\n @@tam = @medidas.length\n if i >= @@tam\n return 0\n else\n return (((@medidas[i] - @medidas[0]) + (@medidas[i - 1] - @medidas[0])) / 24) + get_AIBC(i + 1)\n end\n end",
"def abilityIndex\n abil=@abilityflag!=nil ? @abilityflag : (@personalID&1)\n return abil\n end",
"def ab_counts(_experiment, _alternative)\n raise \"Not implemented\"\n end",
"def aibc(index)\n auxiliar = []\n data[index][1..data[index].length - 1].zip(data[index][0..data[index].length-2]) do |x,y|\n if x < data[index][0]\n auxiliar << 0.0\n else\n auxiliar << (((x - data[index][0]) + (y - data[index][0]))/2) * 5\n end\n end\n auxiliar.reduce(:+)\nend",
"def biodiversity_index(specimens)\n distribution = Hash.new(0)\n specimens.each do |specimen|\n distribution[specimen] += 1\n end\n smallest_population_size = distribution.values.min\n largest_population_size = distribution.values.max\n index = distribution.length ** 2 * smallest_population_size / largest_population_size\nend",
"def calcPercentIdent(fasta)\n pos = nil\n idents = []\n len = nil\n counts = 0\n Bio::FlatFile.new(Bio::FastaFormat, File.new(fasta)).each do |seq1|\n len = seq1.length if len.nil?\n Bio::FlatFile.new(Bio::FastaFormat, File.new(fasta)).each do |seq2|\n next if seq2.full_id == seq1.full_id\n idents.push(0)\n seq1.length.times do |i|\n idents[idents.size - 1] += 1 if (seq1.seq[i] == seq2.seq[i])\n end\n end\n end\n tot = 0\n idents.each {|ident| tot+=ident}\n avIdent = (tot * 100 / idents.size) / len\n return avIdent\nend",
"def calculateAnnuity\n rate = @i /100.0\n @pmt*((1 - (1 / ((1 + rate)**@n))) / rate)\n end",
"def biodiversity_index(specimens)\n species = Hash.new(0)\n\n specimens.each do |el|\n species[el] += 1\n end\n\n num_species = species.length\n smallest_pop = species.sort_by {|k, v| v }[0][-1]\n largest_pop = species.sort_by {|k, v| v } [-1][-1]\n\n index = num_species ** 2 * smallest_pop / largest_pop\n\nend",
"def biodiversity_index(specimens)\n population_size = Hash.new(0)\n specimens.each do |specimen|\n population_size[specimen] += 1\n end\n\n number_of_species = specimens.uniq.length\n smallest_population_size = population_size.values.min\n largest_population_size = population_size.values.max\n\n number_of_species ** 2 * smallest_population_size / largest_population_size\nend",
"def getItemDiscriminationIndex(str,questionsThatGotScored,topCohort,bottomCohort) \n questionsThatGotScoredByTopCohort = questionsThatGotScored.select{|key, hash| topCohort.keys.include?(key)}\n ques1DiscrTopIndex = ((questionsThatGotScoredByTopCohort.select{|key, hash| hash.include?(str)}.length).to_f)/(topCohort.length).to_f\n questionsThatGotScoredByBottomCohort = questionsThatGotScored.select{|key, hash| bottomCohort.keys.include?(key)}\n ques1DiscrBottomIndex = ((questionsThatGotScoredByBottomCohort.select{|key, hash| hash.include?(str)}.length).to_f)/(bottomCohort.length).to_f \n itemDiscriminationIndex = ques1DiscrTopIndex - ques1DiscrBottomIndex \nend",
"def calculate_number_of_possible_RNAs_from_prot(protseq)\r\n result = 1 #Variable for returning product of each aac number of codons\r\n stop = 3 #Variable for remembering that we have to take account of the stop codons too\r\n codons ={\"GCU\"=>\"A\",\"GCC\"=>\"A\",\"GCA\"=>\"A\",\"GCG\"=>\"A\",\"GUU\"=>\"V\",\"GUC\"=>\"V\",\r\n \"GUA\"=>\"V\",\"GUG\"=>\"V\",\"GAU\"=>\"D\",\"GAC\"=>\"D\",\"GAA\"=>\"E\",\"GAG\"=>\"E\",\r\n \"GGU\"=>\"G\",\"GGC\"=>\"G\",\"GGA\"=>\"G\",\"GGG\"=>\"G\",\"AUU\"=>\"I\",\"AUC\"=>\"I\",\r\n \"AUA\"=>\"I\",\"AUG\"=>\"M\",\"ACU\"=>\"T\",\"ACC\"=>\"T\",\"ACA\"=>\"T\",\"ACG\"=>\"T\",\r\n \"AAU\"=>\"N\",\"AAC\"=>\"N\",\"AAA\"=>\"K\",\"AAG\"=>\"K\",\"AGU\"=>\"S\",\"AGC\"=>\"S\",\r\n \"AGA\"=>\"R\",\"AGG\"=>\"R\",\"CUU\"=>\"L\",\"CUC\"=>\"L\",\"CUA\"=>\"L\",\"CUG\"=>\"L\",\r\n \"CCU\"=>\"P\",\"CCC\"=>\"P\",\"CCA\"=>\"P\",\"CCG\"=>\"P\",\"CAU\"=>\"H\",\"CAC\"=>\"H\",\r\n \"CAA\"=>\"Q\",\"CAG\"=>\"Q\",\"CGU\"=>\"R\",\"CGC\"=>\"R\",\"CGA\"=>\"R\",\"CGG\"=>\"R\",\r\n \"UUU\"=>\"F\",\"UUC\"=>\"F\",\"UUA\"=>\"L\",\"UUG\"=>\"L\",\"UCU\"=>\"S\",\"UCC\"=>\"S\",\r\n \"UCA\"=>\"S\",\"UCG\"=>\"S\",\"UAU\"=>\"Y\",\"UAC\"=>\"Y\",\"UAA\"=>\"STOP\",\r\n \"UAG\"=>\"STOP\",\"UGU\"=>\"C\",\"UGC\"=>\"C\",\"UGA\"=>\"STOP\",\"UGG\"=>\"W\"}\r\n \r\n protseq.each_char do |aac|\r\n count = 0 #it saves the number of codons that produce a certain aminoacid\r\n codons.each do |codon, translated_codon|\r\n if translated_codon == aac\r\n count += 1\r\n end\r\n end\r\n result *= count\r\n end\r\n return (result * stop) % 1000000\r\nend",
"def get_distance(indicator, row_from_training, example_to_classify)\n atts = @attributes\n\t\tdist = 0\n\t\tcase indicator\n\t\t\twhen CONTINUOUS_CONST\n\t\t\t\tatts.each do |a|\n\t\t\t\t\tif a.format == CONTINUOUS_CONST\n dist += ((row_from_training.attributes[a.name].to_f - example_to_classify.attributes[a.name].to_f)**MINKOWSKI_DISTANCE_CONST)**(1/MINKOWSKI_DISTANCE_CONST)\n\t\t\t\t\tend\n\t\t\t\tend # end loop atts.each\n\n\t\t\twhen NOMINAL_CONST\n\t\t\t\t# method based on simple matching method\n\t\t\t\tcounterR = 0\n\t\t\t\tcounterQ = 0\n\t\t\t\tatts.each do |a|\n\t\t\t\t\tif a.format == NOMINAL_CONST\n\t\t\t\t\t\tif row_from_training.attributes[a.name] == example_to_classify.attributes[a.name]\n\t\t\t\t\t\t\tcounterQ += 1\n\t\t\t\t\t\tend\n\t\t\t\t\t\tcounterR += 1\n\t\t\t\t\tend\n\t\t\t\tend # end loop atts.each\n\t\t\t\tdist = (counterR - counterQ) / counterR if counterR > 0\n\t\t\t\tdist = 0 if counterR == 0\n\t\t\t\n\t\t\twhen BINARY_CONST\n\t\t\t\t# SOKAL-MICHENER similarity implemented\n\t\t\t\tcounterN = 0 # It counts all binary attributes\n\t\t\t\tcounterA = 0 # It counts the attributes alike and equal 1\n\t\t\t\tcounterD = 0 # It counts the attributes alike and equal 0\n\t\t\t\tatts.each do |a|\n\t\t\t\t\t# 1.- We get counterA value\n\t\t\t\t\tif a.format == BINARY_CONST\n\t\t\t\t\t\tif row_from_training.attributes[a.name] == 1 and example_to_classify.attributes[a.name] == 1\n\t\t\t\t\t\t\tcounterA += 1\n\t\t\t\t\t\tend\n\t\t\t\t\t\tcounterN += 1\n\t\t\t\t\tend\n\t\t\t\t\t# 2.- We get counterD value\n\t\t\t\t\tif a.format == BINARY_CONST\n\t\t\t\t\t\tif row_from_training.attributes[a.name] == 0 and example_to_classify.attributes[a.name] == 0\n\t\t\t\t\t\t\tcounterD += 1\n\t\t\t\t\t\tend\n\t\t\t\t\t\tcounterN += 1\n\t\t\t\t\tend\n\t\t\t\t\t# 3.- We get b value (for Jaccard similarity)\n\t\t\t\t\t# 4.- We get c value (for Jaccard similarity)\n\t\t\t\t\t\n\t\t\t\tend # end loop atts.each\n\t\t\t\tdist = (counterA + counterD) / counterN if counterN > 0\n\t\t\t\tdist = 0 if counterN == 0\n\t\t\telse\n\t\t\t\t#puts \"There's a format indicated and it doesn't exist\"\n\t\t\t\tputs \"ERROR: NOT continuous, NOT nominal, NOT binary, What is this?\"\n\t\tend\n\t\treturn dist\n\tend",
"def run_align_assess\n filename = self.generate_fasta_alignment_file_for_all\n string = \"./lib/AlignAssess_wShorterID #{filename} P\"\n seq_array = Array.new\n if system(string)\n seq_id_array = self.sequences.map{|s| s.seq_id}\n new_filename = filename + \"_assess\"\n f = File.new(new_filename, \"r\")\n flag = false\n read_row= 999999999\n cur_row = 0\n while (line = f.gets)\n if cur_row > read_row && flag\n if line == \"\\n\"\n flag =false\n else\n seq_array << line.split(\"\\t\")\n end\n elsif line == \"Pair-wise %ID over shorter sequence:\\n\"\n flag=true\n read_row = cur_row + 2\n end\n cur_row +=1\n end\n range = seq_array.length - 1\n #seq_array.each do |row|\n for row_num in 0..range\n for i in 1..range#(row_num) \n PercentIdentity.first_or_create(:seq1_id=>seq_id_array[row_num],\n :seq2_id=>seq_id_array[i],\n :alignment_name => self.alignment_name,\n :percent_id=>seq_array[row_num][i])\n # print \"[#{row_num}:#{i-1}=>#{row[i]}],\"\n end\n #print \"\\n\"\n end\n end\n end",
"def indicator_energia()\n\t\t\t\te = totalCaloricValue() / @alimentsList.length\n\n\t\t\t\tif e < 670\n\t\t\t\t\treturn 1.0\n\t\t\t\telsif e <= 830\n\t\t\t\t\treturn 2.0\n\t\t\t\telse\n\t\t\t\t\treturn 3.0\n\t\t\t\tend\n\t\t\tend",
"def acidic_count(amino_acid_sequence)\n count = 0\n comp = amino_acid_sequence.composition\n ACIDIC_AMINO_ACIDS.each do |acidic|\n if comp[acidic]\n count += comp[acidic]\n end\n end\n return count\n end",
"def calcShannonEnt(dataSet)\n numEntries = dataSet.size\n labelCounts = {}\n dataSet.each_with_index do |inst, pos|\n label = inst[-1]\n labelCounts[label]=labelCounts.fetch(label,0)+1\n end\n shannonEnt = 0.0\n labelCounts.each_pair do |k, v|\n prob=v.to_f/numEntries\n shannonEnt-=prob*Math.log2(prob)\n end\n shannonEnt\n end",
"def instability\n cT = total_couplings.to_f\n (cT.zero?) ? 0.0 : @efference / cT\n end",
"def min_umbrellas(weather)\n indexs = []\n result = 0\n weather.each_with_index do |weather, ind|\n if weather == \"rainy\" || weather == \"thunderstorms\"\n indexs << ind\n end\n end\n result += 1 unless indexs.empty?\n indexs.each_cons(2) do |first, second|\n result += 1 if (second - first) > 1\n end\n result\nend"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Return wheter the sequence is stable or not as String (stable/unstable). _Protein whose instability index is smaller than 40 is predicted as stable, a value above 40 predicts that the protein may be unstable._
|
def stability
(instability_index <= 40) ? "stable" : "unstable"
end
|
[
"def stable?\n (instability_index <= 40) ? true : false\n end",
"def complete?\n return nil unless ivsat_table\n line = ivsat_table.split(\"\\n\").find{|l| l.include? 'INFO: Sequence completeness:' }\n line && !line.include?('partial')\n end",
"def stable\n self[:draft] == false && self[:prerelease] == false\n end",
"def danceability_str\n if audio_features.danceability > 0.9\n \"Danceability: ⭐⭐⭐\"\n\n elsif audio_features.danceability > 0.75\n \"Danceability: ⭐⭐\"\n\n elsif audio_features.danceability > 0.6\n \"Danceability: ⭐\"\n\n else\n \"\"\n end\n end",
"def priority\n self.urgent ? \"Urgent\" : \"Not Urgent\"\n end",
"def prefer_stable?\n alias_of.prefer_stable?\n end",
"def is_stable?\n\n Uhuru::RepositoryManager::Model::Versions.get_versions(:product_id => self.id, :stable => true).count > 0\n\n end",
"def to_s\n predicted_score&.to_s\n end",
"def BTI(bool) return bool ? \"1\" : \"0\" end",
"def state_s\n # return \"审核中\" if approving?\n return \"等待激活中\" if unapproved?\n return \"审核被拒绝\" if rejected?\n return \"展示中\" if opened? and available?\n return \"高亮展示中\" if highlighted? and opened? and available?\n return \"已过期\" if !available?\n return \"未展示\" if closed?\n end",
"def sequence_input_present?\n sequence_details[:sequence] == 'true'\n end",
"def profit_switch_string\n\t\tself.profit_switch? ? \"ON\" : \"OFF\"\n\tend",
"def stable_version\n file_to_semver(stable_version_file)\n end",
"def status\n has_torch = @game.player.has_torch?\n return \"You can't see anything, you must purchase a torch\\n\" unless has_torch\n\n output = StringIO.new\n output << @game.player.to_s\n output << \"\\n\"\n\n output << \"#{@game.current_room_model.description}\\n\"\n\n treasure = @game.current_room_model.treasure\n output << \"\\nThere is treasure here worth $#{treasure}.\\n\" if treasure && treasure > 0\n\n monster = @game.current_room_model.monster\n if monster\n output << \"\\nDANGER... THERE IS A MONSTER HERE....\\n\\n\"\n output << \"#{@game.current_room_model.monster}\\n\\n\"\n end\n\n if @game.current_room_model.name != \"Exit\"\n output << \"\\nWhat do you want to do? \"\n end\n\n output.string\n end",
"def impact_to_s(impact)\n if impact < 0.4\n 'minor'\n elsif impact < 0.7\n 'major'\n else\n 'critical'\n end\n end",
"def stable\n self.class.new(map do |release|\n release if release.stable\n end.compact)\n end",
"def seq_number?\n @seq_number > NO_SEQ_NUMBER\n end",
"def insCheck(stc)\n\t\tif stc == '930' #Insurance <= $200\n\t\t\treturn '0010000' # $100\n\t\telsif stc == '931' #Insurance > $200\n\t\t\treturn '0050000' # $500\n\t\telse\n\t\t\treturn false #No insurance extra service.\n\t\tend\n\tend",
"def pretty_play_state\n\n case self.accurate_state\n when :in_future\n \"SCHEDULED\"\n when :live\n if self.pending_final?\n \"PENDING...\"\n else\n if self.sport==\"NBA\"\n \"#{game_remaining} MIN LEFT\"\n elsif self.sport==\"MLB\"\n \"#{self.progress/2} INNING\"\n end\n end\n when :closed\n if self.exception_ending?\n \"CANCELLED\"\n else\n \"FINAL\"\n end\n end\n end"
] |
{
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.