Posts

Showing posts from April, 2014

html - Is the holy grail still important or is that history? -

before html5, lot of effort made have main content in html source, before columns marked aside today. (the optimal way 3 column layouts holy grail ). there 2 reasons this: seo: earlier content counted more important search engines accessibility: show important content first view content without css with html5, can solve problem markup. can markup column on left aside , main content main . dump holy grail, use table-cell css effect of 3 equally high columns , html5 markup tell search engines/screen readers part main content is. is holy grail still important seo/accessibility or history? important other reason? most of time mobile seems answer. in mobile layouts, content order matters. adapt question: is holy grail still state of art multi column layouts? ps: know flexbox coming. i'm asking backwards compatibility in mind.

java - If shared preferences does not contain -

sharedpreferences mprefs = getsharedpreferences("idvalue",0); if(mprefs.contains("date")) { //do }else { mprefs.edit().putstring("date", currentdate); mprefs.edit().commit(); toast.maketext(this, "changed", toast.length_short).show(); } what want code run first time , show toast second time run not show , run code inside first parameters. code runs second "else" statement twice , doesn't run first. it's if string isn't being put in "date"? there wrong code? make editor object , use edit/commit. you can use below code. work fine. sharedpreferences mprefs = getsharedpreferences("idvalue",0); sharedpreferences.editor meditor = mprefs.edit(); if(mprefs.contains("date")) { //do }else { meditor.putstring("date", currentdate); meditor.commit(); toast.maketext(this, "changed", toast.length_sh

javascript - Moment converts date as string for find query and object for aggregate query. How & Why? -

when use find query returns date object whereas while using aggregate gives date string after converting using moment . why? find query this.find({},{ "updated_at":1, "created_at":1, },callback); aggregate query this.aggregate([{ $project:{ "updated_at" :1, "created_at" :1, } }],callback); now when convert date est using moment following results // lets query result in dataarray var created_at = moment(dataarray[0].created_at); var created_at_est = created_at.clone().tz("america/new_york"); dataarray[0].created_at = created_at_est.format('ddd mmm dd yyyy hh:mm:ss'); console.log(typeof(dataarray[0].created_at)); // result string in aggregate query , object in find query i not able understand why happening? can explain this? it's because find provides results mongoose document instances (which can't freely modified) while aggregate provides results plain obj

codeigniter - Google map is having some difficulty on loading? -

<script src="https://maps.googleapis.com/maps/api/js?key="my javascript browser key website"&libraries=places&callback=initautocomplete" async defer></script> this command line giving load google map. , error showing oops! went wrong. page didn't load google maps correctly. see javascript console technical details. please me solve problem new codeigniter please help

Teamcity 9 Nunit 3 reporting -

i cannot life of me teamcity report on nunit tests. ive teamcity 9.1.6 installed nunit 3.4. ive tried executing tests built in runner using msbuild project file no avail. it runs tests , reports them passed in build log cannot real time log and/or tests tab showing. ive tried adding build feature import testresult.xml nothing. there bug in nunit 3.4, prevented working teamcity. fixed in master, , in nunit 3.4.1, planned released within next few days. https://github.com/nunit/nunit/issues/1623

C# DOM XML Parser displays 1 entry instead of 2 -

Image
i have simple xml reader reads xml file dom approach. problem is, have 2 products in particular xml file displays second product (refer invoiceitem box). i'm pretty sure i've made stupid mistake somewhere don't see it. results: source code: http://pastebin.com/rh1pf92n xml: <?xml version="1.0" encoding="utf-8" ?> <invoices> <invoice id="i1"> <invoicedate>21/06/2016</invoicedate> <sellerid>supp001</sellerid> <buyerid>wcs1810</buyerid> <orderid>o1</orderid> <invoiceitem> <product id="r1"> <productname>8gb ram king</productname> <description>8gb ram king brand</description> <capacity>8gb</capacity> <quantity>150</quantity> <unitprice>100</unitprice> </product> <product id="r2">

Fetching MYSQL records in PHP HTML rendring -

i have mysql table 400000 records , query of them till no problem when want loop records, takes 1 or 2 minutes rendering <li> , question best way doing or rending faster? my code: $result = mysql_query('select series ticket_no customer status = 0 order id limit 400000' ); <ul class="lottery slot"> <?php while ($row = mysql_fetch_array($result)) { ?> <li><span><?=$row['ticket_no']?></span></li> <?php } ?> </ul>

php - Send e-mail with page name in it -

i have contact form, e-mails composed , sent using php. use separate php file that. $errors = ''; $myemail = 'mail@gmail.com';// if(empty($_post['name']) || empty($_post['email']) || empty($_post['phone'])) { $errors .= "\n Будь ласка, заповніть усі поля"; } $name = $_post['name']; $email_address = $_post['email']; $message = $_post['phone']; $page = getrequesturi(); if (!preg_match( "/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email_address)) { $errors .= "Некоректна адреса e-mail"; } if( empty($errors)) { $to = $myemail; $email_subject = "contact form submission: $name"; $email_body = "Нове замовлення туру: $page". "Деталі:\n Ім'я: $name \n email: $email_address \n Телефон \n $message"; $headers = "from: $myemail\n"; $headers .= "reply-to: $email_address&

bash - How to avoid calling external utility (grep) twice while maintaining return code & output? -

i have following bash function return property value java-style property file. property wasn't found, should return non-zero. if found, property's value printed & return code must zero. function property_get() { local pfile="$1" local pname="$2" if egrep "^${pname}=" "$pfile" 2>&1 >/dev/null; local line="$(egrep "^${pname}=" "$pfile")" printf "${line#*=}" return 0 # success else return 1 # property not found fi } the question is: how avoid calling egrep twice? first exec status code, 2nd property value. if use $(grep parameters) notation, grep launched in subshell , can't it's return code , won't able determine success or failure of property searching. this should work: ... local line if line=$(egrep "^${pname}=" "$pfile" 2>/dev/null); ...

c++ - OpenCV trained cascade minneighbors set to 100 -

i train cascade classifier detect pedestrian traffic lights, used 5000 positive photos , 1000 negative training, here result xml file got. the problem trained cascade detects many false images. used original code of opencv face detection, , notice best result when set minneighbors in detectmltiscale 100. how should increase trained cascade quality?

javascript - Loading a file path from a text file and inputting it as the source for a video -

i have been trying hardest not have ask here. but, alas... cannot thing work. python programmer have briefest of requirements output in html. dont have time dig jquery , understand syntax, have been trying "bodge" it... alas... no joy! i have written maltego transform in python creates concatonated path (source + entity name) , outputs text file. pass entity web browser redirects user video display page. need import text file using jquery, slot path text file variable , drop variable src video. basic html, sole purpose enable user click full screen on video @ end of series of transforms finds videos associated entity name. nothing fancy. the file contains path called "path.txt". <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <body> <video id="video1" width="520" height="440" src="" type="video/mp4&

arrays - I need to determine if a random number is unique -

i need write function receives number generated in fillarray , determine if has been generated. need return true or false determining if random number must put array. here's working on. help. i've searched similar unfortunately cannot find anything. public class randomgenerator { int arr[] = new int[6]; int size; public void fillarray() { int randnum = (int) (math.random() * 49) + 1; (int = 0; < size; i++) { arr[i] = randnum; alreadythere(randnum); } size++; } public int alreadythere(int randnum) { int find = randnum; boolean found = false; int = 0; while (!found && < size) { if (arr[i] == find) { found = true; } i++; } if (!found) { } return randnum; }

summarize results dynamically produced by a template in R knitr -

i writing report using knitr , template runs analyses on multiple datasets (section 1 of mwe). i can generate summaries of results assigning values variables "stitch together" tables (section 2 of mwe). however, approach cumbersome , inflexible (e.g. lots of typing change specific bits appear in table). how can automate production of summary tables? body of report (mwe.rnw): \documentclass{article} \begin{document} \tableofcontents \newpage \section{run tests} in section run tests using template. <<run-all, include = false>>= library(knitr) ## set data names data_names <- letters[1:3] ## initialize var data data_1 <- null data_2 <- null ## initialize vars chi-squared test results cs_statistic <- null # x-squared cs_parameter <- null # df cs_p_value <- null # p-value ## initialize vars binomial test results bt_p_value <- null # p-value bt_estim

python - Counting Unique Values of Categories of Column Given Condition on other Column -

i have data frame rows represent transaction done user. note more 1 row can have same user_id. given column names gender , user_id running: df.gender.value_counts() returns frequencies spurious since may possibly counting given user more once. example, may tell me there 50 male individuals while less. is there way can condition value_counts() count once per user_id? you want use panda's groupby on dataframe: users = {'a': 'male', 'b': 'female', 'c': 'female'} ul = [{'id': k, 'gender': users[k]} _ in range(50) k in random.choice(users.keys())] df = pd.dataframe(ul) print(df.groupby('gender')['id'].nunique()) this yields (depending on fortune's random choice, chances "quite high" each of 3 keys chosen @ least once 50 samples): gender female 2 male 1 name: id, dtype: int64

ruby - Can we see the request being sent with mechanise gem? -

i trying build request mechanize gem , keep getting redirects error. firstly want know if there's way of seeing actual request being sent after built different params? @agent.verify_mode = openssl::ssl::verify_none cookie = mechanize::cookie.new('xyz_session', @tokenid) cookie.domain = ".mydomain.com" cookie.path = "/" @agent.cookie_jar << cookie @agent.redirection_limit=0 puts @agent.cookies body = {}.to_json #@agent.set_proxy("localhost",3000) @agent.request_headers = {'content-type' => "application/json"} @agent.get("https://access.test.api.mydomain.com/oidc/v1/user/authorise?response_type=code&redirect_uri=http://localhost&client_id=testclient1&service=accountsigninservice&state=any-state") expect(response.code).to eql(302), "authorization code couldn't received" i keep getting redirect limit of 0 reached (mechanize::redirectlimitreachederror) if not

angularjs - Anular js Using with controllers how to change my div as replaced as another div on mouse over on a button? -

anular js using controllers how change div replaced div on mouse on over button ? you can use ng-if or ng-show or ng-hide combined events directives ng-mouseover or ng-mouseenter , ng-mouseleave function supercontroller($scope) { $scope.hovered = false; } angular.module('myapp', []); angular .module('myapp') .controller('supercontroller', supercontroller) <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script> <div ng-app="myapp"> <div ng-controller="supercontroller s"> <button ng-mouseover="hovered=true" ng-mouseleave="hovered=false">hover me</button> <div ng-if="hovered">shown if hovered</div> <div ng-if="!hovered">shown if not hovered</div> </div> </div>

Regex to check if the file format is as expected in C# -

my input list of filenames complete path , need extract items filenames strictly suit below filename format. generic filename format. **c:\my\path\to\file\filename_yyyy-mm-dd_hh-mm-ss.ext** i have tried following regex pattern still see noise. string regexpattern = @"filename_[2-9][0-9]{3}-[0-1][0-9]-[0-3][0-9]_[0-2][0-9]-[0-5][0-9]-[0-5][0-9]\.ext$" let me know if missing something. why use regex when can use datetime s built in parser this: string input = c:\my\path\to\file\filename_yyyy-mm-dd_hh-mm-ss.ext; string filename = path.getfilenamewithoutextension(input); string[] parts = filename.split('_'); if (parts.length != 3) { /*invalid*/ } if (path.getextension(input) != "ext") { /*invalid*/ } if (parts[0] != "filename") { /*invalid*/ } datetime dt; if (!datetime.tryparseexact(parts[1] + "_" + parts[2], "yyyy-mm-dd_hh-mm-ss", cultureinfo.invariantculture, datetimestyles.none, out dt))

swift - Send an IOS image across an api -

i have image trying send rails app via ios app. step 1: this grabs image uiview @iboutlet var notifier: uilabel! @iboutlet var image: uiimage @ibaction func build(sender: anyobject) { let image_data = uiimagepngrepresentation(image.image!) self.service.createnewimage(notifier: notifier, image: image_data!) } step 2: this service func createnewimage(notifier: uilabel, image: nsdata) { let datadictionary = ["image_data": image] self.post("image/build", data: datadictionary).responsejson { (response) -> void in if(response.description[response.description.startindex] character == "s") { notifier.text = "this should success" } else { notifier.text = "failure" } } } this code causes error: *** terminating app due uncaught exception 'nsinvalidargumentexception', reason: 'invalid type in json write (nsconcretemutabledata

ruby on rails - Can you help me figure out what's wrong with my quiz show view? -

in show view, want display multiple choice quiz questions , answers, , add css classes of correct-answer , incorrect-answer , , normal-answer each answer displayed indicate answer 1. answered correctly user 2. answered incorrectly user, or 3. not answered @ (the user picked answer choice). in code, @submitted_quiz.submitted_answers contains answers user inputted. <% question.answers.each |answer| %> <% @submitted_quiz.submitted_answers.each |submitted_answer| %> <% if(submitted_answer.content == answer.content && submitted_answer.question.id == answer.question.id && submitted_answer.got_correct) %> <li><span class ='correct-answer'><%= answer.content %> correct </span></li> <% elsif(submitted_answer.content == answer.content && submitted_answer.question.id == answer.question.id && submitted_answer.got_incorrect) %> <li><span class ='incorrect-answer'><%= answe

css - How to make a horizontal drop down menu in a wordpress theme -

i making first wordpress theme. created horizontal menu, shows sub menu. i'd create drop down menu can see sub menu when put mouse on main menu voice. this code in style.css: /*** menu ***/ #mainmenu ul {margin: 0px 0 0px 0px;float:left;width:100%; list-style: none;} #mainmenu ul li {float: left;margin: 0 0px 0 0;position: relative;} #mainmenu {color: #fff; display: block;font: 14px;padding: 14px 20px;font-family: oswald; text-transform:uppercase;} #mainmenu a:hover {background:#666;} /* button responsive menu*/ .btn-responsive-menu{display: none;float: right;padding:5px;cursor:pointer;margin: -15px 20px 0 0;color: #ffffff;text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25);background:#333;-webkit-border-radius: 4px;-moz-border-radius: 4px;border-radius: 4px;} .icon-bar {display: block;width: 18px;height: 2px;margin:5px;background-color: #f5f5f5;-webkit-border-radius: 1px;-moz-border-radius: 1px;border-radius: 1px;-webkit-box-shadow

Why broadcast receiver is not working in background after app closed in Android 6.0+? -

the problem in broadcast receiver in android marshmallow. <receiver android:name="callreceiver" android:enabled="true" android:exported="true" android:stopwithtask="false" android:permission="android.permission.read_phone_state" android:protectionlevel="signature"> <intent-filter> <action android:name="youneverkill"/> </intent-filter> <intent-filter> <action android:name="android.intent.action.phone_state"/> <action android:name="android.intent.action.new_outgoing_call"/> </intent-filter> </receiver> because android-m i.e. 6+ versions require runtime permissions.you can refer below document: https://developer.android.com/training/permissions/requesting.html https://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-de

duplicates - SAS equivalent to R’s is.element() -

it’s first time i’ve opened sas today , i’m looking @ code colleague wrote. so let’s have data ( import ) duplicates occur want have unique number named vtnr. first looks unique numbers: data m.import; set m.import; vtnr; if first.vtnr=1 unique=1; run; then creates table duplicated numbers: data m.import_dup1; set m.import; unique^=1; run; and table duplicates. here hardcoding numbers, example: data m.import_dup2; set m.import; vtnr in (130001292951,130100975613,130107546425,130108026864,130131307133,130134696722,130136267001,130137413257,130137839451,130138291041); run; i’m sure there must better way. since i’m familiar r write like: import_dup2 <- subset(import, is.element(import$vtnr, import_dup1$vtnr)) i guess there must $ sas? to me looks direct translation of r code import_dup2 <- subset(import, is.element(import$vtnr, import_dup1$vtnr)) would use sql code proc sql; create table

javascript - Expanding a div's height when page scrolls down -

Image
i'm looking way dynamically change div's height when page scrolls. because have fixed panel on right side of screen, , menu banner @ top. when @ top of page, top of side panel touches bottom of banner @ top. thing is, when page scrolled down , banner leaves screen, leaves gap size of top banner between top of screen , top of side panel. i'd put div between them grow in height when page scrolled down. there way in css or js ? i can't have side panel have 100% height because hide elements on top banner, on lower resolution screens. i added ugly images made on paint explain : this css side panel : position: fixed; right: 0; top: 180px; height:calc(100% - 180px); hello not understand banner situation.. regarding need, can call js function whenever scroll: <body> <div class="content" onscroll="dynamicheight()"> </div> <script> function dynamicheight() { var content = document.getelementbyid("c

xamarin.ios - How to assign Background Image to an entry in xamarin forms for ios -

i trying add background image entry in xamarin forms , wrote code rendering in ios , android. android working , ios not working. here sharing rendering code ios: [assembly: exportrenderer (typeof(extendedusername), typeof(renderingentryuname))] namespace ifind.ios { public class renderingentryuname: entryrenderer { // override onelementchanged method can tweak renderer post-initial setup protected override void onelementchanged(elementchangedeventargs<entry> e) { base.onelementchanged(e); if (control != null) { control.textalignment=uitextalignment.center; uiimage img=uiimage.fromfile("images/newimg.jpg"); control.background=img } } } } by default uitextentry used forms entry have border style set uitextborderstyle.roundedrect , background ignored. set border style none , image show up: if (control != null) { control.borderstyle = uitextborderstyle.none;

Sub string in excel -

Image
i substring tow strings tow different columns how first string in column a1 looks like: a76 transfer conditions tools , equipment how string in column b1 looks like: documents/z_documentation/pdf/circular-a76.pdf what have from second string last bit after last / =left(b1,find("@",substitute(b1,"/","@",len(b1)-len(substitute(b1,"/",""))))) and first string have hole thing so string @ , should like: circular-a76.pdf | a76 transfer conditions tools , equipment thanks help write in c1 cell =right($b1,small(if(mid($b1,large(row(indirect("1:"&len($b1))),row(indirect("1:"&len($b1)))),1)="/",row(indirect("1:"&len($b1))),""),1)-1) & " | " & $a1 then press ctrl + shift + enter you

xcode - Change user-defined variable from fastlane -

Image
i have user-defined variable in xcode project - my_variable : linked my_variable in .plist file: , use in code: nsstring *myvariable = [[nsbundle mainbundle] objectforinfodictionarykey:@"my_variable"]; in fastfile have appstore lane and, in case, change value of my_variable . i'm using: env["my_variable"] = "appstorevalue" doesn't work. after bit of research found solution this. i'm using xcargs in gym action, like: gym( scheme: "myscheme", configuration: "release", use_legacy_build_api: 1, xcargs: "my_variable=appstorevalue" )

python - Create a column based on condition pertaining to 2 other columns -

i have 2 columns in pandas dataframe (let's call 'col1' , col2'). both contain true/false values. i need create third column these 2 ('col3'), have true value record if 1 or other of 2 columns has true value in record. currently, i'm doing with: col3 = [] index, row in df.iterrows(): if df.ix[index, 'col1'] == true or df.ix[index, 'col2'] == true: col3.append(true) else: col3.append(false) df['col3'] = col3 it works fast enough size of dataset, there way in one-liner/vectorized way? perhaps using 2 nested np.where() statements? you can use np.logical_or this: in [236]: df = pd.dataframe({'col1':[true,false,false], 'col2':[false,true,false]}) df out[236]: col1 col2 0 true false 1 false true 2 false false in [239]: df['col3'] = np.logical_or(df['col1'], df['col2']) df out[239]: col1 col2 col3 0 true false true 1 fals

php - How to get subtotal from order items collection in magento 1.9.2 community edition -

Image
i trying show order details on frontend backend here code $orderdata = mage::getsingleton('sales/order')->loadbyincrementid($incrementid); $itemcollection = $orderdata->getitemscollection(); foreach($itemscollection $_items) { echo $_items->getname(); echo $_items->getstatus(); echo $_items->getoriginalprice(); echo $_items->getprice(); echo $_items->getqtyordered(); echo $_items->getsubtotal(); echo $_items->gettaxamount(); echo $_items->getpercent(); echo $_items->getdiscountamount(); echo $_items->getrowtotal(); } apart subtotal getting tried too: echo $_items->getbasesubtotal(); but still getting null value. appreciable base_subtotal field of order table. it not field sales order item table..so did not data $_items->getbasesubtotal() in order sales item base total try below code: $items->getbaserowtotal(); source link

javascript - React-Router: Why won't <Link> component's onClick handler dispatch my action? -

i react-router's <link> to fire function on click looks <link> navigating next page before function has chance fire. my component looks similar this: <link to={`/path/to/${foo}`} onclick={() => myfunc(foo, bar)}> <div>this link</div> </link> foo , bar props have been passed down parent components. however, if call e.preventdefault , subsequent functions work fine: <link to={`/path/to/${foo}`} onclick={(e) => e.preventdefault(); console.log('this works!')}> <div>this link</div> </link> i imagine similar this, programmatically navigate route there has better (i.e. less hack-y) way of achieving effect. does have suggestions, might me? this directly not solution, can try instead of using link component, use simple a element, , move needed route inside onclick handler: import { browserhistory } 'react-router'; <a onclick={ browserhistory.push(`/path/to/$

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

i searched on internet provided answers did not in building project. the error starting fork. tried following methods: mvn clean install -u when searched, people said because of java 7 , should work java 6. using java 6 only. some said set surefire plugin this: <groupid>org.apache.maven.plugins</groupid> <artifactid>maven-surefire-plugin</artifactid> <version>2.5</version> <configuration> <skiptests>false</skiptests> <testfailureignore>true</testfailureignore> <forkmode>once</forkmode> </configuration> the actual error is: [error] failed execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project junitcategorizer.instrument: error occurred in starting fork, check output in log -> [help 1] org.apache.maven.lifecycle.lifecycleexecutionexception: failed execute goal org.apache.maven.plugins:maven-surefire-plugin:2

Twig translate dynamic value/string from database -

Image
explanation: pull these values local database , try display them on front-end. issue is, have 2 languages need cater to. example: {% if activelocale == "si" %} {{ record.estate_type_si|raw }} {% elseif activelocale == "en" %} {{ record.estate_type_en|raw }} {% endif %} this works, when have multiple items gets gruesome because have write down 2 times. depending on language value different column in database pulled. i wondering if can similar this: {{ record.estate_type_{{"si"|trans}}|raw }} i gladly buy beer if can me out this. cheers! edit: variables using attribute , can access property of object in dynamic way. have use upper filter match need. {{ attribute(record, 'estate_type_'~ activelocale|upper)|raw }}

How to inspect implementation with Scala macros -

i'd need find out if method used in method implementation. example, have glorious app: object test extends app { def getgreetings = array.fill(2)("hello") println(getgreetings.mkstring("\n")) } i'd test if method getgreetings uses function fill of array's companion object. test succeed above implementation , fail example with: def getgreetings = array("hello", "hello") // nah, fill isn't used with of this video learned can inspect implementation macros this: def printtree(title: string)(expr: any): unit = macro printtreemacro def printtreemacro(c: context)(title: c.tree)(expr: c.tree) = { import c.universe._ val code : string = showcode(expr) val raw : string = showraw(expr) q""" println( $title.touppercase + "\n\n" + $code + "\n\n" + $raw + "\n\n" ) """ } printtree(&

c# - GMap.Net: Process takes a long time to close after window closes -

i testing out gmap.net using wpf. far have added gmapcontrol, setting necessary stuff (cachelocation, mapprovider, zoom etc). control working well, except when close window, takes while before vs recognizes debugging session has closed. apparently, application's process still running time before terminates - it's not bug in vs. delay appears when zoom/pan before close window. want guess still running, i'm not sure how tackle problem. has encountered , have solution? what happening program still caching tiles. all have call gmap.manager.canceltilecaching(); when exit program or close form. gmap named instance of gmap.net

javascript - AngularJS controller does console.log() before service -

Image
i developing app in m.e.a.n stack. i'm using angular controller (from directive), , service. controller calls service, service sends request nodejs , gets result. log result in service , data. the problem controller logs service before controller gets results. in services.js: var self = this; self.show = function() { $http.get('/contactlist').success(function(response) { console.log(response); return response; }); in directives.js: this.contacts = contactssrv.show(); console.log(this.contacts); and that's see in console: (the directive logs before gets results contactssrv.show() ) how can make contactssrv.show() asynchronous? thanks! using .then promise return service.js var self = this; self.show = function() { return $http.get('/contactlist'); }; directive.js contactssrv.show() .then(function (response) { console.log(response); this.contacts = response; });

jquery - Browser spellcheck on static text in contenteditable SPAN -

i have text elements on page , want draw user's attention spelling mistakes; i've been doing forcing spellcheck displays wiggly-red-underline. this seems have stopped working (in chrome) recently, there way achieve please? i've been doing this: <span contenteditable="true" spellcheck="true" class="spellcheck">some text</span> and then $(document).ready(function() { $(".spellcheck").each(function(){this.focus()}); $("#someidneartopofpage").focus(); }); which used work ok (it seems me there used visual effect of page scrolling, each span "visited", don't seem see happening - or, maybe, number of suitable spans on page small, compared previously, , happening faster can see - mentioning in case relevant) if manually click on span , append e.g. space wiggly-red-line appears.

java - android sending email from app no longer working -

i used this tutorial send emails inside app. used same code 3 different apps , worked well. now, few months later, stopped working. have searched possible sites, none of them helped me. tried setting lower security gmail account , changing properties session, nothing worked. appreciate help. log.d("emailsender","sending message"); properties props = new properties(); props.put("mail.smtp.host", host); props.put("mail.smtp.socketfactory.port", "465"); props.put("mail.smtp.socketfactory.class", "javax.net.ssl.sslsocketfactory"); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); session session = session.getdefaultinstance(props, new javax.mail.authenticator() { protected passwordauthentication getpasswordauthentication(

javascript - Sequelize. How to use different value of parameters in creation -

i'm trying write create user function. have such code createuser: function (user) { return db.user.create({ id: user.id, username: user.username, password: sha1(user.password), first_name: user.first_name, last_name: user.last_name, email: user.email, allow_password: user.allow_password }); } but it's correct when fill user's fields. actually, need username , email, when put 2 parameters - i've gotten 500 server error. how can other rows implicit? the answer: have convert password before query createuser: function (user) { if(user.password) { user.password = sha1(user.password); } return db.user.create({ id: user.id, username: user.username, password: user.password, first_name: user.first_name, last_name: user.last_name, email: user.email,

Cumulocity measurement representation -

i create measurements @ reception of event, can them using api, not represented graphically in device management interface. there specific format have respect representable automatically? if so, there place can find formats supported cumulocity? infered c8y_temperaturemeasurement examples in doc didn't find exhaustive list of native formats. here examples of measurements have @ moment: { "time": "2016-06-29t12:10:02.000+02:00", "id": "27006", "self": "https://<tenant-id>/measurement/measurements/27006", "source": { "id": "26932", "self": "https://<tenant-id>/inventory/managedobjects/26932" }, "type": "c8y_batterymeasurement", "c8y_batterymeasurement": { "unit": "v", "value": 80 } }, { "time": "2016-06-29t10:15:22.000+02:00", "id":

oauth 2.0 - instagram api keep raise 'You must provide a client_id' exception when I use python-instagram library -

i registered app in instagram developer dashboard , tried use python-instagram library made facebook. after ran sample_app.py code, accessed test website(localhost:8515) , logged in using instagram id. however, can't access code because of exception "you must provide client_id" i tried same thing using library( https://github.com/seraphicer/python-instagram-ext ) because pull requested original library , maintaining it. i've resorted doing myself; couldn't python-instagram work. ditch entire library. way many bugs lately, , it's not being maintained, think. @classmethod def exchange_code_for_access_token(cls, code, redirect_uri, **kwargs): url = u'https://api.instagram.com/oauth/access_token' data = { u'client_id': cls.get_client_id(), u'client_secret': cls.get_client_secret(), u'code': code, u'grant_type': u'authorization_code', u'redirect_ur

android - Unresolved reference: DaggerTestComponent (Kotlin with Dagger for Test) -

when use dagger , kotlin, we'll need following in our build.gradle dependency kapt 'com.google.dagger:dagger-compiler:2.0' compile 'com.google.dagger:dagger:2.0' provided 'org.glassfish:javax.annotation:10.0-b28' as stated in http://www.beyondtechnicallycorrect.com/2015/12/30/android-kotlin-dagger/ when try perform testing using dagger, , generate daggertestcomponent.builder() per https://labs.ribot.co.uk/fast-and-reliable-ui-tests-on-android-17c261b8220c#.o3efc5knx or https://medium.com/@fabiocollini/android-testing-using-dagger-2-mockito-and-a-custom-junit-rule-c8487ed01b56#.hxtytfns3 , in kotlin language, have below error error:(14, 25) unresolved reference: daggertestcomponent i found https://stackoverflow.com/a/36231516/3286489 explain how daggertestcomponent generated, , try put below in dependency. androidtestapt 'com.google.dagger:dagger-compiler:2.0.1' apparently, think java , not kotlin, issue persist. there kotlin vers

java - Hibernate Lazy Loading Issue -

i mapped entity in hibernate 5 class { private string code; private b child; @lazytoone(lazytooneoption.proxy) @manytoone(fetch=fetchtype.lazy) @notfound(action=notfoundaction.ignore) @joincolumns({...}) public b getchild() { ... } } and query load only a is: from a.code :q with configuration hibernate makes select on , on b entities. don't want load b a what missing?

javascript - Highlight correct and wrong answer when radio button selected in quiz -

i working on multiple choice quiz script uses radio buttons. wanted add feature when radio button selected checks if correct answer chosen chose radio button highlighted green. if wrong answer chosen chosen radio button highlighted red , correct answer highlighted green. submit button enabled. when click on submit button goes next question , process repeated till quiz over. problem the highlighting works after submit button clicked. , quiz stops working second question. how fix this? have included jsfiddle , code below. can 1 this. var pos = 0, test, test_status, question, choice, choices, cha, chb, chc, correct = 0; var questions = [ ["what 10 + 4?", "12", "14", "16", "b"], ["what 20 - 9?", "7", "13", "11", "c"], ["what 7 x 3?", "21", "24", "25", "a"], ["what 8 / 2?", "10", "2", "

R: how to optimize multiple pattern count over multiple strings? -

i have (1) set of sentences, (2) set of keywords, , (3) scores (real numbers) each keyword. need assign scores sentences, score of sentence = sum_over_keywords(keyword count within sentence * keyword score). reproducible example: library(stringi) # generate 200 synthetic sentences containing 15 5-character words each set.seed(7122016) sentences_splitted = lapply(1:200, function(x) stri_rand_strings(15, 5)) # randomly select words sentences our keywords set.seed(7122016) keywords = unlist(lapply(sentences_splitted, function(x) if(sample(c(true,false),size=1,prob=c(0.2,0.8))) x[1])) len_keywords = length(keywords) # assign scores keywords set.seed(7122016) my_scores = round(runif(len_keywords),4) now, scoring sentences: res = system.time(replicate(100, unlist(lapply(sentences_splitted, function (x) sum(unlist(lapply(1:len_keywords, function(y) length(grep(paste0("\\<",keywords[y],"\\>"),x))*my_scores[y] ))))))) i

how to crawler to save mp3 urls in asp.net mvc web application -

i want create application can crawl different websites , collect mp3 urls on basis of given query. user can search song title if results available in database show related song url otherwise crawl websites , find related result save in database , shows resutls user. i give htmlagilitypack go (you can install using package manager). a simple example of how start: string url = "http://www.google.com"; htmlweb web = new htmlweb(); htmldocument doc = web.load(url); when have loaded document, can inspect it: foreach (htmlnode node in doc.documentnode.selectnodes("//a[@href]")) { if (node.attributes.contains("href")) { console.writeline(node.attributes["href"].value); } } the above should print urls can find anchors.

bash - How to change the date format by storing the input in a variable in unix? -

this question has answer here: how convert date format 2 datetime in bash? 2 answers my input ./file \[10\/04\/16 01:02:03 bst\] \[06\/08\/16 05:02:08 bst\] i want convert \[10\/04\/16 01:02:03 bst\] apr 10 16 01:02:03 i using following code, echo '\[10\/04\/16 01:02:03 bst\]' | awk -f'[][/: \\\\]+' 'begin{split("jan feb mar apr may jun jul aug sep oct nov dec",m,/ /)} {print m[$3+0],$2,$4,$5":"$6":"$7}' is possible extract result storing \[10\/04\/16 01:02:03 bst\] in variable $starttime , use in code? using 1 date. possible use 2 dates? you can use date conversion script called script.sh : #!/bin/bash mydt() { ifs='/' read -ra arr <<< "${1//[\[\]\\]}" tz=':europe/london' date -d "${arr[1]}/${arr[0]}/${arr[2]}" '+%b %d %y %t' } v

How to get sysdate value from oracle DB in django -

how sysdate value oracle db using django? tried adding dual class in model below: class dual(models.model): dummy = models.charfield(max_length=1, null=true, blank=true) sysdate = models.datefield(blank=true, null=true) class meta: managed = false db_table = 'dual' tried accessing sysdate: sysdate = dual.objects.only('sysdate') but result in below error: databaseerror: ora-00904: "dual"."sysdate": invalid identifier am doing wrong? please me here. in advance you can retrieve rows select statement cursor iterator. know sysdate query return 1 row, can use fetchone() method. views.py from django.db import connection def get_sysdate(request): cursor = connection.cursor() sql = cursor.execute("select to_char(sysdate,'dd.mm.yyyy hh24:mi:ss') dual") result = cursor.fetchone() return render(request, 'sysdate.html', { 'result' : result, }) sysdate.html

python - string.decode() function in python2 -

so converting code python2 python3. don't understand python2 encode/decode functionality enough determine should doing in python3 in python2, can following things: >>> c = '\xe5\xb8\x90\xe6\x88\xb7' >>> print c 帐户 >>> c.decode('utf8') u'\u5e10\u6237' what did there? doesn't 'u' prefix mean unicode? shouldn't utf8 '\xe5\xb8\x90\xe6\x88\xb7' since input in first place? your variable c not declared unicode (with prefix 'u'). if decode using 'latin1' encoding same result: >>> c.decode('latin1') u'\xe5\xb8\x90\xe6\x88\xb7' note result of decode unicode string: >>> type(c) <type 'str'> >>> type(c.decode('latin1')) <type 'unicode'> if declare c unicode , keep same input, not print same characters: >>> c=u'\xe5\xb8\x90\xe6\x88\xb7' >>> print c å¸æ· if use input '

ant - Copy multiple files using maven-resources-plugin -

i'm trying delete/re-create directory copy arbitrary file directory copy multiple files directory each base directory of module in setup. that said, there have 15 copy-paste operations in total. module called release each other module. i've heard maven-resources-plugin there such purposes , tried utilize follows: <plugins> <!-- use plugin remove install folder, re-created later--> <plugin> <artifactid>maven-clean-plugin</artifactid> <version>3.0.0</version> <configuration> <filesets> <fileset> <directory>${basedir}/module.release/install</directory> <followsymlinks>false</followsymlinks> </fileset> </filesets> </configuration> </plugin> <!-- plugin here used copy necessary files directories --> <plugin> <artifactid>maven-resources-plugin&l