Ruby, how to swap the elements in an array?
How do I swap an(example) array's second and third elements? I tried the following
def swap_elements(array)
array = ["blake", "ashley", "scott"]
array[1], array[2] = array[2], array[1]
end
but I get
: ["scott", "ashley"]
I lost the first[0] element
1 answer
-
answered 2022-05-04 03:38
max
There are many ways to do this - this is a functional approach that doesn't mutate the original array:
def swap_elements(array) # yields the array to the block array.then do |first, *rest| # deconstruct the array rest.reverse # swap the places of 2 & 3 .unshift(first) # put the first back in end end
do you know?
how many words do you know
See also questions close to this topic
-
How to get pass an array through a function with a user input?
I want to ask the user for the size of a 2D array arr[][], but also pass it through the function initializeArray. However, if I pass it through the function, I would have to have a size declarator for col, which doesn't allow the user to enter their own value for the size
#include<iostream> using namespace std; void initializeArray(arr[][10], int N); int main() { int N; cout << "enter an array size: "; cin >> N; int arr[N][N]; initializeArray(arr, N); // I get an error here for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) cout << arr[i][j] << " "; cout << endl; } } void initializeArray(int arr[][10], int N) { for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) arr[i][j] = 0; }
The only solution I found was the make arr[][] a global array, but in that case, I would have to still declare the size parameters, and I want the user to enter whatever they want. Is there another way to fix this?
-
Two-dimensional array C++
Problem: Write a program of a two dimensional integer array of exactly four rows and four columns, and find the sum of the integers each row of the array as well as determine the smallest inputted element/data in the array. The user will input the elements. Display the elements in tabular form. Make the program user friendly. Use a Class and a member function for the process involve.
-
Pass Associative Array from Symfony Controller to Twig and JavaScript
So, I have 2 arrays that I've combined into one array after making sure they're the same length as such.
//Fetching Ratings for All Coaches & Making a Key, Value Associative Array with Coach id as Key and Rating as Value $coaches = $coachRepository->findAll(); $rating = $coachRepository->findRatingByCoach(); //Array of coach IDs $id_array = array(); foreach ($coaches as $c){ $id_array[] = $c->getId(); } $combined = array_combine($id_array, $rating);
Now I want to pass this key, value array to Twig template and JavaScript. I'm currently doing this
return $this->render('...', [ ..., 'combined'=>$combined ]);
And I'm accessing the array in Twig as such
{% for key, value in combined %} {{ key }} - {{ value }} {% endfor %}
And I'm getting this error.
Object of class App\Entity\Coach could not be converted to string
Looking at the Stack Trace I can see that the array combined is being passed in this form.
'combined' => array(object(Coach))
After a bit of debugging it turns out that I thought the issue was with the $
id_array
when in fact it's the $rating
variable that's presenting an issue. I'm not sure why but I'm getting a single float value. I fixed the issue by changing how I'm fetching the $rating, now instead of using a QueryBuilder to get it from the DB, I'm getting it from list of Coaches as such//Array of coach IDs and array of Ratings $id_array = array(); $rating_array = array(); foreach ($coaches as $c){ $id_array[] = $c->getId(); $rating_array [] = $c->getRating(); }
Even if I set the array
-
problems to run rails s on Rails 4 :S
Im trying to run s on my project in Rails 4.2.2
but i get a unexpected error :S
Someone know the reason of the error?
Thanks in advance This is my logs .................................................................................................................................................................................................➜ backend-ror git:(dev) ✗ rails s => Booting Puma => Rails 4.2.2 application starting in development on http://localhost:3000 => Run `rails server -h` for more startup options => Ctrl-C to shutdown server Expected string default value for '--jbuilder'; got true (boolean) Expected string default value for '--serializer'; got true (boolean) Exiting /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:457:in `load': /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/app/controllers/application_controller.rb:39: syntax error, unexpected tIDENTIFIER, expecting keyword_then or ',' or ';' or '\n' (SyntaxError) from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:457:in `block in load_file' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:647:in `new_constants_in' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:456:in `load_file' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:354:in `require_or_load' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:494:in `load_missing_constant' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:184:in `const_missing' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/inherited_resources-1.9.0/app/controllers/inherited_resources/base.rb:11:in `<module:InheritedResources>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/inherited_resources-1.9.0/app/controllers/inherited_resources/base.rb:1:in `<top (required)>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:457:in `load' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:457:in `block in load_file' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:647:in `new_constants_in' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:456:in `load_file' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:354:in `require_or_load' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:494:in `load_missing_constant' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:184:in `const_missing' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activeadmin-1.4.3/lib/active_admin/base_controller/authorization.rb:2:in `<module:ActiveAdmin>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activeadmin-1.4.3/lib/active_admin/base_controller/authorization.rb:1:in `<top (required)>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:274:in `require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:274:in `block in require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:240:in `load_dependency' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:274:in `require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activeadmin-1.4.3/lib/active_admin/base_controller.rb:1:in `<top (required)>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:274:in `require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:274:in `block in require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:240:in `load_dependency' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:274:in `require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activeadmin-1.4.3/lib/active_admin/application.rb:166:in `controllers_for_filters' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activeadmin-1.4.3/lib/active_admin/application.rb:159:in `block (2 levels) in <class:Application>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/config/initializers/active_admin.rb:12:in `block in <top (required)>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activeadmin-1.4.3/lib/active_admin.rb:69:in `setup' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/config/initializers/active_admin.rb:1:in `<top (required)>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:268:in `load' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:268:in `block in load' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:240:in `load_dependency' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:268:in `load' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/engine.rb:652:in `block in load_config_initializer' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/notifications.rb:166:in `instrument' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/engine.rb:651:in `load_config_initializer' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/engine.rb:616:in `block (2 levels) in <class:Engine>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/engine.rb:615:in `each' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/engine.rb:615:in `block in <class:Engine>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:30:in `instance_exec' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:30:in `run' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:55:in `block in run_initializers' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:228:in `block in tsort_each' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:350:in `block (2 levels) in each_strongly_connected_component' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:422:in `block (2 levels) in each_strongly_connected_component_from' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:431:in `each_strongly_connected_component_from' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:421:in `block in each_strongly_connected_component_from' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:44:in `each' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:44:in `tsort_each_child' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:415:in `call' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:415:in `each_strongly_connected_component_from' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:349:in `block in each_strongly_connected_component' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `each' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `call' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:347:in `each_strongly_connected_component' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:226:in `tsort_each' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/tsort.rb:205:in `tsort_each' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/initializable.rb:54:in `run_initializers' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/application.rb:352:in `initialize!' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/config/environment.rb:5:in `<top (required)>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:274:in `require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:274:in `block in require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:240:in `load_dependency' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/activesupport-4.2.2/lib/active_support/dependencies.rb:274:in `require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/config.ru:3:in `block in <main>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/rack-1.6.13/lib/rack/builder.rb:55:in `instance_eval' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/rack-1.6.13/lib/rack/builder.rb:55:in `initialize' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/config.ru:in `new' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/config.ru:in `<main>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/rack-1.6.13/lib/rack/builder.rb:49:in `eval' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/rack-1.6.13/lib/rack/builder.rb:49:in `new_from_string' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/rack-1.6.13/lib/rack/builder.rb:40:in `parse_file' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/rack-1.6.13/lib/rack/server.rb:300:in `build_app_and_options_from_config' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/rack-1.6.13/lib/rack/server.rb:209:in `app' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/commands/server.rb:61:in `app' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/rack-1.6.13/lib/rack/server.rb:337:in `wrapped_app' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/commands/server.rb:139:in `log_to_stdout' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/commands/server.rb:78:in `start' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/commands/commands_tasks.rb:80:in `block in server' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/commands/commands_tasks.rb:75:in `tap' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/commands/commands_tasks.rb:75:in `server' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/commands/commands_tasks.rb:39:in `run_command!' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/railties-4.2.2/lib/rails/commands.rb:17:in `<top (required)>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/bin/rails:9:in `require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/bin/rails:9:in `<top (required)>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/spring-1.5.0/lib/spring/client/rails.rb:28:in `load' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/spring-1.5.0/lib/spring/client/rails.rb:28:in `call' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/spring-1.5.0/lib/spring/client/command.rb:7:in `call' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/spring-1.5.0/lib/spring/client.rb:28:in `run' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/spring-1.5.0/bin/spring:49:in `<top (required)>' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/spring-1.5.0/lib/spring/binstub.rb:11:in `load' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/vendor/cache/ruby/2.3.0/gems/spring-1.5.0/lib/spring/binstub.rb:11:in `<top (required)>' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from /Users/Cristopheer96/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require' from /Users/Cristopheer96/code/Cristopheer96/Guudjob/backend-ror/bin/spring:13:in `<top (required)>' from ./bin/rails:3:in `load' from ./bin/rails:3:in `<main>' ➜ backend-ror git:(dev) ✗
-
Devise Registration controller, every parameter seems to be removed
trying to override Devise Registration controller, following a couple examples online, but for some reason every parameter passed in seems to be removed. this is the controller.
class RegistrationsController < Devise::RegistrationsController skip_before_action :verify_authenticity_token, :only => :create def create p sign_up_params build_resource(sign_up_params) resource.save sign_up(resource_name, resource) if resource.persisted? render json: resource end end
this is the request
curl --location --request POST 'localhost:3000/buyer_users' \ --data-raw '{ "buyer_users": { "email":"peter245@email.com", "password":"123123123", "site_id":"103eb514-8185-4820-8f16-3a9d082c5f60", "account_id": "f362189f-a843-4c19-927a-845ce2cb0ad0" } }'
we seems to be picking up params, but everything is removed
21:16:05 web.1 | Started POST "/buyer_users" for ::1 at 2022-05-06 21:16:05 -0700 21:16:05 web.1 | Processing by RegistrationsController#create as JSON 21:16:05 web.1 | Parameters: {"{\n \"buyer_users\": {\n \"email\":\"peter245@email.com\",\n \"password\":\"123123123\",\n \"site_id\":\"103eb514-8185-4820-8f16-3a9d082c5f60\",\n \"account_id\": \"f362189f-a843-4c19-927a-845ce2cb0ad0\"\n }\n}"=>"[FILTERED]"} 21:16:05 web.1 | {} 21:16:05 web.1 | Completed 200 OK in 7ms (Views: 0.1ms | ActiveRecord: 0.0ms | Allocations: 1155)
routes are set up like this
devise_for :buyer_users, defaults: { format: :json }, controllers: { registrations: 'registrations' }
EDIT: after debugging some more it seems that the entire parameter is taken in as 1 string.
-
Whats missing on my Ruby 'Inverse Of' relationship
I know this topic has been addressed, but I have been at this for 2 days and I'm just stuck. I know inverse of does not create a new query, so should I use another method?
Question: How to set up an 'inverse of' with a has_one, belongs_to situation & same class..
Explanation: A user 'has_one :spouse' and 'belongs_to :spouse_from'. They are inverse of each other. When a User signs up, they can invite their significant other. For Example
- user_a invites & creates user_b
- user_b.spouse_id is set to user_a.id
- In a separate method I want to be able to update like.. user_a.spouse_id = user_a.spouse.id
The only association that works at this point is user_b.spouse.
Class User has_one :spouse, class_name: 'User', foreign_key: :spouse_id, dependent: :nullify, inverse_of: :spouse_from belongs_to :spouse_from, class_name: 'User', foreign_key: :spouse_id, inverse_of: :spouse, optional: true
-
Library functions in Inspec Test
Team --
I have a ruby library helper in which I have defined multiple functions/methods. How do I reference those in
Chef
Inspec
tests?def interface_name # some code with logic end
In my specific use case, I am checking to see if a custom networking device was specified as a JSON parameter, and if it was, I am validating it make sure its real (incase they misspelled it) and also gathering its IP and state and other data as reported by
Ohai
This is what I have so far, but I'm not sure if this is correct
describe file('/path/to/custom_attributes.json') do it { should exist } unless json('/path/to/custom_attributes.json').empty? do its(['networking']['interface_name']) { should_not be_empty } interface_name = file(json('/path/to/custom_attributes.json').params['networking']['interface_name']) end end describe file('/etc/NetworkManager/system-connections/wired_connection') do unless interface_name.empty? its('content') { should_not match(/^interface-name=wl.*/mx) } end its('content') { should match(%r{ca-cert=/etc/ssl/certs/ca-certificates\.crt}mx) } its('content') { should match(/id=\.corp.*type=ethernet.*autoconnect-priority=100.*dns-search=corp\.domain.com.*/mx) } end end
The problem / question is that if I gather the parameter directly from the JSON file, then I am bypassing all the validation logic that I'm doing in the library, which defeats the purpose. So, how do I get access to that library function/method in the Inspec test?
For reference, here is the function:
def interface_name file = '/path/to/custom_attributes.json' if File.exist?(file) && !File.stat(file).zero? attributes = JSON.parse(File.read(file)) device_name = attributes['networking']['interface_name'] if device_name && !device_name.empty? && networking_devices.include?(device_name) interface = device_name Chef::Log.info("Valid custom interface provided, using \"#{device_name}\".") else Chef::Log.debug("Invalid interface (\"#{device_name}\") provided. Valid options are: \"#{networking_devices.keys}\"") interface = nil end else Chef::Log.debug('No custom interface provided.') end interface rescue JSON::ParserError nil end
-
Writing structured facts
I've wrote some ruby code which will run on a linux server and return details about the server as a fact. It does this by connecting to amazon and retrieving some json (it runs two separate commands one to retrieve a list of disks - e.g /dev/sda1, /dev/xvdb and then it maps this to a volumeID via another query).
I've made some small amendments to the output and added some values I'm interested in. The code runs multiple times and returns multiple hashes (one for each disk - maybe I should merge them?). Anyway here's an example of a server which has two disks below (this is just some debug output):
Hash is {"/dev/sda1"=>{"disk_mapping"=>"", "is_lvm_partitioned"=>"false", "volumeid"=>"vol1234"}}. Hash is {"/dev/xvdb1"=>{"disk_mapping"=>"xvdb1", "is_lvm_partitioned"=>"true", "volumeid"=>"vol5678"}}.
The next thing I want to to is turn this into a structured fact (with the devices: /dev/sda1, /dev/xvdb1 as the "keys"). Here's a rough idea of how I've done it (I've skipped a lot of the irrelevant code).
json_string = { "#{path}" => { "disk_mapping" => "#{disk_mapping}", "is_lvm_partitioned" => "#{is_lvm_partitioned}", "volumeid" => "#{getVolumes}" } }.to_json hash = JSON.parse(json_string) if hash.is_a? Hash then debug_msg("Hash is #{hash}.") hash["#{path}"].each do |key, child| debug_msg("Setting key: #{key} child: #{child}.") end end
I've never really wrote any ruby before so this is copied from multiple places, but besides aggregated facts I can't find a way to do this; I've tried to do something like this:
Facter.add(:test["#{path}"]["#{key}"]) do setcode do #{child} end end
So I guess in order I want to know:
- Should I merge the hash somehow? I originally assumed I did but found this incredibly hard due to not knowing how many hash's I'd have.
- Should I be using an aggregated fact or a "standard" one?
- How do I retain the structure of the hash and then call it with a single query (e.g facts test).
- Any examples which are similar to my code (the puppet ones I've found quite hard to follow).
Here's what I'm looking for at the end:
[root@blah ~]# facter test { /dev/sda1 => { disk_mapping => "", is_lvm_partitioned => "false", volumeid => "vol1234" }, /dev/xvdb => { disk_mapping => "xvdb1", is_lvm_partitioned => "true", volumeid => "vol5678" } }
Thanks.
-
Convert 2D meshgrid into a 3D array in Python
I have coordinates (lat, lon) in a meshgrid, and data asociated with each "point". I want to export into a .csv and have each point asociated with the data i want to analyze. So far, my code looks like this.
xx1,yy1=np.meshgrid(xx,yy) row_format = np.stack([z.ravel() for z in (xx1, yy1, data['Hs'])], axis=1) print(row_format) pd.DataFrame(row_format).to_csv('sample.csv')
The data is in a dataframe that has a certain order. But the output is as follows:
x y Hs 265 19 0 266 19 1 267 19 2 And it should be as follows, in order to make sense with the data order:
x y Hs 265 19 0 265 18 1 265 17 2 I only need to make the "x" column to be the one with the "still" value while the "y" column goes through its values ("x" will change value once every "y" value has been written). Anyone know how to change that order? Or another way to get my desired output?
-
Range Not Found, Google Apps Script for Google Sheets
I'm trying to build a custom range for this sort function in an Apps Script for Google Sheets but I keep getting the error: "Exception: Range not found; sortProductionLog @ macros.gs:15"
I'm sure this is something basic but I have searched far and wide and can't seem to find it. Can anyone shed some light?
Thank you, Ryan
SORT_ORDER = [ {column: 118, ascending: true}, // 3 = column number, sorting by descending order {column: 119, ascending: true}, // 1 = column number, sort by ascending order {column: 117, ascending: true}, {column: 25, ascending: true} ]; function sortProductionLog(){ var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName(SHEET_NAME); var LastRow_WithValue = sheet.getLastRow(); var LastColumn_WithValue = sheet.getLastColumn(); var buildRange = "4,1," + (LastRow_WithValue - 4) + "," + (LastColumn_WithValue - 1); var range = sheet.getRange(buildRange); ss.toast(buildRange); range.sort }
-
Categorize similar transactions
Given a list of transactions, some transactions are categorized, some transactions are not categorized. Find similar transactions and categorize them if possible. Similar transactions have the same targetAccount and the amount difference is not greater than 1000 (for all currencies) from the originally categorized transaction. If an uncategorized transaction is similar to more than one transaction, it should take the category from the one with the smallest amount difference. Transactions that cannot be categorized should still be included in the returned list. The returned list should preserve the order of the original list.
categorizeSimilarTransactions(transactions)
Input You can assume that the transactions parameter will always be present and valid. list of transactions (Transaction[])
Output List of transactions(Transaction[]) with enhanced categorization if possible.
This is what a categorized transaction looks like:
{ id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -350, currency: "EUR", category: "eating_out", time: "2021-03-12T12:34:00Z" }
An uncategorized transaction does not have category property. This is what an uncategorized transaction looks like:
{ id: "0f0ffbf9-2e26-4f5a-a6c0-fcbd504002f8", sourceAccount: "my_account", targetAccount: "eating_out", amount: -1900, time: "2021-03-12T12:34:00Z" }
The following two transactions are similar:
{ id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -350, category: "eating_out", time: "2021-03-12T12:34:00Z" }
and
{ id: "a001bb66-6f4c-48bf-8ae0-f73453aa8dd5", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -620, time: "2021-04-10T10:30:00Z" }
Input
categorizeSimilarTransactions([ { id: "a001bb66-6f4c-48bf-8ae0-f73453aa8dd5", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 350, time: "2021-04-10T10:30:00Z", }, { id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -150, category: "eating_out", time: "2021-03-12T12:34:00Z", }, { id: "6359091e-1187-471f-a2aa-81bd2647210f", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 100, category: "entertainment", time: "2021-01-12T08:23:00Z", }, { id: "a8170ced-1c5f-432c-bb7d-867589a9d4b8", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -1690, time: "2021-04-12T08:20:00Z", }, ]);
Expected Output
[ { id: "a001bb66-6f4c-48bf-8ae0-f73453aa8dd5", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 350, category: "entertainment", time: "2021-04-10T10:30:00Z", }, { id: "bfd6a11a-2099-4b69-a7bb-572d8436cf73", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -150, category: "eating_out", time: "2021-03-12T12:34:00Z", }, { id: "6359091e-1187-471f-a2aa-81bd2647210f", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: 100, category: "entertainment", time: "2021-01-12T08:23:00Z", }, { id: "a8170ced-1c5f-432c-bb7d-867589a9d4b8", sourceAccount: "my_account", targetAccount: "coffee_shop", amount: -1690, time: "2021-04-12T08:20:00Z", }, ];
I could find a solution but it's a brute-force approach & not efficient. Is there any other solution with less time complexity may be O(n) or O(log(n))/O(nlog(n)) which is easy to read & understand
const categorizeSimilarTransactions = (transactions) => { if (!(Array.isArray(transactions) && transactions.length)) return []; const categorizedTransactions = transactions.filter(t => t.category); const uncategorizedTransactions = transactions.filter(t => !t.category); let lowestDiff; uncategorizedTransactions.forEach(uncategorizedTransaction => { lowestDiff = Math.min(); categorizedTransactions.forEach(cat => { if (cat.targetAccount === uncategorizedTransaction.targetAccount) { lowestDiffComp = Math.abs(cat.amount - uncategorizedTransaction.amount); if (lowestDiffComp < lowestDiff && lowestDiffComp < 1000) { lowestDiff = lowestDiffComp; uncategorizedTransaction.category = cat.category; } } }) }); const merged = [...categorizedTransactions, ...uncategorizedTransactions]; const orderIds = transactions.map(transaction => transaction.id); merged.sort((a, b) => { return orderIds.indexOf(a.id) - orderIds.indexOf(b.id); }) return merged; };