Posts

Showing posts from June, 2011

Python webapp2 serve static content -

our team migrated project gae aws. 1 component web application built on top of webapp2, framework easy integrate gae. kept webapp2 framework in aws too, minor changes make work. the web application works fine in cloud, i'm trying find way run on local development machines too. when using gae environment easy task because google provides app engine launcher, tool simulates cloud environment well. in aws continued making hacks in order start web application using app engine launcher, want discard it. so, modified python script , starts don't know how serve static content. static files (css, js) added html templates link rel="stylesheet" type="text/css" href="{{statics_bucket}}/statics/css/shared.css"/ , {{statics_bucket}} environment variable points specific amazon s3 bucket per environment. of course, doesn't work on localhost because nobody serving static content on http://localhost:8080/statics/css/shared.css example. google app engin

node.js - Twilio Functions - posting to third party api? -

so, not familiar little confused. i'm trying use twilio functions create function posts incoming sms message third-party api. in general, how go that? this have right now exports.handler = function(context, event, callback) { var got = require('got'); var data = event.body; console.log("posting helpscout: "+requestpayload); got.post('https://api.helpscout.net/v1/conversations.json', { body: json.stringify(data), 'auth': { 'user': process.env.api_key, 'pass': 'x' }, headers: { 'content-type': 'application/json' }, json: true }) .then(function(response) { console.log(response.body) callback(null, response.body); }) .catch(function(error) { callback(error) }) } here started, code twilio function. create new conversation @ scout. note: event.body , event.from , etc. event parameter

gorm - Why is sessionFactory not injected for unit test using Grails 3.2? -

i'm running issue unit test extends hibernatespec failing due sessionfactory not being injected service under test. whenever method on sessionfactory called during test, nullpointerexception (e.g. java.lang.nullpointerexception: cannot invoke method getclassmetadata() on null object ) , test subsequently fails. i'm using grails 3.2.4 , hibernate 5. this working when test used @testmixin(hibernatetestmixin) , looks updates, mixin deprecated , suggests using hibernatespec instead. here's snippet test: class testdatabaseservicespec extends hibernatespec { def setup() { } def cleanup() { } void "test method"() { when: service.method() then: true } } and here snippet service under test: void method() { ... table_names.add(sessionfactory.getclassmetadata('mydomain').tablename) ... } i have tried set service.sessionfactory in setup method setupspec method sessionfactory avail

obfuscation - Is there a code obfuscator for PHP? -

has used obfuscator php? i've tried don't work big projects. can't handle variables included in 1 file , used in another, instance. or have other tricks stopping spread of code? you can try php protect free php obfuscator obfuscate php code. nice, easy use , free. as others have written here not using obfuscation because can broken etc: have 1 thing answer them - don't lock house door because can pick lock. case, obfuscation not meant prevent 100% code theft. needs make time-consuming task cheaper pay original coder. hope helps. wiki

html - jQuery onclick multiple elements with the same class -

i have been doing fair bit of searching one, , think on cusp of answer, stuck! basically, looking click 1 element in turn click 2 other elements of same class. when this, 1 element clicked, whereas other isn't: jquery('.et-pb-arrow-prev').on('click', function(){ jquery('a.et-pb-arrow-prev').click(); console.log('done'); }); i able switch elements around element not being clicked, clicked instead of other, can't both other elements click. instead, getting error: uncaught rangeerror: maximum call stack size exceeded i think i'm there, lost now. appreciated. when trigger click, current element's click handler gets called again reason of call stack error. jquery('.et-pb-arrow-prev').on('click', function(e, manual) { if (typeof manual === 'undefined' || manual === false) { jquery('a.et-pb-arrow-prev').not(this).trigger('click', true); console.log('trigg

python 2.7 - elasticsearch exception SerializationError -

from python script sending data elasticsearch server this me connect es es = elasticsearch('localhost:9200',use_ssl=false,verify_certs=true) and using bellow code able send data local es server es.index(index='alertnagios', doc_type='nagios', body=jsonvalue) but when trying send data cloud es server,the script executing fine , indexing few documents after indexing few documents getting following error traceback (most recent call last): file "scriptfile.py", line 78, in <module> es.index(index='test', doc_type='test123', body=jsonvalue) file "/usr/local/lib/python2.7/dist-packages/elasticsearch/client/utils.py", line 73, in _wrapped return func(*args, params=params, **kwargs) file "/usr/local/lib/python2.7/dist-packages/elasticsearch/client/__init__.py", line 298, in index _make_path(index, doc_type, id), params=params, body=body) file "/usr/local/lib/python2.7/dist-pac

javascript - set index to table row -

i have table has 30 rows. wrote below code set number index each row.from 1-to 30 code works good. when variable called : cyrrentpage has 2 content . row number added 1 before index . instead of start 31. should ? here snippet: var cyrrentpage =2 if(cyrrentpage == 1) { $(".row_number").each(function(index, element) { $(this).text( $(this).closest("tr").index()+1) }); } else { $(".row_number").each(function(index, element) { if(index == 50) { $(this).text("cyrrentpage 0"); } else{ $(this).text( (cyrrentpage-1).tostring()+($(this).closest("tr").index()+1).tostring()) } }); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table border="1"> <tr><td class="row_number">1</td><td> hello</td></tr> <tr><td class="r

python - Naive base classifier of nltk giving unhashable type error -

following code wrote using nltk , python. import nltk import random nltk.corpus import movie_reviews #from sklearn.naive_bayes import gaussiannb documents = [(list(movie_reviews.words(fileid)), category) category in movie_reviews.categories() fileid in movie_reviews.fileids(category)] random.shuffle(documents) #print(documents[1:3]) all_words= [] w in movie_reviews.words(): all_words.append(w.lower()) all_words = nltk.freqdist(all_words) #print(all_words.most_common(15)) #print(all_words["great"]) word_features = list(all_words.keys())[:3000] def find_features(document): words = set(document) features = {} w in word_features: features[w] = {w in words} return features #print((find_features(movie_reviews.words('neg/cv000_29416.txt')))) featuresets = [(find_features(rev), category) (rev, category) in documents] training_set = featuresets[:1900] testing_set = featuresets[1900:] classifier = nltk.naivebayesclassifi

c# - Validation errors texts don't appear -

i have class 2 properties [stringlength(8, errormessage = "user name can't longer 8 chars!")] [required(errormessage = "must filled!")] public string nickname { get; set; } [required(errormessage = "must filled!")] [datatype(datatype.password)] public string password { get; set; } and have partial view, user inserts details , presses sumbit button. nickname: @html.textboxfor(x => x.nickname) @html.validationmessagefor(x => x.nickname) </div> <div> password: @html.textboxfor(x => x.password) @html.validationmessagefor(x => x.password) </div> <button type="submit">log in</button> this post action, [httppost] public actionresult login(shortuser u) { if (modelstate.isvalid == true) { if (u.passmatchuser()) { formsauthentication.setauthcookie(u.nickname, true); } else { modelstate.addmodelerror(

How to export obj/fbx/json file for three.js with the second uv(lightmap)? -

the second layer uv used map lightmap onto models in scene. when work second uv done in 3d max, can export these information obj/fbx/json file can loaded directly three.js? here example provided threejs.org https://threejs.org/examples/?q=lightmap#webgl_materials_lightmap when looking file "obj/lightmap/lightmap.js", can see somes properties such "maplight". so question how json file created? there exporters can export maplight property? have tried export second uv 3d max using obj , fbx format, doesn't work. wiki

sapui5 batch with sap.ui.model.odata.v2.ODataModel -

i created table data using jsonmodel var omodel = new sap.ui.model.json.jsonmodel(query); otableprio = sap.ui.getcore().getcontrol("idtableprio2"); otableprio.setmodel(omodel, "prio2"); everythink , work good. now have added new column(prio) change value. after changing save every rows( in sap ztable ) after clicking buton save . made this var omodel = new sap.ui.model.odata.v2.odatamodel(gserviceurl); omodel.setusebatch(true); (var = 0; < data.length; i++) { sentry.matnr = data[i].matnr; sentry.bbynr = data[i].bbynr; sentry.prio = data[i].prio; omodel.update("/wielosztset('"+data[i].bbynr+"')", sentry, { method: "put", function(){ alert('data updated successfully'); location.reload(true); },function(){ sap.m.messagetoast.show('update failed'

java - Why thymeleaf template does not processing? -

i have simple template print list of item client side spring-boot. when try run error: error 5434 --- [nio-8080-exec-4] org.thymeleaf.templateengine : [thymeleaf][http-nio-8080-exec-4] exception processing template "get_all_items": error resolving template "get_all_items", template might not exist or might not accessible of configured template resolvers 2017-08-22 19:37:31.302 error 5434 --- [nio-8080-exec-4] o.a.c.c.c.[.[.[/].[dispatcherservlet] : servlet.service() servlet [dispatcherservlet] in context path [] threw exception [request processing failed; nested exception org.thymeleaf.exceptions.templateinputexception: error resolving template "get_all_items", template might not exist or might not accessible of configured template resolvers] root cause org.thymeleaf.exceptions.templateinputexception: error resolving template "get_all_items", template might not exist or might not accessible of configu

Lambdas, alphas in Scalaz -

in many traits' signatures 1 can spot awkwardly looking syntax: private trait compositionplus[f[_], g[_]] extends plus[λ[α => f[g[α]]]] could explain me λ[α => f[g[α]]] part? both λ , α seems undefined. edit: see syntax wonder how interpreted compiler. this syntax comes kind-projector . compiler plugin rewrites λ[α => f[g[α]]] to ({ type l[α] = f[g[α]] })#l wiki

datetime - SQLite3 split date while creating index -

Image
i'm using sqlite3 database, , have table looks this: the database quite big , running queries slow. i'm trying speed process indexing of columns. 1 of columns want index quote_datetime column. problem: want index date (yyyy-mm-dd) only, not date , time (yyyy-mm-dd hh:mm:ss), data have in quote_datetime . question: how can use create index create index uses dates in format yyyy-mm-dd? should split quote_datetime 2 columns: quote_date , quote_time ? if so, how can that? there easier solution? thanks helping! :d attempt 1: tried running create index id on data (date(quote_datetime)) got error error: non-deterministic functions prohibited in index expressions . attempt 2: ran alter table data add column quote_date text create new column hold date only. , insert data(quote_date) select date(quote_datetime) data . date(quote_datetime) should convert date + time date, , insert into should add new values quote_date . however, doesn't work , don't k

android - How to slide in a Hidden View from top -

i implement view slides top when button/image/label on actionbar clicked. work default drawerlayout , except sliding left/right sides, slides top-down in case. how can go this? android have default class or action handles this? what i've managed mentioning solution, androidswipelayout . however, not looking for. thank in advance. if have button call following function click on button this. clickme.setonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { yourlinerlayout.setvisibility(view.visible); setlayoutanim_slidedown(view); } }); and here's setlayoutanim_slidedown function slide down layout want slide top down. public void setlayoutanim_slidedown(viewgroup panel) { animationset set = new animationset(true); animation animation = new translateanimation( animation.relative_to_self, 0.0f, animation.relative_to_self, 0.0f, animation.relative_to_self, -1.0f

ios - selected and focused states of UITabBarItem on tvOS -

how can give tabbar items different titles colors selected , focused states? i setting title text attributes not make difference between selected , focused states, have same color. here how create tabbar items: title in titlesarray { let item = uitabbaritem(title: title, image: nil, selectedimage: nil) item.settitletextattributes([nsforegroundcolorattributename: uicolor(white: 1, alpha: 1)], for: .selected) item.settitletextattributes([nsforegroundcolorattributename: uicolor(white: 1, alpha: 0.2)], for: .normal) item.settitletextattributes([nsforegroundcolorattributename: uicolor.blue], for: .focused) tabbaritems.append(item) } tabbar.items = tabbaritems can 1 me understand how achieve this. thanks. try if can in anyway : for normal: uitabbaritem.appearance().settitletextattributes([nsforegroundcolorattributename: uicolor.graycolor()], forstate:.normal) and selected : uitabbaritem.appearance().settit

python - Update wxPython grid in real time -

i extracting data huge log , updating entry in wxpython grid. code have can see window after operation complete, takes 5 mins complete operation. there way update , see data on grid time = 0 itself. tried: import wx import wx.grid gridlib class myform(wx.frame): def __init__(self): ## # constructor create basic frame wx.frame.__init__(self, none, wx.id_any, "tool") # add panel looks correct on platforms panel = wx.panel(self, wx.id_any) self.grid = gridlib.grid(panel) rows = 4 column = 600000 self.grid.creategrid(column, rows) self.count = 0 # change couple column labels self.grid.setcollabelvalue(0, "timestamp") self.grid.setcollabelvalue(1, "cmd") self.grid.setcollabelvalue(2, "address") self.grid.setcollabelvalue(3, "data") # few more operations calculate cmd,timestamp field in range(1

java - Android Fragment instantiation: newInstance() -

i read many articles , stackoverflow answers still cannot understand why need factory method create instance of fragment. the following fragment classes both work fine. fragment 2 constructors: public class ctorfragment extends fragment { private static final string key = "the_key"; public ctorfragment() { // android calls default constructor default constructor must explicitly defined. // have constructor, android won't create default constructor us. } public ctorfragment(string s) { // set arguments. bundle bundle = new bundle(); bundle.putstring(key, s); setarguments(bundle); } @nullable @override public view oncreateview(layoutinflater inflater, @nullable viewgroup container, bundle savedinstancestate) { view fragment = inflater.inflate(r.layout.fragment_my, container, false); textview textview = (textview) fragment.findviewbyid(r.id.textview); // use

osx - swift unhide buttons in one column if mouse is over row -

i working swift 4 osx. have view based nstableview 4 columns. cells in each column has got same custom cell class: class customcell: nstablecellview { @iboutlet weak var btninfo: nsbutton! private var trackingarea: nstrackingarea! override func awakefromnib() { super.awakefromnib() self.trackingarea = nstrackingarea( rect: bounds, options: [.activealways, .mouseenteredandexited], owner: self, userinfo: nil ) addtrackingarea(trackingarea) } override func mouseentered(with event: nsevent) { super.mouseentered(with: event) btninfo.ishidden = false } override func mouseexited(with event: nsevent) { super.mouseexited(with: event) btninfo.ishidden = true } } now realize following situation: if user goes mouse on row, btninfo should visible , hide again, mouse leaves row. problem (with code above), apps crashes, because

sql server - Commonize mssql connection -

i'm using mssql on node.js. i want commonize mssql connection. i summarize connections generated each time multiple modules 1 file could tell me way? example [table1.js] var mssql = require('mssql'); var config = { user: 'user', password: 'pass', server: 'server', database: 'db', stream: true, options: { encrypt: true } } mssql.connect(config, function(err) { var request = new mssql.request(); request.query('select * table1',function(err,data) { callback(data); mssql.close(); }); }); [table2.js] var mssql = require('mssql'); var config = { user: 'user', password: 'pass', server: 'server', database: 'db', stream: true, options: { encrypt: true } } mssql.connect(config, function(err) { var request = new mssql.request(); request.query('select * table2',function(err,data) { callba

forms - External Search bar that cannot replicate "#?" -

i'm librarian working on search bar connects third-party repository. i through simple form action equaling target url. in case, repository applies pound sign, or #, in front of question mark in successful search result, have not seen before. here url of successful search results "test", pound sign following "landing": https://augsburg.on.worldcat.org/coursereserves/landing#?coursesearchfield=all&coursequery=test in fiddle , can see tried replicate url in action field. <form class="lindelladv-search-form" style="" method="get" action="https://augsburg.on.worldcat.org/coursereserves/landing#?" target="_blank" onsubmit="window.location = this.action + '?q=' + encodeuricomponent(this.q.value); return false;" accept-charset="iso-8859-1"> unfortunately, doesn't work. page loads, see #? appear @ end of url--right before question mark , pound sign disappear in

hibernate - Grails 3 Not Returning Correct Class -

i have grails/groovy code developed under grails 2 , refactored grails 3. running in intellij idea (and on our tomcat server), source object documentsource doesn't identified one. instead identified base source class. code returned expected results in grails 2, has me stumped in grails 3. inspecting source object in debugger, top level fields null type , profile , metaclass source. drilling down under target->handler, expected values found type, profile, documentid, documentname, , metaclass. i'm not sure if related gorm/hibernate. we've experimented using different version , i'm not sure impact there. ideas? // base domain class class source { string type profile profile } // extended domain class class documentsource extends source { string documentid string documentname } // further extended domain class class documentlocatorsource extends documentsource { string locatorid } // snippet service class ... sourcereferences.each { sour

php - Doctrine life cycle event and serializing JSON -

i have situation need serialize attribute of entity json database. i'm aware can create own data type purpose , works well, however, prefer understand "how" able make original method work correctly. the problem encountered: i have few entities in store "meta" data json in mysql database. marked entity's attribute type text , implemented prepersist , preupdate life cycle events: public function prepersist(preupdateeventargs $eventargs) { $this->meta = json_encode($this->meta); } public function postpersist(preupdateeventargs $eventargs) { $this->meta = json_decode($this->meta, true); } the life cycle events called in following scenarios (i happen using yaml entity mapping rather annotations): lifecyclecallbacks: prepersist: [ prepersist ] postpersist: [ postpersist ] preupdate: [ prepersist ] postupdate: [ postpersist ] postload: [ postpersist ] the $meta attribute array , when entity persisted serial

node.js - how come I have so many versions of nodejs? -

Image
how come have many versions of nodejs. i have multiple of command prompts applications, have 1. nodejs cmd 2. ubunto bash cmd 3. normal cmd , bunch of others dont use them.. my question is. 1.how update nodejs in system , automatically reflected on of cmd's? possible? 2. why happening? 3. cmd should use running node applications? below snapshots of cmds , result gave me when checked version of node. how update nodejs in system , automatically reflected on of cmd's? why happening? you can install node.js globally, have different versions because didn't install globally, cmds can't automatically reflected. can see blog how install node.js globally: how install node.js on ubuntu 16.04 what cmd should use running node applications? you can run node applications using cmd want, doesn't matter. wiki

Python reduce dictionary memory by bits as keys -

i have dna data 11 million entries. count occurrences of patterns on data "atcg". called kmer counting meaning counting k length substring occurrences. have no problem kmer algorithm. stored counted values in dictionary. keys "aattaccacttcatgtattaaaagatactaac". storing keys strings , dictionary memory increases , gives me memory error. try find way reduce dictionary memory. resources suggests keys can hold ints or bits instead of strings. way store keys efficient , how can that? related code : dd = {} open(filename,'r') f: line in f: line2 = line.rstrip('\n') n = len(line2) in range(n-k+1): pattern = line2[i:i+k] if pattern in dd: dd[pattern] = dd[pattern] + 1 else: dd[pattern] = 1 edited: dictionary printed dictionary; ('cccccccccccccccccccccccccccccc', 105) ('gaaaaggatcaagagcccatttatgccata', 4

android - error permision ACCESS_FIND_LOCATION -

i'm using permission access_fine_location when run.error:requires access_fine_location permission why? thanks in advance. <uses-permission android:name="android.permission.access_fine_location"/> access_fine_location , access_coarse_location both permission required when trying location add both permission in manifest file if targeting android 6.0 , above add runtime permsiion below code string permission = android.manifest.permission.access_fine_location; if (activitycompat.checkselfpermission(searchcityclass.this, permission) != packagemanager.permission_granted && activitycompat. checkselfpermission(searchcityclass.this, android.manifest.permission.access_coarse_location) != packagemanager.permission_granted) { activitycompat.requestpermissions(searchcityclass.this, new string[] {permission}, permission_gps_code);

php - How to apply bindValue method in LIMIT clause? -

here snapshot of code: $fetchpictures = $pdo->prepare("select * pictures album = :albumid order id asc limit :skip, :max"); $fetchpictures->bindvalue(':albumid', $_get['albumid'], pdo::param_int); if(isset($_get['skip'])) { $fetchpictures->bindvalue(':skip', trim($_get['skip']), pdo::param_int); } else { $fetchpictures->bindvalue(':skip', 0, pdo::param_int); } $fetchpictures->bindvalue(':max', $max, pdo::param_int); $fetchpictures->execute() or die(print_r($fetchpictures->errorinfo())); $pictures = $fetchpictures->fetchall(pdo::fetch_assoc); i you have error in sql syntax; check manual corresponds mysql server version right syntax use near ''15', 15' @ line 1 it seems pdo adding single quotes variables in limit part of sql code. looked found bug think related: http://bugs.php.net/bug.php?id=44639 is i'm looking at?

ionic2 - errorCode : MINIMUM_SERVER when access obtainAccessToken in IBM MFP8 -

i'm getting failure when trying call wlauthorizationmanager.obtainaccesstoken() using ionic 2 , mfp 8 this message ============== {"status":-1,"responsetext":"","errormsg":"this version of mobilefirst client sdk requires minimal server version greater ifix 8.0.0.0-if201701250919","errorcode":"minimum_server"} our installation team installed latest ifix pack also. i'm attaching code snippet also. app.component.ts wl.client.pintrustedcertificatepublickey('mycert.cer').then(() => { console.log('--------ssl pin success-------------'); wlauthorizationmanager.obtainaccesstoken().then((accesstoken) => { console.log('--------accesstoken success-------------', accesstoken); }, (response) => { console.log('--------accesstoken failure-------------', response); let usrname ="roney"; let passwrd = "roney@123"; let modalc = this.modal

Kubernetes Kops and Federation -

has had success getting kops , federation work together? we've tried set couple of clusters using kops , have created correct contexts. however, when try join 1 cluster another, dns names used kops incompatible kubefed requires. wiki

java - Why can't a generic interface be used as a type parameter? -

here java generic code programming language pragmatics, scott interface chooser<t> { public boolean better(t a, t b); } class arbiter<t> { t bestsofar; chooser<? super t> comp; public arbiter(chooser<? super t> c) { comp = c; } public void consider(t t) { if (bestsofar == null || comp.better(t, bestsofar)) bestsofar = t; } public t best() { return bestsofar; } } class casesensitive implements chooser<string> { public boolean better(string a, string b) { return a.compareto(b) < 1; } } ... arbiter<string> csnames = new arbiter<string>(new casesensitive()); csnames.consider(new string("apple")); csnames.consider(new string("aardvark")); system.out.println(csnames.best()); // prints "apple" java requires code each generic class manifestly (self-obviously) type safe, independent of particular instantiation. means type of field

c# - Unable to Render ContentControl inside Window -

i think missing simple here. this want: want create mainwindowviewmodel instance mwvm. want associate instance mainwindow. i want associate view instance viewmodel1 member of mwvm. thus, want pass hierarchy of instances viewmodel in view. far, unable see view. i trying render custom contentcontrol inside wpf window. when put mainwindow.xaml entry point of application, don't see anything. when put view1.xaml entry point (in app.xaml), can see text "hello". missing here? mainwindow.xaml <window x:class="mimicview.mainwindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:mimicview" mc:ignorable="d" d:datacontext="{d:designinsta

javascript - Detecting an undefined object property -

what's best way of checking if object property in javascript undefined? use: if (typeof === "undefined") { alert("something undefined"); } if object variable have properties can use same thing this: if (typeof my_obj.someproperties === "undefined"){ console.log('the property not available...'); // print console } wiki

java - I have an error with min and max nextInt -

this question has answer here: how generate random positive , negative numbers in java 8 answers i want make speed on vector x random min -5 , max 5. everytime run game crashing. problem in random because when set velx = 2 or 3 works perfectly, me please. (sorry english, hope understand me) velx = random.nextint(5 - -5) + -5; you want this: velx = random.nextint(10) - 5; (generate random int btw 0 , 10 , subtract 5 , giving range btw -5 (inclusive) , 5 (exclusive). if want 5 inclusive well, change nextint() parameter 11 . otoh shouldn't use real random, rather bell curve (values in middle appearing more outliers). 1 easy way achieve have list values (once outliers , more middle values) , pick randomly among them. might want play around values see works best you. // once, during initialization list<integer> values = new arraylist&l

I need to switch or convert the integer values from MySQL database to a string values in php, undescorejs -

this code; \socialkit\ui::view('timeline/user/info-bodybuild-row'); contains integer values database table 1, 2 , 3. passed frame $themedata['info_bodybuild_row'] display. code working viewing database, need change integer values string. datatype used in table enum type, , iam working on underscore.js framework. if (! empty($timeline['bodybuild'])) { $bbt = \socialkit\ui::view('timeline/user/info-bodybuild-row'); $themedata['info_bodybuild_row'] = $bbt; } values need change is, 1 = 6 pack 2 = fat 3 = thin i run doesnot work resulting in error $bbt = \socialkit\ui::view('timeline/user/info-bodybuild-row'); switch ($bbt) { case '1': $bb = "six pack"; break; case '2': $bb = "fat"; break; case '3': $bb = "thin": break; } $themedata['info_bodybuild_row'] = $bb;

php - How to group by in mysql without showing duplicates? -

i building search page babysitter listing , users can filter results based on wage, distance , rating. works fine, getting 3 or 4 results when there 2 people or 1 people , cannot figure out. here query: select `users`.`id` `user_id`, `user_wage_preferences`.`one_child` `wage`, `user_contact_informations`.`lat`, `user_contact_informations`.`lng`, `user_reviews`.`rating`, sum(user_reviews.recommended) recommended, ( 6371 * acos(cos(radians(59.448355500000005)) * cos(radians(lat)) * cos( radians(lng) - radians(24.7406023)) + sin(radians(59.448355500000005)) * sin( radians(lat))) ) distance `users` left join `user_reviews` on `users`.`id` = `user_reviews`.`nanny_id` inner join `user_wage_preferences` on `users`.`id` =

Remove <style> tags globally using Regex in JavaScript -

how can use regex in javascript remove <style> , <style type="text/css"> , </style> , <style type="text/css"/> . final result css without style tags. for reason code below doesn't work. str.replace(/<style\b[^<]*(?:(?!<\/style)<[^<]*)*<\/style>/gi,''); to capture inline style can use style="(.*)" demo online wiki

javascript - Activate an opened window tab when a link from another window is clicked -

i know if it's possible activate opened window tab when click on link different window. e.g. click on _blank link website a, opens new window website b. now, if want go website website b, have close website b or website manually. is possible create link in website b activate opened website a? it not possible due obvious security reasons :d if have refered tabs window in context, can try popping website new window , calling focus() on yourpopupname.focus(); can focus on popped window. reference : how change browser focus 1 tab another wiki

javascript - How to stop default link click behavior with jQuery -

i have link on webpage. when user clicks it, widget on page should update. however, doing something, because default functionality (navigating different page) occurs before event fires. this link looks like: <a href="store/cart/" class="update-cart">update cart</a> this jquery looks like: $('.update-cart').click(function(e) { e.stoppropagation(); updatecartwidget(); }); what problem? e.preventdefault(); from https://developer.mozilla.org/en-us/docs/web/api/event.preventdefault cancels event if cancelable, without stopping further propagation of event. wiki

list not shuffling python -

the code have here should shuffle list contains "ace of hearts" "two of hearts" , "three of hearts". it retrieves them file well, won't shuffle them , prints list twice. far know, list can include words - seems mistaken. import random def cards_random_shuffle(): open('cards.txt') f: cards = [words.strip().split(":") words in f] f.close() random.shuffle(cards) print(cards) return cards i assume problem loop on lines in file for words in f when want first line of file. assuming file looks this: ace of hearts:two of hearts:three of hearts then need use first line: import random def cards_random_shuffle(): open('cards.txt') f: firstline = next(f) cards = firstline.strip().split(':') # alternative read in whole file: # cards = f.read().strip().split(':') print(cards) # original order random.shuffle(cards) pri

string - Checking palindrome word in python -

i have code check whether word palindrome or not: str = input("enter string") l = len(str) p = l-1 index = 0 while index < p: if str[index] == str[p]: index = index + 1 p = p-1 print("string palindrome") break else: print("string not palindrome") if word inputted, example : rotor , want program check whether word palindrome , give output "the given word palindrome". but i'm facing problem that, program checks first r , r , prints "the given word palindrome" , checks o , o , prints "the given word palindrome". prints result many times checking word. i want result delivered once. how change code? i had make few changes in code replicate output said saw. ultimately, want message displayed @ end of comparisons. in case, had inside loop, each time loop ran , hit if condition, status message printed. instead, have changed prints when 2 pointers index , p

ocr - Microsoft Computer Vision APi misreads O as 0 -

Image
i trying read text image using https://azure.microsoft.com/en-us/services/cognitive-services/computer-vision/ . can see, here o misread 0 sample image: i have tried magickimage enhance quality of image still reads 0. resolve great. if not have use azure ocr api, switching google ocr solve issue. tested here: https://ocr.space/compare-ocr-software edit: added ocr result screenshot, language used = arabic with language works both, google ocr , free ocr.space api. ocr.space result arabic ocr wiki

multithreading - C++ freeRTOS Task, invalid use of non-static member function -

where problem? void myclass::task(void *pvparameter){ while(1){ this->update(); } } void myclass::starttask(){ xtaskcreate(this->task, "task", 2048, null, 5, null); } but, this: error: invalid use of non-static member function i cannot find useful doc check mistake, think should like: (c++11's std::thread) e.g.: xtaskcreate(&myclass::task, "task", 2048, (void*)this, 5, null); solution works me: void myclass::task(){ while(1){ this->update(); } } static void myclass::starttaskimpl(void* _this){ static_cast<myclass*>(_this)->task(); } void myclass::starttask(){ xtaskcreate(this->starttaskimpl, "task", 2048, this, 5, null); } i use pattern wrapper function instanciating pthread non-static member functions. function called in xtask static member function, calling task function using void* pointer. myclass.hpp : class myclass { public: my

python - How can dynamically create permission in django? -

now can create new groups using django group module. from django.contrib.auth.models import group can assign permissions group. example created new group "hr" by group(name="hr") . now want create permission can_create_hr can_edit_hr i should able assign permission groups. how can ? you can create , assign permission directly groups well. create permission add permission group from django.contrib.auth.models import user, group, permission django.contrib.contenttypes.models import contenttype content_type = contenttype.objects.get(app_label='app_name', model='model_name') permission = permission.objects.create(codename='can_create_hr', name='can create hr', content_type=content_type) # creating permissions group = group.objects.get(name='hr') group.permissions.add(permission) if want assign permission group permission

Download image not being displayed iOS Swift -

i'm trying download images , display them based on different conditions. code worked if download images in main thread, trying download them through end now. my console clean, i'm not getting errors - yet images not being displayed? first attempt @ doing end image downloading , doing swift come objective-c. could please @ code below , let me know problem is? //fizzbuzz image download weak var fizzbuzzimage: uiimage! let fizzbuzzstring = "https://emkaydeum.files.wordpress.com/2015/08/fizzbuzz.png" var fizzbuzzurl:nsurl! //fizz image download weak var fizzimage: uiimage! let fizzstring = "https://vignette2.wikia.nocookie.net/leagueoflegends/images/b/b0/fizz_render.png/revision/latest?cb=20151205185848" var fizzurl:nsurl! //buzz image download weak var buzzimage: uiimage! let buzzstring = "https://vignette2.wikia.nocookie.net/disney/images/b/bc/buzz_disney_infinity_render.png/revision/latest?cb=20140605182818" var buzzurl:nsurl! override

javascript - How to run jquery when DOM is loaded in chrome (works in Firefox ) -

i need change style divs calling class. the code has no issue firefox problem occurs on chrome , jquery loads default css(actual css used fields ) works respective divs after 2-3 seconds not expect. need load custom css when divs displayed . thanks efforts <script> /// start script , works fine has $( document ).ready(function() { $('#table_most_recent_c').attr('readonly', 'true'); $("#attempted_c").val()="key"; $(".sub-panel").css({"margin-right":"0%"}); $('.col-sm-6').css({"height":"0px","width":"25%"}); $('.detail-view-row-item').css({"height":"0px","margin":"0 0 17px 0","min-height":"0px"}); $('.col-xs-12').css({"height":"0px"}); $('.col-sm-8&

sql - How to configure the database and hibernate configurations in application properties file outside the spring boot application -

in application properties have: spring.datasource.url=jdbc:sqlserver://localhost:1433;databasename=recipe spring.datasource.username=sa spring.datasource.password=merck123! spring.datasource.driverclassname=com.microsoft.sqlserver.jdbc.sqlserverdriver spring.jpa.show-sql=true spring.jpa.hibernate.dialect=org.hibernate.dialect.sqlserver2012dialect spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.sqlserver2012dialect spring.jpa.hibernate.ddl-auto = update spring.jpa.hibernate.entitymanager.packagestoscan:com i want access hibernate , database outside application after creating jar. possible or spring boot take care of it? you can put application.properties file in same directory spring boot app jar file. or while running .jar app can specify location of config file in command line, like: --spring.config.location=/your/path for more solutions here's similar question: spring boot external application.properties wiki

java - Unable to open Browser in Selenium -

i running simple code in selenium , throws below exception:- @test public void test(){ system.setproperty("webdriver.chrome.driver", "geckodriver.exe"); webdriver driver=new firefoxdriver(); driver.get("https://google.com"); driver.manage().window().maximize(); } following error shown when have executed script: previously working, firefox version 55 , using latest gecko driver version. please help!! exception is:- java.lang.nosuchmethoderror: com.google.common.base.preconditions.checkstate(zljava/lang/string;ljava/lang/object;)v @ org.openqa.selenium.remote.service.driverservice.checkexecutable(driverservice.java:136) @ org.openqa.selenium.firefox.geckodriverservice.access$000(geckodriverservice.java:41) @ org.openqa.selenium.firefox.geckodriverservice$builder.usingfirefoxbinary(geckodriverservice.java:108) @ org.openqa.selenium.firefox.firefoxdriver.toexecutor(firefoxdriver.java:204) @ org.openqa.selen

mongodb - How to populate two collections data together like Joins in SQL -

i'm new mongodb. want result showing 2 collections data joins in sql. here, below scenario can pull table2 's data. can have both tables data displayed? var courseids = db.getcollection('table1').find( { studentid: '347765' } ).map(function(cid){ return cid.courseid; }); db.getcollection('table2').find({ cid : {$in: courseids}}, {name: 1, course: 1}); mongo not relational database , can try aggregate collections lookup. using example documentation, because unfortunately did not give structure of table1 , table2 , connecting field. a collection orders contains following documents: { "_id" : 1, item" : "abc", "price" : 12, "quantity" : 2 } { "_id" : 2, "item" : "jkl", "price" : 20, "quantity" : 1 } { "_id" : 3 } another collection inventory contains following documents: { "_id" : 1, "sku" : "abc&

How to change background color option menu xamarin android -

i try change background color option menu black white code not work.i see link how change background color popup menu android not work me. styles <style name="theme.designdemo" parent="base.theme.designdemo"> </style> <style name="base.theme.designdemo" parent="theme.appcompat.light.noactionbar"> <item name="colorprimary">@color/colorprimary</item> <item name="popupmenustyle">@style/popupmenu</item> <item name="colorprimarydark">@color/colorprimarydark</item> </style> <style name="popupmenu" parent="widget.appcompat.popupmenu"> <item name="android:popupbackground">@android:color/white</item> </style> </resources> popup_menu.xml: <?xml version="1.0" encoding="utf-8" ?> <menu xmlns:android="http://schemas.andr