Posts

Showing posts from June, 2014

python - Animation by using matplotlib + errorbar -

i'm trying make animation based on example. main problem don't know how connect animation errorbar. maybe has solved similar .. import numpy np import matplotlib.pyplot plt import matplotlib.animation animation line, = ax.plot(x, np.sin(x)) def animate(i): ax.errorbar(x, np.array(x), yerr=1, color='green') line.set_ydata(np.sin(x+i/10.0)) # update data return line, #init required blitting give clean slate. def init(): ax.errorbar(x, np.array(x), yerr=1, color='green') line.set_ydata(np.ma.array(x, mask=true)) return line, ani = animation.funcanimation(fig, animate, np.arange(1, 200), init_func=init, interval=25, blit=true) plt.show() import numpy np import matplotlib.pyplot plt import matplotlib.animation animation fig = gcf() ax = gca() x = np.linspace(0, 2*np.pi, 256) line, ( bottoms, tops), verts = ax.errorbar(x, np.sin(x), yerr=1) verts[0].remove() # remove vertical lines yerr = 1 def animate(i=0): #

c - mingw, collect2.exe: error: ld returned 1 exit status error -

first of want make clear started studying "c language" @ uni. i'm @ beginning might not able understand guys using specific words , such. why found of other topics regarding same problem kinda useless: couldn't understand much. anyway, here go. installed today in pc mingw, latest version; followed every single note found in download page. installed eclipse (these 2 softwares suggested our teacher). problem is: whenever try compile little program such as /* * esercitazione.c * * created on: 08/apr/2013 * author: fra */ #include<stdio.h> int main(int argc, char *argv[]) { printf("hello world! \n"); return (0); } i error http://puu.sh/2wrk2 "well let's try old fashioned comand prompt then." thought. headed folder , used comand "gcc firstprogram esercitazione.c". now, problem: whenever open generated .exe file, can't see opening: mean opens , closes fast took me quite effort notice in screen there

testing - Doubts on correct BDD approach in Rails -

i doing bdd in following way: -> creating cucumber scenarios (for integrational tests) -> create needed model rspe unit tests --> cucumber scenarios. however, have heard nice test controller using unit testing (for example rspec). wondering if idea, or "too much" testing. example, famous rails tutorial , doesn't controller tests, integration tests (with rspec directly) , model unit tests (also rspec). so, advice on this? approach? this is, of course, pretty debated issue, here's important blog post detailing arguments testing controllers: http://solnic.eu/2012/02/02/yes-you-should-write-controller-tests.html

java - Turning wsdl result into a multiple line list -

in programming class have been assigned task results wsdl , seperate results list. example, children & family;children;family;friends the task seperate line @ every ";" , input information on next line, transforms line list, such as.. children & family children family friends how got doing this? i've been stuck quite awhile. this in java way say string wsdlstring input , result of method should arraylist<string> : public arraylist<string> seperateintolist(string wsdlstring){ string[] resultarray = wsdlstring.split(";"); arraylist<string> resultlist = new arraylist<string>(resultarray.size()); for(string listitem: resultarray) { resultlist.add(listitem); } return resultlist; } i wasn't quite sure, if want string linebreaks instead of list can use wsdlstring.replace(";","\n");

dart - Is there a way to disable all those symlinks to the packages directory? -

i using dart eclipse plugin following guide: http://blog.dartwatch.com/2013/01/integrating-dart-into-eclipse-and-your.html ( without maven integration ) if use pubspec.yaml file, project gets spammed these packages symlinks. ( using "package explorer" view eclipse ) control on these files created. i argue web root directory , maybe scripts directory should enough. currently, no, there no way control directories "packages" directories , don't. pub place "packages" directories in "bin", "example", "test", "tool", , "web", , subdirectory of those. those of directories package may expected have dart entrypoint. since entrypoint needs "packages" directory next able use "package:" imports, pub place 1 there. it won't place "packages" directories anywhere else. i argue web root directory , maybe scripts directory should enough. "tool" pu

ios - How do I provide content for a general browser? (using the Useragent) -

so have videos post blog - aware, it's kid pictures, , put in in child induced coma quickly. i display http live streaming version of video on ios & macs, standard mp4 file else. so, great have logic provide safari m3u8, , else mp4. thanks! as stands now, have provide 2 different players (which looks bad) <!-- begin video.js responsive wrapper --> <div style='max-width:800px;'> <div class='video-wrapper' style='padding-bottom:45.875%;'> <!-- begin video.js --> <video id="example_video_id_2142731582" class="video-js vjs-default-skin" width="800" height="367" poster="http://blog.thetroutmans.net/wp-content/uploads/2013/04/1stbikeride/poster.png" controls preload="none" data-setup="{}"> <source src="http://blog.thetroutmans.net/wp-content/uploads/2013/04/1stbikeride/1stbikeride.m3u8" type='video/mp4' /&g

c++ - Segfault when calling virtual function of derived class -

i've been having problem segfaults when call virtual function of derived class. however, these segfaults not occur if change name of function different name of virtual function in base class. here's code: //in main //initialize scene objects //camera if((camera = (camera*)malloc(sizeof(camera))) == null){ cout << "could not allocate memory camera" << endl; } //...code in middle //inside file parsing... //infile ifstream //nextstring char* if(!strcmp(nextstring,"camera")){ camera->parse(infile); //segfault here } here base class header (the .cpp instantiates variables in constructor): class worldobj{ public: worldobj(); ~worldobj(); virtual void parse(ifstream&) =0; vec3 loc; //location }; and here code inside camera class use write virtual function: void camera::parse(ifstream &infile){ //do parsing stuff } parse() declared in header file virtual void parse(ifstream&); my problem here if rename parse

vb.net - Hiding function on nested class -

public class class1 private names list(of string) private _class2 new class2 public sub addname(byval name string) names.add(name) _class2.add() end sub public readonly property addage(byval name string) class2 _class2.index = names.indexof(name) return _class2 end end property public sub clear() names.clear() _class2.clear() end sub public class class2 private _age list(of integer) protected friend index integer public property age() integer return _age(index) end set(byval value integer) _age(index) = value end set end property public sub add() _age.add(0) end sub public sub clear() _age.clear() end sub end class end class how can hide ,sub clear , sub add on class2, they'll visible on class1, like; public sub clear() names.clear() _class2.clear() '<<<<<<< end sub i want not visible on

Magento get number of items in cart by category -

i attempting number of items in users cart, each category. must appreciated. take @ magento: limit 3 products category per order ..... $quote = mage::getsingleton('checkout/session')->getquote(); foreach($quote->getallvisibleitems() $item){ $product = mage::getmodel('catalog/product')->load($item->getid()); $product_category_ids = explode(",", $product->getcategoryids()); //$product_category_ids = $product->getcategoryids(); foreach($product_category_ids $category_id){ $category_ids[$category_id]['category_id'] = $category_id; $category_ids[$category_id]['product_count'] = ($category_ids[$category_id]['product_count']) ? $category_ids[$category_id]['product_count'] + $item->getqty() : $item->getqty(); } }

Check that two users are friends together in php/mysql -

i have searched before asking, popular answer before can't project table struct users table userid | username 1|user1 2|user2 3|user3 4|user4 5|user5 6|user6 friend table requestuserid | targetuserid 1|3 1|4 1|6 3|2 3|5 2|4 2|1 now ok, problems is: if userid 1 haved relation userid 2 store in users table like: 1|2 and not store duplicate like 1|2 2|1 now need check user-x friend user-y, if 2 friend php return true, false else. possible if database stored duplicate 1|2 , 2|1, no :( how can 1 query ? you'd using or . select 1 friends (requestuserid = :id1 , targetuserid = :id2) or (requestuserid = :id2 , targetuserid = :id1) this query return empty set on failure, , 1 on success.

actionscript 3 - save flash as3 codes into a jpeg file -

how save codes jpeg? inputted report, going single-handed print screen , edit take forever. thanks in code editor can go each class file , click file > print . print file (maybe pdf). need each class file. if need them in jpg, can open pdf in photoshop, save jpg.

ios - Programatically generated UILabel origin point incorrectly to (0.0) set on first load -

i trying programatically generate 2 uilabels in application each uiimageview on storyboard. code runs , works correctly, however, on first load 2 uilabels form in (0.0) coordinate of main view, opposed uiimageview frame origin.x,origin.y. can't understand why happening. if click on different tab , return page, labels generate in correct location. why this? how can generate labels in correct location? -(void) viewwillappear:(bool)animated { //removed unneccessary code above... int = 0; (uiimageview *plantscreen in self.view.subviews) { if ([plantscreen ismemberofclass:[plant class]]) { @try { //the label hold name uilabel *plantname = [[uilabel alloc] initwithframe:cgrectmake((plantscreen.frame.origin.x), (plantscreen.frame.origin.y+ plantscreen.frame.size.height), 160, 30.0)]; plantname.numberoflines = 1; plantname.minimumscalefactor = .5;

Mongodb - Modelling a product catalog with user specific pricing -

looking @ mongodb product catalog example (for data caching lookups), how best implement pricing , qty available specific user logged in. picturing layout this: [{"_id":"skua", "details":{ "msrp": "$15", "short_desc": "my short description"} , "priceqty" : [{"custid": 1, "price":10 , "qty":25 },{"custid": 2, "price":9 , "qty":20 }] }] (but need push in updated (or add if first log in) pricing when user logs in (ex: remove custid = 1 documents , push in ). or make sense keep item information in 1 place , create separate collection holding sku, price, customer, , qty? not sure how use reference id on sql left join item collection pricing collection second approach. the item collection hold 100k+ (for quoting purposes) pricing , qty hold 2k ordered on spot. unfortunately, have mind in relational world still.

c++ - How to generate swc from swf or abc files -

how can generate swc files swf or abs been made avm2 assembly adobe alchemy compiler. this code generated swf , abc files : java -xms16m -xmx4096m -jar d:/alchemy/bin/asc.jar -as3 -strict \ -import d:/alchemy/flashlibs/global.abc \ -import d:/alchemy/flashlibs/playerglobal.abc \ -config alchemy::debugger=false \ -config alchemy::nodebugger=true -config alchemy::shell=false \ -config alchemy::noshell=true -config alchemy::loglevel=0 \ -config alchemy::vector=true -config alchemy::novector=false \ -config alchemy::setjmpabuse=false \ -swf cmodule.openttd.consprite,800,600,60 xxx.as does know how use option in code make swc. you can pass -swc instead of -swf . way, should move on alchemy flascc .

orchardcms - Orchard Upload Documents w/TinyMCE -

i know orchard contains built-in set of options tinymce uploading media, there equivalent uploading standard documents similar users can link them in editor? have tried tinymce deluxe? http://gallery.orchardproject.net/list/modules/orchard.module.tinymcedeluxe you can use of official pluggins

ruby on rails - What's the ideal way to model this with Mongoid? An issue with multiple models -

i noticing relation problem may have created. i started off photo model. admin upload photos , exist on site. in later iteration albums added codebase collection of photos organized on own page. album has_many :photos, inverse_of: :album photo belongs_to :album, inverse_of: :photo after playing above noticed photo can ever belong 1 album. has been ok. now new issue arises. i'd add photos of members of staff own model. i have special logic in photo model handle using specific upload service (filepicker). staff field :name, type: string how can make staff can have own photos? should create new model staffphoto denormalization? thinking of having photo either embedded or belong_to staff i'm not sure if makes sense belong both album , staff member. thing making sense me right creating separate model , abstracting upload service logic module , including both. wrong. important part photo's overall exist on own, or part of album, or part staff member (mor

python - How can you split a list every x elements and add those x amount of elements to an new list? -

i have list of multiple integers , strings ['-200', ' 0', ' 200', ' 400', ' green', '0', '0', '200', '400', ' yellow', '200', '0', '200', '400', ' red'] i'm having difficulty separating list every 5 elements , creating new list 5 elements inside. however, don't want 3 different lists, want 1 changes everytime new 5 elements goes through. you want like: composite_list = [my_list[x:x+5] x in range(0, len(my_list),5)] print (composite_list) output: [['-200', ' 0', ' 200', ' 400', ' green'], ['0', '0', '200', '400', ' yellow'], ['200', '0', '200', '400', ' red']] what mean "new" 5 elements? if want append list can do: composite_list.append(['200', '200', '200', '400', 'bluel

ruby - Rake migrate Error - database doesn't exist -

i have padrino project uses data mapper , postgres. when run padrino rake dm:create says database created. however, when run padrino rake dm:auto:migrate, error - fatal: database "dbname_development" not exist. i'm working in new environment tried project have uses active record , had no problem. i'm using postgres app on osx , rbenv. although, did try rvm instead of rbenv since other computer uses rvm (the project works fine on computer) - same result. tried connecting created database induction , got same error. if go psql though , list of databases, database shows up. i'm sort of stumped since activerecord works , there no issues when run project on computer. has seen before? thanks!

foreign keys - SQL ALTER TABLE SET (LOCK_ESCALATION = TABLE) on production server -

i need create new table have foreign key users table. users table has 2 millions of records. when run script on our test server locks table , test users cannot query table during transaction. query starts like; begin transaction go alter table dbo.users set (lock_escalation = table) go commit /*create new table , foreign keys here*/ what safe way run on production without locking it? should set production server in "maintenance mode" , set live again when sql transaction complete? for creating new table , foreign keys, , new table indexes, don't need lock or set lock_escalation of referred table (in case, dbo.users). not run above transaction, new table , foreign keys creation.

Dynamics CRM 2011 - View not displaying related information -

i trying create view display data order. there 1 many relationship order payments order. payments display on order form. problem i'm having information payment not display when run query. here xml view. <?xml version="1.0"?> -<fetch distinct="false" mapping="logical" output-format="xml-platform" version="1.0"> -<entity name="salesorder"><attribute name="name"/> <attribute name="customerid"/> <attribute name="totalamount"/> <attribute name="salesorderid"/> <order descending="false" attribute="name"/> -<filter type="and"><condition attribute="totalamountlessfreight" value="0" operator="gt"/> <condition attribute="ree_orderdate" operator="this-month"/> </filter&g

ruby - Exceptions to the "Command-Query Separation" Rule? -

command-query separation "states every method should either command performs action, or query returns data caller, not both. in other words, asking question should not change answer." a = [1, 2, 3] last = a.pop here, in ruby, pop command returns item popped off array. this example of command and query within 1 method, , seems necessary so. if case, code smell have method query command? stack popping well-known exception cqs. martin fowler notes place break rule. i in case it's not code smell, in general is code smell.

arrays - How to allow for user input java -

i'm not sure how make code allows user input information, know how create arraylist database not how make once user enters information , presses 'enter' database complete...can me out? (in java) thanks start tips user input!! helpful! okay have: import java.util.arraylist; import java.util.list; import java.util.scanner; public class beststudent { private string studentname; private string studentgpa; public beststudent() { } public beststudent(string nname, string ngpa) { this.studentname = nname; this.studentgpa = ngpa; } public void setstudentname(string newstudentname) { studentname = newstudentname; } public void setstudentgpa(string newstudentgpa) { studentgpa = newstudentgpa; } public string getstudentname() { return studentname; } public string getstudentgpa() { return studentgpa; } public static void main(string[] args) { list<beststudent> students = new arraylist<beststudent>(); scanner input = new scan

ios - How to offset the title control in Titanium -

how offset title control in titanium? right trying put left: -100 property on label in title control , works when open view moves center. are there suggestions on how can achieve move over? thanks in advance! var txtsearch = titanium.ui.createtextfield({ hinttext: 'keyword search for', height: 'auto', width: 220, left: -100, font: {fontsize: 12}, enabled: true, keyboardtype:titanium.ui.keyboard_email, returnkeytype:titanium.ui.returnkey_default, borderstyle:titanium.ui.input_borderstyle_rounded, autocapitalization: titanium.ui.text_autocapitalization_none, clearbuttonmode: titanium.ui.input_buttonmode_onfocus }); win.settitlecontrol(txtsearch); var btnsearch = titanium.ui.createbutton({ title: 'search', height: 'auto', width: 'auto', font: {fontsize: 13} }); win.rightnavbutton = btnsearch; if click search button , brings me search results page , hit button textbox not

amazon s3 - Mount multiple s3fs buckets automatically with /etc/fstab -

in s3fs instruction wiki, told auto mount s3fs buckets entering following line /etc/fstab s3fs#mybucket /mnt/mybucket fuse allow_other,use_cache=/tmp,url=https://s3.amazonaws.com 0 0 this works fine 1 bucket, when try mount multiple buckets onto 1 ec2 instance having 2 lines: s3fs#mybucket /mnt/mybucket fuse allow_other,use_cache=/tmp 0 0 s3fs#mybucket2 /mnt/mybucket2 fuse allow_other,use_cache=/tmp 0 0 only second line works tried duplicating s3fs s3fs2 , to: s3fs#mybucket /mnt/mybucket fuse allow_other,use_cache=/tmp 0 0 s3fs2#mybucket2 /mnt/mybucket2 fuse allow_other,use_cache=/tmp 0 0 but still not work. second 1 gets mounted: how automatically mount multiple s3 bucket via s3fs in /etc/fstab without manually using: s3fs mybucket /mn/mybucket2-ouse_cache=/tmp you may try startup script. how got around issues having mounting s3fs @ boot time /etc/fstab. how make startup scripts varies distributions, there lot of information out there on

address of pointer to C multi-dimension array -

question code below: #include <stdio.h> int main(int argc,char *arg[]){ if (argc>2){ int m=atoi(arg[1]); int n=atoi(arg[2]); int a[m][n]; int (*p)[m][n]=&a; printf("p : %p, *p : %p, **p : %p\n",p,*p,**p); } return 0; } main env: gcc version 4.6.3 (ubuntu/linaro 4.6.3-1ubuntu5) x86-64 gcc main.c ./a.out 2 4 output: p : 0xbfea7ef0, *p : 0xbfea7ef0, **p : 0xbfea7ef0 question why p == *p == **p . think may because a array, kind of constant pointer address specific, , involves implementation detail of gcc. the observed behaviour same fixed-size arrays , variably-modified arrays: #include <stdio.h> int main(void) { enum { m = 3, n = 4 }; int a[m][n]; int (*p)[m][n] = &a; printf("p : %p, *p : %p, **p : %p\n", p, *p, **p); return(0); } on machine, produced: p : 0x7fff6c542520, *p : 0x7fff6c542520, **p : 0x7fff6c542520 of course, p pointer 2d array i

vb.net - Determining letter grade using arrays -

this form looks like: 10 text boxes down left side user enter student names. to right of each of those, column of text boxes user enter point grade. to right of each of those, column of text boxes user can not enter anything, contain grade when done calculating it. two text boxes user can not enter in, , labeled "average" , "std. dev." when user clicks "calculate" button, to: find average , standard deviation of group, , show in appropriate textboxes. using standard 90-80-70-60 sequence, figure out grade letter each student , put in appropriate textbox private sub calculatebtn_click(sender system.object, e system.eventargs) handles calculatebtn.click ' display student's letter grade dim grade(,) string = {{"a", "90"}, {"b", "80"}, {"c", "70"}, {"d", &qu

scala - Type aliasing type constraints in generics -

i have situation want use bounded generic type constraint on class can produced. problem need abstract class someabstractclass trait foo[a <: someabstractclass] trait bar[a] extends foo[a] // fails error: type arguments [a] not conform trait foo's type parameter bounds [a <: someabstractclass] // need write this, every single subclass of foo trait bar[a <: someabstractclass] extends foo[a] is there easier way promote through system without having retype bounds every time? constraints on type parameters constraints. don't propagate transitively via inheritance them to.

c++ - How to create/read/write JSon files in Qt5 -

qt5 has new json parser , want use it. problem isn't clear functions in layman's terms , how write code it. or reading wrong. i want know code on creating json file in qt5 , "encapsulates" mean. example: read json file /* test.json */ { "appdesc": { "description": "somedescription", "message": "somemessage" }, "appname": { "description": "home", "message": "welcome", "imp":["awesome","best","good"] } } void readjson() { qstring val; qfile file; file.setfilename("test.json"); file.open(qiodevice::readonly | qiodevice::text); val = file.readall(); file.close(); qwarning() << val; qjsondocument d = qjsondocument::fromjson(val.toutf8()); qjsonobject sett2 = d.object(); qjsonvalue value = sett2.v

android - Passing data with intents -

why won't work? trying pass editable string 1 activity another. cannot work. string passed through intent have pre defined? if so, how can pass editable string? @override public void onclick(view v) { // todo auto-generated method stub textout.settext(textin.gettext()); intent intent = new intent(tutorialone.this,mainactivity.class); intent.putextra("text", textin.gettext()); startactivity(intent); } public class mainactivity extends activity { textview gettext; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); gettext = (textview) findviewbyid(r.id.textview1); intent intent = getintent(); intent.getextras().getstring("text"); string s = intent.getstringextra("text"); gettext.settext(s); gettext.settextcolor(color.white); } use instead of this.

ember.js - Finding a few records by id using ember-data -

i trying load few favorite repositories travis-ci mobile trying put here what have array of repository ids this: var favoriterepos = ["668498","557554","7934","207993"]; how go loading these repos ember-data revision 12, the travis custom restadapter , travis api ? this have tried unsuccessfully far: // in repo model - https://github.com/floydpink/travis-ci-www/blob/master/js/app/models/repo.js repo.reopenclass({ favorites : function (favorites) { // favorites array of repo-ids ["451069","538603"] var faves = ember.arrayproxy.create({ isloadedbinding : 'content.isloaded', content : ember.a([]) }); favorites.foreach(function (favorite) { faves.pushobject(repo.find(favorite)); }); return faves; } }); // , in favoritescontroller this.set('content', repo.favorites(favoriterepos)); so generic question is, how go loading few different record

c# - Using absolute paths for build dependencies -

currently use source safe , start migration subversion. external sdk(> 500 mb) hold in source safe now, , way move them vss repository. we have c++ (mostly), c# (many), java (few) projects. hundreds projects. windows platform. i couple several dependency managers not satisfied: nuget - .net painful c++ ivy - not in depth, seems not acceptable c++ first question: can check else? should easy using end developer. best case - simple build within ide. currently inclined next solution: allocate used drive, s: , declare 'dev home'. then place externals here: s:\sdk\boost\1.30\... s:\sdk\boost\1.45\... s:\sdk\oracle\agile_9.0.0.0\... s:\sdk\ibm\lotus_8.0\... s:\sdk\ibm\lotus_9.0\... s:\tools\nuget\nuget.exe s:\tools\clr\gacutil.exe autobuild machine hold mastercopy of 'dev home'. every developer should copy necessary sdks autobuild machine local , create disk subst . i can't find big problems solution: branches. projects in different branc

java - Will GC run if permgen fills up? -

i have application on startup runs 2 or 3 full gc. there lot of heap space , there no need run gc(minor or full). on gc log, can see permgen getting filled , after full gc run.after this, there increase in permgen space. , once classes loaded, there no full gc more. my question if permgen gets filled up, vm run gc claim memory heap , add memory permgen? or throw outofmemory-permgen? my question if permgen gets filled up, vm run gc claim memory heap , add memory permgen? or throw outofmemory-permgen? the gc run full gc in attempt free memory in permgen space. if fails free enough space, oome thrown saying permgen full. no current or past hotspot jvms attempt increase permgen beyond prescribed limit, whether or not there normal heap space allow this. the reasons full gc needs happen before oome (permgen) are: there may have been references permgen objects in non-permgen space. running full gc checks this. (afaik) gc'ing permgen tied full gc anyway ...

c - Running two independent threads in parallel -

i have written server program 2 threads: 1. sending data client side. 2. receiving data client side now when execute them, server accepts request , thread send data created , starts sending data client since joinable, execute until completes execution , other thread not created , control remains in thread. what need apply in order make both threads run simultaneously? i think might looking pthread. here sample code wrote when learned how threads work. counter. first thread adds 1 variable each secound, , other prints out. #include<pthread.h> //for simultanius threads #include<stdio.h> #include<stdlib.h> //for _sleep function //global variables, both thread can reach thease. int = 0; int run = 1; void *fv(void) { while( run ) { _sleep(1000); a++; } } int main(){ pthread_t thread; pthread_create( &thread, 0, fv, 0 ); printf( "%d", ); while( < 60 ) { int last = a;

Saving Generic List in Windows Store Xaml App -

i trying develop xaml app windows store. during development faced problem. want save generic list of object local store each time try save list, fires exception of "type not supported". can me out on saving , restoring generic list in localstore in windows 8 app. take on article accessing app data windows runtime (windows store apps) , cannot store in app settings except windows runtime base types . tried approaches myself: a) use serialization json.net , serialize data file on suspending , restore on startup. b) use sqlite , sqlite-net use simple db in app.

Segmentation Fault in C function -

i trying develop basic shell. shell need c function parse string. new c tried develop basic function , gives me segmentation fault error. please tell me missing. #include<string.h> #include<stdio.h> void parse(char *msg); int main() { char *msg = "this message"; parse(msg); } void parse(char *msg){ char *mm; mm = msg; char *tok; tok = strtok(mm," "); while(tok == null){ tok = strtok(null," "); printf("%s \n",tok); } } error message (runtime) segmentation fault (core dumped) thanks in advance msg points string literal, , attempting modify it. in c, modifying string literals undefined behaviour (in practice, compilers place them in read-only memory). to fix, turn msg array: int main() { char msg[] = "this message"; parse(msg); } also, there couple of issues while loop: 1) condition wrong way round; 2) second strtok() call shou

c# - String was not recognized as a valid DateTime -

my code is: protected void page_load(object sender, eventargs e) { string mydate = request.querystring["period"]; if (!string.isnullorempty(mydate)) { mydate = mydate.replace("!", ":"); } datetime dt1 = convert.todatetime(mydate); datetime dt2 = datetime.now; timespan variable = dt2 - dt1; if (variable.totalminutes > 5) { response.write("download time expired now"); } else { response.redirect("default.aspx", false); } } and i'm getting error like: string not recognized valid datetime. try datetime.parseexact() method; converts specified string representation of date , time datetime equivalent using specified format , culture-specific format information. the format of string representation must match specified format exactly. datetime date = da

actionscript 3 - How to perform copy paste operation of a line drawn by mouse on Group container? -

i working on project need perform copy , paste operation.i draw line of mouse on group container.now want paste it.please provide me solution........... first, need define data structure chart(for example, define line properties start (point), end (point), width , color ) next, need create ui render line inside canvas (group container). ui responsible providing interactions such resize, change color etc. well. can render lot of line instances according properties ( start , end , width , color ) now, copy , paste easy. just duplicate selected line instance , tell ui render duplicated instance.

multithreading - Sockets Winsock async blocking Read Write simultaneously -

i have client server arch , using blocking win sockets. have read , write thread both on server , on client side. say client waiting (blocked) on read() call server write stuff to, can client write socket while blocked on read() call thread. block affect full duplex bidirectonal sockets ? understand block on read why block on write()? or in order work have use select() or poll()? thanks can client write socket while blocked on read() call thread yes, no problem @ all.

wpf - Cannot access property bound to DataGridTextColumn in another element such as Foreground -

i have simple datagrid itemsource bound observablecollection<issue> issue class object containing various properties. have handful of datagridtextcolumn items bound properties of issue object , works expected. binding="{binding path=duedate, stringformat=dd-mmm-yyyy}" header="due date" now, want set color of foreground depending upon if date has passed expect can this: foreground="{binding path=duedate, converter={staticresource datehaspastcolorconverter}}" where datehaspastcolorconverter returns 1 of 2 colors depending upon if date being past has past. my problem can access issue.duedate property in main column binding not available foreground or other property. properties available actual view model itself. how access properties of row to , why not available? it's binding member recognises issue properties , other bdinginds recognise view models properties.

mobile - iPhone not resizing my website to its viewport size (non responsive) -

am trying resolve issue website , when opened in iphone 4s failing re-size viewport. the website not responsive , expected result in mobile device have complete website re-sized viewport. below things tried no viewport meta tag set : works in android, not working in iphone. added viewport width = device-width : works in android, notworking in iphone. added vieport width=980 : works in android,not working in iphone. added viewport width=device-width,initial-scale=1.0 : works in android, not working in iphone. am missing somthing!!! thanks have tried this? <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1., user-scalable=no, target-densitydpi=device-dpi" />

ipad - ios open app after screen unlock -

i'm developing business app ios used customers in cafeteria ordering various products available. whenever ipad screen unlocked customer, custom business app should open if previous customer open different app. so open business app after every screen unlock, possible done , how? no it's no. it's default ios behavior. in jailbroken ipad you'll manage this.

javascript - How to find documents with title like "*.pdf" in alfresco lucene search -

i need restrict search documents title suffix ".pdf" in javascript right add lucene search this: ls += ' +@cm\\:title:"*\\.pdf" ' it job, returns titles like: cloud strategy - presentation (pdf) what correct solution? have tried simple: ls += ' +@cm\\:title:".pdf" '; it worked me on test example.

objective c - NSURL baseURL returns nil. Any other way to get the actual base URL -

i think don't understand concept of "baseurl". this: nslog(@"base url: %@ %@", [nsurl urlwithstring:@"http://www.google.es"], [[nsurl urlwithstring:@"http://www.google.es"] baseurl]); prints this: base url: http://www.google.es (null) and of course, in apple docs read this: return value base url of receiver. if receiver absolute url, returns nil. i'd example url: https://www.google.es/search?q=uiviewcontroller&aq=f&oq=uiviewcontroller&sourceid=chrome&ie=utf-8 this base url https://www.google.es my question simple. there cleaner way of getting actual base url without concatenating scheme , hostname? mean, what's purpose of base url then? -baseurl concept purely of nsurl/cfurl rather urls in general. if did this: [nsurl urlwithstring:@"search?q=uiviewcontroller" relativetourl:[nsurl urlwithstring:@"https://www.google.es/"]]; then baseurl https://ww

jquery - animate and resetting interval -

i bit new @ jquery , need help, searched net solution , tried edit meet requirement. wanted change background event , there slider inside content , when changing controls, background change. i've done had 2 problems: i need reset interval when clicked (now mixing up) i need animate change in background insted of changing directly (ease or fade) here code:- $(window).load(function(){ var images = ['images/background/body-bg.jpg','images/background/body-bg2.jpg']; var = 0; function changebackground() { $('html').css({ 'background': function(){ if (i >= images.length) { i=0; } return 'url(' + images[i++] + ')'; }, 'background-position':'center', 'background-attachment':'fixed',

types - MySQL char vs. int -

i'm having discussion in class datatypes char , int in mysql. have phone number of 8 individual numbers. however, can't find pros , cons each of them. should use char type or int type, , why? if have fixed size can use char(8) -> 8b , mysql works faster fixed size fields, if chose int -> 4b save space , if have index on field work faster char. you can simple benchmark test speed of writes , reads using char(8) , int there no point in using variable length type varchar or varbinary if have fixed size because performance decrease

java - array not working properly -

hi im trying count frequency of 2d array . trying display frequency in way example if table : 0: 1 2 0 1: 2 0 1 2: 1 0 2 i want able count frequency : 0: 0 2 1 1: 2 0 1 2: 1 1 1 so way table should how many times 0 has appeared in first column , how many times 1 has appears in first column , on. not sure problem have . notice 1 gets 2nd iteration stops working or gives out 0 the code have far is (int col =0; col< s ; col++){ system.out.print(col+ ": "); (int row = 0; row<s; row++) { x=val[row][col]; if (table[row][col]==row) { system.out.print(x++ + " "); } //system.out.print(val[col][row]+" "); if (row+1==s) system.out.println(); } } } thanks assuming regular shaped array. make more robust want detect maximum number of columns. int[][] table = new int[][]{{1,2,0},{2,

Explain println and print statement after a loop has been executed in Java? -

what happens here, when print used, why not print line stops? for(int = 0; <=2; i++){ system.out.println(i) system.out.print("s"); } why not print s after 2 this: 0 1 2s from learnt, said buffer ever? mean? computer know print letter s beside 2 because has stopped there, why not print? actually print prints s line stops!. problem here is, println put new line first, , print starts place.

nsusernotification - NSUserNotificationCenter not showing notifications -

i'm not sure if got wrong examples find. wrote little helloworld. #import <foundation/foundation.h> #import <foundation/nsusernotification.h> int main (int argc, const char * argv[]) { nsusernotification *usernotification = [[nsusernotification alloc] init]; usernotification.title = @"some title"; usernotification.informativetext = @"some text"; [[nsusernotificationcenter defaultusernotificationcenter] delivernotification:usernotification]; return 0; } i compile with: cc -framework foundation -o app main.m it compiles , can execute won't show anything. reasons, nothing gets presented. read notifications may not displayed if application main actor. how can make show notification? set delegate , overwrite - (bool)usernotificationcenter:(nsusernotificationcenter *)center shouldpresentnotification:(nsusernotification *)notification { return yes; }

ios - Button in uiview not clickable -

pls help.. have button in subclass, when addsubview in uiview, cant clicked, idea?..thanks the button in subclass: - (void)configuredate{ changebutton=[uibutton buttonwithtype:uibuttontyperoundedrect]; changebutton.frame= cgrectmake(10, 20, 100, 30); [changebutton settitle:@"change date" forstate:uicontrolstatenormal]; [changebutton addtarget:self action:@selector(changedate) forcontrolevents:uicontroleventtouchupinside]; [self addsubview:changebutton]; } i added subclass/button in uiview: dateclass = [[dateclass alloc] init]; [dateclass configuredate]; [myview addsubview:dateclass]; [dateclass releasetable]; the button appears not clickable:( try this: [myview addsubview:dateclass]; [myview bringsubviewtofront:dateclass]; try setting bg color both dateclass , changebutton button test. - (void)configuredate{ changebutton=[uibutton buttonwithtype:uibuttontyperoundedrect]; changebutton.frame= cgrectmake(10, 20, 100, 30); [changeb

xamarin.android - (Android Xamarin) Get Resource string value instead of int -

im starting create simple android app use of xamarin using vs2012. know there type of resource strings. in resource folder, have xml file this: <?xml version="1.0" encoding="utf-8"?> <resources> <string name="recordstable">records</string> <string name="projecttable">projects</string> <string name="activitiestable">activities</string> </resources> in code, want use values of resources like: string recordtable = resource.string.recordstable; //error, data type incompatibility i know resource.string.<key> returns integer cant use code above. hoping recordtable variable have value of records . is there way can use value of resource string code's string variables? try using resources.getstring getting string string resources context context = this; // resources object our context android.content.res.resources res = context.resources; // str

security - Is it Safe editing the CronTab with PHP? -

i'm building script this tuts append , remove cronjob admin part of website made php. is safe implement on server ? issues ? thanks maybe that: list of script in crontab (f.e.): #script1 #script2 #script3 i'm removing script crontab: crontab -l | grep -v "#script1" > crontab.txt && crontab crontab.txt list of script in crontab after edit: #script2 #script3 command crontab -l | grep -v "#script1" > crontab.txt && crontab crontab.txt can run exec() function. i hope helped.

c# - How to draw in WPF by pixel -

necessary draw pixels array data (large). how can that? i tried canvas , rectangle on - computer hanged himself ... tried following options below (drawingcontext) - computer still hangs himself, little bit less. please recommend options least load on computer. int width = 800; - size of array (large!!!) int size = 1; - desirable able make fragment not 1 several pixels protected override void onrender(system.windows.media.drawingcontext drawingcontext) { random rnd = new random(); int width = 800; int size = 1; celltype[,] types = new celltype[width, width]; (int = 0; < width; i++) { (int j = 0; j < width; j++) { int r = rnd.next(0, 100); if (r >= 70) types[j,i] = celltype.isoccupied; else types[j, i] = celltype.isempty; } } (int = 0; < width; i++)

cakePHP - Slug with array of named arguments -

i abit stuck try figure out how can use slug on url array of named arguments: the url follows: /controller/action/param:1-slug1/param:2-slug2/param:3-slug3 this gives me following named params array in request object: [named] => array ( [param] => array ( [0] => 1-slug1 [1] => 2-slug2 [2] => 3-slug3 ) ) how configure route take slug consideration? such output is: [named] => array ( [param] => array ( [0] => 1 [1] => 2 [2] => 3 ) ) thanks help. firstly, don't need [0], [1] stuff, naming parameters same, automatically create array. change url /controller/action/param:1-slug1/param:2-slug2 your route following, router::connect('/:controller/:action/*

Read a file as binary data in JavaScript on the client side -

as question states, i'd way read files on client side using javascript (is there other possible alternative?). these files(images mostly) part of webpage, , not need access filesystem. so question should reduce to, possible open file in binary mode in javascript , read byte byte? there seems confusion i'm trying achieve. question how load binary image data using javascript , xmlhttprequest? deals case when user able make own requests server , set own mime-types etc. i wish create js function/script reads loaded files on web-page binary, purposes of meta-data extraction.

iOS 6+ Facebook / Twitter share - pre-populate text or not -

i have been getting ios 6 , share functionality. see people (e.g. apple in app store), pre-populate facebook share pop-up relevant text, while others leave empty users fill (providing image/url). i see benefits former (since can save users time) e.g. posting: "loving new app". equally, if section left blank users more create personalised message. does know best practise? ok looks itunes app store pre-populate these fields app name , developer name. however had pointed out me colleague @ work: relevant part of facebook's platform policy section iv. 2 here: https://developers.facebook.com/policy/#integration guess jury still out?

c# - How to save only a specific item using Entity Framework? -

i'm using ef4 in web application. currently, when want save specific item, change properties, , call savechanges() . but changes in application committed. how can commit changes of specific item? create new context , attach specific item new context. call savechanges() of new context.

java - Perfect number method -

this program supposed take user input , determine whether or not perfect number. when try compile it, error method testperfect in class scalvert_perfect cannot applied given types; testperfect(num); required :int, int found: int reason: actual , formal argument list differ in length my code: import java.util.scanner; public class scalvert_perfect { public static void main ( string args[] ) { scanner input = new scanner(system.in); int test; int num = 0; int counter = 0; { system.out.print("how many numbers test? "); test = input.nextint(); }while(test < 1); { system.out.print("please enter possible perfect number: "); num = input.nextint(); testperfect(num); printfactors(num); counter++; }while(counter < test); } public static boolean testperfect(int num, int test) { int sum = 0; for(int = 0; < test ; i++)

haskell - How to use ByteStrings with QuickTest in DocTest? -

how define arbitrary instance (as stated here ) when using doctest , quickcheck? doctest , cabal set described here separate directory tests. the doctest line looks this: -- prop> (\s -> (decode . encode $ s == s)) :: bytestring -> bool decode :: bytestring -> bytestring encode :: bytestring -> bytestring where , how define arbitrary instance, doctest can find it? note want define in test project. try -- $setup -- >>> import control.applicative -- >>> import qualified data.bytestring bytestring -- >>> import test.quickcheck -- >>> instance arbitrary bytestring arbitrary = bytestring.pack <$> arbitrary -- >>> instance coarbitrary bytestring coarbitrary = coarbitrary . bytestring.unpack -- | -- prop> \ s -> (decode . encode) s == s decode:: bytestring -> bytestring encode :: bytestring -> bytestring named chunks can used such definitions. however, each complete definition must on 1

How to give confirmation box before deleting multiple rows in php -

i want give confirmation message before deleting multiple rows. below code. please suggest me how give confirmation message before deleting records. $sql="select * employee"; $result=mysql_query($sql); $count=mysql_num_rows($result); ?> <?php while($rows=mysql_fetch_array($result)){ ?> <tr> <td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td> <td><? echo $rows['id']; ?></td> <td><? echo $rows['name']; ?></td> </tr> <?php } ?> <tr> <td><input name="delete" type="submit" id="delete" value="delete"></td> </tr> <?php if($delete){ for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $sql = "delete empl

jquery - How do i check for a specific value in a field using javascript? -

the javascript checks form values not being empty if(!$('nradulti').value){ok=2;} if(!$('transport').value){ok=2;} if(!$('plata').value){ok=2;} if(ok==1){return true;} else if(ok==2){ $('mesaj').innerhtml=" <span class='notarea'>please complete fields.</span>"; return false; } i need add new variable called spam captcha , check equal number, e.g. "what's 2+2" , script proceed if number 4 what line need add please? thanks! you can accomplish basic equality check. i'm not sure framework using, given other calls. if(!$('spam').value == '4'){ ok=2; }

python - File names have a `hidden' m character prepended -

i have simple python script produces data in neutron star mode. use automate file names don't later forget inputs. script succesfully saves file some_parameters.txt but when list files in terminal see msome_parameters.txt the file name without "m" still valid , trying call file m returns $ ls m* no such file or directory so think "m" has special meaning of numerous google searches not yields answers. while can carry on without worrying, know cause. here how create file in python # chi,epsi etc floats. make string file name file_name = "chi_%s_epsi_%s_epsa_%s_omega0_%s_eta_%s.txt" % (chi,epsi,epsa,omega0,eta) # a.out compiled c file outputs data os.system("./a.out > %s" % (file_name) ) any advise appreciated, can find answer posted in stackoverflow time i'm confused. you have file special characters in name confusing terminal output. happens if ls -l or (if possible) use graphical file manager - basicall

choose selected option with knockout.js -

i have combobox looks this: <selectdata-bind="options: adaptposs, optionstext: 'description', click: function(data,event) {$parent.taskchanged(data,event)}"> </select> now want track element chosen (to speak in c# "selectedindexchanged") how function called in knockout? you should use value binding: <select data-bind="options: adaptposs, optionstext: 'description', value: selectedindexchanged, click: function(data,event) {$parent.taskchanged(data,event)}"> </select> read documentation @ knockout site: http://knockoutjs.com/documentation/options-binding.html also don't need have such complex click handler, knockout automatically sends data , event objects function write following code: <select data-bind="options: adaptposs, optionstext: 'description', value: selectedindexchanged, click: $parent.taskchanged"> </select>

c# - Jquery webservice foreach loop -

i'm trying jquery dropdownlist result set of webservice, getyears function returning list of years 2013,2012,2011.... in l ist<string> when bind ddlyears values coming 1,2,3,4,5,6 $.ajax({ type: "post", url: "../webservice.asmx/getyears", data:"{}", contenttype: "application/json; charset=utf-8", datatype: "json", async: true, success: function (msg) { (var myvar in msg.d) { $('#ddlyears').append("<option value='" + myvar.tostring() + "'>" + myvar.tostring() + "</option>"); } }, error: function (jqerr) { errorcaller(jqerr); } }); try this: success: function (msg) { $.each(msg.d, function (k, value) { $('#ddlyears').append("<option value='" + value + "'>" + value + "</option>")

c# - WPF Graph change when calendar date changes -

i have made wpf graph pulls data database. need data automatically change on date change. here code: xaml code: <dvc:chart name="calllogs" background="steelblue" margin="136,0,0,0" title="calls per hour" borderbrush="transparent"> <dvc:chart.legendstyle> <style targettype="control"> <setter property="width" value="0"/> <setter property="height" value="0"/> </style> </dvc:chart.legendstyle> <dvc:chart.axes> <dvc:linearaxis orientation="y" title="ammount of calls" showgridlines="true"/> </dvc:chart.axes> <dvc:chart.series> <dvc:columnseries title="calls per hour" independentvaluebinding=&qu

cmis - Read Alfresco custom metadata via OpenCMIS? -

i created new alfresco document, , added custom aspect (exif aspect) it. how values of metadata via opencmis/dotcmis? i tried following not show exif metadata (nor presumably custom aspect metadata): foreach(iproperty property in document.properties) { if (property.ismultivalued) { metadata.add(property.id, property.valuesasstring); } else { metadata.add(property.id, property.valueasstring); } } you cannot read aspect based properties without using extension gagravarr mentioned until alfresco supports cmis 1.1. of today there no alfresco releases either in enterprise edition or community edition supports cmis 1.1. doubt 4.2 include cmis 1.1 release after will.

c# - How to print code hexadecimal OR decimal OR binary in printer? -

i want execute commands of 1 printer epson tm-t88iii. to more specific: i want print symbol €... printer epson tm-t88iii , generic print/txt only with investigation found solutions, , credible here http://www.novopos.ch/client/epson/tm-u230/apg_div_printer.pdf on last pages and doubts are: how this? how set commands printer way of c#? choose? hexodecimal? binary? decimal? i'm confused! thank you in c# can communicate printer using (for example) serial port classes (if printer has serial interface) or standard i/o classes (for example if has parallel interface you'll address lptx: device). printer character device you'll send bytes (one character = 1 byte because printer uses 8 bit ascii). it'll interpret bytes ascii codes (according current code page) print characters. send command them have use language , because ascii characters special (everything code less 32 ) it'll interpret sequences commands. don't confuse way write command