Posts

Showing posts from March, 2011

Instance variable from Rails model: undefined method `any?' -

trying display affiliate products while keeping controllers skinny possible. know why isn't working? undefined method `any?' nil:nilclass app/models/shopsense.rb require "rest_client" module shopsense def self.fetch response = restclient::request.execute( :method => :get, :url => "http://api.shopstyle.com/api/v2/products?pid=uid7849-6112293-28&fts=women&offset=0&limit=10" ) # !!! attention !!! # # works if put below in `shopsense` in controller instead # @products = json.parse(response)["products"].map |product| product = openstruct.new(product) product end end end app/controllers/main_controller.rb class maincontroller < applicationcontroller before_action :shopsense def index end def shopsense shopsense.fetch end end app/views/main/index.html.erb <% if @products.any? %> <% @products.each |product| %> <div clas

.net 2.0 - How to write a common code to display many picturebox in vb.net 2.0 ? -

imports system.threading.thread public class form1 dim delay integer = 200 dim integer = 1 private sub button1_click(sender object, e eventargs) handles button1.click while <= 5 picturebox1.visible = true picturebox1.refresh() sleep(delay) picturebox1.visible = false picturebox2.visible = true picturebox2.refresh() sleep(delay) picturebox2.visible = false picturebox3.visible = true picturebox3.refresh() sleep(delay) picturebox3.visible = false picturebox4.visible = true picturebox4.refresh() sleep(delay) picturebox4.visible = false picturebox5.visible = true picturebox5.refresh() sleep(delay) picturebox5.visible = false = + 1 if = 6 = 1 end if end while end sub i wrote above code. it's working. following code not not working. want minimize code. want use 20 pic

oracle - Unable to Grant session to a user -

i used yesterday sqlplus on ubuntu 14.04lts today when open connect system : sql> connect system enter password : connected. then want connect account created yesterday : sql> connect slim/slimhmidi; connected. when want create session had error: sql> grant session slim; grant session slim * error @ line 1: ora-01919: role ' session ' not exist i tried create session no vain: sql> grant create session slim; grant create session slim * error @ line 1: ora-01031: insufficient privileges also have error : sql> grant connect slim; grant connect slim * error @ line 1: ora-01932: admin option not granted role ' connect' didn't have these problems yesterday. ora-01919: role ' session ' not exist you trying grant privilege user slim while connected slim . so, grantor , grantee same here. ora-01932: admin option not granted role ' connect as said, connected user slim , means user has

php - Get return value of a command -

i've found many ways run command, exec , system , shell_exec , seem return command output. i want return value (integer). how can that? <?php $retval = something("script.sh"); you can use exec() exec("command", $output, $retval); echo "output: $output\n"; echo "return value: $retval\n"; exec() consumes $output , $retval reference , values set inside of exec() . check manual of exec() again. btw, $output , $retval implicitly initialized, don't need exist before exec() call.

c# - Getting a new unique number for a column in table -

i'm creating online payment system. bank requires unique invoice number. suppose table: public class onlinepaymentinfo { public onlinepaymentinfo() { orders = new list<order>(); } [key] public int id { get; set; } [required] public virtual order firstorder { get; set; } public ilist<order> orders { get; set; } public int invoicenumber { get; set; } public string transactionreferenceid { get; set; } } now order might change. once can't send payment info same invoice id bank online payment. want new unique invoice id. can query database getting maximum number, this: var newid = db.onlinepayments.max(op => op.invoicenumber) + 1; but i'm wondering if best way this.

css - Styling Om components -

the way style , om component based on how react handles styling. horrible mess duplicate common css rules on application there way define styles in function or similar? (defn my-css [] {:border "1px solid #000"}) (defn my-component [state] (dom/div #js {:classname "the-class-name" :style #js (my-css)})) i've tried using defn , def can't find way avoid caused by: clojure.lang.exceptioninfo: javascript literal must use map or vector notation i use: (defn create-style [row] {:background-color (utils/get-background-color (:task_status row)) :color (utils/get-color (:task_status row))}) but using "om-bootstrap". i have #js before :style map , after. think depends on library expecting.

sqlite - Updating a local database app for Windows Phone 8.1 (Universal) -

i using local database (sqlite) in windows phone (universal) app. need push update app. my question 'i have little schema change (added 1 field db). change handled wrapper using ( https://github.com/praeclarum/sqlite-net ). or need write code updating schema without losing data. i found link . applicable windows phone universal apps using above sqlite wrapper. this depends on kind of update you're doing. if take @ the code library you're using you'll notice createtable method migration calling migratetable . migratetable method checks if there new columns need added , adds them table. foreach (var p in map.columns) { var found = false; foreach (var c in existingcols) { found = (string.compare (p.name, c.name, stringcomparison.ordinalignorecase) == 0); //and on so if want add new columns without worrying keys , constraints, should covered library. can, after all, test creating initial db , tables, , simulate update. now, more

ruby - How to duplicate object "by value" in Rails? -

i need duplicate product in spree application. so def my_duplicate_product(product) product.dup.tap |new_product| new_product.slug = "#{product.slug}-#{rand(1000)}" ... this code causes original product#slug changed. what supposed copy of particular product , leave original unchanged? rails version: 4.0.3 update: the problem not in ruby, nor rails — it's globalize gem (v. 4.0.0). this error fixed in 4.0.3. it realy broke #dup values "shared" between original model , duplicated one. see github issue tracker more information: https://github.com/globalize/globalize/pull/352 maybe clone works: def my_duplicate_product(product) product.clone.tap |new_product| new_product.slug = "#{product.slug}-#{rand(1000)}" clone method on ruby doc

parse.com - Weighing Parse Objects - the 128kb Limit -

i want gauge how large parse objects ahead of time. have app lots of addunique , i'd have idea of how capacity addunique single parse object. i'd make sure don't bump or exceed limit. this might of help . answer stack overflow question , appears address question. there lot of comments , info may in post well. function roughsizeofobject( object ) { var objectlist = []; var stack = [ object ]; var bytes = 0; while ( stack.length ) { var value = stack.pop(); if ( typeof value === 'boolean' ) { bytes += 4; } else if ( typeof value === 'string' ) { bytes += value.length * 2; } else if ( typeof value === 'number' ) { bytes += 8; } else if ( typeof value === 'object' && objectlist.indexof( value ) === -1 ) { objectlist.push( value );

xml - Could not initialize LoginButton Facebook-sdk for android -

im working on android project want put facebook login feature, added facebook sdk correctly not initialize loginbutton **java.lang.noclassdeffounderror: not initialize class com.facebook.login.widget.loginbutton** @ sun.reflect.nativeconstructoraccessorimpl.newinstance0(native method) @ sun.reflect.nativeconstructoraccessorimpl.newinstance(nativeconstructoraccessorimpl.java:57) @ sun.reflect.delegatingconstructoraccessorimpl.newinstance(delegatingconstructoraccessorimpl.java:45) @ java.lang.reflect.constructor.newinstance(constructor.java:526) @ org.jetbrains.android.uipreview.viewloader.createnewinstance(viewloader.java:413) @ org.jetbrains.android.uipreview.viewloader.loadview(viewloader.java:105) @ com.android.tools.idea.rendering.layoutlibcallback.loadview(layoutlibcallback.java:176) @ android.view.bridgeinflater.loadcustomview(bridgeinflater.java:207) @ android.view.bridgeinflater.createviewfromtag(bridgeinflater.java:132) @ android.view.layoutinflater.rinflate_origina

directx - directx11 - can't set Texture2D as ShaderResourceView? -

i have written little directx renderengine, render , texture simple polygons. texturing worked createddstexturefromfile(.dds) well. now, try set texture , corresponding shaderresourceview memory buffer. creating texture2d works, then, createshaderresourceview fails . tried call 2nd param set null, fails. trying figure out what's wrong here whole week. i hope can me here. [code] : d3d11_texture2d_desc tdesc; zeromemory(&tdesc, sizeof(tdesc)); d3d11_subresource_data srinitdata; zeromemory(&srinitdata, sizeof(srinitdata)); id3d11texture2d* tex = 0; d3d11_shader_resource_view_desc srdesc; zeromemory(&srdesc, sizeof(srdesc)); // ------------------------- [check mate ] ---------------------------- int w = 512; int h = 512; int bpp = 4; int *buf = new int[w*h]; // filling image (int = 0; i<h; i++) (int j = 0; j<w; j++) { if ((i & 32) == (j & 32)) buf[i*w + j] = 0x00000000; else buf[i*w + j] = 0xfff

javascript - Memory leaks in node.js with concurrent sse connections -

i'm developing high-load testing tool, using eventsource npm library generate concurrent sse connections. i use centos on digitalocean 512mb , 1cpu. take @ code: var http = require("http"), eventsource = require('eventsource'), opensockets = 0; http.globalagent.maxsockets = 70000; console.log(process.memoryusage() ) begintest(); function begintest (options) { (var = 0; < 50000; i++) { settimeout(formposter(i),0); } } function formposter (i) { var url = "http://remoteserver.com/examples/events/connect.sse", es = new eventsource(url); es.onmessage = function(e) { }; es.onerror = function(e) { console.log(e); }; es.onopen = function(e) { opensockets++; if (opensockets == 1 ) { console.log(process.memoryusage() ); process.exit(code=0); } }; } the problem code huge memory leak - first console.log statement outputs { rss: 8925184, heaptotal: 5066496, heapused: 2113192 } wher

mysql - Linking table_a one result with table_b multiple results -

so here code have, prints list like: accounts_id accounts_amount payments_date payments_amount $stmt = $db->query("select * debt_accounts inner join debt_payments on payments_account=accounts_id order accounts_id asc, payments_date asc"); $num = $stmt->rowcount(); $current_price = ""; for($i=0;$i<$num;$i++){$row = $stmt->fetch(pdo::fetch_assoc); if($row['accounts_id'] != $current_price) { echo'<h3>'.$row['accounts_id'].' <font></font></h3>'; $current_price = $row['accounts_id']; } echo''.$row['payments_date'].' - '.$row['payments_amount'].' <br />'; } so want in same query if possible accounts_amount value want accounts_amount - sum(payments_amount) any appreciated please.

c# - ByteToStringConverter does not implement interface member ...IValueConverter.ConvertBack(...)'? -

my bytetostringconverter, job converting bytes human readable size (mb, gb, etc) error 1 name "bytetostringconverter" not exist in namespace "clr-namespace:zemanfilemanager.konverteri". c:\users\nikola\documents\visual studio 2013\projects\zemanfilemanager\zemanfilemanager\zemanfilemanager.xaml 14 9 zemanfilemanager using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; using system.windows.data; namespace zemanfilemanager.konverteri { public class bytetostringconverter : ivalueconverter { public object convert(object value, type targettype, object parameter, string language) { string size = "0 kb"; if (value != null) { double bytecount = 0; bytecount = system.convert.todouble(value); if (bytecount >= 1073741824) size = string.format("

ruby on rails - Devise destroy_session_path not working rails4 -

i'm new rails appreciated. can't seem figure out doing wrong. i have set gem devise , trying use 'logout route path' not working. any appreciated. many thanks error message in console railties (4.1.6) lib/rails/application.rb:144:in `call' rack (1.5.2) lib/rack/lock.rb:17:in `call' rack (1.5.2) lib/rack/content_length.rb:14:in `call' rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service' /users/artloe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/webrick/httpserver.rb:138:in `service' /users/artloe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/webrick/httpserver.rb:94:in `run' /users/artloe/.rvm/rubies/ruby-2.1.2/lib/ruby/2.1.0/webrick/server.rb:295:in `block in start_thread' rendered /users/artloe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/_trace.html.erb (3.6ms) rendered /users/artloe/.rvm/gems/ruby-2.1.2/gems/web-console-2.0.0.beta3/lib/action_dispatch/templates/rescues/routing_e

javascript - Global variable inside anonymous self-executing js function still available outside? -

i have these 2 javascript files: test1.js: (function() { console.log(global_var_test2); })(); test2.js: (function() { global_var_test2 = "test"; })(); obviously if use var keyword in test2.js global_var_test2 variable not available in test1.js..but thought when wrapping code in file inside self-executing anonymous functions created separate scope variables created without var keyword still not visible outside ? when running code above im able access global_var_test2 inside of test1.js. if im remembering correct use of self-executing anonymous function used when writing javascript modules isolate other possibly installed modules have..but doesnt seem work code above.. explain why not ? your understanding incorrect. if assign variable without declaring var , you're creating global variable, wrapper or no wrapper. in "strict" mode, error. therefore, if want make sure you're not polluting global environment — smart — put code in "s

Bash delete/modify line from a file -

lets have file contacts.txt in format number1:name1:phone1:adress1 number2:name2:phone2:adress2 the question how can delete line(contact) file or modify of components of contact? delete line thought of using this grep -ve "name1" and overwrite entire file im sure there better way this... since data appears colon-delimited, obvious tool handle awk. simple sed approaches have disadvantage treat input plain text, not yield desired result. if, example, have mr. smith , mrs. doolittle lives in smithy place 23, removing lines contain "smith" remove mrs. doolittle along mr. smith. awk, on other hand, splits line fields can tests on fields individually. example, remove mr. smith file, use awk -f : '$2 != "smith"' myfile.txt where $2 stands second field, making call select lines second field "smith". -f : sets input field separator colon rather default whitespace, lines in file split @ colons. it allows straightfor

html - Target shows as hyperlink -

i tried create target, whatever reason, target bit "id" links displays text link not not link, if know mean (it's header; underlines , there's pointer arrow cursor change, not link anywhere because target). how make not happen? (page: http://www.thesimplewardrobeblog.com/post/114843804438/how-to-develop-your-personal-style ) thanks in advance, richie my code follows link: <p class="subhead"><a href="#workbook" target="_self">skip workbook below</a></p> target: <h2><a id="workbook">your personal style workbook: 6 exercises discover personal style</a></h2> put id in <h2> tag. not create <a> tag that. so: <h2 id="workbook">your personal style workbook: 6 exercises discover personal style</h2>

android - Remove unused localizations from APK -

for android app no localizations (default language only), how can exclude localizations gradle dependencies? background: app line-of-business app language needs support english. app includes com.google.android.gms:play-services-gcm:7.0.0 push notification support. gcm library includes localizations in 73 languages. i'd rather not included. keeps apk smaller. additionally, if user running non-english language, don't want experience mix of english , localized text. in build.gradle, add resconfigs limit languages: android {     defaultconfig {         // other configuration here         resconfigs "en"     } }

c++ - Checking whether a function (not a method) exists in c++11 via templates -

so sfinae , c++11, possible implement 2 different template functions based on whether 1 of template parameters can substituted. for example struct boo{ void saysomething(){ cout << "boo!" << endl; } }; template<class x> void makeitdosomething(decltype(&x::saysomething), x x){ x.saysomething(); } template<class x> void makeitsaysomething(int whatever, x x){ cout << "it can't anything!" << endl; } int main(){ makeitsaysomething(3); makeitsaysomething(boo()); } or along line. my question is.. how 1 same thing, non-member functions? in particular i'm trying check if there's such thing an: operator<<(std::ostream& os, x& whateverclass); that exists. possible test it? edit: question different : is possible write template check function's existence? in i'm trying see whether function exists, not method i find void_t trick preferable traditional sfina

Dividing equally a vector matlab -

in mfccs have specified f_low , f_high frequency min , max bands, , compute n equally distanced mel values between these 2 frequency values. wrote f_low=1000; f_high=fs/2; filt_num=26; % number of filters stp=round(f_high/filt_num); % step f=f_low:stp:f_high; % frequency vector but can't divide equally f vector, maybe there function in matlab , or missing something? please , in advance. a bit of digging around leads me believe want linearly spaced vector filt_num entries, starting @ f_low , ending @ f_high . should use linspace follows: f = linspace(f_low,f_high,filt_num); this same last 2 lines of code. keep in mind code works when f_high larger f_low . linspace not have issue, supports descending vectors.

Is it possible to display multi-page, multi-layer TIFF images using javascript in a webpage? -

we thinking library can tiff image , display each page (frame) of tiff file in separate canvas element. pages might have layers. want able show/hide layers @ user's will. not necessary tell me complete solution or library. tell me if possible accomplish these requirements javascript or need of server-side programming? should possible. don't think browsers support tiff format natively, quick google search turns at least two tiff parsers javascript. there on, can display in way like; tiff.js has multipage demo .

perl remove data from array with field separator -

i have following perl script. #!/usr/bin/perl -w use strict; use warnings; (@failhost); %currblocked; %addblocked; $action; open (myinputfile, "/var/log/asterisk/messages") or die "\n", $!, "does log file file exist\?\n\n"; while (<myinputfile>) { ($line) = $_; chomp($line); if ($line =~ m/\' failed \'(.*?)\' - no matching peer found/) { push(@failhost,$1); } if ($line =~ m/\' failed \'(.*?)\' . wrong password/) { push(@failhost,$1); print $1 . "\n"; } } exit 0; this produces following results. 212.83.134.244:5065 212.83.134.244:5063 212.83.134.244:5092 212.83.134.244:5109 212.83.134.244:5080 212.83.134.244:5110 212.83.134.244:5096 212.83.134.244:5093 212.83.134.244:5089 212.83.134.244:5073 212.83.134.244:5101 212.83.134.244:5072 212.83.134.244:5092 212.83.134.244:5094 212.83.134.244:5076 212.83.134.244:5080 212.83.134.244:5081 212.83.134.244:5094 212.83.134

networking - Comparing received string on server side - C++ -

i followed tutorial ( http://codebase.eu/tutorial/linux-socket-programming-c/ ) , made server. thing when server receives string client, don't know how compare it. example, following doesn't work: bytes_received = recv(new_sd, incomming_data_buffer, 1000, 0); if(bytes_received == 0) cout << "host shut down." << endl; if(bytes_received == -1) cout << "receive error!" << endl; incomming_data_buffer[bytes_received] = '\0'; cout << "received data: " << incomming_data_buffer << endl; //the comparison in if below doesn't work. if isn't entered //if client sent "hi", should work if(incomming_data_buffer == "hi\n") { cout << "it said hi!" << endl; } you attempting compare character pointer string literal (which resolve character pointer), yeah, code have won't work (nor should it). since in c++, suggest this: if(std::str

sql - insert data with comma delimiter but with different ID -

hi having problem bulk insertion. challenge/objective save column comma delimiter table different id's example-> selected query @temp table rolln                       fullname 441246                   john doe, jane more, john spade 441248                   jose mendez, ali muhm, jacob stile to save in people table result after insertion people-> people_id                    rollnumber               fullname 1                                   441246                      john doe 2                                   441246                      jane more 3                                   441246                      john spade my script created repeating name insert @temp_original select rollnumber, case when charindex(',',fullname)>0 substring(fullname,1,charindex(',',fullname)-1) else fullname end fullname, case when charindex(',',fullname)>0 replace(substring(fullname,charindex('

recursion - swi prolog simple robot -

i writing program in prolog should interact user. have database of bands , dislike, , can ask prolog these bands. first have hello. to prolog, , prolog answers hello , can start asking questions like do band motorhead? and prolog should answer yes band because rock. then should able ask question. my initial idea achieve last word of question, check if in 1 of 2 list (liked-list or disliked-list), , recursively call function interact program. in fact code works well, except 1 annoying detail can't solve. here problem: ?- hello. hello! ask question: band motorhead? band because metal. ask question: don't know band. ask question: band motorhead band because metal. in fact when add question mark @ end of question, prolog answers question (no problem here), recursively call function ask questions, , adds "i don't know band" , calls once again function ask questions instead of calling once, , waiting me type question. here current code interact

arrays - Incremental issue with creating histogram (JavaScript) -

using code below trying create histograms of values in each row of dist , each row of hist histogram of 10 bins. step floating point value (0.12158...). for(i = 0; < dist.length; i++){ for(j = 0; j < dist[0].length; j++){ bin = parseint(dist[i][j]/step); if(bin == 10) bin = 9; hist[i][bin]+=1; } } dist 2d array declared as: var dist = []; for(var x = 0; x < 77; x++){ dist[x] = []; for(var y = 0; y < 50; y++){ dist[x][y] = x*y; } } hist declared as: var hist = []; for(var x = 0; x < 77; x++){ hist[x] = []; for(var y = 0; y < 10; y++){ hist[x][y] = x*y; } } the first row of hist gives me results expect, frequencies totalling 50. however, values in bins of next rows not start zero, values of these sum of values previous histograms plus current value. for example, first row of hist : [1, 10, 8, 9, 6, 7, 4, 3, 1, 1] the second row of hi

Symbolic int results in deletion of main variable (MATLAB) -

i trying this: syms x h4 t4 c13; t = 0.6*sin(pi*x); h1x = 0.5*(1 - t); h0 = h1x; h14x = -h4 -t4*(x - 0.5); h24x = h4 + t4*(x - 0.5); symvar(h14x) which returns ans = [ h4, t4, x] then u13x = (-4*int(h14x, x, 0, x) + c13)/h0 symvar(u13x) returns u13x = -(c13 + 4*x*(h4 - t4/2) + 2*t4*x^2)/((3*sin(pi*x))/10 - 1/2) ans = [ c13, h4, t4, x] and p12x = -3*int(u13x, x, 0, x) symvar(p12x) which is p12x = -3*int(-(c13 + 4*x*(h4 - t4/2) + 2*t4*x^2)/((3*sin(pi*x))/10 - 1/2), x, 0, x) ans = [ c13, h4, t4 ] as can see u13x variables [h4, t4, c13, x] , while integrating p12x got reduced [h4, t4, c13] though integral limits variable (in terms of x ). bug? can't seem weird behaviour. there workaround? here 3 possible workarounds (tested in r2015a). 1. use symbolic function 1 option make input passed sym/symvar symfun in terms of x , use optional second argument specify finite number of variable for: syms x h4 t4 c13; t = 0.6*sin(pi*x); h1x = 0.

Model.SetViewName in Spring -

i know addobject here. can please tell me modelandview.setviewname ("vendorinfo"); sorry beginner @requestmapping(value = "/listsupplier",method = requestmethod.get) public modelandview supplierlist() { list<supplier> supplierlist=adminservice.listsuppliers(); modelandview.setviewname("vendorinfo"); modelandview.addobject("supplierslist", supplierlist); return modelandview; } it sets name of view resolved configured viewresolver . let's view in /web-inf/views/vendorinfo.jsp , view resolver configured prefix /web-inf/views/ , suffix .jsp , view resolver know use prefix + viewname + suffix view rendered. modelandview javadoc

c++ - Number of unique elements in a vector -

if have vector of floats {1.2,1.2,1.2,1.3,1.4} , have find out number of unique elements, how can it? i new c++ , don't know how use iterators. thanks! edit: did this: sort(arra.begin(),arra.end()); vector <float>::iterator = arra.begin(); while ( != arra.end() ) { temp1 = *it; cout<<temp1<<"\n"; it++; while (*it == temp1) { it++; cout<<*it<<"\n"; } count++; } but gives wa. one of approaches following #include <iostream> #include <vector> #include <set> int main() { std::vector<double> v = { 1.2, 1.2, 1.2, 1.3, 1.4 }; std::cout << "number of unique elements " << std::set<double>( v.begin(), v.end() ).size() << std::endl; return 0; } the output is number of unique elements 3 if vector sorted , not empty can use

python - object of type 'int' has no len() -

i have seen other posts on here no 1 me yet. i'm confused. please comment if know what's going on here. my code:` from scipy.integrate import quad sympy.mpmath import * k=0.0 i=0.0 def i_2(x, k): return cos(2*pi*k/sqrt(1-(1-k**2)*cos(x)**2))-1 while k<=0.2: k = k + result = quad(i_2, 0, pi, k, args=()) print(result) i=0.1` the wild import use here : from sympy.mpmath import * shadows quad imported here: from scipy.integrate import quad see: from scipy.integrate import quad sympy.mpmath import * print(quad.__module__) # sympy.mpmath.calculus.quadrature instead, flip import order: from sympy.mpmath import * scipy.integrate import quad print(quad.__module__) # scipy.integrate.quadpack or (much) better yet (and preferred) avoid using wild import altogether: from scipy.integrate import quad sympy.mpmath import cos, pi, sqrt print(quad.__module__) # scipy.integrate.quadpack also, you'll need

c - Need some suggestions on how to print a histogram more neatly -

i'm writing program read input , give histogram of character count k & r - ex. 1.13 any suggestions on how can improve code? matter whether or not if test status in condition or out first? have noticed in examples people test see if c blank or tab first. i think need revisit histogram. doesn't scale results. draws hyphen based on length. revised make little bit more readable think. // print histogram of length of words in it's input. #include <stdio.h> #define in 1 #define out 2 #define max 99 int main(){ int c; // character int countofletters = 0; int insideword = out; int frequencyoflengths[max]; int longestwordcount = 0; int i, j; // counters (i = 0; < max; i++){ frequencyoflengths[i] = 0; } while ((c = getchar()) != eof){ if (c == ' ' || c == '\n' || c == '\t'){ if (insideword == in){ if (countofletters > max){

ios - Change UINavigationBar background image and make the UINavigationBar to scale -

what easiest way change uinavigationbar background image , make main uinavigationbar scale background image size? i designed navigation bar not size of table view controller navigation bar, , imported image xcode , want like: [self.navigationcontroller.navigationbar setbackgroundimage:[uiimage imagenamed:@"bg.png"] forbarmetrics:uibarmetricsdefault]; but not work, anyway think way have problem height since designed nav bigger. how can please? it's better not that, there hacks can do, example hide navigation bar , create personalized bar height want. check post: https://stackoverflow.com/a/7533098/4559321 i recommend change design fit standard uinavigationbar , save lot of work.

C#/WPF - Shared Style Setters -

i'm trying style set of controls display levels device. i'm using label control has style multidata trigger checks if value of field between value, , applies highlight indicate error. <style x:key="highlight-stat" targettype="label"> <style.triggers> <multidatatrigger> <multidatatrigger.conditions> <condition value="true"> <condition.binding> <multibinding converter="{staticresource betweenvaluesconverter}"> <binding/> <binding> <binding.source> <sys:int32>100</sys:int32> </binding.source> </binding> <binding> <bindin

mysql - SQL select percentage -

i have 2 tables in mysql hold users , 1 holds there subscriptions. there users may sign not subscribe. use following query count of users have not subscription: select count(social_users.id) social_users left join socials on social_users.id = socials.social_user_id socials.social_user_id null the above query works fine , return number count of users have no subscription. now, want there percentage relative total number of users. tried make 2 count sql queries , divide them follows: (select count(social_users.id) social_users left join socials on social_users.id = socials.social_user_id socials.social_user_id null) / select count(social_users.id) social_users however, query not work. need know other way allow me embed 2 select , divide them , multiply result 100. try this select ( (select count(social_users.id) social_users left join socials on social_users.id = socials.social_user_id socials.social_user_id null) / (select count(social_users.id) socia

python 2.7 - Converting from PyQt4 signal to PyQt5 signal doesn't work -

i trying convert game pyqt4 pyqt5 , having difficulty converting newer signal types. have gone original , trying convert signal first using pyqt4. commented line old (working) version, underneath new version. 'new' version passing same value event handler: 0. have tried many subtly different versions, nothing seems work. ideas? self.cellbuttonnames = [self.ui.cell0button, self.ui.cell1button, self.ui.cell2button, self.ui.cell3button, self.ui.cell4button, self.ui.cell5button, self.ui.cell6button, self.ui.cell7button, self.ui.cell8button, self.ui.cell9button, self.ui.cell10button, self.ui.cell11button, self.ui.cell12button, self.ui.cell13button, self.ui.cell14button, self.ui.cell15button, self.ui.cell16button, self.ui.cell17button, ..., self.ui.cell126button, self.ui.cell127button, self.ui.cell1

VIM Pressing shift+i exits visual select mode -

i trying comment out file lines in python. following below steps column edit mode. however, every time press shift + i, exits visual mode , enters insert mode. suggestion step 1: press ctrl + v step 2: select lines using arrow keys step 3: press shift + i, quits visual mode. note: 'r' enters replace mode without exiting visual mode yes, exits visual mode let enter text @ beginning of visual selected block, guess want add # comment whole block, type # , press esc see selected block commented out.

ggplot2 - Drawing colored US State map with cut_number() in R -

Image
i have dataframe called "drawdata": geoname ranking 1 alabama 15 2 alaska 2 3 arizona 28 4 arkansas 12 5 california 19 6 colorado 7 7 connecticut 42 8 delaware 37 9 district of columbia 9 10 florida 38 11 georgia 11 12 hawaii 48 13 idaho 10 14 illinois 16 15 indiana 26 16 iowa 34 17 kansas 27 18 kentucky 20 19 louisiana 4 20 maine 51 21 maryland 30 22 massachusetts 39 23 michigan 14 24 minnesota 23 25 mississippi 41 26 missouri 32 27 montana 25 28 nebraska 21 29 nevada 45 30 new hampshire 47 31 new jersey 33 32 new mexico 5 33 new york 44 34 north carolina 13 35 north dakota 31 36 ohio 35 37 oklahoma 6 38 oregon 18 39 pennsylvania 40 40 rhode island 49 41 south carolina 29 42 south dakota 46 43 tennessee 43 44 texas 3 45 utah 17 46 vermont 50 47 virginia 8 48 washington 24 49 west virginia 22 50 wisconsin 36 51 wyoming 1

c++ - Does reference variable occupy memory? -

this question has answer here: why reference size 4 bytes - c++ 2 answers i have read reference variable shares same memory address original variable takes space on stack. , reference has same memory address original variable, known alias. so, question how memory allocations done reference variables ? 8.3.2 references §4 it unspecified whether or not reference requires storage that being said, if reference needs storage, typically needs storage pointer: struct p { int* p; }; struct r { int& r; }; static_assert(sizeof(p) == sizeof(r), "sizeof(p) == sizeof(r)");

c++ - sqlite3 bind variables syntax -

i trying implement c++11 wrapper c api of sqlite, particularly sqlite3_bind functions. in shape of (example code): sqlt3::exec<void>( _db, "insert or replace window values('position', ?3, ?4);\n" "insert or replace window values('size', ?1, ?2);\n" "insert or replace window values('maximized', ?5, '0');\n", size.x, size.y, position.x, position.y, static_cast<int>(ismaximized()) ); the problem here ? shared between different statements. exec function internally prepares subsequent sql statements 1 one. cannot determine parameters should bound statements, because there no api statement slots statement contains. can count of slots n (a max nnn ?nnns) unable determine whether particular slots 0 n occupied. because there can single ? no number , sqlite3_bind_parameter_name returns null both nameless parameter , lack of parameter. ideally have function returns list

sprite kit - How to make different objects compatible with IPhone and IPad using Spritekit -

so i've been trying make objects correct size both ipad , iphone using proportions based on size of screen. i've been having trouble doing objects such sklabelnode, due using fontsize instead of (width, height) format. wanted make sklabelnode of fontsize 35 on iphone 6, how use proportions make same size relative screen ipad 2 works both iphone , ipad? sklabelnode *mylabel2; mylabel2 = [sklabelnode labelnodewithfontnamed:@"helveticaneue-light"]; mylabel2.text=@"click"; mylabel2.fontsize = 35; it's not possible the frame property provides bounding rectangle node’s visual content, modified scale , rotation properties. frame non-empty if node’s class draws content. each node subclass determines size of content differently. in subclasses, size of node’s content declared explicitly, such in skspritenode class. in other subclasses, content size calculated implicitly class using other object properties. example,

c++ - Lua return custom data from C function -

despite searching hard, couldn't find valid lua c api example calling lua function returning custom data c function. example, have register function "getmyvector" , i'm calling lua retrive informations c, got table want access access variable struct in c, example: local x = getmyvector() print(x[1]) -- print(x[2]) -- j print(x[3]) -- k -- how access via this: print(x.i) print(x.j) print(x.k) my c function pushing vector in 3 dimensional array lua_pushnumber: static int getmyvector(lua_state *l) { vec3_t vec; vec[0] = 1; vec[1] = 2; vec[3] = 3; lua_newtable(l); lua_pushnumber(l, vec[0]); lua_rawseti(l, -2, 1); lua_pushnumber(l, vec[1]); lua_rawseti(l, -2, 2); lua_pushnumber(l, vec[2]); lua_rawseti(l, -2, 3); return 1; } you want lua_settable . allows set keys table. if key literal can data x["i"] or x.i . code should like static int getmyvector(lua_state *l) { vec3_t vec; vec[0]

ios - Ignore presentModalViewController upon return -

so hoping simple , can done: i have loginviewcontroller performs facebook login. have code setup once user enters or information , clicks login, returns same loginviewcontroller automatically segues tab controller. want have happen, button called "my profile" in view controller "profileviewcontroller" later in storyboard (6 views later) take me initial loginviewcontroller. the issue segue have goes directly clicking "login" tab controller hard coded loginviewcontroller.m file. makes when click "my profile" in profileviewcontroller, takes me loginviewcontroller, segues automatically tab controller in beginning. what want have segue ignored when click "my profile" button. here segue using (this in loginviewcontroller.m file): uistoryboard *storyboard = [uistoryboard storyboardwithname:@"main" bundle:nil]; uitabbarcontroller *tabcontroller = (uitabbarcontroller *)[storyboard instantiateviewcontrollerwithidentifier

java - JSONObject getString(String.valueof(variable integer)) not working -

i have searched lot answer or explanation why "jsonobject.getstring()" not working. first response php server {"3":["s1","2013","final"],"2":["s0","2010","mid"],"1":["s6","2015","final"]} this code: ccnerequest.add(new basicnamevaluepair("semester", "s")); ccnejsonstring = ccneexams.getjsonfromurl(ccneurl, ccnerequest); if (ccnejsonstring != null) { try { jsonobject jobj = new jsonobject(ccnejsonstring); (int = 0; < jobj.length(); i++) { jsonarray jsonarray = new jsonarray( jobj.getstring(values[i])); } this code working fine me while values[] array implemented this: public string[] values = { "1", "2", "3", "4", "5", "6", "7",

objective c - Prohibit multiple selection of NSMenuItems by cocoa binding -

i have multiple nsmenuitems in nsmenu. want making 1 of them being on state @ same time. (just single selection list box.) the first option implement target/action methods them , write code so. if possible want use cocoa binding this. here want do. i have single variable can set 3 different values (0,1,2). number corresponds menu items(nsmenuitem0, nsmenuitem1, nsmenuitem2). 1 of nsmenuitems here must on state, , others must off state. so initial state, nsmenuitem0 on, nsmenuitem1 , nsmenuitem2 off , variable 0. , if user clicks nsmenuitem1, nsmenuitem0, nsmenuitem2 turn off state , variable set 1. when variable set 2 programatically, nsmenuitem2 should have check, , others shouldn't. i tried create 3 properties corresponds each item's value bind, , tried customise setter method didn't work because when user clicks menu item on state, check turned off. (i want keep check if user clicks item on state.) the setter method wrote this. - (void)setitem0:(bool)