Posts

Showing posts from June, 2010

python - How does readline() work behind the scenes when reading a text file? -

i understand how readline() takes in single line text file. specific details know about, respect how compiler interprets python language , how handled cpu, are: how readline() know line of text read, given successive calls readline() read text line line? is there way start reading line of text middle of text? how work respect cpu? i "beginner" (i have 4 years of "simpler" programming experience), wouldn't able understand technical details, feel free expand if others understand! example using file file.txt : fake file text in few lines question 1: how readline() know line of text read, given successive calls readline() read text line line? when open file in python, creates file object. file objects act file descriptors, means @ 1 point in time, point specific place in file. when first open file, pointer @ beginning of file. when call readline() , moves pointer forward character after next newline reads. calling tell() function o

sqlite3 - Linker error with CMake -

i'm using jetbrains clion pure c (c ansi) development, know it's target c++, company works c , clion uses cmake build system. my system debian jessie system , sqlite3 , libsqlite3-dev installed. i'm trying build simple sqlite3 project this: #include <sqlite3.h> #include <stdio.h> int main() { sqlite3 *sqlconnection; int ret; ret = sqlite3_open("database/path.db, &sqlconnection); if (ret) { printf("ups ... can't open %d", ret); } do_some_queries(sqlconnection); return 0; } the automatic generated cmakelists.txt follwing. cmake_minimum_required(version 3.3) project(project) set(cmake_cxx_flags "${cmake_cxx_flags} -std=c++11") set(source_files main.cpp ) add_executable(project ${source_files}) when build, either through clion, either through command line, linker errors: ... undefined reference `sqlite3_prepare_v2' undefined reference `sqlite3_column_int' undefine

python 3.x - Pypyodbc: return field description of specific field in specific MS Access table? -

i'm trying retrieve description (or other property) of field in ms access database. something in recordset of vba: for each field in recordset.fields debug.print "name: " & field.name debug.print "type: " & field.type debug.print "size: " & field.actualsize debug.print "value: " & field.value next is there way how pypyodbc (or other odbc module)? the cursor.description attribute give following information each column in cursor: name type_code display_size internal_size precision scale null_ok for other information on fields in access table need use com create access dao object , pull information fields collection of table's tabledef object. see accessing microsoft automation objects python for more information on using com python on windows.

python - Pandas: expand list in column to distinct rows -

Image
i have dataset big number of columns contain several values (imported google forms, columns allowing multiple selection). i've imported lists initially. now want analyse data based on values columns, i.e. given df = pd.dataframe(dict(a=[(1,2),(2,3),(1,)], b=[(1,3),(2,5),], c=['a','b','c'])) b c 0 (1, 2) (1, 3) 1 (2, 3) (2, 5) b 2 (1) () c i want plot bar chart x distinct values columns , b (they share same set of options), , y total count of rows having option: you can summing columns (basically concatenating contents) , calling pd.value_counts on them. example (modifying dataframe definition not raise error): df = pd.dataframe(dict(a=[(1,2),(2,3),(1,)], b=[(1,3),(2,5),()], c=['a','b','c'])) counts = pd.dataframe({col: pd.value_counts(df[col].sum()) col in ['a', 'b']}) counts.plot(kind='bar&#

botframework - MS BotBuilder on Azure -

deploying botbuilder on azure fine. but when invoked botframework internal server error. log files show error in stack trace of application log. builder.chatconnector not constructor. anything done solve this? redeoploying application new azure site did trick.

c# - Images disappear in SliderView and ListView while scrolling -

i have sliderview (of appstudio.uwp.controls). images appear load page disappear when scroll through list. tested listview too. same thing happening there too. <controls:sliderview x:name="sliderview" itemssource="{x:bind listforotherpicturesthumbnails}" itemtemplate="{staticresource hero}" relativepanel.below="mainimage" relativepanel.alignleftwithpanel="true" relativepanel.alignrightwithpanel="true" arrowsvisibility="visible" /> the itemtemplate used follows- <datatemplate x:key="hero" x:datatype="local:storageitemthumbnailclass"> <grid margin="6" padding="12" background="white" borderthickness="1" borderbrush="lightgray"> <image source="{x:bind thumbnail, converter={staticres

css - Why does my html page fail to render the same after making it standalone? -

Image
i have web page (web api/asp.net) looks pretty want to: this code produces it: @model webapprptscheduler.models.homemodel @using system.data @{ viewbag.title = "pro*act eservices reporting"; datatable dtunits = model.units; var units = x in dtunits.asenumerable() select new { unit = x.field<string>("unit") }; datatable dtreports = model.reports; var reports = x in dtreports.asenumerable() select new { report = x.field<string>("reportname").toupper() }; list<string> daysofmonth = model.daysofmonth; list<string> ordinalweeksofmonth = model.ordinalweek; list<string> daysofweek = model.daysofweek; list<string> patternfrequency = model.patternfrequency; int maxmonthsbackbegin = model.maxmonthsbackforreportbegin; int maxmonthsba

javascript - Babel transform this by _this -

i have bootstrap modification tooltip. , process js webpack/babel a simplification of code be: $('[data-toggle="tooltip"]').tooltip({ title: () => { return $(this).children('.tooltip-html-content').html(); } }); this should element, bootstrap call function with: gettitle: function () { var title , $e = this.$element , o = this.options title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title) return title } the important line is: o.title.call($e[0]) where $e[0] tooltip dom element. well, when process babel result change this _this before assign _this value consider real this. the question: can avoid conversion in babel specific function? ===== final solution based in response: gettitle: function gettitle() { you've used arrow function, definition closes on this

java - How I get path in xml -

i have xml structure this. <?xml version="1.0" encoding="utf-8" ?> <root> <child1 name="1"/> <child2 name="2"/> <child3 name="3"> <condition>x>=50</condition> <childofchild3 name="3.1"> <condition>y<40</condition> <childofchild3.1 name="3.1.1"> <condition>a>70</condition> <step> <a1> <aa1> </aa1> </a1> <b1 /> </step> <c1> <a1> <aa1> </aa1> </a1> </c1> </childofchild3.1> <c1>

python - Quick slicing of a dataframe using another dataframe in pandas -

i have 2 dataframes in pandas. df "a" contains start , end indexes of zone names. df "b" contains start , end indexes of subzones. goal extract subzones of zones. example: a: start index | end index | zone name ----------------------------------- 1 | 10 | x b: start index | end index | subzone name ----------------------------------- 2 | 3 | y in above example, y subzone of x since indexes fall within x's indexes. the way i'm doing using iterrows go through every row in a, , every row (zone) find slice in b (subzone). solution extremely slow in pandas since iterrows not fast. how can task without using iterrows in pandas?

python - Parallel execution using Canvas Workflow -

i've been working on project requires execution of tasks in parallel way as possible. code below exemplifies problem: # -*- coding: utf-8 -*- __future__ import absolute_import celery.app import celery celery.utils.log import get_task_logger logger = get_task_logger(__name__) app = celery('celeryproject', backend="redis://localhost:6379/0", broker="amqp://guest:guest@localhost:5672//") @app.task def step1(x): # list of str webservice using x return ["step1-%s-%s" % (x, i) in range(5)] @app.task def step2(y): # list of str webservice using x return ["step2-%s-%s" % (x, i) in range(5, 10)] @app.task def step3(z): # process z logger.info(z) @app.task def pipeline(xs): x in xs: r1_list = step1.delay(x).get() r1 in r1_list: r2_list = step2.delay(x, r1).get() r2 in r2_list: step3.delay(r2) i need execute task.pipeline start process. tried can

c - Byte-addressed memory (Data alignment) -

Image
i don't want homework. want tips on how can learn myself. given byte-addressed memory writes lowest highest addresses. have c program has following declarations: long int = 1; char c = 'x'; short int n = 10; short in m = 11; float f = 0.0; in ia32 int 4 bytes, char 1 byte, short 2 byte , float 4 byte. how these declaration saved in memory likely? fill out following in hex digits. how begin here? can give me tips? what's first thing have do? edit: prof told me system ia32. i assume variables declared , defined local (not static/global) variables, example: int main() { long int = 1; char c = 'x'; short int n = 10; short in m = 11; float f = 0.0; } if so, allocated on stack. the principles of allocating local variables on stack same systems: stack grows high addresses low addresses the order of declaration of variables in program corresponds growth of stack each type has alignment - address of variable must di

laravel - Blade @include directive -

blade's @include directive, allows include blade view within existing view. variables available parent view made available included view. how can hide parent values included view? want use variables sent or else, use default variables. for example, consider following view. can access variable named $title <a class="btn btn-danger" href="{{$url or url::previous()}}"><i class="fa fa-arrow-left"></i> {{$title or 'save'}} </a> not prettiest solution, think handle putting of vars in array: <a class="btn btn-danger" href="{{$mydata['url'] or url::previous()}}"><i class="fa fa-arrow-left"></i> {{$mydata['title'] or 'save'}} </a> and including view: @include('view', ['mydata' => null]) note, untested.

actionscript 3 - Adobe AIR - Fullscreen / Display -

windows computer running air. every night educational displays turned off. computers stay on. on displays when turn them on in morning screen resolution goes , forth few times starting @ 1920 x 1080 1024 x 768 1920 x 1080. when happens reason air app freaks out , stays @ 1024 x 768 doesn't take fullscreen , can see desktop. have manually relaunch air app. is there way when happens can detect , go force fullscreen? thanks in advance suggestions. if using maximized window, can listen event.resize on stage (dispatched when window get's resized), , or listen native windows displaystatechange or resize events. if using full_screen (or full_screen_interactive) display state, can listen fullscreenevent.full_screen event know when has changed. here example of few things can try: //in document class or main timeline, listen following events: stage.nativewindow.addeventlistener(nativewindowboundsevent.resize, windowresized); //the above fire anytime

python - Error when starting ipython notebook when into virtual environment -

when type ipython notebook works fine. need work virtual environment: what do virtualenv .env source .env/bin/activate pip install -r requirements.txt now type ipython notebook this given error: /home/derk/assignment2/.env/bin/python: bad interpreter: no such file or directory so when not in virtual environment can start notebook. however, when not virtual environment gives error. the requirements.txt looks this: cython==0.21.2 jinja2==2.7.3 markupsafe==0.23 pillow==2.7.0 backports.ssl-match-hostname==3.4.0.2 certifi==14.05.14 gnureadline==6.3.3 ipython==2.3.1 matplotlib==1.4.2 mock==1.0.1 nose==1.3.4 numpy==1.9.1 pyparsing==2.0.3 python-dateutil==2.4.0 pytz==2014.10 pyzmq==14.4.1 scipy==0.14.1 six==1.9.0 tornado==4.0.2 wsgiref==0.1.2 everything worked correctly before, (maybe after software updates) doesnot. tried reinstalling anaconda (as suggested on sites), without success. problem here? this error can happen when 1 has moved or renamed virtualenv .

c++ - GL_INVALID_OPERATION in glGenerateMipmap(incomplete cube map) -

i'm trying learn opengl , i'm using soil load images. i have following piece of code: gluint texid = 0; bool loadcubemap(const char * basefilename) { glactivetexture(gl_texture0); glgentextures(1, &texid); glbindtexture(gl_texture_cube_map, texid); const char * suffixes[] = { "posx", "negx", "posy", "negy", "posz", "negz" }; gluint targets[] = { gl_texture_cube_map_positive_x, gl_texture_cube_map_negative_x, gl_texture_cube_map_positive_y, gl_texture_cube_map_negative_y, gl_texture_cube_map_positive_z, gl_texture_cube_map_negative_z }; (int = 0; < 6; i++) { int width, height; std::string filename = std::string(basefilename) + "_" + suffixes[i] + ".png"; std::cout << "loading: " << filename << std::endl; unsigned char * image = soil_load_image(filename.c_str(), &

php - Hide Stock Qty/Availability for Specific Attribute Set -

i have bit of odd situation trying fix. magento v1.9.2.4 i have 2 different attribute sets. , b. i want display stock quantity/availability set b, not set a. to make things bit more complex, have 14 customer groups, want 6 of groups ever see quantities/availability. here's have done far arrange this: $customersession = mage::getsingleton('customer/session'); if($customersession->isloggedin()){ $groupid = $customersession->getcustomergroupid(); $group = mage::getmodel('customer/group')->load($groupid); if ('custgroup_1' == $group->getcode()){ $qty = (int) mage::getmodel('cataloginventory/stock_item')->loadbyproduct($_product)->getqty(); echo 'quantity available: ' . $qty; } } the above snippet repeated 5 times [if ('custgroup_1' ...] changed accommodate group need show for. part working fine. i need specify somehow want availability show attribute set b.

javascript - How do you send a complex object with an ajax post method to c# controller? -

i'm trying send complex javascript object mvc controller post method. receive badrequest response every time run method. won't let me debug visual studio, web developer tools. checked fiddler see json object seems in same order view model. please me this? using asp.net core 1.0. please let me know if need provide more information. here's view model: public class routeviewmodel { public routeviewmodel() { } public list<checkpointviewmodel> checkpoints { get; set; } public int totaldistance { get; set; } } public class checkpointviewmodel { public decimal latitude { get; set; } public decimal longitude { get; set; } } the logic compile object follows: function createobject() { var routemodel = { checkpoints: [] ,totaldistance:totaldistance}; (var = 0; < markersorders.length; i++) { var latlng = markersorders[i].getposition(); var checkpoint = { 'latitude'

MATLAB Concatenating Functions -

i have function @(x) f(x) returns 3-by-3 matrix. want define function @(x) f(x) returns 3*n-by-3*n , f(x) repeated n times along diagonal, arbitrary n . this can done arrays (instead of functions) pretty simply: n = 5; = repmat({magic(3)},[1,n]); b = blkdiag(a{:}) but functions, there subtlety since arguments need passed. naive attempts unsuccessful: f=@(x) magic(3); f=@(x) blkdiag(repmat({f(x)},[1,n])) f=@(x) blkdiag({repmat({f(x)},[1,n])}) f=@(x) blkdiag(repmat({feval(@(xx) f(xx),x)},[1,n])) in general, there elegant ways concatenate/combine/repeat function?

php - symfony3 is using mysite.com/web instead of mysite.com -

hello i'm using symfony 3 new project. have deployed host. see project have go mysite.com/web instead of mysite.com how can solve this? here goes .htaccess file # use front controller index file. serves fallback solution when # every other rewrite/redirect fails (e.g. in aliased environment without # mod_rewrite). additionally, reduces matching process # start page (path "/") because otherwise apache apply rewriting rules # each configured directoryindex file (e.g. index.php, index.html, index.pl). directoryindex app.php # default, apache not evaluate symbolic links if did not enable # feature in server configuration. uncomment following line if # install assets symlinks or if experience problems related symlinks # when compiling less/sass/coffescript assets. # options followsymlinks # disabling multiviews prevents unwanted negotiation, e.g. "/app" should not resolve # front controller "/app.php" rewritten "/app.php/app". <ifmodu

r - modify stat_summary to show only a few point -

Image
currently have boxplot below , stat_summary used show quantiles of each distribution text. group = c( rep(c(1,2),100) ) r = rnorm(200,50,63) d = data.frame( group = group, r = r ) head(d) ggplot(data = d, aes(factor(group), r)) + geom_boxplot() + stat_summary(geom="text", fun.y= quantile, aes(label=sprintf("%1.0f", ..y..)), position=position_nudge(x=0.33), size=3) you can see quantiles printed text via fun.y= quantile line of code. how can modify code print median , min , max printing 3 points instead of 5? i can create function , select quantiles want ff= function (x) { return(quantile(x)[1]) } and use fun.y= quantile , print want how incorporate fun.y directly in stat_summary call? thank you. add fun.args stat_summary follows: ggplot(data = d, aes(factor(group), r)) + geom_boxplot() + stat_summary(geom="text", fun.y=quantile, fun.args=list(probs=c(0,

java - Passing value from jsp to servlet but servlet is not available -

i using intellij idea 14 create web app using servlet , jsp whenever try pass value jsp there error http status 404 - /books/booksaleauctionservlet type status report message /books/booksaleauctionservlet description requested resource not available. apache tomcat/7.0.30 myfiles : index.jsp <form method= "get" action="books/booksaleauctionservlet"> username : <input type="text" name="name" id="name"> address : <input type="text" name="address" id="address"> contact : <input type="tel" name="contactno" id="contactno"> email : <input type="email" name="email" id="email"> password : <input type="password" name="pass" id="pass"> <input type="submit" name="save"> and there servlet booksaleauctionservlet inside books package , con

java - Error while posting JSON using JSOUP concept -

i want post nested json input saiku server.i got successful in postman while trying in java code have error such as errorjava.lang.illegalargumentexception: data value must not null below code posting nested json saiku server. // nested json jsonobject object = new jsonobject(); jsonobject querymodel = new jsonobject(); jsonobject cube = new jsonobject(); jsonobject parameters = new jsonobject(); jsonobject plugin = new jsonobject(); jsonobject properties = new jsonobject(); jsonobject metadata = new jsonobject(); jsonobject axes = new jsonobject(); jsonobject details = new jsonobject(); jsonobject columns = new jsonobject(); jsonobject filter = new jsonobject(); jsonobject rows = new jsonobject(); jsonobject measures = new jsonobject(); jsonobject o = new jsonobject(); jsonobject hiera

css - C# Webbrowser: Specifying Max-Device-Width -

i working on web application uses windows forms c# webbrowser take screenshots of web pages , save them archiving purposes. i running issue pages use max-device-width in css media queries responsive layout. apparently max-device-width webbrowser control defaults 1024 px causes css rules fire resulting in layout issues. using max-width in media queries fix this, have undesired effects when resizing browser window on desktop browsers. is there way of specifying max-device-width of webbrowser?

java - LinkedList function from InterviewBit -

i'm struggling solution for question on interviewbit . i linked full description, in short: 1) given head node of linkedlist 2) take first half of list , change values that: "1st node’s new value = last node’s value - first node’s current value 2nd node’s new value = second last node’s value - 2nd node’s current value" here approach (it compiles not mutate list @ all) i see method not modify original list -- seems i'm doing making new list correctly altered values, not changing original. /** * definition singly-linked list. * class listnode { * public int val; * public listnode next; * listnode(int x) { val = x; next = null; } * } */ public class solution { public listnode subtract(listnode a) { listnode current = a; int length = 0; //get length while(current.next != null){ length++; current = current.next; } length += 1; while(current.next != null

java - How to write specific symbols to Docx file using docx4j -

Image
i have specific logical symbols ⇒,∨,∧,¬ , want write text these symbols docx document. short symbols ∨,∧,¬ fine, symbol ⇒ overlaps next character but should like my code looks maindocumentpart mdp = wordmlpackage.getmaindocumentpart(); p p = factory.createp(); r run = factory.creater(); p.getcontent().add(run); text text = factory.createtext(); text.setvalue("((q⇒p)∧q)⇒p"); run.getcontent().add(text); mdp.addobject(p); how correct writing long symbols ⇒? you can use docx4j code generation want. create document in word looks how want it, save docx. to generate code based on docx, 1 of following: upload http://webapp.docx4java.org/onlinedemo/partslist.html or 2. install/use our word addin; @ http://www.docx4java.org/forums/docx4jhelper-addin-f30/docx4j-helper-addin-v1-final-available-t2253.html if still having problems, post xml created in word, or code generated following above steps.

python - Trello API ~ simply getting the contents of a list? -

i trying contents of list on board created understand things work flow. the api seems quite complex, , have been @ hours. have api key, secret key. i tried following docs: https://api.trello.com/1/lists/4eea4ffc91e31d174600004a/cards?key=[application_key]&token=[optional_auth_token] however, not sure these letters/numbers coming from: 4eea4ffc91e31d174600004a . i read following page: https://developers.trello.com/apis (which gave me link url above), there no info on how 4eea4ffc91e31d174600004a . i want visit url gives me json or of vein, contents of list (e.g. cards + names). can visit link programmatically , analysis. edit: using trello developer sandbox: https://developers.trello.com/sandbox/ found id of list, substituted 4eea4ffc91e31d174600004a , following: taco says “invalid token”, know? he's dog. i used secret key token, guess that's not token. question boils down how can token? thanks so full answer is: to cards in list, 3 things re

html - How to change disabled option text color in the pull down list? -

Image
how can change font color of disabled option in select menu? (not select itself, options in pull down menu) want because in chrome/safari there no difference between disabled/enabled options (see first picture). in ie difference somehow obvious. in firefox quite obvious. below approach works in ff. how can in cross-browser manner? https://jsfiddle.net/6wazms1a/3/ html: <select> <!-- want change text color of 'disabled' in pull down list. reason: make non-disabled options more prominent (like in ie , firefox) --> <option disabled>disabled</option> <option selected>enabled selected</option> <option>other enabled</option> <option>another enabled</option> </select> css: option:disabled, option[disabled], option[disabled="disabled"] { color: #ccc; } so far results: chrome/safari bad. there no difference between enabled/disabled options. can hardly tell enabled

Python How Can I Make a Counter To Cycle Through a Dictionary Inside a For Loop? -

i have started coding , don't know it. bit of code tries cycle through numbers loop assign num1 , num2. instead make new 1 called num0. what?! import random numbers = {'num1': '', 'num2': ''} counter = 0 in range(0, 2): number = random.randint(0, 5) counter + 1 numbers['num' + str(counter)] = number; print(numbers) counter + 1 adds 1 value of counter, never stores result assigning result counter . need assign result counter variable, i.e. counter = counter + 1 or more concisely equivalent counter += 1 .

sql server - How to show '0' amount for a month, if no data exists in the table for that month -

Image
i have 2 tables costtable (id,resourceid, amount,date) , resourcetable (resourceid,name) shows output below. i want show 0 amount rest of name in case of september. e.g. if rest of resources not appear in cost table should appear 0 in amount my desired output my current query select rg.id id, rg.name name, isnull(sum(ac.amount), 0) amount, right(convert(varchar(10), ac.[date], 105), 7) [yearmonth] cost ac inner join resource rg on ac.resourcegroupid = rg.id ac.portalid = '100' , [date] >= dateadd(month, datediff(month, 0, dateadd(m, -11, getdate())), 0) group rg.name, rg.id, right(convert(varchar(10), ac.[date], 105), 7) order rg.name desc you can cross join , left join . question hard follow because tables , descriptions differ. however, idea: select t.minid, t.name, ym.yearmonth, coalesce(amount, 0) amount (select name, min(id) minid t group name) n cross join (select distinct yearm

javascript - Instant Search using google api with php -

i had been working on instant search in php using google jquery api . in youtube video program working (because learning video) . database logic correct because tried in simple html page. not working on jquery. please give me suggestion shot out problem. working on ubuntu 14.04. this jquery contained php page. <!doctype html> <html> <head> <title>webpage</title> <script type=text/javascript src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script type=text/javascript> function searchq() { var searchtxt = $("input[name='search']").val(); $.post('search.php', {search_term: searchtxt}, function(output){ $('#output').html(output); }); } </script> </head> <body> <form action="index.php" method="post"> <