Posts

Showing posts from September, 2013

node.js - Sails JS new response in WebStorm -

i'm newbie in sails js.. i'm trying create new custom response, didn't find auto-generator created manually. //somename.js module.exports = function somename(data, options) { console.log('test'); }; i'm trying access response controller: //somecontroller.js module.exports = { somecontroller: function(req, res) { res.somename(); } } the problem webstorm isn't recognize response.. unresolved function or method somename. but when executing app-it's working..(webstorm recognize default responses came 'sails new someapp'). thanks help! the code in sails.js library loads custom responses this: files = getfilesinapiresponsesdirectory() files.foreach(function(file) { name = extractname(file); res[name] = require(file); // <-- dynamic infer @ point }) there no way webstorm code analyzer infer relationship between res , custom response function without running sails.js code or receiving (le

php - Javascript regex email validation -

this question has answer here: how validate email address in javascript? 65 answers i have used regex test email input. give alert when wrong email (for eg without @ or .com) submitted when press ok alert, still posts email email address directed page send_msg.php when should not.. quite new javascript , php still learning.. know if clause should follow else don't know how make post email if true. , can how make display message below email input field instead of making raise alert? <script> function checkemail(inputvalue){ var pattern=/^([a-za-z0-9_.-])+@([a-za-z0-9_.-])+\.([a-za-z])+([a-za-z])+/; if(pattern.test!=(inputvalue)){ alert("please enter valid email address"); return false; } } <form id="contact-form" name= "form1 "action="send_msg.php" method="post">

django - "Exception ignored in:" message in a loop -

i transferred code python2.7 python3.4 changes replaced reading csv reading database , few more. keep on getting message "exception ignored in:" when run app. issue or how can trace since exception ignored in message not provide more info. encounter message when press ctrl-c. found error occurs when assign class instance value dictionary. not sure error is. this message get: exception ignored in: exception ignored in: exception ignored in: exception ignored in: exception ignored in:

php - Regex to check for single/double quotation marks and parenthesis? -

i need have make kind of filter doesn't allow user use following characters in password: " ' ( ) right code got following: if(preg_match('/"/', $password)) { echo "illegal character found.."; } i'm extremely bad regex , kind of appreciated, i've been looking around answers can't seem find both checks single , double quotation marks.. try this: preg_match('~[\'"\(\)]~', $password); // return true when of '"() in password. the whole code should be: $password = '...'; if (preg_match('~[\'"\(\)]~', $password)) { echo 'password contains bad character'; } else { echo 'ok'; }

Oracle Stored Procedure to select from multiple procedures, Array as IN parameter and 1 dynamic condition based on the length of the array element -

i have 3 procedures return different columns values insert in same table. all procedures take array parameter , values of array can of 2 type. if type name = "tin" , if type 2 name = "tan". ex: array = {a,b,b,a}; if(a){ name="tin" }else{ name="tan" } how write procedure values passing array , 1 more condition based length of array element. set serveroutput on create or replace type arrtype varray(200) of varchar2(50); / created create or replace procedure arrtest (arr_in arrtype) begin in 1..arr_in.count loop if(arr_in(i)='a') dbms_output.put_line('tin'); elsif(arr_in(i)='b') dbms_output.put_line('tan'); else dbms_output.put_line('neither tin nor tan'); end if; end loop; end; / procedure created sql> declare 2 array1 arrtype; 3 begin 4 array1 := arrtype(); 5 array1.extend(3);

How can I perform element-wise multiplication for Ruby arrays? -

courses, credits , points ruby arrays equal size. gpa = (([credits, courses, points].transpose.map {|x| x.reduce(:*)}).inject{|sum,x| sum + x }).round(2) this method prompted error message when trying run it. error message: in 'each': undefined method '*' nil:nilclass (nomethoderror) from error message, seems of data nil . perhaps can attempt force data floats. it's not ideal, might end silent errors, it's worth shot. try: [credits, courses, points].transpose.map {|a| a.map {|n| n.to_f} } .map { |x| x.reduce(:*) } .inject{|sum, x| sum + x} .round(2) it works me strings , weird data (although incompatible data converted zeros, effecting math).

How can I start Nginx with php-fpm based on Ubuntu image using Dockerfile? -

i have dockerfile few commands: from ubuntu run apt-get install -y nginx php5 php5-fpm add . /code when run docker build . command next error: e: package 'php5-fpm' has no installation candidate info[0006] command [/bin/sh -c apt-get install nginx php5 php5-fpm] returned non-zero code: 100 how can start nginx php-fpm based on ubuntu image? you can see more complete example here nginx : # install nginx. run \ add-apt-repository -y ppa:nginx/stable && \ apt-get update && \ apt-get install -y nginx && \ rm -rf /var/lib/apt/lists/* && \ echo "\ndaemon off;" >> /etc/nginx/nginx.conf && \ chown -r www-data:www-data /var/lib/nginx for php-fpm , have this example : run apt-key adv --keyserver hkp://keyserver.ubuntu.com --recv-keys e5267a6c; \ echo 'deb http://ppa.launchpad.net/ondrej/php5/ubuntu trusty main' > /etc/apt/sources.list.d/ondrej-php5-trusty.list; \ apt-ge

php - Retrieving data back from my database android? -

my app simple tacking system every users location updated onto server , when called send mobile numbers of people within given range(approx). app works updating location periodically server , uses approximate method find people within range problem im facing send queried list of numbers device. have tried few tutorials no luck app keeps crashing. here code send data along php code. if me figure out how receive numbers server. private void serverconnection() { // todo auto-generated method stub gpstracker gps1 = new gpstracker(mainactivity.this); double latitude = gps1.getlatitude(); double longitude = gps1.getlongtitude(); toast.maketext(getapplicationcontext(),"your location -\nlat:"+latitude+"\nlon:"+longitude,toast.length_long).show(); string lat = string.valueof(latitude); string log = string.valueof(longitude); string svdnum; registrationactivity gsm = new registrationactivity(); sharedpreferences shared

enterprise architect - Default diagram for Toolbox -

i have custom toolbox foo element. i foo green on class diagram , red on flow chart diagram default. adding more 1 stereotype non- uml type impossible (as far know). is possible create 2 toolboxes- 1 class diagrams , 1 flow charts, specifying default diagram each toolbox in profile? not quite way describe it. toolboxes don't specify diagram open, it's other way around: create custom diagram type , associate toolbox. different custom diagrams may use same custom toolbox. you can create 2 custom diagram types, 1 class ("logical") , 1 flow chart ("activity"), if you're after getting same stereotyped element ( foo ) display differently in diagrams, don't need to. the solution create shape script stereotype, checks diagram type , changes color accordingly. diagram type can queried shape script using diagram.type property (for base uml diagram type), or diagram.mdgtype (for custom diagram type, if you've defined one). th

Efficiently Iterating over dictionary list values by skipping missing values Python 3 -

i have pandas dataframe import pandas pd df=pd.dataframe({'location': [ 'ny', 'sf', 'ny', 'ny', 'sf', 'sf', 'tx', 'tx', 'tx', 'dc'], 'class': ['h','l','h','l','l','h', 'h','l','l','m'], 'address': ['12 silver','10 fak','12 silver','1 north','10 fak','2 fake', '1 red','1 dog','2 fake','1 white'], 'score':['4','5','3','2','1','5','4','3','2','1',]}) and want add 2 tags stored in dictionaries. note second dictionary not include key 'a' df['tag1'] ='' df['tag2'] ='' tagset1 = {'a':['ny|sf'], 'b':['dc']

delphi - What is the RootElement of this Content -

i'm trying use trestresponsedatasetadapter. every combination i've tried json rootelement property fails you can view content running in browser: https://api.hubapi.com/contacts/v1/lists/all/contacts/all?hapikey=demo&count=1000 { "contacts":[ { "addedat":1405347851360, "vid":154835, "canonical-vid":154835, "merged-vids":[ ], "portal-id":62515, "is-contact":true, "profile-token":"ao_t-mmn77arlmsbctdpop0rf0qyyooz7bhb6ehvufx9unov0pyuiq1wq-a83bqmzfvfvc45t8s6txhkq_7fcdi5wzne7vxydwtvrkiviisznbjwhujj8oixhxw0owesle2qch2_rzsy", "profile-url":"https://app.hubspot.com/contacts/62515/lists/public/contact/_ao_t-mmn77arlmsbctdpop0rf0qyyooz7bhb6ehvufx9unov0pyuiq1wq-a83bqmzfvfvc45t8s6txhkq_7fcdi5wzne7vxydwtvrkiviisznbjwhujj8oixhxw0owesle2qch2_rzsy/", "properties"

ios - Possible to turn off multibuffering/doublebuffering in Metal? -

in reading powervr alpha drivers vulkan, note multibufering needs performed explicitly. since vulkan , metal similar, can turn off multibuffering altogether? willing sacrifice throughput low latency. http://blog.imgtec.com/powervr/trying-out-the-new-vulkan-graphics-api-on-powervr-gpus as bonus, possible avoid double buffering? know racing beam coming style on desktop don't know if mobile display tech supports simple single-buffering. double buffering not throughput , in fact modern gpus latency increases in single buffered operation. i know racing beam coming style on desktop most not, because racing beam works if can build image scanline scanline. realtime graphics these days operate sending triangles gpu rasterize , gpu has leeway in order in touching pixels. order of triangles relative screen continuously changes. last not least modern graphics systems these days composited, goes contrary racing beam.

ios - How can i make in a multiplayer sprite kit game all the devices have same map? -

i'm having ios sprit kit multiplayer game via game center , i'm trying have same generated map on both devices. how can manage that? generating , sending make both devices have other device map live generating it's sending nsdata other device each 0.5 - 2 seconds i've tried rand() , srand(). didn't quite managed desired result (maybe wrong something). there no standard code that. need setup third party server download content. you can include number of different maps part of app , select random map part of new game. including maps in code enables users instantly have access without need additional downloads.

javascript - angular js import csv or json -

var app = angular.module('app', ['nganimate', 'ngtouch', 'ui.grid', 'ui.grid.importer']); app.controller('mainctrl', ['$scope', '$http', '$interval', function ($scope, $http, $interval) { $scope.data = []; $scope.gridoptions = { enablegridmenu: true, data: 'data', importerdataaddcallback: function ( grid, newobjects ) { $scope.data = $scope.data.concat( newobjects ); }, onregisterapi: function(gridapi){ $scope.gridapi = gridapi; } }; }]); suppoese json file [{ "name":"john smith", "gender":"male", "company":"testicon" }, { "name":"jane doe", "gender":"female", "company":"fasttruck" }] now wll the grid having columns name, gender , company. now how dynamically change grid column names : want firstname instead of name guys please me in

html - jQuery difference between FF and Chrome -

he guys, why code work on chrome, not on ff? the alert below blank in fx gives me rgb color in chrome jquery.each(menuids, function(index, value) { var allclass = jquery('#'+value).attr('class'); if( (allclass.split('current-menu-item')).length > 1){ var currenturl = window.location.href; var allhtml = jquery('#'+value).html(); var allhtml_arr = allhtml.split('href="'); var allhtml_arr1 = allhtml_arr[1].split('">'); if( allhtml_arr1[0] == currenturl ) { var allclass_arr = allclass.split(value); var current_colorcls = jquery.trim(allclass_arr[1]); jquery('ul#primary-menu').addclass(current_colorcls); var prop = jquery('ul.'+current_colorcls).css('border-top'); var prop_arr = prop.split('solid

How are arguments passed to function pointers in C? -

in following code snippet reference , compare called main() without parameters being passed. assume taking ((char *)&key, (char *)string) 2 parameters needed function call. how work internally in c? compiler fill in arguments when compare called? #include <search.h> #include <string.h> #include <stdio.h> #define cnt 2 int compare(const void *arg1,const void *arg2) { return (strncmp(*(char **)arg1, *(char **)arg2, strlen(*(char **)arg1))); } int main(void) { char **result; char *key = "path"; unsigned int num = cnt; char *string[cnt] = { "path = d:\\david\\matthew\\heather\\ed\\simon","lib = path\\abc" }; /* following statement finds argument starts "path" */ if ((result = (char **)lfind((char *)&key, (char *)string, &num, sizeof(char *), compare)) != null) printf("%s found\n", *result); else printf("path not

ascii - Why does vi show the ends of lines as $? -

i using vi on mac, , when i've run :set list , $ (dollar sign) character displayed @ end of each line. confusion $ not ascii value newline. why $ represent end of line? $ chosen default value display represent line, because $ command move cursor end of line, chosen because $ represents end of line anchor in regular expression. there's nothing magical it, , can use character want setting listchars . :help listchars details.

c++ - VirtualAlloc failing -

i trying use virtualalloc reserve , commit block of memory , again extend block. unfortunately, returning null error error_invalid_address despite virtualquery saying address range requested free. here's code: void* allocation = virtualalloc(null, 4096, mem_reserve | mem_commit, page_readwrite); void* desirednextallocation = (char*)allocation + 4096; memory_basic_information info; size_t memory_info = virtualquery(desirednextallocation, &info, sizeof(info)); void* extended = virtualalloc(desirednextallocation, 4096, mem_reserve | mem_commit, page_readwrite); the first allocation returns 0x00000000000d0000. call virtualquery results in following data in 'info': baseaddress 0x00000000000d1000 void * allocationbase 0x0000000000000000 void * allocationprotect 0x00000000 unsigned long regionsize 0x00000000000ff000 unsigned __int64 state 0x00010000 unsigned long protect 0x00000001 unsigned long type 0x00000000 unsigned lon

iphone - iOS Auto Layout UIView Drawing cycle -

in 1 of wwdc videos, apple said layout done top down, ie superview subview (after constraints calculated bottom up). display done top down. my questions are: 1. @ point in viewcontroller view's frame (origin , size) determined? tried log size of view (defined using auto layout), 0 0 0 0, odd, because view generated in simulator; for autoresized view, when view.frame available? same question, except time uiimageview.frame. tried log console, though size fit constraints, logged uiimageview frame 0 0 width_of_original_image height_of_original_image. other views labels, frame printed correctly on console. it seems there mysterious auto layout engine performs transform, , nobody knows going on inside engine, check thrown onto simulator display figure out how view rendered engine??? it's not mysterious. it's quite simple! think of constraints instructions written down on pieces of paper - views. every once in while, it's layout time! runtime collects

ios - View Dismissing itself on touch without any code -

i have series of view controllers navigated "back" , "next" uibarbuttonitems*. problem have view controllers dismiss when view touched anywhere in top half of view without code whatsoever. nothing calling [self dismissviewcontrolleranimated:yes completion:nil]; didn't notice behavior until after updated xcode 6.3.1 can't think of way capture event nslog. i have commented out view still dismisses when touch it. i've never been stumped this. any suggestions ? - (void)viewdidload { [super viewdidload]; // uiswipegesturerecognizer *swipeleft = [[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(actnext:)]; // swipeleft.direction = uiswipegesturerecognizerdirectionleft; // [self.view addgesturerecognizer:swipeleft]; // uiswipegesturerecognizer *swiperight = [[uiswipegesturerecognizer alloc] initwithtarget:self action:@selector(actback:)]; // swiperight.direction = uiswipegesturerecognizerdirectionright; //

How do I update all Chocolatey apps without confirmation? -

i used able call cup all , have apps update. now, asks yes ensure want install selected package. there way can have auto update without typing yes every update? tl;dr - yes, possible. use cup -y also check out menus - choco -h , choco install -h longer answer, we've moved little closer towards other package managers security reasons, default stop , confirm if okay state change. communicate changes in release notes / changelog , end in nuspec file , highly recommend folks scan @ least 1 of see tagged breaking changes. scan current version 1 upgrading catch changes. the 1 important right x.y.z release (in case 0.9.9), once reach v1 semver compliant , breaking changes constitute major version bump (we're still semver in less v1), can scan breaking changes , major new features in x release, new compatible features in .y release, , .z releases contain compatible fixes current release. 0.9.9 introduced new compiled client was/is total rewrite. 0.9.10 hav

jquery - dialog won't close on background/overlay click -

many of pages have dialogs should closed when background (or overlay) clicked -- i.e. when click outside dialog. doing this code $(document).on('click', '.ui-widget-overlay', function(){ $(".ui-dialog-titlebar-close").trigger('click'); }); which came jquery-ui close modal dialog on background click . the code above on master page, , works fine every dialog have tried except one. ones close correctly (i.e. when background clicked) opened invoking following function (or similar) onclick event of control on page. function loadpopupwindowfixedwidthandmodal(path, width) { $("#divpopup").dialog({ title: "tip", width: width }).load(path); } the dialog doesn't close inside user control placed on master page, , made dialog using code $(function () { $("#divfindresult").dialog({ autoopen: false, modal: false, resizable: false, width: 600, position: { my: "

r - geom_text and facets not working -

Image
data file way big dput hoping able identify error. here story: produced following small multiples plot using ggplot following code. working fine. ggplot(sm.df, aes(year, n, group = 1)) + geom_line(aes(colour = top10)) + facet_wrap( ~ shorttitle, ncol=7) + theme_bw() + theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank(), axis.text.x = element_text(angle=45, hjust=1, size =8)) + scale_x_discrete(breaks=seq(1989, 2020, 8)) + ylim(0, 150) now, want annotate each facet overall n. created vector containing x position, y position, , actual values plotted. so, basically, in same x , y position on every plot, different label. 'data.frame': 78 obs. of 3 variables: $ x1 : num 12.5 12.5 12.5 12.5 12.5 12.5 12.5 12.5 12.5 12.5 ... $ y1 : num 130 130 130 130 130 130 130 130 130 130 ... $ n.label: int 1650 1456 1348 1216 1086 1035 985 940 888 826 ... but, when add geom_text(data = x.df, aes(x = x1, y = y1, label = n.label),

java - Android about unable to start activity componentinfo -

i'm new programmer,recently have bug can't solve java.lang.runtimeexception: unable start activity componentinfo{com.example.android.bl uetoothchat/com.example.android.bluetoothfiletran.filetranactivity}: java.lang.nullpointerexception logcat stack trace 04-26 10:19:43.613: e/bluetoothchat(21754): +++ on create +++ 04-26 10:19:44.213: e/checkpermission(21754): _bluetooth code = 1 04-26 10:19:44.213: e/bluetoothchat(21754): ++ on start ++ 04-26 10:19:44.233: e/bluetoothchat(21754): + on resume + 04-26 10:19:44.233: e/checkpermission(21754): _bluetooth code = 13 04-26 10:19:45.643: e/bluetoothchat(21754): - on pause - 04-26 10:19:47.223: e/bluetoothchat(21754): + on resume + 04-26 10:19:55.093: e/bluetoothchat(21754): - on pause - 04-26 10:20:21.363: e/androidruntime(21754): fatal exception: main 04-26 10:20:21.363: e/androidruntime(21754): process: com.example.android.bluetoothchat, pid: 21754 04-26 10:20:21.363: e/androidruntime(21754): java.lang.runtimeexception: u

c++ - Accessing private virtual functions within same class -

i asked, using code , writing in extractmultadd() function, return variable.x variable.y variable.add() , variable.multiply . understand basic concept of virtual tables , when created, despite best efforts, i'm not quite sure how leverage them access private virtual functions. appreciated. #include <cstdio> #include <iostream> class multadd { private: int x; int y; virtual int add() //virtual fuction vtable created thing class { return x+y; } virtual int multiply() { return x*y; } public: multadd(){ x = 2; y = 10; } }; int extractmultadd(void* math) { return 0; } int main() { multadd variable; printf("%d\n", extractmultadd(&variable)); return 0; } i give 2 versions choose. not follow standard, , no means portable, both work on msvc 2013, gcc 4.9, , clang 3.5 test it. second version relatively safer , more portable first one. in fa

unity3d - Unity 5.0.1 Completely Stopping a Coroutine -

alright running slight issue, basically, have coroutine contains for-loop. can call stopcoroutine , startcoroutine methods successfully, of course, pauses , unpauses coroutine. there way stop , restart it? end-goal here able start coroutine, kill @ user's discretion, , restart beginning time, @ user's discretion. accomplishable? thanks. to "rewind" coroutine, call coroutine method again same parameters. if want save these parameters, can use closures: public class coroutineclosureexample : monobehaviour { private system.func<ienumerator> createcoroutinefactory(int someint, float somefloat) { return () => coroutineyouwant(someint, somefloat); } private ienumerator coroutineyouwant(int someint, float somefloat) { for(int = 0; < someint; i++) { yield return new waitforendofframe(); } } private system.func<ienumerator> m_currentcoroutinefactory; private ienumerat

How to print a nested list of objects with the highest sum in python -

i'm still learning python , i'm still having tough time working objects, i'm trying write program calculates critical path of set of activities in project, i've been able critical path of activities , they're stored list of nested objects each object having it's different properties id, predecessor , duration, problem i'm having print out result properly, want print out path has longest duration , path gives value class criticalpath: def __init__(self): ''' initialize variables we're going use calculate critical path ''' self.id = none self.pred = tuple() self.dur = none self.est = none self.lst = none #list store objects self.all_objects = list() def set_properties(self, name, predecessor, duration): self.id = name self.pred = tuple(predecessor) self.dur = duration def main(): #starting_nodes = list()

java - I am getting an error on the 'start' in the (start + finish) at the bottom -

this question has answer here: scoping rules in java 3 answers i getting error on 'start' in (start + finish) @ bottom. way fix add "int start = inputfn.nextint();" below ' scanner inputfn = new scanner(system.in);' screws up. able fix before forgot how did it. please help. public static void main(string eth[]){ system.out.println("please enter integer:"); scanner inputfn = new scanner(system.in); if (inputfn.hasnextint()){ }else{ int start = inputfn.nextint(); system.out.print("play rules , enter integer"); } system.out.println("please enter integer:"); scanner inputsn = new scanner(system.in); int finish = inputsn.nextint(); int answer = (start + finish); system.out.println(answer); } } the if if (inputfn.hasnextint()){ }else{ int start = inputfn.nextint(); system.out.print("play

How to set User-based form field choices in a django ModelForm (with django-allauth) -

i'm using django 1.8 , django-allauth. have simple form dropdown menu allows users choose character model. have usercharacter model looks this: class usercharacter(models.model): user = models.foreignkey(user) character = models.foreignkey(character) is_default = models.booleanfield(default=false) in main form i'm displaying "character" field, appears dropdown menu of character objects. far, - users can select character , saved usercharacter association. what i'm trying display character objects don't have usercharacter linked logged in user. use limit_choices_to feature, so: character = models.foreignkey(character, limit_choices_to={'id__in': usercharacter.objects.filter(user_id=[user_id])) my problem is, don't know how access current user object usercharacter model or modelform. need access current request @ django-allauth logged in user object. in place of [user_id] put self.request.user.id

jquery - CSS real "slide" toggle not "height" toggle -

i have been looking around while did not find solution trying create. i have real "slide" toggle, div "moving down in". if take jquery slidetoggle or several css solutions found, modify height of div, don't slide it. so created own solution animating margin-top property, works nicely, have problem dynamic heights (for example if resize browser-window), not sure how high negative margin-top should make sure slided out, , on other side not delay slide-in because margin-top far out. i use margin-top: -100%; however, if resize window/frame, it's not enough negative margin. maybe there better solution out there did not find it, created fiddle , share idea , hear suggestions. update: latest updated fiddle here ... changed few things, feedback! update - fix typo , tidy up. i think can use in combination jquery show() , hide() code avoid issue. http://jsfiddle.net/jzj80kzs/7/ $('.switch').click(function(event) { var the