Thursday, 15 September 2011

c++ - Command Button Control MFC -



c++ - Command Button Control MFC -

i'm working on chess game in vs 2013. when promote pawn piece, inquire user come in selection using command button control. now, i've designed new dialog in resource script. don't know how input of button clicked. please tell me how implement it.

idd_promotion dialogex 0, 0, 287, 123 style ds_setfont | ds_modalframe | ws_popup | ws_caption | ws_sysmenu caption "dialog" font 8, "microsoft sans serif", 400, 0, 0x0 begin command "rook",idc_rook,"button",bs_commandlink | ws_tabstop,48,37,90,25 command "bishop",idc_bishop,"button",bs_commandlink | ws_tabstop,48,72,90,25 command "queen",idc_queen,"button",bs_commandlink | ws_tabstop,170,37,100,25 command "knight",idc_knight,"button",bs_commandlink | ws_tabstop,170,72,90,25 groupbox "promote to",idc_promote,24,17,236,91 end

c++ mfc

Nuget handling of libraries in Visual Studio 2013 -



Nuget handling of libraries in Visual Studio 2013 -

we have set of functionality in regular dll file, in nuget package. naturally, want pull using nuget instead of having download , update dll:s manually. projects handled in vs 2013, have access through bundle manager.

now, need go on projects in source tree update reference nuget reference instead of old dll reference. can on solution level using bundle manager, since there several dozens of solutions , on hundred projects i'd rather not manually.

is there way automate this? is, iterate through source tree, find every .sln file , update references in underlying project files?

you can writing little c# program. install nuget.core , nuget.visualstudio bundle programme utilize functions in nuget.core.dll , nuget.visualstudio.dll, plus dte functions.

visual-studio visual-studio-2013 nuget

Storing objects in an array for retirevel and modification of instantiated objects (Java) -



Storing objects in an array for retirevel and modification of instantiated objects (Java) -

hello new java , taking course of study in college studies. assignment doing polymorphism, , suppose create 4 objects: 2 without arguments, , 2 arguments.

personlocation personlocation = new personlocation(); persondata persondata = new persondata(); personlocation personlocationoverloaded = new personlocation("hamilton"); persondata persondataoverloaded = new persondata("frizzle", "289-549-1045");

now sure did properly, next part confused. asks "store objects in array retrieval , modification of instantiated objects". not sure how go this. thinking:

personlocation[] personlocation = new personlocation[4]; persondata[] persondata = new persondata[4];

but doesn't create sense because have 8 objects. thought of putting them together:

string[] employees = new string[4]; for(int = 0; < 2; i++) { employees[i] = personlocation; } for(int = 2; < 4; i++) { employees[i] = persondata; }

this seems create more sense because have superclass of location , subclass of data.

any pointers in right direction creating array of objects retrieval , modification of instantiated objects of great help.

if instructor looking have of objects in same array, need rely on fact objects in java extend super object called "object". so, in case, can create new array of type "object", in can mix , match objects set in (putting both info , locations in it). then, when looping through array, can utilize java keyword "instanceof", check if either personlocation or persondata. illustration wrote shown here:

public static void main (string args[]) { personlocation pl1 = new personlocation(); personlocation pl2 = new personlocation(); persondata pd1 = new persondata(); persondata pd2 = new persondata(); object[] array = new object[4]; array[0] = pl1; array[1] = pd1; array[2] = pl2; array[3] = pd2; for(object o : array){ if(o instanceof personlocation){ personlocation temppersonlocation = (personlocation) o; system.out.println(temppersonlocation); } if(o instanceof persondata){ persondata temppersondata = (persondata) o; system.out.println(temppersondata); } } }

which gave me output:

this personlocation persondata personlocation persondata

if have mutual interface or super class (such persondata inherits person or persondata extends person), utilize super class create single array such first illustration well. alter type of array "object" whatever interface/super class is.

it worth noting, in illustration create 2 arrays (one each object type), there no need instantiate size of 4 in each array, since have 2 of each type of objects. instead can instantiate size 2, , result in 4 objects total, not 8 had mentioned. illustration of is:

public static void main(string args[]) { personlocation pl1 = new personlocation(); personlocation pl2 = new personlocation(); persondata pd1 = new persondata(); persondata pd2 = new persondata(); personlocation[] personlocation = new personlocation[2]; persondata[] persondata = new persondata[2]; personlocation[0] = pl1; personlocation[1] = pl2; persondata[0] = pd1; persondata[1] = pd2; (personlocation pl : personlocation) { system.out.println(pl); } (persondata pd : persondata) { system.out.println(pd); } }

resulting in output of:

this personlocation personlocation persondata persondata

my guess if instructor has not taught super classes or instanceof keyword, looking sec illustration have showed.

java arrays object polymorphism

ruby on rails - Mechanize: not logged in the site -



ruby on rails - Mechanize: not logged in the site -

i'm trying authorise other site gem mechanize

my code:

def login_zenit agent = mechanize.new agent.get('http://mobile.zenitbet.com/') |p| f = p.forms.first f.login = 'login' f.fields[1].value = 'password' f.submit end agent.get('http://mobile.zenitbet.com/') redirect_to root_url end

the problem when run login_zenit doesn't work - i'm not authorising site in web browser. although if run code in rails console works perfectly. did create mistake? maybe there problem redirect_to root_url?

thanks!

in general not possible. work visiting app need set appropriate cookies mobile.zenibet.com.

you have cookie values - they're within mechanize object, if extract them wouldn't able set them on right domain. if app beingness served foo.com browser allow set cookies on foo.com or subdomain of it, won't allow set cookies on arbitrary domain (see point 5 in section 5.3 of rfc)

unless app runs on subdomain of zenibet.com think out of luck

ruby-on-rails ruby ruby-on-rails-4 mechanize

mysql - Can I use the same foreign key constraint in two different tables? -



mysql - Can I use the same foreign key constraint in two different tables? -

i trying create database work. have 2 different types of users: internal , external. each type has different properties created 2 separate tables them. in internal table have next fields:

f_name varchar(32), l_name varchar(32), empl_status_id int, admin_grp_id int, reliab_status_id int, supv_id int

and external table has following:

f_name varchar(32), l_name varchar(32), email varchar(32), phone varchar(20), org_id int, supv_id int

i realize create separate table contains names of users , foreign key pointing either internal or external, aside, added foreign key constraint internal table refers supv_id internal user. called fk_supv_id. when tried same external user table, got error 1005 (hy000).

at first couldn't figure out problem when tried doing different name, worked (i.e. instead of calling fk_supv_id internal, called fk_xtsupv_id).

so question is, right way this? it's same foreign key in 2 different tables. in both cases refers internal user. there way without having 2 different names? or should opt table of names thought , add together supv_id constraint table along f_name, l_name, , user_type?

advice , suggestions appreciated,

thanks! :)

there columns , there foreign keys (fks) , there constraints.

you can have column name in table regardless of other tables.

a fk referencing table , column set , referenced table , column set. names identify fk. it's conceptual thing database.

a fk constraint, beingness constraint, thing name must unique on database. has , enforces associated fk, namely 1 described in declaration. can have multiple fk constraints in table enforcing same fk.

the dbms has automatic unique names fk constraints. eg name part plus number part constraint numberth fk constraint of table name. can have same nameless fk constraint definition text multiple times in table , in multiple tables, each different fk constraint. (the ones within given table enforce same fk.)

you should have unique naming scheme when want name them. referencing , referenced table names should involved, , when necessary distinguishing column names.

confusingly, fk when mean fk constraint.

when "it's same foreign key in 2 different tables," misuses terms. there 2 different fks involved, , corresponding fk constraints. mean maybe "it's same referencing columns , referenced table , columns in both fk constraints" or "it's same text re referencing in both table declarations' fk constraint declarations". fk constraint names must unique.

when "in both cases refers internal user," confirming type and/or table of referenced column same both fk constraints. different fk constraints different fks.

mysql database foreign-keys foreign-key-relationship

Plotting "Points" on Google Maps using JavaScript API -



Plotting "Points" on Google Maps using JavaScript API -

i'm loading extensive set of points (latitude, longitude pairs) google map. problem google maps plots these points markers (the default kind), while i'd rather have each point plotted "point" in map: https://www.google.com/maps/search/atm/@54.0260702,-1.6780445,5z

rather marker shown here (on cimarron national park): https://www.google.com/maps/dir/great+bend,+ks,+usa/cimarron+national+grassland,+242+highway+56,+elkhart,+ks+67950,+united+states/@37.7162446,-101.3770814,8z/data=!3m1!4b1!4m13!4m12!1m5!1m1!1s0x87a38bb5b59e293d:0x32155928d84780ee!2m2!1d-98.7648073!2d38.3644567!1m5!1m1!1s0x8708c3c3259cc53b:0x8109b72736458f11!2m2!1d-101.79!2d37.124167

any thought how can achieved through google maps javascript api ?

a quick , dirty illustration (took documentation , modified it):

map.data.setstyle(function(feature) { homecoming /** @type {google.maps.data.styleoptions} */({ icon: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png" }); });

working example

javascript google-maps google-maps-api-3

java - Get a resource using getResource() -



java - Get a resource using getResource() -

i need resource image file in java project. i'm doing is:

url url = testgametable.class.getclass(). getclassloader().getresource("unibo.lsb.res/dice.jpg");

the directory construction following:

unibo/ lsb/ res/ dice.jpg test/ ..../ /* other packages */

the fact file doesn't exist. have tried many different paths, couldn't solve issue. hint?

testgametable.class.getresource("/unibo/lsb/res/dice.jpg"); leading slash denote root of classpath slashes instead of dots in path you can phone call getresource() straight on class.

java resources getresource

python - How to parse a list of SearchResults? -



python - How to parse a list of SearchResults? -

i using app engine search api , i'm trying extract list of doc_ids. here result of query:

search.searchresults(results=[ search.scoreddocument(doc_id=u'-8853541246119947279', rank=0), search.scoreddocument(doc_id=u'-8853541246119948097', rank=0), search.scoreddocument(doc_id=u'-8853541246119946461', rank=0), search.scoreddocument(doc_id=u'51713103325273223', rank=0), search.scoreddocument(doc_id=u'5587798675278816831', rank=0), search.scoreddocument(doc_id=u'-8853541246119946464', rank=0), search.scoreddocument(doc_id=u'-3372400065395745350', rank=0), search.scoreddocument(doc_id=u'5587798675278815364', rank=0) ], number_found=8l)

how extract doc_ids list?

read through documents more:

results = index.search(search.query( #query , options here, including ids_only=true )) doc_ids = [tmp_result.doc_id tmp_result in results]

python google-app-engine

javascript - call 2 different function.js file in wordpress, depending on page -



javascript - call 2 different function.js file in wordpress, depending on page -

i'm trying find how can load 2 different function.js depending of page.

when on "home", want load "function_2.js", , on other pages of website original "function.js".

i need alter in function.php can't figure out what...

can help me ?

thanks lot

check current url

get current url within handle_script() function , depending on path, add together function.js or function_2.js script variable.

javascript php wordpress

android - How to read URL from Urban Airship push notifications -



android - How to read URL from Urban Airship push notifications -

in android project trying send force notifications using urban airship rich composer. receive notifications , able perform actions when notification clicked.

however, sending url message in ua rich composer. how can read url in broadcast receiver function? there way fetch intent? next code code snippet:

public void onreceive(context context, intent intent) { if (intent.getaction().equals(pushmanager.action_push_received)) { // force received } else if (intent.getaction().equals(pushmanager.action_notification_opened)) { // force opened intent launch = new intent(intent.action_main); launch.setclass(uairship.shared().getapplicationcontext(), myactivity.class); launch.setflags(intent.flag_activity_new_task); uairship.shared().getapplicationcontext().startactivity(launch); } }

any help appreciated.

thanks, mukul

android push-notification

python - Creating a sklearn.linear_model.LogisticRegression instance from existing coefficients -



python - Creating a sklearn.linear_model.LogisticRegression instance from existing coefficients -

can 1 create such instance based on existing coefficients calculated in different implementation (e.g. java)?

i tried creating instance setting coef_ , intercept_ straight , seems work i'm not sure if there's downwards side here or if might breaking something.

python scikit-learn logistic-regression

formula - Displaying Excel cell values in a comma-separated list -



formula - Displaying Excel cell values in a comma-separated list -

i have info in excel this:

column1 column2 ni-summer-2 parent ni-548 underneath kid ni-549 ni-550 ni-summer-1 parent ni-421 underneath kid ni-422

i need add together new column displays children in 1 string joined commas, so:

column1 column2 column3 ni-summer-2 parent ni-summer-2,ni-548,ni-549,ni-550 ni-548 underneath kid ni-549 ni-550 ni-summer-1 parent ni-421,ni-422 ni-421 underneath kid ni-422

(the values below each parent should comma-separated in next column.)

please help resolve this.

assuming blank row between entries.

create 2 columns d , e

in column e, set in e1 , re-create formula down:

=if(or(isblank(a2),isblank(a1)),a1,a1&","&e2)

in column d, set in d1 , re-create formula down:

=if(mid(a1,3,8)="-summer-",e1,"")

excel formula

c# - Web API token authentication with a custom user database -



c# - Web API token authentication with a custom user database -

i developing web api 2.1 service needs authenticate connecting clients (html5/js clients create , control). unfortunately, user info (username, password hashes, roles , much, much more info) stored in existing (sql server) database have read access. users database table created 5-6 years ago without reference security frameworks, it's custom format. i'm not allowed create changes either info or database structure.

inspired this article, rolled own token-based method of authenticating users, i'm lacking completeness , (re)assurance of using established security framework.

is there way integrate existing framework, e.g. oauth2, within current project given constraints mentioned above? don't know if makes difference, i'm self-hosting using owin.

edit: don't know why couple of people downvoted question - bad? it's genuine question far i'm concerned, , love have reply (even if it's "no, can't because..."). if people can explain reasons in comment, that'd appreciated.

this reply similar question. says:

make custom user class implements iuser define custom user store implements public class userstoreservice : iuserstore<customuser>, iuserpasswordstore<customuser> wire up

since reply pretty extensive provided basic steps... details here: how customize authentication own set of tables in asp.net web api 2?

this valuable content applies web api:

customizing asp.net authentication identity jumpstart

https://www.youtube.com/watch?v=uhfead2lqyw here version of link (since link reported dead): https://www.youtube.com/watch?v=zktseyrwr4o

hth

c# asp.net authentication asp.net-web-api web-api

objective c - iOS UItextfield reload after key hit -



objective c - iOS UItextfield reload after key hit -

i making simple application has textfield , textview whatever write in textfield updated in textview (both in single view, , root view). textfield updated every time nail key in keyboard. know delegate method "textfielddidediting" helps , helps when click on field or click back. want method invokes every time when nail in keyboard.

any help appreciated. i'm still learning ios

please utilize below textfield delegate method. easy , simple utilize appen , delete mechanism. can delete multiple characters selection. store newstring value textview

-(bool)textfield:(uitextfield *)textfield shouldchangecharactersinrange:(nsrange)range replacementstring:(nsstring *)string { nsmutablestring *newstring = [nsmutablestring stringwithstring:textfield.text]; if (range.length > 0) { [newstring replacecharactersinrange:range withstring:string]; } else { [newstring appendstring:string]; } nslog(@"%@",newstring); homecoming yes; }

ios objective-c

how to convert the type text of MySQL to String in java -



how to convert the type text of MySQL to String in java -

i have probleme in application. in fact not know how convert type text of mysql string in java ?? give thanks you.

string value = resultset.getstring("mytextcolumn");

or maybe so:

stringbuilder sb = new stringbuilder(); bufferedreader br = new bufferedreader( resultset.getclob("mytextclob").getcharacterstrean()); string line; while ((line = br.readline()) != null) { sb.append(line).append("\r\n"); } value = sb.tostring();

best guess

reader in = resultset.getcharacterstream("mycolumn");

see resultset.getcharacterstream.

aha!

as understand there problem in code like:

final string sql = "select description annonce"; seek (preparedstatement stm = connection.preparestatement(sql); resultset rs = stm.executequery()) { while (rs.next()) { string description = rs.getstring("description"); system.out.println("# " + description); } } grab (sqlexception e) { e.printstacktrace(system.out); }

there null returned. description indeed can null, if database field description can (sql) null, prevent that:

create table annonce ( description text not null default ''

or skipt values:

final string sql = "select description annonce description not null";

java mysql string text

Get Distinct rows From C# Data Table with LINQ Comprehensive Query -



Get Distinct rows From C# Data Table with LINQ Comprehensive Query -

i have info table of c#.just want distinct row list on column property of info table.say , have info table columns property x,y & z.i have rows 200 in info table have same x values. want have distinct row based on x column property linq comprehensive query binding list of model (i have).

i have model

public class model { public model(string x) { x= x; } public int x{ get; set; } public string y{ get; set; } public decimal z{ get; set; } }

and stuck comprehensive query.it should give distinct list not working expected.

list<model> modellist= new list<model>(); modellist= (from item in response.asenumerable() select new { description = datatableoperationhelper.getstringvalue(item, "description") }).distinct().select(m => new model(m.description)).tolist(); where datatable response ( has 200 rows) , 'description' 1 of column property.

it gives list not distict value of 'description' property.is there missing consider ? stuck .

it's because code

new { description = datatableoperationhelper.getstringvalue(item, "description") }

creates new object property "description" , compares reference not value of "description".

try this:

modellist = response.asenumerable() .select(item=>datatableoperationhelper.getstringvalue(item, "description")) .distinct() .select(x => new consumablesviewmodel(x.description)) .tolist();

c# linq datatable

java - Setting event listener for two JTextArea's -



java - Setting event listener for two JTextArea's -

i developing image processing software (just fun) , 1 of features has image resizing option. window pops up, 2 jtextarea components desired image width , height resizing. there jcheckbox keeping aspect ratio if user desires it. problem is. when check box selected , user supposedly inputs either width or height first. want other text area update accordingly every time alter made maintain ar. have developed code deals this, not provide want due lack of understanding listener component should assign.

code:

string height, width; if (checkboximage.isselected()){ // aspect ratio = width / height width = widtharea.gettext(); height = heightarea.gettext(); double aspectratio = (double) images.get(tabbedpane.getselectedindex()).getwidth() / images.get(tabbedpane.getselectedindex()).getheight(); /** * do, update width, height area * closest user input */ if(heightarea.gettext().length() != 0 && heightarea.gettext().length() <= 5 && heightarea.gettext().charat(0) != '0'){ //parsing string integer try{ int heightnum = integer.parseint(height); int widthnum = (int) math.round(aspectratio * heightnum); widtharea.settext(string.valueof(widthnum) ); widtharea.updateui(); frameimgsize.repaint(); } catch(numberformatexception e1){joptionpane.showmessagedialog(error,e1.getmessage(),"error", joptionpane.error_message);} } //width has been entered first else if(widtharea.gettext().length() != 0 && widtharea.gettext().length() <= 5 && widtharea.gettext().charat(0) != '0'){ try{ int widthnum = integer.parseint(width); int heightnum = (int) math.round(aspectratio * widthnum); heightarea.settext(string.valueof(heightnum) ); heightarea.updateui(); frameimgsize.repaint(); } catch(numberformatexception e1){joptionpane.showmessagedialog(error,e1.getmessage(),"error", joptionpane.error_message);} } }

is ever valid have non-numeric values in width , height fields?

if not, utilize jspinners or jformattedtextfields instead of jtextfields. if so, (say illustration allow "units" entered width , height) should attach documentlistener jtextfields monitor changes content of underlying text documents. here's example:

widthfield.getdocument().adddocumentlistener(new documentlistener() { public void changedupdate(documentevent e) { update(); } public void removeupdate(documentevent e) { update(); } public void insertupdate(documentevent e) { update(); } // method handles document alter event public void update() { if( aspectcheckbox1.isselected() ) { // parse width , height, // constrain height aspect ratio , update here } } });

you'd add together similar documentlistener heighttextfield.

note if utilize jtextfields need parse contents, read units (where applicable) , handle numberformatexceptions in case user enters invalid numeric values.

to reply question add together handlers...

the update of width should happen when there document alter height gui element. update of height should happen when there document alter width gui element.

you'll need gracefully handle split 0 errors (or restrict input greater 0), perform calculations using doubles , preferably utilize math.round() best integer values preserving aspect.

ie:

int calculateheight(int width, double aspect) { if( aspect <= 0.0 ) { // handle error status } homecoming (int)math.round(width / aspect); }

for tracking aspect ratio, store in fellow member variable , add together actionlistener jcheckbox... because updating target aspect ratio on every value alter of width , height fields result in aspect-ratio "creeping" due integer round-off.

here's illustration on tracking aspect every time aspect ratio check state changes:

private double aspect = 1.0; aspectcheckbox.addactionlistener(new java.awt.event.actionlistener() { public void actionperformed(java.awt.event.actionevent evt) { preserveaspectactionperformed(evt); } }); private void preserveaspectactionperformed(java.awt.event.actionevent evt) { seek { double w = double.parsedouble(widthfield.gettext()); double h = double.parsedouble(heightfield.gettext()); aspect = w / h; } catch(numberformatexception ex) { // ... error occurred due non-numeric input // (use jspinner or jformattedtextfield avoid this) } }

the of import thing avoid using wrong input type job:

jtextareas multiline text jtextfields single line text jformattedtextfields text constrained specific format jspinners numeric entry.

hope helps you.

java swing jtextarea event-listeners

Deleted Profile shows in profile management tool of IBM Websphere -



Deleted Profile shows in profile management tool of IBM Websphere -

i deleted profile in c:\program files (x86)\ibm\websphere\appserver\profiles , still shows in profile management tool, how delete profile in profile management tool?

deleting profile's directory not enough; websphere holds additional info profiles in own internal directories.

the right way delete profile utilize websphere's manageprofiles utility, located in was_home/bin (in case: c:\program files (x86)\ibm\websphere\appserver\bin). example, if profile's name myprofile:

manageprofiles -delete -profilename myprofile

websphere ibm websphere-7

javascript - How do i show a specific slide in Flexslider when someone clicked on sub nav item using jQuery? -



javascript - How do i show a specific slide in Flexslider when someone clicked on sub nav item using jQuery? -

i'm trying specific flexslider slide show when sub-menu-item clicked.

i have added data-attributes slider , slide should active receive jquery (at to the lowest degree plan):

<div id="main-nav" class=""> <ul> <li class="item1"> <a href="#" class="scroll-link" data-id="whatever">whatever</a> <ul id="sub-nav1"> <li><a href="#" data-slider="1" data-slide="0">action</a></li> <li><a href="#" data-slider="1" data-slide="1">another</a></li> <li><a href="#" data-slider="1" data-slide="2">something</a></li> </ul> </li> <li> <a href="#" class="scroll-link" data-id="whatever1">whatever1</a> <ul id="sub-nav2"> <li><a href="#" data-slider="2" data-slide="0">action</a></li> <li><a href="#" data-slider="2" data-slide="1">another</a></li> <li><a href="#" data-slider="2" data-slide="2">something</a></li> </ul> </li> <li> <a href="#" class="scroll-link" data-id="whatever2">whatever2</a> <ul id="sub-nav3"> <li><a href="#" data-slider="3" data-slide="0">action</a></li> <li><a href="#" data-slider="3" data-slide="1">another</a></li> <li><a href="#" data-slider="3" data-slide="2">something</a></li> </ul> </li> </ul>

let's first flexislider:

<div class="flexslider" id="flexslider1"> <ul class="slides"> <li> <h3>flexslider slide 1</h3> <p>lorem ipsum dolor sit down amet, consectetur adipisicing elit. tempora provident velit quidem veniam temporibus, ipsa molestias rem dicta rerum et eveniet consequuntur nobis aliquid sed corporis exercitationem iusto impedit dolorem.</p> </li> <li> <h3>flexslider slide 2</h3> <p>lorem ipsum dolor sit down amet, consectetur adipisicing elit. doloremque natus vel aliquid omnis iusto ullam rerum commodi, quia ex illo libero odit laborum delectus sapiente pariatur sequi adipisci incidunt deleniti!</p> </li> <li> <h3>flexslider slide 3</h3> <p>lorem ipsum dolor sit down amet, consectetur adipisicing elit. magnam, repudiandae qui vitae nesciunt culpa aperiam amet beatae laborum excepturi eos, quos ex illum distinctio quo. fugiat ut ullam, sapiente sed.</p> </li> </ul> </div>

all of flexsliders initiated in head:

<script type="text/javascript" charset="utf-8"> $(window).load(function() { $('.flexslider').flexslider(); }); </script>

and jquery code trying manipulate sliders based on sub-menu-item they've clicked on:

$('#sub-nav li a').on('click', function(event) { event.preventdefault(event); var $sliderno = $(this).attr('data-slider'); var $slide = $(this).attr('data-slide'); var $slider = "#flexslider" + $sliderno; $($slider).flexslider($slide); });

what had was.

$('#sub-nav li a').on('click', function(event) { event.preventdefault(event); //use info instead of attr var $sliderno = $(this).data('slider'); var $slider = "#flexslider" + $sliderno; var $slide = $(this).data('slide'); $($slider).flexslider($slide); // won't run! - why? });

javascript jquery flexslider

ruby on rails - Testing an unauthenticated user Rspec/Devise -



ruby on rails - Testing an unauthenticated user Rspec/Devise -

i have had around maybe im not looking in right places. trying find out how test user cannot access page whos controller has

before_filter :authenticate_user!

ideally capture devise message @ same time

"you need sign in or sign before continuing"

i have far

require 'spec_helper' describe campaignscontroller "should not allow user able access without beingness authenticated" :index response.should redirect_to(new_user_session_path) end

end

at nowadays error

failure/error: response.should redirect_to(new_user_session_path) expected response <redirect>, <200>

campaigns controller

class campaignscontroller < applicationcontroller before_filter :authenticate_user! def index @campaigns = campaign.all end end

in spec helper calling following

# include devise test helpers config.include devise::testhelpers, :type => :controller config.extend controllermacros, :type => :controller

controller_macros.rb

module controllermacros def login_user before(:each) @request.env["devise.mapping"] = devise.mappings[:user] user = factorygirl.create(:user) sign_in user end end end

im not calling login_user method @ stage spec_helper phone call this?

how approach correctly

any help appreciated

thanks

at first seems ok. problem caused if run entire suite, , depending on place phone call login_user add together before(:each) all tests.

i understand want minimise typing, prefer tests little more explicit: want see going on in spec.

so how write kind of test:

describe homecontroller include devise::testhelpers context "when not signed in" describe "get 'index'" "redirects sign in" 'index' response.should be_redirect end end describe "get 'about'" "returns http success" 'about' response.should be_redirect end end end context "when signed in" before user = factorygirl.create(:user) sign_in(user) end describe 'get :index' "returns http success" 'index' response.should be_success end end describe "get 'about'" "returns http success" 'about' response.should be_success end end end end

yes, admitted: still fond of old rspec syntax (using should), reads much more natural me.

ruby-on-rails ruby rspec devise

Call jQuery function when element appears after page load -



Call jQuery function when element appears after page load -

i'm using jquery extension gives custom scroll bars. called this:

$("#thoughtsarticle #recentposts").mcustomscrollbar();

but in case element needs affected doesn't exist when page loads. appears result of user input. how can execute jquery when element appears on page?

from googling i've figured out need utilize delegated events i've not found examples straight apply in case. examples events form submission etc.

edit:

i don't think i've explained i'm looking for. if @ webpage here, when page loads, 'blog' section doesn't exist. if click on blog in navigation bar, reload section of page using ajax. see on blog section have recent posts block on right. want apply custom scroll bar section.

the code posted above in $(document ).ready() script rest of jquery, target element doesn't exist on page load, custom scroll bar not applied.

i've tried putting <script> tag on blog page above jquery, doesn't seem have effect.

i've searched bit on net , think need utilize delegated event? not sure either way don't know how utilize in case none of examples find seem apply in case.

this script fire when document loaded. add together delegate on document apply .mcustomscrollbar(); bit concerned fire 'ready' after point thought, seek other lifecycle event, or apply without delegation immediately, command on page after document ready.

$(function(){ $(document).on('ready','#thoughtsarticle #recentposts',function(){ $(this).mcustomscrollbar(); }) })

jquery

NoSuchMethodError in Tomcat embedded MULE when executing http:set-cookie -



NoSuchMethodError in Tomcat embedded MULE when executing http:set-cookie -

when running mule esb 3.2.1 embedded server within tomcat 7.0.27 (executed webapp-runner), during execution of flow http endpoint, while sending response caller, exception raised:

java.lang.nosuchmethoderror: org.apache.tomcat.util.http.servercookie.appendcookievalue(ljava/lang/stringbuffer;iljava/lang/string;ljava/lang/string;ljava/lang/string;ljava/lang/string;ljava/lang/string;iz)v

exception below:

org.mule.api.muleruntimeexception: connector caused exception is: connector.http.mule.default @ org.mule.transport.abstractconnector.handleworkexception(abstractconnector.java:2034) @ org.mule.transport.abstractconnector.workcompleted(abstractconnector.java:1998) @ org.mule.work.workercontext.run(workercontext.java:369) @ java.util.concurrent.threadpoolexecutor$worker.runtask(threadpoolexecutor.java:886) @ java.util.concurrent.threadpoolexecutor$worker.run(threadpoolexecutor.java:908) @ java.lang.thread.run(thread.java:662) caused by: java.lang.nosuchmethoderror: org.apache.tomcat.util.http.servercookie.appendcookievalue(ljava/lang/stringbuffer;iljava/lang/string;ljava/lang/string;ljava/lang/string;ljava/lang/string;ljava/lang/string;iz)v @ org.mule.transport.http.cookiehelper.formatcookieforasetcookieheader(cookiehelper.java:310) @ org.mule.transport.http.transformers.mulemessagetohttpresponse.createresponse(mulemessagetohttpresponse.java:261) @ org.mule.transport.http.transformers.mulemessagetohttpresponse.transformmessage(mulemessagetohttpresponse.java:90) @ org.mule.transformer.abstractmessagetransformer.transform(abstractmessagetransformer.java:145) @ org.mule.transformer.abstractmessagetransformer.transform(abstractmessagetransformer.java:93) @ org.mule.defaultmulemessage.applyalltransformers(defaultmulemessage.java:1387) @ org.mule.defaultmulemessage.applytransformers(defaultmulemessage.java:1348) @ org.mule.defaultmulemessage.applytransformers(defaultmulemessage.java:1331) @ org.mule.transport.abstractmessagereceiver.applyresponsetransformers(abstractmessagereceiver.java:235) @ org.mule.transport.abstractmessagereceiver.routemessage(abstractmessagereceiver.java:214) @ org.mule.transport.abstractmessagereceiver.routemessage(abstractmessagereceiver.java:163) @ org.mule.transport.abstractmessagereceiver.routemessage(abstractmessagereceiver.java:150) @ org.mule.transport.http.httpmessagereceiver$httpworker.dorequest(httpmessagereceiver.java:299) @ org.mule.transport.http.httpmessagereceiver$httpworker.processrequest(httpmessagereceiver.java:258) @ org.mule.transport.http.httpmessagereceiver$httpworker.run(httpmessagereceiver.java:163) @ org.mule.work.workercontext.run(workercontext.java:310)

if using mule 3.2.1, can not utilize http:response-builder. feature not there. that's why can't utilize it.

check out:

it's not in doc: http://www.mulesoft.org/documentation-3.2/display/32x/http+transport+reference it's not in source: https://github.com/mulesoft/mule/blob/mule-3.2.1/transports/http/src/main/java/org/mule/transport/http/config/httpnamespacehandler.java#l56

mule mule-studio

java - How to use @Size validation while using Float field with javax library? -



java - How to use @Size validation while using Float field with javax library? -

i trying utilize maximum size validation float datatype javax validations. here example

@notnull @size(min = 5, max = 10) public float getphone(){ }

but getting error can't utilize size validation float datatype. ideas?

@size not work float types. quote javadocs of constraint:

/** * annotated element size must between specified boundaries (included). * <p/> * supported types are: * <ul> * <li>{@code charsequence} (length of character sequence evaluated)</li> * <li>{@code collection} (collection size evaluated)</li> * <li>{@code map} (map size evaluated)</li> * <li>array (array length evaluated)</li> * </ul> * <p/> * {@code null} elements considered valid. * */

so constraints size of string or collection. write own validator float , register via xml - see http://beanvalidation.org/1.1/spec/#xml-mapping-constraintdefinition

however, recommend against it, since not create sense speak "size" in context want utilize it.

you utilize @min , @max, not providers back upwards float info type, due problem of rounding.

looking @ example, seems want store phone number. why ever take float begin with?

java validation hibernate-validator

java - Android KeyPairGenerator always generates the same key pair -



java - Android KeyPairGenerator always generates the same key pair -

i making application generates key pair user. in every device keys identical. here code:

public keypair generatekeys() { keypair keypair = null; seek { // instance of rsa cipher keypairgenerator keygen = keypairgenerator.getinstance("rsa"); keygen.initialize(1024); // initialize key generator keypair = keygen.generatekeypair(); // generate pair of keys } catch(generalsecurityexception e) { system.out.println(e); } homecoming keypair; }

and show generated keys code is:

keypair keypair = rsa.generatekeys(); byte[] publickey = keypair.getpublic().getencoded(); byte[] privatekey = keypair.getprivate().getencoded(); privatetext.settext( base64.encodetostring(privatekey, base64.no_wrap) ); publictext.settext( base64.encodetostring(publickey, base64.no_wrap) );

the key generation called 1 time each android device, , reason keys in each device should different.. can tell me missing here?

i believe looking @ first few or lastly few bits. thought had same problem when looked @ bits in middle, indeed different!

java android key-pair key-generator

c# - .NET MD5 signature does not match OpenSSL MD5 signature -



c# - .NET MD5 signature does not match OpenSSL MD5 signature -

i have sign messages web service. service uses openssl md5 signatures. generate openssl 1 pem private key file:

openssl.exe dgst -md5 -hex -out signature.txt -sign privkey.pem texttosign.txt

which generates next signature:

7078388bd081d4b805feb020ab47352320919e4638e36b59d66a684c9bb12a745aaf172e4da2686c3e3750bf627c980a19700f6d8bbd0b62d8714a965a34be2e9f4147ac054c4af1050cdcebd9b475f0ef28e520681b0d67104b8e633ee592bb3ec2c517fb8cf7b13bd86424f00c89518e063d55e7922adab7cf607c85920862

i want implement in code. actual code looks (the private key in pfx file same 1 in pem file):

private static string sign(string stringtosign) { x509certificate2 cert = new x509certificate2("keys.pfx", "", x509keystorageflags.exportable); byte[] info = encoding.utf8.getbytes(stringtosign); byte[] signeddata; using (md5 hasher = md5.create()) using (rsacryptoserviceprovider rsa = (rsacryptoserviceprovider)cert.privatekey) { signeddata = rsa.signdata(data, hasher); } homecoming convert.tobase64string(signeddata); }

this code produces next signature...

chg4i9cb1lgf/ragq0c1iycrnky442tz1mpotjuxknrarxcutajobd43ul9ifjgkgxapbyu9c2lycuqwwjs+lp9br6wfterxbqzc69m0dfdvkougabsnzxbljmm+5zk7pslff/um97e72gqk8ayjuy4gpvxnkirat89gfiwscgi=

...which not match opensll one. should match openssl one? tried utilize openssl.net, did not find resources/tutoral signing.

solved

the right code is:

private static string sign(string stringtosign) { x509certificate2 cert = new x509certificate2("#02299991.pfx", "#02299991", x509keystorageflags.exportable); byte[] info = encoding.utf8.getbytes(stringtosign); byte[] signeddata; using (md5 hasher = md5.create()) using (rsacryptoserviceprovider rsa = (rsacryptoserviceprovider)cert.privatekey) { signeddata = rsa.signdata(data, hasher); } homecoming bytearraytostring(signeddata); //convert.tobase64string(signeddata); } public static string bytearraytostring(byte[] signedbytes) { stringbuilder hex = new stringbuilder(signedbytes.length * 2); foreach (byte b in signedbytes) hex.appendformat("{0:x2}", b); homecoming hex.tostring(); }

your openssl output hex string:

openssl.exe dgst -md5 -hex -out signature.txt -sign privkey.pem texttosign.txt ^

while c# output in base64:

return convert.tobase64string(signeddata); ^

convert byte[] output hex string:

how convert byte array hexadecimal string, , vice versa?

c# cryptography openssl md5

sqlite - SQL: splitting up WITH statements into read-only tables -



sqlite - SQL: splitting up WITH statements into read-only tables -

i working on project in sqlite several insert statements involve recursive statements. these insert statements within triggers watching insert statements beingness called on other databases.

i've found leads recalculation of lots of values every time statement triggered, , rather introduce logic statement recalculate values need recalculated (which creates sprawl , hard me maintain), i'd rather take of temporary views defined in statement , create them permanent tables cache values. i'd chain triggers update of table_1 leads update of table_2, leads update of table_3, etc.. makes code easier debug , maintain.

the issue that, in project, want create clear distinction between tables user editable , meant caching intermediary values. 1 way (perhaps) create "caching" tables read-only except when called via triggers. i've seen few questions similar issues in other dialects of sql nil pertaining sqlite , nil looking solve problem, new question.

any help appreciated!

sql sqlite

sql - How to return N records in a SELECT statement without a table -



sql - How to return N records in a SELECT statement without a table -

i'm creating nacha file , if number of records in file not multiple of 10, need insert plenty "dummy" records filled nines (replicate('9',94)) nail next tens place.

i know write loop or perhaps fill temp table 10 records total of nines , select top n. options sense clunky.

i trying think of single select statement me. ideas?

select nacha_rows nacha_table union select replicate('9',94) --do 0 9 times

the formula (10-count(*)%10)%10 tells how many rows add, can select many dummy rows existing dummy table.

select nacha_rows nacha_table union select top (select (10-count(*)%10)%10 nacha_table) replicate('9',94) master.dbo.spt_values

sql sql-server

r - Assigning pch symbols in plot -



r - Assigning pch symbols in plot -

i have plot of many omega values within want highlight 40 points among many others. plot argument using is:

plot( log( dog[ order( dog$gbm.dog ) , 8 ] ), pch = ifelse( dog$refseq_mrna %in% dog_omegaplus$refseq_mrna, 2, ifelse( dog$refseq_mrna %in% dog_omegaminus$refseq_mrna, 12, "." ) ) )

i want have 1 grouping of highlighted points triangles (pch = 2), other grouping squares (pch = 12) , other points dots ("."). problem plot produces has digits pch symbols should (specifically "2" there should triangles , "1" there should squares).

how designate symbols correctly?

the problem here using "." coerces 2's , 12's character values. constructed simple test case see happening , whether find numeric designation satisfactory:

x <- 1:20 ifelse(x < 5 , 2, ifelse(x > 15, 12, ".")) [1] "2" "2" "2" "2" "." "." "." "." "." "." "." "." "." "." "." "12" "12" "12" "12" [20] "12" # homecoming integers plot(x, pch= ifelse(x < 5 , 2, ifelse(x > 15, 12, 20)))

r plot pch

elisp - Update gtag file in emacs for a single file once on saving -



elisp - Update gtag file in emacs for a single file once on saving -

my configuration copied http://www.emacswiki.org/emacs/gnuglobal#toc4 . purpose update existing tag file 1 time save source file. result same expected.

the total configuration is:

(gtags-mode 1) (defun gtags-root-dir () "returns gtags root directory or nil if doesn't exist." (with-temp-buffer (if (zerop (call-process "global" nil t nil "-pr")) (buffer-substring (point-min) (1- (point-max))) nil))) (defun gtags-update-single(filename) "update gtags database changes in single file" (interactive) (start-process "update-gtags" "update-gtags" "bash" "-c" (concat "cd " (gtags-root-dir) " ; gtags --single-update " filename ))) (defun gtags-update-current-file() (interactive) (defvar filename) (setq filename (replace-regexp-in-string (gtags-root-dir) "." (buffer-file-name (current-buffer)))) (gtags-update-single filename) (message "gtags updated %s" filename)) (defun gtags-update-hook() "update gtags file (insert )ncrementally upon saving file" (when gtags-mode ;;it re-create past error.. (when (gtags-root-dir) (gtags-update-current-file)))) (add-hook 'after-save-hook 'gtags-update-hook)

update

my understanding tags update via command

(gtags-update-single filename) (message "gtags updated %s" filename))

once file in buffer saved. means new added or renamed or removed function updated tag file. in test, see output message(the tags in ededemo directory ):

wrote /other/projectbase/cplusproject/ededemo/src/main.cpp gtags updated ./src/main.cpp

each time function renamed or added after c-x c-s. m-x gtags-find-tag not find new added function. there wrong in understanding?

this line responsible/broken:

(when gtags-;-*- mode: ${1:mode} -*-

looking @ wiki page, can't fathom how managed end that.

the docstring comment corrupted. re-create whole function again.

emacs elisp gnu-global

c# - Directory.GetFilesNameWithoutExtension() Array -



c# - Directory.GetFilesNameWithoutExtension() Array -

i have several files in folder. want names of files (without extensions) in array. possible retrieve entire list of files this? closest have come directory.getfiles("foldername") returns array of "foldername\filename.extensions". possible have array of "filename" each file? problem path.getfilenamewithoutextension() returns single file.

(note: looking more elegant way string.split() or string.substring())

this directory.getfiles() provides:

{"foldername\file1.ext", "foldername\file2.ext"}

this want (elegantly):

{"file1", "file2"}

i assume you're looking path.getfilenamewithoutextension method:

var filenames = directory.enumeratefiles("foldername") .select(path.getfilenamewithoutextension) .toarray();

edit: if want larn select operator, should study linq, great tool boosting productivity in .net. above equivalently expressed as:

var filenames = directory.getfiles("foldername"); (int = 0; < filenames.length; ++i) filenames[i] = path.getfilenamewithoutextension(filenames[i]);

c# arrays file directory

scala - Serialize Case Object Extending Trait -



scala - Serialize Case Object Extending Trait -

given trait conjunction and , or case object sub-types:

trait conjunction case object , extends conjunction case object or extends conjunction

using play 2 json, tried write next writes[conjunction]:

implicit object conjunctionwrites extends writes[conjunction] { implicit val orwrites: writes[or] = json.writes[or] implicit val andwrites: writes[and] = json.writes[and] def writes(c: conjunction) = c match { case a@and => json.tojson(a)(andwrites) case o@or => json.tojson(o)(orwrites) } }

but got bunch of not found: type and/or errors.

how can serialize these case objects?

when create case object, create value name, not type. and , or don't exist types. if want refer type of case object, utilize .type, e.g. and.type.

however, json.writes macro works on case classes, not case objects. you'll have write own definition:

implicit object conjunctionwrites extends writes[conjunction] { def writes(c: conjunction) = c match { case , => json.tojson("and") case or => json.tojson("or") } }

scala serialization playframework-2.0

python - How to write a handler for window move event in Kivy? -



python - How to write a handler for window move event in Kivy? -

i'd write handler event after window moved in windows / linux.

i need such function reset behaviour of app because dragging of window stop/pause clock.schedules , after window released animation schedule not starting properly. wrong behaviour during window move no problem afterwards app should restart correctly.

something simillar code window resize:

class demoapp(app): def build(self): def win_cb(window, width, height): print 'resizing' window.bind(on_resize=win_cb)

is there on_move? haven't seen in api-documentation

no, there no way current window position in kivy. may possible straight utilizing window backend (i.e. pygame) not cross-platform compatible , quite hacky.

however, you're having other problem here. animations , clock schedules both work fine me while moving , resizing window. might want post question asking why schedules getting screwed up, because not expected behavior.

python windows events kivy

php - How can i put a single value in a single column with fputcsv -



php - How can i put a single value in a single column with fputcsv -

i want export info database csv file.

my php code this

$members = db::getresult('select * '.members_table_name.' order '.members_column_prefix.'_lastname, '.members_column_prefix.'_firstname'); $filename = "../db_user_export".".csv"; $handle = fopen($filename, 'w+'); fputcsv($handle, array_keys($members[0])); foreach ($members $member) { fputcsv($handle, $member); }//foreach fclose($handle);

now output in csv this:

"column a" "column b" "column c", "password,username,fistname", "lastname,updated" "loggedin,is_new"

but want this:

"column a" "column b" "column c", "password" "username" "firstname".

anyone knows how ?

do not utilize select * , instead select fields want

php mysql sql csv

jQuery addclass, removeclass and click event problems ( code ) -



jQuery addclass, removeclass and click event problems ( code ) -

jquery(document).ready(function () { jquery('.issocial').click(function () { var hidden = jquery('.socialhidden'); hidden.animate({ "top": "35px" }, 400); jquery(".socialhidden>div").delay(400).animate({ opacity: "1" }, 150); jquery(".issocial").addclass("closejs").removeclass("issocial"); homecoming false; }); jquery('.closejs').click(function () { var hidden = jquery('.socialhidden'); hidden.delay(200).animate({ "top": "-176px" }, 400); jquery(".socialhidden>div").animate({ opacity: "0" }, 150); jquery(".closejs").addclass("issocial").removeclass("closejs"); }); });

can help me prepare code? first part works perfectly... when seek sec 1 working, nothing.

this html:

<button class="issocial">button</button> <div class="socialhidden"> <div> content..... </div> </div>

since changing classes dynamically, should utilize event delegation binding events,

jquery(document).ready(function () { jquery(document).on("click", '.issocial', function () { var hidden = jquery('.socialhidden'); hidden.animate({ "top": "35px" }, 400); jquery(".socialhidden>div").delay(400).animate({ opacity: "1" }, 150); jquery(".issocial").addclass("closejs").removeclass("issocial"); homecoming false; }); jquery(document).on("click", '.closejs', function () { var hidden = jquery('.socialhidden'); hidden.delay(200).animate({ "top": "-176px" }, 400); jquery(".socialhidden>div").animate({ opacity: "0" }, 150); jquery(".closejs").addclass("issocial").removeclass("closejs"); }); });

jquery

mysql - python injection protection for multiple column queries -



mysql - python injection protection for multiple column queries -

how secure sql injection in next code? utilize comma instead of percent sign, because doesn't straight inject string, cant when want select multiple columns database.

this works not safe:

def (columns) % columns string of column names separated commas id = 5 querystr = """select %s dash id=%s limit 1""" q.execute(querystr % (columns, id))

while doesn't work:

def (columns) % columns string of column names separated commas id = 5 querystr = """select %s dash id=%s limit 1""" q.execute(querystr, (columns, id))

i need able alter amount of columns im searching when phone call method.

you can't utilize params argument of execute() add together columns query anyway, because add together single-quotes around argument, forcefulness treated string. you'll end query:

select 'item1, item2, item3' dash id=5 limit 1

you have interpolate columns yourself.

to protect against sql injection, it's responsibility filter list of column names , validate against list of known columns of table. consider whitelisting process.

mysql python-2.7 sql-injection

ruby on rails - NoMethodError: undefined method `assert_block' -



ruby on rails - NoMethodError: undefined method `assert_block' -

apparently method exists , i've been trying utilize it, doesn't seem work in utilize case.

test "should appropriate autocomplete results upon ideal request" :index, { "term" => "al", "max_results" => "20"} assert_response :success assert_not_nil assigns(:payers) assert json_response.length <= 20 assert_block json_response.each |payer_hash| homecoming false unless payer_hash['label'][0..1] == "al" end true end end

that test. @ first thought using wrong because have block within of it. but, @ same time, if had within simple one-liner, utilize assert. using wrong? deprecated in rails 4.1? if so, new way this?

ruby-on-rails testing tdd

actionscript 3 - getDefinitionByName "Variable Not defined" workaround -



actionscript 3 - getDefinitionByName "Variable Not defined" workaround -

ok have game info parser creates game out of info file basically, using extensively getdefinitionbyname has 1 problem if class not loading somewhere else throw variable not defined error information=referenceerror: error #1065: variable {myclass} not defined. workaround using class holds list of components , instantiate create these classes available compiler. ok question part there more efficient way or playing compiler argument or ? there export in first frame in flash professional compiler argument ?

i think want have library project "callable" classes, , reference library project in game.

in flash builder, library project, can check classes compiled (and available getdefinitionbyname). (info here)

actionscript-3 flash

c# - Controlling a WPF app from a DLL (interprocess communication) -



c# - Controlling a WPF app from a DLL (interprocess communication) -

i have dll has talk programme not written in c#. have established connection code:

namespace classlibrary1 { public class class1 { [dllexport("teststring", callingconvention = system.runtime.interopservices.callingconvention.stdcall)] [return: marshalas(unmanagedtype.bstr)] public static string teststring(string test) { homecoming "test" + test; } public static callbackproc _callback; [dllexport("setcallback", callingconvention = system.runtime.interopservices.callingconvention.stdcall)] public static void setcallback(callbackproc pcallback) { _callback = pcallback; //var app = new app(); //var win = new mainwindow(); //app.run(win); messagebox.show("c#: setcallback completed"); } [dllexport("testcallback", callingconvention = system.runtime.interopservices.callingconvention.stdcall)] public static void testcallback(string passedstring) { string displayvalue = passedstring; string returnvalue = string.empty; todaybutton.mainwindow app = new todaybutton.mainwindow(); app.initializecomponent(); messagebox.show("c#: phone call callback. displayvalue=" + displayvalue + ", returnvalue=" + returnvalue); _callback(displayvalue, ref returnvalue); messagebox.show("c#: callback. displayvalue=" + displayvalue + ", returnvalue=" + returnvalue); } public delegate void callbackproc( [marshalas(unmanagedtype.bstr)] string passedvalue, [marshalas(unmanagedtype.bstr)] ref string returnvalue); } }

so callbacks work perfectly. have problem dont know how solve. want utilize interface wpf app. when programme calls dll, dll should start wpf app , wait app close , send information, phone call callback.

the thing dont want start , stop wpf app everytime need info it. want have button "send callback". problem project class library, using dllexport , wpf project won't compile class library.

is there way this, can command whole wpf app dll? command start, stop, pass callback values phone call them wpf forms, or send info testcallback function when press button in wpf.

how possible?

in end have decided i'm gonna utilize simple messaging library since have winforms on dll side , wpf on other side, utilize windows messages. http://thecodeking.github.io/xdmessaging.net/ library used.

another, more advanced way of sharing info http://blogs.msdn.com/b/dmetzgar/archive/2012/10/16/an-updated-custom-wcf-transport-channel-example.aspx wanted utilize in end decided i'm not gonna utilize wcf since i'm not sending alot of data, messages command app.

c# .net wpf dll

android - Not able to get updated apk file in my project -



android - Not able to get updated apk file in my project -

in project when test application on mobile device or emulator app works , show changes did in project -> bin folder .apk file not getting update? help please.

each time create changes in project has apk file earlier. have go through below process again:

project file>right click>android tools>export signed/unsigned application package , proceed until current .apk saved @ target folder.

for .apk in bin folder, eclipse faces problems update, can 'clean' , 'build' project. run either in emulator or on device. solve issue @ bin folder.

good luck.

android apk

julia lang - Discretizing a continuous probability distribution -



julia lang - Discretizing a continuous probability distribution -

recognizing may much statistical question coding question, let's have normal distribution created using distributions.jl:

using distributions mydist = normal(0, 0.2)

is there good, straightforward way should go discretizing such distribution in order pmf opposed pdf?

in r, found actuar bundle contains function discretize continuous distribution. failed find similar julia, thought i'd check here before rolling own.

julia-lang

qt - Playing ulaw file with QAudioOutput -



qt - Playing ulaw file with QAudioOutput -

i'm trying set simple working illustration play .raw file , sound seems distorted. when .raw file plays, can still create out everything, distorted, listening radio station going out of range.

qstring mresourcepath ="test.raw"; qfile audio_file(mresourcepath); if(audio_file.open(qiodevice::readonly)) { audio_file.seek(4); // skip wav header qbytearray audio_data = audio_file.readall(); audio_file.close(); qbuffer audio_buffer(&audio_data); audio_buffer.open(qiodevice::readonly); qdebug() << audio_buffer.size(); qaudioformat format; format.setsamplesize(8); format.setsamplerate(8000); format.setchannelcount(1); format.setcodec("audio/pcm"); format.setbyteorder(qaudioformat::bigendian); format.setsampletype(qaudioformat::unsignedint); qaudiodeviceinfo info(qaudiodeviceinfo::defaultoutputdevice()); if (!info.isformatsupported(format)) { qwarning()<<"raw sound format not supported backend, cannot play audio."; return; } qdebug() << info.devicename(); qaudiooutput output(info, format); output.start(&audio_buffer); // ...then wait sound finish qeventloop loop; qobject::connect(&output, signal(statechanged(qaudio::state)), &loop, slot(quit())); { loop.exec(); } while(output.state() == qaudio::activestate); }

the title of question indicates wish play u-law audio, logarithmic pcm. yet, line

format.setcodec("audio/pcm");

initializes playback linear pcm. 2 possible solutions:

initialize playback appropriate log pcm codec. docs study qaudiodeviceinfo::supportedcodecs() homecoming list of supported codecs. convert log pcm samples linear pcm in real time. it's pretty low impact , can performed using lookup table.

qt audio

jquery - form creation works but not submit -



jquery - form creation works but not submit -

var str = $('<form>').attr({ action: data.action, method: 'post', name: 'form' }); $.each(data.form , function( index, value ) { str.append($('<input>').attr({ type: value.type, name: value.name, alue: value.value }) ); }); str.appendto('body'); str.submit();

data.form array , includes form files. code used create dynamic form , submit it. form creation successful submit part not working. why ?

put action within quotation.

action: 'data.action', $.each('data.form' , function( index, value ) {});

is code right?

jquery forms

selenium webdriver - Firepath is giving absolute path but we need relative path -



selenium webdriver - Firepath is giving absolute path but we need relative path -

i facing issue xpath using firepath .

if select web element using fire path giving xpath html/body/div[1]/div/div[2]/div/form/fieldset/p/input not selecting element it(xpath) generating below (means relative path)

by.xpath("//table[@id='tableid']/tbody/tr[1]")

please guide me alter in firepath.

i think the absolute fire path checked in fire path drop down.

to resolve press f12 fire path, click on drop downwards arrow in fire path tab, united nations check generate absolute xpath , restart fire path.

selenium-webdriver firepath

sql - Transfer a table from a server to another server -



sql - Transfer a table from a server to another server -

besides import , export wizard, there query transfer table server server in sql server 2008?

select * [server1].[db_name].[dbo].[table_name] [server2].[db_name].[dbo].[table_name]

there several options. if have right permissions, can create linked server next instructions here: http://msdn.microsoft.com/en-us/library/ff772782.aspx

and utilize openquery (http://msdn.microsoft.com/en-us/library/ms188427.aspx) select records:

select * new_db.new_schema.new_table openquery(linked_server_name, 'select * old_db.old_schema.old_table');

or can similar openrowset (http://technet.microsoft.com/en-us/library/ms190312.aspx) if don't want go through setting linked server:

select * new_db.new_schema.new_table openrowset('sqlncli', 'server=oldserver;trusted_connection=yes;', 'select * old_db.old_schema.old_table');

both may require tweaking based on authentication method you're using, usernames, privileges, , that.

sql sql-server sql-server-2008 tsql

javascript - IE toDataUrl() Security Error -



javascript - IE toDataUrl() Security Error -

i need image canvas, image amazon s3, have enabled cross-origin resource sharing (cors) there , have set croseorigin attribute "anonymous" img, , works fine chrome , firefox, on ie security error calling todataurl method.

so how prepare ? can't see details on security error.

i'm not sure if it's best way, have found solution this. converting img base64, , no error. helped -> how convert base64

javascript

python - how to get the version number of a tag in a list -



python - how to get the version number of a tag in a list -

i trying grep "included in team_com_build" in list below , version of com_cnss_bt_lnx.la.3.6.1.00.00.032,"32" in case,expected output 32 running below error?how prepare it?

import re comments = [{u'timestamp': 1403046914, u'message': u'patch set 1: looks me, else must approve\n\nthis patchset has been processed service.', u'reviewer': {u'username': u'service', u'name': u'service service account', u'email': u'service@localhost'}}, {u'timestamp': 1403051700, u'message': u'patch set 1: developer build , test comccessful\n\nincluded in team_com_build: com_cnss_bt_lnx.la.3.6.1.00.00.032\n\nhttp://qwiki.company.com/div_wcnss/com_cnss_bt_lnx.la.3.6.1.00.00.032', u'reviewer': {u'username': u'user2', u'name': u'user prakash soy', u'email': u'user2@div.company.com'}}, {u'timestamp': 1403052176, u'message': u'patch set 1: looks me, approved\n\n', u'reviewer': {u'username': u'username', u'name': u'alekhya damera', u'email': u'username@div.company.com'}}] matchobj = re.search("included in team_com_build: (\s*)$", str(comments), re.multiline) print matchobj build = matchobj.group(1) print build chunks = build.split('.') print chunks last_one = chunks[-1] print last_one

error:-

traceback (most recent phone call last): file "su_version.py", line 5, in <module> build = matchobj.group(1) attributeerror: 'nonetype' object has no attribute 'group'

your regular look wrong. 1 work:

matchobj = re.search(r"included in team_com_build: \s+\.(\d+)\\n", str(comments))

it greedily match non-whitespace characters after included in team_com_build until hits . character, followed 1 or more digits (which captured in match group), followed newline. want.

edit:

in response comment, can utilize match both patterns:

matchobj = re.search(r"included in team_com_build:\s+\s+?\.(?:\d+\.){5}(\d+)(?:\.\d+)?", str(comments))

this matches first instance (it returns first instance because match \s+ non-greedily, using \s+?) of 5 consecutive <one or more digit>. groups, followed 1 or more digits (which captured in group), optionally followed .<one or more digits>. ?: characters within of parenthesis means grouping non-capturing, , ? after parenthesis marks grouping optional.

python

Trying to use fabric to check out a git repository to a subdirectory -



Trying to use fabric to check out a git repository to a subdirectory -

i'm using fabric automate branch creation. problem don't know branch name before function called, , fabric doesn't work cd.

how can tell git target directory going 1 level lower?

fabfile:

def new_branch(branch_name): local('mkdir ' + branch_name) local('git clone /var/www/finance ' + branch_name) local('git checkout head ./' + branch_name + ' -b ' + branch_name)

the output i'm getting is:

[localhost] local: mkdir test [localhost] local: git clone /var/www/finance test cloning 'test'... done. [localhost] local: git checkout head ./test -b test fatal: not git repository (or of parent directories): .git fatal error: local() encountered error (return code 128) while executing 'git checkout head ./test -b test' aborting.

one way utilize path parameters git. parameters verified git version 1.7.9.5.

local('git --git-dir ' + branch_name + '/.git --work-tree ' + branch_name + ' checkout head -b ' + branch_name)

git fabric

java - SSL realization for NSURLSession -



java - SSL realization for NSURLSession -

i have big problem in app. had java implementation, need same ios app using security.framework nsurlsession, , dont know how. great if u help me.

java:

// our trusted ca resources certificatefactory certificatefactory = certificatefactory.getinstance("x.509"); int caresid = context.getresources().getidentifier("cert_ca", "raw", context.getpackagename()); x509certificate cert = (x509certificate)certificatefactory.generatecertificate(context.getresources().openrawresource(caresid)); string alias = cert.getsubjectx500principal().getname(); // create empty trust store our ca keystore truststore = keystore.getinstance(keystore.getdefaulttype()); truststore.load(null); truststore.setcertificateentry(alias, cert); // create trustmanagers based on our trust store trustmanagerfactory tmf = trustmanagerfactory.getinstance("x509"); tmf.init(truststore); trustmanager[] trustmanagers = tmf.gettrustmanagers(); // our client certificate resources keystore keystore = keystore.getinstance("pkcs12"); string pass = context.getresources().getstring(r.string.pass); int clientresid = context.getresources().getidentifier("cert_client", "raw", context.getpackagename()); keystore.load(context.getresources().openrawresource(clientresid), pass.tochararray()); // create keymanagers based on our key store keymanagerfactory kmf = keymanagerfactory.getinstance("x509"); kmf.init(keystore, pass.tochararray()); keymanager[] keymanagers = kmf.getkeymanagers(); // create ssl context sslcontext sslcontext = sslcontext.getinstance("tls"); sslcontext.init(keymanagers, trustmanagers, null); url requestedurl = new url(url); httpsurlconnection urlconnection = (httpsurlconnection)requestedurl.openconnection(); urlconnection.setsslsocketfactory(sslcontext.getsocketfactory()); urlconnection.setrequestmethod("get"); urlconnection.setconnecttimeout(1500); // ? urlconnection.setreadtimeout(1500); // ? int responsecode = urlconnection.getresponsecode(); string responsemessage = urlconnection.getresponsemessage(); urlconnection.disconnect();

solve next code (it can helpful someone):

-(void)urlsession:(nsurlsession *)session didreceivechallenge:(nsurlauthenticationchallenge *)challenge completionhandler:(void (^)(nsurlsessionauthchallengedisposition, nsurlcredential *))completionhandler{ if ([self shouldtrustprotectionspace:challenge.protectionspace]) { [challenge.sender usecredential:[nsurlcredential credentialfortrust:challenge.protectionspace.servertrust] forauthenticationchallenge:challenge]; } else { nsstring *path = [[nsbundle mainbundle] pathforresource:@"mobile_client (1)" oftype:@"pfx"]; nsdata *p12data = [nsdata datawithcontentsoffile:path]; cfdataref inp12data = (__bridge cfdataref)p12data; secidentityref myidentity; sectrustref mytrust; extractidentityandtrust(inp12data, &myidentity, &mytrust); seccertificateref mycertificate; secidentitycopycertificate(myidentity, &mycertificate); const void *certs[] = { mycertificate }; cfarrayref certsarray = cfarraycreate(null, certs, 1, null); nsurlcredential *credential = [nsurlcredential credentialwithidentity:myidentity certificates:(__bridge nsarray*)certsarray persistence:nsurlcredentialpersistenceforsession]; [[challenge sender] usecredential:credential forauthenticationchallenge:challenge]; completionhandler(nsurlsessionauthchallengeusecredential, credential); } } osstatus extractidentityandtrust(cfdataref inp12data, secidentityref *identity, sectrustref *trust) { osstatus securityerror = errsecsuccess; cfstringref password = cfstr("123"); const void *keys[] = { ksecimportexportpassphrase }; const void *values[] = { password }; cfdictionaryref options = cfdictionarycreate(null, keys, values, 1, null, null); cfarrayref items = cfarraycreate(null, 0, 0, null); securityerror = secpkcs12import(inp12data, options, &items); if (securityerror == 0) { cfdictionaryref myidentityandtrust = cfarraygetvalueatindex(items, 0); const void *tempidentity = null; tempidentity = cfdictionarygetvalue(myidentityandtrust, ksecimportitemidentity); *identity = (secidentityref)tempidentity; const void *temptrust = null; temptrust = cfdictionarygetvalue(myidentityandtrust, ksecimportitemtrust); *trust = (sectrustref)temptrust; } if (options) { cfrelease(options); } homecoming securityerror; } - (bool)shouldtrustprotectionspace:(nsurlprotectionspace *)protectionspace { // load bundled certificate. nsstring *certpath = [[nsbundle mainbundle] pathforresource:@"mobile_ca" oftype:@"der"]; nsdata *certdata = [[nsdata alloc] initwithcontentsoffile:certpath]; seccertificateref cert = seccertificatecreatewithdata(null, (__bridge cfdataref)(certdata)); sectrustref servertrust = protectionspace.servertrust; cfarrayref certarrayref = cfarraycreate(null, (void *)&cert, 1, null); sectrustsetanchorcertificates(servertrust, certarrayref); sectrustresulttype trustresult; sectrustevaluate(servertrust, &trustresult); homecoming trustresult == ksectrustresultunspecified;}

java android ios security ssl

php - How to Access Protected Folder's in Cpanel -



php - How to Access Protected Folder's in Cpanel -

i have simple question, have purchased domain , have created folder on it, , added few .php script files, accessing .php files in android application using http request.

apparently script files visible every body, if protect them cpanel how may access in android code?

any body help.?

php android security cpanel

html - Root-relative URL not working in CSS -



html - Root-relative URL not working in CSS -

i have below css

.div_img { width: 500px; height: 500px; background-image: url(/images/simple_img.png); }

there root relative url in above css , not working. not showing image on div. please help me how set root relative url in css?

make sure that:

the image exists in location the css file rendered the div has class attribute set div_img the background-image property not getting overridden css directive takes precedence

html css url

swift - What's wrong with my code that tries to check the type of a variable? -



swift - What's wrong with my code that tries to check the type of a variable? -

this question has reply here:

how determine type of variable in swift 4 answers

what's wrong code tries check type of variable?

the next code produces error says "'is' test true". note don't want set p value because nil, hence utilize of optional.

import foundation var p:string? if p string? { println("p string type") } else { println("p not string type") }

now if test against string type, won't compile:

import foundation var p:string? if p string { println("p string type") } else { println("p not string type") }

is compiler bug? if not did wrong?

adding on answers revolve around optional binding, there more direct way apple provides.

the is operator exists purpose. however, doesn't allow test trivial cases rather subclasses. can utilize is this:

let : = "string" if string { println("yes") } else { println("no") }

as expected, prints yes.

swift

php - PDO insert not working -



php - PDO insert not working -

so please bare me, i'm trying work pdo create scripts more secure. have demo , set variable $sth->bindparam(':ip', $ip);, phone call

$data = $con->prepare("insert users (ip) values (':ip')");

the problem reason not entering database. here's total code

<?php $host = "localhost"; $dbname = "users"; $user = "root"; $pass = "root"; try{ $con = new pdo("mysql:host=$host;dbname=$dbname", $user, $pass); } catch(pdoexception $e){ echo $e->getmessage(); } function generaterandomstring($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz'; $randomstring = ''; ($i = 0; $i < $length; $i++) { $randomstring .= $characters[rand(0, strlen($characters) - 1)]; } homecoming $randomstring; } $ip = generaterandomstring().sha1($_server['server_addr']).generaterandomstring(); $sth->bindparam(':ip', $ip); $data = $con->prepare("insert users (ip) values (':ip')"); $data->execute(); ?>

and yes understand that's not how ip fourth, i'm playing around pdo , mysql. additional tips help me improve code nice, in advance.

you have binfd parameter after query not before

$data = $con->prepare("insert users (ip) values ( :ip )"); $data->bindvalue(':ip', $ip , pdo::param_str); // if ip column string $data->execute();

some ref

php mysql database pdo sql-injection

How to install an OSX Automator workflow using „Packages“ installer -



How to install an OSX Automator workflow using „Packages“ installer -

i want utilize osx „packages“ installer install automator workflow, uses obj-c automator action. workflow had installed in folder „services", , obj-c action in folder „automator“, both in user’s or scheme library. unfortunately, packages shows part of existing file hierarchy:

finder window:

packages window: particularly packages not show automator folder, cannot create required payload.

in docs not find way access hidden folders.

any suggestion how create such installer bundle welcome.

my guess packages correctly trying prevent installing /system/library. in general, contents of /system/library part of os x , managed apple. right place user-installed system-wide items in /library.

osx installer automator

xslt - Howto handle a XML with namespaces? -



xslt - Howto handle a XML with namespaces? -

if have xml:

<?xml version="1.0" encoding="utf-8"?> <env:envelope> <m:rgwspublicfirmactrtuser> <m:firmactdescr>ΑΛΛΟ ΛΙΑΝΙΚΟ ΕΜΠΟΡΙΟ ΣΕ ΜΗ ΕΞΕΙΔΙΚΕΥΜΕΝΑ ΚΑΤΑΣΤΗΜΑΤΑ</m:firmactdescr> <m:firmactkind>2</m:firmactkind> <m:firmactkinddescr>ΔΕΥΤΕΡΕΥΟΥΣΑ</m:firmactkinddescr> <m:firmactcode>47191000</m:firmactcode> </m:rgwspublicfirmactrtuser> <m:rgwspublicfirmactrtuser> <m:firmactdescr>ΛΙΑΝΙΚΟ ΕΜΠΟΡΙΟ ΕΙΔΩΝ ΔΩΡΩΝ ΓΕΝΙΚΑ</m:firmactdescr> <m:firmactkind>2</m:firmactkind> <m:firmactkinddescr>ΔΕΥΤΕΡΕΥΟΥΣΑ</m:firmactkinddescr> <m:firmactcode>47191008</m:firmactcode> </m:rgwspublicfirmactrtuser> </env:envelope>

and utilize xslt:

<?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform"> <xsl:template match="/"> <html> <body> <h3>Δραστηριότητες</h3> <table border="1"> <tr bgcolor="#9acd32"> <th style="text-align:left">Δραστηριότητα</th> <th style="text-align:left">Αριθμός δραστηριότητας</th> <th style="text-align:left">Περιγραφή δραστηριότητας</th> <th style="text-align:left">Κωδικός δραστηριότητας</th> </tr> <xsl:for-each select="envelope/rgwspublicfirmactrtuser"> <tr> <td><xsl:value-of select="firmactdescr"/></td> <td><xsl:value-of select="firmactkind"/></td> <td><xsl:value-of select="firmactkinddescr"/></td> <td><xsl:value-of select="firmactcode"/></td> </tr> </xsl:for-each> </table> </body> </html> </xsl:template> </xsl:stylesheet>

all works fine, when have namespace in input xml:

<env:envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:m="http://gr/gsis/rgwspublic/rgwspublic.wsdl" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance">

instead of no namespaces:

<env:envelope>

the xslt won't work

my problem xml received 3rd party , can't command content. need process is. maybe can replace big env:envelope , little env:envelope within within server process, there anyway can create xslt work without changing xml?

to match namespaced elements in xslt have declare namespace prefix in stylesheet same namespace uri, , utilize prefix in xpath expressions:

<?xml version="1.0" encoding="iso-8859-1"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/xsl/transform" xmlns:env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:m="http://gr/gsis/rgwspublic/rgwspublic.wsdl"> <xsl:template match="/"> <!-- ... --> <xsl:for-each select="env:envelope/m:rgwspublicfirmactrtuser">

(m: namespace uri taken comment). namespace uris not have real urls browser can fetch, treated unique identifiers namespace. xml technologies utilize "urn" identifiers namespaces (like urn:example:namespace) instead of http urls.

xml xslt xml-namespaces

domain driven design - DDD referencing large data sets / injecting repository? -



domain driven design - DDD referencing large data sets / injecting repository? -

i struggling find best solution following. need determine whether country "inuse", (e.g. referenced address).

i have next simplified model mapped in nhibernate:

class address { public country country {get; set;} } class country { public list<address> addresses {get; set;} bool isinuse() { homecoming addresses.any(); } }

using isinuse method on country inefficient, result in load of countries (the .any() executed in memory). in addition, country doesn't need know addresses, it's purely there isinuse method. so, above illustration consumer point of view, feels domain object should expose isinuse method, not perform , contains unnecessary relationships.

other options can think of are;

just utilize repository , phone call straight service layer. repository encapsulate phone call issued select count(*), rather select *, case lazy load alternative above. options leave isinuse logic exclusively outside of domain layer. inject repository isinuse(), calls out same above. have read bad ddd practise.

does have advice or improve solutions problem.

hope above makes sense... thanks.

i suggest not calculate each time perform query. denormalize isinuse. each time address added or removed country can determine whether country in utilize , save value.

how go determining value story , there various techniques ranging determining when save address , updating country's isinuse value or using messaging if these happen entities in different bcs.

domain-driven-design repository-pattern

c - Python 'pointer arithmetic' - Quicksort -



c - Python 'pointer arithmetic' - Quicksort -

in idiomatic c fashion, 1 can implement quicksort in simple way 2 arguments:

void quicksort(int inputarray[], int numelems);

we can safely utilize 2 arguments later subdivisions (i.e. partitions, they're commonly called) via pointer arithmetic:

//later on in our quicksort routine... quicksort(inputarray+last+1, numelems-last-1);

in fact, asked before on because untrained in pointer arithmetic @ time: see passing array function odd format - “v+last+1”

basically, is possible replicate same behavior in python , if so, how? have noticed lists can subdivided colon within of square brackets (the slicing operator), piece operator not pass list point on; 1st element (0th index) still same in both cases.

as you're aware, python's piece syntax makes copy, in order manipulate subsection of list (not "array", in python) in place, need pass around both list , start-index , size (or end-index) of portion under discussion, much in c. signature of recursive function like:

def quicksort( inputlist, numelems, startindex = 0 ):

and recursive phone call like:

quicksort( inputlist, numelems-last-1, last+1 )

throughout function you'd add together startindex whatever list accesses make.

python c arrays list pointers

c# - How to call js file function from code behind page -



c# - How to call js file function from code behind page -

i have next function in .js file , need phone call code behind page after saving record.

i have registered scipt file in aspx page

aspx file

<script type="text/javascript" src="/scripts/visit-flash-report.js"></script>

.js file

function reloaddoctab() { alert('hello'); $('#frmdocs').attr('src', $('#frmdocs').attr('src')); }

code behind page

i have tried function not working

page.clientscript.registeronsubmitstatement(me.[gettype](), "reload function", "return reloaddoctab();")

if understand trying do. want save record on postback when page reloads phone call javascript function.

try this:

pagebody.attributes.add("onload", "reloaddoctab()");

c# javascript jquery asp.net vb.net

recursion - What does exit(0) do inside a recursive function? -



recursion - What does exit(0) do inside a recursive function? -

is there way exit programme within resursive function ? if there way, happen if exit ? exit(0) in recursive function ?

exit(0) always* create entire application exit (with status code of 0). whether you're calling recursive function or not irrelevant — it's different return.

*: well, always; there few crazy situations won't, that's besides point

recursion

javascript - How to access object created in one for loop within another for loop? -



javascript - How to access object created in one for loop within another for loop? -

i have function contains for-loop. in for-loop save 4 different strings object saveimagetitles. @ run-through of lastly item in loop trigger function appendobject() contains yet for-loop.

in loop function in appendobject(); want pass on each string saveimagetitles via someotherfunction(objectindex].image[j], saveimagetitles[j]); - saveimagetitles[j] turn undefined.

how save strings 1 loop can iterate through them in sec for-loop?

edit: added jsfiddle

var saveimagetitles = []; var objectindex = 0; var objectcount = 4; var totalobjectimages = 1; function appendobject() { for(var j in products[objectindex].image) { /* function want pass on each string */ someotherfunction(products[objectindex].image[j], saveimagetitles[j]); /* issue - print out first item */ console.log(saveimagetitles[j]); } } function saveobject() { for(var r in products[objectindex].image_titles) { saveimagetitles = products[objectindex].image_titles[r]; if(totalobjectimages == objectcount) { //equals lastly item in loop appendobject(); } totalobjectimages++; } }

javascript arrays object for-loop

Perl - Getting value from comma separated line -



Perl - Getting value from comma separated line -

i've got perl file parser trying rewrite. dynamic parser, , need extract value comma separated line.

the line want 1 value looks this:

entryname-8,44544,99955,52,156,15:16:16,15:19:16

(this line in each parsed file starts withentryname-. after - changes each file beingness parsed)

i want value after sec comma. (99955 in illustration above)

i have tried next without luck:

if (/ entryname-\((.*)\,(.*)\,(.*)\)/ ) { $entry_nr = $3; print "entry number = $entry_nr"; next; }

the problem first capture string .* greedy, consume of string. backtrack find 2 commas , result match end.

also:

you matching literal parentheses \( unusual reason. since not have such, never match. you not need escape commas \, you cannot have random space in regex / entry... unless have 1 in target string you not need capture strings not going use

a simple prepare utilize stricter capture grouping (including points above):

if (/entryname-\d+,\d+,(\d+)/ )

this capture $1.

as mpapec points out in comment, may wish utilize text::csv parse csv data. lot safer. if info simple enough, solution do.

perl

javascript - How to know if the user input a registered valid email address exists -



javascript - How to know if the user input a registered valid email address exists -

i want create registration form email required user should input valid registered email address if not registration not complete. how do that?

example:

<form> <input type="email" name="email" required="required" /> <input type="submit" value="submit" name="submit" /> </form>

if don't want usual approval loop selection paying online service, like:

http://verify-email.org/using-api.html

they say:

looking verify email? email verification tool connects mail service server , checks whether mailbox exists or not.

what beingness verified: format: "name@domain.xxx" valid domain: "somebody@new.york" not valid valid user: verify if user , mailbox exist

disclaimer: i'm not in way connected them, advertising not intent. there might similar free services, not trust those, since harvesting email addresses. free cheese in mousetrap.

javascript php jquery html email

c++ - Live 555 c# wrapper -



c++ - Live 555 c# wrapper -

i new c++ , have inherited code uses live555 obsolete libraries. seems there no documentation available when comes developing c# rcw live555 library. wondering if has been in situation before can guide me can start or if has developed rcw asynchronous live555 can point me sample code. hard believe if there no code sample available c# wrapper or 1 has not tried using live55 libraries in .net application. help much appreciated.

if know basics of c++ start larn c++/cli (more info, even more info) because can write .net libraries in c++.

you have long way go. godspeed!

c# c++ live555

java - Is it possible to call into javascript from a background thread running in a cordova android plugin -



java - Is it possible to call into javascript from a background thread running in a cordova android plugin -

i have cordova application using native plugin on android (other platforms come).

my plugin loaded @ application start (<param name="onload" value="true" /> in plugin.xml) , native code work in initialize method (overloaded cordovaplugin class).

essentially, work in initialize method causes event generated @ later time, , need deliver event javascript api.

is there way can asynchronously phone call javascript native side of plugin, without first having called plugin javascript side? (a phone call js->java give me callbackcontext utilize issue callback, assume).

i found https://github.com/apache/cordova-android/blob/master/framework/src/org/apache/cordova/nativetojsmessagequeue.java don't know how utilize , cannot find documentation - i'm not sure if works or intended public use.

can utilize webview.loadurl("javascript: ... "); phone call in javascript side, or disrupt or interfere cordova framework running in js (if any)?

is there recommended way of acomplishing this, , supported across multiple platforms (or concepts applicable other platforms?)

thanks

currently using workaround - have user phone call through plugin (js->java) , in doing provide callback function registering.

in java side store callbackcontext utilize later. 1 of import thing, of import when utilize callbackcontext.sendpluginresult, pluginresult pass has marked pluginresult.setkeepcallback(true) method, otherwise first phone call callbackcontext cause context become invalid future calls.

i haven't noticed threading issues , not sure (but hopeful) applicable other platforms.

java javascript android cordova