Posts

Showing posts from April, 2014

r - Variable assignment during re-coding loop -

i importing survey data csv file in r, , want use for-loop reassign periods in cells "na". 1 survey item, have this: survey$q1a <- recode(survey$q1a, "'.'=na") # csv column survey$q1a <- as.numeric(as.character(survey$q1a)) where q1a column title in csv file, , refers question 1, part (i have 137 columns). so, in order make for-loop, need able this: for (n in 1:31){ survey$qna <- recode(survey$qna, "'.'=na") # csv column n survey$qna <- as.numeric(as.character(survey$qna)) } 31 items have part a, means need survey$q1a survey$q31a . sake of simplicity, best keep columns in qna format (ironically). have never used r, have experience python , c, , know use % %s operators in languages achieve similar goals. is there way in r without changing how variable/column labeling system?

python - Finding and utilizing eigenvalues and eigenvectors from PCA in scikit-learn -

i have been utilizing pca implemented in scikit-learn. however, want find eigenvalues , eigenvectors result after fit training dataset. there no mention of both in docs. secondly, can these eigenvalues , eigenvectors utilized features classification purposes? i assuming here eigenvectors mean eigenvectors of covariance matrix. lets have n data points in p-dimensional space, , x p x n matrix of points directions of principal components eigenvectors of covariance matrix xx t . can obtain directions of these eigenvectors sklearn accessing components_ attribute of pca object. can done follows: from sklearn.decomposition import pca import numpy np x = np.array([[-1, -1], [-2, -1], [-3, -2], [1, 1], [2, 1], [3, 2]]) pca = pca() pca.fit(x) print pca.components_ this gives output [[ 0.83849224 0.54491354] [ 0.54491354 -0.83849224]] where every row principal component in p-dimensional space (2 in toy example). each of these rows eigenvector of centered covariance mat

html - Resizeable text input -

i use bootstrap in site, wan't create this . my html code: <form class="navbar-form navbar-left" role="search"> <div class="form-group"> <input type="text" class="form-control search-input" placeholder="search"> </div> <button type="submit" class="btn btn-default"> 'find'</button> </form> how can resize input? in tutorial specified , css code there : add part html page : demo here <style stype='text/css'> input[type=text].search_form { border: 1px solid #ccc; border-radius: 3px; box-shadow: inset 0 1px 2px rgba(0,0,0,0.1); width:200px; min-height: 28px; padding: 4px 20px 4px 8px; font-size: 12px; -moz-transition: .2s linear; -webkit-transition: .2s linear; transition: .2s linear; } input[type=text]:focus.search_form { width: 400px; border-color: #51a7e8; box-shadow: inset 0 1px 2px rgba(0,0,0,0.1),0 0 5px

tk - couldn't load file "/usr/lib/x86_64-linux-gnu/magic/tcl/tclmagic.so" -

Image
i have problem running magic vlsi. problem couldn't load file "/usr/lib/x86_64-linux-gnu/magic/tcl/tclmagic.so": /usr/lib/x86_64-linux-gnu/magic/tcl/tclmagic.so: undefined symbol: tk_getcursorfromdata i think caused by: /usr/lib/x86_64-linux-gnu/magic/tcl/magic.tcl in line 13: load /usr/lib/x86_64-linux-gnu/magic/tcl/tclmagic.so the file /usr/lib/x86_64-linux-gnu/magic/tcl/tclmagic.so exists the error source in running magic qflow in shellscript display.sh : #!/bin/tcsh -f #---------------------------------------------------------- # qflow layout display script using magic-8.0 #---------------------------------------------------------- # tim edwards, april 2013 #---------------------------------------------------------- if ($#argv < 2) echo usage: display.sh [options] <project_path> <source_name> exit 1 endif # split out options main arguments (no options---placeholder only) set argline=(`getopt "" $argv[1-]`) set cmdarg

Angularjs Google maps connect multiple markers -

i building ionic app , therein have following requirement: want use google maps , want able mark 3 markers on map -> connect 3 markers automatically -> , calculate area covered. i have following (map shown on screen, can add multiple markers): controller: angular.extend($scope, { map: { center: { latitude: 51.718921, longitude: 8.757509 }, zoom: 11, markers: [], events: { click: function (map, eventname, originaleventargs) { var e = originaleventargs[0]; var lat = e.latlng.lat(),lon = e.latlng.lng(); var marker = { id: date.now(), icon: 'http://maps.google.com/mapfiles/ms/icons/blue.png', coords: { latitude: lat, longitude: lon }, }; $scope.map.markers.push(marker); console.log($scope.map.markers); $sc

CRON JOB - How to grab image from URL ...servlet/byvejr_dag1?by=5466&mode=long -

i want save image server cron job url: http://servlet.dmi.dk/byvejr/servlet/byvejr_dag1?by=5466&mode=long - png image i've tried following codes */5 * * * * curl http://servlet.dmi.dk/byvejr/servlet/byvejr_dag1?by=5466&mode=long > /home/klintweb/public_html/gal.klintmx.dk/images/vejr.png the image saved in folder, can't published because of error - file-size 0 byte there way this the job done php script $profile_image = 'http://servlet.dmi.dk/byvejr/servlet/byvejr_dag1?by=5466&mode=long'; //image url $userimage = 'byvejr_dag1_5466.png'; // renaming image $path = '/home/klintweb/public_html/gal.klintmx.dk/images/vejr'; // saving path $ch = curl_init($profile_image); $fp = fopen($path . $userimage, 'wb'); curl_setopt($ch, curlopt_file, $fp); curl_setopt($ch, curlopt_header, 0); $result = curl_exec($ch); curl_close($ch); fclose($fp); and cron job 0,30 * * * * /usr/bin/php /home/klintweb/publ

Truth value of a string in python -

if <boolean> : # boolean has either true or false. then why if "poi": print "yes" output: yes i didn't why yes printing , since "poi" nether true or false. python best evaluate "truthiness" of expression when boolean value needed expression. the rule strings empty string considered false , non-empty string considered true . same rule imposed on other containers, empty dictionary or list considered false , dictionary or list 1 or more entries considered true . the none object considered false. a numerical value of 0 considered false (although string value of '0' considered true). all other expressions considered true . details (including how user-defined types can specify truthiness) can found here: http://docs.python.org/release/2.5.2/lib/truth.html .

python - Function that has if statement produces nothing when it's called -

#4 gender differences def d_gender(employee1, employee2): if employee1.gender >= employee2.gender : 1 else : 0 d_gender(e1,e2) although defined function doesn't produce anything. wrong here? you need return statement in function: def d_gender(teacher, studio): if teacher.gender >= studio.gender : return 1 else : return 0 then can decide returned value . maybe print : print(d_gender(t1,s1))

javascript - Comparing hours and day with JQuery -

there similar topics on website comparing time have little bit different problem. need compare specified time , now. i have particular times (days, opening , closing hours shop) example: monday opening 10:00 - closing 6:30 pm i want create application checks time , informs user: shop open or close, google app. i need find subtraction's result of , specified time: example if day monday(closing time 6:30) , time 5:20 pm, result 1:10 , means shop open, don't know how can convert 6:30 hours format. based on information provided, can following: var time = "6:30", splittime = time.split(':'), hours = splittime[0], minutes = splittime[1]; then you'll have variables hours , minutes can use comparison.

c# - Summing numbers in many TextBox and writing them to a file -

this program inserting expenses making in textboxes have insert numbers. have save numbers textboxes txt file, summed. can me ideas? private void button2_click_1(object sender, eventargs e) { try { stringbuilder sb = new stringbuilder(); sb.appendline(textbox1.text + " " + textbox2.text + " " + textbox3.text + " " + textbox4.text); file.writealltext(filename, sb.tostring()); } catch (exception ex) { messagebox.show(ex.message, "error!", messageboxbuttons.ok, messageboxicon.error); } } you need line adds numbers this: private void button2_click_1(object sender, eventargs e) { try { stringbuilder sb = new stringbuilder(); sb.appendline(textbox1.text + " " + textbox2.text+ " " + textbox3.text+ " " + textbox4.text); sb.appendline((int32.parse(textbox1.text) + int32.parse(textbox2.text) + int32.parse(textbox3.text) + int32.parse(textbox3.text)

shell - getting a file to print to a specific printer using notepad and command line in visual basic -

i have been trying file print specific printer using notepad. have managed work when set printer in question default printer. this code used achieve this: shell("notepad /p c:\temp\test.txt") the issue i've got need send file printer when not default printer. some applications (including notepad) support printto command. notepad's /pt printername . you'll have experiment printer name right - believe it's name of printer seen in control panel, may name of device or driver itself. (a few quick tests should figure out applies.) shell("notepad /pt mylaserjet c:\temp\test.txt") of course, proper solution problem change application doesn't use shell("notepad",...) printing, sends text printer itself. can have user set printer once, save configuration, , automatically send text proper printer every time. using external application work app should workaround, not solution. :-) can't suggest how that, because you'

sql - Joining a database to an Availability Group-error -

i getting "insufficient transaction log data" error when adding database (42gb) availability group. have taken full , transaction log backups on primary server , restored onto secondary, i'm not sure why there insufficient transaction logs. i suspected maybe due large amount of time takes transfer backup files secondary server , time restore on secondary server, log backup taken insufficient. anyone have suggestions why i'm getting error? try shrinking log file before doing restore. also, allow wizard handle full backup, trans backup , restore.

Xamarin: How do you set a breakpoint in a simple C++ project? -

i new xamarin studio. trying set breakpoint in c++ project's automatically created main.cpp file, contains hello world line only. on xamarin studio community 5.10.3 (build 51) on mac. solution created template in other->miscellaneous->c/c++->console project->cpp. while debugging setting breakpoint execution won't stop @ breakpoint. how make debugger stop there? there should 2 options run program, "start without debugging" , "start debugging" under "run" toolbar @ top. must use second option have program stop @ breakpoint. running program little "run" arrow icon? if so, starts program without debugger. must select "start debugging" option under "run" toolbar.

phpunit - Running tests in PhpStorm for Laravel Homestead vagrant VM -

i've got fresh installation of laravel homestead based on this: https://laravel.com/docs/master/homestead and fresh new project using laravel new. i'm trying run example tests through phpstorm's "run configurations" get vagrant:///users/si/vagrant/homestead/usr/bin/php /home/vagrant/.phpstorm_helpers/phpunit.php --no-configuration /home/vagrant/code/homestead/tests testing started @ 00:49 ... process finished exit code 1 cannot find phpunit in include path (.:/usr/share/php) in phpstorm phpunit settings have phpunit library loaded "use custom autoloader" pointing @ composer autoload.php file this: /users/si/code/homestead/vendor/autoload.php and composer has added phpunit executable @ /users/si/code/homestead/vendor/bin/phpunit i'm confused why phpstorm can't find phpunit executable when i'm telling use composer autoload find it. ok, fixed this. had added remote interpreter in php settings, still using 'local

PHP IF-Statement doesnt work like i want -

this question has answer here: in php, 0 treated empty? 14 answers i started writing website learning html/css/js/php. i designed front-end of site bootstrap. trying validate inputs php. i tried this: if ($durationhh <= 0 && $durationmm <= 0) { echo "durationhh , durationmm can not both 0 @ same time."; echo "<br>"; echo "durationhh , durationmm can not smaller 0."; } elseif (empty($durationhh) || empty($durationmm)) { echo "durationhh , durationmm can not empty."; echo "<br>"; } else { echo $_post["durationmm"]; echo ":"; echo $_post["durationhh"]; } i tested validation putting in values durationhh , durationmm. everything working fine

java - Sorted int[] Converted from String[] -- ArrayIndexOutOfBoundsException -

context i've been trying fix part of program while without success. want sort string [] each element in format: name:number (i.e. john:32 ). progress so far, code splits each element , adds equivalent int [] . attempt compare elements in int [] selection sort , swap elements in string [] . problem i'm getting java.lang.arrayindexoutofboundsexception string [] , called scores . why this? scores = sort(scores); //arrayindexoutofboundsexception here public static string [] sort(string [] a) { //equivalent array containing integer part of score[i] int[] temparray = new int[a.length]; //populate temparray for(int = 0; < a.length; i++) { //acquire numerical part of element //arrayindexoutofboundsexception here******** int num = integer.parseint(a[i].split(":")[1]); //add array temparray[i] = num; } /* selection sort: descending */

iphone - How can I center a UIView programmatically on top of an existing UIView using Autolayout? -

in case of successful foursquare checkin, iphone app shows adds view on top of view shown. i want view centered on x , y , have definite width , height using autolayout, i'm not sure constraints add programmatically. know how in storyboard, i'm not sure type in code same view added later in response successful action in app. i can't working , uiview has nib loads loadnibnamed:. successview *successfulcheckinview = [[successview alloc] initwithframe:cgrectzero]; successfulcheckinview.placenamelabel.text = propervenue.name; successfulcheckinview.placeaddresslabel.text = propervenue.address; successfulcheckinview.delegate = self; [self.ownervc.view addsubview:successfulcheckinview]; try this: nslayoutconstraint *xcenterconstraint = [nslayoutconstraint constraintwithitem:view1 attribute:nslayoutattributecenterx relatedby:nslayoutrelationequal toitem:view2 attribute:nslayoutattributecenterx multiplier:1.0 constant:0]; [superview addconstraint:xcenterconstra

sorting - Linked list alphabetical sort, seg fault in c -

i'm trying sort linked list in alphabetical order, i'm getting seg fault sorting function. how can sort list alphabetically. typedef struct s_file { char *file_name; struct s_file *next; } t_file; void sort_alpha(t_file **begin_list) { t_file *list; char *tmp; list = *begin_list; if (list) { while (list) { if (strcmp(list->file_name, list->next->file_name) < 0) { tmp = list->file_name; list->file_name = list->next->file_name; list->next->file_name = tmp; } list = list->next; } } } in line if (strcmp(list->file_name, list->next->file_name) < 0) // list->next null // list->next->file_name give seg fault a protection needed. possible solution: void sort_alpha(t_file **begin_list) { t_file *list; char

symfony - Remove all validation constraints in child class properties -

i have problem clearing validation constraint extend super class. below code user.php * @var string * @orm\column(type="text", unique=true) * @assert\notblank() * @assert\notnull() * @adminassert\mycustomvalidation */ protected $phonenumber; in admin.php wrote code below class admin extends user * @var string * @orm\column(type="text", unique=true) */ protected $phonenumber; i want remove validation constraints can't remove it. for disabling validation of form can set validation_groups option false , described here in doc. in case can check class data ( as described here in doc ) disabling or not form validation, example: public function configureoptions(optionsresolver $resolver) { $resolver->setdefaults(array( 'validation_groups' => function (forminterface $form) { $data = $form->getdata(); if ($data instanceof admin) { return; }

Xamarin.Social Posting to facebook -

This summary is not available. Please click here to view the post.

Using bash function + grc like an alias breaks Zsh completion -

i'm using grc / grcat colorize terminal output function: function docker() { case $* in ps* ) shift 1; command docker ps "$@" | grcat $home/.grc/conf.dockerps ;; images* ) shift 1; command docker images "$@" | grcat $home/.grc/conf.dockerimages ;; info* ) shift 1; command docker info "$@" | grcat $home/.grc/conf.dockerinfo ;; * ) command docker "$@" ;; esac } but breaking zsh completions , plugins setup using oh-my-zsh in .zshrc this: plugins=(git colored-man-pages colorize vagrant brew ruby docker) plugins+=(gradle rvm rails bundler gem osx pod) plugins+=(bower cp go node npm) plugins+=(zsh-syntax-highlighting encode64) plugins+=(zsh-completions mvn) fpath=(~/.zsh/completion $fpath) autoload -uz compinit && compinit -i when try using docker stop example, completion coming ansi escape sequences: $'\033'\[0m$'\033'\[1m$'\033'\[33mhigh_wright$'\033'\[0m is there way av

javascript - Setting default text of select box depending on another select box -

i have question regarding ability set default text of selectbox depending on default text of selectbox. i trying populate country , state drop down list, state options change in regards country have chosen. however, when no country chosen, state selectbox "please choose country". right says "state" otherwise. in other words, if country select box says "country" want state select box "please choose country". , once user chooses in country selectbox, state selectbox won't say "please choose country" anymore. simple example of have country <.select id="country" name ="country"> state <.select id="state" name ="state"> i inexperienced programmer not sure functions can possibly used. accomplished jquery? appreciate in regards matter , hope question wasn't confusing. thank you. yes can accomplish using jquery. check out plunker created below https

sql - DB2 query to find average sale for each item 1 year previous -

having trouble figuring out how make these query. in general have table with sales_id employee_id sale_date sale_price what want have view shows each sales item how employee on average sells 1 year previous of sale_date. example: suppose have in sales table sales_id employee_id sale_date sale_price 1 bob 2016/06/10 100 2 bob 2016/01/01 75 3 bob 2014/01/01 475 4 bob 2015/12/01 100 5 bob 2016/05/01 200 6 fred 2016/01/01 30 7 fred 2015/05/01 50 for sales_id 1 record want pull sales bob 1 year month of sale (so 2015-05-01 2016-05-31 has 3 sales 75, 100, 200) final output be sales_id employee_id sale_date sale_price avg_sale 1 bob 2016/06/10 100 125 2 bob 2016/01/01 75 275 3 bob 2014/01/01 475

python - Cannot achieve consistency level LOCAL_ONE info={required_replicas 1 alive_replicas: 0, consistency: LOCAL_ONE} -

my cluster size 6 machines. data amount small 30.000. have read,write,delete , update operations might costly although data amount low. don't why error message occurs since data amount low. answers appreciated. when cassandra cluster busy error message: warning code=1000 [unavailable exception] message="cannot achieve consistency level local_one" info={'required_replicas': 1, 'alive_replicas': 0, 'consistency': 'local_one'} this read cassandra python code: cluster = cluster(['localhost']); session = cluster.connect('keyspaace') kafka = kafkaclient('localhost'); producer = simpleproducer(kafka) channels = session.execute("select id channels;") channel_ids = [channel.id channel in channels] sleep_time = 10*60 / (len(channel_ids)+0.0) channel in channel_ids: url = 'http://toutiao.com/m%s/?%s' % (channel, urllib.urlencode({'_': datetime.utcnow().replace(tzinfo=pytz.utc).isoformat()})

parse.com - AVPlayer doesn't play video from my parse -

i'm trying play video parse server i'm getting empty video player , when print url correct video url let thevideo:pffile! = (self.selectedmsg["file"] as! pffile) let url:nsurl = nsurl(string: thevideo.url!)! let player = avplayer(url: url) let playercontroller = avplayerviewcontroller() playercontroller.player = player self.presentviewcontroller(playercontroller, animated: true) { player.play() } any help? i had same issue, tried search around solution, cannot, workable solution save file device, , play locally.

javascript - How to make this bootstrap nav submenu always open? -

i have code make bs nav, don't understand how make submenu open without clicking menu name. this code: http://jsfiddle.net/6hrmodok/2/ and please answer question new code. .gw-nav-list>li.always-active>a, .gw-nav-list>li.always-active>a:hover, .gw-nav-list>li.always-active>a:focus, .gw-nav-list>li.always-active>a:active { background-color: #fff; color: #2574a9; font-weight: bold; font-size: 13px; } .gw-nav-list>li.always-active:before { display: inline-block; content: ""; position: absolute; left: 0px; top: -1px; bottom: 0; z-index: 1; border: 2px solid #2574a9; border-width: 0 0 0 5px; } .always-active .gw-submenu, .gw-nav-list>li.always-active .gw-submenu { display:block; } and javascript; $('.gw-nav > li:not(.always-active) > a').click(function () { .... updated fiddle

java - Send data to the server in service class -

i trying send data server when user mobile internet become active, in application whenever internet connection active broadcast receiver call service method. below method. trying both post , method not request site. not able print "i in service5"(below have printed).it not update database. public class localservice extends service { .... .... public void sendfeedback(){ system.out.println("i in service4"); string filename =mainscreenactivity.username; httpurlconnection urlconnection = null; final string target_uri = "http://readoline.com/feedback.php"; try { bufferedreader mreader = new bufferedreader(new inputstreamreader(getapplicationcontext().openfileinput(filename))); string line; stringbuffer buffer = new stringbuffer(); while ((line = mreader.readline()) != null) { buffer.append(line + "\n");

extjs6 - How to hide and show panel multiple times in extjs -

i trying catch updates in grid , want show message html config in panel docked @ bottom in grid. if click on 1 button show preview message panel hide. this working fine when click on show preview button multiple times. , edit field grid dom of message panel getting null. throwing error typeerror: argument 1 of node.insertbefore not object. using extjs 6 version. edit : hi. here code hide/show panel , changing message panel per condition. var notepanel = ext.getcmp("notepanelcontainer"); if(ispropertyupdate) { notepanel.update("property panel has been updated."); } else { notepanel.update("fields grid has been updated."); } if(ishide){ notepanel.hide(); }else{ notepanel.show(); } not sure doing, created simple fiddle illustrate solution task (at least understand it). as understand use ext.panel.panel docked item show message, heavy component task. use ext.component .

jquery - Javascript Search Engine AND clause -

i'm writing search engine js , jquery rather resulting php database i'm having issue understanding how construct 'query'. currently, following steps taken fill array of objects. 1) php backend develops json file holidays in specific database. 2) javascript frontend pulls json , adds of array through loop. 3) user has few boxes can search array , results added 'results' array updated accordingly each time. one issue i'm having is; how deal multiple if clauses? example, if both search_time , search_state != "all", need narrow search down include objects search_time , search_state values met. query or query. i come background of sql approaching javascript search bit different me, appreciated. javascript search below: (var i=0; (i <= holidays.length) && (found < limit); i++) { var h = holidays[i]; console.log(h); complete = false; while (!complete && (h != undefined)) { if (search_term

c++ - can't understand a macro definition (casting constant number to a class pointer) -

in code, see macro defined below can't understand. #define offset_of_field_(f) (reinterpret_cast<char*>( \ &reinterpret_cast<netparameter*>(16)->f) - \ reinterpret_cast<char*>(16)) the macro name seems calculating offset of field f inside class structure. , has form of subtracting start address address of field. how number 16 used here? , deosn't reinterpret_case apply 16?(not 16 -> f). appreciate if please explain code me. the comment in (now refactored) protobuf header (link here ) explains it // note calculate relative pointer value 16 here since if // use zero, gcc complains dereferencing null pointer. // choose 16 rather other number in case compiler // confused unaligned pointer. #define google_protobuf_generated_message_field_offset(type, field) \ static_cast<int>( \ reinterpret_cast<const char*>( \ &reinterpre

html - How can I resize all photos to the same size? -

i have site: link but have following problem: problem what want is: 1. 2 images must have width of 33.3333% , middle image must remain is another of problems when resize browser,the middle image higher. css .inline-block{ display: inline-block; vertical-align: top; } .left-img,.right-img{ width: 33.3333%; } .left-img{ background: url("/wp-content/themes/wp_bagel/assets/img/img-01.png"); background-size: cover; } .ctr-img{ background: url("/wp-content/themes/wp_bagel/assets/img/img-02.png"); background-size: cover; } .right-img{ background: url("/wp-content/themes/wp_bagel/assets/img/img-03.png"); background-size: cover; } html <div class="left-img inline-block"> <img src="/wp-content/themes/wp_bagel/assets/img/img-01.png" alt="mountain view" style="visibility: hidden;"> </div> <div class="ctr-img inline-block"> <img src="/w

jquery - dynamically generated element appears lowly by using opacity and transition? (javascript, css) -

my goal create li element pressing button. element should appear slowly. want use css , javascript jquery. that's tried: $(document).on('click', '.add', function(){ var li = '<li style="transition: 10s; opacity: 0;"> content </li>'; $(li).appendto("ul"); $("li").last().css( "opacity", "1" ); }); sadly didn't work. reason delay has no effect on generated li item. need change? check out.. solve problem http://jsfiddle.net/tirthrajbarot/tfmfx/39/ html <button>click me</button> <ul id="mylist"> </ul> js: $('button').live('click', function() { $("#mylist").append("<li class='fade'>this test</li>") settimeout(function(){$(".fade").addclass("in");}, 0) }); css .fade.in { opacity:1;} .fade { opacity: 0; -webkit-transition: opac

nginx - HTTPS request URL by Captive-Portal in RPi3 Wireless Access Point -

i running media art project using rasp pi 3 wireless access point captive portal. redirect packets using iptables sinatra can request url sent device. the problem if user's request https website such facebook, google or others, packet can't read. so i've tried bulid reverse-porxy , change iptables' redirect target nginx server decoding request url under https following link: http://www.htpcguides.com/enforce-ssl-secure-nginx-reverse-proxy-linux/ this how change iptables sudo iptables -t nat -a prerouting -p tcp --dport 443 -j dnat --to-destination 127.0.0.1:443 sudo iptables -t nat -a prerouting -p tcp --dport 53 -j dnat --to-destination 127.0.0.1:53 sudo iptables -t nat -a prerouting -p tcp --dport 80 -j dnat --to-destination 192.168.0.1:4567 and how configue nginx: (port 4567 sinatra listened) server { listen 80; server_name 192.168.0.1 localhost; return 301 http://192.168.0.1:4567; access_log /var/log/nginx/backintime-

php - SugarCRM Field Calculation example of ifElse -

i new sugarcrm. have requirement calculate field value through studio. but, in 1 of fields comes in denominator can 0. so, want modify formula through ifelse, how that. example - if (field1>0){calcfield/field1} else(calcfield=0). you can use calculated field , if else this: ifelse(equal($status,"held"),1,0) for more information check link : calculated field in sugarcrm

php - Export to csv in wordpress and download -

i have table in database , want export csv click on export csv button. using wordpress , have custom table in database if(isset($_post['btnmonth'])){ $month = $_post['hidmonth']; $userid = $_post['hiduserid']; //$path = testing($month, $userid); $conn = mysql_connect('localhost', 'sensible_bps', 'inception1111'); mysql_select_db('sensible_bps', $conn); $filename = "toy_csv.csv"; $fp = fopen('php://output', 'w'); if($month == 'all'){ $query= "select * clientsdata client_id = '".$userid."'"; }else{ $query= "select * clientsdata client_id = '".$userid."' , month = '".$month."'"; } $result = mysql_query($query); while ($row = mysql_fetch_row($result)) { $header[] = $row[0]; } header('content-type: application/csv'); header(&

java - android databinding - cannot find class android.view.data -

i'm trying implement databinding in android app, i'm stuck issue: java.lang.classnotfoundexception: didn't find class "android.view.data" my layout file looks this: <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools"> <linearlayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.myapp.views.fragments.locationsearchfragment"> <!-- data setup --> <data> <variable name="location" type="com.myapp.models.address" /> </data> </linearlayout> </layout> i updated build.gradle file following lines: databinding { enabled = true } as documentation suggested: https://developer.android.com/topic/librar

ios - CGDataProviderCopyData builds up in memory causing crash -

okay, i'm downloading bunch of large-ish images (5mb) server in pieces, stitching pieces , rendering total image byte array. however, i've realized data each image not being released, , consequently builds causing memory warning , crash of app. thought because of explicit (__bridge_transfer nsdata *) casting arc take care of releasing object, it's still proving problem. in instruments, objects called "cgdataprovidercopydata" of ~ 1mb build , not discarded each file being stitched whole image. ideas or can steer me in right direction? obliged. // create array add files total image nsmutablearray *bytearray = [[nsmutablearray alloc] initwithcapacity:(imageheight * imagewidth)]; // iterate through each file in files array (nsstring *file in array) { // set baseurl individual file path nsstring *baseurl = [nsstring stringwithformat:@"http://xx.225.xxx.xxx%@",[imageinfo objectforkey:@"baseurl"]]; // specify imagepath ap

jquery - Selenium error with javascript file upload validation -

Image
i trying create functional tests using selenium (on django / python), javascript file validation brings error. site takes csv file input , presents bunch of graphics visualize csv data in different ways. using jquery validation plugin check csv file via 1) extension .csv, , 2) mime-type text/*. this validates fine manually when upload .csv file, when try upload same file in selenium, mime-type error. there way "set" file input's mime-type, or should have that? missing file uploading in selenium? know i'm not supposed click file button , sending full path using send_keys(). i haven't found similar questions on or google. every selenium mime-type question deals downloading files during test, instead of uploading files. thanks help! my selenium test code: file_input = self.browser.find_element_by_id('grade_file') file_input.send_keys('/<fullpath>/grades_deid.csv') grade_form = self.browser.find_element_by_tag_name('form')

sorting - Did I understand the following quicksort algorithm correctly? -

i'm trying understand given algorithm , here thoughts: a given array... x stands number on left side of pivot element, y stands number on right side of pivot element. (let's pivot element element on right side of array.) , a[y] stands pivot element? if understood correctly, algorithm first searches x towards y until first number greater or equal a[y] , search y towards x until first number smaller or equal a[y] . after, swap both numbers , repeat if i hasn't reached j . in end numbers left i smaller a[y] , numbers right j larger a[y] ... move a[y] middle. think this? right? maybe give example random array? cannot yet believe. algorithm quicksort 1 func int div (a array; x, y integer) { 2 num = a[y]; 3 = x; 4 j = y-1; 5 repeat 6 while (a[i] <= num , < y) 7 = i+1; 8 end while; 9 while (a[j] >= num , j > x) 10 j = j-1; 11 end while; 12 if < j 13 swap (a[i], a[j]); 14 en

sql - Multiple correlated subqueries with different conditions to same table -

i have 2 tables: orders | id | item_id | quantity | ordered_on | |----|---------|----------|------------| | 1 | 1 | 2 | 2016-03-09 | | 2 | 1 | 2 | 2016-03-12 | | 3 | 4 | 3 | 2016-03-15 | | 4 | 4 | 3 | 2016-03-13 | stocks | id | item_id | quantity | enter_on | expire_on | |----|---------|----------|------------|------------| | 1 | 1 | 10 | 2016-03-07 | 2016-03-10 | | 2 | 1 | 20 | 2016-03-11 | 2016-03-15 | | 3 | 1 | 20 | 2016-03-14 | 2016-03-17 | | 4 | 4 | 10 | 2016-03-14 | null | | 5 | 4 | 10 | 2016-03-12 | null | i'm trying create view show orders along closest stocks enter_on (i'm using include_after , include_before give overview on date want exclude item that's preordered, stock reflect correctly.) include_after going stock came in not expired yet, if expired, show null, include_before show next incoming stock enter_

How do I read the simpleXML object in php? -

<?php[![enter image description here][1]][1] $try = simplexml_load_file("https://www.theguardian.com/football/series/footballweekly/podcast.xml") ; echo "<pre>" ; print_r($try) ; echo "</pre>" ; then try echo $try->language or $try->item[0]->titel . nothing shows, how can access object? you're missing out 1 level of xml: $try->channel->language $try->channel->item[0]->title

Joomla PHP MySQL Query to use MySQL IF function -

so have joomla site , in joomla documentation can't find mysql's if, else function within query. the part of query need if statement in mysql here. $query->where($db->quotename('container').' != 1'); it should doing : $query->where('if '.$db->quotename('server_number').' != '.$number.' '$query->where($db->quotename('container').' != 1');' end'); if $number input not match server_number column data add statement mysql query. full mysql query : select a.*,ext.media_type database_hwdms_processes left join database_hwdms_media media on media.id = a.media_id left join database_hwdms_ext ext on ext.id = media.ext_id (a.status = 1 || a.status = 3) , a.attempts < 5 , `container` != 1 , server = 1 order a.media_id asc want add "if server_number != 1 container != 1 end" mean replacing "and container != 1" i figured out better way resolve problem

sql server 2008 - SQL Count in Where clause -

i'm trying find items have shown 1 time or less on report. know find how many times each item has apepared, use this. select count(vp.vendorpartid) purchasing.purchaseorder po (nolock) inner join dbo.tblvendor v (nolock) on po.vendorid=v.vendorid inner join purchasing.purchaseorderitem poi (nolock) on po.purchaseorderid=poi.purchaseorderid inner join purchasing.vendorpart vp (nolock) on poi.vendorpartid=vp.vendorpartid v.producttypeid=4 group po.purchaseorderid but tried nest within query able set must appear 1 time or less, , says there's error because "subquery returned more 1 value. not permitted when subquery follows =, !=, <, <= , >, >= or when subquery used expression." i did this, i'm guessing pretty wrong, haha. select vp.vendorpartid,vp.vendorpartdescription purchasing.purchaseorder po (nolock) inner join dbo.tblvendor v (nolock) on po.vendorid=v.vendorid inner join purc

python - How to get the Document Vector from Doc2Vec in gensim 0.11.1? -

is there way document vectors of unseen , seen documents doc2vec in gensim 0.11.1 version? for example, suppose trained model on 1000 thousand - can doc vector 1000 docs? is there way document vectors of unseen documents composed same vocabulary? for first bullet point, can in gensim 0.11.1 from gensim.models import doc2vec gensim.models.doc2vec import labeledsentence documents = [] documents.append( labeledsentence(words=[u'some', u'words', u'here'], labels=[u'sent_1']) ) documents.append( labeledsentence(words=[u'some', u'people', u'words', u'like'], labels=[u'sent_2']) ) documents.append( labeledsentence(words=[u'people', u'like', u'words'], labels=[u'sent_3']) ) model = doc2vec(size=10, window=8, min_count=0, workers=4) model.build_vocab(documents) model.train(documents) print(model[u'sent_3']) here sent_3 known sentence. for second bullet

ios - Why I am getting nil while unwrapping an Optional value when I eliminated all nil_s? -

hey have problem placing variables. how can use variables use lets in function "a" in function "b". in word use variables function "a" in function "b" i have function("a") set notification text: let sentence = textfield.text! + " beautiful text!" let firstword = sentence.characters.split(" ").first.map(string.init) localnotificationhelper.sharedinstance().schedulenotificationwithkey("sometext", title: "see options(left)", message: sentence, date: deadlinepicker.date, userinfo: userinfo) now gotta call firstword inside function("b") in variable here: let predicate = cncontact.predicateforcontactsmatchingname(firstword) i tried add first variables sentence , firstword in viewdidload , outside of class nothing. keep getting error "found nil while unwrapping" call function variable predicate when user tap notification action button this. nsnotificationcenter

python - How does the timeline_markers list work in Blender? -

i have following code: import bpy import math import random markers = [] marker in bpy.context.scene.timeline_markers: frame = marker.frame markers.extend([frame]) print('-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+') print(markers) markers = sorted(markers) print(markers) and when execute it, gives me 2 different output first print statement, before markers = sorted(markers) , after it. that's output: -+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ [33, 93, 151, 212, 265, 409, 640, 786, 524, 317] [33, 93, 151, 212, 265, 317, 409, 524, 640, 786] when cycle reads items in timeline_markers haven't in increasing order? but, assuming it's not this, how work? you assuming timeline_markers stored sorted list, not case. while presented python common list/array, stored internally blender linked list. if trace source code find use listbase defined in dna_listbase.h , impleme