Posts

Showing posts from September, 2011

Uploading Multiple Types of Files using Django Jquery File Upload -

when searching django jquery uploading library, came across one. https://github.com/alem/django-jfu it seems neat , useful. so, decided give shot , started read demo code. however, highlighted line of code hard understand. in file demo/photos/views.py class home( generic.templateview ): template_name = 'base.html' def get_context_data(self, **kwargs): context = super( home, self ).get_context_data( **kwargs ) **context['accepted_mime_types'] = ['image/*']** return context if want configure able upload both pictures (.jpg, .png, etc.) , .pdf files. how shall highlighted line modified? guess 1 context['accepted_mime_types'] = ['image/* text/plain'] is correct? on other hand, photo_upload_form.html shall changed from {% block js_opts %} sequentialuploads: true, acceptfiletypes: /(\.|\/)(png|gif|jpe?g)$/i {% endblock %} to {% block js_opts %} sequentialuploads: true, acceptfiletypes: /(\.|\/)(png|g

how to use python's any -

i feel confused code this[not written me]: version = any(func1(), func2()) # wrong, should any([func1(), func2()]) def func1(): if something: return 1 else: return none def func2(): if something: return 2 else: return 3 version must num. when [func1(), func2()] [1, none] , should return 1, when [none, 2] , should return 2, when [1, 2] , should return 1. so think it's wrong use any() in code, because any() return true or false . if rewirte logic using way, can not find graceful way pythoner. i want know whether any() can achieve logic, if not, how achieve gracefully? you can use or here. version = func1() or func2() make sure functions defined before trying call them. this works because or returns first true-like value or last value (if no value true-like) . , 'none' considered false-like in boolean context.

php - eloquent boot not firing only for one class -

i'm using eloquent project , delete articles. problem database complicated. there articles, have article_lvl1 , article_lvl1 have article_lvl2. when delete article event functions work fine : <?php namespace app\model; class article extends \illuminate\database\eloquent\model { public static function boot() { parent::boot(); // cause delete of product cascade children deleted static::deleting(function($article) { $article->articleniveau1()->delete(); $article->articleniveau2()->delete(); }); } public function articleniveau1() { return $this->hasmany('app\model\articleniveau1', 'id_article'); } public function articleniveau2() { return $this->hasmany('app\model\articleniveau2', 'id_article'); } protected $table = 'article'; public $timestamps = false; protected $primarykey = 'id_article'; } but article can have article_informations, can have article_date. pro

arrays - Java error: non-static method cannot be referenced from a static context -

i know common error noobs myself, can't seem read can understand. homework need create array of longs called numberlist. 1 of methods need complete called tostring, turns array string print. so in main method created blank numberlist object , tried running tostring() method on it. compiler says "non-static method tostring() cannot referenced static context". why!? secondly, created test array of longs want pass numberlist object. called array testexample , made arbitrary values. when write new numberlist(testexample); i more errors. why can not this? finally here's code. please ignore every method except main, constructors, , tostring. thank much public class numberlist implements java.util.collection { //instance stuff private long[] longarray; public static void main ( string[] args ) { long[] testexample; testexample = new long[3]; testexample[0] = 1; testexample[1] = 2; testexample[2] = 3; new numberlist();

python - Empty pdf file when saving figure to file using matplotlib -

i trying save figure pdf using matplot, python 2.7, , windows 7. can save figure .png , when try save .pd f, file blank. here example code: import numpy np import matplotlib.pyplot plt matplotlib.backends.backend_pdf import pdfpages x = [1, 2, 3, 4, 5] y = [6, 7, 8, 9, 10] linewidthplot = '2' linestyleplot = '-' markerplot = 'o' colorplot = 'b' xlabel = 'x' ylabel = 'y' title = 'x v y' # plot data using matplot. fig1 = plt.figure() ax1 = fig1.gca() line1, = plt.plot(x, y, linewidth=linewidthplot, linestyle=linestyleplot, marker=markerplot, color=colorplot) axisscale = 0.05 xmin = min(x) - (axisscale * (max(x) - min(x))) xmax = max(x) + (axisscale * (max(x) - min(x))) ymin = min(y) - (axisscale * (max(y) - min(y))) ymax = max(y) + (axisscale * (max(y) - min(y))) plt.axis([xmin, xmax, ymin, ymax]) ax1.ticklabel_format(useoffset=false) plt.grid() # add legend. first_legend = plt.legend([line1], ["d

Compound circle object in cytoscape.js -

Image
hello possible draw object attached cytoscape.js? it large circle 2 smaller ones. smaller ones should not move individually parent large circle? code appreciated. what you're describing not compound node behaviour. child node within parent, , parent nodes rectangular accommodate bounding box of children. you can implement whatever relationships , interactivity want on elements, using api. behaviour describe possible. you may find these references useful: http://js.cytoscape.org/#notation/compound-nodes http://js.cytoscape.org/#collection/position--dimensions/node.grabbable http://js.cytoscape.org/#collection/events/eles.on http://js.cytoscape.org/#events/collection-events

scala - Slick update return the updated object -

i'm trying have function return updated object after db runs update method on query right now, can't figure out how return object. function wrote using examples found, extend q.update(cat) return future[cat]. def update(id: long, cat: cat): future[unit] = db.run { val q = { c <- cats if c.id === id } yield c q.update(cat).map(_ => ()) } you should try following: def update(id: long, cat: cat): future[option[cat]] = db.run { cats.filter(_.id === id).update(cat).map { case 0 => none case _ => some(cat) } } you should return future[option[cat]] instead of future[cat] , because cat provided id might not exist (the update method returns 0 value then). violating integrity constraints result in failure of future .

How to unpack a nested list in python to sublists? -

assume list is: [ [1,2,3,4], [ [[5], [6]], [7] ]] after unpack, want [1,2,3,4], [5], [6], [7] how low time complexity? the linked duplicate flattens iterable completely. need slight tweak make process stop 1 step earlier: import collections def flattish(l): el in l: if isinstance(el, collections.iterable) , not isinstance(el, str): if any(isinstance(e, collections.iterable) e in el): sub in flattish(el): yield sub else: yield el else: yield [el] the any(... check if iterable contains iterables. flatten [1, [2, 3]] , leave [5] as-is. additionally, yield [el] ensures non-iterables contained in list , result list contains list s, of may have single element.

how to query full name with null values in MS Access? -

this code in ms access in giving full name null values lname last name fname first name mname middle name (change initial) x name extensions jr., sr., iii ect. this code. [lname] & ", " & [fname] & " " & iif(isnull([x]),"",([x]) & ", ") & " " & iif(isnull(left([mname],1)),"",(left([mname],1)) & ".") but when try mysql not give data. free edit or reconstruct code fit qualifications in mysql query. salamat, mabuhay

Excel Sum function - Don't return 0 if a range is blank -

i using excel 2013. using sum function find sum of range of cells. if entire range blank, 0 should displayed. help use count see if there numbers in range, e.g. =if(count(b1:b10),sum(b1:b10),"")

How to write true color random (java) -

this code: import java.awt.*; import java.util.random; import javax.swing.* public class graphspanetest { public static void main(string[] args) { myframe window = new myframe(); } } class myframe extends jframe { public myframe() { mypanel panel = new mypanel(); container cont = getcontentpane(); cont.add(panel); setbounds(100,100,500,500); setvisible(true); } } class mypanel extends jpanel { public void paintcomponent(graphics gr) { super.paintcomponent(gr); random ab = new random(); colors={color.blue, color.red, color.orange, color.pink}; //here error int colorsthis = ab.nextint(colors[colorthis]); //here error gr.setcolor(color.red); //i try it, does't work //and here error int a=1; while (a<10) { random b = new random(); gr.fillrect(b.nextint(900+1),b.nextint(900+1), b.nextint(50+1), b.nextint(50+1));

unix - why should I not use find optimizations? -

i read in manual , info pages sections optimization levels in find command , cannot understand why should not use aggressive optimization level. the relevant sentences found (from man find version 4.4.2 ): conversely, optimisations prove reliable, robust , effective may enabled @ lower optimisation levels on time. the findutils test suite runs tests on find @ each optimisation level , ensures result same. if understood well, it's proofing right behaviour of find through findutils but, test suit ensures otimization levels giving same result. you're missing sentence: the cost-based optimiser has fixed idea of how given test succeed. that means if have directory highly atypical contents (e.g. lot of named pipes , few "regular" files), optimizer may worsen performance of query (in case assuming -type f more succeed -type p when reverse true). in situation this, you're better off hand-optimizing it, possible @ -o1 or -o2 .

react-native init freezes while installing react native in windows 10? -

i have installed react-native-cli globally in windows 10 react native supports windows now.but when init new project freezes while installing react native. the react-native init process can time consuming because it's quietly installing react-native , dependencies, can take few minutes.

rest - Azure Media Player - display encoding progress or some sort message while encoding is in progress -

as know in azure media services encoding little long running task/job. enable feature on azure media player displays sort of message on azure media player. message maybe "this video being encoded" or "encoding in progress - 57%" etc. just wanted know if plugin or available requirement. i think work: if there no plugin or available, can status service calls origin azure media player js files. think work? since media service encoding job , have check status of job. may find link helpful checking status of job - https://azure.microsoft.com/en-us/documentation/articles/media-services-rest-check-job-progress/ .

KDB + query - Implement Not like -

i have use not operation in kdb + query not know how use it. able use operator i.e. http://kdbserver:8001/?select orderdetails symbol "x*" query gives results. how use/implement not same query ? select orderdetails not symbol "x*"

Creating a Kubernetes Service in Java -

i using fabric8.io orchestrate application containers in kubernetes. looking create service manages pod label on port. there specific example of api this. couldnt find in examples https://github.com/fabric8io/kubernetes-client/blob/master/kubernetes-examples/src/main/java/io/fabric8/kubernetes/examples/fullexample.java#l75 there dont seem javadocs available??? fabric8's kubernetes client using generated model , dsl has exact same structure as json , yaml configuration. so in order create service instance looks like: { "kind": "service", "apiversion": "v1", "metadata": { "name": "myservice" }, "spec": { "ports": [ { "protocol": "tcp", "port": 80, "targetport": 8080, } ], "selector": { "key": "val

sql server - Recommended tools to ETL data from Azure SQL Database to Azure SQL Data Warehouse? -

i have requirement build data warehouse using azure sql data warehouse, sourced data single azure sql database. looking @ this article , seems have 2 options: ssis azure data factory my azure sql database normalized, i'd build azure sql data warehouse in star or snowflake schema format, it's not straight copy of tables - there needs transformation happening. given ssis isn't supported on azure sql database , require me running vm sql server on keep processes entirely in azure, azure data factory recommended tool etl data between azure sql database , azure sql data warehouse? 1 choice vs. other more featured in situation? thank you! if looking keep processes entirely in cloud , not spin vm, azure data factory best option data movement. however, @ point in time might recommend elt approach on etl approach. loading data first , completing transformations within sql data warehouse loads quicker , able take advantage of additional compute power when tra

Apache Cordova: SQL windows authentication over VPN -

i super new hybrid architecture of cordova dev tool , not familiar architecture , capabilities of it. working on building app using cordova allow company users (internal) login , access it. our users use cisco anyconnect vpn mobile client on mobile devices. authenticate user connected vpn when login app. if vpn not enabled, app should error out sort of message. ideas or sample code appreciated. thanks!! is there resource can access when using vpn? i'd suggest in app make http request access resource, if they're using vpn it'll work otherwise won't work.

Not enough free space on external mounted NTFS disk on raspberry pi -

Image
i have enough free space on extenral mounted hard drive on pi. i trying copy 10gb of files , not enough free space message. if copy file 1 one have no problem. my sd card has 5gb of free space. read somewhere must have necessary space on sd if copy external drive. could true? additional info: part of mount command: /dev/sda1 on /media/xontros type fuseblk (rw,nosuid,nodev,relatime,user_id=0,group_id=0,default_permissions,allow_other,blksize=4096,uhelper=udisks) the problem automount in pi. mount point /media not proper mounting disks use regular. i edited /etc/fstab adding disk there , mounting in under /mnt , works fine.

c# - NEWID() SQL Server Function in Entity Framework -

i developing web application using angularjs , asp.net , entity framework , sql server database. i want insert rows using ef method : public string addrow(int captionid, string enlang) { string output = ""; try { var cap = new table_name(); string username = system.security.principal.windowsidentity.getcurrent().name; cap.codeid = captionid; cap.created = datetime.now; cap.createdby = username; cap.id = ""; cap.codelanguage = "en"; cap.codecountry = "gb"; cap.caption = enlang; _db.entry(cap).state = entitystate.added; _db.savechanges(); output = "created"; } catch (exception ex) { output = ex.innerexception.message; } return output; } this function works. but have question newid() function, have searched lot know how reproduce same didn't knew, i've looked thread nothing.

sql - Oracle Index is not used when compare timestamp with <= or >= -

i have indexes on 2 columns of type timestamp(2) start_date , end_date , query whare clause like: where c.start_date <= sysdate , sysdate <= c.end_date the explain plan makes table access full instead of index range scan. -if change <= = index used. -if change sysdate systimestamp it's worse in explain plan: sys_extract_utc(internal_function(c.start_date))<=sys_extract_utc(systimestamp(6)) with full scan again. -using to_timestamp brings desired index range scan: where c.start_date <= to_timestamp ('10-sep-02 14:10:10.123000', 'dd-mon-rr hh24:mi:ss.ff') , to_timestamp ('10-sep-02 14:10:10.123000', 'dd-mon-rr hh24:mi:ss.ff') <= c.end_date but need use current date. can explain why happens? edit: these simplified versions of query, same behavior appears. explain plans. explain plan select * communication c c.campaign_start_date <= sysdate , sysd

javascript - Selecting an element whose ID has a period in it -

this question has answer here: can't select div id=“:1” 2 answers i have element has period in it: <div id="parent"> <div id="my.element"></div> </div> and want select using prototype. i've tried this: $$('#parent #my.element'); but isn't working because thinks .element part class. there way around this? fyi, isn't option rename element. unfortunately i'm stuck naming scheme prototype thanks you can escape dot in css, should work $$('#parent #my\\.element'); edit: stated oriol , tested, indeed have use 2 slashes

c++ - classList array wont print output to the user -

so point of program ask student first name, how many classes they're taking semester, , asks names of each of classes. problem can't classlist array work , display class names user in program output. i've marked think issue coming , think super easy fix i'm not seeing it. help? i'm coding in microsoft visual studio 2013 way. #include <iostream> #include <string> using namespace std; class student { public: //public class student student(string first_name, string last_name, int num, string list); student(); void input(); //input user void output(); //output user depending on input // accessors const string get_name(); const int get_numclasses(); const string get_classlist(); // mutators void set_name(string name); void set_numclasses(int num); void set_classlist(string list); private: string name; int numclasses; string classlist; }; // constructor's variable student::

php - how I can call a function twig extension? -

i need call function in vendor (twig) bundle in src . need create function in twing extension ? if yes !! how can yes, need create twig extension. there nice , easy tutorial in symfony documentation .

html - How to trigger an onchange event in Firefox::Mechanize? -

i'm using firefox::mechanize scrape website. i'm stuck on dropdown menu has onchange event associated it. i'm able select option wanted pulldown menu, , i'm able verify because pulldown shows option selected. doesn't trigger onchange event associated it. i'm thinking might need "click" event after selecting option, i'm not sure how incorporate that. here bit of html: <select class="" id="select20279" name="20279" onchange="selectaction(this, this.options[this.selectedindex].value, '20279');"> <option value="">please choose</option> <option value="edit">edit</option> <option value="view">view</option> <option value="delete_now">delete</option> </select> here script: use www::mechanize::firefox; $mech = www::mechanize::firefox->new( tab => 'current', auto

qt - ssl sockets not supported error -

i'm running tornado webserver secure websocket connection on linux centos 6.6. i'm using qt/c++ client connect using qwebsocket opening url "wss://191.23.4.56/etr/job". i'm getting error like, " ssl sockets not supported in platform " error about? the error message "ssl sockets not supported in platform" printed qwebsocket::open() when url scheme wss , qsslsocket::supportsssl() returns false . the static member function qsslsocket::supportsssl() : returns true if platform supports ssl; otherwise, returns false. if platform doesn't support ssl, socket fail in connection phase. that main problem. need find out why qt thinks ssl not supported platform. if downloaded qt binary package function supportsssl() tries load required libraries libssl , libcrypto dynamically. if libraries cannot loaded function supportsssl() returns false . it possible libssl not installed in system. if can find library binari

javascript - KnockoutJS IF binding - keep DOM -

the if binding removes dom , stops executing inner data-bind attributes if condition false . is possible keep dom when condition false ? want stop executing data-bind when condition false not wish remove dom due jquery bindings etc. i came following solution delays knockout binding application until condition satisfied. it not remove binding when condition becomes false not necessary in case. ko.bindinghandlers['applywhen'] = { init: function() { return { controlsdescendantbindings: true }; }, update: function(element, valueaccessor, allbindings, model, bindingcontext) { if (!element.bindingapplied && boolean(ko.unwrap(valueaccessor()))) { element.bindingapplied = true; ko.applybindingstodescendants(bindingcontext, element); } } };

timezone - Java: getTimeZone without returning a default value -

i have following instruction: timezone zone = timezone.gettimezone("asia/toyo"); obviously, should return null, return default timezone, not desired behaviour case. java doc: returns specified timezone , or gmt zone if given id cannot understood. is there way corresponding timezone , null value if string not indicate valid timezone? i don't find solution timezones , iterate on them. instead of iterating use: boolean exists = arrays.aslist(timezone.getavailableids()).contains("asia/toyo"); or: boolean exists = arrays.stream(timezone.getavailableids()).anymatch("asia/toyo"::equals); if need often, putting available ids in hashset more efficient.

android - Logging in Retrofit 2.0 -

previous version of retrofit uses restadapter , has provision of enabling logs. why feature removed in retrofit 2.0 ? to enable log, have do.. retrofit retrofit = new retrofit.builder() .baseurl(base_url) .addconverterfactory(gsonconverterfactory.create()) .build(); /** handles log */ retrofit.client().interceptors().add(new logginginterceptor()); class logginginterceptor implements interceptor { @override public response intercept(interceptor.chain chain) throws ioexception { request request = chain.request(); long t1 = system.nanotime(); logger.d(string.format("sending request %s on %s%n%s", request.url(), chain.connection(), request.headers())); response response = chain.proceed(request); long t2 = system.nanotime(); logger.d(string.format("received response %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers())); // logger.d

Solr - Indexer causes java.lang.OutOfMemoryError: Java heap space -

i using solr index content search. when try (with 1 gb data , ram sizes 10 gb tomcat , solr), getting following error: java.lang.outofmemoryerror: requested array size exceeds vm limit @ java.util.arrays.copyof(unknown source) @ java.lang.abstractstringbuilder.expandcapacity(unknown source) @ java.lang.abstractstringbuilder.ensurecapacityinternal(unknown source) @ java.lang.abstractstringbuilder.append(unknown source) @ java.lang.stringbuffer.append(unknown source) @ java.io.stringwriter.write(unknown source) @ org.apache.tika.sax.totextcontenthandler.characters(totextcontenthandler.java:93) @ org.apache.tika.sax.contenthandlerdecorator.characters(contenthandlerdecorator.java:146) @ org.apache.tika.sax.writeoutcontenthandler.characters(writeoutcontenthandler.java:136) @ org.apache.tika.sax.contenthandlerdecorator.characters(contenthandlerdecorator.java:146) @ org.apache.tika.sax.xpath.matchingcontenthandler.characters(matchingcontentha

delphi - Ide attempts to load package from a wrong location -

i've made little design package , installed in ide (delphi xe8). this package defines new kind of button used on intraweb forms. i've compiled , installed component, , tested test application. it works perfectly. then have big application, made of several packages belonging project group, in several pages use such new button. sometimes (not always), open project group of app, ide complains cannot find package.dcp, tries open desktop (c:\users\maurizio.ferreira\desktop\newbutton.dcp) instead of opening resides (c:\users\public\documents\embarcadero\studio\16.0\dcp\newbutton.dcp) when happens, have close projet group, reopen component project, build , reinstall it, close it, reopen project group. any suggestion ? !!!! i've found !!!! i had package (newbutton.pkg) same name of unit (newbutton.pas) contained in package. (this should forbidden, or, @ least, raise warning). this confuses ide when open project uses such component. i solved prob

php - CakePHP 3.0 - Post Link - adding classes removes alert confirmation functionality -

when add class array postlink, confirm alert stops working. have moved class array different positions within postlink nothing seems work. <?= $this->form->postlink(__('delete'), ['controller' => '<%= $details['controller'] %>', 'action' => 'delete', <%= $otherpk %>], ['class' => 'btn btn-danger btn-sm'], ['confirm' => __('are sure want delete # {0}?', <%= $otherpk %>)]) %> the above code add right classes link, confirmation doesn't work, deletes entry right away. the confirm message , other html options class go in same array <?= $this->form->postlink(__('delete'), ['controller' => '<%= $details['controller'] %>', 'action' => 'delete', <%= $otherpk %>], ['class' => 'btn btn-danger btn-sm'],'confirm' => __('are sure want del

c# - Web.Api accept parameter form value -

i using web.api 2.2, client sending data in style: data={"kind": "conversation", "tags": [], "items": [{"body": "hi there", "timestamp": "1445958749.284379", "kind": "messagetooperator", "nickname": "united kingdom (rickmansworth) #5043", "visitor_nickname": "united kingdom (rickmansworth) #5043"}, {"body": "my name amel , testing olark", "timestamp": "1445958753.320339", "kind": "messagetooperator", "nickname": "united kingdom (rickmansworth) #5043", "visitor_nickname": "united kingdom (rickmansworth) #5043"}, {"body": "hi amel jessica", "timestamp": "1445958763.486881", "kind": "messagetovisitor", "nickname": "jessica wood ", "operatorid": "744399&q

html - Aligning Web Forms -

i have 2 forms want align. able figure out how align height, can't width work way want. in situation, want left box fill in remaining space. using 'auto' fills in space fit contents. instead of expanding form, there gap between 2 forms. the reason require have php around form. there flag dictates whether or not second form shows up. if there 1 form, want expand entire space. if there 2 forms, want them share space. the way thought of doing set right form specific width , have left form mold whether or not else exists. can't figure out how left form expand without specifying exact width. i've included html , css below jsfiddle reference . html <div class="section"> <div class="container"> <form> <fieldset class="left"> <legend>pc management</legend> <div> <input type='submit' value='backup

c# - Task.WaitAll hangs with async/await tasks -

i must missing obvious, deadlock on synchronizationcontext , not see why happens, , not understand how can avoid it... so, application azure workerrole (essentially, far understand, usual windows app without ui). in application, trying parallel execution of number of tasks, , schematic version of code this: private async task dojob() { await someiooperation(); } public void methodexecutedbyworkerroleinaninfiniteloop() { log("start"); task.waitall(dojob(), dojob(), dojob()); log("end"); } my idea here operating default synchronizationcontext here, should avoid deadlock have in similar situation in, example, asp.net. however, sometimes execution hangs - start logged, end not days until restart worker role. naturally,there no way dojob running long. oddly, not happen after worker role starts - may take days or weeks of normal operation until hangs. i simplifying code - maybe important happens in someiooperation - feel obvious related

Seeking a way to look up element names of a dimension to replace data in a cube, in Cognos TM1 -

my apologies if title sounds vague, here's situation. there's cube contains 5 dimensions. data contained in cube involves movie title codes classified under different categories. there's dimension - let's call dim, that's not part of cube, , contains movie title names elements. these title names have movie title codes alias. i'm looking match movie title codes data in cube movie titles in dimension dim , display movie title names, replacing movie title codes in cube. i figure can done using turbo integrator, appropriate dimension subset of dim data source. i'm not sure if it's technically possible extract elements dimension subset , use them populate cube based on conditions. there way using ti @ all? sort of appreciated. in advance! if you're trying think you're trying (and question isn't clearest 1 i've come across), you've got around wrong way. i'm assuming cube contains strings, , each cell contains movi

Nginx - Exclude php files from htpasswd on a specified directory -

my nginx directives: location / { index index.html index.php; auth_basic "members only"; auth_basic_user_file /var/www/clients/client1/web1/web/.htpasswd_stats; } location ~ \.php$ { allow 1.2.3.4; allow 127.0.0.1; deny all; auth_basic "members only"; auth_basic_user_file /var/www/clients/client1/web1/web/.htpasswd_stats; } location /dir/ { auth_basic off; } i use 'auth_basic off' option exclude 'dir' directory htpasswd check. when try acces http://domain/dir/ see files except php files because previous directive asking me authentication. on apache use 'satisfy any' option if use option on nginx, doesn't work me or put on incorrect site. my goal when access http://domain/dir/ there no authentication file. thanks!! this because have separate auth_basic .php files. to save .php files inside /dir/ add location block , set rules inside block according usecase locati

javascript - Understanding Ramda.js -

question 1: var _curry1 = function _curry1(fn) { return function f1(a) { if (arguments.length === 0) { return f1; } else if (a != null && a['@@functional/placeholder'] === true) { return f1; } else { return fn.apply(this, arguments); } }; }; what purpose of checking a['@@functional/placeholder'] === true ? question 2: http://ramdajs.com/0.18.0/docs/#reduce how read notation? (a,b -> a) -> -> [b] -> a this first time seeing such notation, come from? question 1: there no "notation". __.js should clear up: module.exports = {'@@functional/placeholder': true}; so @@functional/placeholder no different foo in a = { foo: true } a.foo a["foo"] (obviously, can't write a.@@functional/placeholder because of odd symbols there.) the intent seen in file: /** * special p

batch file - wmic output is empty when running from remote computer -

when running line locally i'm getting output file expected: wmic product name | more >"c:\temp\installlist.txt" but when trying run command remotely (using psexec running batch file on remote computer) file empty, although i'm using admin credentials. why? why using psexec. why don't specify computer, username , password wmic command. if credentials same local user on remote computer not need specify username , password. wmic /node:"computer" /user:myusername /password:"password" product name | more >"c:\temp\installlist.txt"

Fonts in rails 4.2.4 -

i want make rails application 'mostly mono' font (" http://www.1001fonts.com/mostlymono-font.html "), , tried asset pipeline method says here using fonts rails asset pipeline . i placed in config/application.rb config.assets.paths << rails.root.join("app", "assets", "fonts") and app/assets/stylesheets/application.css @font-face { font-family: 'mostlymono'; src: font-url('/assets/fonts/mostlymono.ttf') format('truetype'); } is there other method or doing wrong? you can use custom fonts bellow way - create folder name "fonts" inside app/assets directory , place mostlymono.ttf fonts inside fonts directory. now add line config/application.rb config.assets.paths << rails.root.join("app", "assets", "fonts") now have rename app/assets/stylesheets/application.css app/assets/stylesheets/application.css.scss , place bellow code- @font-face {

syntax - Compute mean within SPSS loop -

i need compute mean of set of ratings (var v_cr1 v_cr11) provided relevant control variable (var targ_i.1 targ_i.11) each rating satisfies condition (>=4 , not missing). at first attempted adjust syntax found http://stackoverflow.com/questions/12711613/loop-through-items-and-sum-items-in-spss/12794702 . this used: compute targ_vcs=0. execute. vector targ_i = targ_i.1 targ_i.11. vector targ_vc = v_cr1 v_cr11. loop #vecid = 1 11. if (targ_i(#vecid) <=4 , not missing (targ_vc((#vecid)))). compute targ_vcs= targ_vcs+ targ_vc(#vecid). end if. end loop. execute. it seems have worked provide me sum, although returns zeroes instead of missing when conditions not satisfied, can work around that. however, sum valid mean need count of valid v_cr satisfy targ_i. data has targ_i <=4 , not missing there missing v_cr (and other way around, accounted in above code), simple count won't do. i figure need either straightforward way compute mean within loop, way embed count in c

scala - Using the Parser API with nullable columns in Anorm 2.4 -

i'm struggling rid of deprecation warnings i've upgraded anorm 2.4. i've had @ how handle null in anorm didn't me enough. let's take simple example: account database table: id (bigint not null) email_address (varchar not null) first_name (varchar) last_name (varchar) i have 2 functions in scala code: getaccountofid , getaccountsoflastname . getaccountofid returns 0 or 1 account, therefore option[(long, string, option[string], option[string])] keep our example simple getaccountsoflastname returns list of accounts (which potentially have size of 0), therefore list[(long, string, option[string], string)] keep our example simple part of code of these 2 functions: def getaccountofid(id: long): option[(long, string, option[string], option[string])] = { db.withconnection { implicit c => val query = """select email_address, first_name, last_name account id = {id};""" /* rest of co

javascript - how to get the entire content of a JSON file in the console.log -

i have kind of weird question. my json looks this: var content = '{"content":[' + '{"value1": "0", "value2": "0", "value3": "20", "value4": "40", "value5": "string" },' + ... '{"value1": "0", "value2": "0", "value3": "20", "value4": "40", "value5": "string" }]}'; i wondering how content of json file "as is" displayed in console.log(); ? want exact json file. when var obj = json.parse(content); console.log(obj); or var obj = json.parse(content); console.log(obj.content); i this [object object] is there obj.all() or something? you don't parse json logged. a json is string. so only console.log(content);

parsing - Configure cultureInfo for Specflow -

i have 2 machines different cultures format mm/dd/yyyy parsed specflow (it's step argument) in 1 fails in other. i want tests culture independent. how configure specflow use cultureinfo.invariantculture parsing dates ? well, nobody answered this. solution problem edit app.config file , add <bindingculture name="en-us" /> in <specflow> config section. this forces specflow, on both machines, correctly parse mm/dd/yyyy date format.

windows - How to skip the procedure needed to press any key to exit the exe in batch file -

i'm writing batch file under windows , have executable(*.exe) perform tasks despite task needed have been done but seems executable has mechanism press key exit i can't proceed execute next line of batch file because need execute .bat other program automatically i need skip procedure execute whole .bat does have method this? it depends on how executable inputs keystroke. may impossible, might try 1 of following in batch file: *executable* < nul or echo x|*executable* (replace " *executable* " actual name of executable.)

c# - How to close Login form which is coded into Form1 then show another form? -

i have loginform coded mainform or form1, if inputed credentials correct directed form2 , loginform close, , form2 contains logout button, , if click logout button go loginform , input again credentials. i want close or not shown in taskbar icon loginform when i'm login, want see 1 icon not 2 icon in taskbar. note: loginform in form1, , form2 form. void btnlogin_click(object sender, eventargs e) { bool error = true; if ((txtuserlog.text.trim() == "") || (txtpasslog.text.trim() == "")) { messagebox.show("please fill fields!"); } cfgotcall.tether(settings); cfgotcall.engagequery("select * tblusers"); unitbl = cfgotcall.tbl; cfgotcall.untether(); (int = 0; < unitbl.rows.count; i++) { if ((unitbl.rows[i].itemarray.elementat(2).tostring().equals(txtuserlog.text, stringcomparison.ordinalignorecase)) && (unitbl.rows[i].ite

mysql - the diference Java Connection method (ClassForname & RegisterDriver) -

i know 2 ways connect database divided 2 methods (method1 , method 2) connection connection; public void getconnectionmethod1() { try { class.forname("net.sourceforge.jtds.jdbc.driver"); connection = drivermanager.getconnection("jdbc:jtds:sqlserver://localhost:1433/latihan","sa","denni"); } catch (sqlexception e) { } } public void getconnectionmethod2() { try { drivermanager.registerdriver(new net.sourceforge.jtds.jdbc.driver()); connection = drivermanager.getconnection("jdbc:jtds:sqlserver://localhost:1433/latihan","sa","denni"); } catch (sqlexception e) { } } my question is; there difference between them ? method 1 uses class.forname while method 2 uses registerdriver what advantages , disadvantages between them? note : can use preparedstatement on method 2. from jdbc 4.0,java developers no longer need explicitly load jdbc drivers using

applescript - Selecting POSIX file based on file name -

i'm having trouble accessing file while trying select on beginning characters basis... set location "/users/myuser/desktop/" set bom posix file (location & (first file of location name begins "thisfile")) tell application "preview" open bom is path/alias vs text type of thing? only system events , finder know file in file system is. finder has property desktop points desktop of current user. tell application "finder" set bom first file of desktop name begins "thisfile" tell application "preview" open (bom alias) or arbitrary posix path set location posix file "/users/myuser/desktop" text tell application "finder" set bom first file of folder location name begins "thisfile" tell application "preview" open (bom alias) the alias coercion needed because preview doesn't recognize finder file specifier objects.

c# - Select Validation Not Working ASP.NET MVC4 -

my select list data : list of strings public static class questionssecretes { public static readonly ilist<string> liste_questions_secretes = new list<string>() { "selectionner une question", "quelle était la couleur de votre première voiture ?", "quel est le nom de votre école primaire ?", "quel est le nom de votre premier animal de compagnie ?", "quel est votre plat préféré ?", "quelle était la marque de votre première voiture ?" , "quel est le nom de jeune fille de votre mère ?", "quel est le nom de votre commune de naissance ?", }; } viewmodel : annotation attribute [required(errormessage = "veuillez selectionner votre question secrete ")] public string questionsecrete { get; set; } i tried 1 : [stringl

java - Command Pattern basics -

suppose have file contents this, combination of config information , commands: server1 192.168.0.1 server2 192.168.0.12 file1 /home/user1/file1 upload file1 server1 ping server1 replicate server1 shutdown server1 the command pattern well-suited each of "upload", "ping", "replicate", , "shutdown" can represented command. however, still have few questions: 1. responsibility parse input? input file has necessary information files , servers are. parsing? client? receiver? invoker? 2. should parsed information stored? parsed information first 3 lines go in hashmap . according dzone's blog post , the receiver has knowledge of carry out request. so, guessing receiver 1 hashmap stored? 3. can commands return results? commands "ping" or "shutdown" should indicate happened after command executed. can these commands return values? whose responsibility parse input? each

android - How to draw two-direction traffic map in small two-way street like google traffic? -

i making app function same google traffic map. have been stuck below problem weeks i have used "snap roads" method of google api match gps data mobile device road while tracking routes of users. when display speed data, can not find solution draw 2 separated lines in 2 directions on small roads. does know how solution? please give me clue! google traffics bi-directional vector layers. roads api not return such data structure centered road vertices. 1 way fake 2 way lines create copy of snapped geometry , shift longitude 0.0001 - 0.001 every single point in line path. , apply styles.

How to restrict editing privileges in excel per user -

how can restrict editing privileges per user in shared excel workbook allows simultaneous using? example, how can share spreadsheet user, allow user edit column a? you select cells want have unprotected , right click. then select format cells then select protection tab , uncheck locked checkbox. click ok then go top , click on review ribbon click protect sheet enter password twice now person password can unlock , edit sheet. cells person can edit 'unprotected' earlier. default cells unchangeable once sheet protected. however excel doesn't have protection , can cracked. stop users editing protected items though.

android - populating RecyclerView from AsyncTask fails and results in empty Screen -

trying populate data recyclerview cloud, though output in main thread, takes time, decided add asynctask load items ease , insert progressdialog , seems code has no effect, getting empty screen. but asynctask getting executed, able log items in logcat, no idea why don't recyclerview. here code use , looking help: public class bigboard extends actionbaractivity { private list<person> persons; private recyclerview rv; private rvadapter adapter; private string a,b; private progressdialog pr; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); parse.initialize(this, "app-id", "client-key"); setcontentview(r.layout.activity_big_board); loader abc = new loader(); abc.execute(); adapter = new rvadapter(persons); rv=(recyclerview)findviewbyid(r.id.rv); linearlayoutmanager llm = new linearlayoutmanager(this); rv.setlayoutmanager(llm); rv.sethasfixedsize(true);

reactjs - Reload page if click to same path -

:) i'm trying reload browser (with location.reload(); ) if user click in <link> the same path, already. example: i have menu: - home - contact - when user click in 'contact', go '/contact'. in '/contact' , click in 'contact' in menu, page reload. it's possible this? what i'm trying: <link onclick={this.handleclick} to="contact">contact</link> handleclick(){ var currentroute = 'react-route path'; var linkroute = 'link path'; if (currentroute === linkroute) location.reload(); } else { //do default transition } } but don't figure need declare in 'currentroute' , 'linkroute'. :( you shouldn't reload page. thats bad idea. instead disable link this: if on home page links this <a href="/home" data-disabled="true">home</a> <a href="/contact" data-disabled="fals

ios - Swift: Custom UIView not resizing to constraints -

Image
i have created custom uiview loaded xib file. adding view stackview, , setting width constraint on item. it's working if storyboard, if i'm doing swift, can't view stretch constraint. stackview allocating space view, view doesn't stretch space. custom view swift code: import foundation import uikit @ibdesignable class tabbutton: uiview { @iboutlet weak var label: uilabel! @ibinspectable var tabtext: string? { { return label.text } set(tabtext) { label.text = tabtext label.sizetofit() } } override func intrinsiccontentsize() -> cgsize { return cgsize(width: uiviewnointrinsicmetric, height: uiviewnointrinsicmetric) } override init(frame: cgrect) { // 1. setup properties here // 2. call super.init(frame:) super.init(frame: frame) // 3. setup view .xib file xibsetup() } required init(coder adecoder: nscoder) { // 1. setup properties here // 2. call super.init(coder:) super.init