Posts

Showing posts from March, 2014

asp.net web api2 - OWIN and CORS - One CORS Header to rule them all? -

there seems lots of different answers on define cors headers when using owin. have seen these ... 1) add grantresourceownercredentials method context.owincontext.response.headers.add("access-control-allow-origin", new[] { allowedorigin }); 2) in configuration(iappbuilder app) method of startup.cs app.usecors(microsoft.owin.cors.corsoptions.allowall); 3) add web.config <system.webserver> <httpprotocol> <customheaders> <add name="access-control-allow-origin" value="*" /> <add name="access-control-allow-headers" value="content-type" /> <add name="access-control-allow-methods" value="get, post, put, delete, options" /> </customheaders> </httpprotocol> </system.webserver> when try multiple options error saying duplicate cors headers , therefore none of them allowed. is there single place can define cors po...

c++ - Initializing a string array -

i try initialize string array std::cin can not code : string *words[6]; (int i=0 ; i<6;i++){ cin >> words[i]; //error } can me!! you don't need create them dynamically: string words[6]; //notice deleted '*' here (int i=0 ; i<6;i++){ cin >>words[i]; } what you've created array of pointers, in every pointer must initalized new before can use , deleted afterwards.

ionic 2 blank after splash page under android 4.3 -

my question similar ionic-mobile-app-gives-white-screen i have created 1 ionic app runs fine in browser, when convert app getting white screen. i have installed white list plugin , allowed urls in config. have kept meta tag. this 1 ionic 2 application. it runs in web , on android devices when use ionic 1. but, can use android 5.0 or higher version run ionic2. i have tried many methods such how-to-debug-the-white-screen-of-death-in-your-ionic-app , can't inspect button debug chrome inspect . my android device: genymotion, htc one, running android 4.3 (api 18).

c# - XmlSerializer.Deserialize only specific classes -

Image
this situation. need create new application based off existing object classes i'm not allowed change being used other projects. need use these object in conjunction new objects in new application. in new application, each action have request , response class, serialized/deserilized sent on sockets company. provide xsd company use form response , send xml. need deserialize xml newly created object, in case called getaccountdetailsmessageresponse. [system.xml.serialization.xmlroot("getaccountdetailsmessageresponse", namespace = "http://test.com.au/")] public class getaccountdetailsmessageresponse { public mynewheader header { get; set; } public accountsresponse response { get; set; } } //here existing class structure need use, , cannot // main class - containing collection of accounts public class accountsresponse : responseheader { public accountsresponse() { acc...

swift - Comparing array of force unwrapped optionals -

i'm writing test: func test_arrayfromshufflingarray() { var videos = [mockobjects.mockvmvideo_1(), mockobjects.mockvmvideo_2(), mockobjects.mockvmvideo_3()] let tuple = shufflehelper.arrayfromshufflingarray(videos, currentindex:1) var shuffledvideos = tuple.0 let shuffleindexmap = tuple.1 // -- test order different xctassert(videos != shuffledvideos, "test_arrayfromshufflingarray fail") } but on last line last line: binary operator '!=' cannot applied 2 '[vmvideo!]' operands arrays can compared == if element type equatable : /// returns true if these arrays contain same elements. public func ==<element : equatable>(lhs: [element], rhs: [element]) -> bool but neither implicitlyunwrappedoptional<wrapped> nor optional<wrapped> conform equatable , if underlying type wrapped does. possible options (assuming vmvideo conforms equatable ): change cod...

How do I get a computer's programing name and static IP address using VB.NET? -

public function getcomputername() string dim computername string computername = system.net.dns.gethostname return computername end function for pc name use: my.computer.name for ip use: private sub getipaddress() dim strhostname string dim stripaddress string strhostname = system.net.dns.gethostname() stripaddress = system.net.dns.gethostbyname(strhostname).addresslist(0).tostring() messagebox.show("host name: " & strhostname & "; ip address: " & stripaddress) end sub

mysql - One PHP Template Page, Call Different Tables with Hyperlinks -

i have table called c33062 displays data rows in page. have twenty other mysql tables same structure , information, different data. instead of creating page each, i'd create hyperlinks each calls links table information. statement is: $query = "select id, year, price_avg_sold, price_sqft, pct_list_sold, adom, sold_nu, sold_chg, year_1, year_2, year_3, year_4, year_5, year_6, year_7, year_8, year_9, year_10 c33062"; so in essence, i'd make hyperlinks each table, c33063, c33064, c33065 etc when clicked, call particular table's data template page. what correct way hyperlink table? set table name variable in each link , variable value. example http://www.name.com?tabe=30063 table 30063 http://www.name.com?tabe=30064 table 30064 and table value $table = $_get['table']; then use variable in query code below: $query = "select id, year, price_avg_sold, price_sqft, pct_list_sold, ado...

python - How to modify Text widget in Tkinter for interlinear anotation -

Image
i wondering if possible create textbox tkinter can handle interlinear input. need able have different lines "connected" each other, , behaviour of each line can independent. here an example . linguistic annotation program. idea if have line, say: this example x.det be.v a.det example.n the spacing of first line automatically adjusted line modified allow enough space each word in second line not overlap words in first line. is there way this? a simple way use fixed width font (such courrier) in characters same width, format pure text padding spaces. from tkinter import * sentence = [ 'this', 'is', 'an', 'example' ] result = [ 'x.det', 'be.v', 'a.det', 'example.n' ] line_start = [0, len(sentence)] # used split sentence lines no longer line_len line_len = 20 # max characters in each line, including spaces segment_len = 0 in range(len(sentence)): s_len = len(sente...

javascript - React Native Pass properties on navigatorIOS pop -

i'm using navigatorios on react native app. want pass properties when navigating previous route. an example case: i'm in form page. after submitting data, want go previous route , based on submitted data how can pass state variables of current element previous route when using pop go back? any code sample appreciated. this classic example of trivially solved redux or other centralized state store. without that, behavior go "back" via navigatorios's pop method? takes no arguments, doubt that'll work @ all. the best use push , can define route contain form data in passprops : this.props.navigator.push({ title: navigatoriosexample.title, component: navigatoriosexamplepage, backbuttontitle: 'custom back', passprops: { formdata }, }); but really, use redux.

javascript - <input> onmouseenter don't work with left mouse button in Firefox, IE, Edge -

this code works perfect in chrome not in firefox, ie, edge. <input type="text" readonly onmouseenter="this.style.backgroundcolor='red'" onmouseleave="this.style.backgroundcolor='white'"> <input type="text" readonly onmouseenter="this.style.backgroundcolor='red'" onmouseleave="this.style.backgroundcolor='white'"> when press left mouse button on first input , move on second input - color changes correctly in chrome. not in firefox, ie, edge (second input not recorded onmouseenter event). with right , middle mouse button, works code perfect in broswers. do know how fix it? why not work? (i can use raw javascript in project)

python - Inheriting from defaultddict and OrderedDict -

i have tried inheriting both collections.defaultdict , collections.ordereddict so: class ordereddefaultdict(defaultdict, ordereddict): pass and so: class ordereddefaultdict(ordereddict, defaultdict): pass in order created ordered default dict (a class should remember order in new default items generated) seems throw error stating: typeerror: multiple bases have instance lay-out conflict i have read here it's because they're both implemented in c. upon disabling python's c implementation of ordereddict commenting section in collections module: try: _collections import ordereddict except importerror: # leave pure python version in place. pass i have managed inherit both, not seem work expected. have 2 questions then: why can't inherit 2 classes written in c? understand if wouldn't able inherit class written in c why can inherit 1 , not 2? implementing requested class easy subclassing ordereddict , overriding __getitem__() ma...

How to implement range index alias in elasticsearch 2.X -

elastic has replaced range filter range query. having trouble creating index alias using range , unfortunately there not example on index alias page on how this. alias "female_teen" documents gender = female , age = 13-19. here using create alias: range seems ignored. { "actions" : [ { "add" : { "index" : "people", "alias" : "female_teen", "filter" : { "term" : { "gender" : "female" } }, "query" : { "range" : { "age" : "[13 19]" } } } } ] }

html - fixed header in cordova -

i'm trying fix header top, if user scrolls trough list search input field , title bars stays on top of screen. @ moment header scrolls content in body... this have: <body ng-controller="searchctrl" class="animated fadein"> <div class="bar bar-header fixed bar-assertive" style="padding-bottom: 20px;"> <a href="index.html"class="button icon-left ion-chevron-left smaller button-clear button-white"></a> <h1 class="title">suche</h1> </div> <label class="item item-input has-header fixed" style="margin-top: 5px;"> <input type="text" placeholder="solothurn durchsuchen..." name="text" ng-model="searchbox.storename"> </label> <br> the fixed class is: position: fixed; any appreciated! just test add !important css fixed class. 1 of...

java - Deploying a Play Framework application on port 80 beside Apache -

i'm looking way deploy play-framework-1.0 application on port 80. first made zip file 'dist' command, unzipped it. when run command lauch application ( play-java-1.0-snapshot/bin/play-java -dhttp.port=80 -dhttp.adresse=127.0.0.1 ), error : [error] p.c.s.nettyserver - failed listen http on /0.0.0.0:80! oops, cannot start server. play.core.server.serverlistenexception: failed listen http on /0.0.0.0:80! @ play.core.server.nettyserver.play$core$server$nettyserver$$bindchannel(nettyserver.scala:215) @ play.core.server.nettyserver$$anonfun$1.apply(nettyserver.scala:203) @ play.core.server.nettyserver$$anonfun$1.apply(nettyserver.scala:203) @ scala.option.map(option.scala:146) @ play.core.server.nettyserver.<init>(nettyserver.scala:203) @ play.core.server.nettyserverprovider.createserver(nettyserver.scala:266) @ play.core.server.nettyserverprovider.createserver(nettyserver.scala:265) @ play.core.server.serverprovider$class.createserver(serverprovider.scala:25) @ play....

sending data between erlang and c++ -

i using tcp connection send data c++ server. have read ei library when given binary has bunch of functions decoded value out of binary. egs, ei_decode_string, ei_decode_long , others. i trying these simple things: 1. create socket , connect it. {ok, socket} = gen_tcp:connect({127,0,0,1}, 8986, []). 2. use gen_tcp:send/2 send data. gen_tcp:send(socket, term_to_binary("stackoverflow")). therefore, sending binary format of string server. my server, c++ code, gets data , trying whatever client sends me on socket using ei_decode_string like: ideally, when decoded should string, "stackoverflow" since told decode_as_string binary. made sure had enough space in resulting buffer. char *p = (char*)malloc(sizeof(char) * 100); int index = 0; int decoded = ei_decode_string(buff, &index, p); cout<<"the decoded value "<<p<<endl; i not able decode string sent.! missing something? how can send data , decode on server ...

haskell - List of Strings to single String -

i'm trying exercise in book, define function: onseperatelines :: [string] -> string which takes list of string , returns single string when printed shows strings on separate lines. i'm struggling converting list single string onseperatelines :: [string] -> string onseperatelines ls = [x | x <- ls] i can write functions take string , convert list , list outputs list, can't figure out how take list , convert single string. a string nothing list of characters: type string = [char] hence, onseperatelines :: [[char]] -> [char] now, if need application, it's idea first ask hoogle if there's there . whole lot of results: unlines :: [string] -> string -- that's exactly function you're trying implement! unwords :: [string] -> string -- similar, insert spaces, not newlines joinpath :: [filepath] -> filepath -- not relevant here concat :: [[a]] -> [a] -- general task of flattening nested list ...

javascript - Rendering newline character in VueJS -

i'm creating note app users can add note entering multiline text in textarea. when save note in firebase being saved newline (\n) characters want visualize. therefore, wrote filter replaces these characters <br /> , works great. though, need render data using {{{note.content}}} , user can inject html, css, , js executed. should use dompurify validate content or there way safely render newline characters? wrap content in pre element. a <pre> element pre serve whitespace within it, eg: this followed newline, not can tell <br /> <br /> <pre>you can see newline after me! woohoo!</pre> will result in: this followed newline, not can tell can see newline after me! woohoo! this way, not need filtering of newlines.

php - Using Twitter typeahead to make search bar work -

Image
i using twitter typeahead make search bar work coming across issues. purpose of search bar : the search bar used search usernames of users registered site. approach : in head of home.php : <script src="typeahead.min.js"></script> header.php (which included in home.php ): <input type="text" class="form-control" placeholder="search user" name="typeahead"> <script> $(document).ready(function(){ $('input.typeahead').typeahead({ name: 'typeahead', remote:'search.php?key=%query', limit : 10 }); }); </script> search.php : <?php include("connect.php"); $key=$_get['key']; $array = array(); $query = mysqli_query("select * users username '%{$key}%'"); while($row=mysqli_fetch_assoc($query)){ $array[] = $row['username']; } echo json_encode($array); ?...

angularjs - Javascript Self Invoking functions in Angular controllers -

i use self invoking functions include javascript code inside angular controller (i think saw somewhere best practice). controller looks this: (function() { // code })() i use gulp merge controllers 1 file. question this. mean of javascript code invoked , executed when application starts? if so, guess not approach. there solutions issue? comments? thanks no, not code gets executed. when define angular modules (function() { 'use strict'; angular .module('mymodule', []) .controller('mycontroller', ['$http', mycontrollerfunc]); function mycontrollerfunc ($http) { // ... } })(); what gets executed angular methods register module , controller. actual controller logic in callback function, , gets called when controller invoked (e.g. router). so, good, , wrapping code in anonymous functions idea keep, example mycontrollerfunc , out of global namespace.

functional programming - Manual pearson correlation in r -

Image
how create function manually calculates pearson correlation in r. know there native function called cor , if want apply below equation in r each combination of columns in data frame, how it? i wish knew how, believe requires many for-loops, nested for-loops etc make happen , not strong @ programming yet. hope attempt such newbie me can learn. thanks example: set.seed(1) df = data.frame(v1 = rnorm(10), v2=rnorm(10), v3=rnorm(10), v4=rnorm(10)) # v1 v2 v3 v4 # v1 1.00 -0.38 -0.72 -0.24 # v2 -0.38 1.00 0.60 0.18 # v3 -0.72 0.60 1.00 0.08 # v4 -0.24 0.18 0.08 1.00 first write helper function calculate covariance: v <- function(x,y=x) mean(x*y) - mean(x)*mean(y) then use calculate correlation: my_corr <- function(x,y) v(x,y) / sqrt(v(x) * v(y)) here's quick check works correctly: > my_corr(df$v1, df$v2) [1] -0.3767034 > cor(df$v1, df$v2) [1] -0.3767034 note calculating correlation way numerically unstable...

javascript - Angular/WebApp design -

i'm creating web app in angular (beginner) , i'm little deep it. potentially want alter design , input on other possible designs of app. there 2 routes, first route main page shows table full of links. when click on 1 of these links, send me second route (i pass in key data urls second route first one). second route tabulated view of information. one reason wanted alter design have 1 route (with tabs). first tab show table full of links (first route) , rest of tabs show information (second route) therefore compiling 1 route. possible click on link (first route) , lead me next tab key information can use populate tab or better separate out? example (current design): first route (table): person_1, person2, person3 person_4, person5, person6 second route (pretend clicked person1): tab, tab, tab. information person in each tab (using parameters passed in through url). if want show in different tab hide tab using jquery or ng-hide. when link clicked inste...

embedded linux - Yocto Jethro: no package provider for gdbserver -

i using freescale.github.io freescale community bsp. in local.conf, machine ?? = "wandboard" , have added extra_image_features += "tools-debug" this add gdb, gdbserver , other tools rootfs. summary = "debugging tools" license = "mit" inherit packagegroup pr = "r3" mtrace = "" mtrace_libc-glibc = "libc-mtrace" rdepends_${pn} = "\ gdb \ gdbserver \ strace \ ${mtrace} \ " however, got error bitbake cannot find pn gdbserver. computing transaction...error: can't install packagegroup-core-tools-debug-1.0-r3@all: no package provides gdbserver is gdbserver removed bsp? why removed? if not, locate gdbserver? try rebuilding gdb, there's rare bug in gdb makefiles means appears not build gdbserver. clean , force rebuild: bitbake gdb -cclean ; bitbake gdb -c unpack

javascript - Unable to pass Redux store beyond React Router -

i've set first react app using redux, react-router, , react-router-redux. i'm passing store <provider> , can see it's available in provider's props, yay. beyond point lost. it's not available in child <router> unless explicitly add store well. however, regardless of whether pass store directly <router> , available via context in child connect(app) layer (which don't understand well), time gets actual <app> component, store isn't available in either props or context. know should available via props, cannot figure out why it's not getting passed down. i've read lot of similar questions mine, none of approaches i've seen have solved problem. know it's i'm missing conceptually, related connect and/or mapstate/dispatchtoprops , , possibly getinitialstate . i've spent last 2 weeks trying understand of this, i've seen enough videos , read enough articles...i need more specific advice in relation cod...

html - How can I have a div with an image with a white background floated left? -

my code in css is: .logo{ content:url(http://www.dylionsrugby.com.au/wp-content/uploads/2012/04/lion.png/600x600); background-color: white; float: right; } and in html have: <div class="logo"></div> am missing something, nothing appears?` your question general. simulate right positioning using positioning property on image , not on div. .logo{ width: 250px; height: 75px; background-image: url("http://www.slate.com/content/dam/slate/articles/health_and_science/science/2015/07/150730_sci_cecil_lion.jpg.crop.promo-xlarge2.jpg"); background-color: white; background-repeat: no-repeat; background-size: 100% 100%; float: right; } <div class="logo"></div>

algorithm - Find a subset with sum within a range -

how can find subset of array sum of elements within given range? for example: let = [ 1, 1, 3, 6, 7, 50] let b = getsubsetsumrange(3, 5) so b potentially [1, 1, 3], [1, 3], [3], [1, 3]; doesn't matter order need 1 of them. you use dynamic programming approach solve problem. let f[i][j] have value true if possible select numbers among numbers original subset a[1..i] sum equal j. i vary 1 length of a , , j 0 max inclusively, max second number given range. f[i][0] = true i definition (you can select empty subset). then f[i][j] = f[i - 1][j - a[i]] | f[i - 1][j] logically means if can select subset sum j elements 1..i-1 , can subset 1..i , , if can select subset sum j - a[i] elements 1..i-1 , adding new element a[i] subset, can desired sum j . after have calculated values of f , can find f[n][j] true values j lying in desired range. say have found such number k . algorithm find required set that: for = n..1: if f[i - 1][k - a[i]] ...

c++ - Deleting allocated memory pointed by vector element crashes the program -

i´m writing dynamic program read oracle database metadata , build structure in memory. i´m facing problem when freeing memory created new hold data oracle sends me. structure put inside vector , runs fine (i can read , process it). here code (database stuff removed focusing on problem): struct oraclecolumnstruct { std::string name; ub2 ocitype; fieldtype fieldtype; int size; char *buffer; sb2 *indicator; ocidefine *definehandler; }; std::vector<oraclecolumnstruct> columns; void allocatecolumns() { columncount = ... // whatever database (unsigned int = 0; < columncount; i++) { ocitype = ... // whatever database size = ... // whatever database oraclecolumnstruct data; data.name = "whatever"; data.ocitype = ocitype; data.size = size; data.buffer = new char[size]; data...

javascript - Preview an image before it is uploaded -

i want able preview file (image) before uploaded. preview action should executed in browser without using ajax upload image. how can this? please take @ sample code below: function readurl(input) { if (input.files && input.files[0]) { var reader = new filereader(); reader.onload = function(e) { $('#blah').attr('src', e.target.result); } reader.readasdataurl(input.files[0]); } } $("#imginp").change(function() { readurl(this); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="form1" runat="server"> <input type='file' id="imginp" /> <img id="blah" src="#" alt="your image" /> </form> also, can try sample here .

java - How to transform MultiMap<String, String> to MultiMap<String,Integer>? -

i got following multimap , how transform multimap<string,integer> ? multimap<string, string> multimap= // contents here use multimaps#transformvalues(multimap, function) : multimap<string, integer> transformed = multimaps.transformvalues(multimap, new function<string, integer>() { @override public integer apply(string value) { return integer.valueof(value); } }); see also: newcollectiontypesexplained#multimap collectionutilitiesexplained#multimaps functionalexplained

Laravel 5 > orderBy difference between up and down votes > pagination -

assumed i´ve got following db setup users table id name posts table id post votes table id user_id post_id vote (1 = up, -1 = down) ... , let´s assume i´ve setup every one-to-many relationship correctly :) how query top 5 posts measured difference between it´s , down votes? something great ... $posts = post::wherehas('votes', function($query) { $query->orderbyraw('sum(\'vote\'), desc'); })->get(); ... , i`d paginate later on. now working :) $posts = post::has('votes') ->leftjoin('votes', 'votes.post_id', '=', 'posts.id') ->selectraw('posts.*, sum(votes.vote) votes_sum') ->groupby('posts.id') ->orderby('votes_sum', 'desc') ->paginate(5);

Automating a Web Service Login for SAP Business Objects in VBA -

Image
is possible automate login sap business objects web services using analysis microsoft excel com add-in in excel? when run code, presented below "logon sap businessobjects bi platform" window requiring user manually enter web services credentials (note: these not same sap credentials). ideally, able set fields (user, password, web service url, system, , authentication) without user interaction. i attempting automate refresh of excel workbooks connected sap business objects using vba code. reviewing developer documentation available on sap (see here ), able automate commands. there command "saplogon", able provide sap logon credentials, not web service ones. a sample of code below: 'refresh dashboard lresult = application.run("sapexecutecommand", "pausevariablesubmit", "off") lresult = application.run("sapsetrefreshbehaviour", "on") lresult = application.run("sapexecutecommand", "refresh...

python - Import hooks for PyQt4.QtCore -

i'm attempting setup import hooks through sys.meta_path , in similar approach this question . this, need define 2 functions find_module , load_module explained in link above. here load_module function, import imp def load_module(name, path): fp, pathname, description = imp.find_module(name, path) try: module = imp.load_module(name, fp, pathname, description) finally: if fp: fp.close() return module which works fine modules, fails pyqt4.qtcore when using python 2.7: name = "qtcore" path = ['/usr/lib64/python2.7/site-packages/pyqt4'] mod = load_module(name, path) which returns, traceback (most recent call last): file "test.py", line 19, in <module> mod = load_module(name, path) file "test.py", line 13, in load_module module = imp.load_module(name, fp, pathname, description) systemerror: dynamic module not initialized the same code works fine python 3.4 (althoug...

javascript - event to modify sibling element -

in web page, have grid of divs. in each div 3 divs, 2nd hidden, want when user hovers on 3rd div, 1st div becomes hidden , 2nd displayed. i'm using jquery. <div class="container"> <div class="hello">hello</div> <div class="who">sailor </div> <div onmouseover="whoon();" onmouseout="whooff();" class="hover">hover me</div> </div> <div class="container"> <div class="hello">hello</div> <div class="who">dolly </div> <div onmouseover="whoon();" onmouseout="whooff();" class="hover">hover me</div> </div> <div class="container"> <div class="hello">hello</div> <div class="who">kitty </div> <div onmouseover="whoon();" onmouseout="whooff();" class="hover"...

html - Window.open not working as expected -

i'm trying link open popup , not new window, tried following , few variations yet reason window opens in new tab. <script>window.open('add_game.php', 'height=200,width=150')</script> add 2nd , 3rd parameters follows , should work. <script>window.open('add_game.php','new', 'toolbars=0,width=400,height=320,left=200,top=200,scrollbars=1,resizable=1')</script>

javascript - Determine if string is Date or Number -

i'm trying determine if string number or date. here code: this._getfieldformat = (value) => { // check if date let d = new date(value); if (!isnan( d.gettime() ) ) { return 'date'; } // check if boolean // isnan(false) = false, false number (0), true number (1) if(typeof value === 'boolean'){ return 'boolean'; } // check if string number if(!isnan(value)){ return 'number'; } return typeof value; }; it works date like: 2016-04-19t23:09:10.208092z . problem 1 valid date ( wed dec 31 1969 16:00:00 gmt-0800 (pst) ) , isnan(new date()) return false (a date number). any idea on how out of loop? so happening called coercion. since javascript dynamic typing when give 2 different types js engine tries coerce 1 of types reasonable or thought meant. for instance: isnan("37"); false because "37" converted number 37 isnan(new date()) return false (a date number) ...

javascript - angularStrap: open directive from modal and pass value from the scope to the directive scope -

i using strapangular modal , having problems in passing scope directive. search answer on internet , didn't found. $scope.showmodal = function(index) { var scope = $scope.$new({productitem: "dddddd"}); var mymodal = $modal({ templateurl: "<div modal-view product='productitem' class='modal' tabindex='-1' role='dialog'></div>", persist: true, scope: scope, show: false, html: true, animation: 'am-fade-and-scale', placement: 'center' }); mymodal.$promise.then(mymodal.show); }; the directive loads '$scope.product' undefined.

python - Computing separate tfidf scores for two different columns using sklearn -

i'm trying compute similarity between set of queries , set result each query. using tfidf scores , cosine similarity. issue i'm having can't figure out how generate tfidf matrix using 2 columns (in pandas dataframe). have concatenated 2 columns , works fine, it's awkward use since needs keep track of query belongs result. how go calculating tfidf matrix 2 columns @ once? i'm using pandas , sklearn. here's relevant code: tf = tfidfvectorizer(analyzer='word', min_df = 0) tfidf_matrix = tf.fit_transform(df_all['search_term'] + df_all['product_title']) # line issue feature_names = tf.get_feature_names() i'm trying pass df_all['search_term'] , df_all['product_title'] arguments tf.fit_transform. not work since concatenates strings not allow me compare search_term product_title. also, there maybe better way of going this? you've made start putting words together; simple pipeline such enough prod...

sql - recursive geometric query : five closest entities -

the question whether query described below can done without recourse procedural logic, is, can handled sql , cte , windowing function alone? i'm using sql server 2012 question not limited engine. suppose have national database of music teachers 250,000 rows: teachername, address, city, state, zipcode, geolocation, primaryinstrument where geolocation column geography::point datatype optimally tesselated index. user wants 5 closest guitar teachers location. query using windowing function performs enough if pick arbitrary distance cutoff , 50 miles, not selecting 250,000 rows , ranking them distance , taking closest 5. but arbitrary 50-mile radius cutoff might not succeed in encompassing 5 teachers, if, example, user picks instrument different culture, such sitar or oud or balalaika; there might not 5 teachers of such instruments within 50 miles of location. also, imagine have query conservatory of music has sent list of 250 singers, students have been accepted sc...

javascript - Modal Image Click with Bootstrap -

i'm new programming , i'm trying complete lesson on udacity course uses modals through bootstrap. here code, not getting results on test page. enter image description here enter image description here

asp.net mvc - BindModel gets executed before ActionFilterAttribute -

i have started running weird problem. i have asp.net project in have api takes post params. since use interface, used custom deserializer read post object. worked till last few days. but, 1 day started getting 500 - internal server error saying "cannot create instance of interface. ... through createmodel". @ time, using postman app. there virtually no change in code, thought may postman app got corrupted. i wasn't sure, had tried same query on fiddler , worked fine. now, after 3-4 days, fiddler stopped working same error. after digging through, found somehow 'bindmodel' has started executing may be before actionfilterattribute. i'm not sure how possible. there workaround overcome situation? post http call not entering jsonfilter's onactionexecuting method error msg: [missingmethodexception: cannot create instance of interface.] system.runtimetypehandle.createinstance(...) system.runtimetype.createinstanceslow(...) system.activat...

How can I fix ValueError: Too many values to unpack" in Python? -

i trying populate dictionary contents of text file ("out3.txt"). my text file of form: vs,14100 mln,11491 the,7973 cts,7757 ...and on... i want dictionary answer of form: answer[vs]=14100 answer[mln]=11491 ...and on... my code is: import os import collections import re collections import defaultdict answer = {} answer=collections.defaultdict(list) open('out3.txt', 'r+') istream: line in istream.readlines(): k,v = line.strip().split(',') answer[k.strip()].append( v.strip()) but, get: valueerror: many values unpack how can fix this? you have empty line s in input file , suspect 1 of line s have not shared has many commas in (hence "too many values unpack"). you can protect against this, so: import collections answer = collections.defaultdict(list) open('out3.txt', 'r+') istream: line in istream: line = line.strip() try: k, v = l...

R - return datatable row number of max or min value in sliding window -

i trying retrieve row number associated max/min value in sliding-window. i'm subsetting row number retrieve value different column. per request, here dput(head(dataframe3)): structure(list(time = c("00:00:01|", "00:00:03|", "00:00:04|", "00:00:05|", "00:00:06|", "00:00:07|"), average = c(8, 5.75, 5.33333333333333, 5.23076923076923, 5.15, 5.15), negativechange = c(-3, -0.75, -0.333333333333333, -0.230769230769231, -0.15, -0.15), positivechange = c(0, 0, 0.107843137254902, 0.210407239819005, 0.291176470588235, 0.291176470588235)), .names = c("time", "average", "negativechange", "positivechange"), class = c("data.table", "data.frame"), row.names = c(na, -6l), .internal.selfref = <pointer: 0x0000000001300788>) here upload of truncated text data file, , subsequently, code used import r , point trying code end timestamp portion: http://t...

python - Get one related object in single request for Django ORM -

i have models class book(models.model): title = models.charfield(max_length=255, blank=false, null=false) class like(models.model): user = models.foreignkey(user, related_name="like_user", blank=false, null=false) book = models.foreignkey(book, related_name="like_book", blank=false, null=false) class meta: unique_together = ["user", "book"] i want books , check if current user liked each book in single request book.objects.select_related('like_book').all() won't work because of many results book.objects.prefetch_related('like_book').all() will cache like_set contain likes book. not 1 user. in end want have additional field is_liked books = book.objects.magic_fetch('like_book', user=self.request.user).all() books[0].is_liked * updated address comments * so speaking, think use: book.objects.annotate(is_liked=case(when(like__user=self.request.user, then=true), def...

css - why HTML sub menu in a wrong postion? -

Image
i have html,css menu. i want sub menu center main menu(ul.menu) why there space on left? ul.menu li:hover ul defined left: 0 , nearest parents ul.menu , don't understand these space come from? .menu-main-container { padding-bottom:52px; margin-top:-60px; margin:10px auto; } ul.menu { z-index: 597; text-align:center; position: relative;background: gray; width: 960px; margin:auto!important;} ul.menu li { display: inline-block; line-height: 2.1em; vertical-align: middle; zoom: 1; } ul.menu { display:block; letter-spacing:2px; color:#333; font-size:13px; text-decoration: none; padding:0 35px; text-transform:uppercase; font-weight:normal !important;} ul.menu a:hover {background:#efefef; color:#ad7f12} ul.menu, ul.menu li, ul.menu ul { list-style: none; margin: 0; padding: 0; color:#333; } ul.menu li:hover { position: relative; z-index:599; text-decoration:none; background:#efefef; } ul.menu li:hover ul {} ul.menu ul { display: none; } ul.menu ul li { float...

php - How to Xdebug multiple sites hosted on my local machine that make requests to each other (in PhpStorm)? -

i'm attempting xdebug working phpstorm on multiple sites. have 2 sites both being served in same vagrant vm on local machine: http://my-app.dev (makes requests api below, xdebug working) http://my-rest-api.dev (receives requests, xdebug not working) my app makes requests rest api. when visit http://my-app.dev in browser, xdebug working correctly in phpstorm project. i'll have api project open in phpstorm well. when set breakpoints in api project never hit (even though app making requests api). way can breakpoints work in api if open browser tab , type in api's endpoints directly address bar. know there extensions can use test api endpoints, not convenient @ all, since requests cumbersome build manually each time. both projects set in phpstorm listen php debug connections . tried turning on xdebug.remote_autostart = 1 in xdebug.ini file on vm server. i've set max. simultaneous connections 10 in phpstorm debug preferences. any solution on how can debug...

c# - how to insert from different inputs -

i trying insert different values table database , retrieve these values different tables , input textbox in windows form etc .. but syntax of query not correct , want know if there possiblity insert these inputs in 1 query : string query4 = @"insert facfin (nom_pren_rs,trimestre,exercice,nb_factures,prix_total_ht) values ('" + textbox1.text + "','" + textbox3.text + "','" + textbox2.text + "', select cast(count(trimestre) varchar(6)) nb_factures facture (facture.nom_pren_rs='" + textbox1.text + "'), select cast(sum (cast(prix_vente_ht bigint ))as varchar(15)) facture (facture.nom_pren_rs='" + textbox1.text + "') ) "; i know there risk of sql injection , know have use parameters wanted test code see if insert , syntax of insert wrong the nb_factures should varchar(6) casted the column prix_vente_ht in table facture varchar ca...

d - SSE strangeness with Functions -

i've been playing around d's inline assembler , sse, found don't understand. when try add 2 float4 vectors after declaration, calculation correct. if put calculation in separate function, series of nan s. //function contents identical code section in unittest float4 add(float4 lhs, float4 rhs) { float4 res; auto lhs_addr = &lhs; auto rhs_addr = &rhs; asm { mov rax, lhs_addr; mov rbx, rhs_addr; movups xmm0, [rax]; movups xmm1, [rbx]; addps xmm0, xmm1; movups res, xmm0; } return res; } unittest { float4 lhs = {1, 2, 3, 4}; float4 rhs = {4, 3, 2, 1}; println(add(lhs, rhs)); //float4(nan, nan, nan, nan) //identical code starts here float4 res; auto lhs_addr = &lhs; auto rhs_addr = &rhs; asm { mov rax, lhs_addr; mov rbx, rhs_addr; movups xmm0, [rax]; movups xmm1, [rbx]; addps xmm0, xmm1; movups ...