Posts

Showing posts from June, 2013

c - pthread programming, threads don't run simultaneously -

i've following code in programm: for (i = 0; < numthrs; i++) { if (0 != pthread_create(&thrs[i], null, thr_main, &args[i])) { /* handle error */ } printf("thread %d created.\n", i); if (0 != pthread_join(thrs[i], &thread_status)) { /* handle error */ } printf("joined thread %d\n", i); } but i've noticed threads don't run simultaneously, second thread starts execution after first thread has completed execution. i'm new pthread programming. can tell me what's proper way start threads simultaneously? this because pthread_join each thread after creating it, i.e. waiting thread n complete prior starting thread n+1 . instead, try: for (i = 0; < numthrs; i++) { if (0 != pthread_create(&thrs[i], null, thr_main, &args[i])) { /* handle error */ } printf("thread %d created.\n", i); } (i = 0

javascript - parseJSON working in one case and not in other -

i fetching json data server using ajay passing array json_enocode() of php, returned json valid(checked on many online json debugger). $.parsejson() of js not accepting it. parser throwing error(below) 1 set of data while works other set of data. console> syntaxerror: json.parse: unexpected character @ line 1 column 1 of json data i tried removing elements of array 1 one not working single element. here data sets: this working: [{"id":"54a3b103877c0","act_name":"abc","profile_image":"[\"551d\"]"}] while not: [{"id":"2","user_id":"53b595a","review_for_id":"54f25","review_for_type":"city", "r_title":"asfasas asd as","r_body":"a sdasda sdas dasdas das d","r_rating":"3", "other_info":"","added":"2015-03-28 15:47:20",&qu

ios - Does Apple allow us to intercept incoming gsm messages? -

Image
whether legal or not? implementing otp verification app apple concerned privacy may know. a response quoted below apple discussion forum ,also check this

c++ - Converting char to int '23' > 23 -

i have seen many post of how convert single digit int, how can convert more 1 digit number int, '23' convert 23; to convert char array integer, use atoi() . if converting strings, add .c_str() after string variable convert suitable form use. you can use stoi() , provides additional features conversion, such specifying base.

crash - Random lags and crashes on Android 5 with LibGDX -

i developing mobile game - spatium - on play store. game made via libgdx. have porblems on android 5 (lollipop): game randomly stops drawing 2-3 seconds. biggest problem "native crash @ /system/lib/libc.so" - app gets killed in time - can play minutes, other times - crashes after seconds. i testing on samsung galaxy s2 (cyanogenmod 12 - aosp 5.0.2). thought problem not using licensed firmware no - problem same on nexus 5 , htc (both android 5.0.1 , 5.0.2). here full crash logcat in debug mode: http://jpst.it/xlgy i have 2 crash reports on developer console: http://jpst.it/xlhv i saw new gc called time on s2 , put largeheap="true" in manifest nothing changed. here small log gc - http://jpst.it/xli2 i thought have compile new sdk , latest version of libgdx - last night updated sdk (via sdk manager) , updated libgdx project version nothing changed... i browsing internet fix since 5 days , didn't found anything, hope me here. thank you!

bpmn - Is it ever possible to have two boundary event on a task? -

a boundary event cancels task on, ever possible set 2 boundary events on bpmn task? i think not tool i'm using allows it. i know none-interrupting events can multiple, surely not boundary tasks... thanks see bpmn 2.0 specification, page 258 ( 288 in pdf document ): (one or more) intermediate events may attached directly boundary of activity . as spec states one or more , explicitly allows 2 boundary events attached same activity/task.

Installing Laravel 5's Homestead -

i have been trying hard learn , install laravel it's hard keep pace installation process. i'm on windows 7 , i'm on stage add vagrant box. says: vagrant box add laravel/homestead and asked provider working , chose "1" virtualbox download seemed slow stops , gets errors downloads , i've tried week trying work command. tried download file using idm , had file "virtualbox.box" don't know i'd it. , found file large handle , downloaded continuously. someone please me on how proceed on this. factually seems, have slow internet connection continually download file. there way install manually downloaded file on idm i've had? forgive me sounding dumb. it's first time working php frameworks project , have been stuck installing. please help. this might looking for how install manually downloaded .box vagrant i did not try should work.

php - Extract pdf content and convert it in word or csv -

i starter. have pdf file. want php program wherein can extract content of pdf , output in word or csv. to read pdf files, need install xpdf package, includes "pdftotext." once have xpdf/pdftotext installed, run following php statement pdf text: content = shell_exec('/usr/local/bin/pdftotext '.$filename.' -'); after getting content, download phpdocx community version, try this. <?php require_once '../../classes/createdocx.inc'; $docx = new createdocx(); $textinfo = $content; $paramstextinfo = array( 'val' => 1, 'i' => 'single', 'sz' => 8 ); $docx->addtext($textinfo, $paramstextinfo); $docx->createdocx('report.docx'); ?>

firefox addon - Is there an alternative to evalInSandbox? -

is there alternative using evalinsandbox ? the purpose running external js script in safe environment. merits of evalinsandbox (good or bad) not in question. "access 'evalinsandbox' property deprecated security or other reasons." if you're referring amo validator, see this mozilla forums thread , seems warning imprecise, it's meant highlight potential security risk if method used improperly.

How to fix error "SQL Server Agent stopped automatically"? -

i'm using sql server 2014 , having problem. in task manager , on services tab, found sqlagent$villbe_sqlserver (villbe computer name), right click , start. it started and... stopped after 1 second. then, open services.msc , , start sql server agent (villbe_sqlserver) . it's working. after 30 seconds, stopped automatically. when click start again, said that: the sql server agent (villbe_sqlserver) service on local computer started , stopped. services stop automatically if not in use other services or programs. last, right click sql server agent , choose properties , set start type automatic , reboot pc. when reboot done, sql server agent still stopped some other services: sql server browser - running - automatic (start up) sql server (sqlexpress) - cannot start within warning: **windows not start sql server (sqlexpress) on local computer....error code 17058.** can give me anyway fix problem? thank you! if running sqlexpress, sqlagent do

Android: Need an advice with "sign out"-button implementation -

i need advice. need implement "sign out"-button in app. when user presses it, should clean database , open main screen. made drop-recreate of tables in db. found if user clicks sign out while app in process of refreshing data (parsing-saving db) in thread, "sqliteexception: no such table". question is: how implement sign out ? of variants: disable "sign out"-button or not drop tables until data sync completes ? or variants ... ? i followed mvp pattern during app implementation. so, view (activity/fragment) calls presenter's (it's scoped-singletone provided dagger2) load-method , presenter calls intercator start data sync. great see patterns load data. know prefers use android services... tia for idea , you can keep flag in shared preferences "tabledcleared" . once user click on sign out, update value 0, , start clear tables. if tables clearing completed, update value 1. if clearing interrupted, value remain 0 on ne

php - Symfony2 formtype how to pass data -

i build form contains data 2 related entities , able update both entities 1 submit. far, got working form uses formtype static data (e.g. $foo = 'bar'). don't how pass data controller formtype , using in formtype... this i've got: // admincontroller.php // throws exception $em = $this->getdoctrine()->getmanager(); $article = $em->getrepository('acmeblogbundle:articles')->find($id); $form = $this->createform(new articlestype(), $article); this throws exception: expected argument of type "array or (\traversable , \arrayaccess)", "string" given so, tried doing this //this working, (of course) empty $article = new articles(); $form = $this->createform(new articlestype(), $article); by way articlestype.php class articlestype extends abstracttype { public function buildform(formbuilderinterface $builder, array $options) { $builder->add('headline', &#

Ruby on Rails : is IP port 3000 locked out for external access, on Rails 4.2? -

i run 2 versions on ror application on computer: 1 demos (stable state, ror 4.0), other 1 development (ror 4.2). both versions can accessed using http://localhost:3000 . but noticed annoying difference: demo version can accessed computer on network. dev version cannot. big trouble when dev version stabilized , becomes demo. customer wants test on own laptop, through wlan. is there "firewall" feature newly implemented ? 1 of gems ? i glad if can explain me changed behaviour ! server webrick webrick 1.3.1 both environments. here gem files: development (not accessible computer) source 'https://rubygems.org' ruby '2.2.0' gem 'rails', '~> 4.2.0' gem 'bootstrap-sass', '~> 3.3.3' gem 'sass-rails', '~> 5.0.1' gem 'coffee-rails', '~> 4.1.0' gem 'uglifier', '~> 2.7' gem 'bcrypt', '~> 3.1.10' gem 'jquery-rails', '~> 4.0.3

c# - give names to a var object in .net -

just wondering using web method return json data web form. anyway don't want entire class in json 2 of columns. used linq columns here example. ienumerable<person> model = new list<person> { new person { id = 1, name = "bryan", phone = "218-0211", email = "bryan@mail.mil" }, new person { id = 2, name = "joe", phone = "248-0241", email = "joe@mail.mil" }, new person { id = 3, name = "fred", phone = "354-0441", email = "fred@mail.mil" }, new person { id = 4, name = "mary", phone = "344-3451", email = "mary@mail.mil" }, new person { id = 5, name = "jill", phone = "127-3451", email = "jill@mail.mil" } }; var mysubset = in model select new { a. name, a.email }; unfotunately when serialize result , send lose column names. data.name do

statistics - Polynomial feature expansion in R -

i'd polynomial feature expansion data frame -- example, quadratic expansion of df (x1, x2, x3) should give df (x1, x2, x3, x1^2, x2^2, x3^2, x1x2, x1x3, x2x3). i'm using poly(df$x1, df$x2, df$x3, degree=2, raw=t) requires unnecessary amount of typing if have large number of columns. (and poly(df[,1:20], degree=2, raw=t) doesn't work.) what's best way this? edit: have many columns poly ( vector large error). got work simple for loop: polyexp = function(df){ df.polyexp = df colnames = colnames(df) (i in 1:ncol(df)){ (j in i:ncol(df)){ colnames = c(colnames, paste0(names(df)[i],'.',names(df)[j])) df.polyexp = cbind(df.polyexp, df[,i]*df[,j]) } } names(df.polyexp) = colnames return(df.polyexp) } just add additional loops compute higher-order terms. you do.call : do.call(poly, c(lapply(1:20, function(x) dat[,x]), degree=2, raw=t)) basically do.call takes first argument function called ( poly in case) , sec

java - How to reference an ${ENV} var in a propertyConfigurer bean? -

i'm trying modify this example own purposes. i want load properties server-specific file, using this: <beans:bean id="propertyconfigurer" class="org.springframework.beans.factory.config.propertyplaceholderconfigurer"> <beans:property name="locations"> <beans:list> <beans:value>${env_jdbc_config}</beans:value> </beans:list> </beans:property> </beans:bean> where env_jdbc_config enrivonment variable specifying path properties file. this fails `java.io.filenotfoundexception: not open servletcontext resource [/${env_jdbc_config}]` how can accomplish i'm trying here? use systempropertiesmode property of configurer use system properties. check this article , tells tips manage external properties. if want use env variable inside other bean definition use like <bean id="yourbean" class="com.company.yourbean">

ruby on rails - Send notification to pin owner -

i want send notification (actionmailer) owner of pin when user has voted pin. working, did not manage print name of voter in email notification. welcome! i have following in pin controller: def @pin.liked_by current_user redirect_to :back, notice: 'je hebt dit recept nu toegevoegd aan jouw bewaarde recepten.' modelmailer.new_like_notification(@pin).deliver end [edit] have following mailer: def new_like_notification(pin) @pin = pin @user = pin.user mail to: pin.user.email, subject: "#{@pin.user.name}, jouw recept #{@pin.description} wordt lekker gevonden door anderen.", bcc: "oliviervanhees@gmail.com" end [edit] , have created part in view show voter of pin: <% @pin.votes_for.voters.each |p| %> <li><%= p.name %></li> <% end %> so last part gives following error nomethoderror in pins#like define @user pin.user in mailer or refer @pin.user in view.

How to create a dynamic chart in google site with data from google spreadsheet? -

i come vietnam english not quite! please people sympathize if have written confusing! want create line chart in google site data taken google spreadsheet. if data in spreadsheet update chart in site automatically changes (like chart when insert in spreadsheet). spreadsheet response form : http://goo.gl/forms/jrjl0dcaf3 thank much! taken verbatim here in google sites help. have italicized important information automatically updating chart. to insert chart site, follow these steps: open site page you'd insert chart into. click edit page button. go insert menu, , select chart . select spreadsheet list contains chart data you'd display. - if spreadsheet contains chart, can select chart. snapshot of spreadsheet chart, , chart won't update if spreadsheet data modified. insert chart dynamically updates, open charts editor , select live option. - if spreadsheet doesn't have chart in it, enter range of data. if mark live , chart update spreadsheet d

javascript - How to Redirect a user if they manually refresh your webpage via f5 or browser? -

i have lots of buttons on webpage, when button clicked refreshs page need happen increase click counter, there way redirect user page if decide refresh after clicked button, if manually hit f5 or browser refresh redirected? otherwise happens every manual refresh click counter keeps counting? in php or javascript i've looked around , apparently impossible? in javascript can prevent f5 refreshing keydown event , event.preventdefault(), i'm pretty sure can't prevent user clicking refresh button. but both of irrelevant because hacker can send http request, increase counter. you want have php code checks user's ip , increases counter once per ip address. to read user's ip address in php, use $_server['remote_addr'] you store counter data database table, example 3 columns: table name: counters table fields: counter_id - int unsigned auto-increment(ai) ip_address - varchar(45) hit_count - int unsigned then run sql queries php, check if

java - How can i use the lwjgl in bluej? -

the lwjgl consists of 2 parts. set java part copying "lwjgl.jar" "...\bluej\lib\userlib" folder , worked. native part have point java.library.path @ 2 dlls "lwjgl.dll" , "openal32.dll" . how do that? lwjgl looks in special variable find native libs. don't know how bluej works should like: system.setproperty("org.lwjgl.librarypath", new file("pathtonatives").getabsolutepath()); more info , way set here

c# - how do i use the list functions for the linq query? -

Image
i'm making query , want search db "branchid" (pic2) in "rentsorder" (pic2) table add dot in query after rentsorders (pic1) list of collection functions , don't know how use them go on list , find barnchid equals branchid prop you can see in cartype when added dot did "year" prop try following: var query _db.cars .where ( z => z.cartype.year == year && z.cartype.gear == gear && z.rentorders .max ( x => x.actualenddate ) < startrent && z.rentorders .max ( x => x.actualenddate ) < endrent && z.cartype.manufacture.manufacturename == manufacturename && z.rentorders.where(x => x.branchid == branchid).tolist() ).tolist(); i recommend try more acquainted lambda , linq. => lambda operator allows access si

php - Laravel 4.2 Dropdown List -

i want populate select input using data stored in database. i have firstname , lastname fields clients , want display fullname (both firstname , lastname) on dropdown list. i'm using client::lists('firstname', 'id') generate list. apparently show firstname only. how combine 2 fields in above code, or there better alternative this? another related question, how set first option --please select client-- instead of getting first client straight away on top. you define accessor adding following code user model public function getusernameattribute() { return "{$this->lastname} {$this->firstname}"; } and query model way $list = user::get(['firstname','lastname','id'])->lists('username','id'); regard --please select client-- , you may array merge or plus so form::select('list',['0'=>'--please select client--'] + $list);

multithreading - Decoupling in threaded environment java -

i facing decoupling problem. let me explain example: say have different classes uses jar. jar keeps on getting updated , need update our system along too. if there slight change in jar have make changes every class, decided decouple it. these classes call jar classes in such way make object of it, set flag , on basis of derive results. hence every object has own importance in every method. let me explain simple example. say have class x class x { base base; public int getcalresult(int a, int b) { base = new base(); base.seta(a); base.setb(b); return base.getresult(); } public int getcalresult2(int a, int b, int c) { base = new base(); base.seta(a); base.setb(b); base.setc(c); return base.getresult(); } } class base { legacy class inside jar can't change int a, b, c, d; public seta(int a) { this.a = a; } public getresult() { return + b + c + d; } } how decouple sort of structure , make thread sa

html - Php division not working -

for reason when ever compile code, gives me zero. why this? $aou = 5; //amount of upvotes $aod = 2; //amount of downvotes $elo = (auo/aod) * 150; //elo echo "your elo is: " . $elo; the problem type auo , aod instead of $auo , $aod . php trying constants of names, , not variables. constants defined , used without dollar sign, e.g. const foo = 123; echo foo; but variables need $ every time use them, thus $bar = 123; echo $bar;

javascript - Load Soundcloud embedded player OnClick not working in FireFox -

website: https://www.buybeatsfast.com/beats/ clicking "play beat" image should load soundcloud player track , autoplay it. works in chrome in firefox takes soundcloud track's page. tested on windows xp , windows 8 , it's not working @ in firefox, no errors on console either have no clue problem is, i'm not author of code, found on here actually. this html: <div class="tempsc"><a href="https://soundcloud.com/rockitpro/imstillherehook" class="scload"><span class="playbeat"><span class="icon-play-sign playbeaticon"></span> play beat</span></a></div> this js: /*soundcloud click play*/ var formatplayer = '&iframe=true'; formatplayer += '&color=3498db'; formatplayer += '&buying=false'; formatplayer += '&download=false'; formatplayer += '&show_playcount=false'; formatplayer += '&sh

c# - MVC Customized Authentication filter not working as expected -

i have 4 controllers namely account , admin , home , gallery . out of 4 controllers need authorize admin controller , remaining can have access anonymous. i've decorated home controller, gallery controller , account controller [allowanonymous] attribute , i've admin controller decorated custom authorization filter named [custauthfilter] , contains following code. public class custauthfilter : authorizeattribute { protected override bool authorizecore(httpcontextbase httpcontext) { var request = httpcontext.request; string controller = request.requestcontext.routedata.values["controller"].tostring().tolower(); if (controller != "" && controller == "admin") { var isauthorized = base.authorizecore(httpcontext); if (!isauthorized) { return false; } else { if (!object.referenceequals(httpcontext.session["un&

How to serve external js file to node.js server -

can me downloaded js file socket.io browser client.and put on js folder...but having problem node.js doesn't serves me external js <script src="./js/socketio.js"></script> how serve external js file ? here app.js server code var app = require('http').createserver(handler) var io = require('socket.io')(app); var fs = require('fs'); app.listen(8080); function handler (req, res) { fs.readfile(__dirname + '/index.html', function (err, data) { if (err) { res.writehead(500); return res.end('error loading index.html'); } res.writehead(200); res.end(data); }); } io.on('connection', function (socket) { socket.emit('news', { hello: 'world' }); socket.on('my other event', function (data) { console.log(data); }); }); thank in advance.

How to Inject external css style sheet into GWT Panel widget? -

how inject css style sheet 1 of vertical panels in gwt ? i have following code mainpanelresources.java public interface mainpanelresources extends clientbundle { public interface mymainpanelresourcescss extends cssresource{ public static final mainpanelresources instance = gwt.create(mainpanelresources.class); @source("mainpanel.css") public cssresource css(); } } mainpanel.css @external .mainpanel { border: 1px solid black; } found answer in google web toolkit group, in basic css question posted mike dee https://groups.google.com/forum/#!msg/google-web-toolkit/taqng9koemk/yi9btaznamij

php - Restler won't call any API methods -

restler refusing instantiate of api classes. it's saying fails on route, doesn't bother provide other useful information. installed restler via composer via "restler/framework" : "3.0.0-rc6" , created index.php looks this: <?php require __dir__.'/../vendor/autoload.php'; use luracast\restler\restler; $r = new restler(); $r->addapiclass('explorer'); $r->addapiclass('play'); $r->handle(); in exact same directory index.php i've created file called play.php looks so: <?php public class play { public function __construct() { error_log("i called constructor!\n", 3, '/tmp/scott'); } public function index() { error_log("i called index\n", 3, '/tmp/scott'); } when call http://.../api/play never see /tmp/scott file created, , generic failure response restler: { "error": { "code": 404, "messa

c# - I working on Wp8 app.On Phone testing Always Send System.Reflection.TargetInvocationException -

i'm working on window mobile phone app .when test app on emulator it's working totally fine.but if test app on phone send me system.reflection.targetinvocationexceptipon. webclient webclient = new webclient(); webclient.downloadstringcompleted += jobseeker; //progressbarrequest.visibility = system.windows.visibility.visible; webclient.downloadstringasync(new uri(string.format("http://ec2-54-66-100-115.ap-southeast-2.compute.amazonaws.com/jjhj/abvsfss.php?func=login&username={0}&password={1}&cachebust=", txtusername.text, txtpswd.password,datetime.now)));

python - how to dynamically generate a subclass in a function? -

i'm attempting write function creates new subclass named string gets passed argument. don't know tools best this, gave shot in code below , managed make subclass named "x", instead of "mysubclass" intended. how can write function correctly? class mysuperclass: def __init__(self,attribute1): self.attribute1 = attribute1 def makenewclass(x): class x(mysuperclass): def __init__(self,attribute1,attribute2): self.attribute2 = attribute2 x = "mysubclass" makenewclass(x) myinstance = mysubclass(1,2) the safest , easiest way use type builtin function. takes optional second argument (tuple of base classes), , third argument (dict of functions). recommendation following: def makenewclass(x): def init(self,attribute1,attribute2): # make sure call base class constructor here self.attribute2 = attribute2 # make new type , return return type(x, (mysuperclass,), {'__init

c++ - Deferred Rendering Skybox OpenGL -

Image
i've implemented deferred rendering , having trouble getting skybox working. try rendering skybox @ end of rendering loop , black screen. here's rendering loop: //binds fbo gbuffer.bind(); //the shader writes info gbuffer geometrypass.bind(); gldepthmask(gl_true); glclear(gl_color_buffer_bit | gl_depth_buffer_bit); glenable(gl_depth_test); gldisable(gl_blend); //draw geometry geometrypass.setuniform("model", transform.getmodel()); geometrypass.setuniform("mvp", camera.getviewprojection() * transform.getmodel()); mesh3.draw(); geometrypass.setuniform("model", transform2.getmodel()); geometrypass.setuniform("mvp", camera.getviewprojection() * transform2.getmodel()); sphere.draw(); gldepthmask(gl_false); gldisable(gl_depth_test); glenable(gl_blend); glblendequation(gl_func_add); glblendfunc(gl_one, gl_one); glbindframebuffer(gl_framebuffer, 0);

google maps - How to calculate center of bounds without GoogleMaps? -

i have following bounds: var bounds = { southeast: {lat: 54.69726685890506, lng: -2.7379201682812226}, northeast: {lat: 55.38942944437183, lng: -1.2456105979687226} }; by using google maps api calculate canter of bounds above following: // returns (55.04334815163844, -1.9917653831249726) (new google.maps.latlngbounds(bounds.southeast, bounds.northeast)).getcenter(); how calculate center of bounds without using google.maps.latlngbounds.getcenter math? edit : need write "magic" function returns same center lat, lng google.maps.latlngbounds.getcenter : function getboundscenter(bounds) { // need calculate , return center of passed bounds; } var center = getboundscenter(bounds); // center should (55.04334815163844, -1.9917653831249726) var bounds = { southwest: {lat: 54.69726685890506, lng: -2.7379201682812226}, northeast: {lat: 55.38942944437183, lng: -1.2456105979687226} }; center lat = (southwest.lat + northeast.lat)/2 = 55.0

PHP header doesnt redirect instead stays on same page -

i have ecommerce page using stripe api. once payment successful want redirect checkoutproc.php after updating db. after clicking submit page remain on same page. when try on local host works fine doesnt work when live. header @ bottom of checkout.php file given here- <html> <head> <title>unsq</title> <link rel="stylesheet" type="text/css" href="css/styling.css"> <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script src="http://code.jquery.com/jquery-1.11.1.js"></script> </head> <body> <div class="logo" > <img src=css/images/unsquaringlogo.png height="180" width="700"> </div> <div class="container"> <h2>register</h2> <form action="" method="post" id="payment-form"> <span class=&q

model view controller - access to request querystring in mvc -

i have actionlink in view: @html.actionlink("go", "showdetails", "shownews", new { id = 2 },null); and in routeconfig: routes.maproute( name:"newmap", url: "{controller}/{action}/{id}", defaults: new { controller = "shownews", action = "showdetails", id = urlparameter.optional } ); when click on actionlink , request query string cod in controller public actionresult showdetails() { int id; if (!int.tryparse(request.querystring["id"], out id)) { id = 1; } var data = new databasecontext(); var news = data.newsinfo.where(x => x.id == id).firstordefault(); return view(news); } but request return me return 1 (i send 2 actionlink) when go address : localhost/shownews/showdetails?id=2 request.querystring pars 2 value(this true) problem?

python - How to delete existing migrations in Django 1.7 -

so i'm following tango django guide, part 7.3.2. of tutorial. after ran command python3 manage.py makemigrations rango , won't let me re-populate database using populate script. instead got error: django.db.utils.operationalerror: no such column: rango_category.slug . then, tried revert things normal deleting slug code (so before 7.3 of guide). made migration after doing so, because prior migration added slug category never deleted, can't use migrate command revert changes because throws error when tries migrate using old added category slug migration. when point newest migration, still gives me error old one. then, in effort fix things, used bunch of different migrate , makemigrations commands, including --empty, --fake, squashmigrations etc , migrations unrecognizable. is there way delete these existing migrations , start clean slate? this migrate --list looks now, reference: admin [ ] 0001_initial auth [ ] 0001_initial rango [ ] 0001_squashed_000

android - Cannot Run Tasks in Service -

i know basic question, new android service. have done research on google , stackoverflow. there many question in stackoverflow related or similar topic, couldn't able proper answer , being diverted different topics. this simple test code running. public class service extends android.app.service { private handler mhandler; private void ping() { try { log.e("tag", "success"); toast.maketext(getapplicationcontext(), "service ping", toast.length_short).show(); } catch (exception e) { log.e("error", "in onstartcommand"); e.printstacktrace(); } schedulenext(); } private void schedulenext() { mhandler.postdelayed(new runnable() { public void run() { ping(); } }, 3000); } public int onstartcommand(intent intent, int x, int y) { mhandler = new android.os.handler(); ping(); return start_sticky; } @override public ibinder onbind(intent intent) { retur

.htaccess - Remove server.php from Laravel routes -

i installed laravel following instruction on larvel docs. chose use install via composer create project command. in routes. php created dummy route route::get('/', function(){ return 'front page'; }); when access http://localhost/mysite/ shows directory listing of mysite folder. when use http://localhost/mysite/server.php runs route closure. i tried alternate .htaccess code provided @ laravel's docs doesn't work either. i want remove server.php url. thanks in advance help. this behavior expected , how laravel works. public folder meant assets , (supposed be) webservers root directory. if working on localhost not case , root directory contains multiple projects. in order rid of public have change virtual host settings. mentioned here in site . problem doing virtual hosts other projects in localhost become inaccessible.

c# - How can I prevent my web crawler from slowing down over time? -

i made web crawler in c#. starts 1 url, finds urls in url , visits other urls, , on... i add urls string array pre-defined size , dictionary can check if url has been crawled (i use dictionary's containskey() method because it's faster linear array search). it fast when starts working, on time gets painfully slow. reason dictionary's contains() method takes lot of time when dictionary big (100k+ urls, example), , means web crawler slowing down on time. what can this? have check if url has been added already, , dictionary lookup fastest way, way gets slow after dictionary gets large enough.

python - Django modelling - using the right relationships -

i want model 'model' have set (zero or more) of 'attribute's. should able access these 'attribute's. single 'attribute' has 1 'model'. 'model' has 0 or more 'objects'. should able access these 'object's. single 'object' has 1 'model'. 'object' inherit 'attribute's of it's 'model'. i'm not sure how create these models in django. here have far: class model(models.model): # class attribute(models.model): model = models.foreignkey(model) class object(models.model): model = models.foreignkey(model) update when try make 'object' object, error: column myproject_object.model_id not exist similarly, if try make 'model' object. error: null value in column "attributes_id" violates not-null constraint this relation called many-to-many relationship , django has implemented in orm. class child(models.model): # [...

php - Determine if a New MySQL record was created or instead just updated? -

i have php function below creates new project task mysql database record if 1 same id not exist already. if 1 exist same id, instead updates mysql record. this code has lot of time invested important task record's date_modified field updated in event of these 5 fields have changed new value!: - name - description - status - type - priority if of these fields have same value previous value when making update , example if sort_order value changed not update date_modified field! it works great after lots of work crafting work right. mention important not break functionality! now question because function can create , update task records in mysql. i have need know when each of these events happens. if new task record created need know new record created. if task record updated need know record had existed , updated. is there anyway determine of 2 events happened have? private function _addorupdatetaskrecord($taskid, $projectid, $created_by_us

I have put together an iOS file in ipa format using Cordova PhoneGap -

and have ipa file me, , when log onto itunes connect given 2 options xcode or application loader and neither can installed on linux mint. is there other way linux mint user upload ipa apple app store? thanks to submit apple you'll need mac. can either use xcode submit app, or download application loader , submit .ipa file way. more info can found here .

list - C++ | Queue: Dequeue function crashes program -

i attempting make queue in c++ using double linked list. have not tested since stuck @ step dequeue. attempted create temp node, , move around stuff when call delete on head node in queue (called queue), , set head temp node next element, (you can see in code) when call delete, crashes, according ms visual studios 2013. add how weird is, following stack called, after delete called, setprev called , set prev node , crashes there. never call function during of destructors deletes do. try best understand answers still new c++ terminology. below code. oh 1 last thing, in main, did call enqueue once, dequeue once, delete node class ... #ifndef tsdnode_h #define tsdnode_h template <class t> class dnode { private: dnode<t>* next; dnode<t>* prev; t data; public: dnode(t); void setnext(dnode<t>* next); void setprev(dnode<t>* prev); dnode<t>* getnext() const; dnode<t>* g

ruby on rails - Output integer as phone number format in view -

i trying show show formatted phone number like: xxx-xxx-xxxx instead of number string ..any great! <% if @post.phone.present? %> <h4>phone: <small> <%= @post.phone %><br></h4> <% end %> you can use number_to_phone helper, this: <% if @post.phone.present? %> <h4>phone: <small> <%= number_to_phone @post.phone %><br></h4> <% end %> by default, formats phone number xxx-xxx-xxxx : 2.1.1 :009 > number_to_phone(1235551234) => "123-555-1234" 2.1.1 :010 > number_to_phone("1235551234") => "123-555-1234"

java - Using the SAX characters method to parse PCDATA from an XML element -

i'm using sax api parse in xml document, struggling store element pcdata each location within xml. the oracle docs sax api show characters() used parse in pcdata element, i'm not sure on how supposed called. in current implementation, boolean flags used signal when element within xml document has been encountered. flags being triggered in startelement() should when element encountered. i set breakpoint on boolean variable description in charaters() boolean isn't set true until startelement() called, meaning pcdata never parsed. my question how can call characters() after boolean values set in startelement() ? this startelement() called after charaters() : public void startelement(string namespaceuri, string localname, string qname, attributes atts) throws saxexception { if (qname.equals("location")){ location = true; system.out.println("found location..."); try { //read i

algorithm - How do I search the leaves of a tree where each node could have more than two children? -

i'm trying search leaves of tree data structure target value. function looks this: def searchleaves(self, target): #dfs if len(self.children == 0): #is leaf if self.data == target: return true else: return false else: x in self.children: return x.searchleaves(target) however, problem in else statement. if binary tree, do else: return x.leftchild.searchleaves(target) or x.rightchild.searchleaves(target) in order consolidate combinations of falses , trues base case produce. how apply "or" logical operator undetermined amount of children? use any : else: return any(x.searchleaves(target) x in self.children) this equivalent this: else: x in self.children: if x.searchleaves(target): return true return false

Duplicate nonce in BrainTree using Dropin UI -

i'm using braintree marketplace in sandbox, , have problem/question. i'm using customer id when generating client_token, saving payment_nonce in database , using later (w/in 3-4 min) submit_for_settlement. problem each transaction needs unique nonce, if submit dropin ui twice w/in 2-3 mins same nonce , second transaction fails error : cannot use payment methos nonce more once. there way ensure unique nonce's ? thank you instead of creating transaction same nonce, try submitting original transaction settlement using transaction.submit_for_settlement payment method nonces 1 time use. reference same parent method multiple times in server side integration, can create payment method token in vault. in general, should never store payment method nonce in database, short lived , single use only. https://developers.braintreepayments.com/ios+ruby/reference/request/transaction/submit-for-settlement https://developers.braintreepayments.com/ios+ruby/start/vault

openlayers - Issue with for loop and if statements in javascript -

i using javascript , openlayers library in order style vector feature on map. have written following script: var gids = response[object.keys(response)[object.keys(response).length - 1]] // data json obj // add styling - different colors complete var stylecontext = { getcolor: function (feature) { var objectkeys = object.keys(gids); // use objectkeys loop on object properties //use length (var = 0; < objectkeys.length; i++){ //alert(i); ////////////////// if(gids[i][1]=="mt"){ //alert(gids[i][1]); return "green"; } else if(gids[i][1]=="iru"){ alert(gids[i][1]); return "#780000"; //no images on line } /////////////////////// } } }; if run script withou

swift - Syntax for method hiding -

what syntax method hiding in swift? i've tried bunch of options in playground, keep getting errors. haven't been able find documentation on either. in superclass: func performfunction() { print("performing function...") } in subclass, tried couple different options not seem work new func performfunction() { print("function...") } and func new performfunction() { print("function...") } you're looking override keyword: class subclass: parentclass { override func performfunction() { println("function...") } } see the swift programming language: inheritance more info.

mysql - How to grant access to certain users using PHP -

i having issue php, trying write program redirect user previous page (membersonly.php). here code isn't working me. $sess = $_session['sess_username']; if ($sess == "admin") { return; } else { header("location: membersonly.php"); } my attempt allow user "admin" admin.php page. code first thing run. $_session['sess_username'] variable assigned in login.php following code: session_start(); $_session['sess_username'] = $_post['user']; header("location: membersonly.php"); now know correctly setting session username, because in page choose, can use echo $_session['sess_username']; , displays username. not sure doing wrong when try send user membersonly.php if username not admin. when try go page, denies access user, including admin. [edit: solved] forgot add session_start(); @ top of page. danbopes right, "returning" empty page. can this. note code not work unless u

python - NumPy random seed produces different random numbers -

i run following code: np.random.randomstate(3) idx1 = np.random.choice(range(20),(5,)) idx2 = np.random.choice(range(20),(5,)) np.random.randomstate(3) idx1s = np.random.choice(range(20),(5,)) idx2s = np.random.choice(range(20),(5,)) the output following: idx1: array([ 2, 19, 19, 9, 4]) idx1s: array([ 2, 19, 19, 9, 4]) idx2: array([ 9, 2, 7, 10, 6]) idx2s: array([ 5, 16, 9, 11, 15]) idx1 , idx1s match, idx2 , idx2s not match. expect once seed random number generator , repeat same sequence of commands - should produce same sequence of random numbers. not true? or there else missing? you're confusing randomstate seed . first line constructs object can use random source. example, make >>> rnd = np.random.randomstate(3) >>> rnd <mtrand.randomstate object @ 0xb17e18cc> and then >>> rnd.choice(range(20), (5,)) array([10, 3, 8, 0, 19]) >>> rnd.choice(range(20), (5,)) array([10, 11,

Getting data from user in java -

Image
i tried test 2 ways of getting data user. faced 2 errors, attached. first error: second error: have second error ( obeject never closed ) every object create scanner class! import java.io.bufferedreader; import java.io.inputstreamreader; import java.util.scanner; public class inputstreamreaderclass { public static void main(string[] args) { // method 1: inputstreamreader reader = new inputstreamreader(system.in); bufferedreader buffer = new bufferedreader(reader); system.out.println("type text 1: "); string text = buffer.readline(); //method 2: scanner scanner = new scanner (system.in); system.out.println("type text 2: "); string text2 = scanner.nextline(); } } method 1 have fix. have handle error. issue second method warning, , program still run without fix, idea in habit of closing objects you're not using. method 1 needs surrounded try/catch statement, or need throw , exception:

python - NLTK chunked parse tree, save it into a file and loading it with CorpusReader class -

let's have chunked corpus below, , saved in file called test.txt [rapunzel/nnp] let/vbd down/rp [her/pp$ long/jj golden/jj hair/nn] then can load chunkedcorpusreader . >>> nltk.corpus.reader import chunkedcorpusreader >>> reader = chunkedcorpusreader('.','test.txt') >>> reader.chunked_sents()[0] tree('s', [tree('np', [('rapunzel', 'nnp')]), ('let', 'vbd'), ('down', 'rp'), tree('np', [('her', 'pp$'), ('long', 'jj'), ('golden', 'jj'), ('hair', 'nn')])]) >>> print(reader.chunked_sents()[0]) (s (np rapunzel/nnp) let/vbd down/rp (np her/pp$ long/jj golden/jj hair/nn)) and made change on tree object, say, switched chunk tag np npp , called new . >>> print(new) (s (npp rapunzel/nnp) let/vbd down/rp (npp her/pp$ long/jj golden/jj hair/nn)) and want save new tree i