Posts

Showing posts from April, 2015

echo a variable from a multidimentional array outside a function -

Image
the code below works string value not when try access variable directly. data being accessed table @ http://webrates.truefx.com/rates/connect.html?f=html code strips of tags , put in array $row0 , puts in function. can't out. function simplified question. intend concatenate of variables inside function once find out i'm doing wrong. $row0 = array(); include "scrape/simple_html_dom.php"; $url = "http://webrates.truefx.com/rates/connect.html?f=html"; $html = new simple_html_dom(); $html->load_file($url); foreach ($html->find('tr') $i => $row) { foreach ($row->find('td') $j => $col) { $row0[$i][$j]= strip_tags($col); } } myarray($row0); //table stripped of tags function myarray($arr) { $a = 'hello'; //$arr[0][0]; hello come out not variable $b = $arr[1][0]; $r[0] = $a; $r[1] = $b; //echo $r[1]; if //'s removed 1 can see proper value here not outside function. re

d3.js - Convert dc.js chart to pdf -

i using dc.js create charts. want export charts pdf. seems converting svg , using perl scripts convert svg pdf way. suggestions? i've used method using inkscape (on server): js: // --- create chart before --- postdata = { 'url':cryptojs.md5(window.location.href).tostring(), //used name file based on url (used caching, containing parameters in case) 'svg':$('#chart').html() //the created svg chart (using jquery here) }; $.post('create_pdf.php',postdata); //post svg php (using jquery here) create_pdf.php: //save svg file xyz.svg file_put_contents($_post['url'] . '.svg',$_post['svg']); // run command: inkscape -z xyz.svg -a xyz.pdf // png do: inkscape -z xyz.svg -e xyz.png $com = 'inkscape -z ' . $_post['url'] . '.svg -a ' . $_post['url'] . '.pdf'; exec($com); note: use d3.js directly, not dc.js (not sure that)

php - How can I add a custom fee in woocommerce that is calculated after tax -

i've added custom fee checkout page following code: add_action( 'woocommerce_cart_calculate_fees','woocommerce_custom_surcharge' ); function woocommerce_custom_surcharge() { global $woocommerce; if ( is_admin() && ! defined( 'doing_ajax' ) ) return; $percentage = 0.03; $surcharge = ( $woocommerce->cart->cart_contents_total + $woocommerce->cart->shipping_total + $woocommerce->cart->tax_total ) * $percentage; $woocommerce->cart->add_fee( 'my fee', $surcharge, false, '' ); } everything works expected except adding in tax. thought adding $woocommerce->cart->tax_total would trick, value returning 0. is there way calculate tax before fee calculated? i'm not sure if correct way handle issue. but, i've got working solution problem. i calculated tax , added fee calculation. add_action( 'woocommerce_cart_calculate_fees','woocomme

Segmentation fault in C with file -

i have segmentation fault in moment of second file in function imprimir, , dont know whats happend, because open , read firts not other file, confused me, please me #include <stdio.h> #include <stdlib.h> typedef struct { char nombre[40]; int creditos; float nota; } curso; int conteo(file *_entrada); void semestre(file *_entrada,curso *_materias,int *_cantidad,int *_ganadas,int *_perdidas,float *_promedio); void imprimir(curso *_materias,int *_cantidad,int *_ganadas, int *_perdidas,float *_promedio); int main(int argc, char *argv[]) { int ganadas=0; int perdidas=0; float promedio=0.0; int cantidad=0; char *archivoentrada; curso *materias; printf("archivo de entrada \n"); scanf("%s",archivoentrada); file *entrada; entrada=fopen(archivoentrada,"r"); if(entrada==null) { printf("no se logro abrir el archivo de entrada\n"); exit(exit_failure); } can

python - Deleting in Smaller Quantities SQLAlchemy MySQL -

mysql table space tends increase large deletions. i doing: s = session.query(model) s.delete() i understand can add s.limit(1000) and sleep after each deletion , re-querying s.all() determine if entries have been wiped. there way delete in batches of 1000 until original records have been cleaned out? your transaction log , required space going huge if you're deleting large number of records in single transaction. if need transaction, unavoidable (refactor not require it). otherwise, call .commit() between smaller chunks of (say 100,000 or so) records.

c++ - Choosing path of packet in socket programming? -

would possible manually set or @ least influence path packet takes through internet using socket programming application? for e.g. suppose don't want program send packets go through routers based in country a, go around instead. would possible? using c++ advice in context great language helpful well. no. the whole point of packet-switched networks routing determined collectively router located @ each hop along way. why called routers. it's fundamental how network large internet can work in useful way @ all. the originating machine not , cannot hope have enough information decide on inter-country network route and, if did, rest of internet never abide decision. whatever bizarre and/or nefarious use have in mind this, you'll have think of alternatives.

c# - Entity Framework Count and Group By in a Collection -

i have lambda expression returns data filtered, need calculations on records returned. i have 2 entities (user , language) have many-to-many relationship , need make grouped count of returnees languages find out how many people speak each returned language. sample set of data returned lambda expression: user1 (english, spanish) user2 (english, french) user3 (english, spanish) desired result: english 3 spanish 2 french 1 i tried use groupby () , select (), got right result foreach on results, using lambda. [edit] solution key results flattening using selectmany () in combination groupby(). @christos point right answer. you try this: var results = data.selectmany(user=>user.languages) .groupby(language=>language) .select(gr=>new { language = gr.key, total = gr.count()}); i have supposed each user object has sequence of strings, ienumerable<string> , called languages , holds user

c++ - Why won't my do-while loop continue looping? -

i'm working on creating menu error checking , i've come with, can't seem work. #include <iostream> using namespace std; int main() { char option; // user's entered option saved in variable int error1 = 0; //displaying options menu cout << "there 3 packages available." << endl; cout << "monthly price - price per mb overages (excluding c)" << endl; cout << "a) $15 - $.06 each mb after 200 mb." << endl; cout << "b) $25 - $.02 each mb after 2,000 mb ( approx. 2 gb)." << endl; cout << "c) $50 - unlimited data." << endl; //do-while loop starts here { //prompting user enter option according menu cout << "please enter plan have : "; cin >> option; // taking option value input , saving in variable "option" if(option == 'a' || option == 'a') // checking if user selected option 1 { cout <<

Meteor: relative/absolute path issue -

i'm testing out old code , i'm getting error , looks these lines of code: var targetfile='../../../../../public/image1.png'; var sourcefile='../../../../../../game4-dirs/public/image2.png'; fs.writefilesync(targetfile, fs.readfilesync(sourcefile)); the error i'm getting is: error: enoent, unlink '../../../../../public/image1.png' i seem vaguely remember public , game4-dirs aren't accessible relatively product relatively meteor installed (or that, can't quite remember). has change in version 1.2.0.2? using v0.9.3.1 thank :) if meteor application lives @ myapp on disk files under myapp/public available @ root in html / . means url image1.png should /image1.png . it looks ../../../../../../game4-dirs/public/image2.png trying access file not below meteor app's root directory. meteor won't allow on client obvious security reasons. if want use image2.png should move app's /public directory , refer

html - How to lengthen scroll when using scrollTop()? -

i'm using scrolltop() method in website . works fine on screen realized when homepage on bigger screen, scrollbar not scroll down. there way fix this? enter code here without editing scroll function need ensure body height. should @ least 50px > window height. inside of $(document).ready add this: $("body").css("height", window.outerheight + 50 + "px") ie: $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); $("body").css("height", window.outerheight + 50 + "px") });

vb.net - vb filepath getter code gets different filepath then C# getter code -

i converting vb website app c# , of conversions producing weird results example dim holidayfilepath = hostingenvironment.mappath("~/content/usa_holidays.txt") dim slist new list(of date) slist = getholidays(holidayfilepath) dim s string = slist.aggregate("", function(current, ddate) current & ddate.tostring()) returns filepath variable "x:\folder\toolkit\toolkit\content\usa_holidays.txt" and code snippet works expected, producing list of dates strings. but c# version public actionresult index() { var holidayfilepath = hostingenvironment.mappath("~/content/usa_holidays.txt"); var slist = new list<datetime>(); slist = daycalcs.getholidays(holidayfilepath); var s = slist.aggregate("", (current, ddate) => current + ddate.tostring(cultureinfo.currentculture)); return view(s); } returns holidayfilepath variable "x:\\folder\\toolkit\\tool

java - How do I copy element which reference from int array >=40 to a new String array -

i have int array , string array of same length, , want create new string array containing elements original string array; elements @ positions int on corresponding position in int array less or equal 40. public void check (int[]a,string []y){ string[]copy =new string[] for(int i=0,i=j,k;k<copy.length,i<a.length; i++,j++,k++){ if(a[i]>=50) y[j]=copy[k] } you need specify length of array. i.e string[] copy = new string[20]; <---- it helps use ; <---- @ end of each command. period in sentence... i think might wanted: public class inttostrng { public static void main(string[] args) { int[] ints = {2, 3, 4,5, 6, 7,}; string[] stng = new string[ints.length]; for(int = 0; i<ints.length; ++) { stng[i] = integer.tostring(ints[i]); } } }

kubernetes - Error running pod with image from gcr.io -

i've pushed docker container image gcr.io following command: $ gcloud docker push gcr.io/project-id-123456/my-image but when try create new pod following error: $ kubectl run my-image --image=gcr.io/project-id-123456/my-image controller container(s) image(s) selector replicas my-image my-image gcr.io/project-id-123456/my-image run=my-image 1 $ kubectl pods name ready status restarts age my-image-of9x7 0/1 error pulling image (latest) gcr.io/project-id-123456/my-image, untar exit status 1 unexpected eof 0 5m it doesn't pull on local well: $ docker rmi -f $(docker images -q) # clear local image cache $ gcloud docker pull gcr.io/project-id-123456/my-image:latest … error pulling image (latest) gcr.io/project-id-123456/my-image, untar re-exec error: exit status 1: output: unexpected eof can please

Im Trying to Detect a Certain Key being Pressed (Python) -

Image
this code, im beginner , ive been looking around ive looked @ atleast 5-10 posts this, aren't helping me because cant understand code. in code im trying basic starting screen game , want how detect e or s being pressed @ time of start screen, print (" _____________________________________________ ") print ("| |") print ("| |") print ("| chronicles |") print ("| of game |") print ("| |") print ("| |") print ("| |") print ("| |") print ("|_____________________________________________|") print ("| |") pr

Restructure CSV data with Notepad++, Regex -

i have csv file following headers , (sample) data: stopname,routename,travel_direction,latitude,longitude streeta @ streetb,1 namea,directiona,lat,long streetc @ streetd,1 namea,directiona,lat,long ... streete @ streetf,1 namea,directionb,lat,long streetg @ streeth,1 namea,directionb,lat,long ... streeti @ streetj,2 nameb,directionc,lat,long streetk @ streetl,2 nameb,directionc,lat,long ... streetm @ streetn,2 nameb,directiond,lat,long streeto @ streetp,2 nameb,directiond,lat,long . . . i wanting use regex (currently in notepad++) following results: 1 namea - directiona=[[streeta @ streetb,[lat,long]], [streetc @ streetd,[lat,long]], ...] 1 namea - directionb=[[streetd @ streete,[lat,long]], [streetf @ streetg,[lat,long]], ...] 2 nameb - directionc=[[streeth @ streeti,[lat,long]], [streetj @ streetk,[lat,long]], ...] 2 nameb - directiond=[[streetl @ streetm,[lat,long]], [streetn @ streeto,[lat,long]], ...] . . . with regex , substitution, rgx: ^([^,]*),([^,]*),([^,]*),(.*

mysql - How to use mysql_fetch_assoc to process records in php? -

Image
i trying retrieve subject names, there 2 types of subjects optional , main. each student contains optional , main subjects. using subject ids can retrieve name subject table. in result 1 optional subject name appearing, there problem in code? pls me $subject_names = array(); for($i=0;$i<count($student_num_data);$i++) { $optional_id_list = mysql_query("select optional_subject_id ms_student student_id = ".$student_num_data[$i]['student_id']); while($row = mysql_fetch_assoc($optional_id_list)) { foreach ($row $key) { $optional_subject = mysql_query("select subject_name ms_subject subject_id = ".$key['optional_subject_id']); $optional_subject_name = array(); while($row1 = mysql_fetch_assoc($optional_subject)) { $optional_subject_name[] = $row1; } } } $subject_id_list = mysql_query("select subject_ids subject_config

Java: Do While with || and && operators -

so i'm bit confused on following: while testing boolean, first impression use || operator conditions. did not work, loop keep repeating correct response. if used && operator, evaluate conditions way wanted to. i feel backwards, , i'm not looking @ right. can explain this? to make more clear, trying do: string input; scanner keyboard = new scanner(system.in); { system.out.print("enter 1 of following names: john, katie, richard"); input = keyboard.nextline(); input = input.tolowercase(); } while ( !input.equalsignorecase("john") && !input.equalsignorecase("katie") && !input.equalsignorecase("richard")); i want loop repeat until 1 of given names entered. if entered katie, should move on, if enter bob should repeat. so if enter john, boolean first checks that. !(john = john) ft = false. since want check see if equal john, not richard or katie want use || operator. why want check if eq

python - Could not parse the remainder: '%' from '%' Django -

i working django mezannine , running weird issue jinja. templatesyntaxerror @ /services/ not parse remainder: '%' '%' request method: request url: http://192.168.1.14/services/ django version: 1.8.3 exception type: templatesyntaxerror exception value: not parse remainder: '%' '%' exception location: /usr/local/lib/python3.4/dist-packages/django/template/base.py in __init__, line 639 python executable: /usr/bin/python3 python version: 3.4.3 my code looks below: {% image in images %} {% if loop.index % 3 == 0 %} #this line doesn't {{image}} {% endif %} {% endfor %} any idea going on here? thanks % reserved django have use divisibleby {% image in images %} {% if forloop.counter|divisibleby:"3" %} {{image}} {% endif %} {% endfor %}

ruby on rails 4 - How to auto rollback parent record if child record is not valid in has_one association -

here 2 models (rails 4.2) customer , address . customer has_one address . class customer < activerecord::base has_one :address, autosave: true, dependent: :destroy end class address < activerecord::base belongs_to :customer validates :add_line, :presence => true end with autosave set true, address saved along customer . if address not valid, don't want save customer @ all. our question how set has_one association such rollback of customer happens automatically if address not valid? use validates_associated validate address before save customer. class customer < activerecord::base has_one :address, autosave: true, dependent: :destroy validates_associated :address end

android - HTML files for different screen from asset folder -

my application contains html files , related images. i sized images screen size (480x800), image can fit screen width. but when app on large screen device, images become smaller. do need design html files multi-screen? or how make these images fit screen size? try css. .myfullscreenimage { background: url(images/bg.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } and apply myfullscreenimage class <img> tag <img src="source.jpg" class="myfullscreenimage"/>. let me know if works.

javascript - Jquery ajax validate or not? -

i'm using code execute action in controller parameters. , working in validation of inputs. $('.txt-dtr').on('blur', function () { // record type know column of table should value saved. var record = $(this).attr('id'); // record value var value = $(this).val(); // record date var row = $(this).closest('tr'); var date = row.attr('id'); // employee id var empid = $('#semployee').val(); // ajax script saving record $.ajax({ type: 'post', url: '/dtr/savedtr', data: { record: record, value: value, date: date, empid: empid } }); }); this code works, onblur , did'nt type in txt-dtr value parameter null , ajax not execute (which want). the question is, need write validation like if(value != null){ //execute ajax } or leave because without validating ajax not execute? ed

how to use associations in view font-end use angularjs and rails 4 -

i using rails 4 write in back-end , angular js write front end. have trouble use associations. i have 2 models: class record < activerecord::base has_and_belongs_to_many :tags end class tag < activerecord::base has_and_belongs_to_many :records end i using model records_tags connect 2 models record , tag . in controller, write: def index records = record.all.order('created_at desc') render json: {error:0, data: records} end in view <ul> <li ng-repeat ="data in datas"> {{data.tags.name}}</li> </ul> although, use relationship in controller success, variable datas send view don't use relationship them. anyone can me? thats normal, when in controller data collection on activemodel objects, relations live within it. when export json sending json object. include tags records have include tags in json object. def index records = record.all.order('created_at desc') render js

osx - Shortcut to switch panes in Split View on El Capitan -

el capitan (?finally) provides mechanism called split view have 2 apps side-by-side in full screen mode. i want know if there exists, or how i'd go implementing, keyboard shortcut switch/swap panes while in split view. that intended behaviour trigger take left-pane , make right-pane , take right-pane , make left-pane. there no keyboard shortcut doing have stated, u can drag left-pane towards right side mouse on menu bar. hope helps!

In Xcode, how to clean only one project in workspace -

often xcode build become messy, use clean , re- build project. project depends on several open source projects, managed cocoapod. the problem when use clean ⇧⌘k , entire workspace cleaned, of cocoapod-dependencies rebuilt, takes of build time. in of case, want own project cleaned. how do this?

python - Pandas: How to filter for items that occur more than once in a dataframe -

i have pandas dataframe contains duplicate entries. items listed twice or 3 times. filter shows items listed @ least n times. in final table items should shown once. dataframe contains 3 columns: [cola, colb, colc]. should consider colb in determining whether item listed multiple times. note: not drop_duplicates. it's opposite, drop items in dataframe less n times. the end result should list each item once. you can use value_counts item count , construct boolean mask , reference index , test membership using isin : in [3]: df = pd.dataframe({'a':[0,0,0,1,2,2,3,3,3,3,3,3,4,4,4]}) df out[3]: 0 0 1 0 2 0 3 1 4 2 5 2 6 3 7 3 8 3 9 3 10 3 11 3 12 4 13 4 14 4 in [8]: df[df['a'].isin(df['a'].value_counts()[df['a'].value_counts()>2].index)] out[8]: 0 0 1 0 2 0 6 3 7 3 8 3 9 3 10 3 11 3 12 4 13 4 14 4 so breaking above down: in [9]: df['a'].value_counts() > 2 out[9]: 3

I am writing a madlib in php, saving it to a db using mysql, then trying to pull out each new story in descending order -

i not sure how story out of db, getting error: warning: mysqli_fetch_array() expects parameter 1 mysqli_result, string given in /home/ubuntu/workspace/projects/project_1/madlib.php on line 33 call stack: 0.0009 248160 1. {main}() /home/ubuntu/workspace/projects/project_1/madlib.php:0 0.0058 257240 2. mysqli_fetch_array() /home/ubuntu/workspace/projects/project_1/madlib.php:33 <?php //connecting db $dbc = mysqli_connect('localhost', 'root', '', 'project1') or die('error connecting mysql server.'); //creating variables $noun = $_post['noun']; $verb = $_post['verb']; $adjective = $_post['adjective']; $body_part = $_post['bodypart']; $food_item = $_post['fooditem']; $full_story = "here things @ recess." "start game of touch $body_part-ball." "put $noun in someones lunch." "start $food_item fig

javascript - How to alter a promise chain? -

in chain promises there way have 1 of members add promises chain? this code illustrates better mean: $.ajax(......).then(function(r){ ..... return r; }).then(function(r){ var d = $.deferred(); // how add d.promise() chain ? .... return r; }).then(function(r){ // function should able receive "r" // should wait promise above complete :( .... }); i don't have experience jquery promises can pay promise one, nicolas bevacqua explain in ponyfoo article es6 promises in depth . var p = promise.resolve() .then(data => new promise(function (resolve, reject) { settimeout(math.random() > 0.5 ? resolve : reject, 1000) })) p.then(data => console.log('okay!')) p.catch(data => console.log('boo!')) i hope can adapt needs or maybe use native promises instead.

objective c - Logically ANDing NSUInteger and String Type? -

i've searched stackoverflow , other sites, can't seem find answer. in apple text editor source, have @ least 1 routine apparently strange logical anding between 2 non-boolean variables. casting them bools can done, doesn't make sense. i'm learning swift , less familiar objective-c, life of me, can't figure out how trying achieve goal stated "build list of encodings, sorted, , including human readable names." here code: /* return sorted list of available string encodings. */ + (nsarray *)allavailablestringencodings { static nsmutablearray *allencodings = nil; if (!allencodings) { // build list of encodings, sorted, , including human readable names const cfstringencoding *cfencodings = cfstringgetlistofavailableencodings(); cfstringencoding *tmp; nsinteger cnt, num = 0; while (cfencodings[num] != kcfstringencodinginvalidid) num++; // count tmp = malloc(sizeof(cfstringencoding) * num); mem

3d - What C++ compiler would compile without mistakes source codes of this publication for game developing? -

http://cws.cengage.co.uk/rautenbach/students/ancillary_content/c++.pdf tried different compilers received many errors for see need visual c++ visual studio 2008 or higher , directx sdk.

c# - How can I set up my model to perform this transaction? -

i have portion of database created with /* create table of scores of games played. every game have score recorded, there corresponding name if user enters 1 */ create table scores ( id int identity(1,1) not null primary key, score int not null, name varchar (50) ); /* create table of text logs of games played. these reviewed sniff out cheating. */ create table gamelogs ( id int identity(1,1) not null primary key, scoreid int not null foreign key references scores(id) on delete cascade on update cascade, logtext varchar (8000) ); and i'm using model generated entity framework try , perform equivalent of following transaction. insert scores (score, name) values (somenumber, somestring); select max(id) new_id scores; insert gamelogs (scoreid, logtext) values (new_id, someotherstring); the corresponding classes generat

c# - How to change direction of one column of datagridview from right to left? -

i have below code in asp.net datagrid view: <asp:gridview id="gvstore" runat="server" allowpaging="true" allowsorting="true" autogeneratecolumns="false" cellpadding="4" emptydatatext="هیچ کالایی موجود نیست" font-names="tahoma" font-size="small" forecolor="#333333" horizontalalign="center" width="1000px" onrowdatabound="gvstore_rowdatabound" onselectedindexchanging="gvstore_selectedindexchanging" onpageindexchanging="gvstore_pageindexchanging" captionalign="right" datakeynames="store_id"> <pagersettings firstpagetext="ابتدا" lastpagetext="انتها" mode="numericfirstlast" nextpagetext="بعدی" previo

javascript - Callback after multiple asynchronous calls? -

i'm using gmail api retrieve messages in loop , req.write() each message. there's callback each api invocation, how know when whole set done can end response? tried following noticed callbacks not executed in order of array index can't line commented out. for (var = 0; < messages.length; i++) { var message = messages[i]; console.log('- %s', message.id); (function(e){ var request = gmail.users.messages.get({ auth:auth, id:message.id, userid: 'me' }, function(err, response) { if(err) { console.log('api returned error: ' +err); return; } res.write(json.stringify(response,null,'\t')); console.log(e); //if(e==messages.length-1) res.end(); } ); })(i); }

How do I exit a loop in C++ without using break? -

i'm writing code swap integers in array , want know how can exit loop without using break statement , keeping logic consistent. here code below: int swapped = 0; if (arrays[0][first] % 2 == 0) { cout << arrays[0][first] << " odd " << endl; (int = 1; < arraycount; ++i) { (int j = 1; j < arrays[i][0] + 1; ++j) { if (arrays[i][j] % 2 != 0) { int temp = arrays[i][j]; cout << "array #" << 1 << " value " << arrays[0][first] << " swapped " << "array #" << << " value " << temp; arrays[i][j] = arrays[0][first]; arrays[0][first] = temp; swapped = 1; break; } } if (swapped) { break; } using br

ios - Create UILable at runtime and set autolayout programatically related to each other -

Image
i have uiview in uitableviewcell . getting array of names service , want create uilabel in for loop inside uiview in uitableviewcell according text width. i have done @ end problem want check if label being created having width greater space remaining in superview, should created below first line word wrapping of text in uilabel . what have done is, have created sample of code -(void)addadaynamicviw { [self.vwcontainer settranslatesautoresizingmaskintoconstraints:false]; uilabel *lblprevious; int totalwidth; (int i=0; i<8; i++) { uilabel *lbl=[[uilabel alloc]init]; //[lbl setframe:cgrectmake(0, 0, 30, 50)]; [lbl setnumberoflines:0]; [lbl setbackgroundcolor:[uicolor greencolor]]; [lbl settranslatesautoresizingmaskintoconstraints:false]; [lbl settext:[nsstring stringwithformat:@"label num %d",i]]; [self.vwcontainer addsubview:lbl]; nslayoutconstraint *top; top=[nslayout

Facebook iFrame App to Fit Facebook Canvas in iPad -

note following issue been solved update ios latest version (9.0.2) i have web application, runs in facebook iframe. worked perfect long time, , still working in pc, in ipad, make facebook canvas smaller , somehow app not fit new facebook canvas size. how can make app fit size of facebook canvas size? i see in app setting: canvas fixed width "yes" sets canvas width 760 px" sure fb bug, because fb ipad canvas width smaller 760px in last ipad app. there no way define custom width . update ios latest 1 (9.0.2) solve issue!

optimization - Why C++ compiler isn't optimizing unused reference variables? -

consider following program: #include <iostream> struct test { int& ref1; int& ref2; int& ref3; }; int main() { std::cout<<sizeof(test)<<'\n'; } i know c++ compiler can optimize reference variables entirely won't take space in memory @ all. i tested above demo program see output. when compile & run on g++ 4.8.1 gives me output 12. looks compiler isn't optimizing reference variables. expecting size of test struct 1. i've used -os command line option still gives me output 12. have tried program on msvs 2010 compiled /ox command line option looks microsoft compiler isn't performing optimization @ all. the 3 reference variables unused & aren't associated other variable. why compilers aren't optimizing them? the size of struct stays same, there nothing optimize. if create array of test should allocate right size each test . compiler cannot know used or not. that's why there n

python - ZeroMQ bidirectional async communication with subprocesses -

i have server process receives requests web clients. server has call external worker process ( .py ) streams data server , server streams client. the server has monitor these worker processes , send messages them ( kill them or send messages control kind of data gets streamed ). these messages asynchronous ( e.g. depend on web client ) i thought in using zeromq sockets on ipc:// -transport-class , call socket.recv() method blocking. should use 2 sockets ( 1 streaming data server , receive control messages server )? using separate socket signalling , messaging better while poller -instance bit, cardinal step use separate socket signalling , 1 data-streaming. always. point is, in such setup, both poller.poll() , event-loop can remain socket-specific , spent not more predefined amount of time, during real-time controlled code-execution. so, not hesitate setup bit richer signalling/messaging infrastructure environment enjoy increased simplicity of control, separat

android - How to play next song automatically in media player? -

i have seen question answered lot of time here. have problem. when ever music player starts skips first track , and automatically starts playing 2nd track. i want behave normal music payer. public class musicservice extends service { private final mediaplayer mp = new mediaplayer(); private final ibinder localbinder = new localbinder(); arraylist<song> songs = new arraylist<>(); boolean firstattempt = true; public musicservice() { } @override public ibinder onbind(intent intent) { return localbinder; } public class localbinder extends binder{ musicservice getservice(){ return musicservice.this; } } @override public void oncreate() { super.oncreate(); setsongslist(); initmediaplayer(); } void initmediaplayer(){ mp.setaudiostreamtype(audiomanager.stream_music); mp.setoncompletionlistener(new mediaplayer.oncompletionlistener() { @override public void oncompletion(mediaplayer mediaplayer) {

java - how to extract red, green and blue channels of bitmap in Android -

Image
i have bitmap image loaded memory bitmap object. can load imageview,do operations using canvas , forth.but algorithm i'm using need 3 channel grey scale bitmaps. below image article written eric z goodnight on how geek.the link given below. https://www.howtogeek.com/howto/42393/rgb-cmyk-alpha-what-are-image-channels-and-what-do-they-mean/ can see in grey scale images corresponding each channels respective colour areas brightest. how can extract grey scale images corresponding each channels bitmap image in android? require 3 bitmaps objects containing these 3 channel grey scales respectively.i have come across method create grey scale setting saturation of colormatrix 0.but returns on 1 grey scale.is there way grey scale images corresponding 3 channels? a pixel in bitmap format represented 4 bytes integer, describe alpha, red, green , blue channels of pixel. extracting particular channel, can bitwise or on every pixel, appropriate hex value. for instance, 0xfff

geometry - Proving similar triangles within a trapezoid - Mathematics Stack Exchange

Image
abcs trapezoid, , eq , fp bisectors of these trapezoid arms. i prove angle cqb equal angle apd. i tried show similarity between triangles cqb , apd, because both of them isosceles. if show similarity exists, angle cqb equal angle apd. however, don't know how show these triangles similar. you have prove minor base of trapezoid , vertices of isosceles triangles on same circle , major base , vertices of isosceles triangles on circle. angles in green equal , angle in pink equal sum of green , pink equal , 2 angles of isosceles triangles equal

java - ImageView.findViewById on a null object reference -

Image
this question has answer here: what nullpointerexception, , how fix it? 12 answers i've made simple mistake cannot figure out how correct it. it's null object reference . thanks advice ! instead imageview = (imageview)imageview.findviewbyid(r.id.simplicity_bg_id); replace with imageview = (imageview) findviewbyid(r.id.simplicity_bg_id);

java - Sending request to axis1.4 service with proxy -

i trying consume webservice , generate client using axis 1.4 via eclipse . , when sending request service , local proxy blocking request want send wthe request custom proxy details. i'm not sure right place put proxy details in code send request. can of faced same kind of issue, please me resolve.

python - Alternative to referencing variable before assignment -

import time # define variables username = "username" password = "password" customer_info_file_path = "c:\\users\megam\pycharmprojects\general stuff\the square pie co\customer " \ "information\{}.txt ".format(name) username_entry = input("enter username\n>>") password_entry = input("enter password\n>>") if username_entry != username or password_entry != password: print("access denied\nyou have entered username or password incorrectly. please check password , " "account name , try again.\n") else: print("access granted") choice_menu = input("\na) view list of customers\nb) add customer\nc) delete customer\nd) log out\n>>") if choice_menu == "a": customer_info = open(customer_info_file_path, 'a', ) file = open(customer_info_file_path, 'r') output = file.read()

algorithm - Counting sort in C implemented according to pseudocode but doesn't run properly -

i have implemented counting sort according pseudocode ( that's written on blackboard in video explanation ) mysterious reason, doesn't seem sort properly. for test input: 10 9 8 7 6 5 4 3 2 1 it gives: 3 4 5 6 7 8 1 0 0 9 it seems simple problem can't figure out why happening. void counting(int * array, int n){ int *copy, *out, i,j, max, counter; copy = (int*) malloc(sizeof(int) * max); out = (int*) malloc(sizeof(int) * n ); max = array[0]; // finds max size for(i=0;i<n;++i) if(array[i] > max) max = array[i]; // zeroes counting array for(i=0;i<max;++i) copy[i] = 0; //counts for(i=0;i<n;++i) ++copy[array[i]]; //cumulative sum for(i=1;i<max;++i) copy[i] += copy[i-1]; //sorts for(i=n-1;i>=1;--i){ out[copy[array[i]]] = array[i]; --copy[array[i]]; } //overwrite original array sorted output for(i=0;i<n;++i) array[i] = out[i]; } the problem orde

html - Div height animation direction issue from bottom -

i'm working on text fill animation using :after element on top of text , animate height of make fill animation. it's working position absolute , top 0 on :after element. if want make same animation of height in oposite direction bottom top, should change top 0 bottom 0. that's issue appear, :after element goes under text block ? here code : https://codepen.io/1conu59/pen/zdvxop .text { font-family: 'montserrat', sans-serif; font-size: 12em; font-weight: 700; position: relative; display: inline-block; background-color: black; color: #fff; } .text:after { transition: 1s ease; content: attr(data-content); display: block; position: absolute; top: 0; left: 0; right: 0; color: black; width: 100%; height: 0%; overflow: hidden; *background-color: black; z-index: 1000; } .text:hover:after { height: 100%; border-radius: 0px; } <div class="text" da

python - Tkinter .grid() position in center of screen -

in tkinter, i'm using grid() place widgets , want position widget, namely label, in middle of screen. know how this? for example, following code: widget.grid(row=0, column=1) want column 1 there 3 columns (0, 1, 2) without having place widget in column 2. thanks. to able achieve this, need know how many rows , columns window have. for example if have 3 rows , 3 columns (the minimum able locate in center), screen split this: -------------------------------------------- | | | | | 0,0 | 0,1 | 0,2 | | | | | | | | | -------------------------------------------- | | | | | 1,0 | 1,1 | 1,2 | | | | | | | | | -------------------------------------------- | | | | |

cors - AngularJS $http call fails due to Access-Control-Allow-Origin -

i using withcredentials: true on $http call send session id in request headers. but facing: "the value of 'access-control-allow-origin' header in response must not wildcard '*' when request's credentials mode 'include'. origin 'null' therefore not allowed access. credentials mode of requests initiated xmlhttprequest controlled withcredentials attribute." so changed cors filter on server side to: response.setheader("access-control-allow-origin", "http://localhost:8080/"); now getting error: "the 'access-control-allow-origin' header has value ' http://localhost:8080 ' not equal supplied origin. origin 'null' therefore not allowed access." can please tell me solution? try using snippet: response.setheader("access-control-allow-origin", "*");

design patterns - Java Constructor of a class with fields that are are end user fed -

my question is: best way write constructor of java class fields initialized through stdin ? for example suppose have employee class looks like: public class employee { private int empid; private string empname; private list<role> emproles; {....} } i can write setters , getters class. of course, role class have own file. also suppose make setters first 2 fields follows, in order enable end user initialize fields: public void setempid() { system.out.println("please enter employee id"); scanner s = new scanner (system.in); this.empid = s.nextint(); public void setempname() { system.out.println("please enter employee name"); scanner s = new scanner (system.in); this.empname = s.next(); } then: can use such setters in constructor overrides default constructor. is best way write such constructors? is better move scanner object creating in each setter constructor , make argument setters e.g: p

A good way of creating a git master branch from a former one -

okay couldn't think of title this, here's story. i made survey app specific one, odd invitation logic creating pdf @ specific parts of procedure, made master branch since small , 1 time app. then few years later there project use app small modifications. went have problem, want have master branch work on core parts , bug fixes, other branches pull it. the way can think of is, have move master(the first project) branch(version/aa), , remove project specific stuff on master, if pull version/aa, delete specific code branch, have manually revert code parts back, seems full of danger. is there way it? master name , can name branch whatever want , change meaning of name whatever prefer. master default name default branch kept branch main development happens. you can rename existing branches using git branch -m oldname newname . , can introduce branch pointing older version using git branch branchname old-commit-hash . so in case, create branch old point be

javascript - ng-repeat limit make issue for remove -

i have 1 ng-click add md-datepicker : <md-button ng-click="additem()" type="button" >add infants</md-button> then ng-repeat set 4 : ng-repeat="d in radiodata | limitto: 4 " ng-value="d.value" ng-class="{'md-align-top-left': $index==1}" everything working expected have 1 ng-click remove: <md-button ng-click="removeitem()" type="button">remove infants</md-button> then problem start if click more 4 time on additem() not show remove start remove first kind of wierd. there not show . read track $index not working . controller is: $scope.additem = function() { $scope.radiodata.push({}); }; $scope.removeitem = function() { $scope.radiodata.pop(); }; any idea me when call additem() , push new struct radiodata . however, you're limiting shown data 4 items via limitto:4 through ng-repeat . means can still add more 4 items radiodata array, won't sho