Posts

Showing posts from April, 2015

Swift generic class initializer -

i found problem designing result class in swift struct result<t>{ private let data: t? let error: nserror? var issuccess: bool { { return data != nil } } init(data: t) { self.data = data self.error = nil } init(error: nserror) { self.data = nil self.error = error } } usage should this result(data: "something") // t string the problem occurs when want pass error result(error: errorfromsomewhere) //t not specified below real application usage: class parseregistrationprovider: registrationprovider { func register(model: registrationform) -> promise<result<string>> { return promise { accept, reject in let user = pfuser() user.username = model.nickname user.password = model.password user.email = model.emailadreess user.signupinbackgroundwithblock({ (issuccess, error) -> void i...

javascript - fill fields of iframe from another domain with js -

what i'm trying following: i have iframe on website domain don't way styled. since not possible alter content of iframe since it's domain wondering if following approach work. i'm not going show iframe. fields in iframe filled fields on page. way can style form own way. really hopes tell me if possible or not the fields in iframe filled fields on page that isn't possible. same origin policy prevents accessing dom of other page write own content fields.

git - How do you remove a branch and all of its history locally and remotely? -

i have git branch need nuke traces of . think need like git filter-branch --index-filter 'git -d <branch>' --tag-name-filter cat -- --all or maybe git filter-branch --index-filter 'git rm --cached *' --tag-name-filter cat -- <branch> then would git push -f origin :<branch> i'm hesitant try them without knowing sure they'll or if they'll work. let's want nuke evilbranch . you want delete of branch's history. technically includes initial commit, more commits want. first, identify commit consider first commit of branch. let's it's 666bad . need find references it. run git branch -a --contains 666bad git tag --contains 666bad now delete them all. can either use git commands, or go .git/refs . do on every computer might have file. make sure not in detached head. now can kill commits, , therefore code, no longer referenceable (from this github link): git for-each-ref --format='delete %(...

angularjs - Security between UI (Angularja) and Java WS -

how can secure communication between business logic (java) running on tomcat, , ui written in angularjs. communication on rest services. can advise on this, or provide links tutorials, examples? there shouldn't concern securing rest api in server side. because it's kind web resources static css or servlet. if you're using spring in application, recommend consider spring security. here example. and should not worry accessing secured resources ajax request. probably, reuse same session information (that stored in sessionid cookie). you can find more information securing rest resources here .

c - How to delete first n characters from a binary file -

i have binary file want delete first n characters before further processing. have file pointer input. i tried use ftruncate had create file pointer don't want. tried below code not help. #include <stdio.h> #include <unistd.h> int main(void) { file*f,ftemp; f=fopen("./temp","a"); scanf("%d",&n); fseek(f,n,seek_set); ftruncate(fileno(f),/*end of file*/ ); ftemp=f; return 0; } please suggest other way. actually first n bytes binary , rest of part asn. thanks here program lop off first n bytes of ./temp , leaving original file ./temp-old . assumes file fit in memory. specify n on command line. /* * program provided "as is" without warranty of kind, * either expressed or implied. */ #include <errno.h> #include <fcntl.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include ...

change visbilite text in devexpress asp.net -

i need set visibilité false in textbox , nned let him invisible , propriété of code : @html.devexpress().textbox( f => { f.name = "codeclient"; f.text = ""; f.width = 300; f.enabled = false; f.height = 30; f.properties.nulltext = " choisir client"; }).gethtml() can me how change visiblité of textbox visible invisible @html.devexpress().textbox( f => { f.name = "codeclient"; f.text = ""; f.width = 300; f.enabled = false; f.clientvisible = false; f.height = 30; f.properties.nulltext = " choisir client"; }).gethtml() add f.clientvisible = false;

c# - WCF allow services to be discovered -

i'm sure duplicate can't find relating this. i have 4 wcf services within same project, in order new projects link services, need manually enter 4 end points in "add service reference": https://myurl.com/services/test1.svc https://myurl.com/services/test2.svc https://myurl.com/services/test3.svc https://myurl.com/services/test4.svc what i'd use single url (maybe https://myurl.com/services/ ), when entered address of "add service reference" dialog, discover 4 services , list them when click "discover" button when adding service references project in same solution. the thing i've found wcf discovery that's when you're broadcasting on subnet , that's not i'm trying do. edit: isn't duplicate of proposed question. op having issues getting services discovered correctly within same solution i'm having no trouble with. i'd same list of services outside solution when you're in project that's ...

rails - can onclick work with a method as well as javascript? -

if use following line set onchange action pointing javascript function, seems work. <% @documents.each |document| %> <td>< %= check_box_tag "document_ids[]", document.id, checked_flag, :onchange => "myfunction(#{document.id})" %></td> however, if try point def/method, not work expected. appears method called each line displayed. thought onchange/onclick called action if there change or click. <td><%= check_box_tag "document_ids[]", document.id, checked_flag, {:onchange => handle_checkboxes(document.id,checked_flag)} %></td> does ruby/rails allow call method onchange/onclick checkbox_tag ? my goal build array can use in find show documents checked. def handle_checkboxes(id,flag) $doc_ids.push(id.to_s) $test2[id] = 'push' $test3 = 'we arrived' end if use checkbox_tag method variables $doc_ids.inspect["9999999", "21", "22", ...

Using berkshelf with ChefDK and the Chef Supermarket -

i'm brand new chef , linux forgive me if questions blatantly obvious or if i'm doing horribly wrong. far have managed set basic standalone chef server on ubuntu 14.04 instance running in network. setup ubuntu desktop on vm have running on computer. i've been going through tutorials , far process use cookbooks chef supermarket chef server download them chef workstation on ubuntu desktop , upload corresponding demands. however, question have more robust cookbooks such node.js or mongodb when download them workstation , try upload them chef servers fails. says can't upload because missing dependencies has. know exact use case berkshelf used for. however, have no idea how use in relation cookbooks supermarket. tried cd directory downloaded cookbooks , run berks install gives me errors. doing wrong or there whole other process should into? sorry possible bad grammar , if question painfully simple. try following 1 of bunch of available tutorials on how use berks...

salesforce - accessing large number of records in SOQL -

in salesforce, having custom object , there can million of records in object in future. developing dashboard using apex , visualforce need access records @ 1 time in single query. query is: [select count(custom_cases__c), status__c custom_case__c group status__c] so accessing records @ 1 time , exceeding governer limits. what can achieve this? please provide me solution , if possible example because new salesforce. it shame salesforce counts aggregate function not 1 result, amount of rows aggregated. means if have on 50000 results, you'll error (sobject query row exceeded, in line) there idea that, please upvote! the workable solution see @ moment (and solution use myself) program , schedule apex batch job run, , save results in new custom object. use custom object source dashboard.

c++11 - C++ object instantiations -

this question has answer here: default constructor empty brackets 8 answers this question object instantiations in c++. there several ways instantiate objects both on heap , on stack curious know subtle differences. using namespace std; class raisin { private: int x; public: raisin():x(3){} raisin(int input):x(input){} void printvalue() { cout<< "hey deliciousness is: " << x <<endl; } }; basically raisin simple class using demonstration: int main() { raisin * a= new raisin; a->printvalue(); raisin * b= new raisin{}; b->printvalue(); raisin * c= new raisin(); c->printvalue(); raisin x; x.printvalue(); raisin y{}; y.printvalue(); raisin z(); z.printvalue(); //error: request member 'printvalue' in 'z', //which of non-class type 'raisin()' raisin alpha(12); alpha...

ruby on rails - Pre filled, partially not editable input field with simple form? -

is possible create input field, partially filled, filled part not editable, , also, not being submitted? may seem confusing, simple example. have field, looks url. want user specify, let's say, name, field should this: www.something.com/users/ input user should not able edit bold part, "input" part. also, want submit input, not whole url. need <%= f.input :name, :not_editable_decoration: "www.something.com/users/" %> you can try this: <div class="form-group"> <div class="input-group"> <span class="input-group-addon">www.something.com/users/</span> <%= f.input :url, input_html: { class: 'form-control' } %> </div> </div> the above example use bootstrap css. you can put static url instance variable in controller. @static_url = "www.something.com/users/" <span class="input-group-addon"><%= @static_u...

What is this CONTEXT in Go lang when talking about HTTP Requests? -

to might stupid question. on other hand is important me. new go programming , when read sharing values between middlewares , go concurrency patterns: context not figure out meant context when referring sharing values between middleware handlers or request handlers in general. i've been able write web framework go -- frodo . not perfect in lot of ways, learning experiment. see not stupid. under informed being new go lang. thank in advance comprehensive explanation. i found great explanation @ beginning of blog: http request contexts & go request contexts, new terminology, typically way pass data alongside http request processed handlers (or middleware) have written. data user id, csrf token, web token, whether user logged in or not—something typically derived logic don't want repeat over-and-over again in every handler. if you've ever used django, request context synonymous request.meta dictionary.

sql server - FOR XML ... TYPE much slower than FOR XML? -

running sql server 2014 . have stored procedure returns quite large xml . goes this: select( ... xml path (n''), root, type now, query runs in 1 second. if remove type runs in around half time: select( ... xml path (n''), root obviously, latter returns nvarchar(max) instead of xml . want xml data, if ask xml gets slower! if want fetch xml data on client, necessary convert xml using type directive above? q: anyway, why for xml ... type significantly slower for xml ... ? there way improve conversion? did try set variables results xml , varchar(max) without displaying them? maybe time difference measure bound preparing viewer? pasting first letters grid column faster creating formed, indented, displayable xml... sepcifying "type" not needed in cases. need nested xml only. play around aliases, path- , root-literals , - of course - or without type: and - important! - try call surrounding select , without: select ( ...

doctrine2 - Symfony Doctrine ManyToMany add custom join field -

i have 2 entites : cart , item , relation configured manytomany because cart can have multiple items, , items can in multiple carts. so have link table item_cart item_id , cart_id . how can work quantity ? example if need add 800 items id = 2 cart id = 5 ? is possible add field quantity in link table ? thanks help. you can making relationship entity. entity called cartitem or cartitemlink . the association changes manytomany between cart , item 2 associations manytoone , onetomany : cart - manytoone - cartitem - onetomany - item now can add additional fields cartitem , $quantity field mentioned in question. so this: the cartitem : class cartitem { /** many-to-one bidirectional, owning side * @var cart * @orm\manytoone(targetentity="application\entity\cart", inversedby="cartitems") * @orm\joincolumn(name="cart_id", referencedcolumnname="id") */ private $cart; /** ma...

iphone - How to get the JSON formated WebService format from using URL of an web page -

i have url of login page goes login screen in web. now need json format of web page using url have. and can parse , display in table.. so 1st i need json format of web page using url have. how create webservice in json response page i want "username" key , "password" keys in correct format/case sencitive create web service login page return json response, , parse response using sbjson library. in either nsdictionary or in nsarray. , use array populate tableview. this link contain data, creating web service login parse json have used in project , great. happy coding.

javascript - Using a Combobox to fill in a Text Field in Scribus -

i'm building pdf in scribus , stumbling through javascript (basic newbie here) go. i've ran issue , can't seem find answer. i have combobox called producttype user selects product. once want text field called mortclause display proper clause. i've placed following code under combobox's action -> on blur -> javascript. here have not working: var ckselect = this.getfield("producttype"); var ckresult = this.getfield("mortclause"); if (ckselect.value === "va") { mortclause.value = 'va clause'; } else if (ckselect.value === "fha") { mortclause.value = 'fha clause'; } else { mortclause.value = 'normal clause'; }

asp.net mvc - RazorGenerator precompiled views and related scripts -

recently while i'm using great satisfaction razorgenerator precompiled views (internal or external library per needs) i'm involved in such of critical question about... , library/compiled views required javascripts? how can accomplished that? maybe using bundling reading embedded css or js or else external library? any suggestion appreciated! regards at 1 of old positions looked it. in our situation(which may or may not similar yours), bundled custom css , javascript , got little bit of performance boost, enough management worth it. used cdn getting content shared (jquery, bootstrap, etc...). when left know discussing hybrid, cdn bundling approach. it depend on application circumstances though, think performance gain achieved few hundred milliseconds.

servlets - request.getParameter and request.getQueryString yield incompatible results? -

this question has answer here: request.getquerystring() seems need encoding 6 answers in jetty server log, observe following: 07 jan 2016 10:03:52,605 debug ws.ducchandlerproxy - n/a handle (get /ducc-servlet/file-contents?fname=/home/degenaro/ducc/logs/1/x+y+z.log&page=1) 07 jan 2016 10:03:52,605 debug ws.ducchandler - n/a handleduccservletfilecontents qs:fname=/home/degenaro/ducc/logs/1/x+y+z.log&page=1 07 jan 2016 10:03:52,605 debug ws.ducchandler - n/a handleduccservletfilecontents fn:/home/degenaro/ducc/logs/1/x y z.log the code corresponding last 2 entries comprise results of request.getquerystring() , request.getparameter("fname") respectively. how come latter loses '+' character? when call request.getquerystring() query string in url bar. when call request.getparameter("fname") value of parameter enc...

OnClick on subItem of listview item in android -

i have listview. items has subitems. how can onclick event on subitems. problem onclick on subitem, have first onclick on item, sub item. how can onclick on subitem directly listview.setonitemclicklistener(new adapterview.onitemclicklistener() { @override public void onitemclick(adapterview<?> adapterview, view view, final int i, long l) { final int = + 1; final framelayout framelayout = (framelayout) view.findviewbyid(r.id.luxonetopimageid); final framelayout framelayout1 = (framelayout) view.findviewbyid(luxtwotopimageid); framelayout.setonclicklistener(new view.onclicklistener() { @override public void onclick(view view) { int m = (a * 2) - 1; if (arrays[m] == 0) { if (arraysamount(...

c# - Creating a method for search product by name in "ProductModel" class and display it in panel with image buttons and labels -

productmodel.cs: (class) this productmodel class searches product name. check if correct or not. public static product searchproductsbyname(string name, list<product> products) { product pd; pd = new product(); foreach (product rs in products) { if (name == rs.name) { return pd; } } return null; // <<< return value if nothing found } search.aspx: <asp:textbox id="txtsearch" runat="server"></asp:textbox> <asp:button id="btnsearch" runat="server" text="button" onclick="btnsearch_click" /> <br /> <asp:panel id="pnlproducts" runat="server"> <br /> </asp:panel> search.aspx.cs (i want display searched product using searched product ty name method) protected void page_load(object sender, eventargs e) { } protected void btnsearch_click(object sender, eventargs ...

java - JRadioButton in Graphic2D -

i want draw radiobuttons panel in graphic2d don't know how can this. @override public void draw(graphics2d g2) { // ... here draw recntangle2d objects.... } and here simple jbuttonpanel radio buttons: public buttongroup buttons() { jradiobutton button1 = new jradiobutton("red"); jradiobutton button2 = new jradiobutton("green"); jradiobutton button3 = new jradiobutton("blue"); buttongroup colorbuttongroup = new buttongroup(); colorbuttongroup.add(button1); colorbuttongroup.add(button2); colorbuttongroup.add(button3); button1.setselected(true); return colorbuttongroup; } but don't know how can draw in upper method on top below buttonpanel draw recntagles text field. you don't draw radio buttons. add radio buttons (like other swing component) panel , panel paint buttons you. read section swing tutorial on how use radio buttons mo...

python identificare random syntax in text -

i have input text file bio.txt enter chance {win|earn|gain|obtain|succeed|acquire|get} 1⃣click {link|url|link up|site|web link} below️ 2⃣enter name 3⃣do submit(inside optin {put|have|positioned|set|placed|apply|insert|locate|situate|put|save|stick|know|keep} {shipping|delivery|shipment} adress) need locate syntax {win|earn|gain|obtain|succeed|acquire|get} , return random word, example : win how can locate in python started code : input = open('bio.txt', 'r').read() first, need read text file string; find pattern "{([a-z|]+)}" using regex, split them "|" make list random words. achieved following: import re, random seed = [] matches = re.findall('{([a-z|]+)}', open('bio.txt', 'r').read()) [seed.extend(i.split('|')) in matches] input = random.choice(seed)

knockout.js - Initializing a Bootstrap accordion menu in Knockout -

here example of accordion menu should should use data in format compatible json. have data structure, binding between data , html doesn't work. corrections should make display multilevel structure in 2-level menu? var confitems = { "children":ko.observablearray() }; var childrenlength = 3; console.log("a",confitems); (var = 0; < childrenlength; i++) { confitems.children.push({ "idhash": ko.observable("#col-" + (i + 1)), "id": ko.observable("col-"+ (i + 1)), "displaylabel": ko.observable("item " + (i + 1)), "children": ko.observablearray() }); console.log("b",confitems); (var j = 0; j < childrenlength; j++) { confitems.children()[i].children().push({ "idhash": ko.observable("#col-" + (i + 1) + "-" + (j + 1)), "id": ko.observable("col-" + (i + 1) + "-" +...

json - If it possible connect Loadbalancers DNSname to Route53 using AWS Cloudformation template? -

what trying connect loadbalancer dns name to route53. lets on example. here loadbabancer template in resource: "restelb" : { "type" : "aws::elasticloadbalancing::loadbalancer", "dependson": "attachgateway", "properties": { "loadbalancername": {"fn::join": ["",["rest-elb-", {"ref": "vpc"}]]}, "crosszone" : "true", "subnets": [{ "ref": "publicsubnet1" },{ "ref": "publicsubnet2" }], "listeners" : [ {"loadbalancerport" : "80", "instanceport" : "80","protocol" : "http"}, {"loadbalancerport" : "6060", "instanceport" : "6060","protocol" : "http"} ], }...

angularjs - Javascript Method always returns false -

this question has answer here: how return response asynchronous call? 21 answers i'm attempting check user before saving them in firebase users table, when go check using .once() firebase method, function returns false... when console.log inside function, logs correctly, never returns true. auth represents basic firebase auth factory var newuser = function(id) { ref.child('users').child(id).once('value', function(snapshot) { console.log(snapshot.val() === null); return (snapshot.val() === null); }); }; auth.$onauth(function(authdata) { console.log(boolean(newuser(authdata.uid))); if (authdata && !!(newuser(authdata.uid))) { // add user if first time login $scope.authdata = authdata; ref.child('users').child(authdata.uid).$save({ provider: authdata.uid, name: getname(authdata), blah: ...

facebook - How to hide a tab from a fanpage during development -

i'm wondering how hide facebook tab published fanpage while tab under development, appears page admins? in order edit tabs seems have added page, in order able edit them. that's problem when customizing facebook tab, don't want fans see work-in-progress content until it's ready published. here i'm not referring custom built app, apps static html. any 1 has experience this? enable sandbox mode in app settings. goto dev https://developers.facebook.com/apps click on app in left hand column. under setting see if sandbox mode on or off. if want change setting click "edit settings" the sandbox setting under basic settings. for , client test app have give them permissions adding them tester/developer/admin of app. https://developers.facebook.com/docs/applicationsecurity/

python - Deciphering hex-codes as (probably) a timestamp -

i'm parsing logs unclean , exist on 1 line per log-file. i've managed strip them apart regular expressions, leaving me weird hex-like number , it's log-string. think sequence in hex-like number timestamp, can't figure out how decipher it. i wondering if might see pattern. 513328f8003d 51332900003d 5133290c003d 5133293c003d 51332945003d 5133294e003d 51332955003d this seconds later 5134519a102b 5134519c0039 513451b0132b 513451b3102b 513451b31329 513451b3182b 513451b31a2f in few occasions, numbers same. on around 28000 rows happens few times. i'm guessing logs time per second, , in few cases generate encoded timestamp on exact same time, this: 51345d391929 51345d391929 51345d3a042b the update time of log-file (except double-time stated above) around 08:45 morning. maybe it's weird way of notating microtime? can't figure out :p it seems leftmost 4 bytes timestamp: in [29]: datetime.datetime.fromtimestamp(0x5134519a) out[29]: date...

angularjs - Frontend - How to avoid show data from my server -

Image
i'm creating application using angularjs , i'm developing simple login there 1 thing i've notice. when user enter wrong password backend returns error code read , process , tells user "wrong password", so, checking response chrome tools , backend showing data server like: in content says: "websphere application server version v8.5 liberty...". maybe hacker can check information , search wich vulnerabilites 8.5 version of websphere. my question is: how can avoid this? or thing backend shoud fix? if concern dc.title need start server command line rather using eclipse tools. when launched eclipse different html output has dc.title. if launch command line should this: <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-us" lang="en-us"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> however isn't idea rely on server default error p...

ios - PopOverController appears next to the selected cell -

i working on tableviewcontroller in xamarin.ios platform. the following code works when user clicks on second row in first section in tableview. when user clicks, popover view appears. position of popover not appear next selected cell. how handle it? public override void rowselected (uitableview tableview, nsindexpath indexpath) { if (indexpath.row == 1 && indexpath.section == 0) { var vc = new iviewcontroller (this,ivc.iinfo); var nc = new navigationcontroller (vc); nc.preferredcontentsize = new system.drawing.sizef (200, 300); uipopovercontroller popupovercontroller = new uipopovercontroller (nc); popupovercontroller.presentfromrect (tableview.bounds, tableview, uipopoverarrowdirection.any, true); } instead of using tableview , should use selected cell follows. uitableviewcell cell = tableview.cellat(indexpath); popupovercontroller.presentfromrect (cell.bounds, cell, uipopoverarrowdirection.any, true);

java - cannot insert more than 16 columns using SQLServerBulkCopy -

i using bulk copy code msdn website, nothing changed actually. have table correct columns in db (sqlserver 2008 r2 management studio 10). when tried run code, on addcolumnmetadata line throw exception: com.microsoft.sqlserver.jdbc.sqlserverexception: column 17 invalid. please check column mappings. @ com.microsoft.sqlserver.jdbc.sqlserverbulkcopy.validatecolumnmappings(sqlserverbulkcopy.java:1747) @ com.microsoft.sqlserver.jdbc.sqlserverbulkcopy.writetoserver(sqlserverbulkcopy.java:1514) @ com.microsoft.sqlserver.jdbc.sqlserverbulkcopy.writetoserver(sqlserverbulkcopy.java:628) i cannot find bug. can please me? below part of code copied msdn. loop , file path things changed. public static void main(string[] args) { string connectionstring = getconnectionstring(); sqlserverbulkcsvfilerecord filerecord = null; try { // data source file loading class implements isqlserverbulkrecord. // here using sqlserverbulkcsv...

C# Call Different Functions in Core Function -

in c#, how can simplify getdata1() , getdata2() 1 line function only? please see comments in getdata1 , getdata2 , have 2 write 3 lines in each function, use getdatacore simplify it. public ienumerable<int> getdatacore(function passinfunction) { // many other steps foreach (var sensor in sensors) { yield return sensor.passinfunction(); } } public ienumerable<int> getdata1() { // many other steps // todo: use // return getdatacore(getdata1); foreach (var sensor in sensors) { yield return sensor.getdata1(); } } public ienumerable<int> getdata2() { // many other steps // todo: use // return getdatacore(getdata1); foreach (var sensor in sensors) { yield return sensor.getdata2(); } } there's no need write own method project of items in sequence using...

javascript - Google Analytics API - Authorization on Analytics Properties -

i'm using google analytics api. need know if exists function returns me boolean value (or that) telling me if logged google account has rights show charts, didn't find similar in api. so tried different, tried handle error when draw charts function execute(), using callback explained here: https://developers.google.com/analytics/devguides/reporting/core/v3/coredevguide#build-a-core-reporting-api-query code doesn't call callback. here code: var datachart = new gapi.analytics.googlecharts.datachart({ query: { ids: ga_property_id, metrics: 'ga:sessions, ga:users', dimensions: 'ga:date', }, chart: { container: 'chart-container', type: 'line', options: { width: '100%', fontsize: 14 } } }); function makeapicall() { datachart.set({query: daterange}); datachart.execute(handlecorereportingresults); } function handlecorereportingresults(results) { ...

java - Spring Security and Custom External Authentication -

i have such task - integrate web application external single sign-on service. it's custom non-standard implementation of sso based on setting specific cookie , redirecting application. sso , app on same domain. currently i'm using spring security filter check cookie on specific url. works fine scenario : web app -> sso[ supplied callback url] -> redirect app. but fails when user visits app provides auth service , "jumps" url of app (and cookie not checked because "special" url not triggered). what recommended approach solve such problem spring security? thanks! the simplest way solve problem implement own preauthenticatedprocessingfilter: http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#d0e6167 the question if authentication provider provides user name in cookie. if provides – can use filter: http://static.springsource.org/spring-security/site/docs/3.1.x/reference/springsecurit...

angularjs - How to calculate width of text using javascript? -

how width of text. var e=document.createelement('span'); e.style.fontsize = scope.fontsize; e.innerhtml = "test"; console.log(e.offsetwidth); width comes 0 it seems have append created element document . var e=document.createelement('span'); document.body.appendchild(e); e.style.fontsize = 14; e.innerhtml = "test"; console.log(e.offsetwidth); e.remove(); output: 23 hiding element not work ether. e.style.display= "none"; output: 0 to "hide it" add css that. added remove() not show anyway. adding position:absolute; idea, since prevent flickering of rest of html content. position:absolute; margin-left:-1000em;

ios - How to use scrollRectToVisible:animated? -

i have tableview , in 1 of rows have horizontal scrollview , images(images in different view of row), in horizontal scrollview have added few buttons (10 buttons). when user clicks on button scrollview call reloaddata . because call reloaddata horizontal scrollview reloads again new image data. want if user scrolls end , clicked last button scrollview, user should able see selected button not first one. don't know how can use scrollrecttovisible:animated make happen. here code scrollview , adding buttons on it. -(void)addcolorfiltersonview:(uiview *)colorview{ if (_colorfilterview) { [_colorfilterview removefromsuperview]; } self.colorfilterview = [[uiscrollview alloc] initwithframe:colorview.bounds]; [_colorfilterview setautoresizingmask:uiviewautoresizingflexiblewidth|uiviewautoresizingflexibleheight]; [_colorfilterview setbackgroundcolor:samergb(238)]; [_colorfilterview setshowshorizontalscrollindicator:no]; int addedcount ...

OpenCL: How to check for build errors using the C++ wrapper -

if build opencl program source code this cl::program program = cl::program(context, sourcecode); program.build(devices); i check if successful. saw few examples of how in c, since project ist in c++ wondering how (in case goes wrong) readable text message indicates might issue using c++ wrapper. i have enabled exceptions #define cl_hpp_enable_exceptions but not know if build(...) throws exception. i using amd app sdk 3.0 , cl2.hpp khronos webpage (as not included in sdk). the cl::program::build() function indeed throw exception if build fails. here's how can build log: cl::program program = cl::program(context, sourcecode); try { program.build(devices); } catch (cl::error& e) { if (e.err() == cl_build_program_failure) { (cl::device dev : devices) { // check build status cl_build_status status = program.getbuildinfo<cl_program_build_status>(dev); if (status != cl_build_error) continue; // build l...

"Cannot update File menu Recent Files list [Errno 13] Permission denied: recent-files.lst" when I open IDLE (Python 3.4 GUI) -

i have no idea why happens , doesn't come typing cursor when click can't edit anything. i'm running windows 10, , python 3.4.4. know why happening? cannon update file menu recent files list. operating system says: [errno 13] permission denied: 'c:\users\aaron\.idlerc\recent-files.lst' solved, .idlerc folder hidden, after making visible worked fine. if recent-files.lst file hidden, python fail access properly. tried hide .idlerc folder , applied same settings subfolders. can still keep folder hidden, because it's ugly, make sure not set recent-files.lst file hidden, too.

javascript - Is it possible to make curved shape in 3d perspective div? -

Image
there video of concept desktop. https://www.youtube.com/watch?v=4ftpchd3378 well, may there way make curved shape div... or @ least fake it. want bend div looks bit curved in 3d. don't need features in video. if there way in javascript/jquery tell me plz. another possibility use perspective css property, created web photo gallery wall using method, similar results looking for. i used website me build gallery: https://css-tricks.com/almanac/properties/p/perspective/

android - Can the usage of "R.id" before View's name be avoided? -

i'm working on tictactoe app uses 9 imageviews. imageviews clickable , on click, either cross or circle image shown, followed game's logic. since resource file name needs updated every imageview, need write this: @override public void onclick(view v) { switch (v.getid()) { case r.id.oneimage: // code break; case r.id.twoimage: // code break; case r.id.threeimage: // code break; //and on 6 more cases default: break; } } while task need pretty same views, i looking way generic, if possible like: v.getid().setimageresource(r.drawable.cross); or int ivid= v.getid(); string name= "r.id." + ivid; integer.valueof(name).setimageresource(r.drawable.cross); both techniques can't resolve setimageresource() method , it's understandable why. i figured none of these methods work , can't seem think of right query search on google or here, why ended asking own question. appreciated. thanks! edit i'd able u...

c++ - Oracle exception ::getMessage() causing debug assertion -

i'm using visual studio 2015 enterprise oracle 12.1.0. here's code causing assertion: try { // .. }catch(oracle::occi::sqlexception &e) { std::cout << "error code: " << e.geterrorcode() << std::endl; std::cout << "error message: " << e.getmessage() << std::endl; // here } i'm assuming has std::string being allocated dll , deallocated application i'm not sure. got no idea on how fix it. edit 1: "catch value" "catch reference" edit 2: visual studio 2013(v120) platform toolset don't assertion. visual studio 2015(v140) platform toolset though code, library , project settings same.

dictionary - Drupal 7: Display (zoom on) 1 address on multiple marker map -

i managed create map showing multiple addresses (markers) on 1 map. in view: format :geofield map fields: content: title content:location (geofield field) i trying attach view list of addresses way when click on address- automatically zoom on correct marker on big map. final result how can make it?? trying several days already, please, help!

javascript - Inserting an image between text in django when both text and image are in the model -

Image
i'm looking way of inserting image in between text of blog made django. want achieve in following image: as see text divided in 2 columns. there titles, links image , caption. right model like: class post(models.model): body_col1 = models.textfield() body_col2 = models.textfield() body_col1_html = models.textfield(editable=false, blank=true, null=true) body_col2_html = models.textfield(editable=false, blank=true, null=true) image = image = models.imagefield() the text transformed markdown can add css format in admin panel. did render variables in html template using tags: <div class="column-left"> {{ object.body_col1_html|safe}} </div> <div class="column-right"> {{ object.image}} {{ object.body_col1_html|safe}} </div> doing have 2 columns , image on top of second column. i'm looking way remove 2 fields text , have 1 text field, can add image inside text. have javascript function auto...

Mysql stored procedure parallel processing -

can call stored procedures in parallel way increase execution speed. eg: have 3 stored procedures extract data 3 master tables , load/insert single source table.currently having 3 procedures : call sp_1(); call sp_2(); call sp_3(); and running in sequential way insert records takes more time. there way run these procedures in parallel way improve execution time , speed process..kindly me possible work around this. q: can call stored procedures in parallel way increase execution speed. a: short answer no. there's no built-in mechanism (in mysql) make stored procedure run "in parallel". achieve parallel processing, application need designed that, making use of multiple connections mysql, splitting processing chunks can run in parallel, , coordinating processes. as far "increase execution speed", you'd need first identify causing slowness. if issue storage i/o, parallel-izing process not going increase execution speed. if procedure ...

python - How to scrap data using google api -

import requests def search(query, pages=4, rsz=8): url = 'https://ajax.googleapis.com/ajax/services/search/web' params = { 'v': 1.0, # version 'q': query, # query string 'rsz': rsz, # result set size - max 8 } s in range(0, pages*rsz+1, rsz): params['start'] = s r = requests.get(url, params=params) result in r.json()['responsedata']['results']: yield result at first 2,3 attempts retrieving required pages, after 2,3 attempts not getting result. returning "none" or []. google blocking ip after few attempts? solution? i not sure work or not, way avoid getting blocked sites not encourage scraping use proxy while retrieving web pages. please check how proxy can used in code.

ios - iphone: [NSNull getCharacters:]: unrecognized selector error using NSPredicate -

hi when try search entity in core data on fields, following error: [nsnull getcharacters:]: unrecognized selector sent instance this code using set predicate: - (void)filtercontentforsearchtext:(nsstring*)searchtext scope:(nsstring*)scope { nspredicate *resultpredicate =[nspredicate predicatewithformat:@"jobtitle=%@",@"barber"]; searchresults = [getcontacts filteredarrayusingpredicate:resultpredicate]; } however, when set predicate know true on other fields, search works correctly: - (void)filtercontentforsearchtext:(nsstring*)searchtext scope:(nsstring*)scope { nspredicate *resultpredicate =[nspredicate predicatewithformat:@"title=%@",@"dr"]; searchresults = [getcontacts filteredarrayusingpredicate:resultpredicate]; } first version searches on title field/attribute, second on jobtitle field/attribute. examining attributes job , jobtitle in model, cannot discern difference between them. can tell me nsnull comin...

android - How to remove padding in sherlock tab view -

is possible decrease/remove padding left , right in tab? , how can accomplish this? i've tried lot can't figure out how this. use sherlock actionbar tab navigation. i finnaly found this can done setting padding , minwidth on tabview , backgroundstacked of widget.sherlock.light.actionbar.solid.inverse. <style name="gpa_sherlock_theme" parent="@style/theme.sherlock.light.darkactionbar"> <item name="android:actionbarstyle">@style/actionbar.solid.example</item> <item name="android:actionbartabstyle">@style/actionbartabstyle.example</item> <item name="actionbarstyle">@style/actionbar.solid.example</item> <item name="actionbartabstyle">@style/actionbartabstyle.example</item> </style> <style name="actionbartabstyle.example" parent="@style/widget.sherlock.actionbar.tabview"> <item name...

python - Save Uploaded Image as PNG -

in django app, users can upload images. want save every uploaded image png. i've been trying pil it's not working. still seems saving original image type (whatever user uploaded as). doing wrong? if form.cleaned_data['dataset_image']: # dataset.dataset_image = form.cleaned_data['dataset_image'] name = 'dataset%s.png' % (dataset.id) size = (200, 200) try: im = image.open(form.cleaned_data['dataset_image']) im.save(name, 'png') print "saved file: ", im except ioerror: # dont' save image pass when upload jpg (that want convert png), print statement gives this: saved file: <pil.jpegimageplugin.jpegimagefile image mode=rgb size=628x419 @ 0x107354f80> the print statement refers image object when opened file. used jpegimageplugin class because jpeg image. however, when call method save() , save image based on extension of requested filename, in ca...

java - Why does ActivityCompat.requestPermissions() only accept an integer request code between 0-255? -

i updated app targetsdkversion of 23, , implemented request various permissions. initial attempt using activitycompat.requestpermissions() caused illegalargumentexception thrown internals of fragmentactivity: int request_code_a = 9001; activitycompat.requestpermissions(new string[ {manifest.permission.write_contacts}, request_code_a); // crashes java.lang.illegalargumentexception: can use lower 8 bits requestcode however, if request code between 0-255, fine , permission request works expected. int request_code_b = 101; activitycompat.requestpermissions(new string[ {manifest.permission.write_contacts}, request_code_b); // works correctly so question is, reasons there restricting possible values of integer in api this? same information supplied using byte, conscious decision has (apparently) been made use integer instead. case of allowing future extensibility? quoting the source code fragmentactivity exception appears thrown: // use 8 bits of request co...

c# - Connecting IIS to SQL Server 2014 on Windows Server 2012 -

i keep getting error 'cannot open database "mydb" requested login. login failed. login failed user "nt authority\network service"' this connection string sqlconnection _connection = new sqlconnection("data source='myserver\\se';initial catalog=mydb;integrated security=true;multipleactiveresultsets=true; trusted_connection=yes"); the same web form can connect locally sql server on windows 8.1. why this? in connection string, integrated security=true causing attempt login sql server using account iis runs with. based on have described, 8.1 box has iis running account has permission access sql server. you can add network service account sql server valid login, change account iis launches on server account has access sql server, or specify sql login in connection string instead of using integrated security.

Does Pregel allow the structure of a graph to be modified? -

if does, how can archive performance when graph needs modifying? mean modifying add or remove vertices or edges. yes, pregel allows structure modified. called mutations. presented in section 3.4 topology mutations of paper. according paper, available @ ( http://kowshik.github.io/jpregel/pregel_paper.pdf ): "multiple vertices may issue conflicting requests in same superstep (e.g., 2 requests add vertex v , different initial values). use 2 mechanisms achieve determinism: partial ordering , handlers. as messages, mutations become effective in superstep after requests issued. within superstep removals performed first, edge removal before vertex removal, since removing vertex implicitly removes of out-edges. additions follow removals, vertex addition before edge addition, , mutations precede calls compute(). partial ordering yields deterministic results con icts. the remaining conflicts resolved user-defined handlers. if there multip...

c# - How do I require an enum as a strong typed parameter? -

i may going entirely wrong open , suggestions. trying require statustype parameter in this: response(statustype.submit, message); to limited set of types return constant string value. far have come solution: public class response { private statustype _status; response(statustype status, string message) { _status = status; } public string status { { return enum.getname(typeof(statustype), _status); } } } public enum statustype { fail, success, response, confirm } but realize enum parameter weak-typed , allow me enter string value instead. can me? have feeling enum not solution i'm not sure of way. based on comments, getting error when using class vb project. when option strict turned off, vb try "helpfully" convert objects between "compatible" types. hides mistakes , causes hard track down errors. recommend turning 'option strict` on when deve...

android - Create an application that loads a website? -

i have existing mvc web application , want create native application android, ios, , pc that, when launched, navigates website not show typical browser features such url bar, navigation buttons, bookmarks, etc. are there tools allow me 1 or more of targeted platforms? you can use uiwebview native android , ios. to target cross platform, apache cordova ( use phonegap ) worth looking in to, experience (already not ideal webview) worst if manually create native apps each platform.

java - Configuring Spring Security to Authenticate against LDAP without anonymous and without bind DN -

using jndi can authenticate against our ldap server, has anonymous binds disabled, using user's username , password, this: hashtable<string, object> env = new hashtable<string, object>(); env.put(context.initial_context_factory, "com.sun.jndi.ldap.ldapctxfactory"); env.put(context.provider_url, url); env.put(context.security_authentication, "simple"); env.put(context.security_principal, username); env.put(context.security_credentials, password); dircontext ctx = new initialdircontext(env); attribute groups = ctx.getattributes(username).get("groupmembership"); now same thing using spring boot, spring security, , spring ldap. i can configure authentication using bind dn , password, this: defaultspringsecuritycontextsource context = new defaultspringsecuritycontextsource(ldapconfig.url); context.setuserdn(ldapconfig.binddn); string bindpassword = passwordresolver.getpassword(ldapconfig.p...

r - Speed up for loop on a large dataset -

i running analysis of citibike data , have created code works - extracts of trips of bikes started different station bike last stopped (that is, instances start.station.id different previous end.station.id , means bike moved truck. monthly datasets, however, large, summer months containing on 1 million individual trips (you can find them here: citibike data . here snapshot of dataset: head(nov2015, n = 20) tripduration starttime stoptime start.station.id start.station.name 1 1110 11/1/2015 00:00:00 11/1/2015 00:18:31 537 lexington ave & e 24 st 2 1094 11/1/2015 00:00:01 11/1/2015 00:18:15 537 lexington ave & e 24 st 3 520 11/1/2015 00:00:05 11/1/2015 00:08:45 536 1 ave & e 30 st 4 753 11/1/2015 00:00:15 11/1/2015 00:12:48 229 great jones st 5 353 11/1/2015 00:00:22 11/1/20...