w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML Categories
Couchbase : how to define or register a view in Couchbase server using libcouchbase C API
man lcb_make_http_request to get more info about doing restful queries to couchbase Also you can find doc sources in the repo https://github.com/couchbase/libcouchbase/blob/master/man/man3couchbase/lcb_make_http_request.3couchbase.txt#L147-163 const char *docid = "_design/test"; const char *doc = "{"views":{"all":{"map":"function (doc, meta) { emit(meta.id, null); }"}}}"; lcb_http_cmd_t cmd; lcb_http_request_t req; cmd.version = 0; cmd.v.v0.path = docid; cmd.v.v0.npath = strlen(docid); cmd.v.v0.body = doc; cmd.v.v0.nbody = strlen(doc); cmd.v.v0.method = LCB_HTTP_METHOD_PUT; cmd.v.v0.content_type = "application/json"; lcb_error_t err = lcb_make_http_request(instance, NULL, LCB_HTTP_TYPE_VIEW, &cmd, &r

Categories : C

rails rack-protection usage, error "you need to set up a session middleware *before* Rack::Protection::SessionHijacking"
Step 1 is to exclude SessionHijacking middleware from the Rack::Protection pack: # config.ru require 'rack/protection' use Rack::Protection, :except => :session_hijacking ... run YourApp This will solve the problem - but I will assume you really want this Anti-hijacking feature: Step 2. Add the middleware inside Rails application.rb module YouApp class Application < Rails::Application config.middleware.use Rack::Protection::SessionHijacking ... In this way you will make it load after rails own session middleware - ActionDispatch::Session::CookieStore. You can check the result by running rake middleware

Categories : Ruby On Rails

How to test a Rack::Directory serving static files with Capybara? or How to test Rack Middleware with Capybara?
I was able to figure out how to solve this problem by changing this line in env.rb from: Capybara.app = MainSinatra to: Capybara.app = eval "Rack::Builder.new {( " + File.read(File.dirname(__FILE__) + '/../../config.ru') + " )}" And this runs the application from the rack up file (config.ru) and loads all the middleware that wasn't otherwise loading. I found the answer in this blog.

Categories : Ruby On Rails

Location Awareness: Notification when near Coordinates
See Monitoring Shape Based Region in the Location Awareness Programming Guide. - (BOOL)registerRegionWithCircularOverlay:(MKCircle*)overlay andIdentifier:(NSString*)identifier { // Do not create regions if support is unavailable or disabled if ( ![CLLocationManager regionMonitoringAvailable]) return NO; // Check the authorization status if (([CLLocationManager authorizationStatus] != kCLAuthorizationStatusAuthorized) && ([CLLocationManager authorizationStatus] != kCLAuthorizationStatusNotDetermined)) return NO; // Clear out any old regions to prevent buildup. if ([self.locManager.monitoredRegions count] > 0) { for (id obj in self.locManager.monitoredRegions) [self.locManager stopMonitoringForRegion:obj]; } // If the ov

Categories : IOS

Cannot add Module to Java EE Enterprise Application - nullPointer when creating Enterprise Application Project
Root cause is that the WTP project configuration fails due to the wrong java web facet being installed. You could try to determine if the EAR project has deployment descriptor, if so, then force save. final ReferencedComponent ref = AddComponentToEnterpriseApplicationOp.findReferencedComponent(earwc, wc, se, compse);

Categories : Eclipse

Django Timezone aware DateTimeField default value timezone awareness error
Try calling replace on the datetime instead of passing the tzinfo into the __init__ of the datetime. Taken from the django docs: import datetime from django.utils.timezone import utc now = datetime.datetime(9999, 1, 1).replace(tzinfo=utc)

Categories : Django

How do I make my rack app a gem?
Gemspec+correct directory structure+(most importantly) placing a script that will launch your app(with run, probably) into bin/ directory. A little more details on gem binaries here UPDATE An example as requested. I have made a gem called agent which depends on sinatra(it also depends on rack). It has this definition of Agent::Server: module Agent # Your code goes here... class Server < ::Sinatra::Base get '/sync' do [200, "yahoo!"] end end I also created file called test with following contents: #!/usr/bin/env ruby require "rubygems" require "agent" Rack::Handler::WEBrick.run( Agent::Server.new, :Port => 9000 ) Then, if I run chmod 0755 test and ./test after that, I can go to http://localhost:900/sync and see yahoo!.

Categories : Ruby

What is the "env" variable in Rack middleware?
I suggest that you can try to print the 'env' variable with writing a simple programming. require "rubygems" require "rack" def pp(hash) hash.map {|key,value| "#{key} => #{value}"}.sort.join("<br/>") end Rack::Handler::WEBrick.run lambda {|env| [200,{},[pp(env)]]} , :Port=>3000 enter the link localhost:3000

Categories : Ruby On Rails

Using rack-timeout gem on Rails
You need to tell Rails what to do when a Rack::Timeout error is thrown. If you ignore it, execution will stop after 15 seconds (or whatever you configure it to be) If you want to show the user a nice error, you'll need to rescue from that exception (like below). You could do something like this class ApplicationController < ActionController::Base rescue_from Timeout::Error, with: :handle_timeout protected def handle_timeout render "shared/timeout" end end

Categories : Ruby On Rails

Selective Loading using Rack
@padde makes a good point, you need to give us more information. However, one easy way to selectively run things is to use environment variables. The obvious classic use is to run some things in production and some things in development etc, e.g. if ENV["RACK_ENV"] == "production" # do this elsif ENV["RACK_ENV"] == "staging" # do something almost the same else # do something quite different end Rack will generally set those vars for you, but you could use a different one and if you wanted to run it from the commandline you could use env MYVAR=1 bin/rackup config.ru. Consider @padde's request and tell us your goal, not the implementation you believe is best (considering you don't really know what's best or else you wouldn't be asking;) and perhaps you'll get a better answer

Categories : Ruby

Gathering Logs within Rack::Test
You need to stub and set expectations on whatever method your custom logger is calling to write its output. So, for example, if your custom logger writes directly to STDERR with a single argument, you would use: STDERR.stub(:write) {|arg| expect(arg).to_not match(/password/)} If your custom logger writes to the default logger (i.e. env['rack.errors']) instead of STDERR, then you would stub the write method of that object instead. I would have shown that example, but I can't figure out how to get a hold of the Rack environment within an RSpec test. A couple of notes on this implementation: The use of any_number_of_times, as in STDERR.should_receive(:write).any_number_of_times is deprecated in favor of stub There is no reasonable regex to match strings which do not contain a particula

Categories : Ruby

Using CORS and Warden in rack app (Grape API)
Had exactly the same (rather annoying) thingie, ended up with doing this on my one: on a before do block, header 'Access-Control-Allow-Origin', '*' header 'Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT' (You may want to tweak according to RACK_ENV or such...) Seems to work. Note this is not a full CORS implementation(of course its not) but i'll wait for that rack-cors gem fix... HTH

Categories : Ruby

Which rack environment do cucumber features run in?
It uses RAILS_ENV instead of RACK_ENV. In my env.rb file I just had it output the ENV variable. Do this to double check, but in mine I clearly see: "RAILS_ENV"=>"test"

Categories : Ruby On Rails

rack-pjax not working, no errors
I have similar experience though using pjax-rails, but the reason should be the same on JS side. A very possible reason is it takes a bit long for your development server to response. Pjax can't wait so long by default, so it falls back to normal HTTP request. The solution is to add time out option on JS $('.local-nav a').pjax('[data-pjax-container]', {timeout: 2000})

Categories : Ruby On Rails

How to map unspecified path using Rack::Builder.map?
You can just have a default app that produces the error message if the request doesn’t match any of the other mappings: map '/one' do run app1 end map '/two' do run app2 end run default_app Alternatively you could have a mapping for /, since “URLMap dispatches in such a way that the longest paths are tried first, since they are most specific”. (This is actually pretty much equivalent to having a default app like above). map '/one' do run app1 end map '/two' do run app2 end map '/' do default_app end

Categories : Ruby

Before Filter on a rack ( sinatra ) based app in RoR applications
This is an old question but I ran into a similar problem with Sidekiq Web. To get around this we can use route constraints. In your routes file constrain the route to the mounted application: require "sidekiq/web" mount Sidekiq::Web, at: "/sidekiq", constraints: AdminConstraint.new Then in the AdminConstraint, you need to place the calls that are in your before_filter that are applicable for your application's authentication. So for example if I had the following in my ApplicationController: class ApplicationController < ActionController::Base before_filter :authenticate def authenticate user = User.find_by(email: params[:email]) if user && user.authenticate(params[:password]) session[:user_id] = user.id end end end I would put the following in

Categories : Ruby On Rails

ruby rack - can't modify ARGV in middleware?
Try the following: class Pre def initialize(app) @app = app end def call(env) # To be safe, reset the ARGV and rebuild, add any other items if needed ARGV.clear ARGV << "--debug" ARGV << "--host" << "localhost" if some_env_related_logic ARGV << "--test" end Somecommand.new.call(env) end end require 'Somecommand' # Note the change, Somecommand is no longer mentioned here run Pre

Categories : Ruby

How to init rack server listening to a socket
Apparently this is not possible. Rack-compatible servers usually support this feature, but Rack::Server "interface" does not make use of it (at least the latest version as of October 2013). Why not, is beyond me.

Categories : Ruby On Rails

How serve static files with rack-coffee
The rack-coffee README describes one way to do it: If you want to serve stock javascript files from the same directory as your coffeescript files, stick a Rack::File in your middleware stack after Rack::Coffee. Although Rack::File does not appear to be a middleware but a standalone Rack app class, so I would instead use Rack::Static before your code above: use Rack::Static, :root => File.join(Dir.pwd, 'assets'), :urls => ["/javascripts"] use Rack::Coffee, :root => File.join(Dir.pwd, 'assets'), :urls => '/javascripts'

Categories : Javascript

rack-pjax working in development but not production
Before you call pjax, try adding this to your JavaScript: $(document).on('pjax:timeout', function() { return false; }); This will disable the timeout. I had this exact same problem and the issue was that my app was too slow, and was taking too long to load, and pjax would cancel the request and send the browser on. You can of course increase the timeout but I thought this was nicer.

Categories : Ruby On Rails

How to test the request (not response) of a Rack middleware?
I presume you're meaning testing whether it's changing env... A middleware goes something like: class Foo def initialize(app) @app = app end def call(env) # do stuff with env ... status, headers, response = @app.call(env) # do stuff with status, headers and response [status, headers, response] end end You could initialize it with a bogus app (or a lambda, for that matter) that returns a dummy response after doing some tests: class FooTester attr_accessor :env def call(env) # check that env == @env and whatever else you need here [200, {}, ''] end end

Categories : Ruby

Can the Rails logger be accessed from within a Rack middleware?
I've been able to get this to work by writing my own middleware which just adds the Rails.logger to the Rack environment. module Something class UseRailsLogger def initialize(app) @app = app end def call(env) env['rack.logger'] ||= Rails.logger @app.call(env) end end end If you stash that in lib/something/use_rails_logger.rb, then you can add it to your middleware stack and the logger will be available to every layer that comes after it. Note: I wanted to add it to config/application.rb since there's no reason for this setting to be environment-dependent, but for some reason require 'something/use_rails_logger' wouldn't work from that file. Adding it to config/environment/*.rb worked just fine. Beside the require all you need is: config.middleware

Categories : Ruby On Rails

Sinatra/1.4.3 use Rack::Session::Cookie warning
You are using both enable :sessions which makes Sinatra setup cookie based sessions, and use Rack::Session::Cookie, ... which also adds sessions to your app, so you end up with two instances of Rack::Session::Cookie in your middleware stack. The warning is being generated by the session middleware included by Sinatra. By default Sinatra doesn’t create a session secret when running in the development environment (in classic mode at least, it does for modular apps), and so Rack generates the warning in development. You should only need one of the two ways of enabling sessions, using two together could result in them interacting in unexpected ways. To avoid the warning, you can explicitly set a secret for the Sinatra session with the session_secret option: enable :sessions set :se

Categories : Ruby

ActiveRecord leaks connections when using in Rack middleware
ActiveRecord provides a method for clearing connections manually - ActiveRecord::Base.clear_active_connections!. Update the call method in the middleware to clear the active connections after the changes are made in the database. def call(env) # ... prepare in memory storage for what needs to change return_value = @app.call(env) # ... commit changes to the database ActiveRecord::Base.clear_active_connections! # fixes the connection leak return_value end http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/ConnectionPool.html

Categories : Ruby On Rails

When is this Rack::Protection::FormToken a security issue?
According to https://github.com/rkh/rack-protection/issues/38 "FormToken lets through xhr requests without token." So if you were relying on form tokens and had not taken extra steps to protect against xhr requests, then this might be considered a security risk. You might assume a request was genuine (since it's protected by FormToken - right!?) when in fact it was a forgery. By forcing you install FormToken explicitly, the developers are hoping that you will examine what it does and take the necessary steps.

Categories : Misc

Couchbase 2.0 and php5.4
I've used PHP 5.4.x, specifically I used the Bitnami MAPP stack, which comes with the couchbase.so already built for 5.4 (although you can do that yourself easily from the source). Then connected it to my local Couchbase instance (in my case I used the Laravel framework). My Blog: http://blog.couchbase.com/easy-php-couchbase-setup-mac-bitnami But now the couchbase.so is already in the Bitnami stack... so you can skip that part. Bitnami MAPP: http://bitnami.com/stack/mapp Bitnami MAMP: http://bitnami.com/stack/mamp (also can be installed via Mac App Store)

Categories : PHP

What is a couchbase pool
A long time ago the Couchbase engineers intended to build out a concept of having pools similar to zfs pools, but for a distributed database. The feature isn't dead, but just never got much attention compared to other database features that needed to be added. What ended up happening was that the pools/default just ended up being a placeholder for something that the engineers wanted to build in the future. In the old days the idea was that a pool would be a subset of buckets that was assigned to a subset of nodes in the cluster and that this would help with management of large clusters (100+ nodes). So right now I would say don't worry about the whole pools concept because in the current (2.x releases) this is a placeholder that doesn't have any special meaning. In the future though there

Categories : Misc

How to handle exception generated from Rack before reaching your rails app
if the Ruby runtime is booted - which in this case seems it is ... you should be able to configure a (minimal) rack error application just set smt rack-y (require 'my_error_app'; run MyErrorApp) into the jruby.rack.error.app context parameter (e.g. in your web.xml with Warbler)

Categories : Ruby On Rails

Ruby Rack Heroku: Serving Static Files
For your config.ru file, try: use Rack::Static, :urls => ["/images", "/js", "/css"], :root => "public" run Rack::File.new("public") You could also replace the last line with run Rack::Directory.new("public") which would serve up all your files, but would give a file browser like interface if someone went to the url of a directory (like the root directory)

Categories : Ruby

Rack middleware to to prepend while(1); to all ajax/json requests
There's quite a lot of questions molded into one, I think. The middleware itself would look something(haven't checked it, but it feels right) like this: class AntiHijackingMiddleware def call(env) status, headers, body = @app.call(env) # save initial state if env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest" && headers['Content-type'].to_s.include?("application/json") body = "while(1);"+body headers['Content-Length'] = Rack::Utils.bytesize(body.to_s).to_s end [status, headers, body] end end You can add additional conditions on env["REQUEST_URI"] to do url matching. Adding it to Rails' middleware stack is boilerplate.

Categories : Javascript

Running Capybara without rack produces errors when using url parameters
Assuming you have a non-Rack application and are following the instructions in the second answer which references https://groups.google.com/forum/#!msg/ruby-capybara/9UFnfrc1S-s/TfQO5uBv7gMJ, it seems to me that the hack/workaround is only valid for the simplest of use cases, namely when you're not attempting to pass in parameters to the app. I assume that either Rack or Capybara is attempting to invoke your app to pass the parameters and it's failing because you app is just a String and not a callable object.

Categories : Ruby

Are there any basic examples of Rack::Session::Cookie usage?
You have already setup cookie in your question. I am not sure if you means something else by "setup". Instead of env['rack.session'] you can use session[KEY] for simplification. session[:key] = "vaue" # will set the value session[:key] # will return the value Simple Sinatra example require 'sinatra' set :sessions, true get '/' do session[:key_set] = "set" "Hello" end get "/sess" do session[:key_set] end Update I believe it wasn't working for you because you had set invalid domain. So I had to strip that off :domain => 'foo.com',. BTW Sinatra wraps Rack cookie and exposes session helper. So above code worked fine for me. I believe following code should work as expected. require 'sinatra' use Rack::Session::Cookie, :key => 'rack.session', :expire_after => 2592

Categories : Ruby

Force rack-offline (or Rails) to update caching manifest
Probably not, because AppCache is meant for static resources. Best to use a static HTML page, and use JavaScript to load in dynamic content. Check out appcachefacts.info for more information.

Categories : Ruby On Rails

Nested form parent object : got Rack::Utils::KeySpaceConstrainedParams
I encountered the same error then I renamed the name of the checkbox array to something else other than the name of the model. It worked. For example you have @dashboard_banners as your model then you call your checkbox dashboard_banners[]. I think that causes the error. Name it to something else like d_banner[] then fetch ii in the controller as params[:d_banner]. Then you can loop it in the controller or do anything that you like.

Categories : Ruby On Rails

Cookie is changed on every request, using sinatra and Rack::Session::EncryptedCookie
The source for encrypted_cookie shows that it generates different encrypted output every time it is called regardless of the input. There are 2 reasons for this: The library would have to know what the session value was during the last request. It doesn't, all it does is accept a single input, the given session. If you wished to circumvent this and just rewrite the cookie (I suppose) you could, since you have the extra information available higher up in the Sinatra app. It's more secure. It doesn't leak information (if the cookie doesn't change then an observer of the cookie knows nothing changed during the request), and it gives an attacker less time to try and get to a meaningful value.

Categories : Ruby

Testing an AJAX POST using Rack::Test - how to pass in data?
Your post endpoint must parse the posted JSON body itself, which I assume you already do. Can you post how your end point works, also the rack-test, rack,ruby and sinatra version numbers? Please mention also how you test whether the server's receiving anything -- namely test mockup may confuse your detection. post '/user' do json_data = JSON.parse(request.body.read.to_s) # or # json_data = JSON.parse(request.env["rack.input"].read) ... end

Categories : Ajax

"No such middleware to insert before: Rack::Lock (RuntimeError)" after upgrading to Rails 4
As the error suggests ("No such middleware to insert before"), the issue is with the middleware you are trying to insert before (and not the middleware you are trying to insert, which was my initial assumption). In Rails4, threading is enabled by default which removes Rack::Lock. To find a replacement, you can run rake middleware from your rails project directory, and look for something near the start of the stack. I'm going to pick Rack::Runtime as it is early in the stack, and seems pretty standard. So the rewrite config is now: config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do r301 %r{^/(.*)/$}, '/$1', :headers => {'Cache-Control' => 'public, max-age='+2.week.to_s} end

Categories : Ruby On Rails

Send two identical headers with Rack (Access-Control-Allow-Origin)
It's very common to use a hash of arrays so try: headers = { "Access-Control-Allow-Origin" => %w[ http://my.domain1.com http://my.domain2.com ] } I've got a guess that it should be { "Access-Control-Allow-Origin" => [ 'a', 'b' ] * " " } Looking at the RFC, the pertinent part is "5.1 Access-Control-Allow-Origin Response Header" which points to: The Origin header field has the following syntax: origin = "Origin:" OWS origin-list-or-null OWS origin-list-or-null = %x6E %x75 %x6C %x6C / origin-list origin-list = serialized-origin *( SP serialized-origin ) serialized-origin = scheme "://" host [ ":" port ] ; <scheme>, <host>, <port> from RFC 3986 So, try: [ 'a', 'b' ] * ";" Or, for the uninitiated: %

Categories : Ruby

Couchbase- How to query view using the C API - libcouchbase
The library itself comes with manpages, which are the most actual documentation. The index page is man 3 libcouchbase. The page you need is man 3 lcb_make_http_request. Also you can found docs in asciidoc format in the repo itself https://github.com/couchbase/libcouchbase/blob/master/man/man3couchbase/lcb_make_http_request.3couchbase.txt Between 1.x and 2.x releases, we've changed API a lot, so that it isn't backward compatible mostly. And function libcouchbase_make_couch_request was only accessible in "developer preview" version (like beta), eventually it was named lcb_make_http_request, because you can use the same call to create design documents, and also perform admin tasks, like create/flush/delete bucket, etc. Here is the code example from man page above: lcb_http_request_t req; l

Categories : C

Should I use MongoDB or Couchbase 2.x for simple between query?
I have recently done a short review of the respective merits of MongoDb and CouchBase. The most important thing is that there are more similarities than differences, and both are good products that would work well in most cases. I will sum up the differences by saying that MongoDB is generally easier to install, use, and query (plus it has a larger community as you say), whereas CouchBase goes the extra mile for performance(memcache and insert throughput), auto-scaling, and recovery from failure. Personally given a situation like yours of a (presumably) new app with a query requirement and virtually no write, I would go with MongoDB. It would be faster to get it to work and there would be solutions to optimize reads down the road if you'd need to.

Categories : Mongodb



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.