Posts

Showing posts from September, 2010

asp.net - LastActivityDate different than LastLoginDate in ASPNET Membership Provider -

in aspnet membership provider implementation, lastactivitydate different lastlogindate. kind of information stored in column if user not log in? thank you for new user lastlogindate , lastactivitydate equal creationdate. the lastlogindate updated when method "validateuser" called. in cases @ login. the lastactivitydate updated when method "validateuser" called when information profile requested. so in last case can happens when have example backendpage list of users including profile information see lastactivitydate same users. lastactivitydate set date , time access backendpage.

How to get the no of Days from the difference of two dates in PostgreSQL? -

select extract(day age('2013-04-06','2013-04-04'));` gives me no of days ! i.e.: 2 days but failed when have differnt month: select extract(day age('2013-05-02','2013-04-01')); so need no of days 32 days subtraction seems more intuitive. select '2013-05-02'::date - '2013-04-01'::date run query see why result 31 instead of 32 with dates ( select generate_series('2013-04-01'::date, '2013-05-02'::date, '1 day')::date end_date, '2013-04-01'::date start_date ) select end_date, start_date, end_date - start_date difference dates order end_date the difference between today , today 0 days. whether matters application-dependent. can add 1 if need to.

pointers - C++ : Polymorphism and operator overloading -

i having troubles figuring out how overload comparison operators have done when using abstract base class. main problem achieve polymorphism using base class, since it's abstract can't instantiated forced use pointer base class in order access derived class methods. i'll put code in order describe situation better : template <typename _tp> class base { private: _tp attr ; public: foo() = 0 ; friend bool operator == ( base* b1, base* b2) { return ( b1.attr == b2.attr ) ; } }; template <typename _tp> class derived_1 : public base<_tp> { /.../ } ; template <typename _tp> class derived_2 : public base<_tp> { /.../ } ; int main (void) { vector<base*<int> > * v = new vector<base*<int> > (2,0) ; v[0] = new derived_1 () ; v[1] = new derived_2 () ; if ( (*v)[0] == (*v)[1] ) { /.../ } return 0 ; } so, @ point notice (*v)[0] == (*v)[1]

javascript - jquery onclick function not doing what it should -

i have following jquery, on clicking #block4, .maincontent shows. works fine @ first, show , hide div. once clcik again after initial first 2 times, .maincontent div shows , disappears straight away. $('#block4').click(function(){ $(".maincontent").delay(500).fadein(); $("#block4").click(hideit) }); function hideit() { $(".maincontent").fadeout(); }; anyone know problem is? you shouldn't this. better set class or flag might need : $('#block4').click(function(){ var $cont=$(".maincontent"); if(!$cont.hasclass('visible')) $cont.addclass('visible').delay(500).fadein(); else $cont.removeclass('visible').fadeout(); }); as solution try disabling previous event : $("#block4").off('click').click(hideit); or better use .one although prefer class solution : $('#block4').one('click',function(){ $(".maincontent

c# - Reading numbers from a text file to an array -

i want read numbers text file array. numbers in 1 line. if use x.read() ascii code of first character, if use x.readline() , row, not numbers 1 one. i want use cycle numbers 1 one. it's simple, when ascii code can convert digit want, suppose read character ( char ) file '0', '1', '2', ... or '9' , want int value, simple convert char int , subtract integer value of '0' 48. this: char ch = x.read(); int chintvalue = ((int)ch) - 48; but modern programming languages have readint , getinteger method or in io libraries provide.

php - In TCPDF how to tell if my table will be bigger than the page becouse in this case I would have to add a custom header for it -

in tcpdf how tell if table bigger page because in case have add custom header it. if use: $pdf->getaliasnumpage() compare before start table , @ beginning of each row don't seem work. $pdf->getaliasnumpage() if used second time return like: {:pnp:} hope can me this. code looks this: <? $table=""; $islasttable = 0; ($i = 0; $i<sizeof($ar); $i++) { ($j = 0; $j<3; $j++) { if (isset ($ar[$i][$j])) { if($j==0) { if ($islasttable == 1) { $table .= '</table><table border="1" style="text-align:center; vertical-align:middle; padding:5;border-bottopm:1px solid black;">'; $islasttable = 0; } else { $table .= '<table border="1" style="text-align:center; vertical-align:middle; padding:5;">';

javascript - Merge two objects and overwrite the values if conflict -

i'm trying merge 2 objects , overwrite values in process. is possible underscore following? (i'm fine not using underscore want simple) var obj1 = { "hello":"xxx" "win":"xxx" }; var obj2 = { "hello":"zzz" }; var obj3 = merge(obj1, obj2); /* { "hello":"zzz", "win":"xxx" } */ use extend : var obj3 = _.extend({}, obj1, obj2); the first argument modified, if don't want modify obj1 or obj2 pass in {} .

php - Start using Migrations mid way through a Laravel app -

in midst of developing laravel 4 app, i've decided start making use of laravel's migration feature. question: should write migrations creating tables have in database? or write migrations future changes? there no complete right answer this. depends on lot of variables, style of development, how many people you're working , in kind of environment (single production db? multiple dev dbs?), requirements migrations are, etc. etc. if do decide write migrations entire db until point, you'll need make sure migrations can handle potential conflicts. making use of schema::has() , such verify tables exist prior attempting create them, , such. alternatively, can write migrations if db has clean slate, , enforce devs start empty db prior running migrations. has risks, careful. make sure have backups in case migration forgot , need modify it. so, tl;dr: using migrations entire structure part way through project bad thing? no. right application? entirely depen

C# Writing SQL queries -

i'm trying write custom query , keep getting sqlexception unhandled `error' - incorrect syntax near '.' code: var list = dbcontext.database.sqlquery<string>("select a.assetid, a.assetname, a.seg1_code, d.shortname, e.officepercentage, e.maintenancepercentage" + "from [core].[dbo].[asset] a" + "left outer join [core].[dbo].[assetaddress] b" + "on a.assetid = b.assetid" + "left outer join [core].[dbo].[address] c" + "on b.addressid = c.addressid" + "left outer join [core].[dbo].[statelookup] d" + "on c.stateid = d.stateid" + "inner join [core].[dbo].[assetpayrollmarkupoverride] e" + "on a.assetid = e.assetid" + "order d.shortname, a.assetname").tolist(); add space before/after each of string in concatenation. var list = dbco

objective c - iOS and JSON nesting issue -

i working on app game server company , part of app requires user see list of or game servers , whether or not online, offline, how many players on them, server name, etc. data found in json file hosted on web updated mysql database. using code below, can't seem working. now, please understand 1 of first times working json , have no choice client requested. talked partner couldn't seem debug issue himself. the error like: no visible @interface 'nsarray' declares selector 'objectforkey:' i've tried several versions of code, no success. it appreciated if please me debug code , working along commented out section near bottom updating tableviewcells server name, players online, , status (0=offline, 1=online, 2=busy, 3=suspended, -1=unable start). please note format of json file must remain , possible make minor changes. thank you, michael s. my header file: http://pastebin.com/ekuwvsmy my main file: http://pastebin.com/09ju0udu m

Synchronizing Google App Engine DataStore with local instance via Datanucleus REST API or some other Java API -

i'd know if can guide me in aspect, know datanucleus rest api may making contents of local google app engine datastore , online 1 same, there might way easier, i'm having great difficulties understand how might done via api. application has been done in java there's no point in trying develop phyton know, it's way late now. thanks lot interest. edit: found interesting tools here: http://www.appwrench.onpositive.com , better application if done code need executed automatically once day, if know of not hard way achieve i'm telling i'll grateful if tell me so, if not i'll stick tools. i don't know datanucleus, can connect gae datastore local machines using remote api you can use remote api access production datastore app running on local machine . can use remote api access datastore of 1 app engine app different app engine app. with this, can code app synchronize data

Java Convert 7bit Charset Octets to Readable String (From PDU SMS) -

i'm receiving sms gsm modem in pdu format; tp-user-data "c8329bfd06dddf72363904" , is: "�2����r69", while sent sms "hello world!". here java code: private string frompdutext(string pdusmstext) { string endoding = pdusmstext.substring(0, 2); pdusmstext = pdusmstext.substring(18); byte bs[] = new byte[pdusmstext.length() / 2]; for(int = 0; < pdusmstext.length(); += 2) { bs[i / 2] = (byte) integer.parseint(pdusmstext.substring(i, + 2), 16); } try { string out = new string(bs, "ascii"); } catch(unsupportedencodingexception e) { e.printstacktrace(); return ""; } { return out; } } the input packed in 7-bits per character, means every 8 bytes encode 9 characters. constructing parser format can fun exercise or frustrating experience, depending on how take it. better off using library, , quick google search reveals several code examples .

using silverstripe data object concept in wordpress -

i new wordpress, come silvestripe development. i have developed faq accordion has tittle , description. in silverstripe create dataobject, relate desired page , output looping through records in template. <div class="accordioncontainer"> <ul> <% loop accordion %> //loop data object <li> <h2 class="accordionheader"><a href="#">$title</a></h2> <div class='accordioncontent'> <div class ="accordionblock"> $description </div> </div> </li> <% end_control %> </ul> </div> how can achieved in wordpress?? thank in advance :) although wp allows custom post types (like page types in silverstripe), looks relationships may need hand

hide - How to display only the non chosen language in the language switcher menu in a multilingual drupal 7 website? -

hi. i'm newbie in drupal development. i'm building multilingual website in french , english using drupal 7. i'm using internationalization , entity translation modules translate contents , blocks in page. i'm using theme omega, sub-theme foundation downloaded website friendlymachine added sub-theme file modify css. i'm having language switcher block working properly. my question is: code in file can modify (and how?) display in language switcher non chosen (i.e needed) language? i.e: if i'm using website in french, option "english" displayed on language switcher menu. , vice versa. (if i'm using website in english, option "french" displayed in language switcher menu). any welcomed. thank you. hide current language link (which not link text) language switcher block css . has specific class purpose.

rounding - round in Smarty shows wrong result -

in smarty 3 template have code: {$a=8.34} {$b=8.33} {$a-$b|round:2} expected result is: 0.01 but receive this: 0.0099999999999998 does know how fix this? smarty2 applied modifier result of complete expression. smarty3 on direct prepending value. so in smarty3 have use brackets: {($a-$b)|round:2} that should solve it.

visual studio 2010 - TFS File not showing in solution, TF10187 -

i have branch in tfs, after making changes checked in , merged main branch. can see folders , files on server in source control. however, of new files , changes files not available in solution. folders added shown in solution not file inside these folders. check in main branch wanted build of course because nobody wants checked-in solution breaks build. error message: error tf10187:could not open document (path) system cannot find file specified anybody have suggestion, thanks!

ios - Delegation pattern in Obj-C - Am I doing it wrong? -

so in app have following situation: backendcommunicatingclass -> (owned by) -> modelclass -> (owned by) -> homescreenviewcontroller homescreenviewcontroller delegate modelclass. modelclass delegate backendcommunicatingclass. also on when app launches first time, have this: welcomeviewcontroller -> (owned by) -> homescreenviewcontroller homescreenviewcontroller delegate welcomeviewcontroller. when user types username , password in welcomeviewcontroller, information needs way backendcommunicatingclass, , way welcomeviewcontroller display error if needed. right have implemented passing information each class in communication chain, until gets backendcommunicatingclass. result lot of duplication of protocol methods , feel i'm doing wrong. what think? well understand not clearest solution, without seing code, , purpose of program, suggest. implement key value observing (kvo) in end view controller, observing change in home view contro

Django 'ascii' codec can't encode character -

in django want use simple template tag truncate data. this have far: @register.filter(name='truncate_simple') def truncate_char_to_space(value, arg): """ truncates string after given length. """ data = str(value) if len(value) < arg: return data if data.find(' ', arg, arg+5) == -1: return data[:arg] + '...' else: return data[:arg] + data[arg:data.find(' ', arg)] + '...' but when use following error: {{ item.content|truncate_simple:5 }} error: 'ascii' codec can't encode character u'\u2013' in position 84: ordinal not in range(128) error on line starting data = str(value) why? try use unicode() convert value (instead of str()): data = unicode(value)

performance - Is there any standard for response times in desktop applications? -

a customer asks response times under second "dialog-based" applications. speaking our desktop applications getting data business server connected sql server. usually 1 second ok us, have got forms take longer (up 2 or 3 seconds). know standards (or source) specifies should response times user? i've found many different informations, web pages , not desktop applications. i read somewhere 3 seconds "magical" number. read "10 seconds rule" norman nielsen web pages. others speak "4 seconds" rule. i have arguments customer "third party" ("as know, accepted limit specified in iso norm xx") :-) thank you even if actual performance of dialogs can not improved, can @ techniques may improve perceived performance of application. lazy loading, or asynchronously loading parts of dialog after it's shown may improve experience user , not require exceptional effort you. feedback on progress, may improve user'

repository - Using Odata to get huge amount of data -

i have data source provider : public class dsprovider { public iqueryable<product> products { { return _repo.products.asqueryable(); } } } the repository in above example gets records (of products) db , applies filters, not sound right if had 50000 requests/sec website.how can limit repository return required info db without converting service tightly coupled request option i.e. opposite of try achieve using odata? so summarize know if possible query db on odata options supplied user request not have products , apply filters of odata. i found out after doing small poc entity framework takes care of building dynamic query based on request.

c# - Is it better to use this. before code? -

i need go online , find tutorial something. finding people put code this: this.button1.text = "random text"; then find code this: button1.text = "random text"; is better use this.whatever or not matter? this make clear, in cases have use this : differentiate between parameter , local member : //local member object item; private void somemethod(object item){ this.item = item;//must use } pass current class instance method: public class someclass { private void somemethod(someclass obj){ //.... } private void anothermethod(){ somemethod(this);//pass current instance somemethod //..... } } use in extension methods: public static class someclassextension { public static void someclassmethod(this someclass obj){ //use obj reference object calling method... } } call constructor constructor (with different signature): public form1(string s) : this() {//call form1() before executing other code in

javascript - Trying to prevent jQueryMobile swipe gesture from bubbling, but it's not working -

i'm using jquery mobile , created resembles android holo tabs: http://note.io/18rnmrk in order swipe gesture work switching between tabs, code i've added: $("#mypage #pagetabs").on('swipeleft swiperight', function(e){ e.stoppropagation(); e.preventdefault(); }); $("#mypage").on('swipeleft', function(){ ui.activities.swipe(1); }).on('swiperight', function(){ ui.activities.swipe(-1); }); with tabs' html resembling: <div id="pagetabs"> <div class="tab"> <a href="#" data-dayofmonth="26">thu</a> </div> <div class="tab"> <a href="#" data-dayofmonth="27">fri</a> </div> <div class="tab"> <a href="#" data-dayofmonth="28" data-meridian="am">sat am</a> </div> <div class=&qu

Is storing XML with a standard structure in SQL Server a bad use of the XML datatype? -

we have table in our database stores xml in 1 of columns. xml in exact same format out of set of 3 different xml formats received via web service responses. need information in table (and inside of xml field) frequently. poor use of xml datatype? my suggestion create seperate tables each different xml structure talking 3 growth rate of maybe 1 new table year. i suppose matter of preference, here reasons prefer not store data in xml field: writing queries against xml in tsql slow. might not bad small amount of data, you'll notice decent amount of data. sometimes there special logic needed work xml blob. if store xml directly in sql, find duplicating logic over. i've seen before @ job guy wrote xml field long gone , left wondering how work it. elements there, not, etc. similar (2), in opinion breaks purity of database. in same way lot of people advise against storing html in field, advise against storing raw xml. but despite these 3 points ... can work , t

ios - coredata sqlite location, Library/Application Support and iCloud -

we got rejected during review process following issues: ========== 2.23 we still found app not follow ios data storage guidelines, required per app store review guidelines. in particular, found on launch and/or content download, app stores non user-generated content in icloud backup directories, not appropriate. check how data app storing: install , launch app go settings > icloud > storage & backup > manage storage if necessary, tap "show apps" check app's storage the ios data storage guidelines indicate content user creates using app, e.g., documents, new files, edits, etc., should backed icloud. temporary files used app should stored in /tmp directory; please remember delete files stored in location when user exits app. data can recreated must persist proper functioning of app - or because customers expect available offline use - should marked "do not up" attribute. n

Changing an object property in C# for multiple versions of .NET -

i have c# project used part of visual studio extension. to support earlier versions of vs, project set target framework .net framework 3.5. the project makes reference system.servicemodel . depending on version of visual studio running, different version of system.servicemodel used. vs2008 use .net 3.5 version dll, while vs2012 use .net 4.5 version @ runtime, regardless of project target framework. my problem property added httptransportbindingelement in .net 4, called decompressionenabled . because target .net 3.5, cannot compile changes property; however, need change value. the work around using change property @ run time, use reflection: public static void disabledecompression(this httptransportbindingelement bindingelement) { var prop = bindingelement.gettype() .getproperty("decompressionenabled", bindingflags.public | bindingflags.instance); if (null != prop && prop.canwrite) {

jQuery UI Slider within google maps InfoBubble -

i'm building custom infobubble holding 2 jquery ui sliders manipulate data. had no problems creating bubble , slider. unfortunately, somewhere mouse event seems prevented bubbling slider. i prepared fiddle explain behaviour: jsfiddle to reproduce error, following: 1. click on slider knob 2. move mouse outside of infobubble 3. move mouse left , right use slider 4. move mouse info window , see slider movement cease immediately. does know event gets lost , how fix situation? ok, invested quite bit of time find solution this. got working now! the problem lies within infobubble code. events being prevented bubbling map, apparently prevent ghostclicks through bubble. unfortunately prevents other listeners working properly. code snippet handling events found on line 808: /** * add events stop propagation * @private */ infobubble.prototype.addevents_ = function() { // want cancel events not go map var events = ['mousedown', 'mousemove', '

Rails 4 model subfolder -

i'm created model in app/models/request/book folder book::request::status.table_name returns table name "statuses" ("book_request_statuses" - right table name). how can correct table name? model location model/ book/ request/ status.rb model/book/request/status.rb class book::request::status < activerecord::base ... end config/application.rb config.autoload_paths += dir[rails.root.join('app', 'models', '**', '*.rb')] if set self.table_name = "book_request_statuses" model work correctly (in model), it's not way :). sorry english not good 1) create module in app/models/book.rb these lines. module book def self.table_name_prefix 'book_' end end 2) create module in app/models/book/request.rb module request def self.table_name_prefix 'request_' end end 3) put status model inside app/models/book/request/ directory. 4) keep other files in

asp.net - Typing comment notes within the GridView -

to comment out note in code behind, can this: ' vb comment /// c# comment in .aspx page, can use following: <!-- i'm commenting on .aspx page --> as long not within <asp:gridview></asp:gridview> this gives me error stating literal content not allowed: <asp:boundfield datafield="max_scheduled_pick" headertext="max_scheduled_pick" sortexpression="max_scheduled_pick" dataformatstring="{0:mmm dd yyyy}" headerstyle-cssclass="hidden" itemstyle-cssclass="hidden" readonly="true"/> <!-- these order notes --> <asp:boundfield datafield="txt_order_key" headertext="txt_order_key" sortexpression="txt_order_key" headerstyle-cssclass="hidden" itemstyle-cssclass="hidden" /> any suggestions on how add comments code documentation purposes? thanks, rob try using asp comments: <%-- -

solr4 - Solr Cloud Replication Benefit -

can tell me, whats benefit of having more number of replicas of shard other fault torrance? having more replicas enable distribute load among available replicas , leader improve query response time ? you right. more replicas means load distribution failover. divide data shards when single server cannot cope it, , add new replicas when existing server(s) cannot cope qps (queries per second) rate.

html - jQuery load function form in chrome -

i have users page add user button. when user clicks add user button ajax load() function called, loads adduserform when in firefox, ie works. however, when in chrome jquery dialog loads without errors form tag not load. jsfiddle front <form id="adduser"> <select id="ptsiid" name="ptsiid" onchange="secondarysitedisplay();"> <option value=""></option> <option value="1666">london</option> <option value="1544">nyc</option> </select>first name: <input type="text" name="firstname" value="" size="15" maxlength="60">last name: <input type="text" name="lastname" value="" size="15" maxlength="60">job title: <input type="text" name="jobtitle" value="" size="20" maxlen

python - Extract Quarterly Data from Multi Quarter Periods -

public companies in make quarterly filings (10-q) , yearly filings (10-k). in cases file 3 10qs per year , 1 10k. in cases, quarterly filings (10qs) contain quarterly data. example, "revenue 3 months ending march 31, 2005." the yearly filings have year end sums. example: "revenue twelve months ending december 31, 2005." in order value q4 of 2005, need take yearly data , subtract values each of quarters (q1-q3). in cases, each of quarterly data expressed year date. example, first quarterly filing "revenue 3 months ending march 31, 2005." second "revenue 6 months ending june 30, 2005." third "revenue 9 months ending september 30, 2005." yearly above, "revenue twelve months ending december 31, 2005." represents generalization of above issues in desire extract quarterly data can accomplished repeated subtraction of previous period data. my question best way in pandas accomplish quarterly data extraction? there larg

echo javascript result in php/html source code? -

this might bit difficult explain try best explain it. i have page display results javascript. (time (hh/mm/ss) exact). what need display results of javascript shown on page in source coude of page when viewed browser firefox right click, view source files! i thinking echoing results seem wrong idea echoing show results on page , not on source code of page! any appreciated. edit: okay, if impossible show results of javascript in page source how site displays result of current time etc in page source , viewable page source. i.e. wednesday, july 31, 2013 etc etc can viewed on page , on page source!! http://www.timeanddate.com/worldclock/city.html?n=136 i using google chrome view page source. you can't alter source code comes server means of javascript. while javascript can manipulate dom objects, text see when click "view source" came server, , there no way change that. to view changes done scripts, use firebug or similar tool.

python - How to use .join in this process -

hi creating worker generator class, getting hangs on terminate know need use .join close them can't figure out how pass process name terminate function. thought somehow save global variable, thinking dictionary. when time have workers terminated have terminate access function variable , terminate applicable process(es) after dropping poison pill in message queue class worker_manager: = test_imports() #somevarforp #somevarforp2 def generate(control_queue, threadname, runnum): if threadname == 'one': print ("starting import_1 number %d") % runnum p = multiprocessing.process(target=i.import_1, args=(control_queue, runnum)) #somevarforp = p p.start() if threadname == 'two': print ("starting import_2 number %d") % runnum p = multiprocessing.process(target=i.import_2, args=(control_queue, runnum))

html - Correct CSS to replace img align element -

in footer of page http://www.imbued.co.uk/ getting errors on w3c compliance test, understandably, i've used align attribute inline vertically align social media icons corresponding text. correct css alternative use? if remove align attribute text , image aren't both in centre , there no centred float obviously. there's few options. best set style on elements use margin: auto; margin-left: 50%; margin-right: 50%; margin: auto; in case of 1 of images, example, this: <img style='margin-left: 50%; margin-right: 50%; margin: auto;' src=... /> of course, should put css in class , set class of want centered class. css class like: .centered { margin-left: 50%; margin-right: 50%; margin: auto; }

gis - Google Maps fitBounds into specific area -

Image
i want achieve following: "place array of markers may distributed across large range of lat, lng fitbounds method places fitbounds inside custom rectangle." the image below should clarify i'm trying achieve. have array of markers want make sure fits within small box on right hand side of page. the white box contains information pertaining markers, present, don't want markers hidden behind white box, , i'd love if define live within black box. (note black box visual reference question). you can use containslocation ensure point inside of polygon. see here . as go through each coordinate pair in array, verify location within polygon area, add map accordingly. can set attribute points "define" extent in. var latlng = new google.maps.latlng(array[n]); if (google.maps.geometry.poly.containslocation(latlng, polygon)){ marker = new google.maps.marker({ position: latlng, map: map }); marker.dataset.box

java - How can I check whether the variable have value or not? -

i new java .might it's simple question,but didn't it. i have variable, want check whether variable have value or not.for wrote following code.but every time showing false output. public class stringoperations { public static void main(string[] args){ boolean b=new boolean("t87778rue"); int = 10; system.out.println(b.equals(i)); } } you're creating boolean object representing false value, because string parameter not "true" (ignoring case). boolean b=new boolean("t87778rue"); next, check whether boolean object representing false equal 10. it's not. int = 10; system.out.println(b.equals(i)); from boolean constructor api documentation: boolean(string s) allocates boolean object representing value true if string argument not null , equal, ignoring case, string "true".

ruby on rails - Rspec validates_uniqueness_of test failing with additional validation errors -

i have 2 scoped uniqueness validations on answer model, trying test these using rspec , respective shoulda matchers. as seen in test trace below, uniqueness validations message present in errors array however, there 2 , 3 other errors present; "body can't blank (nil)", "body short (minimum 10 characters) (nil)", "user_id can't blank (nil)" . i'm not sure coming from, body , user attributes set explicitly in before block. how can correct these additional errors uniqueness test pass? answer.rb validates_uniqueness_of :correct, scope: :question_id, if: :correct?, message: "you can have 1 correct answer per question" validates_uniqueness_of :user_id, scope: :question_id, message: "only 1 answer per question per user" /* omitted brevity */ answer_spec.rb require "spec_helper" describe answer before(:each) @user1 = create(:user) @answer = create(:answer, correct: true, user_id:

sql - Suddenly DecryptByAsymKey is returning NULL Values -

hoping out there might have had same experience. i have asymmetric key use in sql server encrypt field. created key running create master key encryption password = 'notthep@ssword_just_for_demo' go create asymmetric key mykey algorithm = rsa_1024 go for months, working fine, data encrypted, , run select decryptbyasymkey(asymkey_id('mykey'),tp) tp and results (with tp being encrypted field). suddenly, no reason can discern, giving me null value. there no error, null value. the data still there, there doesn't seem way decrypt it. does have suggestions/thoughts on resolve this? copied db, , removed key, removed master key, , recreated hoping perhaps work, no joy. thanks help.

python - Import package from unit test code -

i keep source code separate test code. so, have project organized this: my_package/ module1.py module2.py tests/ units/ test_a.py test_b.py perf_tests.py how should test_a.py import my_package ? note: i've googled (including so) , not satisfied answers: i don't want use setup.py, because want run development; testing, after all i don't want use symlinks or other hacks i've tried sys.path.append('../') , sys.path.append(os.path.realpath('../')) . both result in importerror: no module named my_package . perhaps similar can done pythonpath - syntax? i want write proper import statement can find correct files first have include __init__.py file inside folder my_package in order allow python recognize folder valid module. can create empty __init__.py file 1 line pass , example. then, can in test_a.py : import os bkp = os.getcwd() os.chdir(r'..\..') import my_package os.chdir(bkp) or use other o

web services - (unsolved) What needs to be set up on Unix for a java web client? -

i created client using proxy in oracle jdeveloper call web service. jdeveloper deployed automatically , code works under windows environment. i'm required migrate code unix server. deployed project .war file , copy unix cannot executed correctly using "jar" command. could give me whole picture or high-level step-by-step instruction need set execute war on unix? i'm new area, , got suggestions installing tomcat first. what have now: 1. war file including .class, .java, web-inf, meta-inf, manifest.mf deployed jdeveloper 2. jdk 1.6.0_25 installed on unix usr/java/ 3. tomcat installed on unix, not under bin or local or usr directory(is ok?) some specific questions: 1. else need? 2. drop .war? 3. need unzip or re-compile war? 4. how can run main class in war? errors poped-up now: 1. cannot find main class 2. tried un-zip war , compile class including main, , "cannot find symbol" webservice specified classes' name. thanks whoever attempt help!

java - Spring AOP: Aspect not working on called method -

this first time aop might noob question. public class myaspect implements aspecti { public void method1() throws asyncapiexception { system.out.println("in method1. calling method 2"); method2(); } @retryoninvalidsessionid public void method2() throws asyncapiexception { system.out.println("in method2, throwing exception"); throw new asyncapiexception("method2", asyncexceptioncode.invalidsessionid); } public void login() { system.out.println("logging"); } invalidsessionhandler looks this. @aspect public class invalidsessionidhandler implements ordered { @around("@annotation(com.pkg.retryoninvalidsessionid)") public void reloginall(proceedingjoinpoint joinpoint) throws throwable { system.out.println("hijacked call: " + joinpoint.getsignature().getname() + " proceeding"); try { joinpoint.proceed(); } catch (throwable e) { if (e in

wpf - Can use a wrappanel with datatemplate for horizontal alignment of items in a listbox -

i trying horizontally align items in listbox(items checkbox items). how can use wrap panel datatemplate? <listbox name="horizontal" itemssource="{binding solution}" scrollviewer.horizontalscrollbarvisibility="disabled" > <listbox.itemtemplate > <datatemplate > <checkbox content="{binding name}" ischecked="{binding ischecked}" margin="5 5 0 0"/> </datatemplate> </listbox.itemtemplate> </listbox> i think want itemspanel property: <listbox name="horizontal" itemssource="{binding solution}" scrollviewer.horizontalscrollbarvisibility="disabled"> <listbox.itemspanel> <itemspaneltemplate> <wrappanel orientation="horizontal"/> </itemspaneltemplate> </listbox.itemspanel> <listbox.itemtemplate> <datatemplate> <checkbox co

asp.net - HttpApplication.Request value change while inside Application_AuthenticateRequest -

today got several errors our production web server indicated had null reference while calling request.currentexecutionfilepath.startswith. occurring inside our application_authenticaterequest in global.asax.cs. after reading of code, found previous line calls request.currentexecutionfilepath.startswith successfully. so, means me value of request.currentexecutionfilepath has changed 1 line next. how possible? how can prevented/fixed? does authentication scheme redirect anywhere if auth fails? if so, , if server.transfer instead of response.redirect , imagine case executionfilepath changes, though not null . @ rate, easiest test case try logging in giving incorrect password.

java - Is height along the x-axis and width along the y-axis in libgdx? -

Image
shouldn't convention in reverse? desktop app config cfg.width = 454; cfg.height = 756; //logcat shows what's expected gdx.app.log("height",integer.tostring(gdx.graphics.getheight()));.//756 gdx.app.log("width",integer.tostring(gdx.graphics.getwidth()));//454 but this: shaperenderer.line(40, 400, 700, 400); produces line: by default no. libgdx uses opengl's default origin in bottom left corner, y going , x going right. your camera messed up. looks you're running on mac. using robovm or mono? robovm support new. possible there's bug.

android - ArrayAdapter.createFromResource issue -

i trying make "select one" on spinner. saw answer regarding subject still having issues. usual way of making custom spinner is: arrayadapter<charsequence> dataadapter1 = arrayadapter.createfromresource(this, r.array.entries, android.r.layout.simple_spinner_item); dataadapter1.setdropdownviewresource(android.r.layout.simple_spinner_dropdown_item); spinner1.setadapter(dataadapter1); spinner1.setadapter( new nothingselectedspinneradapter( dataadapter1, r.layout.contact_spinner_row_nothing_selected, this)); in code have define r.array.entries in strings.xml, app populating spinner mysql , having list grad[i]=json.getstring("grad"); . how can create arrayadapter.createfromresource list instead of entries defined in strings.xml? tnx query data, put in list or array ,

c# - Use regex to match all groups including own delimiter? -

my matching token string is > token > so text between > > match. my string example: (random text) > (some token) > (some token) > (random text) so sample text impossible 1 > possible 2 > possible 3 > impossible 4 i need possible matches. the regex \>(.*)\> only matches 1 group possible 2 > possible 3 when need following matches possible 2 > possible 3 possible 2 possible 3 unless i'm misunderstanding, there doesn't seem need regex here. string input = "(random text) > (some token) > (some token) > (random text)"; list<string> splitlist = input.split('>').tolist(); //(optional) place original input string @ beginning //like regex group match have splitlist.insert(0, input);

cmd - How do you execute .exe files as administrator or give a run as admin option within a batch file in command line -

i have medical program requires multiple programs within share server installed. made batch file grab programs 1 one , install them while adding share location in windows network removes network drive. need copy clipboard method how because there no automation in pasting directory images in 1 of install programs. here have far.... keep in mind every program has run admin not admin cmd @echo off color 2 echo turn on uac turn off uac reboot press enter pause net use z: \\server01\mdcs\auto_update\_csinstaller echo osdetect install set path=\\server01\mdcs\auto_update\_csinstaller start osdetect.exe pause echo osdetect install attempt 2 set path=\\server01\mdcs\auto_update\_csinstaller start osdetect.exe pause echo copy directory press enter echo echo \\server01\oms\pwimage pause echo not restart after wsetup installs echo wsetup install set path=\\server01\oms\image\pwima

Python UDP sendto() Ignoring Exception Block and Crashing -

i have been trying basic chat application working months in python 2.7 (using geany ide), , got basic application working using udp. can connect , broadcast communications, if client connects , closes later, server crashes next time tries broadcast message of clients. issue crashes without returning error message or traceback can't tell what's happening. here code (it work on windows due getch() code in client). server: from socket import * s = socket(af_inet,sock_dgram) s.bind(("25.150.175.48",65437)) maxsize = 4096 listeners = [] while true: data, addr = s.recvfrom(maxsize) if addr not in listeners: listeners.append(addr) #print addr[1] print "new client added %s on port %i" % (addr[0],addr[1]) l in listeners: try: s.sendto(data,l) except: listeners.remove(l) client: from socket import * import select import msvcrt s = socket(af_inet,sock_dgram) s.bind(("25.150.17

android - Adding layout IDs into arrays.xml -

is possible have layout ids inside arrays.xml. tried following doesn't work: <integer-array name="layouts_list"> <item>r.layout.layout1</item> <item>r.layout.layout2</item> <item>r.layout.layout3</item> <item>r.layout.layout4</item> <item>r.layout.layout5</item> </integer-array> other alternatives ? however, can have integer array inside constants.java curious know if has done similar above. the correct syntax <integer-array name="layouts_list"> <item>@layout/layout1</item> <item>@layout/layout2</item> ... </integer-array> but i'm pretty sure won't work, since @layout/layout1 not of type integer. what would work require manual extraction this: <array name="layouts_list"> <item>@layout/layout1</item> <item>@layout/layout2</it

linux - How to allow a domain name in iptables? -

i have linux server gets time offset strange reason i set cron job run , update time using following command /usr/sbin/ntpdate pool.ntp.org the problem command not run because have firewall (iptables) i have use ip allow traffic in network: iptables -a input -p tcp -m tcp -i eth0 -s 11.11.11.11 --dport 5060 -j accept i know how using domain name in case pool.ntp.org or maybe tell me better way keep clocks in sync please advice typically, iptables setup restrict incoming tcp , udp connections initiated remote hosts server except needed. but, outgoing tcp , udp connections initiated server remote hosts allowed, , state kept replies allowed in, so: # allow tcp/udp connections out. keep state conns out allowed in. iptables -a input -p tcp -m state --state established -j accept iptables -a output -p tcp -m state --state new,established -j accept iptables -a input -p udp -m state --state established -j accept iptables -a output -p udp -m state --stat

I have Installed the Titanium studio.Ink In Windows from appcelerator website but unable to run app like Kitchen sink? -

i have tried install android sdk & updates end showing java jdk not installed have installed jdk earlier and in console part--> titanium command-line interface,cli version 3.1.1,titanium sdk version 3.1.1.ga copyright (c) 2012-2013,appcelerator,inc. rights reserved. [error] : "missing java sdk.please make sure java sdk on path what !! this method set environmental variables , plz make sure using javasdk 1.6 instead of 1.7 http://java.com/en/download/help/path.xml thanks

delphi - How to change the ListView OnDrag image? -

Image
i'm using listview viewstyle := vsreport. when drag row 1 point point takes value of column 1 of row being dragged (in case it's 1) , displays inside dark grey rectangle shown below. i've tried looking around in xe4 source code can't find background color set. i'd change background color clskyblue (or similar) don't know how it's done. how go changing default dark grey background image of drag operation? vcl's drag operations not have drag images out of box, provide mechanism providing drag image used. done constructing own "drag image list", either overriding getdragimages method of control (when internal drag object used), or constructing own "drag object" when drag started, , assemble image list in getdragimages method called vcl when drag initiated. this mechanism bit different though tlistview , ttreeview controls because underlying api controls natively support providing drag image item that's being

c - A macro that invokes itself prints itself? -

the following program looks c macro calls itself. #define q(k)int puts();int main(){puts(#k"\nq("#k")");} q(#define q(k)int puts();int main(){puts(#k"\nq("#k")");}) it compiles , runs fine . prints out. is code c? is, rely on outside of standard c work correctly? @devnull pointed out this question has similar program: #define q(k)main(){return!puts(#k"\nq("#k")");} q(#define q(k)main(){return!puts(#k"\nq("#k")");}) does program rely on outside of standard c work correctly? the first program example of implementation of quine in c. @ high level, defines macro q() creates definition of main() prints out 2 lines. first line argument itself, second line argument wrapped in call q() itself. so, following program: #define q(k)int puts();int main(){puts(#k"\nq("#k")");} q(foo) expands into: int puts();int main(){puts("foo""\nq(""foo&q