Posts

Showing posts from February, 2012

php - Cakephp Auth Redirect out of Ajax -

so working on ajax based application. when sessions timesout, user gets redirected users/login in ajax itself... have user redirected different layout. i have tried followings, none of them work... return $this->redirect(array('ajax' => false, 'controller'=>'users','action'=>'login')); $this->auth->logoutredirect = '/'; i set $this->autorender = false; , none of works. what best way have user redirected out of ajax on session timeout? i have in appcontroller. if( $this->auth->loggedin() !== true && $this->params['action'] !== 'login'){ $this->autorender = false; return $this->redirect('/'); } what need render proper response client, not redirect ajax request. only redirecting current ajax request not stop client doing more requests. instead of redirecting it, should - ajax requests - return value client knows interpret signo

Updating data in Ms-Access via asp.net and C#, gett System.Data.OleDb.OleDbException: No value given for one or more required parameters -

i trying update data asp.net form. have gridview, when click on particular row in grid view displays data respective texboxes. want update data. tried write query showed me error. here full code of c#, using system; using system.collections; using system.configuration; using system.data; using system.linq; using system.web; using system.web.security; using system.web.ui; using system.web.ui.htmlcontrols; using system.web.ui.webcontrols; using system.web.ui.webcontrols.webparts; using system.xml.linq; using system.data.oledb; using system.data.sqlclient; public partial class company_master : system.web.ui.page { protected void page_load(object sender, eventargs e) { if (!ispostback) { lbluser.text = session["user_id"].tostring(); lbldiv.text = session["division_id"].tostring(); lblunit.text = session["unitcode"].tostring(); lblloyr.text = session["year"].tostring();

angularjs - Can't open datetime picker in angular app -

i wanted use http://www.malot.fr/bootstrap-datetimepicker/ in angular app. so in head tag included <link rel="stylesheet" type="text/css" href="{{ asset('bootstrap.min.css') }}"/> <link rel="stylesheet" type="text/css" href="{{ asset('datetimepicker.css') }}"/> and <script src="{{ asset('jquery-1.9.1.min.js') }}"></script> <script src="{{ asset('bootstrap.min.js') }}"></script> <script src="{{ asset('bootstrap-datetimepicker.min.js') }}"></script> <script> $(".form_datetime").datetimepicker({format: 'yyyy-mm-dd hh:ii'}); </script> i want apply datetimepicker this <input type="text" value="2012-06-15 14:45" readonly class="form_datetime"> however picker not triggered when click on input field , there absolutely no error in

c# - MEF doesn't discover exports in assembly loaded from byte[] -

i trying use mef application accepts plugins loaded database. when try creating new assemblycatalog , pass in dynamically created assembly, mef appears unable discover exports . assembly = assembly.load(new assemblymover().getassemblybytes("plugin1")); assemblycatalog c = new assemblycatalog(a); assemblycatalog doesn't contain parts (but should). if move exportable class current assembly run following: assemblycatalog c = new assemblycatalog(assembly.getexecutingassembly()); mef discovers part fine (which assume). the interface defined in shared assembly: public interface iplugin { string name { get; } } the assembly plugin1 has single class: [export(typeof(iplugin))] public class testplugin1 : iplugin { public string name { { return "plugin1"; } } } i thought mef used reflection discover parts, verified assembly loaded correctly , contained class testplugin1 . foreach (type t in a.gettypes()) {

c# - Strange issue with IsolatedStorage in WP7 device -

i have strange problem in windows phone 7 application. need read/write xml file in app , i'm using isolatedstorage collect data. app sends/gets data skydrive why use it. ok, here function generate exception: private void createfileintoisolatedstorage(list<record> list) { isf = isolatedstoragefile.getuserstoreforapplication(); if(list.count == 0) list = new list<record>() { new record { date = datetime.today, value = 0 }}; if (isf.fileexists(filename)) { isf.deletefile(filename); } xmlwritersettings xmlwritersettings = new xmlwritersettings(); xmlwritersettings.indent = true; using (isolatedstoragefile myisolatedstorage = isolatedstoragefile.getuserstoreforapplication()) { using (isolatedstoragefilestream stream = myisolatedstorage.openfile(filename, filemode.create)) { xmlserializer serializer = new xmlserializer(typeo

c# - Alternative of Aspect Oriented Programming -

is there alternative of using aspect oriented programming inject repetitive code. suppose have class contains many properties , if property value changed log that. class person { public string name { get{return name;} set { name = value; logpropertychanged("name"); } } public int age { get{return age;} set { age = value; logpropertychanged("age"); } } } how rid of repetitive code security checking, logging , stuff without using aspect oriented programming. you can this a) on parent class of objects protected void setproperty<t>(expression<func<t>> exp, t value) { memberexpression body = (memberexpression)exp.body; //set actual value (body.member fieldinfo).setvalue(this, value); //do logging, locking, etc. field name string fieldname = body.member.name; } b) on objects private int age; public int age { { retu

LINQ - order by results of subset -

Image
edit i'm going illustrate exact problem i'm trying solve. simplified problem explanation wasn't working. i'm writing framework requires me assign threads cpu cores based on load factor. please let's not debate point why i'm doing this. when framework boots, forms map of following hardware: level 1: processor workgroups. level 2: numa nodes. level 3: processors (sockets). level 4: cores. level 5: logical processors (only applicable smt systems). i represent complex 5-level hierarchy. users may query hardware info. user can specify nothing, desired workgroup, desired numa nodes, etc. down level 4. in case, framework filters out full data set , returns matches input, long complies hierarchy (i.e. user doesn't specify cores don't appear under specified processors). next, user specify ranges, in "give me 1 workgroup, 1 numa node, , 3 cpus", example. in case, framework should return 3 cpus lowest assignment. filter & sort

php - Use namespace alias in twig -

i have code checks entity constant in twig template: {% if logrecord.status constant('app\\dealbundle\\entity\\deal::deal_state_money_reserved') %} but embarrassing use such long class name everytime. there way make namespace alias in twig? like: {% use app\\dealbundle\\entity\\deal %} {% if logrecord.status constant('deal::deal_state_money_reserved') %} or need write full class names? you can use macro : {% macro state(name) -%} {{ constant('app\\dealbundle\\entity\\deal::deal_state_' ~ name) }} {%- endmacro %} and use way : {% if logrecord.status == _self.state('money_reserved') %} don't forget use hyphens ( - ) remove whitespaces in macro.

css - jQuery addClass to parent and it's siblings -

i trying apply class element's parent , it's siblings. far have been successful applying 2 lines of jquery makes end result apply in 2 stages looking pretty ugly. <style type="text/css"> td.rostered { opacity: 0.3; } </style> <table> <tr class="flight_search"> <td class="" style="width: 6%; text-align: left"><img id="525" class="roster" src="images/link_image.png" alt="link image"></td> <td class="" style="width: 7%">option 1</td> <td class="" style="width: 24%">london -<strong>paris</strong></td> <td class="" style="width: 25%">dep: <strong>0355</strong> arr: 0615 (02:20)</td> <td class="" style="width: 30%">boeing 767</td> <td class="" style="width: 8%&

javascript - is(':first') returns different (wrong?) results for what should be the same element. jsFiddle inside -

http://jsfiddle.net/garnwraly/sfrwu/2/ given html of only <li> <button id="bam">click</button> </li> and script $('body').on('click', 'button', function (e) { //console.log( e.currenttarget == $('button')[0] ); //true; //console.log($('li').is('li:first')); //true console.log($(e.currenttarget).parent().is('li:first')) //false console.log($('button').parent().is('li:first')); //true console.log($($('button')[0]).parent().is('li:first')); //false }); why $(e.currenttarget).parent().is('li:first') false? after step debugging through jquery code ran, turns out issue way jquery() method used within is() method. know, you can pass context method , , internally, context being used is() method (and being set differently various selectors). when $(e.currenttarget) used, context set button triggered event. while

vb.net - ASP.NET Downloading files from an SQL table -

i'm trying download file sql server table. using gridview. whenever try download file, corrupted file. i using asp.net , vb.net sql server 2012 express. any ideas why ? protected sub gridview1_selectedindexchanged(sender object, e eventargs) handles gridview1.selectedindexchanged dim contentid = convert.toint32(gridview1.selectedrow.cells(1).text) dim contentname = gridview1.selectedrow.cells(2).text dim contenttype = gridview1.selectedrow.cells(3).text lblcontentname.text = "[ " + contentname + " ]" lblcontentname.visible = true end sub protected sub gridview1_rowcommand(sender object, e gridviewcommandeventargs) dim cn new sqlconnection("data source=brian-pc\sqlexpress;initial catalog=master_db;integrated security=true;") if e.commandname = "download" dim filename string = string.empty dim id integer = convert.toint32(e.commandargument) dim cmd new sqlcommand("select

javascript - Order of requires in Asset Pipeline, Does it Matter? -

in javascript application.js file have following //= require search //= require tutorial //= require_self //= require_tree .//message is there problem me putting //= require_tree .//stock after require_self ? looks working i'm not sure of implications of putting tree after self. all doing changing order of javascript contained in application.js, if any, concatenated rest of assets. if have code in application.js required in search or tutorial , not work correctly. you can read more directive in railsguides .

Stop Android Location Service if Location Doesn't Change After a Time -

i trying code service repeatedly checks user location, shuts off if things don't occur within 3 minutes. put shut-the-service-off-logic in onlocationchanged. realized if user puts phone on table , leaves there onlocationchanged may never called, , shutoff logic never entered. there other method overridden gets called every time location requested? need manually call onlocationchanged (and idea?). create countdowntimer , set millisinfuture 3 minutes. in onfinish() of timer removelocationupdate . start timer when requestlocationupdate , cancel , start timer again in onlocationchanged.

bash - unexpected EOF while looking for matching in sorting script -

can please assist script here, fresh eyes, been working on while. so: @ end of script trying enable condition if user inputs single letter input script terminates/exits "exit" message: #!/bin/bash echo 'enter file names (wild cards ok)' read files input_source in $files ; if test -f "$input_source" ; sort $input_source | uniq -c | head -10 elif "$input_source" = [a-z] ; exit echo 'exit' fi done you have unterminated string literal: elif "$input_source = [a-z] ; # where's end? furthermore, once fix that, it's still not valid. you'll want use test , [ , or [[ , , then, = won't it. want this: elif [[ "$input_source" =~ "^[a-z]$" ]];

string - C: counting number of words (need help fixing) -

i new c programming , trying write code counting number of words in string.here code counting number of codes. #include<stdio.h> #include<string.h> void main() { int count=0,i,len; char str[100]; printf("enter sentence"); gets(str); len=strlen(str); for(i=0;i<=len;i++) { if(str[i]==' ') count++; } printf("the number of words :\t%d",count+1); } when input is: here 4 words works fine. gives output the number of words : 4 my question how handle "two consecutive spaces" between word, "space @ beginning" of input , "space @ last" of input. instead of counting spaces, count first non-space character of each word. #include<stdio.h> int main() { int count=0; char str[100]; printf("enter sentence"); gets(str); char *c

fine uploader - Enabling the past function -

reading docs mentions "also containing file list" in paste options target element http://docs.fineuploader.com/integrating/options/fineuploaderbasic.html what this? there example how implement this? have far. #pasteimage text box. using chrome 10.6 need turn on somewhere in jquery.fineuploader-3.4.1.js $(document).ready(function(){ var thumbnailuploader = new qq.fineuploader({ element: $('#thumbnail-fine-uploader')[0], request: { endpoint: '/admin/cfc/image-uploader.cfc?method=upload', params: { profileid: '<cfoutput>#profile.id#</cfoutput>', profiletype:'<cfoutput>#profile.profile_type#</cfoutput>', subdname:'<cfoutput>#decodeforhtml(profile.subdomain_name)#</cfoutput>'

c - How do I traverse a memory block in a struct with pointers? -

goal: traverse vertices memory block in heap struct. errors: expected unqualified-id before ‘(’ token when trying access vertices . also, ‘vertices’ not declared in scope . header: typedef struct heap *priorityqueue_t; typedef struct heapitem *priorityitem_t; priorityqueue_t init(int max_capacity, int source_vertex); implementation: #include "heap.h" #include <stdlib.h> #include <limits.h> struct heap { int size; priorityitem_t vertices; }; struct heapitem { int id; int distance; }; priorityqueue_t init(int max_capacity, int source_vertex) { priorityqueue_t q; q = (priorityqueue_t)malloc(sizeof(priorityqueue_t)); q->vertices = (priorityitem_t)malloc(sizeof(priorityitem_t)*max_capacity); q->size = max_capacity; int i; for(i = 0; < q->size; i++) { q->(vertices + i)->id = i; //errors on line. q->(vertices + i)->distance = int_max; } q->(vertices + source_vertex)->distance = 0;

linux - how to replace a string in an efficient way in C -

i have string generated linux uuid generation code (libc): 1b4e28ba-2fa1-11d2-883f-b9a761bde3fb i need replace of characters in string: - _ 2 f 4 x i generating 200 uuid s using loop. so every uuid need replace using custom function, function must maximum optimised so, how can attain that? i suppose you're using char[] str char *c; for(c = str; *c != '\0'; ++c){ if( *c == '-' ) *c = '_'; else if( *c == '2' ) *c = 'f'; else if( *c == '4' ) *c = 'x'; } switch version char *c; for(c = str; *c != '\0'; ++c){ switch(*c){ case '-': *c = '_'; break; case '2': *c = 'f'; break; case '4': *c = 'x'; break; } }

perl - Make sed not buffer by lines -

i'm not trying prevent sed block-buffering! looking not line-buffer. i not sure if possible @ all. basically there big difference between behavior of sed , of cat when interacting them raw pseudo-terminal: cat spit inserted characters when receives them on stdin, while sed in raw mode not. a thought experiment carried out: given simple sed command such s/abc/zzz/g , sending stream of input sed 123ab means sed at best can provide on standard output characters 123 , because does not yet know if c arrive , cause result string 123zzz , while other character have print came in (allowing "catch up", if will). in way it's obvious why cat respond immediately; can afford to. so of course that's how work in ideal world sed 's authors cared kind of use case. i suspect that not case. in reality, through not terribly exhaustive methods, see sed line buffer no matter (which allows able figure out whether print 3 z's or not), unless tell care mat

How to save the layout view as image or pdf to sd card in android? -

in application, have view customer details, want save view image or pdf sd card print view through third party application (otherwise print view directly through printer possible). i have no idea of how save view image or pdf. can 1 know please me solve problem? add permission in manifest file <uses-permission android:name="android.permission.write_external_storage" /> use code below linearlayout content = findviewbyid(r.id.rlid); content.setdrawingcacheenabled(true); bitmap bitmap = content.getdrawingcache(); file file,f; if (android.os.environment.getexternalstoragestate().equals(android.os.environment.media_mounted)) { file =new file(android.os.environment.getexternalstoragedirectory(),"ttimages_cache"); if(!file.exists()) { file.mkdirs(); } f = new file(file.getabsolutepath()+file.seperator+ "filename"+".png"); } fileoutputstr

java - Using Http client -

i new web services,but how managed create web service after reading docs. able wsdl file fallowing loaction : //?wsdl. generated wsdl contains methods(api's) , able test same soap ui. need response in browser,so decided use http client fallows:- httpclient httpclient = new defaulthttpclient(); httpget getrequest = new httpget( "http://<localhost>/<servicename>/getcustomerattributesbyid?customerid=60000"); httpresponse response = httpclient.execute(getrequest); bufferedreader rd = new bufferedreader (new inputstreamreader(response.getentity().getcontent())); string line = ""; while ((line = rd.readline()) != null) { system.out.println("o/p line:"+line); } but o/p line empty.what might reason.please me. you can try set timeout on http connection. here sample code. httpget getrequest = new httpget( "http://<localhost>/<servicename>/getcustomerattributesbyid?cus

asp.net - Using an external OAuth provider for MVC4 authentication without membership or database -

i'm working on learning mvc4 , surrounding technologies. the templates , wealth of functionality quite overwhelming, app know: a sql database not option, they're , providers charge arm , leg i'd able support facebook authentication via oauth , maybe dropbox (to allow users store documents , config etc if opt to). out of box there's lot of existing templates , code achieving using oauthwebsecurity in authconfig.cs file, , large entirely entity framework focused (which unsurprising given prevalence , commercial interests sql has within microsoft space). i know can poorman's authentication using web.config files , such, wondering if still make use of built-in oauth authentication tools, minus entity-framework , database fuss? i'd still store minimal data (access tokens , such) in xml files etc.

Is it bad to have functions return strings instead of ints? (C++) -

i'm still relatively new programming. i'm in process of working on game sdl , find myself wondering or not using bad habits. for example, have function called titlescreen(), user decides mode of game enter. i can either return value 0-3, process through if/else/else/else statement decide mode selected. or i can return string such "storymode", "freeplay", "tutorial", or "quit" , use decide mode. i second mode because eliminates initital confusion on trying figure out mode selected, have feeling in of head there problem doing way. in situation, best way return value? in case should use enum listing states achieve readability without performance hit. example: enum mode { storymode, freeplay, tutorial, quit }

How to Get only division result between two numbers without modulas in php -

$a = 100; $b = 40; $result = $a/$b; echo $result; for result shown 2.5 want 2 how remove division result in this you can give $a = 100; $b = 40; echo floor($a/$b);

How Do you combine CSS code to an HTML code? I want to Combine them? -

can please copy , paste answer final code? image mapping code image hmtl, want add css shadow it. here code: <style> { -moz-box-shadow: 15px 15px 15px #888; -webkit-box-shadow: 15px 15px 15px #888; box-shadow: 15px 15px 15px #888; } </style> and below html code need add css shadow code image in it: <div style="text-align:center; width:1130px; auto; auto;"> <img id="image-maps_9201304191940558" src="http://images.mylot.com/userimages/images/postphotos/2080106.jpg" usemap="#image-maps_9201304191940558" border="0" width="1130" height="2808" alt="" /> <map id="_image-maps_9201304191940558" name="image-maps_9201304191940558"> <area shape="rect" coords="293,566,385,603" href="http://www..com/about" alt="about" title="about" /> <area shape="rect" coords="631,568,720,603" h

sql - What does displaying first name and last name in ascending order together means? -

here question : "list course id, course name, section, student id, , student name crn 1003. display list in ascending order of student last , first names." my question: since need display list in ascending order of student last name , first name. i'm wondering how can achieve both in 1 order clause? have written following query: select a.cid, a.cname, b.sid, b.lname,b.fname, c.section,c.crn courses a, students b, sections c, registration d a.cid = c.cid , b.sid = d.sid , c.crn = d.crn , c.crn = 1003 ; order b.lname asc; in above query, can't include b.fname along b.lname. please correct me if i'm wrong somewhere. i'm confused last line of question "display list in ascending order of student last , first names" thanks you can specify multiple columns in order by : ... order b.lname asc, b.fname asc;

php - Mysql Select value then update -

basically i'm trying turn id out of table, after value returned needs incremented 1. after 10 increments, resets 0; so want do similar can't seem working: update `gan` set `turn` = (select `turn` `gan` `gan_id`='$gan_id') + 1 i haven't figured out how check if value 10 reset 0; so need happen, in php mysql query, current turn returned gan_id pass in , increment after value has been returned. i've tried running 2 separate queries i'm running issue multiple users getting same turn. mysql_query("set autocommit = 0"); mysql_query("start transaction"); $result = mysql_query("select turn gan gan_id = $gan_id update"); $turn = mysql_fetch_array($result); $somenewval = $turn == 10 ? 0 : $turn + 1; $resupdate = mysql_query("update gan set turn = $somenewval gan_id = $gan_id"); mysql_query("set autocommit = 1"); mysql_query("commit"); no? need select update if wanna handle concurrency

objective c - Having hard time where to put CFRelease calls -

i'm having hard time put cfrelease() calls in below code. either if put cfrelease() inside 1 bracket complain missing in bracket. abmutablemultivalueref phones = abrecordcopyvalue(person, kabpersonphoneproperty); if (phones == nil || abmultivaluegetcount(phones) == 0) { cfarrayref linkedcontacts = abpersoncopyarrayofalllinkedpeople(person); phones = abmultivaluecreatemutable(kabpersonphoneproperty); (int = 0; < cfarraygetcount(linkedcontacts); i++) { abrecordref linkedcontact = cfarraygetvalueatindex(linkedcontacts, i); abmultivalueref linkedphones = abrecordcopyvalue(linkedcontact, kabpersonphoneproperty); if (linkedphones != nil && abmultivaluegetcount(linkedphones) > 0) { (int j = 0; j < abmultivaluegetcount(linkedphones); j++) { abmultivalueaddvalueandlabel(phones, abmultivaluecopyvalueatindex(linkedphones, j), null, null); } } } if (abmultivaluegetcount(

ShortCut key does not appear with an action of actionmanager in delphi -

Image
i try use actionmanager in delphi7, ok, unless need make caption of action1 included shortcut key, example: action1 ctrl+d what need when assign action item shortcut, want appear automatically within button in toolbar.

html - CSS, nth-child doesn't work? -

i building form, crazy reason, nth-child doesn't work on input fields, seems. jsfiddle illustrate problem: http://jsfiddle.net/ngulp/ . second input field shouldn't margin-right, does. why doesn't work? html: <div class="block-inner"> <h1>blah</h1> <hr /> <input type="text" placeholder="voornaam" name="firstname" id="firstname" class="left" /> <input type="text" placeholder="achternaam" name="surname" id="surname" class="left" /> </div> css: input { width: 45%; margin-right: 10%; } input:nth-child(2){ margin-right: 0; } you need use :nth-of-type(n) , otherwise counter increments each element within .block-inner 2 inputs results in 3rd , 4th position.

Having an image at the bottom of the page at all time in HTML -

i'm working on basic html webpage , i'm still learing that's reason stupid question. so have image bar want have going @ bottom of page , staying @ location if scroll on page. visable. can call footer guess should visable. hope understand mean. how do this? :) set in css this: #footer { position: fixed; bottom: 0px; /* */ left: 0px; width: 100%; height: 20px; z-index: 101; } that should trick - apply div element , put image inside or set background.

android - How to transform basic code into more efficient AQuery code -

my questions delay image loading using aquery so app : read json, contains various information, , links images(this done in procedure doinbackground asynctask). also, after reading links in procedure, read pics (see code below more info) class getmessages extends asynctask<string, void, string> { @override protected string doinbackground(string... params) { httpclient httpclient = new defaulthttpclient(); httpget httpget = new httpget(uri); // code reads json ....... bitmap picture = null; try { url newurl = new url(json.getstring("pic_url")); picture = bitmapfactory.decodestream(newurl.openconnection() .getinputstream()); }catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } // after this, put read info, , pics in list of // objects, usen in method onpostexecute populate // custom adapter ...see code below static class viewho