Saturday 15 February 2014

arrays - Accessing values stored in object c++ -



arrays - Accessing values stored in object c++ -

i creating new instance of object storing each instance of virtual function array.

the problem cannot value of each object 1 time create it,

to clear want each instance of floors create homecoming value int when called. virtual function build(int a) returns int

current output

we adding spot value 0 in our array

i need value added output

so based on current illustration should show value 5

i assume should work because of mybuilding.add(new floors(5));

complex.h

class complex { protected: int num; public: virtual void build(int a) { num = a; } };

main.cpp

#include "floors.h" int main() { building mybuilding; mybuilding.add(new floors(5)); mybuilding.build(); homecoming 0; }

floors.h

class floors : public complex { private: int quantity; public: floors(const int& init_quant) : quantity(init_quant) { } int build(floors()) { std::cout << "this floors class" << quantity << '\n'; homecoming quantity; } };

and class handling array, building.h

class building { public: static const int max_materials = 100; complex* materials[max_materials]; int num_materials; public: building() : num_materials(0) {} ~building() { for(int = 0; < num_materials; ++i) { delete materials[i]; } } bool add(complex* s) { if(num_materials >= max_materials) { homecoming false; } materials[num_materials++] = s; homecoming true; } void build() { for(int = 0; < num_materials; ++i) { materials[i]->build(i); std::cout << "we adding spot value " << << " in our array" << '\n'; } } };

at point in time, c++ becoming rusty has been 2 years since programming in professionally. going reply no 1 else has, there better/more right reply given.

you getting output seeing because of line:

std::cout << "we adding spot value " << << " in our array" << '\n';

that line saying print out value of i, not value contained within floor object when phone call build.

you calling build(0) in first iteration of loop. going phone call build function in base of operations class complex class has homecoming type of void. since floors kid of complex , method signature method build best matches 1 takes int , returns void. in example, have created floors object quantity of 5 when phone call build method, calling base of operations class build sets num value of 0. not able access num value building class due beingness marked protected.

as bit rusty , haven't experimented it, can't tell signature of build method in floors class is, can guarantee isn't think is. confused want be. want take different floor object. way beingness used expect signature looking for.

int build() { std::cout << "this floors class" << quantity << '\n'; homecoming quantity; }

in order output think looking need alter build method in building class (note, have alter build method in floor class match method have listed in point 3):

void build() { for(int = 0; < num_materials; ++i) { int quantity = materials[i]->build(); std::cout << "we adding spot value " << quantity << " in our array" << '\n'; } }

c++ arrays

excel - Conditionally copy cells to new workbook -



excel - Conditionally copy cells to new workbook -

i haven't worked vba while , here's i'm trying do: have worksheet column of id numbers, , bunch of columns create reference whether person id has done ("1") or not ("0"). this:

id task1 task2 task3 103 1 1 0 129 0 1 0 154 1 1 1 189 1 0 1 204 0 1 1

what want macro create new workbook each task (and save workbook under name of task), , populate each workbook id #s of have completed task. so, there should should create , save workbook called "task1" has values 103, 154, , 189 in column a, create , save separate workbook called "task2" has values 103, 129, 154, , 204 in column a, , on.

i haven't been successful far. came this:

sub copytoworkbooks() dim lrow, lcol integer sheets("sheet1").select lrow = range("a" & rows.count).end(xlup).row lcol = cells(1, columns.count).end(xltoleft).column each cell in range(cells(1, "b"), cells(1, lcol)) union(range("a1:a" & lrow), range(cells(1, cell.column), cells(lrow, cell.column))).copy workbooks.add range("a1").pastespecial activeworkbook.saveas filename:= _ "users:user:desktop:workbookfolder:" & cell.value & ".xls" 'for saving workbook on mac activeworkbook.close next cell application.cutcopymode = false end sub

this creates , save 3 separate workbooks right workbook names, copies of values in column , of values in column corresponds new workbook name. so, example, workbook "task2" looks this:

id task2 103 1 129 1 154 1 189 0 204 1

any help appreciated. thanks!

i have made couple of changes code in order accomplish task have described:

sub copytoworkbooks() dim lrow integer dim lcol integer dim integer dim j integer dim tcount integer dim ws worksheet dim taskarr variant application.screenupdating = false set ws = activeworkbook.sheets("sheet1") ws.select lrow = ws.cells(ws.rows.count, 1).end(xlup).row lcol = ws.cells(1, columns.count).end(xltoleft).column 'loops through each column = 2 lcol step 1 redim taskarr(1 2, 1 1) tcount = 1 taskarr(1, tcount) = ws.cells(1, 1).value taskarr(2, tcount) = ws.cells(1, i).value 'loops through each row j = 2 lrow step 1 if ws.cells(j, i).value = 1 tcount = tcount + 1 'read values array redim preserve taskarr(1 2, 1 tcount) taskarr(1, tcount) = ws.cells(j, 1).value taskarr(2, tcount) = ws.cells(j, i).value end if next j 'add new workbook workbooks.add activesheet.range("a1", activesheet.cells(tcount, 2).address) = worksheetfunction.transpose(taskarr) activeworkbook.saveas filename:="users:user:desktop:workbookfolder:" & ws.cells(1, i).value & ".xls" 'for saving workbook on mac activeworkbook.close erase taskarr next application.screenupdating = true end sub

instead of copying/pasting values, read values each task array , inserts sheet in destination workbook.

excel excel-vba

c# - Unity MiniJSON: Can't deserialize WWW response -



c# - Unity MiniJSON: Can't deserialize WWW response -

i'm sending www request , getting proper txt response in json, i'm not sure i'm doing wrong deserialize json string dictionary. code:

ienumerator requestscores(int level) { www jsonscores = new www(requestscoresurl + level); yield homecoming jsonscores; //wait download finish float elapsedtime = 0.0f; while (!jsonscores.isdone) { elapsedtime += time.deltatime; if (elapsedtime >= 10.0f) break; yield homecoming null; } if (!jsonscores.isdone || !string.isnullorempty(jsonscores.error)) { debug.logerror(string.format("fail whale!\n{0}", jsonscores.error)); yield break; } string response = jsonscores.text; debug.log(elapsedtime + " : " + response); // here "search" gets null value dictionary<string, object> search = json.deserialize(response) dictionary<string, object>; }

so jsonscores.txt retrieved correctly far can tell dictionary<string,object> search comes out null, doing wrong?

thanks in advance!

ok found wrong in there, getting multiple rows needed deserialize list of dictionaries instead of single one.

this code worked:

list <dictionary<string, object>> list;

...

list = json.deserialize(response) list<dictionary<string, object>>; foreach (dictionary<string, object> row in list) { // whatever row }

c# json unity3d

c++ - How do I get nearest grid intersection? -



c++ - How do I get nearest grid intersection? -

i'm trying draw circle @ closest line intersection on grid relative mouse. draw grid center outward varying x , y separations. attempted right coord off. how right coordinate?

here's code:

class grid : public sf::drawable, public sf::transformable { public: grid(unsigned int xsep, unsigned int ysep, unsigned int canvasw, unsigned int canvash); virtual ~grid() {}; void setfillcolor(const sf::color &color); void setsize(unsigned int xsep, unsigned int ysep, unsigned int canvasw, unsigned int canvash); unsigned int xsep = 0; unsigned int ysep = 0; private: virtual void draw(sf::rendertarget& target, sf::renderstates states) const { // apply entity's transform -- combine 1 passed caller states.transform *= gettransform(); // gettransform() defined sf::transformable // apply texture states.texture = &m_texture; // may override states.shader or states.blendmode if want states.blendmode = sf::blendmode(sf::blendmode::srcalpha, sf::blendmode::oneminusdstcolor,sf::blendmode::add); // draw vertex array target.draw(m_vertices, states); } sf::vertexarray m_vertices; sf::texture m_texture; }; grid::grid(unsigned int xsep, unsigned int ysep, unsigned int canvasw, unsigned int canvash) { xsep = xsep; ysep = ysep; m_vertices.setprimitivetype(sf::lines); m_vertices.clear(); (int i=((canvasw/2)-xsep); > 0; i-=xsep) { m_vertices.append(sf::vector2f(i,0)); m_vertices.append(sf::vector2f(i,canvash)); m_vertices.append(sf::vector2f(canvasw-i,0)); m_vertices.append(sf::vector2f(canvasw-i,canvash)); } (int i=((canvash/2)-ysep); > 0; i-=ysep) { m_vertices.append(sf::vector2f(0,i)); m_vertices.append(sf::vector2f(canvasw,i)); m_vertices.append(sf::vector2f(0,canvash-i)); m_vertices.append(sf::vector2f(canvasw,canvash-i)); } m_vertices.append(sf::vector2f(0,canvash / 2)); m_vertices.append(sf::vector2f(canvasw,canvash / 2)); m_vertices.append(sf::vector2f(canvasw / 2, 0)); m_vertices.append(sf::vector2f(canvasw / 2,canvash)); } int roundnum(int num, int difference) { int rem = num % difference; homecoming rem >= 5 ? (num - rem + difference) : (num - rem); } sf::circleshape point(5); point.setorigin(point.getradius()/2,point.getradius()/2); sf::vector2f mousepos = mappixeltocoords(sf::mouse::getposition(*this)); point.setposition(roundnum(mousepos.x,grid.xsep),roundnum(mousepos.y,grid.ysep)); draw(point);

i see @ to the lowest degree 2 things into.

first, set grid lines uniformly spaced center outward. roundnum(mousepos.x,grid.xsep) snaps position line of grid spaced uniformly wherever x zero. presumably point not @ center of rectangle. @ corner of rectangle? since width of rectangle not multiple of 2 * grid.xsep, grid aligned corner offset grid aligned corner. true y-coordinates well.

edited in response comment: 1 way solve problem subtract width/2 x-coordinate, round it, add together width/2. alternatively, find grid.xsep - ((width/2)%grid.xsep); add together value x-coordinate, round result, subtract value. sec way more complicated avoids having think happens if x in x%n negative. of course of study similar y-coordinates.

second, works when difference 9 or 10:

homecoming rem >= 5 ? (num - rem + difference) : (num - rem);

it work values of difference if replace 5 difference/2. create work correctly values of difference (even or odd), replace 5 (difference + 1)/2.

it may worth confirming want:

point.setorigin(point.getradius()/2,point.getradius()/2);

it appears correct, it's easy check (just draw circleshape @ known grid point, such center) might create sure.

c++ sfml

html - row stays highlighted after mouseover -



html - row stays highlighted after mouseover -

i've come across unusual artifact in chrome (works fine in safari):

as can see, rows remain highlighted when scrolling not when scrolling down. i'd row homecoming it's original background color.

here's basic table:

<table> <tbody> <tr> <td id="checkmark" rowspan=2> </td> <td rowspan=2> ordercreate </td> <td> elemica </td> <td> mr. widgets </td> <td> 23 jan 2013 13:04:35 </td> <td> 49384038503940394 </td> </tr> <tr> <td colspan=4> <span>doc id</span> <span>273ashdf2347sdfh</span> </td> </tr> </tbody> </table>

i'm doing little bit of binding knockoutjs , lift (scala) nil crazy (and there no issues anywhere else, or in safari). hmm.

and here's css

tr { height: 38px; border-bottom: 1px solid $bg-color; background: white; &:hover { background: darken(white, 10%); }

any suggestions? might @ way done path bit ... stuck. thanks.

html css

android - Specifying transparent cutouts in xml drawable -



android - Specifying transparent cutouts in xml drawable -

does android back upwards specifying transparent cutouts in xml shape drawables?

note: i'm using android studio , targeting api 14+.

i'm trying create simple images , several objects. but, far, if specify color alpha of 0, don't see shape @ all. want, foreground shape, alpha of 0 color, create transparent area cuts out layers below it.

i'd rather not in code.

can show me illustration of how this?

android drawable transparent shape mask

java - How could I get a path to one project from another during runtime? -



java - How could I get a path to one project from another during runtime? -

i have project 2 modules named web-app , prebuildactions , there simple console application in prebuildactions.

the construction of folder next:

| prj | project1 -web-app -prebuild

i running prebuild, dlike path web-inf folder located in web-app

system.getproperty("user.dir");

gave me valid path project path prebuild folder. possible path folder web-inf located in other project folder grammatically without running web-app ? trying organize pre-build generation of configs web-app

perhaps -this possible go 1 level executing project? ../../ ?

java

android - Google play developer distribution agreement. Where to view and agree -



android - Google play developer distribution agreement. Where to view and agree -

google play developer console shows message

the google play developer distribution understanding has changed business relationship owner business relationship needs agree new google play developer distribution understanding within next 8 days or access developer console blocked until business relationship owner agrees new agreement.

but cannot find agree it. took @ https://play.google.com/intl/all_us/about/developer-distribution-agreement.html - can view it, cant agree.

any suggestions?

is there google business relationship set owner of dev console? when log console owner account, prompted new understanding , given chance accept.

android google-play

UML diagrams priority -



UML diagrams priority -

i'm new uml and, far know, there lots of uml diagrams:

class diagram / object diagram / component diagram / deployment diagram utilize case diagram / sequence diagram / collaboration diagram / statechart diagram activity diagram

and on. know if there kind of diagram priority in order create model or not. example, first diagrams class, component, utilize case, etc.

if there isn't, can suggest me approch uml diagrams?

thank you.

uml modeling language not development method. therefore, uml standard not define specific ordering diagrams (in fact concept of diagram somehow artificial). projects end using same kind of diagram @ different points of process (every time @ different abstraction level).

uml priority diagrams

javascript - How to hide image on click with two functions? -



javascript - How to hide image on click with two functions? -

i'm using simple image i'm trying on click of image 2 things first hide image , play content in i'm using iframe video has no play button 1 time click on anywhere of video plays i'm trying add together simple play button utilize click on image , video play need help javascript help appreciated.

<div id="playbutton"> <img style="width: 200px; height: 200px; border: 0;" src="http://iconshots.com/wp-content/uploads/2010/01/final1.jpg"> </div>

check fiddle out @ http://jsfiddle.net/cwl9moqk/4/

try this:

jquery: $(document).ready(function() { $('#play-video').on('click', function(ev) { $("#video")[0].src += "&autoplay=1"; ev.preventdefault(); }); }); html: <div id="playbutton"> <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:and9gcrh0aw8dopc_x6jfb8wyuivroo9xy0ewwqskikb8mme_aaepfuzeowimq" onclick="this.style.display='none';" id="play-video"> <iframe id="video" width="420" height="315" src="//www.youtube.com/embed/9b7te184zpq?rel=0" frameborder="0" allowfullscreen></iframe> css: #play-video { width: 200px; height: 200px; border: 0; bottom: 10; left: 0; right: 0; position: fixed; text-align: center; margin: 0px auto; }

check fiddle out @ http://jsfiddle.net/cwl9moqk/4/ if need more help or not looking please comment - i'm happy help!

javascript jquery html

java - Make a Grid from a string in a text file -



java - Make a Grid from a string in a text file -

i have 3 run arguments min width, max width , text file name. text files filled 1 long string of random characters. want set each character grid spot. string file. how create grid?

class gridcipher{ static int mingridwidth; static int maxgridwidth; static file inputfile; public static void main(string[] args) throws filenotfoundexception { if (handlearguments(args)) processinput(); } static final string usage = "usage: gridwriter min_width max_width input_file_name"; static boolean handlearguments(string[] args) { // check right number of arguments if (args.length != 3) { system.out.println("wrong number of command line arguments."); system.out.println(usage); homecoming false; } seek { mingridwidth = integer.parseint(args[0]); maxgridwidth = integer.parseint(args[1]); } grab (numberformatexception ex) { system.out.println("min_width , max_width must integers."); system.out.println(usage); homecoming false; } inputfile = new file(args[2]); if (!inputfile.canread()) { system.out.println("the file " + args[2] + " cannot opened input."); homecoming false; } homecoming true; } static void processinput() throws filenotfoundexception { scanner input = new scanner(inputfile); string line = input.nextline(); int length = line.length(); // number of characters. // seek each width in appropriate range (int width = mingridwidth; width <= maxgridwidth; width++) { // determine heigth of grid int height = line.length() / width; // add together 1 height if there's partial lastly row if (line.length() % width != 0) height += 1; loadunloadgrid(line, width, height); } } static void loadunloadgrid(string line, int width, int height) { char grid[][] = new char[height][width]; // determine number long columns int longcolumn = line.length() % width; if (longcolumn == 0) longcolumn = width; //load input info grid column int charcount = 0; (int c = 0; c < width; c++) { (int r = 0; r < height; r++) { if (r < height - 1 || c < longcolumn) { grid[r][c] = line.charat(charcount); charcount += 1; } } } // output info grid rows (int r = 0; r < height - 1; r++) { (int c = 0; c < width; c++) { system.out.print(grid[r][c]); } } // special handling lastly row (int c = 0; c < longcolumn; c++) { system.out.print(grid[height - 1][c]); } system.out.println("\""); } }

if text file has abcde, abcde. characters in grid determined min , max width.

if understand correctly want abcdefg into

b c d e f g

but in fragment writing on screen miss new line character

// output info grid rows (int r = 0; r < height - 1; r++) { (int c = 0; c < width; c++) { system.out.print(grid[r][c]); } }

should

// output info grid rows (int r = 0; r < height - 1; r++) { (int c = 0; c < width; c++) { system.out.print(grid[r][c]); } system.out.println(); }

java multidimensional-array

linux - check if command is running in bashrc -



linux - check if command is running in bashrc -

here question. since there problem dropbox folder automatics sync. have add together " ~/.dropbox-dist/dropboxd &" in .bashrc. whenever open terminal, automatically start synchronizing. problem arise when want have tab in terminal. receiving next warning "another instance of dropbox (8664) running! ". although not impact dropbox, quite annoying. searched unfortunately not find solution on web. help appreciated in advance.

thanks

add yout .bashrc

ps cax | grep dropbox > /dev/null if [ $? -eq 0 ]; echo "process running." else ~/.dropbox-dist/dropboxd & echo "process not running." fi

linux bash terminal dropbox

java - Where disappeared the method TextView.getTextColor(Context context, TypedArray typedArray, int defStyle) in new Android 5.0? -



java - Where disappeared the method TextView.getTextColor(Context context, TypedArray typedArray, int defStyle) in new Android 5.0? -

after sdk updating android 5.0 disappeared method textview.gettextcolor(context context, typedarray typedarray, int defstyle). used method custom textview (for int colorid definition xml). how determineint color id xml?

here sample code getting color textview:

textview tv = (textview) findviewbyid(r.id.yourcomponentid); int tv_color = tv.gettextcolors().getdefaultcolor();

or can color normal text this:

textview tv = (textview) findviewbyid(r.id.yourcomponentid); int tv_color = tv.getcurrenttextcolor();

in case of using first example, can color various states using

textview tv = (textview) findviewbyid(r.id.yourcomponentid); colorstatelist colorstatelist = tv.gettextcolors(); int tv_color colorstatelist.getcolorforstate(states, failcolor);

hope helps.

reference: getcolorforstate

java android textview android-5.0-lollipop

Error limit size post Json Android export .NET -



Error limit size post Json Android export .NET -

i'm working export of data, including images in android application web application generated .net.

i'm thinking error in amount of info generated json, such sending info 3 images correct, when set 4 or plus pictures, error occurs in post shipping.

need help, or type of solution sending separate images.

tks

android .net json size image-size

c# - Display this SQL into MVC View -



c# - Display this SQL into MVC View -

i have mvc 5 entity framework 6. i've been trying figure out using linq razor view , i'm not getting results.

how t-sql

select rt.name, count(r.rtypeid) rtypid dbo.request r bring together dbo.rtype rt on r.rtypeid = rt.rtypeid grouping rt.name, r.rtypeid

that returns these results...

name rtypeid alter request 42 new request 386 re-run 28 other 1

here 2 models created rt

namespace dbmr.models { using system; using system.collections.generic; using system.componentmodel.dataannotations; using system.linq; public partial class rtype { public rtype() { this.requests = new hashset<request>(); this.requestinputs = new hashset<requestinput>(); } public int? rtypeid { get; set; } [display(name = "request type:")] public string name { get; set; } public nullable<bool> isselected { get; set; } public virtual icollection<request> requests { get; set; } public virtual icollection<requestinput> requestinputs { get; set; } } }

for r

namespace dbmr.models { using system; using system.collections.generic; using system.componentmodel.dataannotations; using system.linq; public partial class request { public int requestid { get; set; } public string jobid { get; set; } public string title { get; set; } public int statusid { get; set; } public int? rtypeid { get; set; } public int urgencyid { get; set; } public int categoryid { get; set; } public int dtypeid { get; set; } public int resolutionid { get; set; } public int analystid1 { get; set; } [datatype(datatype.date)] public int analystid2 { get; set; } public nullable<system.datetime> opendt { get; set; } [datatype(datatype.date)] public nullable<system.datetime> closedt { get; set; } public int analystid3 { get; set; } public virtual analyst analyst { get; set; } public virtual analyst analyst1 { get; set; } public virtual analyst analyst2 { get; set; } public virtual category category { get; set; } public virtual dtype dtype { get; set; } public virtual resolution resolution { get; set; } public virtual rtype rtype { get; set; } public virtual status status { get; set; } public virtual urgency urgency { get; set; } } }

just trying create page in mvc app displays summary table.

what best way accomplish this?

controller:

//create context using(var ctx = new mydbcontext()) { var items = ctx.requests .groupby(r => new { r.rtype.name, r.rtypeid }) .select(r => new myrequestdata { name = r.rtype.name, count = r.count() }); homecoming view(items); }

class hold data

public class myrequestdata { public string name { get; set; } public int count { get; set; } }

view:

<table> <tr> <th> heading 1 </th> <th> heading 2</th> </tr> @foreach(var item in model) { <tr> <td>@item.name</td> <td>@item.count</td></r> } </table>

c# entity-framework model-view-controller

php - Base64 encoded message issue with webservice for mobile app -



php - Base64 encoded message issue with webservice for mobile app -

we posting message website , displaying on mobile app. storing message in base64 encoded format in mysql database. mobile app giving base64 encoded string, , mobile developer doing decoding there side , displaying normal text. issue when using 'enter, single quote, double quote' characters displayed ' \n, \' , \" ' this.

is there solution this displayed correctly in android , iphone app. or can php server side.

you need utilize nsdatabase64encodingendlinewithlinefeed instead of nsdatabase64encoding64characterlinelength parameter in ios while converting base64 normal string using base64encodedstringwithoptions method

nsstring *strnormaltext = [yourbase64data base64encodedstringwithoptions:nsdatabase64encodingendlinewithlinefeed];

try these below parameters if needed :

nsdatabase64encoding76characterlinelength nsdatabase64encodingendlinewithcarriagereturn note : in android same alternative might available

php android ios mysql mobile-application

javascript - How can I embed a twitter timeline in a Shiny app -



javascript - How can I embed a twitter timeline in a Shiny app -

i keen embed twitter timeline part of shiny app. have got relevant code snippet

<a class="twitter-timeline" href="https://twitter.com/pssguy/timelines/524678699061641216" data-widget-id="524686407298596864">soccer</a> <script>!function(d,s,id){var js,fjs=d.getelementsbytagname(s) [0],p=/^http:/.test(d.location)?'http':'https';if(!d.getelementbyid(id)){js=d.createelement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentnode.insertbefore(js,fjs);}}(document,"script","twitter-wjs");</script>

i have created twitter.js file (the above minus script tags ) , ui.r below

library(shiny) shinyui(fluidpage( tags$head(includescript("twitter.js")), titlepanel(""), sidebarlayout( sidebarpanel( ), mainpanel( a("soccer", class="twitter-timeline", href="https://twitter.com/pssguy/timelines/524678699061641216", data-widget-id="524686407298596864") ) ) ))

this produces error

error: c:\users\pssguy\documents\r\testgoogletwitter/ui.r:19:124: unexpected '=' 18: mainpanel( 19: a("soccer", class="twitter-timeline", href="https://twitter.com/pssguy/timelines/524678699061641216", data-widget-id=

if omit data-widget-id="524686407298596864", link which, when clicked on, opens browser window right timeline

one thing have noticed script given not quite same in twitters development tutorial https://dev.twitter.com/web/embedded-timelines

<script type="text/javascript"> window.twttr = (function (d, s, id) { var t, js, fjs = d.getelementsbytagname(s)[0]; if (d.getelementbyid(id)) return; js = d.createelement(s); js.id = id; js.src= "https://platform.twitter.com/widgets.js"; fjs.parentnode.insertbefore(js, fjs); homecoming window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } }); }(document, "script", "twitter-wjs")); </script>

tia

you need quote data-widget-id not syntactically valid name:

> make.names("data-widget-id") [1] "data.widget.id"

so next should work:

library(shiny) runapp(list(ui = fluidpage( tags$head(tags$script('!function(d,s,id){var js,fjs=d.getelementsbytagname(s) [0],p=/^http:/.test(d.location)?\'http\':\'https\';if(!d.getelementbyid(id)){js=d.createelement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentnode.insertbefore(js,fjs);}}(document,"script","twitter-wjs");')), titlepanel(""), sidebarlayout( sidebarpanel() , mainpanel( a("soccer", class="twitter-timeline" , href = "https://twitter.com/pssguy/timelines/524678699061641216" , "data-widget-id" = "524686407298596864") ) ) ) , server = function(input, output, session){ } ) )

javascript r twitter shiny

r - Rmarkdown v2, embed Latex document -



r - Rmarkdown v2, embed Latex document -

i writing paper using rmarkdown v2 in rstudio , exporting pfd format. within paper, want include regression table generated software , saved latex document (.tex).

how do that?

i looked @ rmarkdown v2 documentation , on-line not find reference this, because thought utilize r way (which not alternative yet in case)

using: r version 3.1.1, rstudio 0.98.1017, windows 7

r latex rmarkdown

java - How to use out parameter in oracleprepared statment -



java - How to use out parameter in oracleprepared statment -

i have procedure has 2 output parameters , 1 object input parameter. have provide input parameter array(sql array) have no thought how deal output parameters.

oraclepreparedstatement pstmt = (oraclepreparedstatement)conn.preparestatement( "call stg_core.insert_flexi_gl_response(?,?,?)"); pstmt.registerreturnparameter(1, oracletypes.varchar); pstmt.setarray( 3, array_to_pass );

i getting compilation error @ oracletypes.varchar. have tried importing alternative provided eclipse nil working.

i getting error oracletypes cannot resolved variable. kindly provide me solution or workaround.

java oracle

arrays - What are these last lines of code doing in Exercise 1-13 of K & R's The C Programming Language? -



arrays - What are these last lines of code doing in Exercise 1-13 of K & R's The C Programming Language? -

i new programming in general, please bear lack of knowledge.

i have spent couple of hours on exercise 1-13. decided answer, found @ link https://github.com/ccpalettes/the-c-programming-language-second-edition-solutions/blob/master/chapter1/exercise%201-13/word_length.c .

because didn't want re-create sake of learning, tried understand code , remake it. (this resulted in finish copy, understand improve have otherwise.)

this have far:

#include <stdio.h> #define in 1 #define out 0 #define largest 10 main() { int c, state, l, i, j; int length[largest + 1]; (i = 0; <= largest; ++i) length[i] = 0; state = out; while ((c = getchar()) != eof) { if ((c >= 'a' && c <= 'z') || (c >= 'a' && c <= 'z')) { if (state == out) { l = 0; state = in; } ++l; } else if (state == in) { if (l <= largest) ++length[l - 1]; //minus 1 because nth term of array array[n-1] else //if (l > largest) ++length[largest]; state = out; } if (c == eof) break; } (i = 0; <= largest; ++i) { if (i != largest) //because array[10] refers 11th spot printf("\t %2d |", + 1); //plus 1 because 1st array [0] //this results in 1-10 because 0-9 plus 1 makes highest 10 else printf("\t>%2d |", largest); (j = 0; j < length[i]; ++j) putchar('x'); putchar('\n'); } homecoming 0; }

please ignore comments. meant me, explain programme myself.

i having 2 issues can't figure out, , they're driving me crazy:

the output accounts 1 word less in input, meaning "my name not bob" results in:

... 2 |xx 3 |x 4 |x ...

also, don't understand going on @ end of program. specifically, don't understand here why variable j beingness used:

(j = 0; j < length[i]; ++j) putchar('x');

thanks much help, , i'm sorry if beginner community.

well, trying sum answers since question not closed. first, need right main() line:

int main(void) { ... homecoming 0; }

the int necessary because homecoming value @ end of function, , void means function doesn't receive arguments.

i've copied code , executed on machine (ubuntu 12.04) , worked perfectly. nowadays examples generate error?

as said, j variable traverse vector. length[i] vector holds, in each position i number of words length i. instance, if position 3 has value of 4, e.g. length[3] = 4, means there 4 words length 3.

finally, if may, i'd give tip. practice choosing meaningful names variables. code linked here helped me understand programme should do. variable names such, length, or defines in, out or largest vague.

i hope gather answers until , helped more.

c arrays kernighan-and-ritchie

javascript - Pause & Resume setTimeout in a loop -



javascript - Pause & Resume setTimeout in a loop -

i have next $.each loops through object. every 5 seconds get_file() function called. there anyway include pause , resume option. if click pause loading of info stops. , of course of study when click resume button starts 1 time again left off.

hope can help.

$.each(obj, function (i, v) { settimeout(function () { file = v.new_file; var timeline_date = moment(v.last_modified_date).format("dddd, mmmm yyyy, h:mm:ss a"); bhover = 0; //re-highlight links $(".timeline_msg").html(timeline_date); get_file(file); }, 5000 * (i + 1)); });

make array of timers, can clear them when pause button clicked. utilize global variable maintain track of how far through list of files load. can resume left off.

var curfile = 0; var load_file_timers; function load_files() { load_file_timers = obj.map(function(v, i) { if (i < curfile) { homecoming null; } else { homecoming settimeout(function() { var file = v.newfile; var timeline_date = moment(v.last_modified_date).format("dddd, mmmm yyyy, h:mm:ss a"); bhover = 0; //re-highlight links $(".timeline_msg").html(timeline_date); get_file(file); curfile++; }, 5000 * (i - curfile + 1)); } }); } load_files(); $("#pause").click(function() { $.each(load_file_timers, function(i, timer) { if (timer) { cleartimeout(timer); } }); }); $("#resume").click(load_files);

javascript jquery

html - html5/javascript multiplying input types and displaying in table -



html - html5/javascript multiplying input types and displaying in table -

how create button onclick takes these 2 values entered, , multiply them , display them in table? if can't help me table part multiplication helpful!

lets html is:

<form> <label>first number</label> <input type="text" id="number-1"> <label>second number</label> <input type="text" id="number-2"> <input type="submit" value="multiply" id="multiply"> </form> <table> <thead> <tr> <th>value 1</th> <th>value 2</th> <th>result</th>

and javascript, having jquery, is:

$(function(){ $('#multiply').click(function(event){ event.preventdefault(); var value1 = $("#number-1").val(); var value2 = $("#number-2").val(); var result = value1 * value2; var newrow = $("<tr></tr>"); var firstcell = $("<td></td>"); var secondcell = $("<td></td>"); var resultcell = $("<td></td>"); var valueone = $("#number-1").val(); var valuetwo = $("#number-2").val(); var result = valueone * valuetwo; firstcell.append( valueone ); secondcell.append( valuetwo); resultcell.append( result ); newrow.append(firstcell); newrow.append(secondcell); newrow.append(resultcell); $('#table-body').append(newrow); }); }); </script>

that should trick if understood want :-)

javascript html

python - ValueError: too many boolean indices for a n=600 array (float) -



python - ValueError: too many boolean indices for a n=600 array (float) -

i getting issue trying run (on python):

#loading in text file in need of analysis x,y=loadtxt('2.8k 293k 15102014_rerun 47_0k.txt',skiprows=1,unpack=true,dtype=float,delimiter=",") c=-1.0 #need flip voltage axis yone=c*y #actually flipping array plot(x,yone)#test origin=600.0#where origin? i.e v=0, taking 0 1v elements of array xorg=x[origin:1201]# array origin final point (n) xfit=xorg[(x>0.85)==true] # taking array origin , shortening farther relevant area

it returns valueerror. have tried doing process much smaller array of 10 elements , xfit=xorg[(x>0.85)==true] command works fine. programme trying narrow field of vision, of data, relevant point can fit line of best fit linear element of data.

i apologise formatting beingness messy first question have asked on website cannot search can understand going wrong.

this reply people don't know numpy arrays (like me), mre pointers numpy docs.

numpy arrays have nice feature of boolean masks.

for numpy arrays, operators homecoming array of operation applied every element - instead of single result in plain python lists:

>>> alist = range(10) >>> alist [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> alist > 5 true >>> anarray = np.array(alist) >>> anarray array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> anarray > 5 array([false, false, false, false, false, false, true, true, true, true], dtype=bool)

you can utilize array of bool index numpy array, in case filtered array positions corresponding bool array element true.

>>> mask = anarray > 5 >>> anarray[mask] array([6, 7, 8, 9])

the mask must not bigger array:

>>> anotherarray = anarray[mask] >>> anotherarray array([6, 7, 8, 9]) >>> anotherarray[mask] valueerror: many boolean indices

so cant utilize mask bigger array masking:

>>> anotherarray[anarray > 7] valueerror: many boolean indices >>> anotherarray[anotherarray > 7] array([8, 9])

since xorg smaller x, mask based on x longer xorg , valueerror exception.

python arrays numpy boolean

php - Site looks fine on Local Server but crashes horribly when uploaded -



php - Site looks fine on Local Server but crashes horribly when uploaded -

here's site i'm working on http://amaralondon.com/keith/ammoura

if viewed chrome/ff/safari shows expected. when view through localhost using xampp it's fine on ie11 too, when utilize url above , view on ie11 looks more picasso came along , griefed site shreds. have feeling there may something/something missing causing site display badly on ie , wondering if gurus out there might able help?

cheers,

keith

lol it's good, missing

<meta http-equiv="x-ua-compatible" content="ie=edge">

tag... d'oh!

php html cross-browser

Classic ASP export to CSV generates blank 1st row -



Classic ASP export to CSV generates blank 1st row -

i have .asp page generates csv file download using info mysql database. issue is, first row of generated csv file blank. how eliminate blank 1st row output?

<%response.buffer = true response.clear response.contenttype = "text/csv" response.addheader "content-disposition", "attachment;filename=export.csv" struserid=request.querystring("uid") set con = server.createobject("adodb.connection") %> <!--#include file="databaseconnection.asp"--> <%con.open dsntest set rec1=con.execute ("select * orders receivedp = '0000-00-00 00:00:00' , pid = '" & struserid & "' order zipid asc")%> sep=; address;city;state;zip; <%while not rec1.eof strzipid = rec1("zipid") set rec3=con.execute ("select * zip zipcode = '" & strzipid & "'") %> <%=rec1("address")%>;<%=rec3("city")%>;<%=rec3("state")%>;<%=rec3("zipcode")%>; <%rec1.movenext wend rec1.close set rec1 = nil rec3.close set rec3 = nil con.close set con = nothing%>

bit of guess here, seek having vbs in single block of code , utilize vbcrlf add together line breaks need them - ie

<% con.open dsntest set rec1=con.execute ("select * orders receivedp = '0000-00-00 00:00:00' , pid = '" & struserid & "' order zipid asc") response.write "sep=;" & vbcrlf response.write "address;city;state;zip;" & vbcrlf while not rec1.eof strzipid = rec1("zipid") set rec3=con.execute ("select * zip zipcode = '" & strzipid & "'") response.write rec1("address")&";"&rec3("city")&";"&rec3("state")&";"&rec3("zipcode") & vbcrlf rec1.movenext wend 'etc

closing block of asp code , starting new 1 on next line adds line

csv asp-classic export-to-csv

Passing structure to function in C -



Passing structure to function in C -

#include<stdio.h> #include<stdlib.h> struct point { int x; int y; }; void get(struct point p) { printf("enter x , y coordinates of point: "); scanf("%d %d",&p.x,&p.y); } void put(struct point p) { printf("(x,y)=(%d,%d)\n",p.x,p.y); } int main () { struct point pt; get(pt); put(pt); homecoming 0; }

i trying write programme x , y coordinates user , them print them out screen. 1 time come in x , y coordinates , go out print them out screen get: (x,y)=(56,0). new working structures help good. give thanks you.

you may homecoming construction straight function, since little structure.

struct point get() { struct point p; printf("enter x , y coordinates of point: "); scanf("%d %d",&p.x,&p.y); homecoming p; } int main () { put(get()); homecoming 0; }

c structure pass-by-value

for loop - Concatenation of a dynamic integer value in a php function -



for loop - Concatenation of a dynamic integer value in a php function -

i trying print dynamic values , using utilize foreach(). here code trying. original code have integrate , create dynamic loop runs 4 times. have alter print_static_1_container print_static_$i_container.

<?php if(!function_exists('print_static_1_container')) { function print_static_1_container() {

this code trying:

<?php for($i=1;$i<=4;$i++) { $function = create_function('$i', 'echo "print_static_{$i}_container";'); function $function() { global $site; ?> <!-- static 1 container --> <!-- ********************************************* start ************************************************* --> <div class="static-<?php echo $i; ?>-home"> <div class="row"> <div class="gal-head home-section-head"> <?php if(isset($site['theme_options']->static_$i_html_content) && !empty($site['theme_options']->static_$i_html_content)) echo $site['theme_options']->static_$i_html_content; ?> </div> </div> </div> <?php } } ?>

the error

unexpected '.' in line function print_static_.'$i'._container()

should be:

$function_name = "print_static_$i_container"; if(!function_exists($function_name)) { $function_name = function() { // stuff };

you can phone call function this: $function_name();

you can utilize variables within double quotes only. php interprets single-quoted strings appear, is, value stored in variable not replaced in string.

php for-loop

Batch Copy file to another direction -



Batch Copy file to another direction -

this code doesn't work well. should re-create created file directory. code don't re-create , don't see made error

@echo off dir *.txt>>alek.txt %%x in %1 echo %%x>>"%2" re-create "h:\bat\zad\a\alek.txt" "h:\bat\zad\b" :pause

i think need alter 3rd line this:

for /f %%x in %1 echo %%x>>"%2"

if you're trying write contents of file file. work within batch file pass 2 parameters into.

batch-file copy

Can't Access MongoDB instance hosted in Google Cloud VM from RoboMongo -



Can't Access MongoDB instance hosted in Google Cloud VM from RoboMongo -

i have created project , deployed mean stack using "click deploy". when visit <> / 3000 see mean page coming server. can ssh machine , see stuff there. can access mongodb instance in way.

i created separate vm installed node.js , mongodb myself. both working similar way.

my problem - can't access either of machines local robomongo instance neither can access them local shell. had similar issue in aws world , solution create security grouping permit mongodb port (27017). tried , added "firewall rule" under "network" , allowed port incoming traffics --> bellow

mongodb communication outside source ranges: 0.0.0.0/0 allowed protocols or ports: tcp:27017 issue persists , can't access mongodb instance robomongo or local shell.

any thought ?

i suggest check if mongodb listening on port 27017 running next command:

sudo netstat -nap | grep 27017

i suggest seek turn off ip tables on vm , seek access maybe rule blocking access. 1 thing check bindip using db.servercmdlineopts()

mongodb google-app-engine google-cloud-storage robomongo

javascript - On hover, find a matching class from a set of divs and assign a class name to a match (jquery/js) -



javascript - On hover, find a matching class from a set of divs and assign a class name to a match (jquery/js) -

js/jquery newbie here. i'm trying create in interactive map markers absolutely positioned on page , when hovered over, related info pane should appear on top left part of screen. preferably, fade in , fade out on mouse out. i've tried various things nil seems work. here simplified markup should show i'm trying do:

<div class="body"> <div class="links"> <span class="one">1</span> <span class="two">2</span> <span class="three">3</span> <span class="four">4</span> </div> <div class="panel"> <span class="one"> 1</span> <span class="two">2</span> <span class="three">3</span> <span class="four">4</span> </div> </div>

css:

.body .panel span{ display:block; width:100px; height:100px; background:red; margin:10px; text-align:center; display: none; color:white; } .links span{ display: block; } .body .panel span.visible{ display: block; }

some jquery i've been trying understand. got somewhere around here

$(document).ready(function(){ $(".links span").hover(function() { var index = $(this).index(); $(".panel span").each(function() { $(this).eq(index).toggleclass("visible"); }); }); });

just made fiddle

$(".links span").hover(function() { var index = $(".links span").index($(this)); $(".panel span").eq(index).toggleclass("visible"); });

as want display related span, it's not necessary utilize each().

and farther info mentioned you're new js/jquery - it's (in case, not in general) possible utilize this instead of $(this) - var index = $(".links span").index(this); - both homecoming same result. this dom object in context of hover() callback function, $(this) jquery object. illustrate difference , same result, i've added console message both in adjusted fiddle.

as reference nice article "this" - http://remysharp.com/2007/04/12/jquerys-this-demystified

javascript jquery html fadein interactive

excel - Using vba code to control a button (class selectpicker instead of select or formfield) in a html webpage -



excel - Using vba code to control a button (class selectpicker instead of select or formfield) in a html webpage -

i connect automatically fo next web pages: https://ssologin-bp2s.bnpparibas.com/ssologinaction.do need move greenish button (close "authentification" label) "cartesecure id" , cannot figure out how move button. below html code

<div class="row form-group"> <label class="col-xs-12 col-sm-4 col-md-4 col-lg-4 control-label" for="authenthication">authentification :</label> <div class="col-xs-10 col-sm-7 col-md-6 col-lg-6"> <select name="authlevels" id="authlevels" class="selectpicker" data-width="auto" data-style="btn-success"> <option value="1">standard</option> <option value="2">carte securid</option> <option value="3">certificat ipki</option> <option value="4">bnp paribas</option> </select>

i have tried several options on vba,

with ie.document

.getelementbyid("userid").value = user .getelementbyid("password").value = pwd .getelementbyid("authlevels").selectedindex = 2 .getelementbyid("authlevels").value = "2"

but nothing's working believe not work because class selectpicker , not formfield or select. might wrong of course.

if set me in right direction.

many thanks

the select box see in page source hidden , dynamically replaced greenish button

try using both:

.getelementbyid("authlevels").selectedindex = 1 'set hidden list: zero-based! .getelementbyid("authlevel").value = 2 'a hidden field associated greenish button

html excel vba

Python 2.7 + Django 1.7 + PostgreSQL 9.3: I'm getting a UnicodeEncodeError when trying to save some text to my database. What gives? -



Python 2.7 + Django 1.7 + PostgreSQL 9.3: I'm getting a UnicodeEncodeError when trying to save some text to my database. What gives? -

in models.py file have defined model follows:

class mything(models.model): thing_id = models.charfield(max_length=20, unique=true, null=false) code_snippet = models.textfield(null=true)

i trying populate table bunch of info pulling downwards google api. 1 piece snippet of javascript. 1 of items beingness returned api has snippet of js throwing error.

the error getting is:

unicodeencodeerror: 'ascii' codec can't encode characters in position 213-214: ordinal not in range(128)

the offending bit of text appears in section:

type="text/javascript" charset="utf-\xad\u20108"></script>

i'm \xad, must sort of unicode escape sequence.

i checked postgresql encoding, , using utf-8.

i place line @ top of models.py, didn't create difference:

from __future__ import unicode_literals

what going on here? why can't unicode-aware database save string? also, when did start using 'ascii' codec?

---- edit: total stack trace below -----

error/mainprocess] task apps.r2d_service.tasks.sync_jsnippets_task[e74712bf-2e04-4bed-b08c-f24f9ebb3049] raised unexpected: unicodeencodeerror('ascii', u'<script type="text/javascript">\n window._sm_plcmnt = "finyo_5225_5119";\n var _sm_viewed = false;\n</script>\n<script src="https://cdn.company412media.com/ng/js/augur.js" type="text/javascript" charset="utf-\xad\u20108"></script>\n<script src=\'https://cdn.company412media.com/ng/pub.js\'></script>\n<script type="text/javascript">\n$$(\'#bib_actions_table tr:nth-child(1) a\').each(function (tab) {\n tab.observe(\'click\', function (e, el) {\n if (!_sm_viewed) {\n sm_augur.init();\n _sm_viewed = true;\n }\n });\n});\n\n</script>\n', 213, 215, 'ordinal not in range(128)') traceback (most recent phone call last): file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/celery/app/trace.py", line 240, in trace_task r = retval = fun(*args, **kwargs) file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/celery/app/trace.py", line 437, in __protected_call__ homecoming self.run(*args, **kwargs) file "/home/vagrant/myapp/apps/r2d_service/tasks.py", line 25, in sync_jsnippets_task sync_jsnippets() file "/home/vagrant/myapp/apps/r2d_service/sync.py", line 44, in sync_jsnippets myapp_creative.sync(r2d_creative) file "/home/vagrant/myapp/apps/r2d_service/models.py", line 244, in sync self.save() file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/base.py", line 590, in save force_update=force_update, update_fields=update_fields) file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/base.py", line 618, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/base.py", line 680, in _save_table forced_update) file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/base.py", line 724, in _do_update homecoming filtered._update(values) > 0 file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/query.py", line 600, in _update homecoming query.get_compiler(self.db).execute_sql(cursor) file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 1004, in execute_sql cursor = super(sqlupdatecompiler, self).execute_sql(result_type) file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py", line 786, in execute_sql cursor.execute(sql, params) file "/home/vagrant/.virtualenvs/myapp/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 90, in execute logger.debug('(%.3f) %s; args=%s' % (duration, sql, params), unicodeencodeerror: 'ascii' codec can't encode characters in position 213-214: ordinal not in range(128)

you need convert strings using base64 can save database.

import base64 base64.b64encode("stings")

python django postgresql unicode utf-8

How to add Hyperlink on php/html table that displays information from mysql database -



How to add Hyperlink on php/html table that displays information from mysql database -

i have next mysql table:

+----------+---------+------+--------------+ | name | cost | life | whenacquired | +----------+---------+------+--------------+ | aardvark | 2500.00 | 5 | 2012-01-01 | | bobcat | 2000.00 | 4 | 2012-03-01 | | cougar | 3000.00 | 6 | 2013-01-01 | | deer | 5000.00 | 4 | 2010-01-01 | | eagle | 2000.00 | 3 | 2009-01-01 | +----------+---------+------+--------------+

where have written php script read mysql db:

<?php $con=mysqli_connect("example.com","peter","abc123","my_db"); // check connection if (mysqli_connect_errno()) { echo "failed connect mysql: " . mysqli_connect_error(); } $result = mysqli_query($con,"select name animals"); echo "<table border='1'> <tr> <th>name</th> </tr>"; while($row = mysqli_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['name'] . "</td>"; echo "</tr>"; } echo "</table>"; mysqli_close($con); ?>

which produces:

+----------+ | name | +----------+ | aardvark | | bobcat | | cougar | | deer | | eagle | +----------+

to display name, want name hyperlink when clicked brings corresponding data, example: when aardvark clicked, next info pop up

+----------+---------+------+--------------+ | name | cost | life | whenacquired | +----------+---------+------+--------------+ | aardvark | 2500.00 | 5 | 2012-01-01 | +----------+---------+------+--------------+

you'll have utilize css/javascript this.

there 3 ways: more easy way print data, not displaying yet until clicks link. hyperlink part. in illustration used 'span' element styled hyperlink.

//place within head tag <style> .hyperlink-lookalike { text-decoration:underline; color:blue; cursor:pointer; } </style> <script> //javascript function toggle animal info function show_extra_info(id) { var tr = document.getelementbyid('extra_info_'+id); if(tr.style.display=='none') { tr.style.display='table-row'; } else{ tr.style.display='none'; } } </script> //inside loop echo '<tr>'; echo '<td colspan='2'><span class="hyperlink-lookalike" onclick="show_extra_info(' . $row['id'] . ')">' . $row['name'] . '</span></td>'; echo '</tr>'; echo '<tr id="extra_info_' . $row['id'] . '" style="display:none;">'; echo '<td>' . $row['cost'] . '</td>'; echo '<td>' . $row['life'] . '</td>'; echo '</tr>';

the sec way is, , 1 uses hyperlink, go detail view:

echo '<td><a href="http://www.example.com/animaldetailedinfo.php?id=' . $row['id'] . '">' . $row['name'] . '</a></td>';

the 3rd (more advanced) way ajax request info , display in 'div' tag. might want utilize javascript library jquery. 1 time again if want show in popup hyperlink not necessary. span element onclick event fires javascript function request server more info easier.

$.get("http://www.example.com/animaldetailedinfo.php", function( info ) { $( "#popupcontainer" ).html( info ); });

php mysql

Xamarin.Forms Switch Control is not Visible on Android prior to selecting an Entry Control -



Xamarin.Forms Switch Control is not Visible on Android prior to selecting an Entry Control -

i have registration form looks this

<stacklayout> <stacklayout horizontaloptions="fillandexpand" padding="{x:static local:styles.labelbeforeentrypadding}"> <label text="{binding labelpasswort2}" horizontaloptions="{x:static local:styles.labelhorizontaloptions}" textcolor="{x:static local:styles.registrationpagetextcolor}" /> </stacklayout> <custom:strypeentry text="{binding passwort2}" ispassword="true" isenabled="{binding controlsenabled}" horizontaloptions="fillandexpand" /> </stacklayout> <!--newsletter--> <stacklayout orientation="horizontal" horizontaloptions="startandexpand"> <switch istoggled="{binding newsletter}" isenabled="{binding controlsenabled}" verticaloptions="startandexpand" horizontaloptions="startandexpand" /> <label text="{binding labelnewsletter}" verticaloptions="centerandexpand" horizontaloptions="start" textcolor="{x:static local:styles.registrationpagetextcolor}" /> </stacklayout> <!--datenschutz--> <stacklayout orientation="horizontal" horizontaloptions="startandexpand"> <custom:strypeswitch istoggled="{binding privacy}" isenabled="{binding controlsenabled}" verticaloptions="startandexpand" horizontaloptions="startandexpand" /> <label text="{binding labelprivacy}" verticaloptions="centerandexpand" horizontaloptions="start" widthrequest="300" textcolor="{x:static local:styles.registrationpagetextcolor}" /> </stacklayout>

the problem switches not visible when displaying form, become visible when entry focused.

the strypeentry customized entry border corder , prop capitalize, nil fancy , switch made custom renderer prepare issue of not displaying.

i tried prepare buttontext alignment did not help (xamarin.forms: wrong button text alignment after click (android))

i tried this

public override void childdrawablestatechanged(view child) { base.childdrawablestatechanged(child); control.text = control.text; control.checked = control.checked; }

but still no fix

(i'm testing on gt-i9505 android 4.4.2. version of xamarin.forms assemblies 1.2.2.0)

please help me, give thanks you

seems have reply own question.

i fixed issue adding height- , widthrequest switch in xaml

hope helps else. , maybe if find improve solution, please allow me know.

greetings~

android xamarin.forms

javascript - Match the character * and not the \* in regex? -



javascript - Match the character * and not the \* in regex? -

i have next string item * \* , *. match * characters , skip \* one.

var input = "item * \\* , *"; var output = (some regex magic happens here) alert(output); // item foo \* , foo

any ideas?

here's think you're trying acheive:

class="snippet-code-js lang-js prettyprint-override">var input = "item * \\* , *"; var repl = "foo"; var output = input.replace(/(\\\*)|\*/g, function(_, a) { homecoming || repl; }); alert(output); // item foo \* , foo

basically, when provide function replace method, pass in match , matched groups arguments function , utilize homecoming value replacement string. in case, since argument a has value when matches "\*", leave match unmodified. otherwise, replace "foo".

javascript regex

java - In Swing, is there a way to extract a predefined mouse cursor Image from the toolkit? -



java - In Swing, is there a way to extract a predefined mouse cursor Image from the toolkit? -

i'd create custom help cursor "badging" built-in default mouse cursor question mark when user hovering on object can clicked context-sensitive help. i'd work nicely across platforms/look-and-feels (to consistent white windows mouse , black mac mouse, instance.) there way cursor image current toolkit generate combined image set cursor?

this question points out info can't gotten cursor object. there's comment there suggested fishing around in jre, i've tried bit: there , in google images, didn't find straightforwardly accessible graphics files plunder

an alternative add together mousemoved listener , draw manually little right of cursor (on parent, suppose, avoid clipping @ borders?) bit concerned overhead, , in initial explorations, looking complicated. i'd take other suggestions finding or making nice help cursor well. (the hand best built-in, doesn't "help" question-mark.)

i'm not sure best solution in case, because built-in mouse cursor should best. anyway can utilize mouse listeners , draw on glasspane according mouse position. here's glasspane drawing example.

java swing mouse-cursor

android - Retrofit POST request w/ Digest HTTP Authentication: “Cannot retry streamed HTTP body” -



android - Retrofit POST request w/ Digest HTTP Authentication: “Cannot retry streamed HTTP body” -

i'm trying implement digest authentication using retrofit. first solution sets implementation of okhttp's authenticator on okhttpclient:

class myauthenticator implements authenticator { private final digestscheme digestscheme = new digestscheme(); private final credentials credentials = new usernamepasswordcredentials("user", "pass"); @override public request authenticate(proxy proxy, response response) throws ioexception { seek { digestscheme.processchallenge(new basicheader("www-authenticate", response.header("www-authenticate"))); httprequest request = new basichttprequest(response.request().method(), response.request().uri().tostring()); string authheader = digestscheme.authenticate(credentials, request).getvalue(); homecoming response.request().newbuilder() .addheader("authorization", authheader) .build(); } grab (exception e) { throw new assertionerror(e); } } @override public request authenticateproxy(proxy proxy, response response) throws ioexception { homecoming null; } }

this works requests through retrofit. however, described in this stackoverflow question, post requests result in "cannot retry streamed http body" exception:

caused by: java.net.httpretryexception: cannot retry streamed http body @ com.squareup.okhttp.internal.http.httpurlconnectionimpl.getresponse(httpurlconnectionimpl.java:324) @ com.squareup.okhttp.internal.http.httpurlconnectionimpl.getresponsecode(httpurlconnectionimpl.java:508) @ com.squareup.okhttp.internal.http.httpsurlconnectionimpl.getresponsecode(httpsurlconnectionimpl.java:136) @ retrofit.client.urlconnectionclient.readresponse(urlconnectionclient.java:94) @ retrofit.client.urlconnectionclient.execute(urlconnectionclient.java:49) @ retrofit.restadapter$resthandler.invokerequest(restadapter.java:357) @ retrofit.restadapter$resthandler.invoke(restadapter.java:282) @ $proxy3.login(native method) @ com.audax.paths.job.loginjob.onruninbackground(loginjob.java:41) @ com.audax.library.job.axjob.onrun(axjob.java:25) @ com.path.android.jobqueue.basejob.saferun(basejob.java:108) @ com.path.android.jobqueue.jobholder.saferun(jobholder.java:60) @ com.path.android.jobqueue.executor.jobconsumerexecutor$jobconsumer.run(jobconsumerexecutor.java:172) @ java.lang.thread.run(thread.java:841)

jesse wilson explains can't resend our request after authenticating, because post body has been thrown out. need returned www-authenticate header because of digest authentication, can't utilize requestinterceptor add together header. maybe it's possible perform separate http request in requestinterceptor, , utilize www-authenticate header in response, seems hacky.

is there way around this?

as workaround, ended swapping out okhttp apache's httpclient, has built-in digest authentication. provide implementation of retrofit.client.client delegates requests apache's httpclient:

import retrofit.client.client; import org.apache.http.impl.client.closeablehttpclient; import org.apache.http.auth.credentials; import org.apache.http.auth.authscope; import org.apache.http.client.credentialsprovider; import org.apache.http.impl.client.basiccredentialsprovider; import org.apache.http.impl.client.httpclientbuilder; import retrofit.client.request; import retrofit.client.response; public class myclient implements client { private final closeablehttpclient delegate; public myclient(string user, string pass, string hostname, string scope) { credentials credentials = new usernamepasswordcredentials(user, pass); authscope authscope = new authscope(hostname, 443, scope); credentialsprovider credentialsprovider = new basiccredentialsprovider(); credentialsprovider.setcredentials(authscope, credentials); delegate = httpclientbuilder.create() .setdefaultcredentialsprovider(credentialsprovider) .build(); } @override public response execute(request request) { // // we're getting retrofit request, need execute apache // httpurirequest instead. utilize info in retrofit request create // apache httpurirequest. // string method = req.getmethod(); bytearrayoutputstream bos = new bytearrayoutputstream(); if (request.getbody() != null) { request.getbody().writeto(bos); } string body = new string(bos.tobytearray()); httpurirequest wrappedrequest; switch (method) { case "get": wrappedrequest = new httpget(request.geturl()); break; case "post": wrappedrequest = new httppost(request.geturl()); wrappedrequest.addheader("content-type", "application/xml"); ((httppost) wrappedrequest).setentity(new stringentity(body)); break; case "put": wrappedrequest = new httpput(request.geturl()); wrappedrequest.addheader("content-type", "application/xml"); ((httpput) wrappedrequest).setentity(new stringentity(body)); break; case "delete": wrappedrequest = new httpdelete(request.geturl()); break; default: throw new assertionerror("http operation not supported."); } // // execute request `delegate.execute(urirequest)`. // // ... // }

then set new client implementation on restadapter.builder:

restadapter restadapter = new restadapter.builder() .setclient(new myclient("jason", "pass", "something.com", "some scope")) .setendpoint("https://something.com/api") .build();

android authentication retrofit okhttp

java - Android to Php server communicaton using HttpURLConnection -



java - Android to Php server communicaton using HttpURLConnection -

my project upload image, sound files parameter(like description , date).

though google announced utilize httpurlconnection instead of httpclient. using httpurlconnection.

i have code upload image , sound in server folder.

but description send not received in server.

like question many in stackover flow. did not exact solution.

my android code is:

fileinputstream fileinputstream = new fileinputstream(sourcefile_image); url url = new url(uploadserveruri); conn = (httpurlconnection) url.openconnection(); conn.setdoinput(true); // allow inputs conn.setdooutput(true); // allow outputs conn.setusecaches(false); // don't utilize cached re-create conn.setrequestmethod("post"); conn.setrequestproperty("connection", "keep-alive"); conn.setrequestproperty("enctype", "multipart/form-data"); conn.setrequestproperty("content-type","multipart/form-data;boundary=" + boundary); conn.setrequestproperty("uploaded_file", filename); dos = new dataoutputstream(conn.getoutputstream()); dos.writebytes(twohyphens + boundary + lineend); //adding parameter string description = ""+"desceiption image"; // send parameter #name dos.writebytes("content-disposition: form-data; name=\"description\"" + lineend); dos.writebytes("content-type: text/plain; charset=utf-8" + lineend); dos.writebytes("content-length: " + description.length() + lineend); dos.writebytes(lineend); dos.writebytes(description + lineend); dos.writebytes(twohyphens + boundary + lineend); // send #image dos.writebytes("content-disposition: form-data; name=\"uploaded_file\";filename=\""+ filename + "\"" + lineend); dos.writebytes(lineend); // create buffer of maximum size bytesavailable = fileinputstream.available(); buffersize = math.min(bytesavailable, maxbuffersize); buffer = new byte[buffersize]; // read file , write form... bytesread = fileinputstream.read(buffer, 0, buffersize); while (bytesread > 0) { dos.write(buffer, 0, buffersize); bytesavailable = fileinputstream.available(); buffersize = math.min(bytesavailable, maxbuffersize); bytesread = fileinputstream.read(buffer, 0, buffersize); } // send multipart form info necesssary after file data... dos.writebytes(lineend); dos.writebytes(twohyphens + boundary + twohyphens + lineend);

and php code:

$description= $_post['description']; $file_path = $file_path . basename( $_files['uploaded_file']['name']); if(move_uploaded_file($_files['uploaded_file']['tmp_name'], $file_path)) { echo "success"; } else{ echo "fail"; }

image , sound updating successfully.

but parameter not received or dont know how receive parameter in php.

is android , php code send , receive parameter correct?

is other solution.

i trying lot not works , not getting thought too.

check link

android code:

string description = ""+"desceiption image"; dos.writebytes("content-disposition: form-data; name=\"description\"" + lineend); //dos.writebytes("content-type: text/plain; charset=utf-8" + lineend); //dos.writebytes("content-length: " + description.length() + lineend); dos.writebytes(lineend); dos.writebytes(description); // mobile_no string variable dos.writebytes(lineend);

php code:

$description =$_post['description'];

java php android httpurlconnection multipartform-data

Generic result to key value list or dictionary in vb.net -



Generic result to key value list or dictionary in vb.net -

i need homecoming key value paired list of state (region) names abbreviated value within dnn install. in function below obtain desired results inferred variable named regionlist, cannot cast these results key value paired list or dictionary , homecoming result. help appreciated.

public function getregionpercountry(countrycode string) list(of keyvaluepair(of string, string)) dim lc new dotnetnuke.common.lists.listcontroller() dim countryid integer dim regionlist2 list(of keyvaluepair(of string, string)) = new list(of keyvaluepair(of string, string)) if not countrycode nil dim entrycollection system.collections.generic.list(of dotnetnuke.common.lists.listentryinfo) entrycollection = lc.getlistentryinfoitems("country") countryid = entrycollection.where(function(x) x.value = countrycode).select(function(x) x.entryid).firstordefault() entrycollection = lc.getlistentryinfoitems("region") dim regionlist = entrycollection.where(function(x) x.parentid = countryid).select(function(x) new {.key = x.text.tostring(), .value = x.value.tostring()}).tolist() regionlist2 = regionlist end if homecoming regionlist2 end function

vb.net dictionary collections key-value

Builds on TFS take ages when restoring Nuget packages -



Builds on TFS take ages when restoring Nuget packages -

when build solution on visualstudio.com takes absolutely ages. 15 minutes build , test. considering 60 minutes of free build time that's far long.

nearly build time restoring nuget packages.

my build configured not clean downwards source every time in theory packages shouldn't need downloading every time because it's hosted maybe setting irrelevant.

is else seeing issue? what's recommended way handle nuget packages when using visualstudio.com? i'm tempted add together packages source command don't have downloaded.

every time build in elastic build services new server. server used build , destroyed. need nuget packages every time.

i recommend create azure vm , run custom build in there. not take time 60 minutes , 'static' server cache packages...

tfs nuget tfsbuild nuget-package

python - Writing headers in CSV file -



python - Writing headers in CSV file -

i have programme run on cron job , write output csv file.

i write correctly create programme write headers on first row when file created. there way of programme checking if there rows in csv file and, if not, writing headers.

just utilize flag:

headers_written = false

then when writing rows:

if not headers_written: writer.writerow(headers) headers_written = true writer.writerow(somerow)

you'd postpone creating author until sure have stuff write:

writer = none # ... if not writer: author = csv.writer(open(filename, 'wb')) writer.writerow(headers) writer.writerow(somerow)

python csv

Android Camera Landscape Image -



Android Camera Landscape Image -

i'm developing app has surfaceview camera. want take landscape images in both landscape , portrait modes. preview shown okay since used camera.setdisplayorientation(90); in code.

however when take image, displayed rotated. can rotate 1 time again become portrait done. know how take landscape image camera?

this how configured photographic camera parameters

private void configure() { camera.parameters params = camera.getparameters(); // configure image format. rgb_565 mutual format. list<integer> formats = params.getsupportedpictureformats(); if (formats.contains(pixelformat.rgb_565)) params.setpictureformat(pixelformat.rgb_565); else params.setpictureformat(pixelformat.jpeg); // take biggest image size supported hardware /*list<camera.size> sizes = params.getsupportedpicturesizes(); camera.size size = sizes.get(sizes.size()-1); params.setpicturesize(size.width, size.height);*/ params.setpicturesize(constants.image_width, constants.image_height); list<string> flashmodes = params.getsupportedflashmodes(); if (flashmodes.size() > 0) params.setflashmode(camera.parameters.flash_mode_auto); // action mode take pictures of fast moving objects list<string> scenemodes = params.getsupportedscenemodes(); if (scenemodes.contains(camera.parameters.scene_mode_action)) params.setscenemode(camera.parameters.scene_mode_action); else params.setscenemode(camera.parameters.scene_mode_auto); // if take focus_mode_auto remember phone call autofocus() on // photographic camera object before taking image params.setfocusmode(camera.parameters.focus_mode_auto); camera.setparameters(params); }

and take image

private void takepicture() { configure(); camera.autofocus(new camera.autofocuscallback() { @override public void onautofocus(boolean success, photographic camera camera) { camera.takepicture(shuttercallback, picturecallback_raw, picturecallback_jpeg); } }); }

this save image taken camera

picturecallback picturecallback_jpeg = new picturecallback() { public void onpicturetaken(byte[] data, photographic camera camera) { file storagedirectory = camerahelper.getstoragedirectory(); string filename = camerahelper.getstoragefilename(); imagepath = storagedirectory.getpath()+file.separator+filename; file output = new file(storagedirectory, filename); seek { fileoutputstream fos = new fileoutputstream(output); fos.write(data); fos.close(); imagecapturedstate=true; } grab (filenotfoundexception e) { e.printstacktrace(); } grab (ioexception e) { e.printstacktrace(); } } };

this photographic camera preview when take picture

this how displayed 1 time saved (the image in preview rotated 90 degrees.)

so see, can rotate image, become portrait 1 time have done it. how can save landscape image without ratating? give thanks you!

android camera

Twitter integration in iOS without dialog -



Twitter integration in iOS without dialog -

i integrating twitter in ios app , and found reply stack overflow , other resources. have question if ios device user not add together twitter account, how can implement case. have seen in android app can post text, images , links twitter login page help of web view -

how can post on twitter without showing dialogue in ios?

ios 5 twitter framework: tweeting without user input , confirmation (modal view controller)

after searching related post know both dialog , using request. how can handle above case.

an advance thanks

ios twitter

linux - Having problems running python script even when putty is closed -



linux - Having problems running python script even when putty is closed -

so basically, have bot i'm running, , maintain running when exit putty.

i've tried using nohup python bot.py & still ends python bot when close putty program. i've tried using run.sh file /usr/bin/nohup bot.py & within it. won't work :( there else i'm missing?

i have made sure run.sh executable other forums have suggested, , still can't open run

i'm kinda new linux terminal.

if guys help me out awsome :)

you need detach terminal when exit, still running. can utilize screen or tmux or other multiplexer.

here how screen:

screen -s mybot -m -d /usr/bin/python /path/to/bot.py -s give session name (this useful if want attach later. screen -d -r mybot) -m create new session -d detach (launch program, detach terminal returning prompt)

linux bots

javascript - Cordova(phonegap):- how to get mobile CallLog? -



javascript - Cordova(phonegap):- how to get mobile CallLog? -

i developing mobile application using cordova like, send mobile phone call log history.

please help me. thanks

for can utilize

android (help ios welcome) cordova plugin access phone call history on device. call history

javascript cordova cordova-plugins

ruby on rails - How to detect if number of associated objects change? -



ruby on rails - How to detect if number of associated objects change? -

class post < activerecord::base has_many :comments after_save :do_something, if: -> (post) { [ post.comments.count.changed? ] } end class comment < activerecord::base belongs_to :post end

how execute do_something if number of comments alter ?

i want execute do_something if observe more 3 changes illustration : 2 comments added, 2 deleted.

ruby-on-rails activerecord

ruby on rails - ActiveRecord find with include against table with records that might not be there -



ruby on rails - ActiveRecord find with include against table with records that might not be there -

here's situation. have set of lists of words. words can appear in more 1 list. each word/list combination, might have illustration sentence.

words

class word < activerecord::base has_and_belongs_to_many :lists has_many :sample_sentences end

lists

class list < activerecord::base has_and_belongs_to_many :words has_many :sample_sentences end

sample sentences

class samplesentence < activerecord::base belongs_to :word belongs_to :list end

... , back upwards habtm, have bring together table.

everything works fine except this:

using eager loading, grab words in particular list and sample sentences word particular list.

i have tried many variations scopes, wheres, etc.

most variations (testing in irb)

w=word.includes(:sample_sentences).where(words: {id: 48}).where(sample_sentences: {list_id: 6})[0]

this works great if word has illustration sentence in associated list. does not work if word has no illustration sentence in list. returns no records.

the documentation active record query interface , countless questions on stack overflow tell me resulting sql uses left outer bring together data. believe issue result of additional on sample_sentences table seems eliminate possibility of getting word query no sample sentences.

this indeed borne out.. if drop additional on sample_sentences table, records regardless of whether or not word has associated sample sentence. problem is, sample sentences in not interested.

development database engine sql lite. production mysql.

so.. i'm not sure best thing be. thoughts?

if reading request correctly using eager loading, grab words in particular list , sample sentences word particular list.. appears want words regardless of whether have comments. seek this: word.includes(:sample_sentences, :lists).where(lists: {id: #list id }). include sample sentences if exist , can test empty?.

ruby-on-rails ruby activerecord eager-loading

python - django tenant schema example gives ImproperlyConfigured error -



python - django tenant schema example gives ImproperlyConfigured error -

i installed django tenent schema app using pip. downloaded tenant illustration app form "https://github.com/bernardopires/django-tenant-schemas/tree/master/examples/tenant_tutorial". when seek run next error django.core.exceptions.improperlyconfigured: application labels aren't unique, duplicates: auth

any thought why may happening?

python version 2.7 django version 1.7.1

django-tenant-schemas has not been officially supported django version 1.7 (see https://github.com/bernardopires/django-tenant-schemas/pull/178).

i know not reply question "any thought why may happening", @ to the lowest degree explains why things don't work way should.

edit: of django-tenant-schemas v1.5.1 (january 5th, 2015) django 1.7 supported.

python django

python - Generating palindromic anagrams of a string of length upto 10^5 -



python - Generating palindromic anagrams of a string of length upto 10^5 -

i have tried next takes much time when seek string of 17 characters.

string = input() def permute(xs, low=0): if low + 1 >= len(xs): yield xs else: p in permute(xs, low + 1): yield p in range(low + 1, len(xs)): xs[low], xs[i] = xs[i], xs[low] p in permute(xs, low + 1): yield p xs[low], xs[i] = xs[i], xs[low] p in permute(list(string)): mstr = "".join(p) if mstr == mstr[::-1]: print("yes") break

this solution 'game of thrones' challenge on hackerrank. how can cut down execution time , create run real fast strings of length 10^5?

thanks.

trying combination cannot fast enough, of course. there much simpler way it. based on next observation: let's assume count[c] number of occurrences of c in given string. reply yes if , if number of characters odd value of count less or equal 1. observation gives simple o(n) solution.

here pseudo code:

count[c] = 0 each character c appears in string = 1...length(s): count[s[i]] += 1 with_odd_count = 0 each c: if count[c] % 2 == 1: with_odd_count += 1 if with_odd_count <= 1: print("yes") else: print("no")

python chr ord

python - 404 Exception when deploying a Flask application via mod_wsgi -



python - 404 Exception when deploying a Flask application via mod_wsgi -

my question similar 1 asked here. have flask application runs fine on local machine. want upload application online , followed steps under mod_wsgi given here. reason, url's seek access giving me 404 on server. code snippets follows.

httpd.conf file

<virtualhost *:80> servername abc.com serveralias www.abc.com serveradmin myusername@gmail.com errorlog /path/to/error/logs/error.log customlog /path/to/error/logs/access.log combined wsgiscriptalias / /path/to/wsgi/file/app.wsgi <directory /path/tp/wsgi/folder> order deny,allow allow </directory> </virtualhost>

app.wsgi

activate_this = '/path/to/activate/file/activate_this.py' execfile(activate_this, dict(__file__=activate_this)) # set path import sys sys.path.insert(0, '/path/to/home/dir') app import app application if __name__ == "__main__": application.run()

init.py under app

# import flask , template operators flask import flask, render_template flask.ext.mongoengine import mongoengine # define wsgi application object app = flask(__name__) app.config["mongodb_settings"] = {'db': "dbname"} app.config["secret_key"] = "secret" db = mongoengine(app) # sample http error handling @app.errorhandler(404) def not_found(error): homecoming "todo: 404 page", 404 app.data.controllers import mod_data mod_data app.list.controllers import mod_list mod_list # register blueprint(s) app.register_blueprint(mod_data) app.register_blueprint(mod_list)

my directory construction below:

. ├── app │   ├── controllers.py │   ├── info │   ├── __init__.py │   ├── __init__.pyc │   ├── list │   ├── static │   └── templates ├── application.py ├── app.wsgi ├── config.py ├── env │   ├── bin │   ├── include │   └── lib ├── input.csv ├── new-input.csv └── run.py

python mod-wsgi flask

python - multithreading running slower than single thread? -



python - multithreading running slower than single thread? -

i'm trying profile basic function in python see comparative advantage of multithreading evaluating results. seems threaded version performs increasingly worse size of info across function applied increases. there overhead in starting threads i'm not taking business relationship here? can explain how accomplish multithreaded optimization / i'm doing wrong?

from multiprocessing import pool def f(x): homecoming x*x pool = pool(processes=4) import timeit print timeit.timeit('map(f, range(20000000))', setup = "from __main__ import f", number = 1) print timeit.timeit('pool.map(f, range(20000000))', setup = "from __main__ import f, pool", number = 1)

results:

5.90005707741 11.8840620518 [finished in 18.9s]

if relevant, ran in sublime text 3.

the "unit of work" in each job way small. concern when "map" jobs this--the overhead of mapping process dominates. of course of study mapping job separate process more time consuming mapping in same process, no surprise multiprocess solution slower.

try function lot more computation , see benefits of multiprocessing.

python multithreading

How to capture the return value of java from ant build file -



How to capture the return value of java from ant build file -

i calling java method ant build file. want capture output of method i.e. homecoming value ant variable/property.

the ant java task has several attributes create property :

resultproperty (= rc) : name of property in homecoming code of command should stored. of involvement if failonerror=false , if fork=true. outputproperty (= stdout) : name of property in output of command should stored. unless error stream redirected separate file or stream, property include error output. errorproperty (= stderr) : name of property in standard error of command should stored.

core ant has properties no variables. property 1 time set immutable design. there ways overcome restrictions, f.e. several ant addons or ant script task access ant api. rule of thumb => overwriting properties should used special cases.

ant

selenium webdriver - JAVA: How can we print the parameter value in console? -



selenium webdriver - JAVA: How can we print the parameter value in console? -

class1:has reusable function this-

class="lang-java prettyprint-override">public class class1 { webdriverwait wdw = new webdriverwait(driver, 10); public webelement getelement(webelement element) { wdw.until(expectedconditions.elementtobeclickable(element)); } }

class2:

public class class2 { public static void main(string[] args) { ge.getelement(login_button).click(); } }

now how can "login_button" print in console (with more message)if element not nowadays on page or timed out etc

have tried: class1:

public class getelement { webdriverwait wdw = new webdriverwait(driver, 10); public webelement getelement(webelement element) { seek { homecoming wdw.until(expectedconditions.elementtobeclickable(element)); } grab (exception e) { system.err.println(element); } homecoming null; } }

but printing element gives in console:

proxy element for: org.openqa.selenium.support.pagefactory.defaultelementlocator@57250572 instead of

login_button

you have webelement & want print it's name, can utilize gettext() method of webelement interface. @ webelement - java.lang.string gettext().

public class getelement { webdriverwait wdw = new webdriverwait(driver, 10); public webelement getelement(webelement element) { seek { homecoming wdw.until(expectedconditions.elementtobeclickable(element)); } grab (exception e) { system.err.println(element.gettext()); } homecoming null; } }

java selenium-webdriver

python - django 'Commande' object has no attribute '__name_ -



python - django 'Commande' object has no attribute '__name_ -

hi stackoverflow people,

in project seek code view manage external api used fetch datas, nowadays them , store them in database.

when seek access view, encounter next error

traceback:

environment: request method: request url: http://127.0.0.1:8000/commande/recherche django version: 1.7.1 python version: 3.4.2 installed applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'commands') installed middleware: ('django.contrib.sessions.middleware.sessionmiddleware', 'django.middleware.common.commonmiddleware', 'django.middleware.csrf.csrfviewmiddleware', 'django.contrib.auth.middleware.authenticationmiddleware', 'django.contrib.auth.middleware.sessionauthenticationmiddleware', 'django.contrib.messages.middleware.messagemiddleware', 'django.middleware.clickjacking.xframeoptionsmiddleware') traceback: file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response 87. response = middleware_method(request) file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/middleware/common.py" in process_request 72. if (not urlresolvers.is_valid_path(request.path_info, urlconf) , file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in is_valid_path 619. resolve(path, urlconf) file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve 494. homecoming get_resolver(urlconf).resolve(path) file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve 345. sub_match = pattern.resolve(new_path) file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve 345. sub_match = pattern.resolve(new_path) file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in resolve 224. homecoming resolvermatch(self.callback, args, kwargs, self.name) file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in callback 231. self._callback = get_callable(self._callback_str) file "/home/user/.virtualenvs/commands-project/lib/python3.4/functools.py" in wrapper 434. result = user_function(*args, **kwds) file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/core/urlresolvers.py" in get_callable 97. mod = import_module(mod_name) file "/home/user/.virtualenvs/commands-project/lib/python3.4/importlib/__init__.py" in import_module 109. homecoming _bootstrap._gcd_import(name[level:], package, level) file "/home/user/workspace/python/commands-project/project/commands/views.py" in <module> 6. .form import commandesform, commandeform file "/home/user/workspace/python/commands-project/project/commands/form.py" in <module> 11. class commandeform(forms.modelform): file "/home/user/.virtualenvs/commands-project/lib/python3.4/site-packages/django/forms/models.py" in __new__ 293. opts.model.__name__) exception type: attributeerror @ /commande/recherche exception value: 'commande' object has no attribute '__name__'

my models.py :

from django.db import models class client(models.model): client = models.integerfield(null=true) class commandes(models.model): date_debut = models.datefield() date_fin = models.datefield() id_groups = models.charfield(max_length=100) id_client = models.foreignkey(client) class commande(models.model): id_flux = models.charfield(max_length=100, null=true, blank=true) id_commande = models.charfield(max_length=100, null=true, blank=true) id_client = models.foreignkey(client)

my views.py :

from django.shortcuts import render http.client import httpconnection urllib.parse import urlparse, urlunparse .form import commandesform, commandeform import requests def resultat(request): homecoming render(request, 'commands/resultat.html') def recherche(request): if request.method == 'post': if 'commandes' in request.post: pass if 'commande' in request.post: pass else: formcommandes = commandesform() formcommande = commandeform() homecoming render(request, 'commands/recherche.html', {'formcommandes': formcommandes })

and form.py:

from django import forms .models import commande, commandes class commandesform(forms.modelform): class meta: model = commandes() fields = ('date_debut', 'date_fin', 'id_groups') class commandeform(forms.modelform): class meta: model = commande() fields = ('date_debut', 'date_fin', 'id_groups', 'id_client', 'id_flux', 'id_commande')

this next exception need manage : 'commande' object has no attribute 'name'

i know 'name' attribute in class not instance. fact can't figure out is, why exception raise 'commande' object , not 'commands' object

python django