Posts

Showing posts from June, 2013

Netbeans 8.1, Gluon Project Android Error -

Image
i'm using netbeans 8.1, gluon , nbandroid plugins, on windows 8.1, , when create gluon basic project can't run on android platform, error android_home , in last 2 days have searched lot tries have made don't help. here error: caused by: org.gradle.internal.exceptions.locationawareexception: android_home not specified. either set gradle property, system environment variable or directly in build.gradle setting extension jfxmobile.android.androidsdk. caused by: org.gradle.api.gradleexception: android_home not specified. either set gradle property, system environment variable or directly in build.gradle setting extension jfxmobile.android.androidsdk. i tried sample project gluon, , error still appears, if create android project (nbandroid, not gluon) , run it, ok. i see same difference other questions on project, when create gluon basic project automatically android project created, don't see on lot of movies watch on youtube. can me, please? if more data ne

c++ - template meta-programming how to specialize on a collection -

i have following utlsharedipcwrapper template class created access user defined type placed in inter-process memory. normally class used simple type example: // construct faultreport - default no faults auto faultwrapper = managed_shm.construct< utlsharedipcwrapper<uint64_t>>("faultreport")(0); and works well, had need use boost shared memory map collection ( boost::interprocess::map ) template argument) in: using char_allocator = boost::interprocess::managed_shared_memory::allocator<char>::type; using shm_string = boost::interprocess::basic_string<char, std::char_traits<char>, char_allocator>; using keytype = shm_string; using valuetype = std::pair<const keytype, shm_string>; using shmemallocator = boost::interprocess::allocator<valuetype, boost::interprocess::managed_shared_memory::segment_manager>; using sharedmemorymap = boost::interprocess::map<shm_string, shm_string, std::less<keytype>, shmemallocator&g

python 2.7 - Percentage of proximity to cluster in kmeans -

i trying clustering in python. this script follows: import scipy import numpy np scipy.cluster.vq import kmeans2 collections import counter def dist(a,b): return np.linalg.norm(a-b) x = scipy.randn(100, 2) k=int(raw_input("give value of k: ")) pts = 100*np.random.random((12,2)) centroids, assigned_clusters = kmeans2(x, k) pt in pts: #print tuple(pt) distperxy=dict() i=1 cent in centroids: distperxy[i]=(float(dist(pt,list(cent)))) i+=1 mnmm=min(distperxy.iterkeys(), key=(lambda key: distperxy[key])) tot = sum(distperxy.values()) perc=distperxy[mnmm]/tot print mnmm,perc basically trying determine nearest cluster each point , percentage of proximity cluster. example if point near centroid1 in k-means k=3. percentage calculation described in code above,i.e, dividing distance closest cluster sum of distances clusters?

node.js - Ask user to complete registration after social login through Passport -

i wonder best practice ask user more information complete registration after social login passport. able sign in user through twitter, , callback route '/auth/twitter/callback' called. however, @ point i'm presenting form ask them few more pieces of information. problem @ point req.isauthenticated() returns true already, while i'd rather set isauthenticated manually after complete registration, not twitter callback called. suggestions? there few ways can achieve want , point of view fiddling around req.isauthenticated() not best. recommend following approaches. method 1 in addition req.isauthenticated() put new condition check whether user completed registration or not i.e. user.completedregistration() completedregistration() function checks either mongodb or other logic decide yes or not. sample follow: var isauthenticated = function (req, res, next) { if (req.isauthenticated() && user.completedregistration()) { //user both authenti

How to do calculations on elements from a sublist in R -

my code follows: x <- data.frame(matrix(rnorm(20), nrow=10)) colnames(x) <- c("z", "m") n_boot<-4 bs <- list() (i in 1:n_boot) { bs[[i]] <- x[sample(nrow(x), 10, replace = true), ] } bt<-matrix(unlist(bs), ncol = 2*n_boot, byrow = false) colnames(bt) <- rep(c("z","m"),times=n_boot) m_to_boot <- bt[,seq(2,8,by=2)] funct<-function(m_boot_max) { od<-(1/((10*((10^((16-m_boot_max-25)/5))^3)/3)*((max(m_boot_max)-min(m_boot_max))/50))) } v_boot<-apply(m_to_boot,2,funct) rows.combined <- nrow(m_to_boot) cols.combined <- ncol(m_to_boot) + ncol(v_boot) matrix.combined <- matrix(na, nrow=rows.combined, ncol=cols.combined) matrix.combined[, seq(1, cols.combined, 2)] <- m_to_boot matrix.combined[, seq(2, cols.combined, 2)] <- v_boot colnames(matrix.combined) <- rep(c("m_boot","v_boot"),times=n_boot) df<-as.data.frame(matrix.combined) start0 <- seq(1, = 2, length = n

go - How to Add a Slice Array inside of a Struct -

i'm looking add array string variable inside of struct have created in go. type recipes struct { //struct recipe information name string preptime int cooktime int recipeingredient string recipeid int recipeyield int } it called by recipe1.name = "bbq pulled chicken" recipe1.preptime = 25 recipe1.cooktime = 5 recipe1.recipeingredient = "1 8-ounce can reduced-sodium tomato sauce, two" recipe1.recipeid = 1 recipe1.recipeyield = 8 recipeingredient have multiple ingredients can't 1 string. have multiple array/slice elements inside recipeingredient. have idea on how able please? use slice of string . example, package main import "fmt" type recipe struct { name string preptime int cooktime int ingredients []string id int yield int } func main() { var recipe recipe recipe.name = "bbq pulled chicken"

javascript - Save data in localstorage of browers in ember simple auth -

i have used ember-simple-auth fb login.i able fetch fb's access_token , sending token server exchange of server token.this works fine , and able make transition user feed page.but problem facing first time user.i have show them onboarding screen before taking them feed screen.and next time can skip onboarding process them. torii.js export default torii.extend({ torii: service('torii'), authenticate() { return new rsvp.promise((resolve, reject) => { this._super(...arguments).then((data) => { console.log(data.accesstoken); raw({ url: 'http://example.co.in/api/socialsignup/', type: 'post', datatype: 'json', data: { 'access_token':data.accesstoken,'provider':'facebook'} }).then((response) => { console.log(response.token); resolve({ // jscs:disable requirecamelcaseoruppercaseidentifiers

canvas - Android Use finger to erase bitmap transparency and match background -

scenario: use fingerpaint example basis draw text fingerpaint region want user able erase part of text finger dragging on it reference: how erase paint finger tries: it gets want, src , clear dragging path black. prefer dragging path color drawn canvas without redrawing entire canvas finger moves. if know fingerpaint this: canvas.drawcolor(0xffaaaaaa); i wrote black colored text on top of canvas via drawtext. tried following combos allow user erase text: mpaint.setcolor(0xffaaaaaa); mpaint.setxfermode(new porterduffxfermode(porterduff.mode.clear)); mpaint.setcolor(color.transparent); mpaint.setxfermode(new porterduffxfermode(porterduff.mode.clear)); mpaint.setcolor(0x00aaaaaa); mpaint.setxfermode(new porterduffxfermode(porterduff.mode.clear)); you can multiply 3 out substituting clear mode src mode , showed same result. question: anyone know how can make erasure drawpath take appropriate action of erasing part of bitmap dragged on , while d

tkinter - Python 3.4 GUI if statement with buttons -

i'm trying learn coding python 3.4. built mini gui , i'm having trouble getting work. prints out 2 every time though press button 1 . want 1 printed out in label when click button on , 2 button 2 if statement. from tkinter import * root = tk() root.geometry("500x500") root.title("test") def button_press(): if one: x = 1 display.configure(text=x) if two: x = 2 display.configure(text=x) display = labelframe(root, bg="red", width="462", height="60") display.pack() 1 = button(root, text="1", width="15", height="5",command=button_press) one.pack(side="left") 2 = button(root, text="2", width="15", height="5", command=button_press) two.pack(side="left") root.mainloop() you have 2 ways: or using different function each button or pass lambda 1 parameter. bt … command = fct1 bt … command = fct

excel - Find cells on one sheet and copy the rows to another sheet -

i have sheet called backlog containing rows , columns of data. need code search row row in 2nd last column looking #n/a. when finds #n/a needs check last column if contains c or not. if contains c whole row should appended sheet called logoff. if last column not contain c whole row should appended sheet called denied. row should deleted original backlog sheet once moved either logoff or denied. code have below not working. after first statement goes end sub, there not compiling errors. private sub commandbutton2_click() dim imbacklogsh worksheet set imbacklogsh = thisworkbook.worksheets("backlog") dim logoffsh worksheet set logoffsh = thisworkbook.worksheets("claims logged off") dim deniedsh worksheet set deniedsh = thisworkbook.worksheets("claims denied") imbacklogsh.select dim long = 3 cells(rows.count, 13).end(xlup).row if cells(i, 13).value = "#n/a" if cells(i, 14).value =

Error display in vaadin table -

i'm pretty new vaadin framework, working fine until... table header don't show properly,... i'm working on portlet runs on exoplatform, i'm using vaadin 6, table display first header, tried nothing seems work. here code: table = new table("my table"); table.setcolumnheadermode(table.column_header_mode_explicit); table.setpagelength(9); table.setwidth("100%"); table.addcontainerproperty("sad", string.class, null); table.addcontainerproperty("asd", integer.class, null); table.addcontainerproperty("qwerty", integer.class, null); table.setcolumnheadermode(table.column_header_mode_explicit); table.setcolumnheader("sad", "sad"); table.setcolumnheader("asd", "asd"); table.setcolumnheader("qwerty", "qwerty"); i had same problem, try wrap table panel. works me. it seems

python - Gravitational Waveform Plot From h5 File -

i want plot waveform 2 black-hole mergersi have .h5 file got public waveform catalog. i kind of beginner using python don't know in situation. have .h5 file has .dat file inside want use make plot. got file public waveform catalog at: http://www.black-holes.org/waveforms/data/displaydownloadpage.php/?id=sxs:bbh:0001# the name of file : rhoverm_asymptotic_geometricunits.h5 it in lev5 directory. contents of .h5 file described in: https://www.black-holes.org/waveforms/docs.html there dataset in file think describes waveform want plot. problem don't know how data set. have gotten far doing: import numpy np import h5py pylab import plot,show f = h5.py.file("rhoverm_asymptotic_geometricunits.h5","r") ks = f.keys() from here don't know how create x , y axis go plot function. assuming need attribute belongs h5py module, not sure if using right terminology. appreciated. try this: import matplotlib.pyplot plt import h5py f = h5py.f

optimization - How do I efficiently structure a golang program for optimum garbage collector runs? -

optimizing code better results in golang gc seems more of rather important thing time-optimized gc runs. told how accomplishes in run "depends on pattern of heap memory usage.", i'm not sure means/entails perspective of programmer in language. or not can controlled? i have read through recent book "the go programming language" brian w. kernighan, there nothing topic in it. , information on topic on internet years ago, don't apply. some things include: making sure pointers/objects ever stored/remembered need be allocating objects capacities of expected or sane not duplicating data when able, using streaming data through functions instead of putting data big heap front. i bit annoyed fact strings , byte arrays recreated when converting between 1 or other (due strings being immutable). when going 1 other, , safe operation, recast pointers other type using unsafe. are of these practices worth gc run faster , clear more? there else do?

javascript - dynamically creating function with promise infinite loop mocha -

8 hours later.... not sure happened, realized when wrote file root directory of project, got stuck in infinite loop. anywhere else, worked fine. //update still working on this. missed superbowl. update have writefilesync gives exact same error. i've been banging head on 1 while now. promisefunction = [promisefunction1, promisefunction2, promisefunction3].reduce((oldfunction, newfunction)=>{ return function (){ return oldfunction().then(()=>{ return newfunction() }) } } when try test promisefunction(), infinite test loop (all of tests test promisefunction keep firing in perpetuity) the catch however, promise function screwing promisify(fs.writefile) when try using different promise function, promisify(fs.readfile) , works fine. when console log difference between readfile , writefile promises, there respective results: //readfile readfilepromise promise { _bitfield: 67108864, _fulfillmenthandler0: undefined, _rejectionhandler0:

Implementing the insert array method for a hand-written dynamic array - C++ -

so code supposed take dynamic array , inserts smaller array , if there's not enough space in larger array makes new array , copies values old array new 1 smaller array can inserted. here's code allocates new size new array dynamic_array &a being smaller array , being position it's inserted to: void dynamic_array::insert(dynamic_array &a, int i) { if (i < 0 or > size){ throw exception(subscript_range_exception); } int *new_array; int range = a.get_size(); //my size method return how many values in int blocks_needed = (size) / block_size; if (size % 5 > 0) { blocks_needed = blocks_needed + 1; //add block if needed } if (size + range >= allocated_size) { //new space needed //get more space try { new_array = new int[blocks_needed * block_size]; } catch (bad_alloc){ throw exception (memory_exception); } then there's 3 different loops. 1

html - Make text above the gradient -

Image
how have text ("welcome mane frame radio") above gradient specify in css (jumbotron:after class)? snipp: http://bootsnipp.com/user/snippets/l056a let bg image on body this: body { background-image: url('http://znc.mane-frame.com/static/silverleaf.png'); background-repeat: no-repeat; background-attachment: fixed; } then use gradient jumbotron's background, this: .jumbotron { display: block; margin: 0 auto; position: relative; background: linear-gradient(to bottom, rgba(255, 26, 2, 0.2) 0%, rgba(127, 13, 1, 1) 100%); } now don't need jumbotron:after anymore.

authentication - Why won't this VBA program using ServerXMLHTTP60 authenticate properly? -

Image
i have 4 different queries of ipr 1.2.3.4 (ip-reputation) ibm's xforce database, using basic authentication (base64 encoded), url-reputation. version in python works great, printing out appropriate json information: ... if __name__ == '__main__': apikey = "1234...." apipwd = "5678..." result = requests.get('https://xforce-api.mybluemix.net:443/ipr/1.2.3.4', verify=false,auth=(apikey, apipwd)) if result.status_code != 200: print( "~ bad status code: {}".format(result.status_code)) else: print("~ result {}".format(result.status_code)) print("~ rx data={}".format(result._content)) the version in go (using demisto's goxforce github) works great. after setting environment-variable key , password, issue commandline: 'xforcequery -cmd ipr -q 1.2.3.4' and prints out json information 1.2.3.4, again, perfectly. i use browser-utility called 'postman', specify

c++ - stringstream.rdbuf causing cout to fail -

i surprised see program go quiet when added cout @ point, isolated responsible code: std::stringstream data; data<<"hello world\n"; std:std::fstream file{"hello.txt", std::fstream::out}; file<<data.rdbuf(); std::cout<<"now rdbuf..."<<std::endl; std::cout<<data.rdbuf()<<std::endl; std::cout<<"rdbuf done."<< std::endl; the program quietly exits without final cout. going on? if change last .rdbuf() .str() instead completes. during call std::cout<<data.rdbuf() , std::cout unable read characters data 's filebuf because read position @ end of file after previous output; accordingly , sets failbit on std::cout , , until state cleared further output fail (i.e. final line ignored). std::cout<<data.str()<<std::endl; not cause cout enter failed state because data.str() returns copy of underlying string regardless of read position (for mixed-mode stringstreams an

php - Only getting list of files on /var/www/html folder -

i'm trying host laravel app on ubuntu machine added laravel app /var/www/html folder root directory domain on apache conf file. when access domain, list of files in /var/www/html folder. when insert index.html file test, works when access domain. can happening? laravel served out of index.php inside public folder. you getting list of files because domain pointing var/www/html contains root of laravel application , not public directory contains index.php . if go www.yourdomain.com/public find application served correctly if apache set recognize index.php should be. to fix don't need use public inside url can edit /etc/apache2/sites-available point directory /var/www/html/public , able access through www.yourdomain.com .

html - JavaScript AddEventListener not working -

so i'm trying make slideshow user can click next browse through pictures. i've created array images: var staff = new array(); staff[0] = "/images/isabelle.png"; staff[1] = "/images/nook.png"; staff[2] = "/images/timothy_tommy.png"; staff[3] = "/images/mabel.png"; staff[4] = "/images/sable.png"; staff[5] = "/images/labelle.png"; and function changing images: var = 1; function nextimage(){ document.getelementbyid("slide").src = staff[i]; if(i < staff.length) i++; else = 0; //wraps around first image } the addeventlistener function call added registerhandlers function initialize onload: document.getelementbyid("next").addeventlistener("click",nextimage,false); and image , "next" button placed in divs inside body: <div class="container"> <img id ="slide" src="images/isabelle.png" /> </div> &l

java - Implementation of toString() method in a linkedList -

i trying implement method prints out contents inside linked list. here explanation of classes use: 1) nonemptylistnode , emptylistnode inherit abstractlistnode . 2) trailing node represented emptylistnode . i implemented it, however, felt bad since taught instanceof keyword bad. here questions: 1) can implement tostring() without instanceof keyword? 2) implement tostring() in recursive way? here code: abstract public class abstractlistnode { abstract public object item(); abstract public abstractlistnode next(); abstract public boolean isempty(); abstract public int size(); abstract public string tostring(); } class nonemptylistnode extends abstractlistnode { private object myitem; private abstractlistnode mynext; public nonemptylistnode (object item, abstractlistnode next) { myitem = item; if (next == null) { mynext = new emptylistnode(); } else { mynext

Identify similar repeating ascending patterns in numeric vectors in R -

i have multiple numeric vectors have similar repeating ascending pattern. eg: vec_1 <- c(43, 17, 186, 193, 186, 186, 474, 491, 498, 498, 673, 736, 743, 716, 44, 19, 193, 194, 193, 193, 472, 498, 476, 499, 673, 743, 714, 714, 19, 21, 194, 180, 194, 194, 485, 499, 481, 476, 712, 719, 712, 17, 40, 174, 180, 169, 495, 485, 673, 177, 485, 481, 714, 730, 733, 40, 33, 190, 174, 180, 482, 495, 495, 479, 703, 733, 704) there 5 repetitions. in above example: starts 43, ends 716 starts 44 (where 1. ends), ends 714 etc. i want generate new vector identifies repetition number. vec_1 be: rep_nums_1 <- c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, ..., 5) the number of items within each repetition can differ (so cant assign first 14 elements 1, next 14 2, etc.) not sure how best approach this. non elegant solution check if next element in sequence smaller current m

Datepicker on codeigniter -

i have datepicker purely working in test_datepicker.html. here code: <!doctype html> <html> <head> <title>date picker</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" > <script src="http://code.jquery.com/jquery-1.10.2.js"></script> <script src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script> <script type="text/javascript"> $(function() { $( "#datepicker" ).datepicker(); }); </script> </head> <body> this working, when sync on ci php code not working. http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" ?>' > http://code.jquery.com/jquery-1.10.2.js" ?>' > http://code.jquery.com/ui/1.11.4/jquery-ui.js"

algorithm - Recurrence: T(n) = 3T(n/2) + n^2(lgn) -

here full question... analysis of recurrence trees. find nice nonrecursive function f (n) such t(n) = Θ( f (n)). show work: number of levels, number of instances on each level, work of each instance , total work on level. this homework question not expect exact answers, guidance because have no idea start. here part a: a) t(n) = 3t(n/2) + n^2(lgn) i have no idea begin. these types of recurrences solved master's theorem in case a=3 , b=2 , therefore c = log2(3) < 2 . so in third case , complexity o(n^2 * log(n))

ios - Convert NSmangedObject to JsonModel -

in application using jsonmodel parsing json response server , while storing in core data using nsmanagedobject , nsmanagedcontext provided apple itself. whenever fetch want convert nsmanagedobject jsonmodel. problem have use 2 separate class manage jsonmodel , nsmanagedobject . you can link. get core data objects json or in easy way andrew-madsen 's answer nsmanagedobject *managedobject = ...; nsarray *keys = [nsarray arraywithobjects:@"key1", @"key2", ..., nil]; // these keys properties of managed object want in json nsstring *json = [[managedobject dictionarywithvaluesforkeys:keys] jsonrepresentation]; for more detail try link nsmanagedobject-to-json

multithreading - When multi-threading is a bad idea? -

according way understand threads, programming multi-threaded program either can speed program or match execution time of single-threaded version of program. so, 2 questions are: 1- said true or false ? 2- give example when multi-threading code produce negative results on performance ? a multi-threaded program can behave worse single-threaded equivalent. due to: the cost create additional threads the cost of context switches the potential false sharing . creating many threads small amount of work alters adjacent regions of memory exhibit of issues. multi-threaded programs in general introduce additional complexity , present numerous opportunities bugs. should taken account when deciding whether or not use multiple threads.

php - Yii2 controller or configuration raise that only handle the following request methods: GET, HEAD -

Image
i trying simple rest response using json format. i created simple model: model <?php namespace app\models; use yii; use yii\db\activerecord; class post extends activerecord { /** * @inheritdoc */ public static function tablename() { return 'posts'; } public function rules() { return [ [['title', 'content'], 'required'], ]; } } and simple controller: controller namespace app\controllers; use yii; use yii\rest\activecontroller; class postscontroller extends activecontroller { public $modelclass = "app\models\post"; } ?> it configuration of web.php file: $config = [ 'id' => 'basic', 'basepath' => dirname(__dir__), 'bootstrap' => ['log'], 'components' => [ 'request' => [ 'cookievalidationkey' => 'wch

c# - Facebook SDK for Windows mobile -

is possible use facebook sdk windows phone 8.1? because not providing sdk although there before 2 years ago. i'm working visual studio community 2015. can 1 please tell me if there way integrate facebook windows phone 8.1 app. thank you! which sdk http://facebooksdk.net/docs/phone/ refer to? though has windows 8 in heading, if drill sub page, mentions compatibility 8.1 well. example, http://facebooksdk.net/docs/phone/config/

bash - How to check if any array element is not holding a specific string -

is there way of checking elements in array, , if elements in array not holding string mystring return true? example, if element of array 2 elements holding mystring want make return false, else true: [mystring][mystring] = false/don't [mystring][a] = false/don't [@#$2][mystring]=false/don't [asda][wrwe]=true q: how can check array n elements, if none of elements within array hold other value other mystring should return true? my attempt was: element_number in `seq 0 $going_through_the_elements_of_the_array`; my_var=${the_array[$element_number]} if ! [[ $my_var == "$my_string" ]] echo " should printed" exit fi done this should want: case ${the_array[@]} in *my string*) echo "true" ;; *) echo "false" ;; esac it expands array single string uses re mechanism in case statement search targe

sql server - Unable to retrieve the Value from the XML from the root element -

i working on xml retrieve data using sql server, not able retrieve correct values query listed below. declare @xml xml, @hdoc int set @xml = ' <root> <a> <b>name</b> <y> <c> <d>m</d> </c> </y> <e>test1</e> </a> <a> <b>cx</b> <e>test</e> </a> </root> ' exec sp_xml_preparedocument @hdoc output, @xml select a.d, a.b, a.e openxml(@hdoc, 'root/a') ( d [nvarchar](20) '//y/c/d', b [nvarchar](500) 'b', e [nvarchar](500) 'e' ) -- output of query d b e m name test1 m cx test the problem want corresponding value of <d> , wherever, <d> not provided, return value "m". need value null wherever <d> value not provided. any appr

oracle - Multiple rows of SQL in single row under different columns -

please find below example: empid. compcode. amount 101. basic. 1000 101. hra. 200 102. basic. 1200 102. hra. 200 102. medical. 100 i format data shown below: emplid basic. hra. medical 101. 1000. 200. 102. 1200. 200. 100 is there way generate output using oracle sql? your problem solve using pivot in sql. select * ( select empid,compcode,amount tablename ) s pivot ( sum(amount) compcode in ('basic', 'hra', 'medical') )as pvt

python - How to give different weights to features while training a SGDClassifier in Scikit? -

from documentation, class sklearn.linear_model.sgdclassifier(class_weight=none) like class_weight function, how give weights particular aspects of feature set? feature sets consists of raw text, , name. while training want give more weight name, , less weight raw text. how do that? there no option give weights features in sgdclassifier , , far know in no other learner in scikit-learn. in general, not make sense give different weights features. after all, machine learning because want computer figure out features more important. if name more important raw text classifier figure out internally. now, if still want have different features different importance can combine multiple classifiers: train 1 classifier using name feature, , train classifier using raw text features. combine output taking weighted average of each classifier's output. can give name -classifier higher weight, increase name 's impact on combined output.

sql - Calculate average cost correctly after purchase or delete purchase? -

i have table table_transactions in table when inserting or deleted update 2 tables itemremains , ref_items column averagecost. example data formula avgcost = (currentqty*currentavgcost+new.qty+new.amt)/(currentqty+new.qty) 1)purchase itema - 10units - 10$ = itemremains qty=10 ref_items avgcost=10 2)sale itema - 4units - 25$ = itemremains qty=6 ref_items avgcost=10 3)purchase itema - 10units - 15$ = itemremains qty=16 ref_items avgcost=13,13 4)purchase itema - 10units - 20$ = itemremains qty=26 ref_items avgcost=15,77 my questions how return or calculate if delete 1 of purchase? if delete purchase 3)purchase itema - 10units - 15$ = itemremains qty=20 ref_items avgcost=13,13 trigger work after inserting or deleting on table table_transactions trigger code declare variable current_qty d_qty; declare variable current_cost d_amt; declare variable new_cost d_amt; begin if (inserting) begin current_qty =0; current_cost =0; new_cost =0; select su

javascript - dropzone doesnt upload some pictures (internal server error 500) -

i use dropzone file(images) upload. when upload on local computer, files upload successfully. when upload files on web host, dropzone gives iternal server error on pictures(not all). experiment, uploaded 1 picture several times. , dropzone gives error, , sometime doesnt(on same picture). not blame picture's size (i tried pictures 4-5 kb). here's code dropzone.autodiscover = false; var mydropzone = new dropzone("div#dropzone", { url: "{{action('admintourscontroller@storeimage')}}", addremovelinks : true } ); mydropzone.on('sending', function(file, xhr, formdata){ formdata.append("_token", $('meta[name="csrf_token"]').attr('content')); // laravel expect token post value named _token default }); var = 1; mydropzone.on('complete', function(a, b, c){ var src = json.parse(a.xhr.responsetext).uploaded_path; $("<input type='hidden' name='gallery-img-" + i++

Creating new VM nodes, is this vagrant or puppet? -

i have 8-cpu server , installed centos 7 on it. dynamically , programmatically spin , down vm nodes work, ex. hadoop nodes. is technology use vagrant or puppet, or else? have played around vagrant, appears every new node requires new directory in file system, can't spin new vm far can tell api call, think. , doesn't there's real api vagrant, machine-readable output. , if understand properly, puppet deals configuration management pre-existing nodes. is either of these correct technology use or there else more fitting want do? yes, can use vagrant spin new vm. configuration of particular vm can done using puppet. take at: https://www.vagrantup.com/docs/provisioning/puppet_apply.html and if you're problem having separate directories each vm, you're looking multimachine setup: https://www.vagrantup.com/docs/multi-machine/ for example using multiserver setup take @ https://github.com/mlambrichs/graphite-vagrant/blob/master/vagrantfile in config

css - Unnecessary code generating in HTML website -

Image
i developed html website. used html , css only. while looking view source, showing unnecessary code @ end of page , files too. how can solve this? you're infected ramnit file infector virus. it's not curable. win32/ramnit.a file infector ircbot functionality infects .exe, , .html/htm files, , opens door compromises computer. using backdoor, remote attacker can access , instruct infected computer download , execute more malicious files. infected .html or .htm files may detected virus:vbs/ramnit.a. win32/ramnit.a!dll related file infector seen infection. has ircbot functionality infects .exe, .dll , .html/htm files , opens door compromises computer. component injected default web browser worm:win32/ramnit.a dropped ramnit infected executable file. source: http://www.techspot.com/community/topics/not-curable-win32-ramnit-a-infected-and-ruined-everything-please-help.195427/ you'll need wipe hard disk , reinstall os

html - divs overlap in phone -

first of wondering why wait! of past questions have not been well-received, , you're in danger of being blocked asking more. is @ top of page, if when struggling enough understand going on, being threatened exclusion struggling understand going on? nevertheless, have 2 divs sit nicely on laptop screen, 1 of them overlaps @ other screen resolutions? using clear:both makes video floated right sit under 1 floated left not centred.i sure simple else need it, please. page is: http://dowgivaf.uk/freeze.html the code is: i keep trying insert code not work properly. have read comes out messed up. @ risk of being excluded not being able answer own question, can me this, please?

javascript - External file java script does not function -

my code not function in external file <script src="action_input.js"></script> . put code in <body></body> or <head></head> , not function. my code functions in <body><script> code js</script></body> , not so. code is: // identify form elements: var search_code = document.getelementbyid('search_code'); var insert_code = document.getelementbyid('insert_code'); var result = document.getelementbyid('result'); var button = document.getelementbyid('button'); var audio = new audio('sound.wav'); // respond button click button.onclick = function validate() { // show verification result: if(search_code.value == insert_code.value) { result.textcontent = 'cod gasit'; result.classname = "ok"; audio.play(); //http://soundbible.com/tags-winning.html } else { result.textcontent = 'codul nu este corect'; r

ways to process a post request in django view and re-send it to another view -

i have view receives post request html form, , process , send post request view of original data, , more data add it, i read http not allow pass same post request received. i read official documentation , don't find way of doing so, , read library requests, , when tried using , send request made httpresponseredirect , keeps sending post writing tons of things in address bar, , kind of looks tries use instead of post. i found here these questions: which function in django creates httprequest instance , hands view? simulating post request in django but don't understand how can create request in efficient way, django app, , send view of app. post_data = {'name': 'something'} response = requests.post('http://localhost:8000/polls/thanks/', name = "somthing") content = response.content return httpresponseredirect(content) views nothing more functions in python there isn't stopping passing parameters separate view. whet

Android fixed background image in scrollview while scrolling -

i have situation need scrollview have background image shouldn't scroll along it's parent when moving. before of suggest me links setting background image , that, have tried , it's not working. the whole story goes like: have activity fragments have own backgrounds input fields. when focusing on input fields, keyboard appears , background image squeezes. put image on background of scrollview fixed issue of squeezing background raised concern background image should stay static while scrolling parent scrollview. the second solution of may suggest setting background of activity rather playing scrollview. that's right, had make style element background of theme appears odd while transitioning different fragments plus adds overhead when have lot of code , fragments move forward , back. that's point stuck. have gone through links below, if need know tried or not. link1 link2 link3 ... , on below layout using fragments (it's being done programmaticall

ffmpeg video filter with RGB -

i need filter mp4 video ffmpeg using rgb values. example opengl this void main() { vec4 color = texture2d(stexture, vtexturecoord); float colorr = (1.0 - color.r) / 2.0; float colorg = (1.0 - color.g) / 2.0; float colorb = (1.0 - color.b) / 2.0; gl_fragcolor = vec4(colorr, colorg, colorb, color.a); } can ffmpeg command ? if ffmpeg compiled libx264, can use ffmpeg -i input.mp4 -vf extractplanes=r -c:v libx264rgb -pix_fmt rgb24 output.mp4 you can specify bgr24 or bgr0 (32-bit; has unused 4th channel)

C# Naming Guideline for local variables -

this question has answer here: c# field naming guidelines? 12 answers a question naming local variables in c# method takes parameter of same name please see code below private int dosomething(string activationcode) { ... int ??whatnametochoosehere?? = convert.toint32(activationcode); ... } what strategy apply in above scenario note: method paramter , local variable differ type only you cannot that. proper way of doing name variables different names.

java - Apache POI works with .xls but not with .xlsx -

i'm creating export apache poi. when i'm using export xls, hssfrow , hssfcell, working perfect both locally , on server. when change xlsx, xssfcell , xssfrow, working locally not on server. giving me following error: there unexpected error (type=internal server error, status=500). fail save: error occurs while saving package : part /docprops/core.xml fail saved in stream marshaller org.apache.poi.openxml4j.opc.internal.marshallers.zippackagepropertiesmarshaller@7621d6eb not sure why happening. ideas? poi version 3.11, have tried others same result. here pf export component: <p:commandlink styleclass="exportallpages" ajax="false"> <p:dataexporter type="xlsx" target="techdata" filename="tdam" pageonly="false" postprocessor="#{global.postprocessxls}"/> </p:commandlink> here exception have in logs: fail save: error occurs while saving package : part /docprops/core.x

While calling exe file from vb6, We are getting error exe stopped working -

i called exe file vb6. shell "d:\sample.exe rpno, prtvw, glngbr". we getting error exe stopped working i meant post comment don't have enough rep that. first of shell "d:\sample.exe rpno, prtvw, glngbr" think part of name of program trying open "d:\sample.exe" , rest without "" quotes can try shell "d:\sample.exe", rpno, prtvw, glngbr secondly try opening program want open shell statement , see if same error because getting error should have nothing program used open error coming program "sample.exe" rpno, prtvw, glngbr i've never seen before, , tried myself , didn't work @ all, try these out , hope helps.

c# - ListView Delete Refresh does not work? -

i'm developing wpf mvvm application basic crud functionality. use listview contains , show data users. when add or update user listvew refreshing immediately, after delete command listview not refreshing. in case have close application , run again make refresh listview. xaml <listview name="lstusers" scrollviewer.horizontalscrollbarvisibility="disabled" scrollviewer.verticalscrollbarvisibility="disabled" issynchronizedwithcurrentitem="true" itemssource="{binding viewlist.view, updatesourcetrigger=propertychanged, isasync=true}" selecteditem="{binding currentselecteduser, mode=twoway}" height="150" margin="0,40,10,260" grid.columnspan="2" grid.rowspan="2"> view model private observablecollection<user> _users; public userviewmodel() { _users = new observablecollection<user>(getallusers()); // paging control

node.js - s3 failing on preflight even with cors all methods and origins -

i don't understand... seems simple, yet fails on options call put request. "response preflight invalid" s3 cors: <?xml version="1.0" encoding="utf-8"?> <corsconfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <corsrule> <allowedorigin>*</allowedorigin> <allowedmethod>get</allowedmethod> <allowedmethod>put</allowedmethod> <allowedmethod>post</allowedmethod> <maxageseconds>3000</maxageseconds> <allowedheader>*</allowedheader> </corsrule> </corsconfiguration> the url: http://localhost:9002/api/sign_s3?file_name=wcyqzgrkis24or4mv4hdpp-uxdnq6p9mvoj6drmpcju.jpg&file_type=image/jpeg the url s3 (keys removed): https://jayehtest.s3.amazonaws.com/wcyqzgrkis24or4mv4hdpp-uxdnq6p9mvoj6drmpcju.jpg?awsaccesskeyid=xxx&content-type=image%2fjpeg&expires=1454923884&am