mardi 4 août 2015

Ruby2.0: What is the difference between Ruby Refinements and Monkeypatches?

I could do some simple task in either way,

Refinements

module StringRefinements
  refine String do
    def do_something
      "bla bla bla..."
    end
  end
end

So, I can use do_something method wherever StringRefinements module was using.

Monkeypatch

class String
  def do_something
    "bla bla bla..."
  end
end

I would like to know the difference between Ruby's new concept Refinements and the one Monkeypatch. And what are the advantages of using Refinements over Monkeypatch?



via Chebli Mohamed

What is a good way to suppress 304 responses in Rack?

Rack seems to use the If-Modified-Since header. So one way to suppress 304 responses is to delete this header.

Is this a good way to suppress 304 responses? Is there a better way?



via Chebli Mohamed

Rails controllers architecture with many to many relationships

I am developing a portal via RubyOnRails where pupils, teachers and parents can participate in different contests with their art works.

There are 3 entities: Contests, Categories (competitor categories / age groups) and Nominations (kinds of activity). Contest can have many Categories. Each ContestCategory can have many Nominations. Each Category can belong to several Contests. Every Nomination can belong to many ContestCategories. So I presume there is many-to-many relationship between Contests and Categories and many-to-many relationship between ContestCategories and Nominations. I've created following models: Contest (contest.rb), Category (category.rb), Nomination (nomination.rb), ContestCategory (contest_category.rb) and ContestCategoryNomination (contest_category_nomination.rb).

My models:

class Category < ActiveRecord::Base
  has_many :contest_categories
  has_many :contests, through: :contest_categories
end

class Contest < ActiveRecord::Base
  has_many :contest_categories
  has_many :categories, through: :contest_categories
  has_many :nominations, through: :contest_categories
  has_one :provision
end

class ContestCategory < ActiveRecord::Base
  belongs_to :contest
  belongs_to :category
  has_many :contest_category_nominations
  has_many :nominations, through: :contest_category_nominations
end

class ContestCategoryNomination < ActiveRecord::Base
  belongs_to :contest_category
  belongs_to :nomination
end

class Nomination < ActiveRecord::Base
  has_many :contest_category_nominations
  has_many :contest_categories, through: :contest_category_nominations
  has_many :contests, through: :contest_categories
end

I want to create an ajax-based modal window during creation of new Contest to link it with Category and select multiple Nominations that belong to this Category.

  1. What controllers should I create to satisfy has_many relationships between my models?
  2. What are the naming conventions (singular and plural) in rails to satisfy my relationships? For example, ContestsCategoriesController or ContestCategoryNominationsController or may be ContestCategoryNominationsController?
  3. What action method should I create in this controllers to invoke to render this modal window? Should it be new_category action in CategoriesController or new action in ContestsCategoriesController or new action in ContestsCategoriesNominationsController?


via Chebli Mohamed

Ruby on Rails: if current page? is homepage, don't show form

I want to not show a form, but only if current page is NOT the home page

This is what I have so far...

I have my route setup:

root 'projects#index'

My view:

<% if !current_page?(url_for(:controller => 'projects', :action => 'index')) %>
  show some stuff
<% end %>

This doesn't show if the url is localhost:3000/projects

But it shows if its localhost:3000

So I need to somehow make sure that if its the homepage, it won't show. Also, I have search parameters for the home page, and I still don't want to show if its like localhost:3000/projects?search=blahblahblah



via Chebli Mohamed

Trying to reference earlier 'case' in a case statement

When someone tries to update a value that is not currently stored in my hash, I would like to immediately reference back to "when 'add'" without restarting the entire case statement (since I already know they want to add and don't want to prompt them again). Is there a way to reference back to the case choice -> when "add" section of my code without restarting the entire case statement? I know I could use nested case statements but I would rather not copy/paste identical code if I don't have to.

Also, sorry for the abrupt ending of the code. I just didn't want to put in anything unnecessary to the solution.

    hash = {}
    puts "Would you like to add or update this hash?"
    choice = gets.chomp
    case choice
    when "add"
      puts "What key you like to add?"
      key = gets.chomp
      puts "With what value?"
      value = gets.chomp
      hash[key] = value
    when "update"
      puts "Which key would you like to update?"
      key = gets.chomp
      if hash[key].nil?
        puts "Key not present, would you like to add it?"
        #here I would like the code that references back to "when 'add'" if the user types 'yes'    



via Chebli Mohamed

Nested forms using the Cocoon gem in Ruby on Rails 4.2

I'm building a web app using Rails 4.2 and I have a model called Strategy which has a has_many relationship to a Tactic model.

To create a view for Strategy, I need to have many nested Tactics on the form. I've been using the Cocoon gem to develop this view.

So far, I've been able to get the form to work properly for the most part but the issue is that I wanted to add a Type attribute to my Tactic model.

For a given strategy, I want to have 3 tactics of one given type, and 2 models of another.

The issue is that rendering my view, all five models are listed sequentially without any room for putting in my own HTML code around them.

Is there a simple way to separate out which of these are rendered? Right now, my view looks as follows...

<%= form_for @strategy do |f| %>
    <div class="strategy">
        <%= f.label :name %>
        <%= f.text_field :name %>
    </div>

    <div class="tactics">
        <%= f.fields_for :tactics do |i| %>
            <%= render 'tactics_fields', f: i %>
        <% end %>
    </div>

    <div class="buttons">
        <%= f.button "Save Strategy", class: 'button' %>
    </div>
<% end %>

If anyone can offer any advice, it would be greatly appreciated.



via Chebli Mohamed

extend array by n numbers while repeating elements

If I have an array like this

[1,2,3]*2 
#=> [1,2,3,1,2,3,1,2,3]

But I want to do it to certain length, that length is 1.5 the original array, preferably in one line

[1,2,3].size = 3
[1,2,3,1,2] or something like this



via Chebli Mohamed

Unable to run node_modules/.bin/browserifyinc. Ensure you have installed it with npm

Unable to run node_modules/.bin/browserifyinc. Ensure you have installed it with npm. (in /Users/labuser/Downloads/betfair_nav_demo-master/app/assets/javascripts/application.js)

I am using Ampersand JS with Rails application. gem 'rails', '4.2.1' gem "browserify-rails", '1.2.0'

I have installed npm install ampersand -g

npm install browserify --save-dev

npm install underscore --save

My Rails app is working without browserify-rails gem.



via Chebli Mohamed

Rails ActiveRecord - querying on last record of relationship

I have a model Book with a has_many relationship to State.

class Book < ActiveRecord::Base
   has_many :states
   ...
end

State sets the visibility of the book to "private", "restricted" or "public" through a name attribute. For auditing purposes, we keep a record of all state changes so to get the current state of a book I use

> book = Book.first
> book.states.last.name
> "public"

Now I need to query on all Book objects where the current state is public.

Something along the lines of:

Book.joins(:visibility_states).where(states: { state: "public"})

The problem is that the query above return all books that are currently pubic, or have been public in the past. I only want it to return books that are currently "public" (i.e. book.states.last.name == "public").

I know I can do it with select but that's generating one query for each record:

Book.all.select { |b| b.states.last.name == "public" }

Is there a way to do it using ActiveRecord only?



via Chebli Mohamed

Convert Jira's time tracking field format to hours

I am using JIRA api to extract timespent by users on issues. The time spent is in the format:

"12w 1d 2h 5m" or "12h" or "12m" etc

The API isn't exporting the number of hours. Is there a quick (requires no effort on my part) way to convert this to hours (or seconds). I suppose this is some sort of a standard format, is there a name for it? I know how to do this myself, just don't want to reinvent the wheel



via Chebli Mohamed

Cannot fnd bson_ext in path

I am getting the highly poular message:

** Notice: The native BSON extension was not loaded. **

For optimal performance, use of the BSON extension is recommended.

To enable the extension make sure ENV['BSON_EXT_DISABLED'] is not set
and run the following command:

  gem install bson_ext

If you continue to receive this message after installing, make sure that
the bson_ext gem is in your load path.

I am running rbenv and have tried gem install bson_ext. I get no errors - it tells me Successfully installed bson_ext-1.12.3. However bson_ext is not found - I assume its an executable. How do I know where it should be installed so that I can update my path accordingly?

If I search in my local .rbenv dir I see:

.rbenv/versions/2.2.2/lib/ruby/gems/2.2.0/gems/bson_ext-1.12.3/ext/bson_ext/bson_ext/

But do not see anything that appears to be an executable.



via Chebli Mohamed

difference between calling super and calling super()

What is the difference between calling super and calling super()? Which is the best one if the arguments passed to the child method don’t match what the parent is expecting.



via Chebli Mohamed

Unable to send mail with attachment using Mandrill-api gem (Rails 4.1)

Emails without attachment are delivered fine, but when there is an attachment I get the following error in production:

ArgumentError: An SMTP To address is required to send a message. Set the message smtp_envelope_to, to, cc, or bcc address.

  • Letter opener in dev model shows the email rendering perfectly
  • This error only shows up in production

the call to mailer is:

# template variables
merge_vars = {"AMOUNT" => "100"}

invoice = Invoice.new(customer)

attachments[invoice.name] = {
  data: invoice.invoice_data,
  mime_type: 'application/pdf'
}

mail(to: user.email, cc: cc_emails.compact.uniq, subject: mail_subject, content_type: content_type) do |format|
  # Template renders fine
  format.html{mandrill_template('invoice_template', merge_vars)}
end

InvoiceMailer < ActionMailer::Base has defaults for "from" and "reply_to"

Mandril gem version 1.0.53 and Rails 4.1.10.



via Chebli Mohamed

Gem "Malformed Version Number String"

I'm building a gem. I just got the basic project structure laid out, and I tried building it with gem build my_gem.gemspec, which worked fine. Then I installed it with gem install My\ Gem-0.0.1.gem and it still looked like it worked fine. Then I tried to run irb and I got this:

/Users/<username>/.rbenv/versions/2.2.2/lib/ruby/2.2.0/rubygems/version.rb:206:in `initialize': Malformed version number string on (ArgumentError)

Then I tried making some changes and saved them. I ran gem build my_gem.gemspec. Same error. All irb, rails, and gem sub-commands are generating a stack trace with this at the top. What did I do to break all of these commands and how do I reverse it?



via Chebli Mohamed

Is it possible to set Ruby ENV with bash in Chef?

I have a Chef recipe in which I am creating a new randomly named user using a shell script and exporting the username as a variable. Is it possible to set the same user as a session variable in Ruby? Something like...

ENV['CHEFUSER'] = 'echo $CHEFUSER'

which does not work unfortunately. Or any way to pass environment variables from bash to ruby. I need this new user to be recognized in the same recipe in which it was created.

Thanks, sorry if this has been addressed, I could not find any info on it.



via Chebli Mohamed

Paperclip S3 Bucket and Rails Images will upload but will not display

I am using paperclip gem along with an AWS s3 bucket to upload images to my app. I have it all working properly and the images will upload to the actual bucket and the web pages will load. The only problem is the images themselves will not display and it will only display their names like enter image description here

to display the image I am using the code

<%= image_tag @post.image.url(:medium), class: "edit_recipe_image" %>

has any one experiences this before or possibly know a solution to fix this?

Thanks in advance!



via Chebli Mohamed

how to stub specific IDs only in cucumber test?

Very new to Ruby and cucumber, and i've got a controller that accepts an ID. Basically a rest API, so the client would call /cows/1234 and /cows/777. That would then route to getFluffyCow and pass :id = 1234 or 777.

My initial attempt is as follows:

allow(getFluffyCow).to receive(:call).with(1234).and_return(mock_cow1)
allow(getFluffyCow).to receive(:call).with(777).and_return(mock_cow2)

but the response is returning nothing. What am I doing wrong?

Thanks!



via Chebli Mohamed

attr_accessible error on rails 4.1.8 upon performing rake db:migrate on heroku

I am still learning Ruby (so I am a complete noob), right now I have my app successfully running locally but when trying to opening the apps on heroku , in which I first perform the heroku run rake db:migrate I stumbled upon a problem.. it tells me :

Running `rake db:migrate` attached to terminal... up, run.2149
-- attr_accessible(:pName, :pQuantity, :pMeter, :pWeight, :pSellPrice,  :pCategory, :pPic)
-- attr_accessible(:pName, :pQuantity, :pMeter, :pWeight, :pSellPrice, :pCategory, :pPic)
rake aborted!
NoMethodError: undefined method `attr_accessible' for #<ActiveRecord::Migration:0x007f2dc2ba45b8>
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:648:in `block in method_missing'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in `block in say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:621:in `say_with_time'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:641:in `method_missing'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:406:in `method_missing'
/app/db/migrate/20150802134246_create_inventories.rb:2:in `<class:CreateInventories>'
/app/db/migrate/20150802134246_create_inventories.rb:1:in `<top (required)>'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `block in require'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:232:in `load_dependency'
/app/vendor/bundle/ruby/2.0.0/gems/activesupport-4.1.8/lib/active_support/dependencies.rb:247:in `require'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:761:in `load_migration'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:757:in `migration'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:752:in `disable_ddl_transaction'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:1044:in `use_transaction?'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:954:in `rescue in block in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:951:in `block in migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:948:in `each'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:948:in `migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:807:in `up'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/migration.rb:785:in `migrate'
/app/vendor/bundle/ruby/2.0.0/gems/activerecord-4.1.8/lib/active_record/railties/databases.rake:34:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:migrate

I have been trying to find out the reason, after wondering around I found out about change in rails 4.0.0 in that attr_accessible are no longer used and we should use strong parameter instead, So removing the attr_accessible from model will solve the problem...

However, I have an empty Model, there is no attr_accessible everywhere i look. (beside this is weird why my apps runs locally but not on heroku?) I can't figured out why this error appear and where to look for solutions.. I have been trying to look at active_record file but am afraid of making any changes, any idea?

also, could anyone tell me any resources that can help me read this type of log errors? I have tried to read some articles but can't find one that is easy to understand for noobs like me... ;(



via Chebli Mohamed

Excluding/Including items from one array based on values from another

I have two arrays, one containing hashes, the other integers. They look like this (samples):

mainArray[0] = {"ID" => 23, "NAME" => "SALLY"}
mainArray[1] = {"ID" => 34, "NAME" => "BILL"}

idArray[0] = 432
idArray[1] = 34

I want to filter mainArray so that only entries in it whose ID values are in idArray make the cut. How can I best do this? I don't mind making a new array if that helps.



via Chebli Mohamed

How do I call exposed methods in C# DLL from Ruby on Linux using Mono?

I have a DLL which contains code that I would like to access from Microsoft Visual Foxpro as well as Ruby on Rails.

I set up a C# DLL and generated the corresponding .so file using Mono according to this question. mono --aot -O=all dlltest.so

As noted in that question, the function nm -Ca dlltest.so shows a form of my method, but FFI cannot see it.

Also as mentioned in that question, nm -D --defined-only dlltest.so indicates that my method is not defined. However, FFI can see and access the one that is defined as mono_aot_file_info.

It seems like the poster of that question was close to getting it to work, but I was unable to find anything about why the method is showing as not defined or how to change that.

Is there something I can do to define the methods in the .so file? Or is this not possible?

Note that the method is exposed in the DLL, and FoxPro can access it just fine.



via Chebli Mohamed

Ruby on Rails frontend and Java backend architecture?

I am building a Ruby on Rails webapp and it is great for the web front end, display, what the user sees etc. But I want request from a user that involves some heavy processing to be done inside a Java backend layer.

So my question what do you think is the best approach for joining these two layers up? I can think of two approaches:

  1. Building up the request into a JSON object in the Ruby on Rails layer and using RabbitMQ to send it as a message to the Java backend layer which sends another JSON object back in a message as a response. I tend to lean more towards this approach as there a nice RabbitMQ clients for Ruby and Java.

  2. Have a my Java layer running on a web server(such as Tomcat or maybe Netty?) that accepts HTTP requests from the Ruby on Rails layer and sends the response back through the server using HTTP?

Note any persistence will be handled by the Java layer also.

Any more ideas or and/or comments on the above two ideas would be great.

Thanks.



via Chebli Mohamed

In RubyMine How do I Reset the Current Stack Frame?

In IntelliJ IDEA, or Eclipse, while working with java I am able to reset the current stack frame while debugging. For example, if I am debugging a method and I make some changes or want to go back and look something over I can reset the current stack frame and the debug pointer will go back to the beginning of the method. Is there anything like that in RubyMine?



via Chebli Mohamed

Allow users to sort images based on category selected (paperclip gem) - Rails

Currently my home page (index.html.erb) shows all the user images loaded within the past 24 hours, which is part of posts. However I would like to add a form that allows the user to sort images based on their category and upload date. (For example images with the category music, uploaded within the past month) I understand how to query the database but I dont know how to take the user input. When I create a form, suing simple form: <%= simple_form_for @posts do |f| %>, it throws an error, saying I cannot use an object. Ive thought about ajax but it doesnt seem to work well with the paperclip gem, plus I rather get it done on the backend. I hope my issue well enough. If not feel free to comment as I will be around to respond. Thanks in advance.

Post Controller:
 def index  
 @posts = Post.all.where(created_at:(Time.now - 1.day)..Time.now)
 end

Schema for Post table:

create_table "posts", force: :cascade do |t|
t.string   "title"
t.string   "instagram"
t.text     "description"
t.datetime "created_at",                            null: false
t.datetime "updated_at",                            null: false
t.integer  "user_id"
t.string   "image_file_name"
t.string   "image_content_type"
t.integer  "image_file_size"
t.datetime "image_updated_at"



via Chebli Mohamed

Failing to use numeric characters within Ruby array as indices for a string

I am trying to use the numeric charecters from the array held within the positions argument as indices to access the characters of the string inside the string argument to subsequently print a new string. I have an idea of what I need to do to get it to work, but I am hung up.

Total code thus far:

  def scramble_string(string, positions)
    str = string
    pos = positions.join
    newstr = []
    i = 0
    while i < pos.length do
      return newstr.push(str[pos[i]])
      i += 1
    end
  end
  scramble_string("hello", [2, 3, 4, 5])

I suspect my problem lies within this part of the code...

return newstr.push(str[pos[i]])



via Chebli Mohamed

Ruby - DOS (Win32) path name to NT (native) path name

I need to get the NT (native) path of a file from the DOS (Win32) path in Ruby (1.9.3).

Meaning, I have the string:

dos_path = "C:\Windows\regedit.exe"

but I need:

nt_path = "\Device\HarddiskVolume1\Windows\regedit.exe"

Is there any way to do so? Thanks!



via Chebli Mohamed

Why weakly typed languages would not need abstract classes?

Someone told me that the reason why Ruby does not implement abstract classes (you have to implement it yourself using some intelligent tricks) is that it isn't strongly typed. Can anybody explain that to me?



via Chebli Mohamed

Error while installing Sass on Win8.1: "ERROR: While executing gem (Errno::EACCES) Permission denied @ rb_sysopen"

I installed Ruby via the official installer, installed the non x64 version just in case. Then I tried to install sass via the command line like on the http://ift.tt/1f0fI2t page, The following ensued:

sgarcia C:\Users\sgarcia
> gem install sass
Fetching: sass-3.4.16.gem (100%)
ERROR:  While executing gem ... (Errno::EACCES)
    Permission denied @ rb_sysopen - C:/Program Files (x86)/Ruby22/bin/sass.bat

Any ideas what could be causing this?



via Chebli Mohamed

A better way to do conditional active record statements?

I'm trying to figure out a better way to have one query here. I want to be able to send something to last where statement a wildcard so I can select all vendors. Right now if i don't include that line it doesn't filter by vendor so I essentially get all the purchase requests.

Any thoughts of a cleaner way to do these sorts of queries?

  if @vendor == "0" #checks for vendor
    @purchase_requests = PurchaseRequest.includes(:purchase_order)
                          .where(:created_at => @date_start..@date_end)
                          .where(:total_cost => @cost_beginning..@cost_end)
  else
    @purchase_requests = PurchaseRequest.includes(:purchase_order)
                          .where(:created_at => @date_start..@date_end)
                          .where(:total_cost => @cost_beginning..@cost_end)
                          .where("purchaseorder.VendorRef_ListID = ?", @vendor)
  end



via Chebli Mohamed

Unexpected label while trying to iterate over a ruby hash

I am in the process of trying to iterate over a ruby hash. I'll have to admit that my knowledge of ruby is very poor and i am in the process of trying to correct that, and so please bear with me if this is a very elementary question.

I am wondering if the syntax of my hash is off. The reason why it is looking the way that it is is because it is part of a rakefile, and i need to incorporate multiple addresses in this. (which i've never done, i've always only had 1 address to worry about) I know the solution to this is to build the addresses in as a rakefile, and then loop over them.

clinic.build_address.each do | build_address |
                            {
                              (city: "Minneapolis"
                              state: "MN"
                              address1: "316 10th ave"
                              zip: "55414"),
                              (city: "Hudson"
                              state: "WI"
                              address1: "119 Belmont Street"
                              zip: "54016")
                            }

With what I have right now I am getting an unexpected label (it is not liking that I have 'city:minneapolis')

Would anybody be able to take a quick look at what I have with this?



via Chebli Mohamed

How can I make files inaccessible to the user, but accessible to my program?

I am making a small game at the moment, and want it to be possible for users to save their characters, which will likely be stored in a text file. Is there any way to make this text file inaccessible to the user in the windows explorer or whathaveyou, so that save tampering is impossible (or at least harder), but also accessible to my program?



via Chebli Mohamed

I don't know why I can't display an image when I create a product using CarrierWave? I also get an error now when I want to edit my product.

I'm using Rails -v 4.2.1 & ruby 2.1.5p273 (2014-11-13 revision 48405) [x86_64-darwin14.0]

controllers/products_controller.rb

class ProductsController < ApplicationController
  before_filter :find_product, only: [:edit, :show, :update, :destroy]

  def index
    @products = Product.order("created_at DESC")
  end

  def show
  end

  def new
    @product = Product.new
  end

  def create
   @product = Product.new(product_params)

   if @product.save!
      flash[:success] = "Product created!"
      redirect_to products_path
    else
      flash[:danger] = "Error creating product."
      redirect_to new_product_path
    end
  end

  def edit
  end

  def update
    if @product.update_attributes(product_params)
      flash[:success] = "Product Updated!"
      redirect_to products_path
    else
      redirect_to "edit"
    end
  end

  private

  def product_params
    params.require(:product).permit(:name, :description, :price, :images)
  end

  def find_product
    @product = Product.find(params[:product_id])
  end
end

models/product.rb

class Product < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

uploaders/image_uploader.rb

class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  storage :file

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  version :thumb do
    process resize_to_fill: [200, 200]
  end 

  version :small_thumb, from_version: :thumb do
    process resize_to_fill: [20, 20]
  end

  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end
end



via Chebli Mohamed

Does ActiveSupport's Object#try method work with Thor::CoreExt::HashWithIndifferentAccess?

I'm working on a Middleman (Ruby) site. There are data objects which are instances of Thor::CoreExt::HashWithIndifferentAccess. However, it seems whenever I call try that I get nil.

I see that Thor::CoreExt::HashWithIndifferentAccess takes advantage of method_missing. Does this break how try works? Is anyone able to replicate this?

UPDATE: Here's a simple example. I'm using Middleman which provides access to data files.

# /data/people.yml
jane:
  name: Jane Doe
  age: 25
john:
  name: John Doe
  age: 25

Then in a template you have access to the data.people method which returns a Thor::CoreExt::HashWithIndifferentAccess instance:

data.people.inspect
 #=> {"jane"=>{"name"=>"Jane Doe", "age"=>25},"john"=>{"name"=>"John Doe", "age"=>25}}

data.people.class
 #=> Thor::CoreExt::HashWithIndifferentAccess

Now when I call try on anything I get nil:

data.people.jane
 #=> {"name"=>"Jane Doe", "age"=>25}

data.people.try('jane')
 #=> nil

data.people.try(:jane)
 #=> nil

data.people.try(:something_that_does_not_exist)
 #=> nil

data.people.jane.try(:name)
 #=> nil



via Chebli Mohamed

"Watir::Exception::NoMatchingWindowFoundException: browser window was closed" error when using IE with Page-Object

I'm running tests in Ruby Mine 2.7.1 using Page-Object + Rspec.

Environment: Windows 7 x64, Ruby 1.9.3 p551, IE 11.

Gems: watir, rspec, bundler, page-object

When i run tests in Chrome or Firefox everything is ok.

But when i try to run them in IE, the IE window with correct page gets opened and after that i get an error specified in Subject: "Watir::Exception::NoMatchingWindowFoundException: browser window was closed"

The point is that the browser is actually open at that moment and shows a correct page. (See the screencast showing what happens: http://ift.tt/1hhIBzU)

Test gets finished with an error and the config.after do section doesn't get executed because the browser window remains opened.

That error happens when the following code is executed:

before(:each) do

visit <ClassName>

end

Seems like the IEDriverServer loses connection with IE right after the page is opened.

The most confusing this is that in very rare cases, everything is working good, and in even more rare cases everything is working with significant slowdowns with timeout error at the end.

sleep <n> delays don't help.

I tried different versions of selenium-webdriver gem (it is required by watir gem), different versions of IEDriverServer for both x86 and x64 platforms - result is the same.

What do i do to set IEDriverServer not to lose the IE browser?



via Chebli Mohamed

How to implement sudo su in Ruby script?

I have sudo access to oracle user being non_root user (say guest_admin user). I need to login as oracle user to run some steps but my ruby script is failing at the very first step i.e., sudoing as oracle. Below is the piece of code.

require "java"
require "highline/import"
require "rubygems"
require 'rvm/capistrano'

curr =  File.expand_path(File.dirname(__FILE__))
$LOAD_PATH << curr  unless $LOAD_PATH.include? curr

system "sudo su - oracle"

I am getting the following error:

ruby test.rb

$rvm_path (/usr/local/rvm/scripts/rvm) does not exist.
/usr/local/rvm/scripts/rvm: line 171: __rvm_teardown: command not found
stty: standard input: Invalid argument
stty: standard input: Invalid argument

Can somebody help me fixing this? It's a show-stopper for me right now.

I tried to move require 'rvm/capistrano' at the end of the file but that dint help much.

Thanks.



via Chebli Mohamed

Check how many parameters block being passed has, and then invoke yield with different parameters

I want to know if something like this is possible, as hash.each does two different things based on arguments passed to block

{ "a"=>3, "b"=>2}.each {|k| puts k}

{ "a"=>3, "b"=>2}.each {|k,v| puts k}

Both output different things, and not just what's below..

a
b
..
a
b

i get this

a
3
b
2
..
a
b

So i want to know if there is a way to get my function to do something custom depending on the number of arguments of block being passed to it.

like this

def my_method do
   if yield.args==2
     yield("hi","bro")
   else 
     yield("what's up")
   end
end

my_method {|a,b| puts a; puts b;} //"hi" "bro"

my_method {|a| puts a; } //"whats up"



via Chebli Mohamed

Rails routes: Wrong singular for resources

I have the following line in my routes.rb (Rails 4.1.4):

resources :request_caches

However, when I run rake routes I get the following output:

request_caches    GET    /request_caches(.:format)            request_caches#index
                  POST   /request_caches(.:format)            request_caches#create
new_request_cach  GET    /request_caches/new(.:format)        request_caches#new
edit_request_cach GET    /request_caches/:id/edit(.:format)   request_caches#edit
request_cach      GET    /request_caches/:id(.:format)        request_caches#show
                  PATCH  /request_caches/:id(.:format)        request_caches#update
                  PUT    /request_caches/:id(.:format)        request_caches#update
                  DELETE /request_caches/:id(.:format)        request_caches#destroy

As you can see, Rails somehow maps request_caches plural to request_cach singular. But it should be request_cache. Is this some kind of special case, because of the word caches? I've also played around with

resources :request_caches, as: :request_cache

But this results in wrong routes like request_cache_index. And furthermore, I think this is a standard task and should be solved clearly using Rails intern route helpers.

So, what am I doing wrong?



via Chebli Mohamed

Using def_delegate with a hash

I know how Forwardable#def_delegate works with methods on objects, but is there a similar way to forward methods names to hash keys. Like:

hash = { some_value: 42, other_value: 31415 }
def_delegate :hash, :some_value, :other_value

Calling object.some_value should return 42

PS: def and class eval is a way, but is there a nicer way?



via Chebli Mohamed

why does the array elements change after block?

I am trying to solve this problem

Given a sentence containing multiple words, find the frequency of a given word in that sentence.

Construct a method named 'find_frequency' which accepts two arguments 'sentence' and 'word', both of which are String objects.

Example: The method, given 'Ruby is The best language in the World' and 'the', should return 2 (comparison should be case-insensitive).

Hint: You can use the method Array#count to count the frequency of any element in the given array.

Since the comparison should be case-insensitive. I use these code to help:

word = "the"
word_set = []
word.size.times do |i|
  word[i] = word[i].upcase
  word_set << word
  word[i] = word[i].downcase
end

Inside the block every time after upcase method the word does change and does add to the word_set, however when the block finish the word_set just contain the the the What is the problem?



via Chebli Mohamed

Travis CI command is not available from console

I've installed the travis gem

gem install travis

Installed successful, but travis login is not available from console (Ubuntu):

travis login
-bash: /usr/bin/travis: No such file or directory



via Chebli Mohamed

Rails 3: Displaying conversation list and selected conversation on the same page (using Mailboxer)

Framework: Rails 3/ Jruby with Mailboxer gem.

I want to create a Facebook style inbox page that allows a user to scroll through their Inbox, Sent Items and Trash, whilst keeping the selected conversation displayed on the right hand side of the page (like Facebook's implementation of the desktop inbox)

The action of clicking the conversation title should render that entire conversation to the right side of the page, avoiding the need of dedicating an entire page to one conversation within the web browser. This is so (in a later version) I can implement an AJAX call that will only refresh the conversation part of the page, whilst allowing the user to keep an eye on their conversation list.

My problem is, I'm completely stumped as to how this would be implemented, without the routing error No route matches [GET] "/conversations/20/show_conversation" that I'm currently getting. I'm fairly new to Ruby on Rails, so the whole routing side of things is a bit confusing.

My question how do I display all my conversations, as well as the transcript of one selected conversation (at any given time) on the same page. Preferably, I would like to avoid the use of Javascript/ jQuery and stick to the Ruby on Rails implementation, if possible.

Here's a screenshot of my "messages" page, where "Conversation.." (on the right) should display the transcript of the conversation I had with the target user.

enter image description here

My controller code for the current page:

class ConversationsController < ApplicationController
    before_filter :authenticate_user!
    before_filter :get_mailbox
    before_filter :get_conversation, except: [:index]
    before_filter :get_box, only: [:index]
    before_filter :get_conversation, except: [:index, :empty_trash]

    def index
        @conversations = @mailbox.inbox.paginate(page: params[:page], per_page: 10)
        @inbox = @mailbox.inbox.paginate(page: params[:page], per_page: 10)
        @trash = @mailbox.trash.paginate(page: params[:page], per_page: 10)
        @sent = @mailbox.sentbox.paginate(page: params[:page], per_page: 10)
    end

    def show_conversation
        @conversation
        redirect_to conversations_path
    end 

    [...]

    private 

    def get_mailbox
        @mailbox ||= current_user.mailbox
    end

    def get_conversation 
        @conversation ||= @mailbox.conversations.find(params[:id])
    end

    def get_box
        if params[:box].blank? or !["inbox","sent","trash"].include?(params[:box])
            params[:box] = 'inbox'
        end
        @box = params[:box]
    end
end

My corresponding views: index.html.erb

<% page_header "Your Conversations" %>

<p><%= link_to 'Start conversation', new_message_path, class: 'btn btn-lg btn-primary' %> 
<%= link_to 'Empty trash', empty_trash_conversations_path, class: 'btn btn-danger', 
    method: :delete, data: {confirm: 'Are you sure?'} %></p>

<!-- tab things, they're awesome -->
<div class="left_col">
  <div class="col-sm-3">
    <ul class="nav nav-pills">
      <%= mailbox_section 'inbox', @box %>
      <%= mailbox_section 'sent', @box %>
      <%= mailbox_section 'trash', @box %>
    </ul>
  </div>

  <!-- this working part isn't in the tutorial -->
  <% if @box == 'trash' %>
    <%= render partial: 'conversations/conversation', collection: @trash %>
  <% elsif @box == 'inbox' %>
    <%= render partial: 'conversations/conversation', collection: @inbox %>
  <% elsif @box == 'sent' %>
   <%= render partial: 'conversations/conversation', collection: @sent %>
  <% end %>   
  <%= will_paginate %>
</div>

<div class="right_col"> 
  <p><small>Conversation...</small></p>
  <%= @conversation %> <!-- should I have a partial or something? -->
</div>

_conversation.html.erb partial where the link to show_conversation is

<%= link_to conversation.subject,   show_conversation_conversation_path(conversation) %>

<div class="btn-group-vertical pull-right">
    <% if conversation.is_trashed?(current_user) %>
        <%= link_to 'Restore', restore_conversation_path(conversation),
                         class: 'btn btn-xs btn-info', method: :post %>
    <% else %>
        <%= link_to 'Move to trash', conversation_path(conversation), 
                         class: 'btn btn-xs btn-danger', method: :delete,
                  data: {confirm: 'Are you sure?'} %>

        <% if conversation.is_unread?(current_user) %>
            <%= link_to 'Mark as read', mark_as_read_conversation_path(conversation), 
                    class: 'btn btn-xs btn-info', method: :post %>
        <% end %>
    <% end %>
</div>

<p><%= render 'conversations/participants', conversation: conversation %></p>

<p><%= conversation.last_message.body %>
  <small>(<span class="text-muted">
<%= conversation.last_message.created_at.strftime("%-d %B %Y, %H:%M:%S") %>
</span>)</small></p>

And finally, my routes.rb

resources :conversations, only: [:index, :show, :destroy] do
    member do
        post :reply, :restore, :mark_as_read, :show_conversation
    end

    collection do 
        delete :empty_trash
    end
end

resources :messages, only: [:new, :create]

root :to => 'conversations#index'

I do have a working conversation partial that builds the conversation on a separate page. It works fine, but I haven't included it because I want to move away from having a separate page to view the conversation. Any help on this would be greatly appreciated!

Thanks,



via Chebli Mohamed

How can I get zbar to deploy on Heroku?

I am using the ruby-zbar gem in a rails app to scan barcodes from jpgs. I installed the zbar library using homebrew on my local machine and everything works fine. However, when deploying to Heroku I consistently get errors such as the following:

remote:        LoadError: Didn't find libzbar on your system
remote:        Please install zbar (http://ift.tt/refsyg) or set ZBAR_LIB if it's in a weird place
remote:        FFI::Library::ffi_lib() failed with error: library names list must not be empty

I've tried following the advice from this Stack Overflow post (Heroku Zbar Didn't find libzbar on your system (LoadError)), namely to set the ZBAR_LIB ENV variable to /app/vendor/lib/libzbar.so, or failing that to run heroku bash and try to find a file named libzbar.so and point ZBAR_LIB to its path.

However, I can't seem to find the heroku buildpack referenced in the original Stack Overflow post (the link to http://ift.tt/1mpaR2J goes to a 404 page), so I can't replicate the solution outlined there.

I have tried all of the following buildpacks:

http://ift.tt/1ImOq5Q
http://ift.tt/1KO1BT3
http://ift.tt/1ImOsdY

During the build process I can see hopeful messages like this:

remote: -----> Multipack app detected
remote: -----> Fetching custom git buildpack... done
remote: -----> ZBAR app detected
remote: -----> Downloading and installing ZBAR
remote: -----> Configuring ZBAR
remote: -----> Make!
remote: -----> Make install !!!
remote: -----> Writing profile script
remote: -----> Fetching custom git buildpack... done
remote: -----> Ruby app detected
remote: -----> Compiling Ruby/Rails
remote: -----> Using Ruby version: ruby-2.2.1

But setting ZBAR_LIB to /app/vendor/lib/libzbar.so gives me some version of this error:

remote:        LoadError: Didn't find libzbar on your system
remote:        Please install zbar (http://ift.tt/refsyg) or set ZBAR_LIB if it's in a weird place
remote:        FFI::Library::ffi_lib() failed with error: Could not open library '/app/vendor/lib/libzbar.so': /app/vendor/lib/libzbar.so: cannot open shared object file: No such file or directory

And trying to find libzbar.so on heroku run bash has not been successful for me -- I can see many files that are similar in name (even a libzbar.rc) but none that fits the bill.

~ $ find / -name '*libzbar*'
find: `/var/lib/polkit-1': Permission denied
/app/vendor/zbar/plugin/.deps/plugin_libzbarplugin_la-plugin.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-QZBar.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-QZBarThread.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-moc_QZBarThread.Plo
/app/vendor/zbar/qt/.deps/qt_libzbarqt_la-moc_QZBar.Plo
/app/vendor/zbar/gtk/.deps/gtk_libzbargtk_la-zbargtk.Plo
/app/vendor/zbar/gtk/.deps/gtk_libzbargtk_la-zbarmarshal.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-symbol.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-video.o
/app/vendor/zbar/zbar/zbar_libzbar_la-error.lo
/app/vendor/zbar/zbar/processor/zbar_libzbar_la-lock.lo
/app/vendor/zbar/zbar/processor/.libs/zbar_libzbar_la-lock.o
/app/vendor/zbar/zbar/processor/zbar_libzbar_la-lock.o
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-null.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-x.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-posix.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-lock.Plo
/app/vendor/zbar/zbar/processor/.deps/zbar_libzbar_la-win.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-config.o
/app/vendor/zbar/zbar/zbar_libzbar_la-processor.o
/app/vendor/zbar/zbar/zbar_libzbar_la-refcnt.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-convert.o
/app/vendor/zbar/zbar/zbar_libzbar_la-video.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-window.o
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-null.Plo
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-v4l1.Plo
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-v4l2.Plo
/app/vendor/zbar/zbar/video/.deps/zbar_libzbar_la-vfw.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-processor.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-image.lo
/app/vendor/zbar/zbar/zbar_libzbar_la-refcnt.o
/app/vendor/zbar/zbar/zbar_libzbar_la-error.o
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-qrdectxt.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-binarize.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-isaac.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-rs.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-qrdec.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-bch15_5.Plo
/app/vendor/zbar/zbar/qrcode/.deps/zbar_libzbar_la-util.Plo
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-video.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-config.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-processor.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-convert.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-window.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-refcnt.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-error.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-img_scanner.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-image.o
/app/vendor/zbar/zbar/.libs/zbar_libzbar_la-symbol.o
/app/vendor/zbar/zbar/zbar_libzbar_la-img_scanner.o
/app/vendor/zbar/zbar/zbar_libzbar_la-image.o
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-null.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-dib.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-xv.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-x.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-ximage.Plo
/app/vendor/zbar/zbar/window/.deps/zbar_libzbar_la-win.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-img_scanner.lo
/app/vendor/zbar/zbar/libzbar.rc
/app/vendor/zbar/zbar/zbar_libzbar_la-symbol.o
/app/vendor/zbar/zbar/zbar_libzbar_la-config.lo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-decoder.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-config.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-convert.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-processor.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-symbol.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-scanner.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-error.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-jpeg.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-video.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-window.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-refcnt.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-svg.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-img_scanner.Plo
/app/vendor/zbar/zbar/.deps/zbar_libzbar_la-image.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-window.lo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-code39.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-pdf417.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-qr_finder.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-i25.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-ean.Plo
/app/vendor/zbar/zbar/decoder/.deps/zbar_libzbar_la-code128.Plo
/app/vendor/zbar/zbar/zbar_libzbar_la-convert.lo

Has anyone had success getting zbar to run on heroku? If so, what buildpack did you use? I would be thrilled to learn how to make this work.



via Chebli Mohamed

Elasticsearch stops after import data from model

  1. I deployed my app to vps.
  2. Started Elasticsearch, and checked it with ps aux | grep elasticsearch
  3. cd app/currect && RAILS_ENV=production bin/rails c
  4. User.import

    Output:

    Scoped order and limit are ignored, it's forced to be batch order and batch size  
      User Load (0.4ms)  SELECT "users".* FROM "users"  ORDER BY "users"."id" ASC LIMIT 10
    Faraday::ConnectionFailed: connection refused: localhost:9200
    
    
  5. Elasticsearch stopped and import doesn't work, why ?

I am using Ubuntu 14, Puma server, SQLite database. Does it matter?

Additional notes:

http://ift.tt/1P3OOuv - gemfile.lock from project

http://ift.tt/1IVORti - elasticsearch config

http://ift.tt/1P3OOux - elasticsearch log

Before User.import

ps aux | grep elasticsearch

shows elasticsearch process

After User.import ps aux | grep elasticsearch doesn't show process

How to check if elasticsearch uses 9200 port ?



via Chebli Mohamed

Finding a definition of a method in a big github repository

I'd like to know the definition of method from a huge github repository (say from example i want to see the definition of super method in this github repository).

Are there any tools to do it quickly?



via Chebli Mohamed

Ruby- web api with rest client gem

I'm new in Ruby (and in developing too) and I would like to get the response from another url (my url) in the get method.

i'm using rest-client gem.

I have tried this code:

class UsersController < ApplicationController require 'rest-client' def index

RestClient::Request.execute( method: :get, url: 'https://my-url')

end

end

but when I open http://localhost:3000/users I get a blank page

Thanks in advance,

Joel



via Chebli Mohamed

define_method with predefined keyword arguments

I want to define a method that takes keyword arguments. I would like it to raise when keyword arguments are not provided, and I can code this myself - but ideally I would like to let Ruby do that for me. Also I would like to be able to inspect the freshly defined method using Method#parameters. If I use a shorthand double-splat (like **kwargs) the actual structure I expect is not visible to parameters.

I can of course do this:

define_method(:foo) do | foo:, bar: |
  # ...
end

which achieves the desired result:

method(:foo).parameters
# => [[:keyreq, :foo], [:keyreq, :bar]]

but I cannot pass those arguments programmatically, they have to be literally placed in the code. Is there a way I could bypass this?



via Chebli Mohamed

Push websocket notification with Faye from Observer in Rails 4

I'm trying to build a simple websocket notification system using rails observers gem and faye. The problem is that I can't publish with faye from the observer.

First I created the observer:

class ScoreObserver < ActiveRecord::Observer

     def after_save(score)
       @notification = Notification.new(user_id: '2', content: '¡rororscoreeeeeeeeeeeeee!')
       if @notification.save
          client = Faye::Client.new('http://localhost:9292/faye')
          client.publish("/messages/new", {
            'title' => 'testitle',
            'content' => 'testcontent'
            })
       end      
     end

end

As you can see it 'observes' the scores model and insert a record in the notifications table. After that I want it to push a notification with faye using pubilsh.

Then in the client side I run the subscribe script

$(function() {
  var faye = new Faye.Client('http://localhost:9292/faye');
  faye.subscribe("/messages/new", function(data) {
    eval(data);
    alert('it works')
  });
});

And it doesn't work. The observer is aware of the action and makes the record save correctly but the client doesn't receive any push from the websocket.

I've tested the subscription with a simple broadcast and it works so it seems that is the observer part which is failling. Websockets are up and listening

Do you have any clue of what could be wrong ?

I was looking for an alternative just in case this approach is wrong, and I thought about render a script from the observer and broadcast/publish from a .js file, since all the tuts do it from a script. But I'm having some trouble with this approach too, I can't render a script from the observer in respond_to since the model extends from Observer and not from Base and doesn't have the method.

Thanks



via Chebli Mohamed

Rails: Order by associate, first not downloaded

I have problem with displaying files. My app:

class User
   has_many :downloads
   has_many :downloaded_files, :through => :downloads, source: :file
end

class File 
   attr_accessor :downloaded

   has_many :downloads
   has_many :users, :through => :downloads
end

class Download
   belongs_to :user
   belongs_to :file
end

And when an user logs in I want to display all files, but files downloaded by current user should be displayed last. The file table has about 500 records so I need simple and fast method to achieve this. How to do this?

The technologies I am using

  • Rails 4.2.1
  • Ruby 2.2.2
  • PostgreSQL


via Chebli Mohamed

Convert Jira's time tracking field format to hours

I am using JIRA api to extract timespent by users on issues. The time spent is in the format:

"12w 1d 2h 5m" or "12h" or "12m" etc

The API isn't exporting the number of hours. Is there a quick (requires no effort on my part) way to convert this to hours (or seconds). I suppose this is some sort of a standard format, is there a name for it? I know how to do this myself, just don't want to reinvent the wheel



via Chebli Mohamed

how can I convert a string to JSON in Ruby

I have read the data online but it is in a string format. I've also researched online but the few examples I checked returned string format too. How can i make it so that it returns a JSON object.

assuming the result of reading the data was

text = '{"one":1,"two":2}'

then i used:

data = JSON.parse(text).to_json 

but when i do

puts data.class

the result is still a string



via Chebli Mohamed

How to reference a file outside of model in Rails?

I'm adding the carrierwave gem to an app in Rails, and I'm getting a weird NameError. I've followed all other posts on it, yet none of them worked. Here's the error:

uninitialized constant Post::ImageUploader

Extracted source (around line #2):
class Post < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

And post.rb:

class Post < ActiveRecord::Base
  mount_uploader :image, ImageUploader
end

Also, here's one site that I went to, but it didn't describe where to place the code, so I got really confused.

Can anyone help me figure out what's going on? Thanks.



via Chebli Mohamed

lundi 29 juin 2015

Adding counted rows to running number in UPDATE

I am trying to UPDATE usernames to our database, but I have problem with UQ.

In our schema we have corporate admin users and contacts in the same table. Every corporate has 1 admin user which where composed by taking 6 characters from their name and adding running number (if there were 6 character duplicates).

For example:

CompanyName: Test Company
UserName: testco-1

Running number with admin users (with the same 6 character start) varies from 1 to 15(ish).

Our contact table has column CorporateAdminId which is set to NULL with Admin users, but contacts are referred to admin user with this field. So the table has a relationship to itself.

NOTE: Before contacts did not have usernames Because software upgrades our contacts need to have username also. Usernames to contacts are created with the same rule (6 char+running number) and the first 6 characters are defined by AdminUserId reference (not the contacts own corporate name)

For example:

AdminUserId: GUID (Refers to Test Company)
CompanyName: Data miner
UserName: testco-2

My problem here is that how can I count how many usernames there are in the database at the moment that start f.e with 'testco' and add this number to the running number that I use to create contact usernames (so there will be no collissions with UQ)

SQL : stored procedure won't return any error message or number

Here is my insert stored procedure:

CREATE PROCEDURE spainsert 
    @A_Name nvarchar(50) 
AS BEGIN 
   BEGIN TRY
      DECLARE Detailed_Error VAR_CHAR(MAX); 

      Insert into A(A_Name) 
      values(A_Name) 
   END TRY 
   BEGIN CATCH
       SELECT 
          Detailed_Error = CAST(ERROR_NUMBER() AS VAR_CHAR ) + ' : '+ ERROR_MESSAGE() + ' : ' + CAST(ERROR_LINE() AS VAR_CHAR );
   END CATCH 
END 

When I try to enter NUMBER instead of NAME : exec spa insert 500, it won't show any error, but just saves that row into table. Could you please help me how to handle errors, how to know the number and the error message ?!

Thank you all ! 123456787523535464654645654651541541255435.4153241653241636524165324135

SQL Server float data type

I started this thread SQL Server float data type understanding

And the following question is partially related to it, so I bring it up back here.

Documents and SQL Server users say that float(8 bytes) and real(4 bytes) data types are for approximate use only. I can see that via use of SQL Server Management Studio and some simple queries like

declare @f float=0.000123456789123456789;
select @f;

where the output becomes 0.000123456789123457 (auto round-off error) as the precision is set to 15 non-zero digits and after the decimal point.

I think the output by SQLServer Management Studio is implementation defined. Because the byte series fed into the system is transformed into a long bit integer then cast into a float type of the same precision depending upon the language being used to implement the system and the casting functions. If the main cause lies right at this point then I think the approximation issue can be fixed. That is to reprogram the functions with data streaming to get back the exact values as previously input.

However, I still wish to learn what other particular examples you know about that can exhibit their approximate error symptoms ?

I still do have another question mentioned also in my previous thread about the byte order and its transformation of float and real data type when it is being processed in either big and little endian systems. If someone could offer me some ideas, it would be really awesome. My take on this is that float is fixed on little endian, real is not an exception because they are different only in the storage. Their functions are totally the same. Yet confirmation from experts over this is badly needed.

SQL find missing language entries in table

I have a table which is missing some entries for a certain language. How can I get a list of all language text in english (lang 1 in table) which is missing the foreign translation counterpart (lang 2)

My table is as follows

PageName | LanguageNo | TranslationName | TranslationText   |
main     |     1      | SomeName        | some english text |
main     |     2      | SomeName        | some foreign text |
main     |     1      | SomeName2       | some english 2    |
other    |     1      | SomeName3       | some english 3    |
other    |     2      | SomeName3       | some foreign 3    |

For example, using the above table data, only the following should be returned:

main     |     1      | SomeName2       | some english 2    |

How can I write a SQL statement to achieve this?

Thanks

SSIS Balanced Data Distributor 2014 SP1 for VS 2012 doesn't work

I'm trying to install SSIS Balanced Data Distributor 2014 SP1 for Visual Studio 2012, but this component is not displayed in the SSIS Toolbox.

I install x86 version of this component. The TxBDD.dll is located in the directory correctly: C:\Program Files\Microsoft SQL Server\120\DTS\PipelineComponents

How can I fix it?

Thanks!

How to convert code from SQL Server to Oracle

I wrote this code in SQL Server. I want to write this code for Oracle and PL/SQL. Could anyone help me how I can do this job?

SQL Server / T-SQL:

ALTER TRIGGER [dbo].[checkBalance]
   ON  [dbo].[Orders]
FOR insert
AS
BEGIN
    IF (SELECT goodcount FROM goods WHERE id=(SELECT gid FROM Inserted)) < (SELECT gcount FROM Inserted)
    BEGIN
        RAISERROR ('Inventory is low',10,1)
        rollback
    END 

How to insert value in NULL from another corresponding row?

How to join for 3 tables, so that some null values in result, can be replaced.

I tried this:

SELECT        ISNULL(Culture,CultureInfoCode) as Culture, ISNULL(Name,'NA') as Name,  ISNULL(Value,'NA') as Value
FROM            SiteLanguages Left JOIN
                         WebDbResources ON SiteLanguages.CultureInfoCode = WebDbResources.Culture Left JOIN
                         KeyWebDbResources ON WebDbResources.KeyWebDbResourceID = KeyWebDbResources.KeyWebDbResourceID
                         where Status=1

Here is the result

Culture  Name                                                 Value
en-US    Key_FirstName                                        John
TR       NA(Here It should also be Key_FirstName)             NA (ok)

But I want Name field in second row as Key_FirstName and Value NA (For corresponding TR Culture).

Here is the schema:

SiteLanguages:

CultureInfoCode Status
en-US            1
TR               1
AR               0

KeyWebDbResources:

KeyWebDbResourceID  Name
1                   Key_FirstName

WebDbResources:

WebDbResourceID  KeyWebDbResourceID   Culture   Value
1                   1                  en-US    FirstName

Second translation does not exist for TR, that's why I want to Fill null on join having Culture and key.

Published to Azure VM with MSSQL, SQL DELETE not working

Published my ASP.net finally as i was knew to it and had a few things to sort out. But I managed it.

The page runs fine, and the SQL server saves data, pulls the data for the next session, but it will not delete the data.

This only happens on the Azure VM, locally it works fine without any problems.

Im thinking its probably some sort of setting?

Does anyone know what can be wrong.

Thanks

how to export transparent data to encrypted database in sql server

I want to move/copy transparent data from a database to another database having same tables structure but encrypted. How can i do this job?

How to run to a sequence from stored procedure?

I am trying to run a sequence from a stored procedure. I am passing the name of the sequence to the stored procedure and the stored procedure will return the sequence value, but the stored procedure is not recognizing the passed sequence name. the error says:Incorrect syntax near '@SeqName'.

Here what I have tried:

ALTER PROCEDURE [dbo].[GetSeqNextValue] (@SeqName varchar(50), @NewNum bigint output) 

AS

BEGIN
          SET @NewNum = NEXT VALUE FOR @SeqName
END

SQL Server connection in Wildfly using JTDS driver

What is the correct way to setup a SQL Server datasource on Widlfly?

I need to access a SQL Server database from my web application which runs on Wildfly.

I have setup the datasource as follows:

<datasource jta="false" jndi-name="java:jboss/db" pool-name="db" enabled="true" use-ccm="false">
    <connection-url>jdbc:jtds:http://sqlserverIP_ADDRESS;instance=SQLEXPRESS;DatabaseName=DB</connection-url>
    <driver-class>net.sourceforge.jtds.jdbc.Driver</driver-class>
    <driver>jtds-1.3.1.jar</driver>
</datasource>

This works fine except that when the SQL Server is restarted, the connection is lost and the datasource doesn't manage to recreate one. So I get errors like:

Invalid state, the Connection object is closed.

This post suggests adding some validation, so I did this:

<validation>
    <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
    <validate-on-match>false</validate-on-match>
    <background-validation>false</background-validation>
</validation>

But that does not solve the problem and I still get the same "connection closed" error from time to time.

This other post suggests using a DataSource instead of a Driver, so I have added this to my configuration:

    <datasource-class>net.sourceforge.jtds.jdbcx.JtdsDataSource</datasource-class>

But when I test the connection I get an exception:

java.sql.SQLException: The serverName property has not been set.
at net.sourceforge.jtds.jdbcx.JtdsDataSource.getConnection(JtdsDataSource.java:150)

In mssql: when I SUM values of each month between 2 dates, I get the wrong value

I am really struggling with a query. I want the sum of each month between Aug 2014 and July 2015. If I specify the between dates in the where clause it sums all the months.

Here is my query:

DECLARE @CurrentYear int = DATEpart(year,getdate()) 
DECLARE @PreviousYear int = DATEpart(year,getdate()) -1
SELECT  
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'08') THEN a.balance ELSE 0 END) AS BalanceAug ,
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'09') THEN a.balance ELSE 0 END) AS BalanceSep ,
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'10') THEN a.balance ELSE 0 END) AS BalanceOct ,
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'11') THEN a.balance ELSE 0 END) AS BalanceNov ,
SUM(CASE WHEN a.fin_period = concat(@PreviousYear,'12') THEN a.balance ELSE 0 END) AS BalanceDec ,
...etc.
FROM subaccount_history a with (nolock) 
WHERE fin_period between concat(@PreviousYear,'08') and concat(@CurrentYear,'12')

The issue is with the between clause, i tried group by but that also doesn't work. It sums everything between the 2 dates specified.

SQL SERVER - Return rows in stored procedure

For starters, I'm fairly new to SQL.

So, I am trying to develop an application in asp.net with blogs and categories in two languages. One of the functionalities is returning the name of a category in a particular language. Not all categories have two languages. Some have English, others have Italian, others have both. Here's the function that performs the select i was talking about.

DECLARE @Name NVARCHAR(250)
IF EXISTS(SELECT Name = Coalesce(BlogCategoryTranslation.Name, ' ')
FROM BlogCategoryTranslation WHERE BlogCategoryID = @CategoryID AND LanguageID=@LanguageID)
BEGIN   
    SET @Name=(SELECT Name
    FROM BlogCategoryTranslation WHERE BlogCategoryID = @CategoryID AND LanguageID=@LanguageID) 
END 

ELSE
BEGIN
    SET @Name=(SELECT top 1 Name FROM
    BlogCategoryTranslation WHERE BlogCategoryID = @CategoryID AND LanguageID=@LanguageID);
END

RETURN @Name

Now I have a stored procedure that returns the Category Name for a given language. What I want is to always return a Category. If it doesn't exists in a particular language, i want to display the record in other language. Is this possible and if it is, what would be the suggestions in order to do that.

ALTER PROCEDURE [dbo].[BlogCategoryLanguage]
    @BlogCategoryID INT,
    @LanguageID INT
AS
BEGIN

SELECT BlogCategoryID AS 'CategoryID',
    Language.Name AS 'Language',
    dbo.BlogNameCategoryByLanguage(1,1) as 'Name',
    dbo.Blog_PublishedInCategory(1,BlogCategory.ID) AS 'Published'
FROM BlogCategoryTranslation
INNER JOIN BlogCategory 
        ON BlogCategory.ID = BlogCategoryTranslation.BlogCategoryID
INNER JOIN Language 
        ON Language.ID = BlogCategoryTranslation.LanguageID
WHERE BlogCategoryID = 1

I would really appreciate a few tips. It's the first time i have posted a question here and I'm not quite sure how this works. If this is a repost somehow, sorry for that.

Why am I getting a deadlock when my code is accessed multiple times?

In my c# code I have the following method that creates a document in the database, adds metadata regarding the document to the database and then updates some information regarding the date the repository was last updated. This method is often called numerous times in quick succession as multiple file uploads are common. However I am having problems with the code failing due to deadlock in sql server.

private IEnumerable<DocumentMetadata> CreateDoc(int? jobId, int?repositoryId, int? folderId, string documentTypeString,       IEnumerable<DocumentModel> files)
{
    if ((jobId == null && repositoryId == null) || (jobId != null && repositoryId != null))
        {
            throw new InvalidOperationException("Either job id or repository id must be specified");
        }
    using (var tran = new TransactionScope())
    {
        List<DocumentMetadata> newDocuments = new List<DocumentMetadata>();

        var documentType = GetDocumentTypeByPrefix(documentTypeString);

        if (folderId == null)
        {
            // Find the root folder
            var job = getJob(jobId);
            var rootFolder = getRootFolder(job);

            // If we can't find a root folder, create one
            if (rootFolder == null)
            {
                rootFolder = CreateRootDirectory(job);
            }

            folderId = rootFolder.FolderId;
        }

        User currentUser = _userService.GetCurrentUser();

        foreach (var file in files)
        {
            var document = new Document() { Document1 = file.Data };
            var documentMetadata = new DocumentMetadata
            {
                Document = document,
                CreatedDate = file.CreatedDate,
                FileName = file.Filename,
                FileSize = file.Data.Length,
                FolderId = folderId,
                DocumentType = documentType,
                JobId = jobId,
                RepositoryId = repositoryId,
                User = currentUser
            };

            _unitOfWork.DocumentMetadata.Add(documentMetadata);
            newDocuments.Add(documentMetadata);
        }

        // set repository updated date 
        if (repositoryId != null)
        {
            DocumentRepository repo = GetDocumentRepository(repositoryId);
            if (repo != null)
            {
                repo.UpdatedDate = new DateTimeOffset(DateTime.Now);
            }
        }

        _unitOfWork.SaveChanges();
        tran.Complete();

        return newDocuments;
    }
}

After some debugging it would appear that the updating of the repository id is causing the deadlock problem. If I remove this code block outside of the transaction all files are saved with no errors.

Why would this code block

if (repositoryId != null)
        {
            DocumentRepository repo = GetDocumentRepository(repositoryId);
            if (repo != null)
            {
                repo.UpdatedDate = new DateTimeOffset(DateTime.Now);
            }
        }

cause the deadlock? No other access is being made to the DocumentRepository table apart from in this method - as the locks are obtained in the same order surely there should be no deadlock?

What is it about this code that is leading to deadlock?

Updated: The code for GetDocumentRepository is:

 public DocumentRepository GetDocumentRepository(int repositoryId) 
 { 
     var result = DocumentRepositories.SingleOrDefault(x => x.RepositoryId == repositoryId); return result; 
 }

Ensuring the database connection opens and closes every time I use Dapper to access the database

Here is what I am currently doing in one of my repository classes:

private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString);

public IEnumerable<Product> GetProducts(int categoryId = null, bool? active = null)
{
    StringBuilder sql = new StringBuilder();
    sql.AppendLine("SELECT * ");
    sql.AppendLine("FROM Product ");
    sql.AppendLine("WHERE @CategoryId IS NULL OR CategoryId = @CategoryId ");
    sql.AppendLine("  AND @Active IS NULL OR Active = @Active");

    return this.db.Query<Product>(sql.ToString(), new { CategoryId = categoryId, Active = active }).ToList();
}

One thing I want to do is put the IDbConnection property in a BaseRepository that all of my other repos inherit from. What do I do to ensure my database connection opens and closes properly in each of my data access functions like the example above? Here is what I currently do with Entity Framework (w/ a using statement around each function, but now I am switching the DAL to use pure Dapper:

using (var context = new MyAppContext())
{
    var objList = (from p in context.Products
                   where (categoryId == null || p.CategoryId == categoryId) &&
                         (active == null || p.Active == active)
                   select p).ToList();

    return objList;
}

I noticed in the Dapper examples that everything is wrapped in a using statement like I would expect, but occasionally I see them wrapping their functions in the follow using:

using (var connection = Program.GetClosedConnection())

GetClosedConnection() returns a new SqlConnection, but what is the difference between the two?

public static SqlConnection GetOpenConnection(bool mars = false)
{
    var cs = connectionString;
    if (mars)
    {
        SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(cs);
        scsb.MultipleActiveResultSets = true;
        cs = scsb.ConnectionString;
    }
    var connection = new SqlConnection(cs);
    connection.Open();
    return connection;
}
public static SqlConnection GetClosedConnection()
{
    return new SqlConnection(connectionString);
}

Truncate selected tables in SQL Server

How to truncate selective tables in SQL Server 2008, I have a list of tables which may be excluded during truncate process.

Anybody can guide?

Date wise optional parameter searching in SQL Stored Procedure

I want to take a leave report from my leave application table when I search. In the table I have Leavefrom(datetime), LeaveTo(datetime) columns. Now I want to take the rows on the basis of these two columns. My searching parameters are nullable they are @employeeid, @datefrom, @dateto.

I need to get the result must between the date of Leavefrom, LeaveTo. I am trying to make a stored procedure for this.

ALTER PROCEDURE [dbo].[SP_GetSpecificLeaveReport]
@empid int=null,
@leavefrom date=null,
@leaveto date=null
AS
BEGIN
    SET NOCOUNT ON;
    SELECT ela.appliedDate,ela.appliedBy,ela.leaveFrom,ela.leaveTo,ela.noOfDays,
    ejd.firstName,ejd.lastName,
    ltm.leaveType
    from dbo.tblEmployeeLeaveApplication as ela inner join dbo.tblEmployeeJobDetails as
    ejd on ela.empId=ejd.recordId inner join dbo.tblLeaveTypeMaster as ltm 
    on ela.leaveTypeId=ltm.record_Id where



END

SQL Select statment with remove first row

I have multiple rows in table, I'm using select statement to fetch the details.

select * from pdetails where pcode='P000437' 

Result

enter image description here

my query print 3 records but I don't want to print first row.

Is there any option to use select statement with condition to count and remove first row.

Query is giving invalid column error

I have a query which is giving me error as

Column 'designation' does not belong to table Table.

Here is my query:-

Select  upper(ra1user.first_name +  ' ' + ra1user.last_name)  RA1_Name, " +
                       "ra1user.email As RA1_Email_ID,  upper(ra2user.first_name + ' ' + ra2user.last_name) [RA2 Name], " +
                       "ra2user.email As RA2_Email_ID, upper(Emp_name) empName, " +
                       "um.email As empEmail_ID, upper(empDesignation) empDesignation, " + 
                       "(select CONVERT(VARCHAR(10),dateadd(mm,1,DATEADD(dd,-(DAY(getdate())-1),getdate())),101)) " +
                       "as empConfirmation_Date  , " +
                       "convert(varchar(10), em.date_of_Joining, 103) as date_of_Joining " +
                      "from    emp_mst em " +
                       "join user_mst um on um.employee_mkey = em.mkey  " +
                       "left join user_mst ra1user on ra1user.employee_mkey = em.reporting_to  " +
                       "left join user_mst ra2user on ra2user.employee_mkey = em.reporting_to2  " +
                       "join type_mst_a desig on em.new_design_mkey=desig.master_mkey " +
                        "where  em.emp_card_no="

Data conversion failed -"The value could not be converted because of a potential loss of data."

I have a simple data flow where I read data out of a table, do some data conversions, and load it into another table:

enter image description here

However when I run the package I get the following errors:

Error: 0xC02020C5 at Atish to CRM, Data Conversion [142]: Data conversion failed while converting column "CAMPAIGNNAME" (28) to column "Copy of CAMPAIGNNAME" (203).  The conversion returned status value 2 and status text "The value could not be converted because of a potential loss of data.".
Error: 0xC0209029 at Atish to CRM, Data Conversion [142]: SSIS Error Code DTS_E_INDUCEDTRANSFORMFAILUREONERROR.  The "Data Conversion.Outputs[Data Conversion Output].Columns[Copy of CAMPAIGNNAME]" failed because error code 0xC020907F occurred, and the error row disposition on "Data Conversion.Outputs[Data Conversion Output].Columns[Copy of CAMPAIGNNAME]" specifies failure on error. An error occurred on the specified object of the specified component.  There may be error messages posted before this with more information about the failure.
Error: 0xC0047022 at Atish to CRM, SSIS.Pipeline: SSIS Error Code DTS_E_PROCESSINPUTFAILED.  The ProcessInput method on component "Data Conversion" (142) failed with error code 0xC0209029 while processing input "Data Conversion Input" (143). The identified component returned an error from the ProcessInput method. The error is specific to the component, but the error is fatal and will cause the Data Flow task to stop running.  There may be error messages posted before this with more information about the failure.

My mappings:

enter image description here

Lastly since the error seems to be complaining about 'CAMPAIGNID', the datatype of it on the destination table is uniqueidentifier. Honestly don't know what I'm missing here. Any help wold greatly be appreciated!

Error when using LIKE in report builder

I'm trying to use LIKE in report builder and I got this error:

An error occurred while reading data from the query result set.
Conversion failed when converting the varchar value '%' to data type int.
(Microsoft SQL Server, Error: 245)

this is my code:

select count(*) from projects where received LIKE '%'+@received+'%'
and institution# = @institution and program# = @program

how could i solve it?

SQL Wildcards to RegExp replace certain text in a column content

I have got a table where one of the column has text mixed with HTML data. This was due to a bug (fixed) in a script, but the SQL data needs to be edited to reflect the changes. The column has a type nvarchar(max, null). All I need to do is find tags such as <a img="lkss">,<div attr=val> and replace them with empty string "". I looked into this, but the solution says how to replace the entire contents based on one pattern. My problem is that I need to replace contents partly, but preserve clean text (i.e. not HTML tags/attributes). Any suggestion/help is appreciated.

Test column data:

<div attr=val; color=somecolor>inside text<div some=val><a some=val>Inside anchor

Expected result:

inside textInside anchor

SQL Server - Columns from row data; one row per Unique ID

I am creating a table collaborating a lot of mapped data, but the query result would be far better suited to produce one row per unique ID than it currently is.

For example, I currently have:

UNIQUE ID  | ID NAME |  SourceName | SourceDate | StoreName | StoreOrder
 1         | First   |  Example 1  | 1990       | Barnes    | 1
 1         | First   |  Example 1  | 1990       | Noble     | 2
 1         | First   |  Example 2  | 1996       | Barnes    | 1
 1         | First   |  Example 2  | 1996       | Noble     | 2
 2         | Second  |  Example 1  | 1990       | Barnes    | 1
.... And so on ...

Source info and Store info are not related, they are only related through UniqueID.

What would be ideal is:

UNIQUE ID  | ID NAME |  SourceName1 | SourceDate1 | SourceName2 | SourceDate2 | StoreName1 | StoreOrder1| StoreName2 | StoreOrder2
 1         | First   |  Example 1   | 1990        | Example 2   | 1996        | Barnes     | 1          | Noble      | 2          |

I know this is a bit of a messy solution, but it is required for further analysis. A single table, single row per unique ID would be perfect, no matter the column names etc.

It would also be great to have the column names dynamically allocated. For example if one ID has 4 stores allocated then there would be StoreName1 through to StoreName4 (Empty data entries would be 0 or NULL).

Does anyone have any suggestions on how to perform this?

Seeding SQL Server by Entity Framework code-first approach with many-to-many relationship

I'm using EF6 code first with ASP.NET Web API.

Suppose there are two model classes

public class RawMaterial {
    public int ID { get; set; }
    public string Name { get; set; }
}
public class Furniture {
    public int ID { get; set; }
    public string Name { get; set; }
    public virtual ICollection<RawMaterial> RawMaterials { get; set; }
}

DbContext

public class FurnitureContext : DbContext {
    public DbSet<RawMaterial> RawMaterials { get; set; }
    public DbSet<Furniture> Furnitures { get; set; }
}

And in the initializer class,

protected override void Seed (FurnitureContext context) {
    var glass = new RawMaterial { Name = "glass" };
    var wood = new RawMaterial { Name = "wood" };
    var paint = new RawMaterial { Name = "paint" };
    context.RawMaterials.AddRange(new RawMaterial[] { glass, wood, paint });

    var chair = new Furniture {
        Name = "chair",
        RawMaterials = new RawMaterial[] { wood, paint }
    };
    var coffeeTable = new Furniture {
        Name = "coffee table",
        RawMaterials = new RawMaterial[] { wood, glass }
    };
    context.Furnitures.AddRange(new Furnitures[] { chair, coffeeTable });

    context.SaveChanges();
}

I encountered a run time error complaining "an item cannot be removed from fixed size array". So clearly the program's trying to remove wood from chair before adding it to coffeeTable. So I changed the initializations to use Lists, as

var chair = new Furniture {
    Name = "chair",
    RawMaterials = new List<RawMaterial> { wood, paint }
};

After that, I could clearly see that wood was indeed removed from one of the furnitures' RawMaterials.

I also tried selecting wood from the context by

var chair = new Furniture {
    Name = "chair",
    RawMaterials = new RawMaterial[] {
        context.RawMaterials.Where(r => r.Name == wood.Name).FirstOrDefault()
    }
};

The result is still the same.

So my question is: how can I add the test data such that wood is present in both chair and coffeeTable? I am aware that this is not typically how many-to-many relations are defined, since RawMaterial does not know of Furniture. Or should I define the models the other way?

Thank you.


Edit: I check the database tables in SQL Server Object Explorer, and the SQL for RawMaterial is

CREATE TABLE [dbo].[RawMaterials] (
    [ID]           INT            IDENTITY (1, 1) NOT NULL,
    [Name]         NVARCHAR (MAX) NULL,
    [Furniture_ID] INT            NULL,
    CONSTRAINT [PK_dbo.RawMaterials] PRIMARY KEY CLUSTERED ([ID] ASC),
    CONSTRAINT [FK_dbo.RawMaterials_dbo.Furnitures_Furniture_ID] FOREIGN KEY ([Furniture_ID]) REFERENCES [dbo].[Furnitures] ([ID])
);


GO
CREATE NONCLUSTERED INDEX [IX_Furniture_ID]
    ON [dbo].[RawMaterials]([Furniture_ID] ASC);

And the SQL for Furniture is

CREATE TABLE [dbo].[Furnitures] (
    [ID]   INT            IDENTITY (1, 1) NOT NULL,
    [Name] NVARCHAR (MAX) NULL,
    CONSTRAINT [PK_dbo.Furnitures] PRIMARY KEY CLUSTERED ([ID] ASC)
);

So basically entity framework is not creating the database the way I need. That's why I cannot add wook to both chair and coffeeTable. How should I modify the Entity Models?

How to get group-wise correlation in SAS?

My data somewhat looks like this:

Product Attribute1 Attribute2 P1 1 -1 P1 1 -1 P1 1 -1 P1 1 -1 P1 1 -1 P2 1 1 P2 1 1 P2 1 1 P2 1 1 P2 1 1 . . .

Now I need to find out the correlation between attribute1 and attribute2 for each product individually. My actual data set contains around 100 products. Hence my output should be somewhat like this" Product Correlation P1 -1 P2 1 . . . How will I go about that in SAS/SQL?

SQL Job (Send Mail) - error formatting query probably invalid parameters

I know this has come up a lot in the past but none of the fixes I've Googled or found on here has worked for me in this instance.

I'm running a fairly standard SQL Server Agent Job as a Transact-SQL script with the follow details: (replaced some stuff as *** for my boss's sanity)

-- Start T-SQL

USE msdb
EXEC sp_send_dbmail
  @profile_name = 'MainProfile',
  @recipients = 'test@test.co.uk',
  @subject = 'T-SQL Query Result',
  @execute_query_database = 'test30',
  @query = 'SELECT ReferralReceivedDate,testRef,testcoMetadata.testcoRef,testcoMetadata.TimeSpentWithtester    
FROM TestCasesTable, TestcoMetadata 
WHERE testcasestable.CaseID = TestcoMetadata.CaseID AND AgencyName = [Test Injury] AND TestcoMetadata.TestcoRef IS NOT NULL AND TestcoRef <> '' 
order by ReferralReceivedDate desc',
@attach_query_result_as_file=1,
@query_attachment_filename = 'Results.csv',
@query_result_separator = ','

-- End T-SQL --

The query itself runs fine as a normal query with no issues. The owner of this job has been used on other jobs again with no problems. In the step properties the Database selected is the same one as that mentioned in the @execute line.

I have a feeling this is either falling over the way it's trying to create the csv or something to do with permissions with dbmail part. I'm only a part time DBA so this has now lost me and I need help.

SQL SERVER BEST CLINT EDITION

I have sql server developer edition in my computer and im doing many databases to same customer, so which edition of sql server should i install in customer server pc to give him th ability to work in all databases at same time frm differnt applecations.

How to get list of values from stored procedure using Linq?

I would like to get list of values from stored procedure. How to do it ?

Example : My stored Procedure

create PROCEDURE Get_ListOf_Holiday
AS
BEGIN
    select * from holiday
END

In my Linq :

using (PlanGenEntities3 entity2 = new PlanGenEntities3())
{
   var testList = entity2.Get_ListOf_Holiday();
}

But i am always getting values like -1. But in my Sql server I am getting the output like list of holiday details.

How to solve this. Please any one help me to fix ?

OPENXML in Sql server

I have a XML structure "1234"

I want get the "Version" values using "OPENXML".

I know it can be done with the below query.

DECLARE @AttachVersions XML
SET @AttachVersions = '<AttachVersion><Version>1</Version><Version>2</Version><Version>3</Version><Version>4</Version></AttachVersion>'
SELECT ParamValues.[Version].value('.', 'VARCHAR(10)') AS [Version] FROM @AttachVersions.nodes('/AttachVersion/Version') as ParamValues([Version])

We can not change the input parameter to XML.

I know there is an alternate way to get the with "OPENXML" if it's an attribute value. Here's the sample code

DECLARE @FileterOptions VARCHAR(MAX)

SET @FileterOptions = '<AttachVersion><Version Value="1" /><Version Value="2" /><Version Value="3" /><Version Value="4" /></AttachVersion>'

DECLARE @AttachVersionHandle INT

CREATE TABLE #tmpAttachVersionList
(
    [Value] INT
)

EXEC sp_xml_preparedocument @AttachVersionHandle OUTPUT, @FileterOptions

INSERT #tmpAttachVersionList ( [Value] )
    SELECT [Value] FROM OPENXML( @AttachVersionHandle, '//Version' ) WITH #tmpAttachVersionList

SELECT * FROM #tmpAttachVersionList

DROP TABLE #tmpAttachVersionList


Is it possible to get the "Version" values with OPENXML using "XPath"?

All actions denied on MS SQL Server on Go Daddy Hosting

i have a website hosted on GoDaddy and I need to create a database for it. So headed to the Databases section and created a MS SQL Database then on my local pc I tried to access the database via SQL Server Management studio, I was able to login to the database but I cannot make any operations. I get it does not exist or you do not have permission. So deciced to go the Security tab, then Login and tried to change my username that I'm using to systemadmin role but I also got Cannot alter the server role 'sysadmin', because it does not exist or you do not have permission. What could be the problem? There are no other accounts on it. The default sa account is disbaled and I can't enable it coz it will prompt no permissions etc.

I don't understand it. Why GoDaddy allows me to create a database but with no permissions or rather I cannot alter it. Anyone facing the same issue? Thanks

Importing txt file to sql server without mentioning data types of each column

while importing any txt file to sql server, i create an empty table first by mentioning data structure (variable names and their data type) and then copying data into this empty table from text file. Following is the query which i use.

CREATE TABLE test ( account_id varchar(20), target integer, ttl_spend_bp_8m numeric(38,4), trns_bp_fuel_8m bigint );

COPY test FROM 's3://acncrmbpmanalytics/PT/sc_feb_jfr_final_population.txt' WITH CREDENTIALS AS 'xxxxxxxxxx' IGNOREHEADER 1 maxerror 1000 delimiter '\t' DATEFORMAT 'YYYY-MM-DD' TIMEFORMAT 'YYYY-MM-DD HH:Mi:SS' COMPUPDATE ON;

But this time i have a txt file having 255 variables and i do not know data types of these variables. How should i import this table to sql server?

C# Execute Store Procedure in SqlServer without parameters

Hi right no I have this method to execute the store procedure:

public static DataTable ExecuteProcedureNoParams(string connectionStringName, string procedureName)
    {
        using (DbCommand sprocCmd = SqlDB(connectionStringName).GetStoredProcCommand(procedureName))
        {
            DataTable dt = new DataTable();
            using (IDataReader sprocReader = SqlDB(connectionStringName).ExecuteReader(sprocCmd))
            {
                dt.Load(sprocReader);
                // DisplayRowValues(sprocReader);
            }

            return dt;

        }
    }

private static SqlDatabase sqlDB;

    public static SqlDatabase SqlDB(string connectionString)
    {
        if (sqlDB == null)
        {
            sqlDB = CreateConnection(connectionString);
        }
        return sqlDB;
    }

    private static SqlDatabase CreateConnection(string connectionString)
    {
        DatabaseProviderFactory factory = new DatabaseProviderFactory();

        if (string.IsNullOrWhiteSpace(connectionString))
        {
            // Create the default Database object from the factory.
            // The actual concrete type is determined by the configuration settings.
            return factory.CreateDefault() as SqlDatabase;
        }
        else
        {
            // Create a Database object from the factory using the connection string name.
            return factory.Create(connectionString) as SqlDatabase;
        }

    }

Now, the error that i'm getting is that it cannot find my store procedure. I tested the connection String in the web config and it also working properly.

it fails in the IDataReader call.

could please anyone help me with this issue?

Changing the value of row in sql server

I have a database column:

Model
------
EH2

I want to make it like:

Model
---------
Primo EH2

I have tried:

update Table
set Model = REPLACE(Model,' ','Primo EF2')

but it did not work.

How to Use Between Clause in Sql query without using and clause

I have created a query which gets results between 2 dates, Its working fine.. Now i have a scenario in which users does not enter any date..In this case I need to fetch all the result from database regardless of date.. The following query fails when user does not enter any date, it returns empty result set.
Kindly guide me how to resolve this problem.

select * from emp_register
where date between '10-10-2015' and '15-10-2015' 
or status= 'Y'

How to order by column by sequence of another column

i have this query which give me this table:

SELECT 
CS.Name, 
CS.FirstStep,
--CSS.NextCAPAStepID,
CS.ID
FROM CAPA_STEP_SEQUENCE CSS
LEFT JOIN CAPA_STEP CS ON CS.ID = CSS.CAPAStepID
WHERE CAPAStepID in (100000009,100000010,100000011,100000012,100000013)
GROUP BY CS.Name, CS.ID, CS.FirstStep
ORDER BY CS.FirstStep DESC

http://ift.tt/1Kpih2N

I heave to sort this table by this column from another table:

SELECT NextCAPAStepID
FROM CAPA_STEP_SEQUENCE 
WHERE CAPAStepID in (100000009,100000010,100000011,100000012,100000013)

http://ift.tt/1GHaZQH

When i try to order by first query by CSS.NexstCAPAStepID it makes that in the first order column NextCAPAStepID is sorted ASC and then whole table is sorted with this sequence but in my case i want to sort whole table by sequence from CSS.NextCAPAStepID. Notice also that row with value 1 in column FirstStep should be always in the top.