Posts

Showing posts from May, 2012

java - How do I use @Valid to validate local variables? -

this followup question here . how add @valid local variable? here code class authorizationserver : @notblank private string authorizationserverid; @property @indexed(unique = true) @notblank private string authorizationurl; @property(policy = pojomaticpolicy.to_string) @notblank private string clientauthorizationurl; @notblank private string devicerootcert; this controller: byte[] bytes = ioutils.tobytearray(request.getinputstream()); string signature = authorization.split(":")[1]; objectmapper mapper = objectmapper(); authorizationserver authorizationserver = mapper.readvalue(bytes, authorizationserver.class); how validate authorizationserver against annotations declared in authorizationserver class? when tried @valid authorizationserver authorizationserver = mapper.readvalue(bytes, authorizationserver.class); i got error @valid not applicable local variable . i think exception says all. bean validation not

security - Applets loading very slow on Java 8u 45 with stack overflow error while it works fine with Java 7 -

i getting stackoverflow error on java console while opening applets on network on java version 8 build 1.8.0_45-b15 . applet gets loaded takes around 8 minutes , same works fine in of java 7 versions on network . can please .. stacktrace follows . java.lang.stackoverflowerror @ java.security.accesscontroller.doprivileged(native method) @ sun.security.provider.policyfile.getpermissions(unknown source) @ sun.security.provider.policyfile.getpermissions(unknown source) @ sun.security.provider.policyfile.implies(unknown source) @ java.security.protectiondomain.implies(unknown source) @ java.security.accesscontrolcontext.checkpermission(u i have similar problem , finding. we using applet in firefox. current testing versions: firefox: 46.0.1 java: jre1.8.0_51 (32bit) i used jfr (java flight recorder) , oracle mission control analyse long hang (about 5s) on startup of our ui. my finding far method permissions.implies() takes extremely long unknown reason. my anal

I want to upload multiple image name in a same row using PHP MYSQL -

here code for ($i = 0; $i < count($_files["user_files"]["name"]); $i++) { // image mime type $image_mime = strtolower(image_type_to_mime_type(exif_imagetype($_files["user_files"]["tmp_name"][$i]))); if (in_array($image_mime, $valid_image_check)) { $foldername = "uploads/"; $ext = explode("/", strtolower($image_mime)); $ext = strtolower(end($ext)); $filename = rand(10000, 990000) . '_' . time() . '.' . $ext; // if user upload file abc,jpg, convert 291905_1399918178.jpg based on random number , time. $filepath = $foldername . $filename; if (!move_uploaded_file($_files["user_files"]["tmp_name"][$i], $filepath)) { echo "fail uplaod"; } else { $smsg .= "<strong>" . $_files["user_files"]["name"][$i] . "</strong> upl

Directly adding footer in JQuery DataTable -

i want directly add footer jquery datatable, body of table using dt.row.add() method. how possible without using footer callback method? thanks. datatables doesn't seem have api add footer dynamically, if that's want. checks presence of <tfoot> element during initialization only. to add footer dynamically: destroy table destroy() . $('#example').datatable().destroy(); append <tfoot><tr><th></th></tr></tfoot> <table> element making sure you're adding many <th></th> elements there columns in table. re-initialize table same options: $('#example').datatable({ /* options here */ });

css - HTML tags structure -

Image
i'm building webapp following structure : however, i'm not developping web, , know html tags should use enclose different sections of app. should use <header> tags header bar, <nav> menu, <aside> notifications , <article> body, or else? (i'd appreciate if can give me kind of skeleton this) i don't think standard way, recommend looking smacss -- scalable , modular architecture css. https://smacss.com/book/type-layout it's great philosophy on how organize , name css/html. following smacss, divide content based on header, footer, , article. whereas navigation child element of either header or article, can either choose use tag (if navigation remain constant throughout entire web structure), or if it'll flexible , changing, should stick labeling navigation class or id, , not use tag (this ensure can reuse css possible... read entire smacss article more on reusing css , further reading on oocss -- object oriented

javascript - Get templateUrl from ui-router -

maybe title isn't clear. i'm working on 2 nested angular apps. both have own router built ui-router . if call state unknown main router, i'd search state in sub-app router templateurl , url related state. i thought creating service parser. parse file find data want. solution not best option have, that's why wanted know if there specific function/method in ui-router achieve it. read on ui-router doc, seems not :/ feel free ask more details or suggest solution can match goal :) you can achieve using dynamic parameters in $stateprovider configuration defined on sub-module. have anchored routes on main module, , if there match, ui-router fetch associated template. if there no matched absolute route/url, ui-router falls on parameterised route, so: // anchored $stateprovider .state('mainappstate', { url: '/anchored', controller: 'myctrl' }) // sub module .state('subappstate', { url: /:parameter res

asp.net mvc 2 - MVC 2 - Images and CSS do not display on website -

i have 1 mvc2 site not display images , css or allow user login. other mvc 2 sites working fine , have exact same settings application pool. i'm using iis8.5 , windows server 2012 r2. application pool settings managed pipeline mode: integrated identity: application pool identity the website works correctly on own pc. does know how fix this? i got work. turned out duplicate mime types.

Is git add . no longer supported? -

this question has answer here: warning: ran 'git add' neither '-a (--all)' or '--ignore-removal' 2 answers i used git add . add all, tells me warning: ran 'git add' neither '-a (--all)' or '--ignore-removal', did git remove dot notation functionality? git add -a works. actually when used git add . not adding because ignoring deleted things have done (if have done any) if have deleted file , tried command , stay ,that's why should use git add -a because of time that's want (not sure) , if still wanna run command , git add --ignore-removal . can sure doing , because ignoring deletion have done , not staging .

c - Vectorization: aligned and unaligned arrays -

this question try more insights loop vectorization, particularly using openmp4. code given bellow generate 'size' random samples, these samples extract piece 'q' of 'qsize' samples position 'qpos'. program finds position of 'q' in 'samples' array. code: #include <float.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <mm_malloc.h> // simd size in floats, assuming 1 float = 4 bytes #define vec_size 8 #define align (vec_size*sizeof(float)) int main(int argc, char *argv[]) { if (argc!=4) { printf("usage: %s <size> <qsize> <qpos>",argv[0]); exit(1); } int size = atoi(argv[1]); int qsize = atoi(argv[2]); int qpos = atoi(argv[3]); assert(qsize < size); assert((qpos < size - qsize) && (qpos >= 0)); float *samples; float *q; samples = (float *) malloc(size*

c# - Clean alternatives to passing index by reference -

in code parsing array of bytes. sequentially parse bytes passing around index so: headerdata = parseheader(bytes, ref index) middledata = parsemiddle(bytes, ref index) taildata = parsetail (bytes, ref index) without hardcoding amount increment header, there way achieve similar functionality without having pass index reference? 1 of rare cases using ref keyword best solution? like slaks said, possible solution use stream. to create stream current bytes array can following: memorystream stream = new memorystream(bytes); to read current byte of stream can use readbyte method, shown below: byte b = stream.readbyte(); the stream keep track of current index in array, new code like: memorystream stream = new memorystream(bytes); headerdata = parseheader(stream) middledata = parsemiddle(stream) taildata = parsetail (stream) check out documentation see other methods available memorystream .

build - How to make up-to-date check notice non-file arguments in a Gradle Task? -

suppose have task class mytask reads input file, conversion on , writes output file ( build.gradle ): class mytask extends defaulttask { @inputfile file input @outputfile file output string conversion @taskaction void generate() { def content = input.text switch (conversion) { case "lower": content = content.tolowercase() break; case "upper": content = content.touppercase() break; } output.write content } } project.task(type: mytask, "mytask") { description = "convert input output based on conversion" input = file('input.txt') output = file('output.txt') conversion = "upper" } now works fine, when change input.txt or remove output.txt in file system executes again. problem it doesn't execute if change "upper" "lower" , wrong. i

sql server - Trying to format SQL query results -

Image
found query here on stack overflow found helpful pull table names , corresponding columns microsoft sql server enterprise edition (64-bit) 10.50.4286 sp2 database. select o.name, c.name sys.columns c join sys.objects o on o.object_id = c.object_id o.type = 'u' order o.name, c.name it produces table 2 columns this, each row has table name in column 01 , corressponding columns in column 02: what want this, 1 column each table name , tables columns listed below this: i've started doing manually in excel, on 5000 rows returned nice if there way format results in query this. in advance! as telling you, un-sql-y thing do. resultset have arbitrary number of columns (equal number of user tables in database, huge). since resultset must rectangular, have many rows maximum number of columns in of tables, many of values null . that said, straightforward dynamic pivot gets want: declare @columns nvarchar(max); declare @sql nvarchar(max);

java - JPQL Query a list of Strings inside an Entity -

i'm using java ee7 glassfish 4.1 server build system can post ideas, , each idea may have tags. i've declared entity idea as: @entity @table(name = "ideas") public class idea implements serializable { // id, description, etc. @elementcollection private list<string> tags; // getters, setter, etc. } after reading jpa: query embeddable list inside entity tried find tag following way: public list<idea> getideaswithtag(string tag) { string querystr = "select ideatags idea " + "inner join i.tags ideatags " + "where ideatags.tags = :ptag"; object res = em.createquery(querystr) .setparameter("ptag", tag) .getresultlist(); return (list<idea>) res; } but i'm getting transactionrolledbacklocalexception caused by: caused by: java.lang.illegalargumentexception: exception occurred while creating query in entitymanager: exception descriptio

java - How to start a web action from an imagebutton -

i trying develop android app have problems. know little bit java i'm perfect xml part. made imagebutton , want browser open url when user clicks on button. please explain me how step step? this button code taken main_activity.xml <imagebutton android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/donate" android:src="@drawable/donate" android:text="@string/about_link" android:autolink="all" android:layout_below="@+id/textview2" android:layout_centerhorizontal="true" /> please remember im not @ java copy , paste activitymain.java use on imgebutton click listner webview=(webview)findviewbyid(r.id.webview1); webview.loadurl("http://www.google.com");

javascript - trying to create ie9 friendly version of working code -

so have multipush menu great ... has js file can add classes of things pushed when menu activated, great... problem ie9 doesn't understand jquery plugin , trying create i.e9 snippet here original code ... $(document).ready(function(){ // html markup implementation, overlap mode $( '#menu' ).multilevelpushmenu({ containerstopush: [$( '.tile-area-title'), ( '.navbtn'), ( '.tile-area-main' ), ('#logo-title'), ('.submenu-ctn')], collapsed: true, // fun changing of menu wrapperclass: 'mlpm_w', menuinactiveclass: 'mlpm_inactive' }); this code .navbtn when clicked stuff works browsers... $(document).ready(function () { var $navtoggle = $('.nav-toggle'); $(".navbtn").click(function (e) { e.stoppropagation(); if($navtoggle.hasclass('active')){ $('#menu').multilevelpushmenu('collapse');

javascript - Understanding Protractor and WebDriverJS control flow -

can me understand how webdriverjs/protractor works in case? function mypageobject(buttonelementfinder) { this.getbuttonbyindex = function(index) { return { mybutton: buttonelementfinder.get(index) } } } 1. describe('my button', function() { 2. 3. it('should contain text foo', function() { 4. var myelementfinder = element.all(by.css('.foo')); 5. var pageobject = new mypageobject(myelementfinder); 6. var button = pageobject.getbuttonbyindex(0); 7. expect(button.text()).tobe('foo'); 8. }); 9. 10. }); does webdriverjs control flow have action added on line 6 because of .get method of elementfinder s? i presume expect adds item control flow on line 7? edit: have update code use element.all . var myelementfinder = element.all(by.css('.foo')); myelementfinder elementarrayfinder , object. nothing async happening here. var pageobject = new mypageobject(myelementfinder); obvious. var bu

java - Listener for log4j -

the question - there listener can catch event create new file in log4j? need output in every new file in beginning file system info system. i ovveride method createwriter of rollingfileaddapter class

batch file - How to answer the "Set /p choice" command on new line? -

code: @set /p choice= how you?(answer here) @echo %choice%? @pause desired output: @set /p choice= how you? (answer here) @echo %choice%? @pause yes, easy possible: @echo off echo how you? set /p "choice=" echo %choice%? pause

javascript - Access ng-model from one div to another div -

i want access ng-model value 1 div div. html: <div class="form-group" ng-repeat="key in condition.keys"> <select class="form-control" ng-show="key.aggregator" ng-model="key.aggregator" ng-options="field.name field.label (name, field) in aggregators"></select> <select class="form-control" ng-model="key.field" ng-options="s.field s.field s in subschema($parent.condition,$index)" ng-change="onfieldchange($parent.condition,$index)" required> <option value="">choose one</option> </select> </div> <div class="form-group mb-left">{{key.field}} <select class="form-control" ng-model="condition.operator" ng-options="field.name field.label (name, field) in fields | instancefilter :key.field :condition" required> <option value="">choose

python - Matplotlib density plot in polar coordinates? -

Image
i have array saved txt file has entries corresponding value of distribution in polar coordinates. looks this: f(r1,theta1) f(r1, theta2) ..... f(r1, theta_max) f(r2,theta1) f(r2, theta2) ..... . . . . . . . f(r_max,theta1) .................f(r_max, theta_max) i want density plot of f (the higher f is, more red want color be). there way matplotlib? explicit code helpful, majorly new this. in example, a theta1...thetan, b r1...rn, c f(a, b): #fake data: = np.linspace(0,2*np.pi,50) b = np.linspace(0,1,50) a, b = np.meshgrid(a, b) c = np.random.random(a.shape) #actual plotting import matplotlib.cm cm ax = plt.subplot(111, polar=true) ax.set_yticklabels([]) ctf = ax.contourf(a, b, c, cmap=cm.jet) plt.colorbar(ctf) essentially filled contour plot in polar axis. can specify alternative colormap cmap=... . cm.jet goes blue red, red bei

Parsing the nested JSON Array using Jackson library in java -

i know how parse following json using jackson library in java construct uri http://api.statdns.com/google.com/cname { "status": { "status": 200, "msg": "success" }, "apicalls": [ { "api": { "method": "get", "success": "200", "baseurl": "http://api.statdns.com/", "param1": "google.com/", "param2": "cname", "continue_on_fail": "1", "add_header2": "'accept', 'application/json'", "add_header1": "'content-type', 'application/json'", "client_id": "101" }, "id": 1385 } ] } i have wr

ios - NSDateComponentsFormatter Units Separator -

i want convert time in minutes user friendly string. following code resolves issue, except 1 thing - want result 1 hr 30 min , got 1 hr, 30 min . how specify units separator nsdatecomponentsformatter? of course, can remove commas manually, isn't looks best way me. nsdatecomponentsformatter *formatter = [[nsdatecomponentsformatter alloc] init]; formatter.allowedunits = nscalendarunitday | nscalendarunithour | nscalendarunitminute; formatter.unitsstyle = nsdatecomponentsformatterunitsstyleshort; nslog(@"%@", [formatter stringfromtimeinterval:90*60]); if application targeting os x 10.12 (or later, presume) or ios 10.10 (or later), apple added new units style called "nsdatecomponentsformatterunitsstylebrief" formatter.unitsstyle = nsdatecomponentsformatterunitsstylebrief and print out "1 hr 30 min" https://developer.apple.com/reference/foundation/nsdatecomponentsformatterunitsstyle/nsdatecomponentsformatterunitsstylebr

java - Hibernate JPA check for a conflict when generating IDs -

i using postgresql database table may have inserts id set manually user, or need id generated using hibernate. this may lead occurrence of generating id has been inserted database manually. there way hibernate can check collisions between generated id , existing ids? hibernate cannot check that, because sequence allocated database. either: assign negative numbers manually inserted ids use uuid instead of sequences

grep - Skip git commits with a specific string using git log -

this question has answer here: how invert `git log --grep=<pattern>` or how show git logs don't match pattern 8 answers i take latest 5 commits using git log not contain specific string, example "merge branch". i tried several options, none of them worked. e.g.: git log -n 5 --grep="merge branch" --invert-grep git log -n 5 -v --grep="merge branch" git log -n 5 --not --grep="merge branch" it seems --invert-grep job doesn't work ( http://git-scm.com/docs/git-log ) if you're trying non-merge-commits, can use: git log -n 5 --no-merges this will, of course, skip merge commits don't contain "merge branch" in log message.

Can not replace the content of a csv file in Go -

i have created csv file (assume "output.csv") using os.openfile flags, os.create , os.rdwr . i'm doing series of operations on file. in every iteration, need rewrite contents of csv file ("output.csv"). code appends csv file. before each rewrite , truncate file , seek beginning. example: package main import ( "fmt" "os" ) func main() { if f, err := os.create("test.csv"); err == nil { defer f.close() n := 10; n > 0; n-- { f.truncate(0) // comment or uncomment f.seek(0, 0) // these lines see difference := 0; < n; i++ { f.writestring(fmt.sprintf("%d\n", i)) } } } else { fmt.println(err) } }

c# - Second Enemy object not acting like the first enemy -

how come when add new enemy object list of objects loaded game, second 1 doesn't move around screen first one? objlist code class items { public static list<obj> objlist = new list<obj>(); public static void initialize() { objlist.add(new player(new vector2(50, 50))); objlist.add(new enemy(new vector2(500, 500))); objlist.add(new enemy(new vector2(600, 200))); objlist.add(new blueball(new vector2(300, 400))); objlist.add(new greenball(new vector2(350, 100))); objlist.add(new orangeball(new vector2(900, 250))); objlist.add(new pinkball(new vector2(100, 500))); objlist.add(new redball(new vector2(600, 500))); objlist.add(new yellowball(new vector2(500, 250))); } the third entry in list second enemy wish load game. first 1 works should second enemy doesn't move around screen first. below enemy class movement code. enemy class class enemy : obj { float spd = 1;

asynchronous - Python Asyncio blocked coroutine -

i'm trying code simple program based on asyncio , publish/subscribe design pattern implemented zeromq. publisher has 2 coroutines; 1 listens incoming subscriptions, , 1 publishes value (obtained via http request) subscriber. subscriber subscribes specific parameter (the name of city in case), , waits value (the temperature in city). here code: publisher.py #!/usr/bin/env python import json import aiohttp import aiozmq import asyncio import zmq class publisher: bind_address = 'tcp://*:10000' def __init__(self): self.stream = none self.parameter = "" @asyncio.coroutine def main(self): self.stream = yield aiozmq.create_zmq_stream(zmq.xpub, bind=publisher.bind_address) tasks = [ asyncio.async(self.subscriptions()), asyncio.async(self.publish())] print("before wait") yield asyncio.wait(tasks) print("after wait") @asyncio.coroutine

swift - Obj C bridging header does not seem to matter? -

i have swift / parse iphone project in xcode. have added parse frameworks , long import bolts , import parse in swift file able use parse functions. wondering, why need obj c bridging header @ all? there nothing in it, yet everywhere says need setup bridging header parse work in swift projects? the difference in deployment target. ios8, can use embedded frameworks, can import frameworks simple import frameworkname . if use cocoapods, can add use_frameworks! directive podfile , can use pods frameworks without bridging header. if want provide support ios7, have still use bridging header, because embedded frameworks not supported version of ios.

c++ - Signed vs Unsigned comparison -

#include <iostream> int main() { signed int = 5; unsigned char b = -5; unsigned int c = > b; std::cout << c << std::endl; } this code prints 0 . can please explain happening here? guessing compiler converts a , b same type( unsigend int maybe) , compares them. let's see how computer stores value b: 5 00000101 , -5 11111011 , so, when convert unsigned char , became positive number value 11111011 in binary, larger 00000101 . so, that's why a = 00000101 smaller b (0 means false).

android - How to add a LinearLayout in the same activity which has Listview? -

i have activity there linear layout occupies half of screen , below need keep listview has hold number of items. doing this <scrollview> <linearlayout> </linearlayout> <listview> </listview> </scrollview> but reading threads think not idea keeping listview inside scrollview. facing lot of issues height of listview not proper. so how keep layout , listview inside same activity without using scrollview? it not recommended include scrolling view (listview) inside scrollview. want achieve can done adding headerview can inflated xml. linearlayout ll = inflater.inflate(r.layout.my_layout, null); listview.addheaderview(ll);

How to install java neural network framework in ubuntu 14.04 -

can tell how install java neural network framework in ubuntu 14.04? after downloading package unable install via terminal. with neuroph, after downloading zipped distro, unzip it, reference @ least core jar (neuroph-core-2.9.jar) , import necessary classes in java project. can downloaded from http://neuroph.sourceforge.net/download.html netbeans ide separate download , latter requires window system installation , use. api docs @ http://neuroph.sourceforge.net/javadoc/index.html.em .

c# - universal windows app , making a WebRequest Method = GET -

does know how webresponse ?? method getresponse() obsolet, btw it's windows universal app. uri uri = new uri("myuri"); httpclient httpclient = new httpclient(); httpwebrequest webrequest = (httpwebrequest)httpwebrequest.create(uri); httpclient.defaultrequestheaders.add("name", "value"); httpclient.defaultrequestheaders.accept.tryparseadd("application/json"); webrequest.method = "get"; httpwebresponse response = webrequest.getresponseasync(); streamreader streamreader1 = new streamreader(response.getresponsestream()); solved: solved this: private async void start_click(object sender, routedeventargs e) { response = new httpresponsemessage(); outputview.text = ""; httpclient.defaultrequestheaders.add("name", "value"); // value of 'inputaddress' set user , therefore untrusted input. // if can't create valid uri, // notify

java - Commit in PLSQL loop for update -

i using below function in java program copy column temporary table main table. function test(tbl_name varchar2, tmp_tbl_name varchar2, id_col varchar2, req_col varchar2, batch_size number) return number begin execute immediate 'select count(1) ' || tmp_tbl_name total_records; offset := 0; while offset < total_records loop max_results := offset + batch_size; execute immediate 'select ' || id_col || ', ' || req_col || ' ' || tmp_tbl_name || ' seq_nbr between :offset , :max_results' bulk collect seq_ids, req_col_valuess using offset, max_results; forall ind in seq_ids.first .. seq_ids.last execute immediate 'update ' || tbl_name || ' set ' || req_col || ' = :req_col_val ' || id_col || ' = :id_col_val' using req_col_valuess(ind), seq_ids(ind); offset := max_results; commit; end loop; return 0; exception when others raise cust_exception; end; expected result when running batch_size of 100000,

how to achieved sprite reflection in libgdx -

i working on open world game pokemon using libgdx.i stuck on effect want done before moving other features of game. have idea how achieve reflection effect? .concept behind? https://gamedev.stackexchange.com/questions/102940/libgdx-sprite-reflection for basic reflection, draw texture flipped vertically can scale height -1. redraw texture appropriate distance under player. you shoudl add clipping rectangle around water's edge reflection draws water is. perfomance purposes, when player near water. i can't give actual code don;t know code, once you've had go @ handling reflection abaove, come here , ask more specific questions taht may have. this question broad , opinion based , hence highly voted down.

api key - API key for themoviedb.org -

i need use themoviedb.org 1 of apps working on. using api, need api key. how api key on themoviedb.org? i found in forum: can request api key clicking on "api" link within account page on left hand sidebar. see here

c# - Render view dynamically based on model in Asp.net mvc -

i have 2 domain classes , 1 flatclass , other pgclass . based on these 2 have created viewmodel. if user has selected flat radio button ui flatclass populated, otherwise on selection of pg radio button pgclass populated. , on view using viewmodel . is load , pass properties of other class has not selected in viewmodel in view performance point view or can suppress or obselete properties of non- selected class based on condition ?? . don't want create 2 partial views, how render ui based on dynamic selection of model controller in single partial view ? although best practice use 2 different partial views model. in case want implement single partial view, may create base class inherits both flatclass , pgclass. now can create single partial view new viewmodel. public class baseclass { public flatclass? flat {get; set;} public pgclass? pg {get; set;} } please note both objects nullable, since using 1 of them @ time , other 1 null.

html - How can I make list item with uniform length? -

i creating unordered list horizontal tab component. want each list item filling in 1 of 3 boxes uniform length , height shown on image. here jsfiddle , javascript. should change on css make happen? $(function(){ $('#tabs').tabs({ event: "mouseover" }); }); https://jsfiddle.net/m1xhc4v5/6/ add these 3 values css: #tabs li{ display: inline-block; text-align: center; width: 30%; } you need make element inline-block receive width. used 30% allow borders, can fine-tune ever value like. jsfiddle

java - request.getRemoteAddr() returns null -

this question has answer here: how remote address of client in servlet? 8 answers i developing application in local machine using tomcat 7 & servlet 3. in trying read client address in servlet identify request coming using request.getremoteaddr() returning null. i tried metioned here , facing same issue. read using machine name instead of localhost resolve issue. tried using machine name still same issue. can provide links or solution doc necessary configuration changes retrieve ip address ? one of possibilities can getremoteaddr() can return null if request has been consumed, means response has been sent. has been noticed in tomcat 7 also fallback can check x-forwarded-for header calling getheader("x-forwarded-for") , see ip return.

android - No padding-effect in custom ImageView -

i've got issue assigning padding-values custom imageview. please note, i'm not extending imageview view : public class customimageview extends view the image loaded assets folder via path. source- , target- rect calculated in onlayout(...) , bitmap assigned in ondraw(...) . good news: image displayed ;-) bad news: assigning padding-values setpadding(...) has no effect on image (problem solve!). tested "normal" imageview -object , worked desired. unfortunately task extend custom class view , not imageview . if knows how solve - , i'm not first 1 problem ;-) - let me know! here's ondraw -method, no magic: @override protected void ondraw(canvas canvas) { super.ondraw(canvas); if (bitmap != null) canvas.drawbitmap(bitmap, sourcerect, targetrect, paint); } when setting paddings view, should considered during drawing. can achieve this, creating bitmapdrawable variable in custom view, , initialize , draw according padd

Laravel eloquent add extra models to hasMany -

i have user model , each user has multiple licenses . there 2 default licenses apply users not in licenses table , need created on fly using data contained in user model. how can create 2 licenses each time i'm getting user's licenses , add output of licenses() ? class user extends model implements authenticatablecontract, canresetpasswordcontract { use authenticatable, canresetpassword; protected $table = 'users'; public $timestamps = false; protected $fillable = ['name', 'email', 'password']; protected $hidden = ['password', 'remember_token']; public function licenses() { return $this->hasmany('app\license', 'user_id', 'id')->where('deleted', '=', '0'); } } you create function in model call licenses , add licenses. remember test places use function no strange stuff happen. <?php class user extends model

How to inherit common properties in javascript oops using same prototype? -

here full code: <!doctype html> <html> <head> <meta charset="utf-8"> <script src="d:\jquery-1.11.3.min.js"></script> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="https://cdn.rawgit.com/iamphill/bootstrap-offcanvas/master/dist/css/bootstrap.offcanvas.min.css" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>oops2</title> <link rel="stylesheet" href="style.css"> <style> .navheight { height: 198px; !important } html, body { width: 100%; height: 100%; } #paint { overflow: scroll; width: 100%; height: 100%; !important

How to remove magento root folder from site url? -

i new in magento. site http://neptun.al/new/ . need remove magento root folder url. required url must http://neptun.al/ here piece of code .htaccess file you can put here magento root folder path relative web root rewritebase /new what should ? you can move magento source new directory root directory , change secure base url , unsecure base url in core_config_data use http://neptun.al

undefined method `to_model' in rails -

i have following activeadmin model class adminuser < activerecord::base has_many :challenges devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable end and following challenge model class challenge < activerecord::base belongs_to :subdomain belongs_to :admin_user has_many :comments, :dependent => :destroy end i defined following method in application.html.erb helper_method :all_admin_users def all_admin_users @users = adminuser.all end adminuser has following attributes :id,:name,:email when try access challenges of particular user <ul> <% all_admin_users.each |user| %> <li> <%= link_to user.name ,user.challenges%></li> <br /> <% end %> </ul> i following error "undefined method `to_model' challenge::activerecord_associations_collectionproxy here's routes.rb file rails.application.routes.draw resources :comments devise_f

How to say jetty-runner to not use random dir -

i´m using jetty-runner start application. on every start creates new temp folder. avoid it. here example: java -djava.io.tempdir=webapp -jar jetty-runner-9.3.0.m2.jar wars\*.war context.xml when start it, creates folder in webapp jetty-0.0.0.0-8080-mywar.war-_-any-2227787194488516977.dir . uses right syntax "jetty-"+host+"-"+port+"-"+resourcebase+"-_"+context+"-"+virtualhost+"-"+randomdigits+".dir" . my question ist how avoid it, generate random digits. reuse webapps , genreate new one, if wars changes. by default, jetty create temporary directory each web application. name of directory of form: "jetty-"+host+"-"+port+"-"+resourcebase+"-_"+context+"-"+virtualhost+"-"+randomdigits+".dir" each time when start jetty, use check war file existing deployment folder , if identifiyes war file changed, jetty deletes old depolyment fol