Posts

Showing posts from February, 2015

java - Antimalware Service Executable slow down IO operations -

i have java program write temporary files in temp directory. temp directory on ssd. write operation fast. specific sample data very, slow , cpu of antimalware service executable high (30% - 35%). write speed approx. 50 kb/s. if set breakpoint on write loop cpu of antimalware go 0%. if continue cpu of antimalware go high. can repeat multiple time. it antimalware scanning temporary data intensively. why occur , how can prevent this? to prevent scanning can exclude files being scanned file name, directory name, file extension of associated process. so, open “windows security essential” or “windows defender” (type in start menu). go settings -> excluded files , locations.

java - executor service with multiple tasks on each thread -

after researching web couldn't find answer hope here can. i'm running executorservice multiple threads (lets 2 simplification). on each thread i'm submitting runnable has many tests in it. tests use software on computer. my scenario if test fails on thread - need restart software on computer. so if test on thread 1 needs restart software - need pause work of second thread (all threads needs pausing including thread one). on second thread test might using software - want finish running test - pause next tests in line/the thread - restart software - , continue work on both (all) threads. things i've tried , not quite sure how implement are: offers john these videos: advanced java: multi-threading . thanks in advance help. i suggest have scheduledthreadpoolexecutor . you implement instance of singleton store status (pause / run) software (take care of concurrency), , each of runnable test, you'll check state @ beginning of execution. if stat

Use a variable to name a class in python -

suppose want following psuedocode work method generateclass(string name, <string,type>[] attributes) class name() //used int // char b attributes[0].[0] attributes[0].[1] attributes[1].[0] attributes[1].[1] how in python?

system commant wont work as in shell when calling a python comman on Ubuntu from R -

i'm trying invoke within r system command invokes call python script (that includes import pandas) following: getwd() [1] "/home/production" > system("python in_tag_main_model/python_scripts/connect_to_couchbase.py") traceback (most recent call last): file "in_tag_main_model/python_scripts/connect_to_couchbase.py", line 11, in <module> import pandas pd importerror: no module named pandas within connect_to_couchbase.py i'm calling pandas, isn't recognized, though when i'm running exact command machines shell: production@va-rsrv01:~$ python in_tag_main_model/python_scripts/connect_to_couchbase.py production@va-rsrv01:~$ it works great,any ides why system isn't working me? thanks in advance! it looks r system function executing different python executable. have 3 options specify executable want: you absolute path: system("/anaconda2/bin/python in_tag_main_model/python_scripts/connect_to

php - Fatal error: Call to undefined function expect_popen() -

since upgrade php 5.5.9 5.6 on ubuntu 14.04 lts server have been getting problems expect library php. keeps displaying fatal error in description. believe package need libexpect-php5 . installation checks confirm installed: root@k1:/etc/php5/conf.d$ dpkg --get-selections | grep -v deinstall | grep expect empty-expect install expect install expect-dev install expect-lite install libexpect-ocaml install libexpect-ocaml-dev install libexpect-perl install **libexpect-php5** install // installed right? libexpect-simple-perl install libghc-hspec-expectations-dev install libghc-hspec-expectations-doc install libghc-hspec-expectations-prof install libnet-scp-expect-perl install libtest-expect-perl inst

javascript - Multiple-tags input field -

Image
i started angularjs, , working on simple form tags input field , submit button. input field supposed accept multiple tags on clicking submit tags saved array. now using ngtagsinput directive found on github( http://mbenford.github.io/ngtagsinput/ ). directive gives me <tags-input></tags-input> html element creates input field accepts multiple tags before submission. here like(look @ tags field): this works fine, need directive gives me similar functionality instead of element ie. <tags-input> , want attribute can include inside conventional <input> element <input attribute='tags-input'> . question: is there way can use ngtagsinput attribute? are there other directives out there may suit need? if yes please post link in answer. thanks in advance. no. can see on tags-input.js file, directive configured element : return { restrict: 'e', require: 'ngmodel', scope: { tags: '=ng

javascript - How do you normalize weights q-learning with linear function approximation -

i developing simple game program show q-learning linear function approximation. screen shot in game, there uncountable state. have consider many factors player's position, speed, , enemy's position (there 12 ~ 15 enemy objects). ended changing algorithm using table use linear function approximation. i decided around 20 ~ 22 features.(constant, player position, player speed, of enemies position). , there after implementing algorithm, got stuck in problem. weight value overflowed in few second after running program. found didn't normalize features , weight. it easy normalize feature value because each feature has bound . however, wasn't enough normalize feature value. still end overflow. my problem how normalize weights. below code implement normalize features. //f feature f[0] = 1; f[1] = this.getnormminmax(this.player.x,0,cc.winsize.width); f[2] = this.getnormminmax(this.player.vel,-80,80); for(var i=0; i<poolist.length;++i)

Firebase v3 GoogleAuthProvider not saving email -

Image
(1) question: is there way read user email having uid? (permitted super user or server) ps.: don't want save in realtime database, because though current user can change it, can erase or put fake email.. (2) problem: i'm trying retrieve user email googleauthprovider in firebase v3 thats code i'm using: signinwithgoogle(): promise<any> { let provider = new firebase.auth.googleauthprovider(); provider.addscope("https://www.googleapis.com/auth/userinfo.email"); return firebase.auth().signinwithpopup(provider) .then((result) => { console.log(result.user.email); console.log(result.credential); let token = result.credential.accesstoken; return this.createorupdateuser(result.user, token); }); } the result: result.user.email # null result.user.providerdata[0].email # correct_email@gmail.com though email in providerdata, not attached auth.. fireba

c - Funtion pointer to function returning pointer to said function type -

for implementation of finite state machine, achieve this: currentfunction = currentfunction(int arg); with currentfunction being function pointer function returns function pointer of same function type. is possible in c? how? first of all, need obscure things always originate muddy program design. trying solve problem x, , think method y it. ask how y working, though not correct solution begin with. root of problem might x incorrectly designed. that being said, can using struct wrapper , thereby taking advantage of incomplete struct types: typedef struct func_wrapper_t { struct func_wrapper_t (*func) (int); } func_t; ... func_t some_function (int x) { ... return (func_t){ some_function }; } ... int main(void) { func_t f = some_function(0); return 0; }

ios - iCarousel get user tapped index -

i want index user has tapped.i have tried several ways detect none of working. here have tried. func carousel(carousel: icarousel, didselectitematindex index: int) { print("this has been tapped carousel \(index)") } func carouselcurrentitemindexdidchange(carousel: icarousel) { let index=carousel.currentitemindex print("this current index \(index) ") } func carousel(carousel: icarousel, viewforitematindex index: int, reusingview view: uiview?) -> uiview { let webv:wkwebview! webv = wkwebview(frame: cgrectmake(10, 10, 250, 250)) if let updatedresource = mydict[index+1]{//name of resource want load let url = nsbundle.mainbundle().urlforresource(updatedresource, withextension: "html") let requestobj = nsurlrequest(url: url!); webv.loadrequest(requestobj); let tapgesture = uitapgesturerecognizer(target: self , action: selector("tap

php - How to add Tabs and Line Breaks from Array using file_put_contents -

i connecting sqlite database. use following query results: $db = new sqlite3('sshtunnel.sqlite'); $results = $db->query('select * tunnel'); now, want add tabs , line breaks row array using file_put_contents in php: while ($row = $results->fetcharray(sqlite3_assoc)) { file_put_contents($file, $row, file_append).php_eol; } the results displayed unformatted in 1 line: testtesttest test test test i wish have structure: test test test test test test where mistake? while ($row = mysqli_fetch_row($results)) { foreach($row $value) { $value .= '|';//use ever char append file_put_contents($file, $value, file_append | lock_ex); } file_put_contents($file, '\n', file_append | lock_ex); }

asp.net - How can I have two TinyMCE editors on the same page with different configurations -

i've been debugging whole day. i have asp.net mvc project , tinymce editor template, problem last tinymce shown. @html.textarea(string.empty, new { id = textareaid, value = viewdata.templateinfo.formattedmodelvalue }) <script type="text/javascript"> tinymce.init({ mode: "exact", elements: "textarea#@textareaid", theme: "modern", inline: true, plugins: [ "advlist autolink lists link image charmap print preview hr anchor pagebreak", "searchreplace wordcount visualblocks visualchars code fullscreen", "insertdatetime media nonbreaking save table contextmenu directionality", "template paste textcolor colorpicker textpattern imagetools" ], toolbar1: "insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | lin

ASP.NET MVC - Does PDB files makes site perform slow -

we have asp.net mvc website hosted in azure web apps. everytime deploy site takes literally couple of minutes load. i've noticed site performs slow. when looking @ bin folder, noticed quiet lot of pdb files. wondering if pdf files causing performance issue. insights appreciated. pdb files don't affect performance in way , used when debugging.

python - Legend with labels besides seafile heatmap -

i have following code: from string import letters import numpy np import pandas pd import seaborn sns import matplotlib.pyplot plt sns.set(style="white") # compute correlation matrix df = pd.dataframe(np.random.randint(0,100,size=(100, 4)), columns=list('abcd')) corr = df.corr() # generate mask upper triangle mask = np.zeros_like(corr, dtype=np.bool) mask[np.triu_indices_from(mask)] = true # set matplotlib figure f, ax = plt.subplots(figsize=(11, 9)) # generate custom diverging colormap cmap = sns.diverging_palette(220, 10, as_cmap=true) # draw heatmap mask , correct aspect ratio sns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, square=true, #xticklabels=5, #yticklabels=5, linewidths=.5, cbar_kws={"shrink": .5}, ax=ax) plt.show() how possible place additional legend right of plot says thinks like: a: first label b: ... c: ... d: ... i have label correlation bar says 'correlation'. data of course not real data.

Passing several variables from Excel to Python with XLwings -

i have same question post multiple variable (and macro instead of function) ( passing variable excel python xlwings ) i try sub hello () dim name,name2 string runpython ("import test; test.sayhi('" & name1 & " , " & name2 & "')") end sub but error : --------------------------- error --------------------------- traceback (most recent call last): file "<string>", line 1, in <module> typeerror: sayhi() missing required positional arguments: 'name2' how overcome error plz ? thanks help your string resolves single argument. fix single quotes this: runpython ("import test; test.sayhi('" & name1 & "' , '" & name2 & "')"

linux - HTML::Grabber Perl Empty String at Grabber.pm line 78 -

script source : http://kayrules.com/list-malay-words/ i'm trying run script: #!/usr/bin/perl use html::grabber; use lwp::simple; $numargs = $#argv + 1; if ($numargs != 1) { print "usage: ./grabber.pl <letter>\n"; exit; } $letter = uc($argv[0]); $url = "http://ms.wiktionary.org/wiki/wiktionary:senarai_perkataan_$letter"; $dom = html::grabber->new( html => get($url)); @array; $dom->find('div.mw-content-ltr li')->each(sub { $body = $_->find('a')->attr('title'); @words = split / /, $body; @dashed = split /-/, @words[0]; push @array, lc(@dashed[0]); if(@dashed[1]) { push @array, lc(@dashed[1]); } }); $anagrammed; @filtered = uniq(@array); foreach $word (@filtered) { $anagrammed = anagram($word); $length = length($word); print "$length|$anagrammed|$word\n"; } sub uniq { %seen; gr

python - Remove a nested list if any of multiple values is found -

i have list of lists , i'd remove nested lists contain of multiple values. list_of_lists = [[1,2], [3,4], [5,6]] indices = [i i,val in enumerate(list_of_lists) if (1,6) in val] print(indices) [0] i'd lists of indices conditions can: del list_of_lists[indices] to remove nested lists contain values. i'm guessing problem try check against multiple values (1,6) using either 1 or 6 works. you use set operation: if not {1, 6}.isdisjoint(val) a set disjoint if none of values appear in other sequence or set: >>> {1, 6}.isdisjoint([1, 2]) false >>> {1, 6}.isdisjoint([3, 4]) true or test both values: if 1 in val or 6 in val i'd not build list of indices. rebuild list , filter out don't want in new list: list_of_lists[:] = [val val in list_of_lists if {1, 6}.isdisjoint(val)] by assigning [:] whole slice replace indices in list_of_lists , updating list object in-place : >>> list_of_lists = [[1, 2], [3, 4],

neo4j - show excerpt of database -

i'm looking cypher query show excerpt of data in neo4j database. need provide quick overview of kind of data can found in db. the query should show number of nodes labels possible relations between them. want subset of nodes in database contains full complexity of data in database. i tried accomplish limit limits total number of nodes returned. thanks help there's set of procedures via apoc library(neo4j 3x): apoc.meta.graph e.g. call apoc.meta.graph iterate on graph , collect labels , relationships finds. there's writeup of meta procedures in blog post .

How to send a packet with Contiki using uip? -

i'm looking way send packets contiki using uip interface. give idea of current state, feel blind man bangs against walls. below code shows do. if share hint grateful. process(allo_process, "allo process"); autostart_processes(&allo_process); process_thread(allo_process, ev, data) { process_begin(); sensors_activate(button_sensor); (;;) { process_wait_event(); if (ev == sensors_event && data == &button_sensor) { uip_send("allo", 4); } } process_end(); } edit i managed send packets rime interface using example: contikidoc . people care, don't forget add line makefile: contiki_with_rime = 1 . packets printed "radio messages" panel. however, original question remains open: how use uip interface? tried reproduce first example in doc part of code missing :-/

c# - Drag and Drop upload file by using Generic Handler in visual studio webform -

when trying pass files(drag , drop) generic handler, context.request.files.count in generic handler contains 0, i've tried lot of ways still unable solve it. generic handler: commonfunction _commonfunction = new commonfunction(); public void processrequest(httpcontext context) { context.response.contenttype = "text/plain"; httpfilecollection files = context.request.files; string dhidstr = context.request["dhid"]; int dhid = convert.toint32(dhidstr); //string destination = _commonfunction.generatefolderpath(dhid); string invalidfiles = ""; var appsettings = configurationmanager.appsettings; var dropboxfileext = appsettings["dropboxfileext"].tostring(); var dropboxfolder = appsettings["dropboxfolder"].tostring(); //var finaldestination = dropboxfolder.replace("[dealfolder]", destination); list<string> fileexts =

c# - Converting a SQL join into LINQ with EF with filtering -

i'm learning entity framework , attempting convert existing sql query linq query, struggling convert it. select taskitems.description,taskitemresponses.iscompleted,taskitemresponses.userid,taskitemresponses.notes tasklists left join taskitems on tasklists.tasklistid = taskitems.tasklistid left join taskitemresponses on taskitemresponses.taskitemid = taskitems.taskitemid , taskitemresponses.userid = '1' this works fine me, brings following data, showing list of tasks, , if user has responded of them, if they've completed , notes they've added. description iscompleted userid notes task null null null task b null null null task c null null null task d 1 1 i've done now. task e null null null but when i'm trying convert linq query within c# can't figure out syntax, far i've got var query = t in dbcontext.tasklist join ti in dbcontext.taskit

javascript - Map.prototype.set returns with undefined in internet explorer 11 -

i'm trying build react application, , use react-css-modules. runs fine under ff , chrome, in ie11 encounter following issue, @ page loading following exception message: unable property 'set' of undefined or null reference it seems issue occurs in generateappendclassname (line 37) of react-css-modules, stylesindexmap remain undefined. seems following operation set undefined map. stylesindexmap = stylesindex.set(styles, new _simplemap2.default()); in theory map.set should return map under ie11, understand problem?

multithreading - Filling a vector in order using threads in C++ -

i'm attempting fill huge double vector (1929x1341, might bigger) data, right takes around 10 seconds do. for reference, code far: vector<vector<float>> vector1; (int x = 0; x < mapwidth; x++) { vector<float> vector2; (int y = 0; y < mapheight; y++) { int somenumber = calculatenumber(x,y); vector2.push_back(somenumber); } vector1.push_back(vector2); } i'm thinking should able cut down on work-time dividing work on separate threads. separate second for-loop each own thread. unfortunately, not threads. main issue vectors needs filled in order. can't separate second vector own threads , combine them later, put them semi-random order. i've looked mutex , condition variables, not able find solution specific problem. would willing me out here? you may like: std::vector<std::vector<float>> vector1(mapwidth); std::vector<std::thread> threads; (int x = 0; x < mapwidth; x++) {

reactjs - TypeError: Cannot read property 'setState' of undefined in JEST while testing onChange event, anyone can help me in resolving this issue -

i started learning react & jest framework, created login page 2 input control login jsx: import react 'react'; import es6bindall 'es6bindall'; export default class login extends react.component { constructor(props,context) { super(props,context); this.state = { username: '', password: '', loginmsg : '' } es6bindall(this,['txtonchange','handleclick']); } txtonchange(e){ this.setstate({ loginmsg: '' }); if (e.target.name === 'username') { this.setstate({ username: e.target.value }); } else if (e.target.name === 'password') { this.setstate({ password: e.target.value }); } } handleclick() { if(this.state.password === 'testing' && this.state.username =

winforms - DataGridViewComboBox dropdown size on multiline -

i have datagridviewcombobox in datagrid. 1 of other columns allows multiple lines of text entered. my problem dropdown in datagridviewcombobox expands fill cell. dropdown 1 line. here examples: http://imgur.com/qx4wsuk . in example, first column's dropdowns should 1 line, , not fill whole cell. you need set cell style's alignment , display style: var datagrid = new datagridview(); var combobox = new datagridviewcomboboxcolumn(); combobox.defaultcellstyle = new datagridviewcellstyle { alignment = datagridviewcontentalignment.topleft}; combobox.displaystyle = datagridviewcomboboxdisplaystyle.combobox; msdn on datagridviewcontentalignment msdn on datagridviewcomboboxdisplaystyle

jsf - Spring webflow & PrimeFaces expression language - bean method is interpreted as a property in websphere but not tomcat -

i have webflow input: <input name="allocationconfig" required="true"/> which used correct controller when searching list of stores in primefaces autocomplete input: <p:autocomplete completemethod="#{controllerlookup.get(allocationconfig).searchforstore}" ... /> controllerlookup spring bean returns particular controller (which spring bean) when passed allocationconfig webflow. controller returns list of stores display in autocomplete input. this works fine when run on tomcat, when deployed onto websphere, error: javax.el.propertynotfoundexception: /web-inf/flows/manage-allocation/manage-allocation.xhtml @76,97 completemethod="#{controllerlookup.get(allocationconfig).searchforstore}": property 'get' not found on type com.web.controller.allocations.controllerlookup @ com.sun.faces.facelets.el.tagmethodexpression.invoke(unknown source) @ org.primefaces.component.autocomplete.autocomplete.broadcast(autocom

android - Caused by: java.lang.NumberFormatException: Invalid double: "["5.0","5.0"]" -

i integrating citrus wallet in company's app , stuck on following error. the stack trace: java.lang.runtimeexception: error occured while executing doinbackground() @ android.os.asynctask$3.done(asynctask.java:304) @ java.util.concurrent.futuretask.finishcompletion(futuretask.java:355) @ java.util.concurrent.futuretask.setexception(futuretask.java:222) @ java.util.concurrent.futuretask.run(futuretask.java:242) @ android.os.asynctask$serialexecutor$1.run(asynctask.java:231) @ java.util.concurrent.threadpoolexecutor.runworker(threadpoolexecutor.java:1112)

php - Store 2 inputs having same name into 1 'address' column of the database -

i have 2 address inputs 'address1' , 'address2' having same name 'address[]' . want put value of both inputs in single address column of database problem data of 2nd input being stored database. index.php $addressdata = $_post['address']; foreach ($addressdata $addressvalue) { $query = "insert `users` (`name` ,`address` , `birthdate` ,`age` , `coach` , `phone`,`email` ,`password`) values ( '".mysqli_real_escape_string($link, $_post['name'])."' , '".mysqli_real_escape_string($link, $addressvalue)."' ,'".mysqli_real_escape_string($link, $_post['birthdate'])."' ,'".mysqli_real_escape_string($link, $_post['age'])."' , '".mysqli_real_escape_string($link, $_post['coach'])."' , '".mysqli_real_escape_string($link, $_post['phone'])."' , '".mysqli_real_

load balancing - IBM MobileFirst Session Affinity -

environment details: ibm mfp 7.1.0.00.20160401-2103 ibm liberty 8.5.5.5 setup: 1. mfp app deployed in 2 liberty servers. 2. mobile devices can access app via webserver , requests routed on round-robin fashion properly. device: 1. android 2. ios problem: 1. user has logged app , accessing adapter. 2. these adapters protected security test. 3. still request routed liberty server's round-robin webserver. 4. ideally, request should forward server authenticated. configuration: 1. in authenticationconfig.xml - securitytest & realm defined. 2. login initiates via wl.client.login({realmname}); realmname - mapped in security test 3. adapters protected security test defined in authconfig.xml 4. liberty server - manual & unique cloneid provided both server in httpsession of server.xml 5. in webserver, plugin-cfg.xml configured session affinity along cloneid of each server. <uri affinitycookie="jsessionid" affinityurlidentifier="jses

matrix - how to merge matrices in R with different number of rows -

i merge several matrices using row names. these matrices not have same number of rows , columns. instance: m1 <- matrix(c(1, 2, 3, 4, 5, 6), 3, 2) rownames(m1) <- c("a","b","c") m2 <- matrix(c(1, 2, 3, 5, 4, 5, 6, 2), 4, 2) rownames(m2) <- c("a", "b", "c", "d") m3 <- matrix(c(1, 2, 3, 4), 2,2) rownames(m3) <- c("d", "e") mlist <- list(m1, m2, m3) for them get: row.names v1.x v2.x v1.y v2.y v1.z v2.z 1 4 1 4 na na b 2 5 2 5 na na c 3 6 3 6 na na d na na 5 2 1 3 e na na na na 2 4 i have tried use lapply function merge: m <- lapply(mlist, merge, mlist, = "row.names", = true) however, did not work: error in data.frame(c(1, 2, 3, 4, 5,

How to filter documents in a tm corpus in R based on metadata? -

i using r tm package , trying select documents index , metadata: orbit_corpus<-corpus( tm_corpus, readercontrol = list(reader=myreader)) meta(my_corpus[[1]]) author : a8 origin : department heading : whib id : 1 year : 2013 i find documents within first hundred documents of corpus have been published in 2013. works identify whether metadata 'year' document 1 2013. meta(my_corpus[[1]],"year") == 2013 [1] true i need gives me option find among first 100 indexes, meet criterion. imagine similar (but not work , unfortunately not generate list of documents). meta(orbit_corpus[[1:100]],"year") == 2013 error in x$content[[i]] : recursive indexing failed @ level 4 many help! you use tm_filter on first 100 documents of corpus ( orbit_corpus[1:100] ) tm_filter(orbit_corpus[1:100], fun = function(x) meta(x)[["year"]] == "2013") from documentation tm_filter returns corpus containing document

java - Aspect is not intercepting HttpStatusReturningLogoutSuccessHandler.onLogoutSuccess() method -

i trying log users login , logout activity, able intercept login using pointcut expression org.springframework.security.web.authentication.authenticationsuccesshandler.onauthenticationsuccess() . but logout activity doesn't intercept using pointcut expression org.springframework.security.web.authentication.logout.httpstatusreturninglogoutsuccesshandler.onlogoutsuccess() below loglogoutactivity() @after("execution(* org.springframework.security.web.authentication.logout.httpstatusreturninglogoutsuccesshandler.onlogoutsuccess(..))") @transactional public void loglogoutactivity(joinpoint joinpoint) throws throwable { preparelogandsave(historylogcode.logged_out.getid(), historylogcode.logged_out.getvalue(), "successfully logged out."); } does know how log logout activity? btw, using spring security authenticate users. in advanced.

android - React Native PixelRatio.get() returns a value outside the provided "buckets" for Nexus 5x -

based on react native documentation, pixelratio.get() should return 1 of following values device pixel density: - pixelratio.get() === 1 mdpi android devices (160 dpi) - pixelratio.get() === 1.5 hdpi android devices (240 dpi) - pixelratio.get() === 2 iphone 4, 4s iphone 5, 5c, 5s iphone 6 xhdpi android devices (320 dpi) - pixelratio.get() === 3 iphone 6 plus xxhdpi android devices (480 dpi) - pixelratio.get() === 3.5 nexus 6 when calling pixelratio.get() on nexus 5x density value 2.625 . expected? supposed manually manage values between basic ones or bug inside react native? fyi, i'm using rn v0.24 react native deferring android density. android documentation explains well: each generalized size , density spans range of actual screen sizes , densities. example, 2 devices both report screen size of normal might have actual screen sizes , aspect ratios different when measured hand. similarly, 2 devices report screen density of hdpi might h

sql - mysql sum only specific groups of a table -

is there way sum specific groups of table? example if have keys / vals / 1 / 2 b / 3 b / 3 c / 1 c / 1 and want grouping , c not others such b above: keys / vals / 3 b / 3 b / 3 c / 2 this seems straightforward stored proc not sure if possible query? union all non-b part b part: select keys, sum(vals) tablename keys <> 'b' group keys union select keys, vals tablename keys = 'b'

java - hibernate extend more entities with a single metadata table -

i have entities in java web project, each entity defined in specific table. due continuos customizations required on entities model, i've decided create 1 metadata entity , table save additional attributes of existing entities, follows: id, entitytype, entityid, metakey, metavalue i'd use metadata entity extend dynamically entities need additional key/value attributes, referencing uniquely entity entityname , entityid. is there smart way to that? right now, everytime need store additional key/value entity, call specific method on metadatadao add key/value, , retrieve once load entity data, i'd need smarter way manage storing/reading/attaching metas entity. hope question clear. best regards

android - Cordova sqlite does not create DB on $cordovaSQLite.openDB or window.openDatabase -

i'm trying store data in sqlite db @ ionic app. i'm creating db , 1 table following code: var db = null; angular.module('starter', ['ionic', 'starter.controllers', 'ngcordova', 'slick']) .run(function($ionicplatform, $cordovasqlite) { $ionicplatform.ready(function() { if (window.cordova && window.cordova.plugins.keyboard) { cordova.plugins.keyboard.hidekeyboardaccessorybar(true); cordova.plugins.keyboard.disablescroll(true); } if (window.statusbar) { statusbar.styledefault(); } if (window.cordova) { db = $cordovasqlite.opendb({ name: "kog.db" }); $cordovasqlite.execute(db, "create table if not exists teams (id integer, title text, day text, fromtime text, totime text, location text)"); console.log("android"); } else { db = window.opendatabase("kog.db", '1', 'kog', 1024 * 1024 * 100); // browser

sorting - How do I extract an algorithm from these instructions? -

i've been reading through the art of computer programming , , though has moments of higher maths can't get, exercises have been fun do. after i've done 1 of them go on answer, see if did better or worse book suggests (usually worse), don't answer current 1 i'm on trying convey @ all. the book's question , proposed solution can found here what i've understood t may number of 'missing' elements or may general constant, don't understand seemingly arbitrary instruction sort them based on components, me looks spinning wheels in place since @ first glance doesn't closer original order. , decision (among others) replace 1 part of paired names number ( file g contains pairs (i,xi) n−t < ≤ n). so question is, simply, how extract algorithm answer? bit of clarification: i understand aims do, , how go translating c++. not understand why supposed sort copies of input file, , if criteria sort by, reasons changing 1 side of pairs number.

c# - How to make Unity call a method after creating an object instance but before it is injected anywhere -

i'm using unity dependency injection. i'd achieve this: public interface myinterface { void mymethod(); } when building unity container: mycontainer.registertype<myinterface, myconcretetype>(); mycontainer.addpostconstructor(x => (x myinterface)?.mymethod()); is possible? there better/more elegant way? another way - register implementations via special factory , use it: class factory { iunitycontainer _container; public factory(iunitycontainer container) { _container = container; } public void register<ttype>() ttype : myinterface { mycontainer.registertype<myinterface, ttype>(new injectionfactory(c => { var result = c.resolve<ttype>(); result.mymethod(); return result; })); } public myinterface get() { _container.resolve<myinterface>(); } } ... public testclass { factory _factory; public t

php - Laravel unable to load view -

just started learning laravel tried create route view when load on web browser says sorry, page looking not found. can 1 me out in codeigniter simple create controller , view , can see on web broswer found laravel difficult codigniter true?? can define me how mvc structure laravel5 found tutorials of old laravel , files , structure change got confused suggestions please routes.php route::get('main', 'main@index'); main.php namespace app\http\controller; use illuminate\http\request; use app\http\requests; use app\http\controllers\controller; class main extends contoller { public function _construct() { $this->middleware('guest'); } public function index() { return "hello world controller"; } } if running laravel project locally, can run through own server. dont need apache server form wamp or xampp,,but need mysql database. start if require database. now go command prompt, navigate directory

Greedy algorithm for knapsack in java -

i trying write simple greedy algorithm knapsack problem. inputs 2 parallel arrays. 1 array contains value of item , other array contains weights. the greedy algorithm i’m trying write go follows: check item has highest value , put in knapsack. set value of item zero. check again item has highest value , put in knapsack if knapsack can still hold it. if can hold it, set value again 0 (after you’ve put in) , start looking highest value again. if knapsack cannot hold anymore end program. i know there lot of better greedy algorithms out there seems me pretty simple 1 , think manage this. problem have go through entire values array find maximum value. when i’ve found put in knapsack , set value zero. problem have go in loop find new highest value item , put in knapsack. don’t know how go doing this. i writing in java. first of all, solve knapsack greedily using highest ratio value/weight instead of value. secondly, not need search maximum in each step if sort list of it

c# - Why the SQL Server error when many clients are trying to write to a table? -

i have simple program on 200 machines logs form user opening. everytime form open sql connection opened, row inserted , guess connection closed ? read connection pooling on default guess not closing ? not allowed call web service or potential better way question why error , there , idea how fix ? or on sql end ? maybe setting can try changing ? using (sqlconnection connection = new sqlconnection(connectionstring)) { try { connection.open(); using (sqlcommand command = new sqlcommand( "insert loggerloanform values(@session, @form, @datestamp, @loannumber)", connection)) { command.parameters.add(new sqlparameter("session", llf.sesssionid)); command.parameters.add(new sqlparameter("form", llf.form)); command.parameters.add(new sqlparameter("datestamp", llf.datestamp));

javascript - Spring boot and Thymeleaf application: jquery is loading but not executing -

Image
i have created simple spring boot application view loading jquery not executing it.details below: my project structure [ my controller my jquerycode my html page import jquery chrome inspector shows jquery loaded fine but still jquery code not running, , if try running directly console., says jquery not defined guys please tell me doing wrong / or missing. if change the: <script type="javascript" to <script type="application/javascript" it should work, type='javascript' not defined media type according http://www.iana.org/assignments/media-types/media-types.xhtml

php - Call array with array_key and get the array value -

i want send key of multi dimension array function , value of key, should item or , sub array. imagine have function: public function returnarray($index){ $arr = [ 'name' => 'ali', 'children' => [ '1' => 'reza', '2' => 'hasan', '3' => 'farhad', 'info' => [ 'a', 'b', 'c' ] ] ]; return $arr[$index]; } and when call this: returnarray('[name][children][info]') the result should info array. what should do? thanks in advance. just fyi, code smells bad - re-implementing array within string, makes me think it's idea access array directly this: $arr["name"]["children"]["info"] but, sake of complete answer

php - How protect .env file laravel -

i move project host can access .env address mysite.com/.env , display file variables , secure data. .env file : app_env=local app_debug=true app_key=base64:xxxxxxx app_url=http://localhost db_connection=mysql db_host=127.0.0.1 db_port=3306 db_database=xx db_username=xx db_password=secret cache_driver=file session_driver=file queue_driver=sync redis_host=127.0.0.1 redis_password=null redis_port=6379 mail_driver=smtp mail_host=mailtrap.io mail_port=2525 mail_username=null mail_password=null mail_encryption=null how can hidden file ?and logical solution? note : (i move files public folder in root directory.) all except public folder move higher level, such folder laravel - http://prntscr.com/bryvu7 change file publi_html/index.php line require __dir__.'/../bootstrap/autoload.php'; to require __dir__.'/../laravel/bootstrap/autoload.php'; and line $app = require_once __dir__.'/../bootstrap/app.php'; to $app = require_once _

angularjs - Fixed Header showing when we navigate to different page in single page application -

i'm using datatables angularjs , fixedheader plugin works fine when table displayed on page. issue when navigate different page (single page application) using angular ui router, fixedheader header still shows. does know why case? it looks issue fixedheader plugin datatables . there angular-datatables module @ https://l-lin.github.io/angular-datatables/#/welcome , has page plugins work it. page lists fixedheader plugin , mentions same issue seeing. see https://l-lin.github.io/angular-datatables/#/withfixedheader . this page says following: beware when using routers. seems header , footer stay in dom when change application state. need tweak code remove them when exiting state. it shows workaround angular-ui-router: $stateprovider.state("contacts", { templateurl: 'somewhereindaspace', controller: function($scope, title){ // stuff }, onenter: function(title){ // stuff }, onexit: function(){ // remove datata

php - Search results form to show another page -

i using vebra plugin on wordpress, use shortcodes show search area , shortcode show results. i have homepage ( http://lytham.voodoodev4.co.uk/ ) using "search" shortcode, "properties" shortcode on http://lytham.voodoodev4.co.uk/?page_id=33 when search on page refreshes page, how push search results page? search php: <div id="propertyfilter" class="vp_search"> <form action="<?php echo vp_get_search_link()?>" method="get"> <?php vp_hidden_fields(); ?> <div class="property_refine">refine search:</div> <div class="property_type"> <?php vp_get_areas(); ?> </div> <div class="property_search_group"> <p>minimum number of bedrooms</p> <?php vp_get_bedrooms(); ?> </div> <div class="property_search_group vp_price"&g