Posts

Showing posts from January, 2012

php - Mysqli update throwing Call to a member function bind_param() error -

hi have 70/80 field form need insert table instead of manually creating 1 huge insert statement firstly have created table in db names of inputs in form here code use create/alter table function createtable($array, $membermysqli) { foreach ($array $key => $value) { //echo "<p>key: ".$key." => value: ".$value . "</p>"; $query = "alter table questionnaire add ".$key." text"; if($stmt = $membermysqli->prepare($query)) { $success = $stmt->execute(); } } echo "<h1>array count: ". count($array) ."</h1>" ; } this works fine , altered table how wanted it. insert form values basic 1 field insert store id of row , have loop post variables updating row. here code that: $stmt = $membermysqli->prepare("insert questionnaire(userid) values (?)"); $stmt->bind_param('s'

python - Plotting with lines connecting points -

Image
i'm creating program determine minimum, maximum, , percentiles of winds @ heights. file split 5 columns. code far looks this: import matplotlib.pyplot plt f = open('wind.txt', 'r') line in f.readlines(): line = line.strip() columns = line.split() z = columns[0] u_min = columns[1] u_10 = columns[2] u_max = columns[4] u_90 = columns[3] plt.plot(u_min,z,'-o') plt.plot(u_max,z,'-o') plt.show() as can see it's plotting each min , max @ specific altitude dot. how can adjust makes line instead. edited answer due comment to create line connects min values: store min values in list (using append) plot list the code: import matplotlib.pyplot plt f = open('wind.txt', 'r') min_vector = [] max_vector = [] z_vector = [] line in f.readlines(): line = line.strip() columns = line.split() z = columns[0] u_min = columns[1] u_10 = columns[2] u_max = columns[

silverlight - Catastrophic error during OOB update using CheckAndDownloadUpdateAsync() -

i'm in dead end error, may experienced similar , knows how resolve? the problem when calling checkanddownloadupdateasync() request server sent , server returns either 304 or 200 http code. in case of 200 silverlight runtime performs update of application. doesn't happen me. strange thing works on mac, not on windows. request get https://somedomain.com/some.xap http/1.1 if-modified-since: mon, 01 jun 2015 15:13:18 gmt user-agent: silverlight host: somedomain.com response http/1.1 200 ok content-type: application/octet-stream last-modified: tue, 14 jul 2015 13:02:36 gmt x-request-id: v-5daa5e84-2a36-11e5-bbce-22000ac00b9d x-ah-environment: preprod x-cache-hits: 2 x-age: 1989 expires: tue, 14 jul 2015 15:14:18 gmt cache-control: max-age=0, no-cache, no-store pragma: no-cache date: tue, 14 jul 2015 15:14:18 gmt transfer-encoding: chunked connection: keep-alive connection: transfer-encoding x-akamai-staging: essl sl runtime gets valid 200 ok response, throws catastro

r - understanding ggplot2 geom_map map_id -

this comes ggplot2 documentation: # better example crimes <- data.frame(state = tolower(rownames(usarrests)), usarrests) library(reshape2) # melt crimesm <- melt(crimes, id = 1) if (require(maps)) { states_map <- map_data("state") ggplot(crimes, aes(map_id = state)) + geom_map(aes(fill = murder), map = states_map) + expand_limits(x = states_map$long, y = states_map$lat) last_plot() + coord_map() ggplot(crimesm, aes(map_id = state)) + geom_map(aes(fill = value), map = states_map) + expand_limits(x = states_map$long, y = states_map$lat) + facet_wrap( ~ variable) } i don't understand how can work since there no common identifier in states_map data frame uses "region" name states column , crimes data frame labels states, "states." ties data map? in example poster renames columns of map data frame conform data ggplot2 documentation doesn't seem it. how? when rename columns of states_map in example above, "state"

java - How to customize the binding expression in Netbeans? -

Image
i have jcheckbox, when select it, must disable jcombobox. i try negate binding expression in mode: ${!enabled} but doesn't work, java application doesn't start. what's trouble? you have go selected property not enabled property of checkbox. and have bind combobox's enabled property checkbox's selected property. ${!selected}

jquery - Update element within a cloned div -

i have div <div id="mydiv"><h3 id="myheader"></h3 ></div> and have created few clones of div var $divclone1 = $('#mydiv').clone(); var $divclone2 = $('#mydiv').clone(); var $divclone3 = $('#mydiv').clone(); i want able set value of myheader different in each of 3 clones - idea list individual clones screen different myheader values. how can achieved jquery? ids should unique on page. i'd suggest using class names instead of ids. if need unique ids each element, apply them after cloning. i use jquery once reference original div, make clones of that. <div class="mydiv"><h3 class="myheader"></h3 ></div> var $mydiv = $('.mydiv'), $divclone1 = $mydiv.clone(), $divclone2 = $mydiv.clone(), $divclone3 = $mydiv.clone(); $divclone1.find('.myheader').attr('id', 'clone1').text('clone1'); // a

osx - Phonegap installation fails using npm -

Image
i followed up , running phonegap on mac osx on every single step got stuck i have tried many solutions , fixes still nothing working. followed this answer still stuck. what cause these issues?! update1: when install cordova using sudo npm install -g cordova following: even when type cordova, -bash: cordova: command not found update2: i fixed cordova installation using following steps: sudo chown -r $user /usr/local sudo chmod -r 0775 /usr/local add path using this answer add path bash_profile using this link open terminal , type cordova -v , working displaying version phonegap still failing , can't seem find fix it

ios - Trying to animate a circle formation using Swift -

Image
i new swift animations , need in understanding this. so have following code creates circle based on input provided. func drawcircle(percentage:cgfloat){ //some circle drawing code , circle drawn using percentage % provided. } i call function with drawcircle(0.5) i this. call using drawcircle(0.75) i this. based on percentage passed create circle/semi-circle/ring. hope making sense. now part want animate circle formation. when call drawcircle(0.5) should animate smoothly 0.0% 0.5% if call method timer , pass parameters sequentially (0.00, 0.1, 0.2 etc 0.5) can work. example: but don't think it's right way do. looking if there better way using animations in swift transition 0.0 0.5 smooth. [i don't want change existing codes circle creation. existing code base made working , has time factor , risk change right on existing code. looking function "drawcircle(%)" can used achieve desired output. suggestions welcome.] tia>

C++ Switch Cases -

Image
i doing quiz online based on c++ switch statement. came across question , have fair understanding of how switch statements work 1 question made absolutely no sense me. can please explain? why answer d , not c? case 2: default case or what? quiz can found at: http://www.cprogramming.com/tutorial/quiz/quiz5.html here's how code behaves. x equal 0 so cout<<"zero"; executed. since there's no break; after it, the second case executed: cout<<"hello world"; and since cout<<"something"; doesn't add newline after printing, they're printed single word.

How to create an event emitter with elixir, the otp way -

what best way in elixir create foreground process tick on every given amount of time? my main problem approach like: defmoulde ticker def tick do_something() :timer.sleep(1000) tick end end works, wrong design. it's not ticking every second, every second plus time do_something() complete. spawn process handle "something" still there small lag. also, i'm trying build mix app, there genservers involved, , main foreground process (the 1 i'm asking here) should call servers every x seconds. there otp way of doing this? i think timer:apply_interval/4 should suit needs. used this: defmodule tick def tick io.inspect(:tick) end end :timer.apply_interval(:timer.seconds(1), tick, :tick, []) the arguments in order interval, module name, function call , arguments call with. can send messages genservers inside function. check out full documentation here: apply_interval/4 another thing consider if tick function ever sending

python - Django ManyToManyField not saving in admin -

models.py class document(models.model): document_type_d = models.foreignkey(documenttype, verbose_name="document type") class section(models.model): document_type_s = models.manytomanyfield(documenttype, verbose_name="document type") class documenttype(models.model): document_type_dt = models.charfield("document type", max_length=240) when create section in admin doesn't appear save document_type_s. in django shell can see documenttype saving properly: >>> dt = documenttype.objects.all() >>> d in dt: ... print d.document_type_dt ... campus lan wan unified communications when check sections get: >>> original_sections = section.objects.all() >>> in original_sections: ... print a.document_type_s ... lld.documenttype.none lld.documenttype.none lld.documenttype.none lld.documenttype.none lld.documenttype.none lld.docum

Java best practice: Class with only static methods -

i have application have class called plausibilitychecker . class has static methods, checkzipcodeformat or checkmailformat . use them in gui classes check input before sending lower layer. is practice? thought i'd go static methods don't have care passing instance gui classes or having instance field in each gui class doesn't reference gui object. i noticed files class of java nio has static methods assume can't horribly wrong. i you're doing right. apart of that, advices utility class: make sure doesn't have state. is, there's no field in class unless it's declared static final . also, make sure field immutable e.g. string s. make sure cannot super class of other classes. make class final other programmers cannot extend it. this 1 debatable, may declare no-arg constructor private , no other class create instance of utility class (using reflection or similar do, there's no need go protective class). why may not this? well, s

ruby - Using a rails engine in rspec -

how can create rails engine inside of spec test? using test gem. here trying module zan class engine < ::rails::engine isolate_namespace myengine end end and getting failure/error: class engine < ::rails::engine nameerror: uninitialized constant rails i've tried bundle exec rake spec same result. you need add rails dependency of gem, , require in spec helper: # your_gem.gemspec spec.add_development_dependency 'rails' # spec_helper.rb require 'rubygems' require 'bundler/setup'

c++ - OpenCV stitch images by warping both -

Image
i found lot questions , answers image stitching , warping opencv still not find answer question. i have 2 fisheye cameras calibrated distortion removed in both images. now want stitch rectified images together. pretty follow example mentioned in lot of other stitching questions: image stitching example so keypoint , descriptor detection. find matches , homography matrix can warp 1 of images gives me stretched image result. other image stays untouched. stretching want avoid. found nice solution here: stretch solution . on slide 7 can see both images warped. think reduce stretching of 1 image (in opinion stretching separated example 50:50). if wrong please tell me. the problem have don't know how warp 2 images fit. have calculate 2 homografies? have define reference plane rect() or something? how achieve warping result shown on slide 7? to make clear, not studying @ tu dresden found while doing research. warping 1 of 2 images in coordinate frame of other more

c# - How to return an object that's dependent on a chain of using statements? -

i'd write method similar one: c make() { using (var = new a()) using (var b = new b(a)) { return new c(b); } } this bad since when method returns, c keeps reference disposed object. note that: a implements idisposable . b implements idisposable . c not implement idisposable since author of c stated c not take ownership of b . your situation similar have seen when querying database. in attempt separate logic, see code this: var reader = executesql("select ..."); while (reader.read()) // <-- fails, because connection closed. { // process row... } public sqldatareader executesql(string sql) { using (sqlconnection conn = new sqlconnection("...")) { conn.open(); using (sqlcommand cmd = new sqlcommand(sql, conn)) { return cmd.executereader(); } } } but, of course, can't work, because time sqldatareader returns executesql method, connection

parsing - PHP Parse/Syntax Errors; and How to solve them? -

Image
everyone runs syntax errors. experienced programmers make typos. newcomers it's part of learning process. however, it's easy interpret error messages such as: php parse error: syntax error, unexpected '{' in index.php on line 20 the unexpected symbol isn't real culprit. line number gives rough idea start looking. always @ code context . syntax mistake hides in mentioned or in previous code lines . compare code against syntax examples manual. while not every case matches other. yet there general steps solve syntax mistakes . references summarized common pitfalls: unexpected t_string unexpected t_variable unexpected '$varname' (t_variable) unexpected t_constant_encapsed_string unexpected t_encapsed_and_whitespace unexpected $end unexpected t_function … unexpected { unexpected } unexpected ( unexpected ) unexpected [ unexpected ] unexpected t_if unexpected t_foreach unexpected t_for unexpected t_while unexpected t_do

ios - Watchkit`s WKInterfaceImage setImage causes "Terminated due to Memory error" -

i want animate images on watch (like activity app, if you´re interested, it´s not important problem) i draw images in loop first: glancecontroller.m nsmutablearray *images = [[nsmutablearray alloc] init]; for(int = 0, j = 0; < 10; i++, j++){ @autoreleasepool { // ... uigraphicsbeginimagecontextwithoptions(rect.size, no, 0); // ... // create uiimage , save array later uiimage *ejcircle = uigraphicsgetimagefromcurrentimagecontext(); [images addobject: ejcircle]; ejcircle = nil; uigraphicsendimagecontext(); } } so far works fine, autoreleaspool, memory consumption not high here, (about 5 mb before autoreleasepool gets drained 2 mb) however try animate in wkinterfaceimage , memory error: // take array , create animated image out of uiimage * img = [uiimage animatedimagewithimages:images duration:1.0]; // memory normal 2 mb after line [wkinterfaceimage setimage:img]; // app crashes here //

parsing - Creating Simple Parser in F# -

i attempting create extremely simple parser in f# using fslex , fsyacc. @ first, functionality trying achieve allowing program take in string represents addition of integers , output result. example, want parser able take in "5 + 2" , output string "7". interested in string arguments , outputs because import parser excel using excel dna once extend functionality support more operations. however, struggling simple integer addition work correctly. my lexer.fsl file looks like: { module lexer open system open microsoft.fsharp.text.lexing open parser let lexeme = lexbuffer<_>.lexemestring let ops = ["+", plus;] |> map.oflist } let digit = ['0'-'9'] let operator = "+" let integ = digit+ rule lang = parse | integ {int(int32.parse(lexeme lexbuf))} | operator {ops.[lexeme lexbuf]} my parser.fsy file looks like: %{ open program %} %token <int>int %token plus %start input %type <int>

database - SQL: My very short code times out; REGR_SLOPE is being super slow -

i'm pulling (read-only) information database has couple thousand rows in 2 different tables, 1 5 columns , 1 3 columns. here's code: select distinct q1.machine_id, q1.signal_id, round(86400000*(regr_slope(ts.value, ts.epoch) on (partition ts.machine_signal_id))) rate, q1.last_value tsd_sub ts, ( select ms.machine_signal_id, ms.last_timestamp machine_signal ms (ms.machine_id 'cv%' or ms.machine_id 'mt%') , (ms.signal_id = any('wfrcount','wfrcntr') or ms.signal_id '%waferct%')) q1 ts.machine_signal_id = q1.machine_signal_id , ts.epoch > (q1.last_timestamp - 604800000) now i'm not sure why should take long, code runs on fifteen minutes until times out. inner bit, select * machine_signal (machine_id 'cv%' or machine_id 'mt%') , (signal_id = any('wfrcount','wfrcntr') or signal_id '%waferct%') runs quickly, pulling 5 columns , 3 hundred rows. full code using (relati

class - Javascript: Revealing Module Pattern. Access private members -

i have javascript library exposing members using ' revealing module pattern '. have particular need need access private member . can me on regard? tips , tricks? highly appreciate if can shed light on this. in advance. revealing module pattern addy osmani var myrevealingmodule = (function () { var privatevar = "ben cherry", publicvar = "hey there!"; function privatefunction() { console.log( "name: " + privatevar ); } function publicsetname( strname ) { privatevar = strname; } function publicgetname() { privatefunction(); } // reveal public pointers // private functions , properties return { setname: publicsetname, greeting: publicvar, getname: publicgetname }; })(); myrevealingmodule.setname( "paul kinlan" ); myrevealingmodule.getname(); // there anyway access 'privatefunction'???? is there anyway access ' pr

linux - How to use a different .bashrc -

i got common .bashrc in /home/ folder. have .basrch (.bashrc1) (i have lot of aliases) cannot copy content 1 another. so. want know if there possibility use .bashrc1 default or if there additional command execute aliases .bashrc1 thanks in .bashrc , put source /path/to/.bashrc1 to force bash use different .bashrc (bad practice) mv ~/.bashrc ~/bob/ bash --rcfile ~/bob/.bashrc for example, if use gnome, add custom keyboard shortcut above command.

multi-tenant database architecture -

i building saas application , discussing 1 database per client vs shared databases. have read lot, incluisve topics here @ have still many doubts. our plataform should highly customizable each client. (they should able have custom tables , add custom fields existing tables). multiple database aproach seems great in case. the problem is. should "users" table in master database or in each client database?. user might have 1 or more organizations, present in multiple databases. also, generic tables countries table, etc? it makes sense in master database. have many tables created_by field have foreign key user. have permission related tables client. i loose power of foreign keys if multiple databases, means more queries database. know can use cross-join between databases if in same server loose scalability. (i might need have multiple database servers in future). have tought federated tables. not sure performance. the technologies using php , symfony 2 framework , m

scripting - powershell - inserting 7-zip parameters as variables -

i trying run script archive specific directory , exclude type of files. problem if try insert of parameters main 7z command - parameters doesn't work here code: $source = "c:\source" $destination = "d:\dest" $date = get-date -uformat "%d-%m-%y" $name = "d-"+$date+".zip" $excludefiletypes= "-x!'*.css' -x!'*.exe' -x!'*.dll' -x!'*.iso' -x!'*.ace' -x!'*.arj' -x!'*.jar' -x!'*.bz2' -x!'*.lha' -x!'*.lzh' -x!'*.rar' -x!'*.zip' -x!'*.tar' -x!'*.tgz'" 7z "$destination$name" "$source" -r $excludefiletypes -mx=9 if replace $excludefiletypes value - 7z command works. have no idea problem. guess can't work variables that. i had same issue while ago trying execute msi installers command line. try executing this: $cmdargs = "a $destination$name $source -r $excludefiletypes -mx=9&q

c++ - SFML- Missing ';' before identifier -

i want player create object of class bullet. result: syntax error : missing ';' before identifier 'bullet' from i've can find issue bullet class isn't known compiler @ point, how make known? player class class player :public entity{ private: float velocity; sprite titlesprite; texture titletexture; sprite playersprite; texture playertexture; bullet bullet; // <----------- public: virtual void draw(rendertarget& target, renderstates states)const; virtual void update(float dt); void moveplayer(float offset); sprite getplayersprite()const; sprite gettitlesprite()const; bullet getbullet(); player(); virtual ~player(); }; bullet class #include "player.h" class bullet : public entity{ private: sprite bulletsprite; texture bullettextucre; public: void shootbullet(float offset); sprite getbulletsprite()const; sprite getbullettexture();

python - Why do GeneratorExit and StopIteration have different base classes? -

i taking @ hierarchy of built-in python exceptions, , noticed stopiteration , generatorexit have different base classes: baseexception +-- systemexit +-- keyboardinterrupt +-- generatorexit +-- exception +-- stopiteration +-- standarderror +-- warning or in code: >>> generatorexit.__bases__ (<type 'exceptions.baseexception'>,) >>> stopiteration.__bases__ (<type 'exceptions.exception'>,) when go specific description of each exception, can read following: https://docs.python.org/2/library/exceptions.html#exceptions.generatorexit exception generatorexit raised when generator‘s close() method called. directly inherits baseexception instead of standarderror since technically not error. https://docs.python.org/2/library/exceptions.html#exceptions.stopiteration exception stopiteration raised iterator‘s next() method signal there no further values. derived exception rather standarderror

python - How can I run site js function with custom arguments? -

i need scrape google suggestions search input. use selenium+phantomjs webdriver. search_input = selenium.find_element_by_xpath(".//input[@id='lst-ib']") search_input.send_keys('phantomjs har python') time.sleep(1.5) lxml.html import fromstring etree = fromstring(selenium.page_source) output = [] suggestion in etree.xpath(".//ul[@role='listbox']/li//div[@class='sbqs_c']"): output.append(" ".join([s.strip() s in suggestion.xpath(".//text()") if s.strip()])) but see in firebug xhr request this . , response - simple text file data need. @ log: selenium.get_log("har") i can't see request. how can catch it? need url using template requests lib use other search words. or may possible run js initiate request other(not input field) arguments, possible? you can solve python+selenium+phantomjs only. here list of things i've done make work: pretend browser head changing p

How does sql server decides which transaction is first and which one is the last if both happen at the same time -

i have basic question transaction - if 2 transactions different sessions start @ same time, 1 transaction has wait till other finishes. 1 of acid properties. question how system decide transaction first 1 , 1 has wait both transactions happen @ exatly same time. right, not possible determine since sql server internal. see when there 2 processes accessing same table, once process declared dead lock victim while other executes. choosing process dead lock victim taken care sql server. believe might consider milli seconds or micro seconds difference between 2 processes , set priority. hope helps!

javascript - Modal window with Angular (UI-Router / Directive) -

i have spent time looking generic way of controlling modal window angularjs , none of proposed options anywhere near 'good' solution. the directive solution i found this demo, downside of have manually manage , store state of modal , cross-scope update it: scope.$parent[attrs.visible] = true; also if had add more functionality adding item popup involve more ugly code on parent page scope. the ui-router solution this official guide on how use modals ui router. this using ui.bootstrap.modal my question is, there simple , elegant solution quite frankly simple problem... something example: .state('popup', { url: '/item/add/', views: { 'popupview': { templateurl: "/mypopup.html", controller: "mypopupcontroller" } }, type: 'modal' }) and things close, redirect, submit, handled in mypopupcontroller . i not seekin

How to add horizontal as well as vertical lines in listView android -

i want custom listview remember need stretch listview lines vertical , horizontal if there not list item. try using list divider horizontal lines , use vertical lines in list_item.xml shows lines depends upon size of array means if arraylist has 5 objects shows 5 lines both vertical , horizontal.

c - Search function not working between files -

i have 2 files test2.c , comfunc.c test2.c conatins #include "common.h" #include <stdio.h> #include <stdlib.h> int main() { printf("hello"); int n, i,po; char *process=null;//stores host ip connected char *ip = null,*port=null;//port connect char *pch=null; ip = malloc(50*sizeof(char)); pch = malloc(50 *sizeof(char)); port = malloc(50 * sizeof(char)); process = malloc(5 * sizeof(char)); //int n; char str[650]; //int = 0, ret = 0; struct data_struct *ptr = null; ptr = openfile("server.cfg", o_rdonly); ptr = search_in_list("clientip", null); if ( ptr != null) { printf("\nclientip:%s\n",ptr->val); ip = ptr->val; } else { printf("can't find clientip connect\n"); exit(0); } ptr = search_in_list("port", null); if ( ptr != null) {

java - ClassCastException when subclassing ParseUser (Parse.com) -

i have custom fields in _user class on parse , subclass in order implement convenience methods such getname(), getsurname() , on... have no problems when subclassing parseobjects, parseuser classcastexception when obtaining current user. here have done: @parseclassname("_user") public class parsestudent extends parseuser { ... } then subscribed new class in application class parseobject.registersubclass(parsestudent.class); when try access current user instance of subclass in way parsestudent user = (parsestudent) parseuser.getcurrentuser(); i exception. ideas on wrong? the problem in custom subclass subscribing, performed after parse initialization. must done before it, stated in docs .

Safari fails to render image in nested SVG -

so given html, background image loads fine in firefox, ie , chrome. in safari, ignores it. <!doctype html public "-//w3c//dtd html 4.01//en" "http://www.w3.org/tr/html4/strict.dtd"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <meta http-equiv="content-style-type" content="text/css"> <title></title> </head> <body> <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" viewbox="0 0 141.72999572753906 255.1199951171875"> <image xlink:href="http://labels.labellogiclive.com/alfresco_10_p1_alf001_uk__v0.svg" preserveaspectratio="none" x="0" y="0" width="141.73" height="255.12"></image> </svg> </body> </html> now thought might server issue, not gi

edi - after custom order->save() not returning and stopping execution in magento -

after custom order->save() not returning , stopping execution in magento my code below: ​​ $order->setpartnerwarehouse($warehouse); $order->settradingpartner($businesstype); $order->setpartnerorderid($partnerorderid); $order->setwarehouse($warehouse); $order->setcustomerordernumber($customerordernumber); $order->setpickupdate($pickup->datetime); $order->setpickupmethod($pickup->description); $order->setpartnershipmentmethod($pickup->code); $order->save(); $icn = rand(100000000, 999999999); $edi = generateresponse_855($order, $icn); echo $edi; i not able return after order save action, there thing, please suggest

sql - Delete Last Character -

stringx varchar(30); stringx not column in table . i have stringx = 'he teacher , ' how can delete last char ( , )? you can use rtrim that: select rtrim(stringx, ', ') tabkename also note have space before , after , , need both , , in rtrim call.

php - Converting string to INT returns 0 -

i know there alot of similar topics posted similiar problems none helped me in case. creating insert form table called product. passing data post method. part giving me troubles. since post pass string values, need convert id_category int because type set int in database. problem when convert string value int value returned 0. <form method="post" action="insert_product.php" enctype="multipart/form-data"> <table> <tr> <td>kategorija:</td> <td><select name="category" tabindex="1"> <option value="">odaberi kategoriju</option> <?php $sql="select * category order category_name"; $result=mysqli_query($connection,$sql) or die(mysql_error()); if(mysqli_num_rows($result)>0){ while($row=mysqli_fetch_assoc($result)){ echo "<option value='{".$row['id_category']."}'>&q

ruby on rails - Error Undefined method `admin?' for nil:NilClass - Seems simple won't work -

i have small problem ive tried fix hour. seems simple. if goes user index view want them redirected root url. unless they're admin. any clues how fix? thank in advance. i have simple test test "should redirect index when not logged in" :index assert_redirected_to login_url end but receive error. 1) error: userscontrollertest#test_should_redirect_index_when_not_logged_in: nomethoderror: undefined method `admin?' nil:nilclass app/controllers/users_controller.rb:78:in `admin_user' test/controllers/users_controller_test.rb:42:in `block in <class:userscontrollertest>' my admin_user method in user controller below # confirms admin user. def admin_user redirect_to(root_url) unless current_user.admin? end you need check if user has been logged in. if not, current_user nil . may want check in admin_user method too. redirect_to(root_url) unless current_user.try(:admin?)

javascript - show multiple alert in one message in jquery -

i have multiple required field controls on aspx form. now want show validation message on button click if not filled or checked. i want on 1 message in jquery. here jquery code:- $(document).ready(function () { $('#btnsave').click(function (e) { if (!validatetitle() || !validateprefix() || !validatetextboxes()) { e.preventdefault(); } }); function validatetitle() { if ($("#ddltitle").val() > "0") { if ($("#ddltitle").val() == "1104" && $("#txttitle").val() === "") { alert("please enter text in other title"); return false; } return true; } else { alert('please select title'); return false; } } function validateprefix() { if ($("#d

swift - Segment controller issue -

Image
i've got segment controller above connected code bellow. @iboutlet weak var coatsegmentcontroller: uisegmentedcontrol! @ibaction func coatselectinput() { switch (self.unitsegmentcontroller.selectedsegmentindex) { case 0: coatsetter = 1 //println("switched coat 1") println(unitsegmentcontroller.selectedsegmentindex) case 1: coatsetter = 2 //println("switched coat 2") println(unitsegmentcontroller.selectedsegmentindex) case 2: coatsetter = 3 //println("switched coat 3") println(unitsegmentcontroller.selectedsegmentindex) default: println("coat switch did not work") } } no matter segment select return i've selected first segment. if hook unit segment outlet works. unit 1 stops working. @iboutlet weak var unitsegmentcontroller: uisegmentedcontrol!