Posts

Showing posts from February, 2014

to compare the memory usage between the use of the static array and java.util.ArrayList in a sorting operation -

runtime rt = runtime.getruntime(); long totalm = rt.totalmemory(); long currentm; int []n = new int[10000]; system.out.print("10000 ints used: "); system.out.println(totalm - rt.freememory()); its not working. cannot use long calculation? thanks in advance, please give me suggestions answering implicit question in title: difference in "memory usage between use of static array , java.util.arraylist in sorting operation". in java 8: none . because sort delegated arraylist class, sorts backing array directly using arrays.sort() . in java 7 , below, list converted array, array sorted, , result put list. so, memory doubled array, plus whatever memory need sorting operation itself, depends on version of java. happens linkedlist in java 8.

angularjs - Angular: how to get a template ng-model into a directive for filtering -

i'm trying create directive displays template below , allow easy filtering. when option on select list selected , value entered input box model change. need directive contain model , use model filtering. this far i've got far. can give me guidance on i'm pretty sure there's redundant code in example too. <div ng-controller="resultsctrl"> <div ng-controller="searchfilterctrl"> <dynamic-filters dynamic-filters-directive-search="getsearchfilters"></dynamic-filters> </div> <div ng-repeat="person in persons | filter: search"> {{person.name}} </div> template: <select ng-model="filtertype"> <option value="age">age</option> <option value="customerid">customerid</option> <option value="productid">productid</option> </select> <input type="text" name="sele...

Expose mongoose models via Node.js REST service -

there following schemas: var quest = new schema({ name: { type: string, required: true } }); var attempt = new schema({ quest: { type: objectid, ref: 'quest' }, success: { type: boolean, required: true, default: false } }); var person = new schema({ name: { type: string, required: true }, attempts: [attempt] }); we have list of quests , list of people. every time person attempts pass quest, create attempt entry. nice expose person via rest service so, have list of empty attempt s containing attached attempts plus 1 attempt every quest wasn't attempted. i've ended having this: router.get('/people/:id', function(req, res) { return peoplemodel.findbyid(req.params.id, function (err, person) { if(!person) { .... } if (!err) { return questsmodel.find(function (err, quests) { if (!err) { var result = person.attempts; quests.f...

html - PHP form validation (don't know how to split it in two different pages) -

i working on contact form in php. knowledge of php pretty non-existent. i've tried while html form submit php form have text fields validated , required if blank couldn't work. don't know ajax, otherwise, have attempted that. so, have resorted having php self-form inside html page. this current version: <?php // define variables , set empty values $firstnameerr = $lastnameerr = $emailerr = $messageerr = ""; $first_name = $last_name = $email = $message = ""; if ($_server["request_method"] == "post") { if (empty($_post["first-name"])) { $firstnameerr = "first name required"; } else { $first_name = test_input($_post["first-name"]); } if (empty($_post["last-name"])) { $lastnameerr = "last name required"; } else { $last_name = test_input($_post["last-name"]); } if (empty($_post["email"])) { $emailerr = ...

javascript - Optimal MLB lineup using Knapsack variant -

i writing program find best possible mlb lineup using knapsack solution. pass in player data has players calculated value , salary. salary "weight" in terms of being knapsack problem. my problem not able select players, rather select optimal lineup. choosing pitcher, center, first baseman, second baseman, third baseman, short stop, , 3 outfielders. can successfully. want "weight" 36,000, choosing lineup total of 21,000. here knapsack code: calculatelineup.prototype.findoptimallineup = function(data, capacity) { var items = data.data; var idxitem = 0, idxcapspace = 0, idxposition = 0, oldmax = 0, newmax = 0, numitems = items.length, weightmatrix = new array(numitems+1), keepmatrix = new array(numitems+1), positionarray = new array("p", "c", "1b", "2b", "3b", "ss", "of", "of", "of"), solutionset...

sql - How to determine if my batches are all consecutive? -

company produces 3 batches per year each using following naming convention: yyyy11,yyyy22,yyyy33 in case batch_id =1 batches sequential. absence of batches 200933 , 201022 make batch_id=2 non sequential. with batch_sequences as( select 1 batch_sequence, '200911' batch_date dual union select 2 batch_sequence, '200922' batch_date dual union select 3 batch_sequence, '200933' batch_date dual union select 4 batch_sequence, '201011' batch_date dual union select 5 batch_sequence, '201022' batch_date dual union select 6 batch_sequence, '201033' batch_date dual), batch_entries ( select 1 batch_id, '200911' batch_date dual union select 1 batch_id, '200922' batch_date dual union select 1 batch_id, '200933' batch_date dual union select 1 batch_id, '201011' batch_date dual union select 1 batch_id, '201022' batch_date dual union select 1 batc...

c# - The use of ApplicationException -

this question has answer here: what applicationexception in .net? 3 answers i'd know if use of applicationexception recommended return application errors when user breaks business rule. example: public void validate(string name, string email) { int count1 = (from p in context.clients (p.name == clients.name) select p).count(); if (count1 > 0) throw new applicationexception("your name exist in database"); int count2 = (from p in context.clients (p.email == clients.email) select p).count(); if (count2 > 0) throw new applicationexception("your e-mail exist in database"); } is or bad strategy? if isn't, better approach? in code example, better off throwing argumentnullexception more meaningful. applicationexception not give caller indication exception ...

activerecord - How do I use join and indexBy in Yii2? -

i have this, loads each , every ebay row individually, generating thousands of sql statements: $products = \app\models\product::find() ->joinwith('ebay', false, 'inner join') ->indexby(function($row){return $row->ebay->epid;}) ->all(); i tried this, gave error: 'getting unknown property: app\models\product::ebay.epid' $products = \app\models\product::find() ->joinwith('ebay', false, 'inner join') ->indexby('ebay.epid') ->all(); setting eager loading = true doesn't either. still loads each row individually loads them again @ end. how can efficiently join table in yii , index value in joined table? you won't able indexby . however, arrayhelper::index can index array on related model field. here's how can done: $products = \app\models\product::find() ->with('ebay') ->all(); arrayhelper::index($products, 'ebay.epid'); th...

ios - Localisation issues with localisation strings -

just spend evening, trying figure out. here doing: 1) creating clean project tabbed ios application in xcode 6.3.1; 2) under project/info/localisations adding localisation (russian,german, doesn't matter) 3) in main.strings file, changing corresponding strings, or doing same exporting/importing .xliff file. 4) deleting app simulator/device, cleaning project product/clean, deleting derived app data corresponding folder 5) changing language in simulator/device 6) making run... still english. localised strings wont pick up, no matter what.(even though looks fine trough assistant editor) what doing wrong? suppose complicated? try running on device. xcode 6.x had known issues simulator not showing localizations.

data structures - Quadtree equivalent of AVL tree -

i looking quadtree/octree/2^n tree self-balances accepts new observations, without knowledge of every other point, iow, cannot rely on median writing in 'streaming' context. avl tree balances goes pivoting, there similar data structure higher dimensioned data? the avl tree, returns 1 result, element find. especiall ebucket based quadtrees return list of objects near queried location. calling programm has inspect objects in result ones fullfill application task. from perspective balancing makes little sense. more dense region (e.g city) has more detailed structures , therefore has deeper quadtree. not bad. don't see need quad balancing. further quadtree types (point, lines, object quadtrees) quad node when splitted, splitts in 4 equal size sub rectangular or quadratic sub nodes. these types called restricted quad trees. there 1 hint in literature have found on balanced quadtrees (m.bern, d-eppstein , j.gilbert: mesh generations, cited in hanan samet: founda...

android - Custom font in navigation bar using supersonic -

i quite new (read absolute beginner) mobile development using hybrid framework. first project decided use supersonic framework appgyver. problem occured, when wanted change font of title in navigation bar. here's tried: i put downloaded font-related files folder appname/app/common/assets/fonts . afterwards created stylesheet, contains "custom" font definition: @font-face { font-family: 'ralewaybold'; src: url('/fonts/raleway-bold-webfont.eot'); src: url('/fonts/raleway-bold-webfont.eot?#iefix') format('embedded-opentype'), url('/fonts/raleway-bold-webfont.woff2') format('woff2'), url('/fonts/raleway-bold-webfont.woff') format('woff'), url('/fonts/raleway-bold-webfont.ttf') format('truetype'), url('/fonts/raleway-bold-webfont.svg#ralewaybold') format('svg'); font-weight: normal; font-style: normal;} saved raleway.css (here, need say, tried put code android.css , appl...

php - Search for substrings of text in a node in a XML file -

i have php found in q&a forum queries xml file: $doc = new domdocument; // create new dom document $doc->preservewhitespace = false; // set features $doc->formatoutput = true; // create indents on xml $doc->load('i.xml'); // load file $xpath = new domxpath($doc); $query = '//users/user/firstname[.= "'.$_post["search"].'"]'; // xpath (starts root node) $names = $xpath->query($query); // list of matched elements $output=""; foreach ($names $node) { $output.=$doc->savexml($node->parentnode)."\n"; // parent of "<firstname>" element (the entire "<user>" node , children) (maybe parent node directly using xpath) ...

arrays - How do I multiply a long integer with different numbers in C program? -

i new c programming , writing program takes number suppose 9 digits long. after multiply each digit either 1 or 2. using arrays ask user enter numbers. know if there way multiply 9 numbers different numbers 1 integer instead of using arrays? here code arrays: #include <stdio.h> int main(void) { int sin_num[9]; int num1; int num2, num11, num12; int num3, num4, num5, num6, num7, num8, num9, num10; for(num1=0; num1<9; num1++) { printf("enter sin number 1 one:"); scanf("%d", &sin_num[num1]); } num2 = sin_num[0] * 1; num3 = sin_num[1] * 2; num4 = sin_num[2] * 1; num5 = sin_num[3] * 2; num6 = sin_num[4] * 1; num7 = sin_num[5] * 2; num8 = sin_num[6] * 1; num9 = sin_num[7] * 2; num10 = sin_num[8] * 1; right doing this: element 1 * 1 element 2 * 2 element 3 * 1 how can do, lets if enter 123456789 multiply different numbers: 123456789 121212121 well could...

Oracle SQL - Combine two select statements -

select qi.qtyonhand + qd.delqty teste, qi.itemname qitem qi, qdel qd qi.itemname = qd.itemname , qd.deptname = 'recreation'; select qi.qtyonhand - qs.saleqty teste, qi.itemname qsale qs, qitem qi qi.itemname = qs.itemname , qs.deptname = 'recreation'; i'm trying update qitem quantity count adding qdel table's quantity , subtracting qsale table's quantity. i'm trying put 1 column, there may not items in qdel table department name of "recreation" when try put select statements one, leaves out items qitems . how this? if not give desired result, can show sample data better explain need? select qi.qtyonhand + nvl(qd.delqty,0) + nvl(qa.saleqty,0) teste, qi.itemname qitem qi left outer join (select * qdel deptname = 'recreation') qd on qi.itemname = qd.itemname left outer join (select * qsale deptname = 'recreation') qs on qi.itemname = qs.itemname (qd.delqty not null or qs.saleq...

logistic regression - R - Stepwise random results -

if set seed before regression (logistic) lr = glm(target ~ 1, family=binomial, data = x) set.seed(12345) lr = stepaic(lr, scope = f, family=binomial, data = x, k = 3) summary(lr) i different results depending on seed different performance. 1 random part of algorithm? because in neural net result depends on first weights if have local minima, in logistic regression random part? (since conceptual question didn't add reproducible example.)

jersey - Using Server Request and Response filters for ThreadLocal storage in a RestEasy based service -

i working on resteasy based restful service. have filter class serves server request filter server response filter (i.e. implements containerrequestfilter , containerresponsefilter interfaces). at beginning of request, use filter put object threadlocal . object used resources throughout request. @ end of request, before sending out response, filter removes object threadlocal . my question is there guarantee the request filter, resource , response filter execute in same thread? there possibility after request filter puts object threadlocal , different thread execute request (and not have access object)? i sure case saw http://jersey.576304.n2.nabble.com/does-filter-method-of-containerrequestfilter-run-in-resource-method-thread-td7582648.html (official jersey forum) , have doubts. javax.ws.rs.container.containerrequestcontext.setproperty(...) and javax.ws.rs.container.containerrequestcontext.getproperty(...) are right approach. javadoc states: in ...

Java Caching System - finding map size -

i'm using java caching system (jcs - https://commons.apache.org/proper/commons-jcs/ ) need find size of cache (from class org.apache.commons.jcs.access.cacheaccess) with cacheaccess.getstats() can string gives me stats of cache e.g. string stats = ((icacheaccess<string, book>) cache).getstats(); and give me lots of info region name = bookcache hitcountram = 0 hitcountaux = 0 ---------------------------memory cache list size = 5015 map size = 5015 put count = 5015 hit count = 0 miss count = 0 ---------------------------indexed disk cache alive = true key map size = 0 data file length = 0 hit count = 0 bytes free = 0 optimize operation count = 0 times optimized = 0 recycle count = 0 recycle bin size = 0 startup size = 0 purgatory hits = 0 purgatory size = 0 working = true alive = false empty = true size = 0 but need map or list size. any ideas - other regex :-) you can try list<istatelement> stats = ((icacheaccess<string, book>) cache)...

php - Warning: Attempt to assign property of non-object, but the Object exists -

this class: class network { protected $value = null; protected $properties = array(); public $type = null; function __construct($value = null, $type = null) { $this->value = $value; $this->type = $type; } public function __set($name, $value) { if(isset($this->{$name})) { $this->{$name} = $value; } else { $this->properties[$name] = new self($value, null); } } public function __get($name) { return $this->properties[$name]->value; } public function __tostring() { return $this->value; } } this trying do: $networks = new \stdclass(); $networks->test= new \orange_post\network('test'); $networks->test->enabled = true; $networks->test->enabled->type = 'boolean'; but error: warning: attempt assign property of non-object on last line, $networks->test->enabled->type = 'boolean'; ...

if statement - Else component of if/else not executing (C++) -

i have relatively large program , not of relating question, particular bit stumping me. below int main: int main () { int casenumber ; string clientname, clientemail, subject, path, filename, firsttime ; //creates string path of files created , python project stored (with .exe) path = _pgmptr ; filename = "emailgenerator.exe" ; filename.length() ; path.erase(path.length() - filename.length()) ; //checks first time use customizing cout << "welcome ticket email generator.\n\n" << "if first time using program,\nplease enter y customize personal details.\n" << "if not, enter other character.\n" ; cin >> firsttime ; cin.ignore() ; if (firsttime == "y" || firsttime == "y") { //save sender email (defaults morgan_wallace@cable.comcast.com - creator) setsender (path) ; ...

Assembly multiple definition -

giving code section .data msg db "hello, world!",0xa len equ $ - msg section .text ;we must export entry point elf linker or global _start _start: mov eax,4 mov ebx,1 mov ecx,msg mov edx,len int 0x80 mov eax,1 xor ebx,ebx int 0x80 when try run it, shows command linux1[8]% nasm -f elf -l hello.lst hello.asm linux1[9]% ls hello.asm hello.lst hello.o linux1[10]% gcc -o hello hello.o hello.o: in function `_start': hello.asm:(.text+0x0): multiple definition of `_start' /usr/lib/gcc/x86_64-redhat-linux/4.4.7/../../../../lib64/crt1.o:(.text+0x0): first defined here hello.o: not read symbols: file in wrong format collect2: ld returned 1 exit status how fix multiple definition problem? define _start once, how com...

ios - Bluetooth characteristic being set to nil -

i running app communicates mac iphone via bluetooth , vice versa. working (with 2 generated characteristics 1 mac iphone , 1 iphone mac) apart from, characteristic mac iphone not being updated , think due charachteristic on mac being set nil no apparent reason. so update char on mac do: - (void)updatevalueforcharacteristic:(int)sendid { nslog(@"sent %d", sendid); if (self.characteristic != nil) { dispatch_block_t block = ^(void) { nsdata *value = [nsdata datawithbytes:&sendid length:sizeof(sendid)]; [_managerout updatevalue:value forcharacteristic:self.characteristic onsubscribedcentrals:nil]; }; dispatch_queue_t queue = dispatch_get_global_queue(dispatch_queue_priority_default, 0); dispatch_async(queue, block); }else{ //why being called?! } } and receive on iphone do: - (void)peripheral:(cbperipheral *)peripheral didupdatevalueforcharacteristic:(cbcharacteristic *)characteristic...

python - How to use bootstrap on Django's FileField/CharField/BooleanField/Upload button -

Image
i have following django setup. models.py class method1(models.model): inputfile_param = models.filefield() species_param = models.charfield(max_length=20, choices=(('mouse', 'mouse'), ('human','human'))) norm_mode_param = models.charfield(max_length=20, choices=(('genecount_norm', 'gene count'), ('totalscore_norm','total score'))) logscale_param = models.booleanfield(default=false) views.py from .forms import method1form def method1_input(request): if request.method == 'post': form = method1form(request.post, request.files) # handle file upload if form.is_valid(): q = form.save() q.save() # run code # given parameters q.run_code1() # show method1_result executed. return httpresponseredirect(reverse('method1-result', kwargs={'id': q.id })) else: ...

Matlab: display full error path -

consider following foo.m file: try disp(r3) catch me disp(getreport(me)) end when run with: matlab -nodisplay -nodesktop -nosplash -nojvm -wait -r "run('foo.m')" i get: undefined function or variable 'r3'. error in foo (line 2) disp(r3) error in run (line 96) evalin('caller', [script ';']); i wondering if possible display full path of files referenced in errors. know can use which and, instance, get: » run c:\prog-lang\matlab\toolbox\matlab\lang\run.m but errors directly displayed like error in c:\prog-lang\matlab\toolbox\matlab\lang\run.m (line 96) rather than error in run (line 96) one option hack error report returned getreport , example using function search , replace each instance of "foo" full path file - function msg = getreportfull(e) stack = dbstack(); stack(1) = []; msg = getreport(e); = 1:length(stack) fname = stack(i).name; fpath = whic...

Docker: Connectivity between Physical Machine - VM -Docker container -

i have started have experimentation docker. on windows host have virtual machine holds docker container. want have communication between host , container or may other vms , container. host ip 192.168.2.10 subnet mask 255.255.255.0 vm ip 192.168.254.130 subnet mask 255.255.255.0 container gets ip 172.17.0.13 i have seen few blogs talking bridging still not sure , how that. not networking stuff. a little guidance help. thanks edit: followed bridge-building not understand ip range give bridge, so, gave 192.168.254.1/24. command ip addr show bridge0 shows state unknown . i'll assume using docker on windows linux host running on virtualbox. note default docker-machine creates nat adapter (with port forward) , host-only adapter, tricky different machines talk correct ip. as answered adrian typically "publish" ports port forwarding, if container has communicate via many ports , running 1 such container / host easier start container via docker ru...

iot - Lua alarm does not execute code -

i'm programming in nodemcu using lualoader. i'm trying read adc of node , send php file in public domain. with next code adc , node's ip , send through get. x = adc.read(0); ip = wifi.sta.getip(); conn=net.createconnection(net.tcp, 0) conn:on("receive", function(conn, payload) print(payload) end) conn:connect(80,'example.com') conn:send("get /data.php?mdata="..x.."&ip="..ip.." http/1.1\r\n") conn:send("host: example.com\r\n") conn:send("connection: keep-alive\r\naccept: */*\r\n") conn:send("user-agent: mozilla/4.0 (compatible; esp8266 lua; windows nt 5.1)\r\n") conn:send("\r\n") print ("done") the code works correctly. if paste in lualoader return: http/1.1 200 ok date: wed, 30 sep 2015 02:47:51 gmt server: apache x-powered-by: php/5.5.26 content-length: 0 keep-alive: timeout=2, max=100 connection: keep-alive content-type: text/html done howev...

creating an array in a class PHP -

this question has answer here: php parse/syntax errors; , how solve them? 11 answers i trying complete objective homework assignment , im running issues. these instructions given me: create class named daysofweek. include array of 7 days of week member of class. include function member of class when called, displays contents of array. create object , call function. my textbook "w3schools" , im finding little difficult understand complete task. php class daysofweek{ var $days = array("monday", "tuesday", "wednesday", "thursday". "friday"); function showarray(){ $arrlength = count($days); ($x = 0, $x < $arrlength, $x++){ echo $days[$x]; echo "<br>"; } } } this code have written. way believe have written extent of: i cr...

java - HTML Can't Find Table ID -

Image
http://games.espn.go.com/ffl/freeagency?leagueid=1566286&teamid=4&seasonid=2015#&seasonid=2015&view=projections&context=freeagency&avail=-1 i trying use jsoup rip table link. new html , can not find right "table id" use. code below, , have gotten work tables other pages, code not issue. don't know how find right table id. thank you! this html code see: http://pastebin.com/d5h5qbb6 import java.io.ioexception; import org.jsoup.jsoup; import org.jsoup.nodes.document; import org.jsoup.nodes.element; import org.jsoup.select.elements; public class readurl { public static void main(string[] args) { //extracttableusingjsoup("http://mobilereviews.net/details-for-motorola%20l7.htm","phone_details"); extracttableusingjsoup("http://games.espn.go.com/ffl/freeagency?leagueid=1566286&teamid=4&seasonid=2015#&seasonid=2015&view=projections&context=freeagency&avail=-1","insert table id he...

How to call a python function through an ajax call in a django project? -

i'm starting on simple web app , i'm trying call python function render separate view via ajax call. want click on try button , render different html template. right displays error message ajax, have no idea possibly breaking it. need point me in right direction..some sort of starting point appreciated. in advance :) my project urls.py looks from django.conf.urls import include, url, patterns django.conf.urls.static import static django.contrib.staticfiles.urls import staticfiles_urlpatterns sudokuproject import settings urlpatterns = patterns('', url(r'', include('sudokuapp.urls', namespace="sudoku"))) + static(settings.media_url, document_root=settings.media_root) urlpatterns += staticfiles_urlpatterns() my app urls.py from django.conf.urls import include, url . import views urlpatterns = [ url(r'home/', views.sudoku_home, name="home"), url(r'solve/', views.sudoku_solve, name="solve")...

MongoDB to assist with recommendations -

i have 3 collection schema shown below: user collection has information regarding friends , listening count(weight) per artist { user_id : 1, friends : [3,5,6], artists : [ {artist_id: 10 , weight : 345}, {artist_id: 17 , weight : 378} ] } artist collection schema has information regarding name of artist, tags given various users them. { artistid : 56, name : "ed sheeran", user_tag : [ {user_id : 2, tag_id : 6}, {user_id : 2, tag_id : 5}, {user_id : 3, tag_id : 7} ] } tags collection having information various tags. {tag_id : 3, tag_value : "hiphop"} i want provide user recommendations artists using below rules: rule 1 : find artists listened user's friends not user, order them sum of friends' listening counts. rule 2 : select tag used user, find artist tag not in user's listening list, , order them number of unique listener. can me write query perform above. ...

php - Validating dynamically added input fields in Laravel 5 -

Image
problem: need validate dynamically added input fields. here screenshot of ui: scenario 1: adding new schedule, validation works perfectly. the form validated using form request file: public function rules() { $rules = [ 'name' => 'required|max:255', 'due_at' => 'required|date_format:y-m-d', 'users' => 'required', 'task_name' => 'required|max:255' ]; if($this->request->get('task_name')){ foreach($this->request->get('task_name') $key => $val) { $rules['task_name.'.$key] = 'required|max:255'; $rules['task_description.'.$key] = 'required|max:255'; } } return $rules; } public function messages() { $messages = []; foreach($this->request->get('task_name') $key => $val) { $messages['task_name.'.$key....