Posts

Showing posts from July, 2010

Creating xml using DOM in java -

i trying create xml multiple elements. below code trying. element root = doc.createelement("root"); doc.appendchild(root); element member = doc.createelement("member"); root.appendchild(member); element name = doc.createelement("name"); name.appendchild(doc.createtextnode("xxx")); member.appendchild(name); element phone = doc.createelement("phone"); phone.appendchild(doc.createtextnode("vvvv")); member.appendchild(phone); element sss = doc.createelement("somethingnew"); root.appendchild(sss); element nnn = doc.createelement("name1"); nnn.appendchild(doc.createtextnode("aaa")); sss.appendchild(nnn); element ppp = doc.createelement("phoneex"); ppp.appendchild(doc.createtextnode("cc&q

ruby - Rails Activerecord Ambiguous column name on .joins -

here code. work fine if have in :search field or if have in :supplier field if have in both "ambiguous column name 'number'". there way select or something? @date_from = params[:date_from] || date.today.beginning_of_month.strftime('%m/%d/%y') @date_to = params[:date_to] || date.today.strftime('%m/%d/%y') q = "%#{params[:search]}%" @products = product.where("discont = ? , nonproduct = ?" ,0,0) @products = @products.where('number ?' ,q) if params[:search].present? @products = @products.joins(:supplier_items).where('supplier = ?' ,params[:supplier]) if params[:supplier].present? @products = @products.paginate(page: params[:page], per_page: 25) just prefix number table name for example: @products = product.where(:discount => 0, :nonproduct => 0) @products = @products.where('products.number ?', query)

android - Setting facebook's profile picture as a LinearLayout background -

i have been trying no avail set facebooks profile picture linearlayout background in application. here 2 ways tried this: first way: got uri profile picture , converted drawable protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_profile); linearlayout banner = (linearlayout)findviewbyid(r.id.banner); profile profile = profile.getcurrentprofile(); if(profile != null){ // profile_pic_id.setprofileid((profile.getid())); drawable d; uri uri = profile.getlinkuri(); //also tried profile.getprofilepictureuri(random_num,random_num) try { inputstream inputstream = getcontentresolver().openinputstream(uri); d = drawable.createfromstream(inputstream, uri.tostring()); } catch (filenotfoundexception e) { d = getresources().getdrawable(r.drawable.blue_material);

php - Prevent opening page without login -

i have created webpage (lets call root main.php) , decided put login on top of (file index.php). login works fine, problem this. if type address of page (main.php) directly in browser, opened. there way prevent opening page unless go through login? in case relevant, login code: <!doctype html> <html > <head> <meta charset="utf-8"> <title>login</title> <link rel="stylesheet" href="/css/style.css"> </head> <body> <div class="login_container"> <div id="login-form"> <h3>login</h3> <fieldset> <form action="checklogin.php" method="post"> <input name="username" type="text" required placeholder="username"> <input name="passwo

android - Navigate via back-button from child fragment back to parent activity -

i have main activity , 2 fragments. in main activity have navigation drawer navigates through fragments. handle button pressed this: @override public void onbackpressed() { if (getfragmentmanager().getbackstackentrycount() > 0) { getfragmentmanager().popbackstackimmediate(); } else { super.onbackpressed(); } } after navigating between 2 fragments, when hit button, last fragment backstack. however, navigating fragment fragment should not possible. more clarity: i have 1 activity (with navigation drawer) , 2 fragments. navigation drawer can go both fragments many times want. when hit button, want go main_activity.xml . when navigate through activities, best way use intent s (if understood question): intent intent = new intent(this, mainactivity.class); startactivity(intent);

ruby - Two files are found in WATIR-Classic 3.0.0 but not in WATIR-Classic 3.7.0 -

i can find 2 files named 'testcase.rb' , 'assertions.rb' in watir-classic 3.0.0, 2 files not found in watir-classic 3.7.0. reason this? or found in other folder? in watir-classic 3.0.0 , testcase.rb , assertion.rb files define watir::testcase , watir::assertions classes. these classes provide subset of functionality found in test::unit . per commit , these files deleted in watir-classic 3.1.0 . since there number of feature-rich testing frameworks--from minitest rspec --there's no need include parallel framework in watir-classic gem.

Check if any form fields have changed upon saving asp.net c# -

i've got large .net form hundreds of input fields, users navigate off form page without saving, what's best way check if field value has changed when try navigate away? c# function or javascript? don't take control out of users hand :-) ask him on exit, if wants save changes. maybe did changes mistake, don't want save. you can achieve javascript/jquery. like: $(document).ready(function() { formmodified=0; $('form *').change(function(){ formmodified=1; }); window.onbeforeunload = confirmexit; function confirmexit() { if (formmodified == 1) { return "new information not saved. wish leave page?"; } } $("input[name='commit']").click(function() { formmodified = 0; }); });

Unable to connect to the remote server when using HttpClient on an Azure Website -

our application making http requests httpclient websites. in local work, unknown reason fails in production. our application azure website. we getting following error: unable connect remote server . we have ip based ssl certificate, our ip address not blacklisted anywhere. not happening before 3-4 days. depending on url call, work, not, don't why. update it seems happen when make requests website hosted godaddy, called support , our ip address not blocked. if isolated not godaddy issue, contact support on azure. might tech issue or networking issue. isolate source , fix it.

php - What is the difference between a public = $default and public = $test? -

i'm trying learn new going through cakephp's tutorials , in section link database.php mamp/sql, asks change information in array calls public $default . there public $test array in same file. what public $test array for? know can run page linking $default $test serve purpose? ie: class database_config { public $default = array( 'datasource' => 'database/mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'admin', 'password' => 'admin', 'database' => 'blog_tutorial', 'prefix' => '', //'encoding' => 'utf8', ); public $test = array( 'datasource' => 'database/mysql', 'persistent' => false, 'host' => 'localhost', 'login' => 'admin',

How to increment global variable from function in python -

i'm stuck simple increment function like from numpy import * pylab import * ## setup parameters , state variables t = 1000 # total time simulate (msec) dt = 1 # simulation time step (msec) time = arange(0, t+dt, dt) # time array vr = -70 #reset el = -70 ## lif properties vm = zeros(len(time)) # potential (v) trace on time rm = 10 # resistance (mohm) tau_m = 10 # time constant (msec) vth = -40 # spike threshold (v) ## input stimulus = 3.1 # input current (na) vm[0] = -70 fr = 0 ## iterate on each time step def func(ie, vm, fr): i, t in enumerate(time): if == 0: vm[i] = -70 else: vm[i] = vm[i-1] + (el- vm[i-1] + ie*rm) / tau_m * dt if vm[i] >= vth: fr += 1 vm[i] = el return ie = 3.1 func( ie

javascript - Strange bug with date input and angular -

i'm working on angular based app , have strange bug.. when use: <input type="date" ng-model="date"> the $scope.date has 1 day delay... when try run attachment code prints date have selected 1 day delay :( can do?! thank :) var app = angular.module('app', []); app.controller('ctrl', ['$scope', function($scope){ }]) <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <body ng-app="app"> <body ng-controller="ctrl"> <input type="date" ng-model="date"> {{ date }} </body> </body> i think similar issue : jquery datepicker off 1 day i have solved using momentjs library. provides lots of time-zone methods. moment.utc([year, month, day])._d

linux - script doesn't start on boot with init -

i have following script #!/bin/sh # chkconfig: 345 99 01 # description: startup script ### begin init info # provides: weblogic # required-start: $local_fs $network $remote_fs # required-stop: $local_fs $network $remote_fs # default-start: 2 3 4 5 # default-stop: 0 1 6 # short-description: start , stop ourdb # description: ourdb fast , reliable database # engine used illustrating init scripts ### end init info . /etc/rc.d/init.d/function service=startweblogic.sh user=******* password=****** dbschemaname=****** hostname=******* port=******** weblogic_start() { pgrep -f startweblogic.sh > /dev/null if ! [ $? -eq 0 ]; echo "exit" | sqlplus -l "$user/$password@(description=(address=(protocol=tcp)(host=$hostname)(port=$port))(connect_data=(sid=$dbschemaname)))" | grep "connected to" > /dev/null if [ $? -eq 0 ]; /home/usr/orac

angularjs - What should i do to put data from the controller in a directive? -

i've scenario: 1) user clicks on link , request sent (from controller) backend create db record. 2) response returned promise in controller , able see data db. 3) link clicked in #1 opens directive (element directive btw) displays popup window. 4) controller , directive not related, need show data in popup (opened directive). i'm new ajs , knowledge smattering. should use service/rootscope? send data promise directive. it sounds main question how data directive. can think of 2 ways (there more). you can use directive's isolate scope pass in information controller. have few options binding scope (see scope section of $compile ). = two-way binding or & expression binding & . might like app.directive('mydirective', [ function() { restrict: 'e', templateurl: 'some template url', scope: { databaserow: '=' } } ]) which used in html <my-directi

javascript - NodeJS + PhantomJS + phantomJS-node + JQuery + click a link is not working -

i tried use phantomjs(v1.9.8) module ( https://www.npmjs.com/package/phantom ) node.js goal display current url , navigate programatically clicking next link using jquery. im unsuccessful in clicking next link. tried doing hard way via document no avail. kindly point me right direction on how this. code: var phantom = require('phantom'); function scrape(keyword) { phantom.create("", {}, function(ph) { console.log("phantom bridge initiated"); ph.createpage(function(page) { page.set("settings.javascriptenabled", true, function() { console.log("...enabling javascript"); }); page.set("settings.useragent", "mozilla/5.0 (x11; linux x86_64) applewebkit/537.36 (khtml, gecko) chrome/41.0.2227.0 safari/537.36", function() { console.log("...setting user agent"); }); function traverse_

PHP mail() - Exchange 2003 doesn't receive email -

i have php mail() script sends html email contains embedded images. the code this: mail($to, $subject, $message, $headers); the headers so: mime-version: 1.0 content-type: multipart/mixed; boundary="--a9cf4407bac7d49ebd2d94af284cb0d8" from: myname <name@domain.co.uk> reply-to: name@domain.co.uk the email delivers fine outlook.com , gmail.com addresses. i've tested when sent our office runs microsoft exchange 2003 email doesn't deliver. doesn't reach logs baffles me. exchange isn't blocking email, isn't receiving it. is there known php / exchange 2003 conflict? or issue elsewhere? i'm happy supply more code if needed. you seem using php's native mail function. cumbersome configure , troubleshoot. you may save lot of time looking phpmailer or swift mailer. these libraries maintained , fixed stay compatible exchange , other systems. also, exchange may easier set email account on , let application use it.

Chrome extension open new tab on new tab -

Image
i have created chrome extension that, part of it's operation, opens new tab specified url. chrome.runtime.onmessage.addlistener( function(request, sender, sendresponse) { if( request.message === "open_new_tab" ) { chrome.tabs.create({"url": request.url}); } } ); (full code available on github ) this works fine on tabs webpages, cannot work on empty tabs, example: chrome://apps/ clarify, if have tab open , on stackoverflow.com, when click on extension button opens new tab loading generated url. when on new tab, or tab url begins chrome:// extension not work. what permissions need include allow extension open in tab? including new tabs , chrome:// tab? manifest.json: { "manifest_version": 2, "name": "myminicity checker", "short_name": "myminicity checker", "description": "checks city needs , redirects browser accordingly.", "version": &

ios - ComponentKit how push view controllers CKComponentController -

hi stated use componentkit library given facebook , have been going through documentation not find how use ckcomponentcontroller class. like how push view controller , navigation of various view controllers. if of aware of how use ckcomponentcontroller please let me know i'm bit stuck due less documentation thank you. imran. our usual approach pass object weak reference navigation controller "context" object passed top-level component. be sure it's weak reference or you'll end retain cycle! as accessing in component controller, expose context object property on component , read property off of self.component .

javascript - Chrome issue, mousewheel scrolling iframes -

i've been searching on internet success, appreciate if can me. my problem is, seems last google chrome version has created bug/or not scrolling using mousewheel. try explain issue in better way. case scenario: i have page with iframe , iframe has vertical scroll , parent window too. in past when start scrolling inside iframe , when reach end/top scrolling continues parent window , behavior has change when reach end/top scrolling stops... anyone has idea that? bug? configuration? can codding? thank all! new versions of different browsers not support iframe properly. focus oriented. scrolls part of page on mouse cursor , if want scroll parent page change cursor focus. posts of linkedin go this.

django - Recent values in CharField -

i have model class mod(model): f = charfield(max_length=10) and form: class modform(modelform): class meta: model = mod fields = ('f',) when display form user want suggest dropdown mod.objects.all() values of 'f'. how in simplest way? tried specify widgets = {'f': select}, not editable. can use selectize.js make selectable preloading ajax values, seems long way. models.py class mod(models.model): choice_1 = 'choice 1' choice_2 = 'choice 2' field_choices = ( (choice_1, 'the real charfield value'), (choice_2, 'another charfield value') ) f = models.charfield( max_length=10, choices=field_choices, default=choice_1 ) forms.py class modform(modelform): class meta: model = mod fields = ('f',) end of views.py return render(request, 'template.html', context={'mod_form': mod_form}) template.html {{mod

android - How to open List view in a specific place of activity? -

Image
i want open list view bottom of screen little high of middle of screen. have no idea how it. have idea it done fragment , not know how use in current activity , xml want shown in following picture : i hope question quite clear. know how implement list view not know ho implement in way wanted (i mean appear , disappear out disturbing other views). list should overlay other views. edit including xml file if can see have done in design <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <framelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <imageview android:layout_width="match_parent" android:l

ios - screen orientation issues in phonegap -

i have been using phonegap build. have encountered need run app in portrait mode phones , in landscape mode on tablets (same app - different orientations),from config files see there no such distinction available. pg has ability this?is available in pgb. there soluction this? using below code fixed issues var devicetype = (navigator.useragent.match(/ipad/i)) == "ipad" ? "ipad" : (navigator.useragent.match(/iphone/i)) == "iphone" ? "iphone" : (navigator.useragent.match(/android/i)) == "android" ? "android" : (navigator.useragent.match(/blackberry/i)) == "blackberry" ? "blackberry" : "null"; if(devicetype=='ipad') { screen.lockorientation('landscape'); } if(devicetype=='iphone') { screen.lockorientation('portrait'); }

interface - C++ multiple data sources within class -

i wonder how 1 go adding different data sources existing code. example, let's have piece of code: //datafromfile.cpp #include "data.h" class datafromfile { public: datafromfile() { filename = ""; } ~datafromfile() { delete data; } void loadvalue(const char *filename) { //getting data file } void printdata() { data->printdata(); } private: string filename; data *data; }; //source.cpp #include <iostream> #include "datafromparameter.h" int main(int argc, char **argv) { datafromfile olddata; olddata.loadvalue("example.txt"); olddata.printdata(); return 0; } and need create class datafromdatabase or datafromparameter without changing way datafromfile works (this code used throughout various programs , going through code out of question). creating interface seemed way go, came solution: //idata.h #include "data.h" class idata { public: idata() { data = null; } virt

c++ - Passing pointers to different variable types to a function and reuse them later for assignmet -

in gui based project need page1 mark variable to changed , call page2, page2 reads user's input , updates marked variable new value. variable type different , variables held external linked library. how achieve without creating fname_uint8, fname_uint16, fname_giventype variants markers , setters? this example sums scenario: there varholder class holds lot of structs lot of variables, e.g.: class varholder { public: typedef struct { int8_t var1; int16_t var2; int32_t var3; char str1[40]; float var4; } struct1_t; /* ...continues... */ struct1_t struct1; } now class firststage wants mark 1 variable change, , calls member of committer_instance instance of class committer class firststage { /* ... */ void dofirststage(void) { /* globally defined committer instance */ g_committer_instance->mark_var_change(&varholder_instance->struct1.var1); } } committer::mark_var_chang

Itextsharp Generate PDF document with Portrait and Landscape -

i using itextsharp generate pdf document. currently, html contents converted pdf document. default page orientation portrait. however, requirement is create pdf document page in portrait , in landscape. the following line generates pdf document portrait orientation document.setpagesize(pagesize.a4); and, if change line creates whole document in landscape. document.setpagesize(pagesize.a4.rotate()); how can generate pdf mixed portrait , landscape orientation? kindly advise. you have need. method using correct one. can use more once, aware of fact need change page size before new page created: document document = new document(); pdfwriter.getinstance(document, new system.io.filestream(filename, system.io.filemode.create)); document.setpagesize(pagesize.a4); document.open(); document.add(new paragraph("hi in portrait")); document.setpagesize(pagesize.a4.rotate()); document.newpage(); document.add(new paragraph("hi in landscape"

ios - [__NSCFNumber length]: unrecognized selector sent to instance with NSUserDefaults -

i creating 1 app in saving array of custom object in nsuserdefaults using below code : [util setsubproductsarraypreference:myarray forkey:productid]; //util.m +(void)setsubproductsarraypreference:(nsmutablearray *)subproducts forkey:(nsstring *)string { (int i=0; i<subproducts.count; i++) { subproducts *po=[subproducts objectatindex:i]; nsstring *st=[nsstring stringwithformat:@"%d",i]; [util setsubproductspreference:po forkey:st]; } nsuserdefaults *prefs = [nsuserdefaults standarduserdefaults]; nsdata *myencodedobject = [nskeyedarchiver archiveddatawithrootobject:subproducts]; [prefs setobject:myencodedobject forkey:string]; [prefs synchronize]; } +(void)setsubproductspreference:(subproducts *)subproducts forkey:(nsstring *)key { nsuserdefaults *prefs = [nsuserdefaults standarduserdefaults]; nsdata *myencodedobject = [nskeyedarchiver archiveddatawithrootobject:subproducts]; [prefs setobject:myencoded

C - Nary Tree: error while appending a new child to the tree -

i'm developing nary tree in c using structure this: typedef struct snarynode { int *data; // point node ’s data int n; // number of children struct snarynode **child; // child list } narynode; typedef narynode narytree; i can't use list (as required project). i'm able create tree, when try append new child tree, "data" value of tree overwrited new value. example: create root data = 1 , want append new child data = 2 , @ end both root , new child have same "data" value, data = 2 . think problem not due mistake pointers management, since don't know i'm wrong, decided ask opinion. here full code: lm_array2.h #ifndef lm_array2_h #define lm_array2_h typedef struct snarynode { int *data; // point node ’s data int n; // number of children struct snarynode **child; // child list } narynode; typedef narynode narytree; typedef void (*datafreefunc) (const void *); void printarraytree (narytree*); narytree *

javascript - 2 AngularJS apps on the same website, multiple pages -

i trying implement this angularjs/bootstrap typeahead app , use angularjs search functionality well. have typeahead implemented , working, can not seem figure out how implement 2 angularjs apps on same website...? the first comment helped because didn't understand angularjs, learning @ time. first comment helped realize misunderstanding , gave "light bulb" moment of having 2 separate modules include functionality needed. angularjs - being modular - great! can build capable apps using it.

c++ - Does a shared variable have a default lock? -

i have program iterating through vector of objects , applying function each element of vector. comparison between each of elements follows: #pragma omp parallel shared(i, myvector) for(i = 0 ; < myvector.size() ; i++) { for(int j = + 1 ; j < bdd.size() ; j++) { myvector[i]->compare(*myvector[j]); // } } i not modify vector. add value in attribute of each object element. therefore, think not need locks use. here problem : using several threads (tested 1 8 threads) not speed process. wondering if fact myvector shared variable automatically lock variable cannot used several threads @ same time.

javascript - Getting variables from a Bootstrap slider -

i have variable price range slider webshop. want echo value in php. code in test.php file: <script> var slidervalue = $('#output').val(); </script> <?php echo "<script>document.writeln(slidervalue);</script>"; ?> and code in bootstrap-slider.js file: $(function() { $("#pricelimit") .slider({}) .on('slide', function() { $('#output').html(this.value); }) .trigger('slide'); }); and code of slider itself: <input id="pricelimit" type="text" class="span2" value="" data-slider-min="10" data-slider-max="200" data-slider-step="5" data-slider-value="[20,100]"/> however, on page, says 'undefined'. going wrong here? first, make sure have included jquery library in test.php or if included in file, check if jquery included there too. then, rem

delphi - Crash.txt generated while sending mail from xampp php & Socket Error # 11001 -

following file generated while trying send email date/time : 2015-05-15, 15:00:18, 188ms computer name : gs-1459 user name : gs-1076 registered owner : gslab / hewlett-packard company operating system : windows 7 x64 service pack 1 build 7601 system language : english system time : 6 hours 11 minutes program time : 4 seconds processors : 4x intel(r) core(tm) i5-3470 cpu @ 3.20ghz physical memory : 5446/8080 mb (free/total) free disk space : (c:) 306.09 gb display mode : 1600x900, 32 bit process id : $a08 allocated memory : 23.68 mb command line : "c:\xampp\sendmail\sendmail.exe" -t executable : sendmail.exe exec. date/time : 2011-06-18 01:10 compiled : delphi 2006/07 madexcept version : 3.0l callstack crc : $fecf9b34, $3d6bf7f9, $3d6bf7f9 exception number : 1 exception class : eidsmtpreplyerror exception message : <https://accounts.google.com/continuesignin?sarp=1&scc=1&plt=akgnsbtf

Amazon IAM users signed URL's for access through CloudFront -

is possible create cloudfront signed url's users created in iam using access key , secret key? i can create them using root credentials not iam users because don't have .pem file private key. is there missing or possible? i've searched around can't find info has helped me. thanks the simple answer it's not possible. you have create cloudfront key-pair trusted signer. see details here ... http://docs.aws.amazon.com/amazoncloudfront/latest/developerguide/private-content-trusted-signers.html#private-content-creating-cloudfront-key-pairs

java - How to get HTML element properties on placing the cursor over it? -

is there way can properties of element on place cursor on? using javafx browser load websites. cannot use firebug or plugins. there possibility achieve this? please help. inspect element in firebug. in javascript, when "choose element" mode activated, can attach mouseover handler document. receive repeated calls mouse moves on elements. can tell element mouse on via target property on event object, e.g.: document.addeventlistener("mouseover", function(e) { // use e.target know element }, false); then @ element. might hook mouseout know when leave element. there limits this. instance, can't list of event handlers attached through normal dom api. here's simple example demonstrating handler: var lastelement = null; var display = document.getelementbyid("display"); document.addeventlistener("mouseover", function(e) { if (e.target != lastelement) { lastelement = e.target; show("tag",

java - change the display of a JXDATEPICKER -

i used jxdatepicker in jframe . but, date appears in following form: ven.15/10/2014 i want date appears in following format: yyyy-mm-dd thanks. you can use simpledateformat this: simpledateformat sf= new simpledateformat( "yyyy-mm-dd" ); res = sf.format(mydate);

javascript - My model doesn't bind on my checkbox -

this checkbox. have model there named selall. <input type="checkbox" ng-click="selectall(filteredtitles, cpportfolioitem)" ng-model="selall"> now have button needs remove checkmark on checkbox. <button class="btn-success btn " ng-click="updatetitlestatus(4)"> note have function on ng-click of button put $scope.sellall = false; inside function checkmark still there pressed it. how can uncheck checkbox? thanks. you can using following logic check , uncheck checkbox based on previous state $scope.selall = !$scope.selall in ng-click function of button here working plunker code http://embed.plnkr.co/mjognxot8p1oo9dcmuer/preview hope helps!!!!!!

How to draw boundary around the address based on latitude amd longitude in Google Map -

i have got drop down of state , cities . upon selection of state , corresponding cities displayed , once clicked on go button , showning particular city uisng google map. could please let me know if how posible show area around dashed or dotted lines ?? i see poly line doesn't suit requirement draws 1 line . right have got latitude , longitude obtained via $(document).on('click', '.gobtn', function(event) { $.getjson('https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '', function(data) { latitude_res = data.results[0].geometry.location.lat; longitude_res = data.results[0].geometry.location.lng; }).done(function() { }); }); this simple jsfiddle how showing map http://jsfiddle.net/zlutg/1010/ could please let me know how draw dashed / dotted around boundary of latitude amd longitude ?? how draw boundary around address based on latitude amd longitude if have way find b

How to set default argument value in F#? -

take function example: // sequence of random numbers open system let randomsequence m n= seq { let rng = new random() while true yield rng.next(m,n) } randomsequence 8 39 the randomsequence function takes 2 arguments: m, n . works fine normal function. set default m, n , example: (m = 1, n = 100) when there's no arguments given, function take default value. possible in f#? you can achieve same effect overloading discriminated union . here's suggestion based on op: type range = default | between of int * int let randomsequence range = let m, n = match range | default -> 1, 100 | between (min, max) -> min, max seq { let rng = new random() while true yield rng.next(m, n) } notice introduction of range discriminated union. here (fsi) examples of usage: > randomsequence (between(8, 39)) |> seq.take 10 |> seq.tolist;; val : int list =

How to make myself def class act as array in ruby? -

class heap attr_accessor :a, :heap_size def initialnize(a, heap_size) @a = @heap_size = heap_size end end = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1] = heap.new(a, a.length-1) what should do? can aceess 16 use a[i],etc. you can use inheritance: class heap < array attr_accessor :heap_size def initialize(a, heap_size) @heap_size = heap_size super(a) end end = [16, 14, 10, 8, 7, 9, 3, 2, 4, 1] heap = heap.new(a, a.length-1) heap[0] # => 16

winapi - How can I know the type of dc (Windows device context) with Windows API -

i got handle of dc (of type hdc ) under windows. can type of cd(memory dc, window dc ,printer etc.) windows apis? this in general not possible, , not necessary either. device context meant abstract underlying implementation. occasionally, however, helpful know, contents of device context displayed, adjust rendering, example. calling getdevicecaps nindex set technology retrieves information. doesn't allow discern between 4 device context types plus subtypes, though.

scala - playframework fall back configuration? -

how let playframework's configuration falls other configuration files if default 1 not exist. for example, default play use application.conf, if not exist, use c1.conf. if c1.conf not exist, uses c2.conf. i use play framework 2.3 in scala thanks. such feature doesn't exist in play framework. can specify file should used configuration passing 1 of possible properties startup script. available parameters described in documentation under section called specifying alternative configuration file . -dconfig.resource - allows choice file within application -dconfig.file - sets file outside of application -dconfig.url - uses file loaded given url if none of properties passed application, it'll use application.conf default one. to complete task, can write bash script verify whether script want run exists. if so, pass using 1 of aforementioned parameters or use different 1 otherwise.

Kafka consumer - how to add a topic -

in scenario, have n consumers (all consumers have 1 stream/no partitioning), each subscribed separate set of topics, how process new topics, added producers? should create new consumer each added topic? or can add topic working consumer? (how that?) or better keep 1 consumer group n consumers , not divide topics between n consumers(streams)? the initial config, described, topics devided between consumers of same consumer group not goood @ all. consumer not able fail=over each other, because have different lists of topics. kafka issue unnecessary rebalance. you need not add consumer each added topic - better consume such topics beginning, adding them common path /mytopics/* you better divide topics partitions , add new partitions if need. transparent , without effort.

c++ - GetModuleFileNameEx - Split output -

i trying process name process id, , i've use getmodulefilenameex , write function. char* processname(ulong_ptr processid) { char szbuffer[max_path+1]; handle hprocess = openprocess(process_query_information | process_vm_read | process_terminate, false, processid); if(getmodulefilenameex(hprocess, null, szbuffer, max_path) == 0) sprintf(szbuffer, "null"); closehandle(hprocess); return szbuffer; } the output full-path&process-name, , want split can process-name without full-path. is there way this, or other function can use process name process id? first: you're returning pointer local memory , going end in tears char* processname(ulong_ptr processid) { char szbuffer[max_path+1]; ... return szbuffer; } aside that, can use _splitpath_s() or filename path, or pathfindfilename function available on windows platforms shell api #include "windows.h" #include "psapi.h" #include "

python - How could i blink text in listbox -

this question has answer here: is possible colour specific item in listbox widget? 1 answer how make blinking text on listbox item import tkinter window = tkinter.tk() ncbox = tkinter.listbox(window, width=14, height=7, fg="blue", font=("helvetica", 20)) ncbox.grid(row=2, column=2,columnspan=4,sticky=nw) ncbox.insert("apple") ncbox.insert("banana") ncbox.insert("grape") now want blink apple on listbox. how that? you should try following if want iterate on lines in listbox. can't directly check string listbox. ncbox.get(first, last=none) if still doesn't work got to: http://www.tutorialspoint.com/python/tk_listbox.htm http://zetcode.com/gui/tkinter/widgets/ http://effbot.org/tkinterbook/listbox.htm

picasso - Android Image invalidate in fresco -

i migrating android image caching library picasso fresco. want know if there way invalidate image catched adding feature replace existing image there way in picasso like picasso.with(context).invalidate(uri); this line remove cached image , use new 1 using url provided same like, http://example.com/image_path in fresco have tried using fresco.getimagepipeline().evictfrommemorycache(uri); this removing image view adding same old cached image again , not getting new 1 network working in picasso. please refer question invalidate cache in picasso accepted answer doing great in case of picasso. fresco.getimagepipeline().evictfrommemorycache(uri); above code line remove image catche image remains there in disk , render same if called. need remove same image disk well. bellow 2 lines remove the image disc cache need remove small thumbnail image if saved disk cache. fresco.getimagepipelinefactory().getmaindiskstoragecache().remove(new simplecachekey(uri.tostri

makefile - GNU make is adding white space after -I (shared directory) option -

i'm trying use armclang compiler through gnu makefile, there clash between both tools when using -i option. for armclang compiler, -i means "adds specified directory list of places searched find included files.syntax -idir" without space. for gnu makefile ‘-i dir’ has same meaning (but space). in makefile have following: $(aarch32_bootobj): %.o: %.s @echo " [asm ] $<" @armclang --target=armv8a-arm-none-eabi -icommon/shared -c $< -o $@ when running makefile, i'm getting following warning , error : armclang: warning: argument unused during compilation: '-i common/shared' aarch32/shared/bootcode.s:32:10: error: not find include file 'boot_defs.hs' where boot_defs.hs exists under common/shared when running same armclang command outside makefile, works. therefore i'm assuming makefile has formatted -icommon/share option , added automatic space after -i. is there way run armclang command correctly?

color space - OpenCV Display Colored Cb Cr Channels -

Image
so understand how convert bgr image ycrcb format using cvtcolor() , seperate different channels using split() or mixchannels() in opencv. however, these channels displayed grayscale images cv_8uc1 mats. i display cb , cr channels in color barns image on wikipedia . found solution in matlab , how do in opencv? furthermore, mentioned solution displayed cb , cr channels "fills other channels constant value of 50%". question is: is common way display cr cb channels? or there recommendations or specifications when displaying cr cb channels? i made code scratch described in answer . looks it's need. mat bgr_image = imread("lena.png"); mat ycrcb_image; cvtcolor(bgr_image, ycrcb_image, cv_bgr2ycrcb); mat ycrcbchannels[3]; split(ycrcb_image, ycrcbchannels); mat half(ycrcbchannels[0].size(), ycrcbchannels[0].type(), 127); vector<mat> ychannels = { ycrcbchannels[0], half, half }; mat yplot; merge(ychannels, yplot); cvtcolor(yplot, yplot, cv

google maps - anchor tag not working in Desktop or Salesforce1 -

i displaying marker every near account , below anchor tag should navigate respective account upon clicking it.i have used code in workbook,but works neither in desktop nor in salesforce1.i have checked posts users reported redirection happening wrong page.but in case page refreshes , stays on same page.please help try{ if(sforce.one){ accountnavurl = 'javascript:sforce.one.navigatetosobject(\'' + account.id + '\')'; } } catch(err) { console.log(err); var did=account.id; accountnavurl= '\\' + account.id; } console.log('-->'+accountnavurl ); var content='<a href src="'+accountnavurl +'" >'+account.name+ '</a><br/>'+account.billingstreet +'<br/>' + account.billingcity +'<br/>' + account.billingcountry; below whole code <apex:page standardcontroller="account" ext

sql server - can dacpac be used for managing databases having large volume of data? -

our current database of 200mb, once application goes live, expecting grow large volume.. may be, 20-30 gb of data in that. we planning use "dacpac" (generated database project - ssdt) deploy on production server. database created number of tables, , lots of initial data in lookup tables. however, concern future deployments when using "dacpac" (generated database project - ssdt) upgrade database on production server. as have no past experience of using dacpac deployments, can please suggest me following - does deployment depend on volume of data? or if depends upon schema changes? example, if target database of 20-30 gb, how approximate time can take upgrade it? how can version database schema? can upgrade process rolled if goes wrong? and lastly, better traditional way of manual writing sql scripts upgrade database? from experience, volume of data have impact when deploying dacpac. time increase depend on changes being applied in dacpac a

java - Could not connect to SMTP host Permission denied: connect -

the email working in windows server 2008, when changed windows server 2012, causing error. systemexception: javax.mail.messagingexception: not connect smtp host: smtp.sendgrid.net, port: 25; nested exception is: java.net.socketexception: permission denied: connect i have googled , told -djava.net.preferipv4stack=true, put entry in jvm system property , asked disabled antivirus. both didn't worked. tried contacting isp open 25 port , 25 port listening. code. properties props = new properties(); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.host", smtp_host_name); props.put("mail.smtp.port", 25); props.put("mail.smtp.auth", "true"); smtpauthenticator auth = new smtpauthenticator(); session mailsession = session.getdefaultinstance(props, auth); mailsession.setdebug(true); transport transport = mailsession.gettransport(); mimemessage message = new mimemess