Friday, 15 January 2010

c - Creating a struct of callbacks in LuaJIT FFI -



c - Creating a struct of callbacks in LuaJIT FFI -

so first load in dll need

local ffi = require("ffi") local thedll = ffi.load("thisdll")

in ffi cdef have struct

ffi.cdef [[ typedef struct { /* * begin_proj callback */ bool (__cdecl *begin_proj)(char *proj); /* * save_proj_state */ bool (__cdecl *save_proj_state)(unsigned char **buffer, int *len); } structcallbacks;

i have function in cdef

__declspec(dllexport) int __cdecl start_session(structcallbacks *cb);

now phone call function

print(thedll.start_session(mycallbacks))

the question how can pass structs function needs (how create mycallbacks struct of callbacks lua functions)?

just create struct , assign fields lua functions, other value.

local callbacks = ffi.new("structcallbacks") callbacks.begin_proj = function(proj) homecoming false end callbacks.save_proj_state = function(buffer, len) homecoming true end

see ffi callback docs more in-depth info on callbacks.

c dll lua ffi luajit

html - Placeholder in Contactform 7 - Wordpress -



html - Placeholder in Contactform 7 - Wordpress -

i making website client of me im running problem. i've made contact form in wordpress using contact form 7. plugin easy utilize when wanted utilize placeholder property of plugin did not show placeholder when loaded page.

this how set placeholder in contactform 7

[text* your-name placeholder "name"]

the placeholder tag works fine textarea doesnt work textbox above. can explain me doeing wrong here?

edit

when inspect element google chrome , inspect textbox says has placeholder. doesnt show placeholder.

html wordpress contact-form-7

How to retrieve webpage using Windows command line? -



How to retrieve webpage using Windows command line? -

i trying retrieve webpage e.g. http://google.com/ using command line , save file locally e.g. google.com_20-06-2014.txt need to:

(1) give custom headers (2) able utilize http proxy (3) able utilize both get/post

i have tried using windows-version of wget had problem setting , doesn't seem way.

example:

wget --user-agent="mozilla/5.0 (windows nt 6.1; wow64)" --header="accept-encoding: gzip" -d http://www.google.com/

is there improve way can 1,2,3 on windows?

windows command-line download command-prompt

php - mysql order by max matches field value -



php - mysql order by max matches field value -

i have total 3 table like

table:links id | name | cat_id | weight 1 | test1 | 1 | 5 2 | test2 | 1 | 10 3 | test3 | 1 | 15 4 | test4 | 1 | 2 table:tags id | name | link_id 1 | tag1 | 1 2 | tag2 | 1 3 | tag1 | 2 4 | tag2 | 2 5 | tag1 | 3 6 | tag2 | 4

here

test1 have tags like: tag1,tag2 test2 have tags like: tag1,tag2 test3 have tags like: tag1 test4 have tags like: tag2

so want closest tag match form test 1

so result should be: test2,test3,test4

depend on tag match , weight

try this:

select distinct(l.name) link links l inner bring together tags t on l.id = t.link_id , l.id <> 1 grouping t.link_id order count(t.link_id) desc

sqlfiddle demo

php mysql

java - How to set a timezone with org.joda.time? -



java - How to set a timezone with org.joda.time? -

i want parse string datetime object:

datetimeformatter fmt = datetimeformat.forpattern("m/d/yyyy hh:mm"); datetime dt = fmt.parsedatetime(stringdate + " " + stringtime).withzone(datetimezone.forid("europe/dublin"));

if introduce time 06/22/2014 10:43 get

06/22/2014 8:43 +0100,

but want get

06/22/2014 10:43 +0100

how can this?

you should apply timezone formatter, not datetime. otherwise, date have been parsed in local timezone, , you're simply transposing desired timezone.

datetimeformatter fmt = datetimeformat.forpattern("m/d/yyyy hh:mm") .withzone(datetimezone.forid("europe/dublin")); datetime dt = fmt.parsedatetime("06/22/2014 10:43");

java jodatime

jquery - Should I use a switch statement to associate CSS IDs with JavaScript variables? -



jquery - Should I use a switch statement to associate CSS IDs with JavaScript variables? -

function getvariablefromid(id) { switch (id) { case "gta1": homecoming gta1; case "gta2": homecoming gta2; case "gta3": homecoming gta3; ... case "gtj0": homecoming gtj0; } }

so have switch statement in code takes #id of div tag using .attr , associates javascript variable. each numeric code represents 1 square on chessboard-like grid. there 100 squares. there easier or more compact method performing calculation this, or simplest way?

use array instead of 100 variable , hundred conditions in switch. array array of strings/numbers or objects. declare array number of elements want , number id utilize index of array.

arrgta = ["somevalue1", "somevalue2"]; //could array of strings/numbers or objects. function getvariablefromid(id) { idx = parseint(id.replace("gta", "")); homecoming arrgta[idx-1]; }

javascript jquery html css

ios - How to implement custom slider of my own? -



ios - How to implement custom slider of my own? -

i new in ios , trying implement slider in application. have button in middle of uiview , button deed horizontal slider , should have 3 step (maximum, minimum, middle). show 2 different views e.g. when in middle shows half portion of view1 , half portion of view2 , when goes towards maximum value show total view of view1 , when goes towards minimum show total view of view2. have tried lot not find suitable solution. please give me suggestion slider , tell me how implement this.

try utilize segmented control. sounds me, solve task.

ios objective-c uislider

ios - UISearchDisplayController UISearchBar Animation in a UIScrollView under UIPageControl -



ios - UISearchDisplayController UISearchBar Animation in a UIScrollView under UIPageControl -

it's tough bug squash, objc-fu beginner , confidence crashing longer pretty bug...

the app required have view (let's phone call mainview) uipagecontrol , uiscrollview in order have 2 views scrollable horizontally. hence have implemented adding:

// added on viewdidload... [self addchildviewcontroller:[self.storyboard instantiateviewcontrollerwithidentifier:@"vc1"]]; [self addchildviewcontroller:[self.storyboard instantiateviewcontrollerwithidentifier:@"vc2"]]; // farther processing of kid view controllers... self.scrollview.pagingenabled = yes; (nsuinteger = 0; < [self.childviewcontrollers count]; i++) { uiviewcontroller *controller = [self.childviewcontrollers objectatindex:page]; cgrect frame = self.scrollview.frame; frame.origin.x = frame.size.width * page; frame.origin.y = 0; controller.view.frame = frame; [self.scrollview addsubview:controller.view]; } // expanding scroll view's content size scrolling... self.scrollview.contentsize = cgsizemake( scrollview.frame.size.width * [self.childviewcontrollers count], scrollview.frame.size.height);

note mainview equipped uisearchdisplaycontroller having uisearchbar hidden offscreen. (not sure if info vital.)

the problem in sec kid view controller identifier vc2 equipped uisearchdisplaycontroller having uisearchbar, , when search bar dismisses on end searching, animation how create vc2's uisearchbar reposition in cgrect(0, 0, 320, 40) of mainview instead of vc2. hence vc2's uisearchbar "warped" vc1.

first effort solve containing each kid view controller in view hoping cgrect(0, 0, 320, 40) of vc2's uisearchbar remain in vc2, no avail:

for (nsuinteger = 0; < [self.childviewcontrollers count]; i++) { uiviewcontroller *controller = [self.childviewcontrollers objectatindex:page]; cgrect frame = self.scrollview.frame; frame.origin.x = frame.size.width * page; frame.origin.y = 0; //controller.view.frame = frame; uiview *container = [[uiview alloc] initwithframe:frame]; [container addsubview:controller.view]; [self.scrollview addsubview:container]; }

somehow guessing when vc2's uisearchdisplaycontroller animates it's uisearchbar frame uses 1 of self.uiscrollview not sure.

could please shed lite on bug , fire death please? it's in ios7

main view ------------------- | vc1 | vc2 ------------------------------------- | |_________________| <- search bar (this 'warped' vc1 @ same | | | position on end editing) | | | | | | | | | | | | | | | | | | | | | | | | -------------------------------------

found solution, weird, works, got thought searchbar disappears headerview in ios 7 after noticing memory address of uisearchbar's superview changed on end search.

the next code snippet added of delegated methods possible, namely viewwillappear, searchdisplaycontrollerwillendsearch:, searchdisplaycontrollerdidendsearch::

if (self.searchdisplaycontroller.searchbar.superview != self.searchdisplaycontroller.searchcontentscontroller.view) { [self.searchdisplaycontroller.searchbar removefromsuperview]; [self.searchdisplaycontroller.searchcontentscontroller.view addsubview:self.searchdisplaycontroller.searchbar]; }

will take reply still should there wrong share. give thanks much.

ios uiscrollview uisearchbar uisearchdisplaycontroller uipagecontrol

css3 - CSS specificity for elements with more than one class -



css3 - CSS specificity for elements with more than one class -

i having issue unable level of specificity need create code work. have <ul> want create backgrounds of <li>'s alter when hovered on fancy little slide-in animation.

i managed working pretty using linear-gradient transition on :hover. decided wanted have different list items have different background colors each other, added 3 classes: .red, .blue, , .gold, , figured create .level1 class have required properties other linear gradient itself—namely, background-size: 200% 100%, background-position:right bottom, , transition:all 1s ease, , specify linear gradient , color each individual color class. know pretty intangible, post code below.

here hoping have (or it):

body .push [class^="level1"] { background-size: 200% 100%; background-position:right bottom; transition:all 1s ease; } body .push [class^="level1"]:hover { background-position:left bottom; } body .push .level1.blue { background: linear-gradient(to right, #282e59 50%, rgba(0,0,0,0) 50%); } body .push .level1.red { background: linear-gradient(to right, #94272a 50%, rgba(0,0,0,0) 50%); } body .push .level1.gold { background: linear-gradient(to right, #e5d037 50%, rgba(0,0,0,0) 50%); }

but doesn't work. values in first class take effect, have rid of first 1 body .push [class^="level1"] { ... } , set info in 3 color-specific ones,

body .push .level1.blue { background: linear-gradient(to right, #282e59 50%, rgba(0,0,0,0) 50%); background-size: 200% 100%; background-position:right bottom; transition:all 1s ease; } body .push .level1.red { background: linear-gradient(to right, #94272a 50%, rgba(0,0,0,0) 50%); background-size: 200% 100%; background-position:right bottom; transition:all 1s ease; } body .push .level1.gold { background: linear-gradient(to right, #e5d037 50%, rgba(0,0,0,0) 50%); background-size: 200% 100%; background-position:right bottom; transition:all 1s ease; }

is there way consolidate information?

it seems problem not specificity, shorthand background: declaration overwriting position & size values in original declaration. seek changing background: background-image: in overwrites:

body .push .level1.blue { background-image: linear-gradient(to right, #282e59 50%, rgba(0,0,0,0) 50%); } body .push .level1.red { background-image: linear-gradient(to right, #94272a 50%, rgba(0,0,0,0) 50%); } body .push .level1.gold { background-image: linear-gradient(to right, #e5d037 50%, rgba(0,0,0,0) 50%); }

css3 css-specificity memory-efficient

ruby - A hash using lambdas without relying on conditionals or enumerators -



ruby - A hash using lambdas without relying on conditionals or enumerators -

if have list of accepted aliases , root names basic colors:

coloraliases = { ["red", "crimson", "auburn", "rose", "maroon", "burgundy"] => "red", ["blue", "teal", "aqua", "azure", "cobalt"] => "blue", ["green", "emerald", "absinthe", "avocado", "lime"] => "green", ["yellow", "banana", "lemon", "gold", "citrine"] => "yellow" }

i couldn't this:

coloraliases["crimson"] #=> "red"

i'm trying coax behavior so:

basecolor = lambda |str| x = nil coloraliases.each |keys, value| if keys.include?(str) x = value break end end# of coloraliases hash x end

which should work expected.

am wondering if there more elegant ways this, ways not involving conditional blocks or enumerators. ternary operators ok or improve because they're compact still not preferable because they're conditionals.

your hash design wrong. not using in way hash supposed used. should be:

coloraliases = { "red" => "red", "crimson" => "red", "auburn" => "red", "rose" => "red", "maroon" => "red", "burgundy" => "red", "blue" => "blue", "teal" => "blue", "aqua" => "blue", "azure" => "blue", "cobalt" => "blue", ... }

and then, get:

coloraliases["crimson"] # => "red"

ruby hash lambda

ruby on rails - Kaminari paginate but re-submit form parameters -



ruby on rails - Kaminari paginate but re-submit form parameters -

i using kaminari gem paginate products list.

this search feature works ajax , has top-bar filter style search:

this implies few parameters passed search bar controller processed filter results.

the kaminari paginate helper, has own links , redirects controller action :page parameter, , rest of search filters ignored. when click on page 2 or next link, products no longer filtered , shows page 2 of all products.

i need search parameters sent every time pagination link clicked. how can that?

see post please. it's answered maker of awesome kaminari gem.

ajax pagination kaminari gem

i not sure if using gem search functionality. if are, post might helpful:

http://techbrownbags.wordpress.com/2014/01/17/rails-ajax-search-sort-paginate-with-ransack-kaminari/

ruby-on-rails ajax ruby-on-rails-3 pagination kaminari

ios - Push View Controller From AppDelegate and Tab Bar -



ios - Push View Controller From AppDelegate and Tab Bar -

my app setup tab bar controller rootviewcontroller, , each tab has navigationcontroller in it. when actions performed, want app force viewcontroller onto screen. flow of when app starts, or opens background, checks stored nsdate , compares current date. if right status met, shows uialertview. if button named "push" selected, runs code force new view. reason need ran appdelegate, there no guarantee tab may open if app beingness used in background. since every tab contains navigationcontroller, thought run appdelegate:

- (void)alertview:(uialertview *)alertview clickedbuttonatindex:(nsinteger)buttonindex { if (alertview.tag == 100) { if (buttonindex == 0) { //cancel nslog(@"cancel"); } if (buttonindex == 1) { nslog(@"ok"); [self.tabbarcontroller.selectedviewcontroller pushviewcontroller:self.newview animated:yes]; } } }

i warning message says uiviewcontroller may not respond -pushviewcontroller:animated. suggestions else do?

the homecoming type selectedviewcontroller uiviewcontroller, need tell compiler it's navigation controller. cast,

[(uinavigationcontroller *)self.tabbarcontroller.selectedviewcontroller pushviewcontroller:self.newview animated:yes];

ios uinavigationcontroller uitabbarcontroller appdelegate pushviewcontroller

package - Matrix multiplication in the examples section of R documentation -



package - Matrix multiplication in the examples section of R documentation -

i producing .rd file document function in bundle have written. in examples field include matrix multiplications using %*% command `build & check' procedure appears see % comment , check fails. there way around this, other using crossprod() function? - little tedious since numerous multiplications.

stripping out of content of file, looks this

\name{travel data} \alias{travel}\alias{trav.qly}\alias{trav.mly} \doctype{data} \title{ visits abroad uk residents } \description{} \details{} \examples{ v<-rbind(cbind(b%*%k[1:84,1:84]%*%t(b),b%*%k[1:84,85:120]),cbind(k[85:120,1:84]%*%t(b),k[85:120,85:120])) c<-cbind(k[1:84,1:84]%*%t(b),k[1:84,85:120]) } \keyword{datasets}

then bundle checker gives me output looks this

* checking examples ... error running examples in ‘regspec-ex.r’ failed error occurred in: ... > v<-rbind(cbind(b + c<-cbind(k[1:84,1:84] error: unexpected symbol in: " c" execution halted exited status 1.

thanks comments , suggestions. appears problem has been addressed here r message board. key utilize \ marks before % demonstrated in .rd file matmult.

r package matrix-multiplication

javascript - Replacement of HTC files -



javascript - Replacement of HTC files -

i working on project using html components files (.htc), want upgrade project should work on browsers ie10, htc files no longer supported ie10. please give me solution how can convert part of project using htc files. please refer below code:

this.style.add("behavior", "url(xyz.htc)");

i want replace htc file , code written within file. should needs set in replacement of htc file.

please help.

update .htc (html components) custom attributes js since ie10 standard mode doesn't back upwards htc.

check link

edit :

var method_behavior = { get: function () { homecoming this.style.behavior }, set: function (val) { this.style.behavior = val } } //input if (!htmlinputelement.prototype.hasownproperty("behavior")) { object.defineproperty(htmlinputelement.prototype, "behavior", method_behavior); }

then in html page

<script src="new_js_file_name" type="text/javascript"></script> <script type="text/javascript"> function loaded() { document.getelementbyid("id_name").behavior = "new_behavior"; } </script>

javascript css internet-explorer xhtml html-components

android - Inverting color of textview on SlidingTabStrip -



android - Inverting color of textview on SlidingTabStrip -

i need create animation due briefly invert color of textview while animation. i'm using slidingtablayout viewpager, this:

the colors reference.

the finish code here:

slidingtablayout: here slidingtabstrip: here

[update]

i've tried it:

int normaltextcolor = color.argb( 0, 0, 0, 0); int pressedfiltercolor = color.argb(225, 238, 11, 83); bitmap bitmap = bitmap.createbitmap(1, 1, bitmap.config.argb_8888); //make 1-pixel bitmap canvas canvas = new canvas(bitmap); canvas.drawcolor(normaltextcolor); //color want apply filter canvas.drawcolor(pressedfiltercolor, porterduff.mode.lighten); //apply filter int pressedtextcolor = bitmap.getpixel(0, 0); textview.settextcolor(pressedtextcolor);

but still not working.

as raybaybay said no simple way in android. going have work layers. if familiar photoshop or gimp, how layers are, if not take here http://docs.gimp.org/en/gimp-image-combining.html#gimp-concepts-layers. key here know how combine layers. start testing screen , multiply modes http://developer.android.com/reference/android/graphics/porterduff.mode.html. javadoc on porterduff modes useless, article (jump straight "transfer" section) should help http://www.xenomachina.com/2011/05/androids-2d-canvas-rendering-pipeline.html understand going on.

now, code see familiar android samples. should check graphics/xfermodes demo, on "apidemos" sample. can install straight eclipse: new > other > android sample project. demo shows porterduff modes there , how utilize them. hope helps.

android android-animation android-tabhost

c++ - Is Windows SDK always needed for including Windows.h? -



c++ - Is Windows SDK always needed for including Windows.h? -

i tried utilize findfirstfile win api function in c programme , noticed can utilize after including windows.h in visual studio 2010. bit confused because never installed windows sdk on system. thought 1 can utilize windows.h after installing windows sdk. can explain me why possible? wondering starting capital letter of windows.h. in past used windows.h. have presentation of code on computer visual studio 2010 installed , need sure compile on computer. big helpful information!

the windows sdk isn't way headers - included visual studio.

visual c++ , windows header files

microsoft visual c++ includes copies of windows header files current @ time visual c++ released. therefore, if install updated header files sdk, may end multiple versions of windows header files on computer. if not ensure using latest version of sdk header files, receive next error code when compiling code uses features introduced after visual c++ released: error c2065: undeclared identifier.

source: http://msdn.microsoft.com/en-gb/library/windows/desktop/aa383745(v=vs.85).aspx)

c++ visual-studio-2010 include

java - JPA @Version field doesn't get incremented -



java - JPA @Version field doesn't get incremented -

i'm new jpa , hibernate , have problem optimistic locking. have class wich hase @version annotated field. when update entity represented class, version counter not increase. here code: class:

@entity @table (name = "studenten") public class pupil implements serializable{ private static final long serialversionuid = 705252921575133272l; @version private int version; private int matrnr; private string name; private int semester; public pupil (){ } public pupil (int matrnr, string name){ this.matrnr = matrnr; this.name = name; } public pupil (int matrnr, string name, int semester){ this(matrnr, name); this.semester = semester; }

and here main method:

public static void main(string[] args) { entitymanagerfactory emf = persistence.createentitymanagerfactory("veda_vortrag"); entitymanager em = emf.createentitymanager(); entitytransaction tx = em.gettransaction(); try{ tx.begin(); pupil s = em.find(student.class, 195948); s.setsemester(1); em.persist(s); tx.commit(); }catch(exception e){ if(tx != null && tx.isactive()){ tx.rollback(); system.out.println("error in transaction. rollback!"); } } finally{ em.close(); emf.close(); } }

and here console says:

hibernate: select student0_.matrnr matrnr0_0_, student0_.name name0_0_, student0_.semester semester0_0_, student0_.version version0_0_ studenten student0_ student0_.matrnr=? hibernate: update studenten set name=?, semester=?, version=? matrnr=?

can tell me what's wrong?

edit: ok, have tried something. i've set locking lockmodetype.optimistic_force_increment , got error-message:

error: hhh000099: assertion failure occured (this may indicate bug in hibernate, more due unsafe utilize of session): org.hibernate.assertionfailure: cannot forcefulness version increment on non-versioned entity jun 20, 2014 9:00:52 org.hibernate.assertionfailure <init>

so seems clear have non-versioned entity. why? have @version annotation in class.

edit: begin think problem in persistence.xml. here is:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <persistence-unit name="veda_vortrag"> <provider>org.hibernate.ejb.hibernatepersistence</provider> <properties> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/uni"/> <property name="javax.persistence.jdbc.user" value="*******"/> <property name="javax.persistence.jdbc.password" value="******"/> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.driver"/> <property name="hibernate.dialect" value="org.hibernate.dialect.mysqldialect"/> <property name="hibernate.show_sql" value="true"/> <property name="hibernate.format_sql" value="true"/> </properties> </persistence-unit>

is there wrong?

the entitymanager.persist() method used new entities have never been persisted before.

because fetching entity don't need phone call persist or merge anyway. dirty checking update on behalf.

the commit trigger flush anyway should see update.

make sure utilize javax.persistence.version annotation , not other bundle (spring info or similar).

java mysql hibernate jpa transactions

objective c - What are the easy to use and open source Baracode scanner for ios sdk? -



objective c - What are the easy to use and open source Baracode scanner for ios sdk? -

i want user barcode scanner in app ios in xcode 5.1, want barcode scanner open-source. googled couldn't find one.

use zbar bar code reader sdk. open source scanning.

http://zbar.sourceforge.net/iphone/

they have mentioned not working in iphone 3g. works fine in iphone 4 & above. checked i'm using sdk.

ios objective-c open-source

mvel - Issue with mvel2 - Elasticsearch -



mvel - Issue with mvel2 - Elasticsearch -

we running elasticsearch mass update (elasticsearch uses mvel)

and getting below error

**** compiler bug! study @ http://jira.codehaus.org/browse/mvel2 expression:

int cindex= 0; if(ctx._source.xid == 46461){ if(ctx._source.containskey("attributes") && ctx._source.attributes.size() > 0){ for(cindex = 0; cindex < ctx._source.attributes.size(); cindex++){ if(ctx._source.attributes[cindex].attributename != null && ctx._source.attributes[cindex].attributename.indexof("select") >= 0 && ((ctx._source.attributes[cindex].attributevalue == "oy") || (ctx._source.attributes[cindex].containskey("attributevalueid") && ctx._source.attributes[cindex].attributevalueid != null && ctx._source.attributes[cindex].attributevalueid == "one") && ctx._source.attributes[cindex].attributename == "attribute_select_1403272286210_2498")){ ctx._source.attributes[cindex].attributevalue = "oye"; ctx._source.attributes[cindex].attributevalueid = "one"; } } } }

it working fine few records , not working few records. did face issue? not sure if es has update mvel version around appreciated.

this issue seems fixed in "2.2.0", version of mvel using. can seek <mvel.version>2.2.0.final</mvel.version>

also please refer link here http://jira.codehaus.org/browse/mvel-299

elasticsearch mvel

delphi - Save text from the clipboard to a file -



delphi - Save text from the clipboard to a file -

i trying out below code should save clipboard text text file in delphi xe6. code runs fine generates junk values in output file, when clipboard contains copied text fragment. how can code changed work properly?

function saveclipboardtextdatatofile( sfileto : string ) : boolean; var ps1, ps2 : pchar; dwlen : dword; tf : textfile; hdata : thandle; begin result := false; clipboard begin seek open; if( hasformat( cf_text ) ) begin hdata := getclipboarddata( cf_text ); ps1 := globallock( hdata ); dwlen := globalsize( hdata ); ps2 := stralloc( 1 + dwlen ); strlcopy( ps2, ps1, dwlen ); globalunlock( hdata ); assignfile( tf, sfileto ); rewrite( tf ); write( tf, ps2 ); closefile( tf ); strdispose( ps2 ); result := true; end; close; end; end; end;

you see junk because cf_text ansi. request ansi text, os converts clipboard contents ansi, , set in unicode string. utilize cf_unicodetext unicode applications.

also consider points raised in comments question.

delphi delphi-xe6

xcode - Range of doubles in Swift -



xcode - Range of doubles in Swift -

i writing swift application , parts of require making sure user inputs add together specified value.

a simplified example:

through programme interaction, user has specified totalvalue = 67 , turns = 2. means in 2 inputs, user have provide 2 values add together 67.

so lets on turn 1 user enters 32, , on turn 2 enters 35, valid because 32 + 35 = 67.

this works fine, moment verge more 1 decimal place, programme cannot add together numbers correctly. example, if totalvalue = 67 , on turn 1 user enters 66.95 , on turn 2 enters .05 programme homecoming error despite fact 66.95 + .05 = 67. problem not happen 1 decimal place or less (something turn 1 = 55.5 , turn 2 = 11.5 works fine), 2 decimal spots , beyond. storing values doubles. in advance

some illustration code:

var totalweights = 67 var input = double(mytextfield.text.bridgetoobjectivec().doublevalue) /*each turn button click*/ /*for turn 1*/ if inputvalid == true && turn == 1 && input < totalweights { myarray[0] = input } else { //show error string } /*for turn 2*/ if inputvalid == true && turn == 2 && input == (totalweights - myarray[0]) { myarray[1] = input } else { //show error string }

if want exact values floating point float/double types not work, ever approximations of exact numbers. using nsdecimalnumber class within swift, i'm not sure bridging should simple.

xcode double swift addition

From trailing slash to query (PHP/.htaccess) -



From trailing slash to query (PHP/.htaccess) -

i maintain links in address bar short , clean possible, example:

http://example.com/th1ng

if in database there row 'th1ng' username, above link should work like

http://example.com/user.php?name=th1ng

while still showing first, clean link in address bar.

if user doesn't exist, shows/redirects 404 page.

also, there other files , directories need access via trailing slash too. , possible there query on top well, like

http://example.com/th1ng?img=13805

which should deed like

http://example.com/user.php?name=th1ng?img=13805

i got of php stuff, including database check , redirecting 404 in case user doesn't exist.

but.. proper way around showing clean link in address bar? other files , directories on server still beingness accessible well. can assume .htaccess needs used don't see how exactly.

thanks help!

you need utilize mod_rewrite that. placed in .htaccess.

rewriteengine on rewritecond %{request_filename} !-d rewritecond %{request_filename} !-f rewriterule ^(.*)$ user.php?name=$1 [qsa,l]

php .htaccess slash

r - Divide 3D space into smaller cubes -



r - Divide 3D space into smaller cubes -

i have set of points in 3d. want split entire volume occupied points 128x128x128 number of cubes. , want count number of points in each cube. can suggest how in r?

i have tried rgb , scatterplot3d packages did not find solution there. also, need color these cubes in accordance numbers. please suggest how go it.

although not influence solution, info not symmetrically spread in directions. split quantity: max(x,y,z) 128 border length of each cube.

thank you.

if sure want do, here's attempt.

dat <- as.data.frame(replicate(3, runif(10000))) # toy info n <- 3 # set 128, number of cubes in each direction cut_dat <- lapply(dat, cut, breaks = seq(0, 1, l = n + 1)) # break cubes do.call(table, cut_dat) # cross tabulate count #, , v3 = (0,0.333] # # v2 #v1 (0,0.333] (0.333,0.667] (0.667,1] # (0,0.333] 383 361 379 # (0.333,0.667] 362 382 371 # (0.667,1] 389 358 370 # #, , v3 = (0.333,0.667] # # v2 #v1 (0,0.333] (0.333,0.667] (0.667,1] # (0,0.333] 345 383 372 # (0.333,0.667] 374 388 381 # (0.667,1] 383 368 373 # #, , v3 = (0.667,1] # # v2 #v1 (0,0.333] (0.333,0.667] (0.667,1] # (0,0.333] 342 355 360 # (0.333,0.667] 386 386 374 # (0.667,1] 346 372 357

so 3d array counts. have reduced number of cubes 3 in each direction display concept.

edit: gavin kelly's suggestion can done here

table(cut_dat[[1]]:cut_dat[[2]]:cut_dat[[3]])

to info representation.

or more human readable:

tab2 <- expand.grid(lapply(cut_dat, levels)) tab2$freq <- table(cut_dat[[1]]:cut_dat[[2]]:cut_dat[[3]]) head(tab, n = 4) # v1 v2 v3 freq #1 (0,0.333] (0,0.333] (0,0.333] 374 #2 (0.333,0.667] (0,0.333] (0,0.333] 379 #3 (0.667,1] (0,0.333] (0,0.333] 384 #4 (0,0.333] (0.333,0.667] (0,0.333] 377

r 3d

java - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2 -



java - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2 -

i know due fact 1 or more jar files corrupted in ~/.m2/ repository cant figure out jar file(s) has been corrupted or jars, required delete , re-download.

[error] failed execute goal org.apache.maven.plugins:maven-compiler- plugin:2.3.2:compile (default-compile) on project crudwebappmavenized: execution default-compile of goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile failed: api incompatibility encountered while executing org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile: java.lang.unsupportedclassversionerror: com/sun/tools/javac/main : unsupported major.minor version 52.0 [error] ----------------------------------------------------- [error] realm = plugin>org.apache.maven.plugins:maven-compiler-plugin:2.3.2 [error] strategy = org.codehaus.plexus.classworlds.strategy.selffirststrategy [error] urls[0] = file:/c:/users/hp/.m2/repository/org/apache/maven/plugins/maven- compiler-plugin/2.3.2/maven-compiler-plugin-2.3.2.jar [error] urls[1] = file:/c:/users/hp/.m2/repository/org/codehaus/plexus/plexus-utils/2.0.5/plexus-utils-2.0.5.jar [error] urls[2] = file:/c:/users/hp/.m2/repository/org/codehaus/plexus/plexus-compiler-api/1.8.1/plexus-compiler-api-1.8.1.jar [error] urls[3] = file:/c:/users/hp/.m2/repository/org/codehaus/plexus/plexus-compiler- manager/1.8.1/plexus-compiler-manager-1.8.1.jar [error] urls[4] = file:/c:/users/hp/.m2/repository/org/codehaus/plexus/plexus-compiler-javac/1.8.1/plexus-compiler-javac-1.8.1.jar [error] number of foreign imports: 1 [error] import: entry[import realm classrealm[maven.api, parent: null]]

java maven

php curl not getting same response as fiddler -



php curl not getting same response as fiddler -

this php code : $source = $_post['source']; $destination = $_post['destination']; $class = $_post['class']; $day = $_post['day']; $month = $_post['month']; $data = array( 'lccp_src_stncode_dis' => $source, 'lccp_dstn_stncode' => $destination, 'lccp_classopt' => $class, 'lccp_day' => $day, 'lccp_month' => $month ); # create connection $url = 'data per raw req '; $ch = curl_init($url); echo $ch." <br>"; # form info string $poststring = http_build_query($data); echo $poststring; $header = array ( 'host' => 'data per raw req ' 'connection'=> 'keep-alive', 'content-length'=> '180', 'cache-control'=> 'max-age=0', 'accept'=> 'text/html', 'origin'=> 'data per raw req ', 'user-agent' => '', 'content-type' => 'application/x-www-form-urlencoded', 'referer': 'data per raw req ' 'accept-encoding'=> '', 'accept-language' => 'en-us,en;q=0.8' ); # setting options curl_setopt($ch, curlopt_post, true); curl_setopt($ch, curlopt_postfields, $poststring); curl_setopt($ch, curlopt_returntransfer, true); curl_setopt($ch, curlopt_httpheader, $header); //# response curl_setopt($ch, curlopt_postfields, $response = curl_exec($ch); curl_close($ch); #print response echo " $response ";

receiving form info from:

<html> <form method="post" action="poster.php"> <table> <tr><td>source:</td><td><input type="text" name="source"></td></tr> <tr><td>destination:</td><td><input type="text" name="destination"></td></tr> <tr><td>day:</td><td><input type="text" name="day"></td></tr> <tr><td>month:</td><td><input type="text" name="month"></td></tr> <tr><td>class:</td><td><input type="text" name="class"></td></tr> <tr><td><input type="submit" name="submit" value="submit"></td> <td><input type="reset" name="reset" value="reset"></td></tr> </table> </form> </html>

this raw request

post http://www.indianrail.gov.in/cgi_bin/inet_srcdest_cgi_date.cgi http/1.1 host: www.indianrail.gov.in connection: keep-alive content-length: 91 cache-control: max-age=0 accept: text/html origin: **<---modified since can't post more 2 links user-agent: content-type: application/x-www-form-urlencoded referer: ** <---modified since can't post more 2 links accept-encoding: accept-language: en-us,en;q=0.8 lccp_src_stncode_dis=ndls&lccp_dstn_stncode=hyb&lccp_classopt=sl&lccp_day=26&lccp_month=6

fiddler giving appropriate response cgi, whereas php script shows html container, i've been stuck on hr ! please help ! edit: output verbose :

* adding handle: conn: 0x2cab910 * adding handle: send: 0 * adding handle: recv: 0 * curl_addhandletopipeline: length: 1 * - conn 3 (0x2cab910) send_pipe: 1, recv_pipe: 0 * connect() www.indianrail.gov.in port 80 (#3) * trying 203.176.113.78... * connected www.indianrail.gov.in (203.176.113.78) port 80 (#3) > post /cgi_bin/inet_srcdest_cgi_date.cgi http/1.1 host: www.indianrail.gov.in accept: */* http://www.indianrail.gov.in http://www.indianrail.gov.in/know_station_code.html content-length: 89 content-type: application/x-www-form-urlencoded * upload sent off: 89 out of 89 bytes < http/1.1 200 ok < date: fri, 27 jun 2014 05:38:17 gmt * server apache/2.2.15 (red hat) not blacklisted < server: apache/2.2.15 (red hat) < connection: close < transfer-encoding: chunked < content-type: text/html; charset=utf-8 < * closing connection 3

^off topic: why did allow me post links time, should have been recognized links ?

also, compare sessions in fiddler, fiddler shows request own app on local host, not app indian railways site. screenshot : nevermind, not plenty rep edit: i'll happy if can show me how create request http_request2 i've posted exact raw request gives me required output fiddler in comments, no, i'm not missing authentication , cookie headers , like

header not entered associative array, wrong :

$header = array ( 'host' => 'data per raw req ' 'connection'=> 'keep-alive', 'content-length'=> '180', 'cache-control'=> 'max-age=0', 'accept'=> 'text/html', 'origin'=> 'data per raw req ', 'user-agent' => '', 'content-type' => 'application/x-www-form-urlencoded', 'referer': 'data per raw req ' 'accept-encoding'=> '', 'accept-language' => 'en-us,en;q=0.8' );

correct method :

$header = array ( 'host:*data per raw req* ' 'connection:keep-alive', 'content-length:180', 'cache-control:max-age=0', 'accept:text/html', 'origin:*data per raw req* ', 'user-agent:', 'content-type:application/x-www-form-urlencoded', 'referer:*data per raw req* ' 'accept-encoding:', 'accept-language:en-us,en;q=0.8' );

even info entered in associative array i've used formatted url encoded post string, apparently pretty much has entered in raw http request. curl doesn't formatting.

php curl fiddler

f# - Why do I see the Program+ prefix when printfn tries to print an object? -



f# - Why do I see the Program+ prefix when printfn tries to print an object? -

i have object of class created, printing object %a format specifier, see typename program+myclass instead of myclass ? why that?

someone might programme namespace, if how come not able next ?

let o = program+myclass()

here total code

open scheme type myclass() = fellow member val x = 3 get,set [<entrypoint>] allow main argv = allow o = myclass() o |> printfn "here myclass object %a" console.readkey() 0 // homecoming integer exit code

as john correctly explains, part before + in program+myclass there because code compiled program module. f# modules compiled nested classes , myclass nested class within program (which static class) , + comes standard .net naming of nested classes.

you can avoid putting class in namespace (but you'll still need have main function in module):

namespace myprogram open scheme type myclass() = fellow member val x = 3 get,set module main = [<entrypoint>] allow main argv = allow o = myclass() o |> printfn "here myclass object %a" console.readkey() 0 // homecoming integer exit code

now, myclass straight in namespace (not nested class) , print without program+ prefix.

f# c#-to-f#

jquery - How to Stop li-scroller? -



jquery - How to Stop li-scroller? -

i using plugin: li-scroller here code: jquery function code

i there way can destroy/stop/restart (remove divs , mark , start again) when applied unordered list via function.

<ul id="ticker01"> <li><span>10/10/2007</span><a href="#">the first thing ...</a></li> <li><span>10/10/2007</span><a href="#">end doing ...</a></li> <li><span>10/10/2007</span><a href="#">the code ...</a></li> <!-- eccetera --> </ul> class="lang-js prettyprint-override">$("ul#ticker01").liscroll();

jsfiddle

to stop , destroy scroller need "undo" li-scroller adds can utilize followiing jquery:

$("ul#ticker01") .clearqueue().stop() //stops animation .unwrap() //removes mask div .unwrap() //removes tickercontainer div .unbind() //unbinds events attached (like hover) .removeclass('newsticker') //removes class .removeattr('style'); //removes height style

example

jquery scroller

c - Query on handling TAB character? -



c - Query on handling TAB character? -

in ascii characterset world, below 3 whitespace characters have number.

space(32) linefeed(10) carriagereturn(13)

so, easy write programme read or write such whitespace characters in standard way using programming language(like c) in portable way, using next notations,

linefeed - '\n' carriage homecoming - '\r' space - ' '

i learnt tab collection of 4 or 8 space characters.

my question:

how understand meaning of '\t' character in programming language(like c)? when there no standard definition of tab in characterset world?

in ascii, horizontal tab code 9. ascii horizontal tab code 9 regardless of character set code written in.

in c, '\t' horizontal tab in character set of source code, regardless of character set of io. integer value of '\t' may/may not 9.

the character set of code , character set of io (e.g. files) commonly same. in 2014, there both ascii (at to the lowest degree ascii codes 0 - 127).

in c, printing '\t' precise;

moves active position next horizontal tabulation position on current line. if active position @ or past lastly defined horizontal tabulation position, behavior of display device unspecified. c11 §5.2.2 2

with ascii, horizontal tab intended not represent printable information, rather command devices. ascii original definition led ambiguity precise action of command device: move next tabulation stop.

given these similar, different meanings, , acknowledging other languages have various meanings, precise meaning highly dependent on situation. hence maintain portability, other situation dependent info needed (e. g. definition or list of tab stops) precisely generate , interpret horizontal tab.

recommend: unless info format requires ( csv, makefile), not generate tabs, spaces. upon reading '\t', interpret it, able, same 1 or more consecutive spaces.

c language-agnostic

neo4j - Matching pattern with optional nodes -



neo4j - Matching pattern with optional nodes -

i have cypher query tries capture nodes in order:

a:genus-->b:family-->c:order-->d:class-->e:phylum

with labels genus, family, order, class, phylum , homecoming similar table below.

each of nodes a:e have other properties in reality, nodes may linked in next manner

a:genus --> b:no_rank --> c:family --> d:class --> e:no_rank --> f:phylum

how capture such construction pattern may miss label or have additional nodes in between single query.

currently cypher query looks this:

start basetaxa=node:ncbitaxid('taxid:2006379') match basetaxa-[:childof*0..]->(genus:`genus`)-[:childof*0..]->(family:`family`)-[:childof*0..]->(order:`order`)-[:childof*0..]->(class:`class`)-[:childof*0..]->(phylum:`phylum`) homecoming genus.taxid,family.taxid,order.taxid,class.taxid,phylum.taxid;

which returns this

+-----------------------------------------------------------------------+ | genus.taxid | family.taxid | order.taxid | class.taxid | phylum.taxid | +-----------------------------------------------------------------------+ | 914 | 206379 | 32003 | 28216 | 1224 | +-----------------------------------------------------------------------+ 1 row

neo4j cypher

android - Query based on the difference in number of occurrences in other tables -



android - Query based on the difference in number of occurrences in other tables -

i have 3 tables.

table_main: +-----+----------+-------------+ | _id | entry_id | info | +-----+----------+-------------+ | 1 | a1 | info 1 | | 2 | a2 | info 2 | | 3 | a3 | info 3 | +-----+----------+-------------+

table_additions:

+----------+-----------+ | entry_id | timestamp | +----------+-----------+ | a1 | 123456 | | a2 | 123458 | | a1 | 123654 | | a1 | 123658 | | a2 | 123843 | | a3 | 123911 | +----------+-----------+

table_deletions:

+----------+-----------+ | entry_id | timestamp | +----------+-----------+ | a3 | 123556 | | a2 | 123558 | | a3 | 123754 | | a1 | 123858 | | a3 | 123863 | | a3 | 123976 | +----------+-----------+

i working in android. want info table_main of entries have :

number of occurances in table_additions > number of occurances in table_deletions

so, in above example, output should be:

+-----+----------+-------------+ | _id | entry_id | info | +-----+----------+-------------+ | 1 | a1 | info 1 | | 2 | a2 | info 2 | +-----+----------+-------------+

this can done correlated subqueries:

select * table_main (select count(*) table_additions entry_id = table_main.entry_id ) > (select count(*) table_deletions entry_id = table_main.entry_id )

android sqlite android-sqlite

javascript - js-ctypes: Pointer to intptr_t -



javascript - js-ctypes: Pointer to intptr_t -

in ctypes have

tbbutton.ptr(ctypes.uint64("0x1e677e60")

this equivalent abutton.address() in line of code here:

var rez = sendmessage(htoolbar, 0x417 /** tb_getbutton **/, 1, abutton.address());

when run code error:

exception: expected type intptr_t, got tbbutton.ptr(ctypes.uint64("0xaa4eb20"))

so because in sendmessage defintion have this:

var sendmessage = user32.declare('sendmessagew', ctypes.winapi_abi, ctypes.intptr_t, ctypes.voidptr_t, // hwnd ctypes.uint32_t, // msg ctypes.uintptr_t, // wparam ctypes.intptr_t // lparam );

so question is: type of tbbutton.ptr(ctypes.uint64("0x1e677e60") can alter lparam in sendmessage defintion type.

or alternatively: possible create intptr_t? ctypes.intptr_t(abutton.address()), tried doesn't work.

it pointer tbbutton, whatever tbbutton is, while intptr_t integer big plenty hold pointer address.

you need cast pointer intptr_t.

var lparam = ctypes.cast(tbbuttonptr, ctypes.intptr_t);

javascript firefox-addon jsctypes

rx java - How to wait for async Observable to complete -



rx java - How to wait for async Observable to complete -

i'm trying build sample using rxjava. sample should orchestrate reactivewareservice , reactivereviewservice retruning wareandreview composite.

reactivewareservice public observable<ware> findwares() { homecoming observable.from(wareservice.findwares()); } reactivereviewservice: reviewservice.findreviewsbyitem threadsleep simulate latency! public observable<review> findreviewsbyitem(final string item) { homecoming observable.create((observable.onsubscribe<review>) observer -> executor.execute(() -> { seek { list<review> reviews = reviewservice.findreviewsbyitem(item); reviews.foreach(observer::onnext); observer.oncompleted(); } grab (exception e) { observer.onerror(e); } })); } public list<wareandreview> findwareswithreviews() throws runtimeexception { final list<wareandreview> wareandreviews = new arraylist<>(); wareservice.findwares() .map(wareandreview::new) .subscribe(wr -> { wareandreviews.add(wr); //async!!!! reviewservice.findreviewsbyitem(wr.getware().getitem()) .subscribe(wr::addreview, throwable -> system.out.println("error while trying find reviews " + wr) ); } ); //todo: there should improve way wait async reviewservice.findreviewsbyitem completion! seek { thread.sleep(3000); } grab (interruptedexception e) {} homecoming wareandreviews; }

given fact don't want homecoming observable, how can wait async observable (findreviewsbyitem) complete?

you may utilize methods blockingobservable see https://github.com/netflix/rxjava/wiki/blocking-observable-operators. e.g

blockingobservable.from(reviewservice.findreviewsbyitem(..)).toiterable()

rx-java

autocomplete - How to remove KVO methods from Xcode auto-completion popup? -



autocomplete - How to remove KVO methods from Xcode auto-completion popup? -

when write class in objective-c xcode maintain showing automatically inferred kvo methods. well, don't utilize kvo in code, , will. it's bordering me, , number of methods more methods declared in class.

how remove kvo methods auto-completion window? believe there's mechanism command this, have no idea.

i extracted out properties causes kvo method generation separated protocol, , doesn't border me anymore. best workaround me now.

xcode autocomplete

python - How to fix the daemonize import error in graphite? -



python - How to fix the daemonize import error in graphite? -

i configuring graphite monitoring system. when next tutorial on https://gist.github.com/surjikal/2777886 ran next import error:

python /opt/graphite/bin/carbon-cache.py start traceback (most recent phone call last): file "/opt/graphite/bin/carbon-cache.py", line 28, in <module> carbon.util import run_twistd_plugin file "/opt/graphite/lib/carbon/util.py", line 21, in <module> twisted.scripts._twistd_unix import daemonize importerror: cannot import name daemonize

googling around found several possible solutions issue:

1) remove daemonize imports /opt/graphite/lib/carbon/util.py (https://answers.launchpad.net/graphite/+question/239063):

from time import sleep, time twisted.python.util import initgroups twisted.scripts.twistd import runapp # twisted.scripts._twistd_unix import daemonize # daemonize = daemonize # backwards compatibility

2) utilize twisted 13.1.0 instead of higher twisted version.

3) install daemonize via pip , import directly (https://www.digitalocean.com/community/tutorials/installing-and-configuring-graphite-and-statsd-on-an-ubuntu-12-04-vps):

# twisted.scripts._twistd_unix import daemonize import daemonize

what stable , proven solution twisted environment prepare import issue?

option (2) sounds best alternative me - particularly if can find documentation graphite team twisted 13.1 beingness supported version of twisted (they should document supported versions of dependencies).

with alternative (1) you're diverging installation upstream. going admin headache.

i'm pretty sure alternative (3) won't help. daemonize module related in has same name , vaguely same thing. not drop-in replacement, though.

python twisted graphite python-daemon

c# - WCF transport with https communication with certificates issue -



c# - WCF transport with https communication with certificates issue -

i have web application hosted in iis on server communicates web service installed on same server. web service installed standard service , not through iis.

the service , running , can navigate in browser using https. added certificate using netsh: wcf transport security via certificates

however when web application tries invoke calls web service error on following:

an error occurred while making http request https://theserver/vehicleservice/connectxml/1.0/https. due fact server certificate not configured http.sys in https case. caused mismatch of security binding between client , server.

i looked deeper error , found this:

<exceptiontype>system.io.ioexception, mscorlib, version=4.0.0.0, culture=neutral, publickeytoken=b77a5c561934e089</exceptiontype> <message>unable read info transport connection: existing connection forcibly closed remote host.</message> <exceptiontype>system.net.webexception, system, version=4.0.0.0, culture=neutral, publickeytoken=b77a5c561934e089</exceptiontype> <message>the underlying connection closed: unexpected error occurred on send.</message>

does know causing issue? need add together configuration iis?

i have tried adding certificates locally , works fine me.

your securityprotocoltype may not enabled (from windows registry). if this:

class="lang-none prettyprint-override">system.io.ioexception: unable read info transport connection

try 1 of next protocol types:

class="lang-c# prettyprint-override">servicepointmanager.securityprotocol = securityprotocoltype.ssl3; // tls, tls11, or tls12

c# web-services wcf iis ssl

python 2.7 - subprocess.popen(replacing a parameter from a list and place it on a command) -



python 2.7 - subprocess.popen(replacing a parameter from a list and place it on a command) -

it's first week python, apologize in advance if question sounds stupid.

basically wrote code:

__author__ = 'houssam' import subprocess subprocess import popen, pipe check = subprocess.popen(["winexe", "--system", "-u","mydomain\\myusername%mypassword", "//computername", "cmd /c c:\\windows\\system32\\inetsrv\\appcmd list site"],stderr=subprocess.pipe, stdout=subprocess.pipe) (stdout,stderr) = check.communicate() if check.returncode == 0: print 'iis installed on scheme in location below:' print stdout elif check.returncode == 1: print 'iis not installed on scheme ' , stderr

so can query iis of specific computer "//computername" , works.

however have 20 computers. want create list list = [computer1,computer2,computer3] , have function does: each c in list replace name of computer unique parameter "//computername" within subprocess.check_output calls winexe command don't have write command computers have.

i appreciate help , suggestions.

thank you,

houssam

i found answer:

i created list of servers

servers = [//computer1", "//computer2"]

then added statement , set list within popen follow:

server in servers: check= subprocess.popen(["winexe", "--system", "- u","mydomain\\myusername%mypassword", server, "cmd /c c:\\windows\\system32\\inetsrv\\appcmd list site"],stderr=subprocess.pipe, stdout=subprocess.pipe) (stdout,stderr) = check.communicate() if check.returncode == 0: print 'iis installed on scheme in location below:' print stdout elif check.returncode == 1: print 'iis not installed on scheme ' , stderr

then set in function follow:

def iis_check(servers): server in servers: check= subprocess.popen(["winexe", "--system", "- u","mydomain\\myusername%mypassword", server, "cmd /c c:\\windows\\system32\\inetsrv\\appcmd list site"],stderr=subprocess.pipe, stdout=subprocess.pipe) (stdout,stderr) = check.communicate() if check.returncode == 0: print 'iis installed on scheme in location below:' print stdout elif check.returncode == 1: print 'iis not installed on scheme ' , stderr

python-2.7 parameters subprocess popen winexe

python - Why is this Django view erroring out before it displays a debug print statement? -



python - Why is this Django view erroring out before it displays a debug print statement? -

i have, development server in django project, django view 500 generated, apparently before view can run initial debug output. output development server, per intended ajax hit, is:

internal server error: /ajax/say traceback (most recent phone call last): file "/library/python/2.7/site-packages/django/core/handlers/base.py", line 114, in get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) file "/library/python/2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view homecoming view_func(*args, **kwargs) file "/users/jonathan/unixytalk/unixytalk/views.py", line 71, in ajax_say request.session, room = room)): file "/library/python/2.7/site-packages/django/db/models/manager.py", line 163, in filter homecoming self.get_queryset().filter(*args, **kwargs) file "/library/python/2.7/site-packages/django/db/models/query.py", line 590, in filter homecoming self._filter_or_exclude(false, *args, **kwargs) file "/library/python/2.7/site-packages/django/db/models/query.py", line 608, in _filter_or_exclude clone.query.add_q(q(*args, **kwargs)) file "/library/python/2.7/site-packages/django/db/models/sql/query.py", line 1198, in add_q clause = self._add_q(where_part, used_aliases) file "/library/python/2.7/site-packages/django/db/models/sql/query.py", line 1234, in _add_q current_negated=current_negated) file "/library/python/2.7/site-packages/django/db/models/sql/query.py", line 1125, in build_filter clause.add(constraint, and) file "/library/python/2.7/site-packages/django/utils/tree.py", line 104, in add together info = self._prepare_data(data) file "/library/python/2.7/site-packages/django/db/models/sql/where.py", line 79, in _prepare_data value = obj.prepare(lookup_type, value) file "/library/python/2.7/site-packages/django/db/models/sql/where.py", line 352, in prepare homecoming self.field.get_prep_lookup(lookup_type, value) file "/library/python/2.7/site-packages/django/db/models/fields/__init__.py", line 1079, in get_prep_lookup homecoming super(integerfield, self).get_prep_lookup(lookup_type, value) file "/library/python/2.7/site-packages/django/db/models/fields/__init__.py", line 369, in get_prep_lookup homecoming self.get_prep_value(value) file "/library/python/2.7/site-packages/django/db/models/fields/__init__.py", line 1073, in get_prep_value homecoming int(value) typeerror: int() argument must string or number, not 'sessionstore' [18/jun/2014 11:34:28] "post /ajax/say http/1.1" 500 111136

the urlpatterns has:

url(r'^ajax/say/?$', 'unixytalk.views.ajax_say'),

the source function is:

#@ajax_login_required @csrf_exempt def ajax_say(request): print 'reached here!' if not request.session.get('identifier', none): session = session() session.save() request.session['identifier'] = session.id #print repr(request) #conversation = request.post['conversation'] #if not request.user in conversation.users: #return try: print repr(get_post(request)) text = get_post(request)['params']['text'] print 'door 1' print repr(text) except keyerror: print 'door 2' homecoming httpresponse(json.dumps([]), mimetype='application/json') except typeerror: print 'door 3' homecoming httpresponse(json.dumps([]), mimetype='application/json') if get_post(request)['params'].get('time', none) != none: room = room.objects.filter(identifier = get_post(request)['params']['room'])[0] if len(individualcontribution.objects.filter(session = request.session, room = room)): instance = individualcontribution.objects.filter(session = request.session, room = room)[0] else: instance = individualcontribution(room = room, session = request.session['identifier']) instance.text = text instance.timestamp = get_post(request)['params']['timestamp'] instance.save() homecoming httpresponse(json.dumps([]), mimetype='application/json')

this function work in progress, , intended farther refinement.

the development server's console output shows 1 or 2 hits without server error, before displaying error output above. (the page references /ajax/say supposed give brain dump every second, , happens initial bit out putout without error, 500 every sec after that.) non-error output is:

inner sanctum ~/unixytalk $ python manage.py runserver validating models... 0 errors found june 18, 2014 - 11:34:26 django version 1.6.2, using settings 'unixytalk.settings' starting development server @ http://127.0.0.1:8000/ quit server control-c. reached here! {u'params': {u'room': u'ee8696bab4df6a68e0f3', u'time': 1403109268206}} door 2 reached here! {"monologues": {}, "sessions": []} {"monologues": {}, "sessions": []} /library/python/2.7/site-packages/django/http/response.py:330: deprecationwarning: using mimetype keyword argument deprecated, utilize content_type instead super(httpresponse, self).__init__(*args, **kwargs) [18/jun/2014 11:34:28] "post /ajax/listen http/1.1" 200 34 [18/jun/2014 11:34:28] "post /ajax/listen http/1.1" 200 34 {u'params': {u'text': u'aaaa', u'room': u'ee8696bab4df6a68e0f3', u'time': 1403109268212}} door 1 u'aaaa' [18/jun/2014 11:34:28] "post /ajax/say http/1.1" 200 2

i'm guessing i'm trying create session object string or non-integer id, or that, i.e. first run creates pollution affects sec , subsequent goes. "session" not django's session, empty (django model) class used create unique integer key.

--update--

in response dhana, models defined project are:

from django.contrib.auth.models import user django.db import models unixytalk import settings class room(models.model): identifier = models.charfield(max_length = settings.max_hash_length, null = true, blank = true) class session(models.model): pass class individualcontribution(models.model): room = models.foreignkey(room) session = models.integerfield() text = models.textfield() timestamp = models.floatfield() username = models.textfield()

i think error here

instance = individualcontribution.objects.filter(session = request.session, room = room)[0]

when querying data,it gives error

typeerror: int() argument must string or number, not 'sessionstore'

it asking string or number providing sessionstore.

if provide individualcontribution model details give more details.

python ajax django django-views django-sessions

stored procedures - ORACLE Search All Tables of a String with BLOB Column -



stored procedures - ORACLE Search All Tables of a String with BLOB Column -

i'm trying search using string tables didn't seem work in blob columns. got procedure forum. it's working in searching string not in blob. can please help me please?

create or replace procedure find_string( p_str in varchar2 ) authid current_user l_query long; l_case long; l_runquery boolean; l_tname varchar2(30); l_cname varchar2(30); l_x number; begin dbms_application_info.set_client_info( '%' || upper(p_str) || '%' ); x in (select * user_tables ) loop l_query := 'select ''' || x.table_name || ''', $$ ' || x.table_name || ' rownum = 1 , ( 1=0 '; l_case := 'case '; l_runquery := false; y in ( select * user_tab_columns table_name = x.table_name ) loop l_runquery := true; l_query := l_query || ' or upper(' || y.column_name || ') userenv(''client_info'') '; l_case := l_case || ' when upper(' || y.column_name || ') userenv(''client_info'') ''' || y.column_name || ''''; end loop; if ( l_runquery ) l_case := l_case || ' else null end'; l_query := replace( l_query, '$$', l_case ) || ')'; begin execute immediate l_query l_tname, l_cname; dbms_output.put_line ( 'found in ' || l_tname || '.' || l_cname ); exception when no_data_found /*select 0 l_x dual;*/ dbms_output.put( '.'); end; end if; end loop; end;

thank much!

you cannot search strings within blob column using normal sql string operations. need utilize dbms_lob bundle accomplish goal.

refer this link illustration of how done. there plenty of examples on google can guide further.

oracle stored-procedures blob

When I use Spring Boot to start a remote service interface I get a "missing EmbeddedServletContainerFactory bean" exception -



When I use Spring Boot to start a remote service interface I get a "missing EmbeddedServletContainerFactory bean" exception -

following entire stacktrace in intellijidea:

"c:\program files\java\jdk1.6.0_29\bin\java" -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:57558,suspend=y,server=n -javaagent:c:\users\clearity\.intellijidea13\system\groovyhotswap\gragent.jar -dfile.encoding=utf-8 -classpath "c:\program files\java\jdk1.6.0_29\jre\lib\charsets.jar;c:\program files\java\jdk1.6.0_29\jre\lib\deploy.jar;c:\program files\java\jdk1.6.0_29\jre\lib\javaws.jar;c:\program files\java\jdk1.6.0_29\jre\lib\jce.jar;c:\program files\java\jdk1.6.0_29\jre\lib\jsse.jar;c:\program files\java\jdk1.6.0_29\jre\lib\management-agent.jar;c:\program files\java\jdk1.6.0_29\jre\lib\plugin.jar;c:\program files\java\jdk1.6.0_29\jre\lib\resources.jar;c:\program files\java\jdk1.6.0_29\jre\lib\rt.jar;c:\program files\java\jdk1.6.0_29\jre\lib\ext\dnsns.jar;c:\program files\java\jdk1.6.0_29\jre\lib\ext\localedata.jar;c:\program files\java\jdk1.6.0_29\jre\lib\ext\sunjce_provider.jar;d:\work_space\external card related\project_related\icpay_v3_merchant\out\production\icpay_v3_merchant;c:\users\clearity\.gradle\caches\modules-2\files-2.1\org.codehaus.groovy\groovy-all\2.1.6\165b8246372a829c1915611646f6d964010656cf\groovy-all-2.1.6.jar;d:\work_space\spring-boot\annotations-api.jar;d:\work_space\spring-boot\catalina.jar;d:\work_space\spring-boot\commons-codec-1.6.jar;d:\work_space\spring-boot\commons-logging-1.1.3.jar;d:\work_space\spring-boot\ecj-4.3.1.jar;d:\work_space\spring-boot\el-api.jar;d:\work_space\spring-boot\fluent-hc-4.3.4.jar;d:\work_space\spring-boot\httpclient-4.3.4.jar;d:\work_space\spring-boot\httpclient-cache-4.3.4.jar;d:\work_space\spring-boot\httpcore-4.3.2.jar;d:\work_space\spring-boot\httpmime-4.3.4.jar;d:\work_space\spring-boot\jasper-el.jar;d:\work_space\spring-boot\jasper.jar;d:\work_space\spring-boot\jsp-api.jar;d:\work_space\spring-boot\juli-6.0.41.jar;d:\work_space\spring-boot\servletapi-3.0.jar;d:\work_space\spring-boot\spring-aop-4.0.5.release.jar;d:\work_space\spring-boot\spring-beans-4.0.5.release.jar;d:\work_space\spring-boot\spring-boot-1.1.1.release-tests.jar;d:\work_space\spring-boot\spring-boot-1.1.1.release.jar;d:\work_space\spring-boot\spring-boot-actuator-1.1.1.release.jar;d:\work_space\spring-boot\spring-boot-autoconfigure-1.1.1.release.jar;d:\work_space\spring-boot\spring-boot-gradle-plugin-1.1.1.release.jar;d:\work_space\spring-boot\spring-context-4.0.5.release.jar;d:\work_space\spring-boot\spring-context-support-4.0.5.release.jar;d:\work_space\spring-boot\spring-core-4.0.5.release.jar;d:\work_space\spring-boot\spring-expression-4.0.5.release.jar;d:\work_space\spring-boot\spring-web-4.0.5.release.jar;d:\work_space\spring-boot\spring-webmvc-4.0.5.release.jar;d:\work_space\spring-boot\tomcat-coyote.jar;d:\work_space\spring-boot\tomcat-dbcp.jar;d:\work_space\spring-boot\tomcat-util-7.0.16.jar;d:\docs\httpcomponents-client-4.3.4-bin\httpcomponents-client-4.3.4\lib\commons-codec-1.6.jar;d:\docs\httpcomponents-client-4.3.4-bin\httpcomponents-client-4.3.4\lib\commons-logging-1.1.3.jar;d:\docs\httpcomponents-client-4.3.4-bin\httpcomponents-client-4.3.4\lib\fluent-hc-4.3.4.jar;d:\docs\httpcomponents-client-4.3.4-bin\httpcomponents-client-4.3.4\lib\httpclient-4.3.4.jar;d:\docs\httpcomponents-client-4.3.4-bin\httpcomponents-client-4.3.4\lib\httpclient-cache-4.3.4.jar;d:\docs\httpcomponents-client-4.3.4-bin\httpcomponents-client-4.3.4\lib\httpcore-4.3.2.jar;d:\docs\httpcomponents-client-4.3.4-bin\httpcomponents-client-4.3.4\lib\httpmime-4.3.4.jar;c:\download\usefuljars\fastjson-1.1.39.jar;c:\download\jpos-1.9.0.jar;d:\docs\slf4j-1.7.7\slf4j-1.7.7\slf4j-log4j12-1.7.7.jar;d:\docs\slf4j-1.7.7\slf4j-1.7.7\slf4j-nop-1.7.7.jar;d:\docs\slf4j-1.7.7\slf4j-1.7.7\slf4j-api-1.7.7.jar;c:\download\usefuljars\druid-1.0.4.jar;c:\program files (x86)\jetbrains\intellij thought 13.1.3\lib\idea_rt.jar" merchantapplication connected target vm, address: '127.0.0.1:57558', transport: 'socket' . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: spring boot :: (v1.1.1.release) exception in thread "main" org.springframework.context.applicationcontextexception: unable start embedded container; nested exception org.springframework.context.applicationcontextexception: unable start embeddedwebapplicationcontext due missing embeddedservletcontainerfactory bean. @ org.springframework.boot.context.embedded.embeddedwebapplicationcontext.onrefresh(embeddedwebapplicationcontext.java:135) @ org.springframework.context.support.abstractapplicationcontext.refresh(abstractapplicationcontext.java:476) @ org.springframework.boot.context.embedded.embeddedwebapplicationcontext.refresh(embeddedwebapplicationcontext.java:120) @ org.springframework.boot.springapplication.refresh(springapplication.java:683) @ org.springframework.boot.springapplication.run(springapplication.java:313) @ org.springframework.boot.springapplication.run(springapplication.java:944) @ org.springframework.boot.springapplication.run(springapplication.java:933) @ org.springframework.boot.springapplication$run.call(unknown source) @ org.codehaus.groovy.runtime.callsite.callsitearray.defaultcall(callsitearray.java:45) @ org.codehaus.groovy.runtime.callsite.abstractcallsite.call(abstractcallsite.java:108) @ org.codehaus.groovy.runtime.callsite.abstractcallsite.call(abstractcallsite.java:120) @ merchantapplication.main(merchantapplication.groovy:17) caused by: org.springframework.context.applicationcontextexception: unable start embeddedwebapplicationcontext due missing embeddedservletcontainerfactory bean. @ org.springframework.boot.context.embedded.embeddedwebapplicationcontext.getembeddedservletcontainerfactory(embeddedwebapplicationcontext.java:185) @ org.springframework.boot.context.embedded.embeddedwebapplicationcontext.createembeddedservletcontainer(embeddedwebapplicationcontext.java:158) @ org.springframework.boot.context.embedded.embeddedwebapplicationcontext.onrefresh(embeddedwebapplicationcontext.java:132) ... 11 more disconnected target vm, address: '127.0.0.1:57558', transport: 'socket' process finished exit code 1

help me

spring spring-boot

ios - Embedded UICollectionView not getting didSelectItemAtIndexPath calls -



ios - Embedded UICollectionView not getting didSelectItemAtIndexPath calls -

i have collection view placed in container view can utilize separate controller it. info loads , displayed perfectly. don't didselectitematindexpath calls, though made sure set same controller serve info source , delegate. drives me crazy calls shouldhighlightitematindexpath , didhighlightitematindexpath. explicitly set allowsselection , allowsmultipleselection yes. how possible don't selection functionality? wasted several hours on this, , appreciate suggestions. thanks!

ios uicollectionview

c# - Could not find default endpoint element that references contract ' -



c# - Could not find default endpoint element that references contract &#39; -

i have created wcf webservice, while refer other web service showing error "could not find default endpoint element references contract '"..

my webconfig is

<service name="eenadumobilefeedtamil.eenadutamilcomments" behaviorconfiguration="servicebehaviour"> <endpoint address="" binding="webhttpbinding" contract="eenadumobilefeedtamil.ieenadutamilcomments" behaviorconfiguration="web"> </endpoint> </service> <behaviors> <endpointbehaviors> <behavior name="web"> <webhttp /> </behavior> </endpointbehaviors> <servicebehaviors> <behavior name="servicebehaviour"> <servicemetadata httpgetenabled="true" /> <servicedebug includeexceptiondetailinfaults="false" /> </behavior> <behavior name=""> <servicemetadata httpgetenabled="true" /> <servicedebug includeexceptiondetailinfaults="false" /> </behavior> </servicebehaviors> </behaviors>

c# wcf

c# - Why is it so difficult to find the printer status in windows? -



c# - Why is it so difficult to find the printer status in windows? -

using c# - i'm trying find list of printers local , online (i.e. connected , ready take print requests)

i know printer driver works - jobs wait until printer online, need find specific online. these available windows .net framework doesn't seem accurately expose online.

i'm trying utilize lots of different methods , none seem accurately work

// list of available printers. var printserver = new printserver(); var printqueues = printserver.getprintqueues(new[] { enumeratedprintqueuetypes.local, enumeratedprintqueuetypes.connections }); foreach (printqueue printqueue in printqueues) { console.writeline(printqueue.isoffline); // works isoffline, doesn't tell online - , it's not inverse relationship }

very frustrating - help appreciated.

should add together i'm using windows 8.1, , solution should work win 7+

edit:

so given next collection of printers :

i expect see along lines of

getting printers send onenote 2013 : online pack1 : offine microsoft xps document author : online fax : online epsonb12b28 (xp-412 413 415 series) : offine brother mfc-9970cdw printer : online

but reported online on status see

i have queried every conceivable windows device either native driver or using windows management instrumentation (wmi) classes.

to started, take read of article c# source: http://www.codeproject.com/articles/80680/managing-printers-programatically-using-c-and-wmi

also, not in c# vb, quick glance info on same subject here: http://msdn.microsoft.com/en-us/library/aa394598(v=vs.85).aspx

full wmi reference here: http://msdn.microsoft.com/en-us/library/aa394572(v=vs.85).aspx

cheers , luck!

c# .net wpf windows printing

c# - Failed To Create Assembly in MS SQL SERVER -



c# - Failed To Create Assembly in MS SQL SERVER -

i trying implement routing funcationality in ms sql server 2012 using prospatial tutorial, created c# class , build dll file.

using system; using system.collections.generic; using system.linq; using system.text; using microsoft.sqlserver.server; using microsoft.sqlserver.types; namespace prosqlspatial.ch14 { public partial class userdefinedfunctions { [microsoft.sqlserver.server.sqlfunction] public static sqlgeometry geometrytsp(sqlgeometry placestovisit) { // convert supplied multipoint instance list<> of sqlgeometry points list<sqlgeometry> remainingcities = new list<sqlgeometry>(); // loop , add together each point list (int = 1; <= placestovisit.stnumgeometries(); i++) { remainingcities.add(placestovisit.stgeometryn(i)); } // start tour first city sqlgeometry currentcity = remainingcities[0]; // begin geometry sqlgeometrybuilder builder = new sqlgeometrybuilder(); builder.setsrid((int)placestovisit.stsrid); builder.begingeometry(opengisgeometrytype.linestring); // begin linestring first point builder.beginfigure((double)currentcity.stx, (double)currentcity.sty); // don't need visit city 1 time again remainingcities.remove(currentcity); // while there still unvisited cities while (remainingcities.count > 0) { remainingcities.sort(delegate(sqlgeometry p1, sqlgeometry p2) { homecoming p1.stdistance(currentcity).compareto(p2.stdistance(currentcity)); }); // move closest destination currentcity = remainingcities[0]; // add together city tour route builder.addline((double)currentcity.stx, (double)currentcity.sty); // update list of remaining cities remainingcities.remove(currentcity); } // end geometry builder.endfigure(); builder.endgeometry(); // homecoming constructed geometry homecoming builder.constructedgeometry; } }; }

i enabled clr , when seek create assembly using above created dll:

create assembly geometrytsp 'd:\routing\my example\geometrytsp\geometrytsp\bin\debug\geometrytsp.dll' permission_set = external_access; go

i'm getting "failed create appdomain" error this:

msg 6517, level 16, state 1, line 2 failed create appdomain "master.dbo[ddl].12". exception has been thrown target of invocation.

what should reason?

try remove neamespace section

namespace prosqlspatial.ch14 { }

sql server utilize default namespace

c# sql .net sql-server clr

Session getting destroyed when ajax call is made in rails application -



Session getting destroyed when ajax call is made in rails application -

i have ruby on rails site. applicationcontroller looks like

class applicationcontroller < actioncontroller::base protect_from_forgery before_filter :handle_cookie default_marketplace = 1 def handle_cookie if (session[:isimpersonation].nil?) puts "initilized 0" session[:isimpersonation] = 0 end end

i initializing variable isimpersonation in session object if nil. when normal request made (i.e non-ajax) variable initialized 1 time once i.e. session object retains variable isimpersonation.

but when create ajax phone call like:

$.ajax({ url : "/a/fetch", type : "post", info : { rundate : $('#rundate_select :selected').val(), id : idval, mp : mpval }, beforesend : function(xhr) { xhr.setrequestheader('x-csrf-token', $('meta[name="csrf-token"]') .attr('content')); }, success : function(data) { var $elem = $('<div>').html(data); $("#overall").html( $elem.find('#overall').html()); }, error : function(data) { } });

during ajax phone call variable in session re-initialized. searched , followed post: rails not reloading session on ajax post.

but, not working me. thought missing?

finally, got working. missing:

<%= csrf_meta_tags %>

in tag of layout file i.e. application.html.erb

ruby-on-rails ruby-on-rails-3 session

opengl es - Cocos2d - only one scheduler called -



opengl es - Cocos2d - only one scheduler called -

i'm trying trace 2 paths on screen through series of vertices (connect dots style). each should different color, , each has own list of vertices.

i started out creating class can trace path, creating 2 instances of class, 1 each path. overrode draw method. worked fine except reason first instance of class called draw method. figured problem opengl did 1 time again using ccdrawnode , still had same bug.

only 1 instance (blackpath) draws objects on screen. in fact scheduled updateendpoint: method not called whitepath object, although created.

my drawer.m class:

const float size = 10; const float speed = 5; cccolor4f pathcolor; int numpoints; nsarray * path; cgpoint endpoint; @implementation drawer -(id)initwithpath:(nsarray*)p andcolorisblack:(bool)isblack{ self = [super init]; // record input path = p.copy; pathcolor = ccc4f(1.0f, 1.0f, 1.0f, 1.0f); if(isblack){ pathcolor = ccc4f(0.0f, 0.0f, 0.0f, 1.0f); } // set variables numpoints = 1; endpoint = [[path firstobject] position]; nslog(@"drawer initialized path of length %u , color %hhd (isblack)", p.count, isblack); [self schedule:@selector(updateendpoint:)]; homecoming self; } -(void)updateendpoint:(cctime)dt{ nslog(@"(%f, %f, %f, %f) path", pathcolor.r, pathcolor.g, pathcolor.b, pathcolor.a); [self drawdot:endpoint radius:size color:pathcolor]; cgpoint dest = [[path objectatindex:numpoints] position]; float dx = dest.x - endpoint.x; float dy = dest.y - endpoint.y; // new coords current + distance * sign of distance float newx = endpoint.x + min(speed, fabsf(dx)) * ((dx>0) - (dx<0)); float newy = endpoint.y + min(speed, fabsf(dy)) * ((dy>0) - (dy<0)); endpoint = ccp(newx, newy); if(endpoint.x == dest.x && endpoint.y == dest.y){ if(numpoints < path.count-1){ numpoints+=1; } else{ [self unschedule:@selector(updateendpoint:)]; } } }

and here instantiate objects:

-(id) init{ self = [super init]; [self addallcards]; [self addscore]; xshrinkrate = [[grid getinstance] sqwidth] / shrinktime; yshrinkrate = [[grid getinstance] sqheight] / shrinktime; droplist = [nsmutablearray new]; notdroplist = [nsmutablearray new]; [self schedule:@selector(dropcard:) interval:0.075]; [self schedule:@selector(shrinkcards:)]; drawer * whitepath = [[drawer alloc] initwithpath:[[score getinstance] whitepath] andcolorisblack:false]; [self addchild:whitepath]; drawer * blackpath = [[drawer alloc] initwithpath:[[score getinstance] blackpath] andcolorisblack:true]; [self addchild:blackpath]; homecoming self; }

change (non-const) global variables instance variables of class so:

@implementation drawer { cccolor4f pathcolor; int numpoints; nsarray * path; cgpoint endpoint; }

opengl-es cocos2d-iphone

javascript - How to filter/search multidimensional array of objects? -



javascript - How to filter/search multidimensional array of objects? -

i have info construction below:

var options = [{ name: "option one", foo: "bar", values: [{ name: "value one", value: "value", options: [{ name: "option two", values: [{ name: "value two", value: "value", options: [] }] }] }] }, { name: "option three", values: [{ name: "value three", value: "value", options: [] }] }];

i need flatten it, filter out properties don't want , maintain knowledge of depth of each object below info structure:

var flattenedfilteredoptions = [{ depth: 0, name: "option one", values: [{ name: "value one", value: "value" }] }, { depth: 1, name: "option two", values: [{ name: "value two", value: "value" }] }, { depth: 0, name: "option three", values: [{ name: "value three", value: "value" }] }];

so want properties of name, values, , value in output. can point me in right direction start or have solution?

thanks all, here did, maintain in mind configuring properties filter isn't quite in configurable, recursion worked:

function flattenoptions(optionsarray, depth, flattenedoptions) { depth = depth || 0; flattenedoptions = flattenedoptions || []; (var = 0; < optionsarray.length; i++) { var alternative = optionsarray[i]; var nextdepth = depth + 1; var flattenedoption = { depth: depth, name: option.name, values: flattenvalues(option.values, nextdepth, flattenedoptions) }; flattenedoptions.push(flattenedoption); } homecoming flattenedoptions; } function flattenvalues(valuesarray, nextdepth, flattenedoptions) { var values = []; (var = 0; < valuesarray.length; i++) { var value = valuesarray[i]; values.push({ name: value.name, value: value.value }); if (value.options.length > 0) { flattenoptions(value.options, nextdepth, flattenedoptions); } } homecoming values; }

javascript arrays javascript-objects

c# - Loop over a FormCollection to get radiobutton SelectedAnswers -



c# - Loop over a FormCollection to get radiobutton SelectedAnswers -

how can values of radio buttons named predicatively questions[i] using form collection?

in form collection

questions[0].objectid questions[0].selectedanswer questions[1].objectid questions[1].selectedanswer questions[2].objectid questions[2].selectedanswer 3 - 13 ... etc... questions[14].objectid questions[14].selectedanswer (a bunch of other stuff)

in controller

[httppost] public actionresult postresults(formcollection form) { list<selectedanswer> selectedanswers = new list<selectedanswer>(); (int = 0; < 15; i++) { //this part not working... selectedanswers.add(new selectedanswer() { questionid = form["questions"][i].objectid; answerid = form["questions"][i].selectedanswer} } //continue other stuff }

my ultimate goal save selected values database.

got working

(int = 0; < 15; i++) { long x = int64.parse(form[string.format("questions[{0}].objectid", i)]); long y = int64.parse(form[string.format("questions[{0}].selectedanswer", i)]); if (x > 0 && y > 0) { selectedanswers.add(new selectedanswer() { questionid = x, answerid = y }); } }

c# asp.net-mvc model-view-controller radio-button formcollection

haskell - Passing different number of the arguments -



haskell - Passing different number of the arguments -

i have this:

(aeson.object jsonobject) -> case (hashmap.lookup "high" jsonobject, hashmap.lookup "low" jsonobject) of (just (string val), (string val2)) -> [val, val2] _ -> error "couldn't both keys"

i'd able pass "high" , "low" arguments , pattern matching on them retrieve actual values json. and, of course, number of such arguments can vary.

parsejson :: [string] -> [string] parsejson keys = (aeson.object jsonobject) -> case (?????) of (?????) -> ???? _ -> error "couldn't retrieve keys"

how can this?

try this. assume (aesonobject.jsonobject) refers case of existing case expression, it's not syntactically valid otherwise.

import control.monad ( sequence ) getstring (just (string value)) = value getstring _ = nil parsejson :: [string] -> [string] parsejson keys = case ... of (aeson.object jsonobject) -> case sequence (map (getstring . flip hashmap.lookup jsonobject) keys) of values -> values _ -> error "couldn't retrieve keys"

flip hashmap.lookup jsonobject gives lookup function key value (which maybe. composing getstring gives succeeds on string values, in same way existing inline pattern-match does.

finally, sequence on maybe monad turns [maybe string] maybe [string], returning just output if elements of input just.

haskell

dotnetnuke - Source to learn DNN basics developer -



dotnetnuke - Source to learn DNN basics developer -

i have gone through many links , couldn't find suitable site learning dotnetnuke basics after deployment. can suggest ... basic developer. how start, extension, modules, usability

rigin

the best place start http://www.dnnsoftware.com/wiki/page/module-development

while video tutorial series there old, best thing out there @ time. though might biased, created it.

dotnetnuke

ruby - My rack middleware in Rails 4 not executing -



ruby - My rack middleware in Rails 4 not executing -

i trying build cms application using ruby on rails 4.inorder proper controller.i need preprocess querystring before using it in match method shown below

# config/routes.rb cms::application.routes varparameter=env["query_string"] @controller=preprocessqstring(varparameter) match '/cms/home', to: 'login#show', via: [:get, :post] match 'cms/:content(/:action(/:id(.:format)))',to: @controller+'#show', via: [:get, :post] end

to set env["query_string"] using next rack middleware

# lib/httpvariables.rb require 'rack' class httpvariables def initialize(app) @app = app end def call(env) @status, @headers, @response = @app.call(env) request=rack::request.new(env) env["request_uri"]=request.env["request_uri"] env["query_string"]=request.env["query_string"] env["server_port"]=request.env["server_port"] env["server_protocol"]=request.env["server_protocol"] [@status, @headers, self] end end

i have added line in application.rb

# config/application.rb config.middleware.use rack::httpvariables

to suprise if seek start rails server it's failing showing:

mundile@mundile-hp:~/ror-workspace/workspace/cms$ rails server => booting webrick => rails 4.1.1 application starting in development on http://0.0.0.0:3000 => run `rails server -h` more startup options => notice: server listening on interfaces (0.0.0.0). consider using 127.0.0.1 (--binding option) => ctrl-c shutdown server exiting /home/mundile/ror-workspace/workspace/cms/config/routes.rb:68:in `block in <top (required)>': undefined method `+' nil:nilclass (nomethoderror)

i need help out there identify cause of problem. seems env["query_string"] giving nil why ? thanks.

i changed middleware code to:

# lib/httpvariables.rb require 'rack' class httpvariables def initialize(app) @app = app end def call(env) request=rack::request.new(env) env["request_uri"]=request.env["request_uri"] env["query_string"]=request.env["query_string"] env["server_port"]=request.env["server_port"] env["base_url"]=request.base_url @app.call(env) end end

this works charm. have used code reply question: rails access request in routes.rb dynamic routes

ruby ruby-on-rails-4 rack

python - Why do I get an AttributeError when I use scatter() but not when I use plot() -



python - Why do I get an AttributeError when I use scatter() but not when I use plot() -

i wish plot using matplotlib/pylab , show date , time on x-axis. this, i'm using datetime module.

here working code required-

import datetime pylab import * figure() t2=[] t2.append(datetime.datetime(1970,1,1)) t2.append(datetime.datetime(2000,1,1)) xend= datetime.datetime.now() yy=['0', '1'] plot(t2, yy) print "lim is", xend xlim(datetime.datetime(1980,1,1), xend)

however, when utilize scatter(t2,yy) command instead of plot (t2,yy), gives error:

attributeerror: 'numpy.string_' object has no attribute 'toordinal'

why happening , how can show scatter along plot?

a similar question has been asked before as- attributeerror: 'time.struct_time' object has no attribute 'toordinal' solutions don't help.

if utilize int or float type yy don't error scatter():

yy = [0, 1]

python matplotlib python-datetime

vb.net - Function from a referenced library which has function pointers as parameters -



vb.net - Function from a referenced library which has function pointers as parameters -

update: changed question match updated code , more specific problem.

i have no experience working vb.net or visual studio, , limited experience c. have been trying larn function pointers , delegates still don't understand them.

i writing project in vb.net makes calls methods dll file.

c code dll file:

typedef unsigned char byte; typedef unsigned short word; typedef unsigned long dword; typedef void (__stdcall *fp_setbaud)(word); typedef short (__stdcall *fp_get)(word); typedef void (__stdcall *fp_put)(byte); typedef void (__stdcall *fp_flush)(void); typedef void (__stdcall *fp_delay)(word); byte __stdcall initrelay(fp_setbaud _setbaud, fp_get _get, fp_put _put, fp_flush _flush, fp_delay _delay) { ... } byte __stdcall readrelay(void){ ... }

vb.net module code:

declare function initrelay lib "z:\devel\relayapi\debug\relayapi.dll" (byval setbaud action(of short), byval getit func(of short, short), byval putit action(of short), byval flushit action, byval delay action(of short)) byte declare function readrelay lib "z:\devel\relayapi\debug\relayapi.dll" () byte public sub setbaud(byval baud short) ... end sub public function getit(byval timeout short) short ... end function public sub putit(byval dat short) ... end sub public sub flushit() ... end sub public function delayms(byval ms short) short ... end function

vb.net form code:

dim byte phone call initrelay(addressof modulecode.setbaud, addressof modulecode.getit, addressof modulecode.putit, addressof modulecode.flushit, addressof modulecode.delayms) = readrelay()

the error getting when phone call a = readrelay() within vb.net code. error appears on each 1 of parameters , says following:

an unhandled exception of type 'system.accessviolationexception' occurred

the readrelay function uses of functions passed initrelay function. initrelay called prior readrelay , gives me no errors. assuming error still has how passing function pointers initrelay function.

i have been using this website seek figure out type conversions still don't know do.

does have info on should doing phone call these functions?

edit

new delegate declarations suggested below:

private setbauddelegate new action(of short)(addressof modcommstuff.setbaud) private getitdelegate new func(of short, short)(addressof modcommstuff.getit) private putitdelegate new action(of short)(addressof modcommstuff.putit) private flushitdelegate new action(addressof modcommstuff.flushit) private delayitdelegate new action(of short)(addressof modcommstuff.delayms) .... phone call initrelay(setbauddelegate, getitdelegate, putitdelegate, flushitdelegate, delayitdelegate)

i think need pin delegates not garbage collected.

dim handle gchandle = gchandle.alloc(objecttopin, gchandletype.pinned)

don't forget free object after done using .free

handle.free()

more info available @ website. http://manski.net/2012/06/pinvoke-tutorial-pinning-part-4/

update 1

after reading more looks pinning delegates not allowed, still have maintain delegate in memory. seek creating instance variables delegates , keeping them in fields defined in form's code. should plenty maintain delegates getting garbage collected , maintain unmanaged "stubs" getting cleaned up.

along same lines, managed delegates can marshaled unmanaged code, exposed unmanaged function pointers. calls on pointers perform unmanaged managed transition; alter in calling convention; entry right appdomain; , necessary argument marshaling. unmanaged function pointer must refer fixed address. disaster if gc relocating that! leads many applications create pinning handle delegate. unnecessary. unmanaged function pointer refers native code stub dynamically generate perform transition & marshaling. stub exists in fixed memory outside of gc heap.

however, application responsible somehow extending lifetime of delegate until no more calls occur unmanaged code. lifetime of native code stub straight related lifetime of delegate. 1 time delegate collected, subsequent calls via unmanaged function pointer crash or otherwise corrupt process.

update 2 here illustration actual code. did takes single argument, if need adjusted additional arguments allow me know.

private sub initrelay(d1 action(of short)) 'this sub represents initrelay function exported library. wouldn't have straight in code. end sub private sub setbaud(baud short) 'this setbaud sub in module end sub 'this in form code, @ class level (outside subs) private setbauddelegate new action(of short)(addressof setbaud) 'this sub whatever sub in code calls initrelay private sub test() initrelay(setbauddelegate) end sub

vb.net delegates visual-studio-2013 function-pointers