Posts

Showing posts from July, 2014

android - how to scroll an expandable list view till its end? -

Image
i made class extending expandablelistview . following code : class customexpandablelistview extends expandablelistview { public customexpandablelistview(context context) { super(context); } protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { /* * adjust height */ heightmeasurespec = measurespec.makemeasurespec( 700, measurespec.at_most); super.onmeasure(widthmeasurespec, heightmeasurespec); } } and used as. expandablelistview list = new customexpandablelistview(kaasmain.this); adapter adapter = new adapter(kaasmain.this, objectslvl1); list.setadapter(adapter); parent.addview(list); // list.setgroupindicator(); list.settranscriptmode(expandablelistview.transcript_mode_always_scroll); list.setindicatorbounds(0, 0); list.setchildin

php - Updating div on button click, when the button is generated by clicking on another button -

on clicking button magic1 or magic2 , div mybox updated text, button id , button (different magic1 , magic2 ). after clicking on newly generated button should display button id of newly generated button in box div. when click on newly generated button, box div not getting updated. here code. jquerycode.php initial file. on clicking button magic1 or magic2 , ajax call page session.php. jquerycode.php file <!doctype html> <?php $first=$_post['q']; echo $first; ?> <html> <head> <meta charset="utf-8" /> <title>my jquery ajax test</title> <style type="text/css"> #mybox { width: 300px; height: 250px; border: 1px solid #999; } #box { width: 300px; height: 250px; border: 1px solid #999; position: absolute; right

javascript - How to call 2 child functions in one main function -

i have several functions in javascript results want use in if statement in function. my problem first listed child function seems returning result. when swap order of functions around still returning result child function listed first. i'm beginner , not familiar functions yet. see example below. please specific answers. function main(a) { return functone(x); // name of function "functone" example return functtwo(y); // name of function "functtwo" example if(functone(x)!="true") { return false; } else { if(functtwo(y)!="true) { return false; } else { return true; } } } you can't return 2 values 1 function. code should function main(a){ if(functone(x)!="true") {return false;} else {if(functtwo(y)!="true") {return false;} else {return true;} } }

c# - Create items in Sitecore tree from a windows application -

i have sitecore web application development completed. testing purposes have populate sitecore tree large number of items. populate sitecore tree want develop .net windows application, because have create more 100,000 items , going take long time. but how connect api of sitecore application windows application? mike edwards has series of blog posts on setting unit tests run against set of sitecore databases, outside of iis. can use information in these posts understand configuration files need import windows application able call sitecore apis without going through iis. note won't have sitecore context.

Help in Matlab Laplace Equation -

i have tried implement laplace equation in matlab code sequence shown below. created laplaceexplicit.m , used function numgrid in same. however, shows error "input variable n undefined". should done? code below- function [x,y,t]= laplaceexplicit(n,m,dx,dy) echo off; numgrid(n,m); r = 5.0; t = r*ones(n+1,m+1); % t(i,j) = 1 includes boundary conditions x = [0:dx:n*dx];y=[0:dy:m*dy]; % x , y vectors = 1:n % boundary conditions @ j = m+1 , j = 1 6 t(i,m+1) = t(i,m+1)+ r*x(i)*(1-x(i)); t(i,1) = t(i,1) + r*x(i)*(x(i)-1); end; tn = t; % tn = new iteration solution err = tn-t; % parameters in solution beta = dx/dy; denom = 2*(1+beta^2); % iterative procedure epsilon = 1e-5; % tolerance convergence imax = 1000; % maximum number of iterations allowed k = 1; % initial index value iteration % calculation loop while k<= imax = 2:n j = 2:m tn(i,j)=(t(i-1,j)+t(i+1,j)+beta^2*(t(i,j-1)

php - catch constants as type string -

i have function takes constant string , know if possible obtain value of constant referent. myfunction( "fetch_assoc" ) argument related pdo::fetch_assoc is possible? i'm putting class work database, thanks yes, can use constant function. note has full qualifier though. constant("pdo::fetch_assoc") , not constant("fetch_assoc") (unless want constant named fetch_assoc in global namespace, not in pdo class).

javascript - Grab Values between Slashes using Regex -

http://example.com/...../post/index/88/mike-hey-dddd i need grab ## index/##/ "##" denotes numeric value. i'm planning run regex javascript. you can use \/ escape slashes want use in regular expressions: so result be: var input = "http://example.com/...../post/index/88/mike-hey-dddd"; var match = input.match(/\/index\/(\d+)/i); // make sure validate result, might not // match given alternative url. var number = match ? match[1] : false; alert(number);

Execute bat file in asp.net localhost -

hi trying execute bat file in asp.net. runs in developer/iis express dosnt in iis. think there permissions. thanks. system.diagnostics.process myprocess = new system.diagnostics.process(); myprocess.startinfo = new processstartinfo(@"c:\data\myfile.bat"); myprocess.start(); myprocess.close(); check permissions on c:\data\ folder. make sure iis_iusrs has read , execute permissions. otherwise if application pool configured run using application pool identity feature "synthesised" account called iis apppool\<pool name> created on fly used pool identity. in case there synthesised account called iis apppool\defaultapppool created life time of pool. can add account c:\data\ folder permissions grant access application.

asp.net mvc 4 - Cannot get route to rename URL -

i'm trying remove 'home' form url, in other words: www.domain.com/home/about/ becomes www.domain.com/aboutus the problem is, home not being removed , can't work out why. can see others have identical questions near identical answers mine here on on so @ loss why won't work. my global.asax is using system.web.http; using system.web.mvc; using system.web.routing; namespace company.ui { // note: instructions on enabling iis6 or iis7 classic mode, // visit http://go.microsoft.com/?linkid=9394801 public class mvcapplication : system.web.httpapplication { protected void application_start() { arearegistration.registerallareas(); webapiconfig.register(globalconfiguration.configuration); filterconfig.registerglobalfilters(globalfilters.filters); routeconfig.registerroutes(routetable.routes); } public static void registerroutes(routecollection routes) {

database design - MySQL constants table -

how can create constants table in mysql match type (using int differentiate among different types) full name of type. constants table should read , not expected ever need changing or updating reading. create table accounts ( accounttype int, ... ); create table accounttypes ( typeid int, typename varchar(255), ); in java there immutablemap<integer><string> (in guava), or enums integer instance variables, , in c++ there enum or static const string[...] ... = { ... } type integer index. is possible, or there better alternative? looks need similar this: create table accounttype ( typeid int primary key, typename varchar(255), typeshortname varchar(255) ); insert accounttype values (1, 'foo', 'f'), (2, 'bar', 'br'), (3, 'baz', 'bz'); create trigger accounttypeinserttrigger before insert on accounttype each row signal sqlstate '45000' set message_text

how to create custom exception with a number in constructor in Java -

if create custom exception string message have: super(message) however, want have double number in exception message. constructor myexception: message:90.6 . throw exception: throw new myexception("my message", 90.6); here code i've tried didnt works. appreciate. public class myexception extends exception { private string message; private double qtyavail; public myexception(string message, double qtyavail){ super(message); this.qtyavail = qtyavail; } why don't do public myexception(string message, double qtyavail){ super(message + " " + qtyavail); }

javascript - Copying AJAX JSON object into existing Object -

i have several javascript prototypes. initially, instances have id's filled in, generic place holder information other data. send message server id , object type (using jquery's ajax function) , server returns json object missing information (but no id). variables in returned object have exact same name in existing object. what's easiest way transfer existing empty object? i've come few alternatives set object equal returned object, copy in id (loses prototype functions?) create function each object takes object identical structure , copies data loop through key-value pairs of json object , copy them existing object if use third option, correct way that? : for (var key in json) { if (object.hasownproperty(key)) { object[key] = json[key]; } } assuming json returned object , object existing object. try using extend() : var newobject = jquery.extend({}, oldobject);

javascript - jQuery is not defined error in Firefox -

i following tutorial plus lesson on jquery. in video tutorial, code same in firefox @ end it's throwing referenceerror: jquery not defined in firebug console. this whole code - <!doctype html> <html> <head> <title>day 1 jquery</title> <style> li {color:blue;} </style> </head> <body> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul> <srcipt src="http://code.jquery.com/jquery-latest.js"></script> <script> jquery(document).ready(function(){ var list = jquery('ul li'); console.log(list); }); </script> </body> </html> i looked @ no help: $ not defined err

ruby - Remove controller_name from URL in Rails -

my url http://www.example.com/players/playersdetail/100006 have players controller. need remove or hide controller , method name (players/playersdetail) url , want name in place of id(100006) ex- http://www.example.com/gagan-gupta ex- http://www.example.com/gagan-gupta/about ex- https://www.facebook.com/gagan-gupta/friends how achieve in ruby on rails? routes is something::application.routes.draw "players/search" post "players/search" "players/playerslist" "players/playersdetail" "players/list" "players/followers" "players/following" end your::application.routes.draw scope ":name" '', to: 'players#show' :about, 'players#about' :friends, 'players#friends end end reference

sql - Single query to count by category by joining multiple tables -

i have following 3 tables. write single query count of number of courses enrolled in student every difficulty level, , total number of courses enrolled in well. students have not enrolled should listed too. students table: student id student name 1 alice 2 bob 3 charlie 4 david courses table: course id course name difficulty level 1 arithmetic 1 2 advanced calculus 3 3 algebra 2 4 trignometry 2 enrollment table: enrollment id student id course id 1 1 1 2 1 3 3 1 4 4 2 2 5 2 3 6 2 4 7 3 3 here's expected output: output: student id student name total courses courses courses

oop - Appropriate way for business logic layer to deal with its neighbors? -

good morning, have use-case in project says if user isn't logged in application display warning message him , determines if user logged in or not managed bean called loginpagecode , class in business logic layer responsible determine if user logged in or not in order take decision displaying message(that action taken when specific action occurs in jsf page called home.jsf ), thought of 2 approaches follows: make home page determine if user logged in or not , pass final decision business logic class make business logic class responsible determining if user logged in or not , require deal directly loginpagecode i want know suitable way of doing point of design. if business logic layer needs know if user logged in, should pass along information argument. the business layer should not need know how user authenticated, if needs know if user logged in should given information -- that's separation of concerns you! :) the main idea can reuse same business rul

c# - Share common functionality between two static classes -

i need share common functionality between 2 static classes: public static class class { public static void classmethod() { sharedmethod<object>(); } //ideally private method internal static void sharedmethod<t>() { } } public static class genericclass<t> { public static void genericclassmethod() { sharedmethod<t>(); } } is there better design here? internal last choice, method sharedmethod has no significance outside 2 classes. requirements: i can't combine them single class, need them separately, 1 generic , other not. the classes need not strictly static, shouldn't instantiable or inheritable. sharedmethod can fall in either class, doesn't matter. this workaround doesn't meet 3 requirements (which impossible imo) made same functionality wanted. i ended using single class marc suggested in comments. had generic class nested inside non generic class act generi

How to get CMake to build a Fortran program with MPI support? -

i trying parallelize fortran program using mpi. use cmake build of program. difficult find support on getting cmake create working makefile fortran mpi support on google, gather, added following commands cmakelists.txt script: find_package(mpi required) add_definitions(${mpi_fortran_compile_flags}) include_directories(${mpi_fortran_include_dirs}) link_directories(${mpi_fortranlibrary_dirs}) this locate mpi on system , set variables found in following 3 commands. in linking line, added mpi libraries variable list of other libraries program needed build. target_link_libraries(${exe_name} otherlibs ${mpi_fortranlibrary_dirs}) doing cmake , make worked build program , program ran; however, when tried add more source required me include mpif.h include file, compilation failed due not being able find header file. not use mpi because compiler cannot find mpi.mod file in path. i inserted "message" commands cmakelists.txt file , printed out values of var

PayPal PDT is not returning a tx value in the QueryString when using custom return URL -

this follow question paypal pdt not returning tx value in query string i struggeling same problem, using real paypal , not sandbox: specify custom return url in paypal form tx parameter not attached anymore. is there still way solve problem? what payment? need give test with, e.g. button or cart upload form post. it's next impossible figure out what's wrong without context reproduce issue. even though there return there may not be tx checkout, instance if it's future subscription payment. in case tx empty. on general note, shouldn't using pdt important. though given transaction successful pdt return may never occur whatever reason. simply, if customer doesn't choose return or browser crashes beforehand. so, don't use pdt. use ipn important business logic. (or if you're able program checkout, there far better options such express checkout api solutiontype=sole)

css - Two Column Div Layout: Left = Fluid, Right = Fixed and Scrollable -

the layout rather simple , easy achieve , has been covered here lot, problem comes when want right div scrollable. i cannot left side fluid , statically positioned while allowing right side fixed width and scrollable. <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <style type="text/css" style="display: none !important;"> body { margin: 0 0 0 0; overflow: hidden; } #page-wrap { background: white; max-width: 100%; } #main-content { background-color: #797979; padding-right: 350px; padding-top: 20px; height: 100%; float: left; position: abs

Relative paths using requirejs in combination with Typescript and AMD -

there several javascript files, organized in folders scripts/folder1, scripts/folder2, ... with requirejs.config.baseurl folder defined default, example scripts/folder1. in requirejs.config.paths files addressed filename, , addressed relative path (like ../folder2/blabla). when coding typescipt file folder2/blabla.ts need module "math" folder1. write import mod1 = module("../folder1/math"); regarding typescript, fine that. can find module. however, requirejs there problem. not know module "../folder1/math", knows "math". the problem seems import statement expects filename, being adressed starting current directory. however, isn't module id requirejs knows about. using absolute paths anywhere, both in requirejs configuration , import statement in typescript, solves problem. am doing wrong? or absolute paths way go? specify baseurl equivalent root folder of typescript files: require.config({ baseurl: './scr

java - Is there any way to refactor this code or re-write it in a compact form? -

Image
i'm working on android app produces image effects on image. below snapshot of app: as can see, on bottom - there horizontal scrollbar, , user touches 1 of images on horizontal scrollbar, same effect applied on above image. i've total of 26 image effects , therefore 26 images in horizontal scrollbar. now, in code, i've find images , set onclicklistener() 's 1 particular listener. i'm accomplishing task in following way: sepiagreenishimage = (imageview) findviewbyid(r.id.sepiagreenish); embossimage = (imageview) findviewbyid(r.id.emboss); sharpenimage = (imageview) findviewbyid(r.id.sharpen); slightyellowishimage = (imageview) findviewbyid(r.id.ligth_yellow); slightbluishimage = (imageview) findviewbyid(r.id.light_blue); slightreddishimage = (imageview) findviewbyid(r.id.light_red); slightgreenishimage = (imageview) findviewbyid(r.id.light_green); negativeimage = (im

android - PHP Google+ Plaform server side user verification and get access token -

i'm using google+ platform on android app plusclient , stuff. when user signs in can interact php server content, on every request want verify if user says is. for purpose, on every php request ask id , access token can call " https://www.googleapis.com/oauth2/v1/tokeninfo?access_token= $accesstoken" , check if id same on access token. is valid server-side user auth verification method? if not, best approach? my other question how access token when connect plusclient send php server? have call googleauthutil.gettoken? yes, you'll need use googleauthutil.gettoken that's photohunt android sample app do. have copy/paste source code https://developers.google.com/+/photohunt/android#authenticating_with_photohunt saccesstoken = googleauthutil.gettoken(ctx, account, "oauth2:" + scopes.plus_login + " " + scopes.plus_profile); hope helps

sql - Exporting table from sqlite3 -

guys! weeks ago exported tables sqlite3 database via commands in prompt. tables exported in files , there actual sql code of creating tables , inserting data in them. this: pragma foreign_keys=off; begin transaction; create table [teachers] ( [teacherid] number(9,0), [firstname] varchar2(20), [lastname] varchar2(20), [office] varchar2(20), constraint [sqlite_autoindex_teachers_1] primary key ([teacherid])); insert "teachers" values(1,'jin','bailey','8-59'); ...... but when try export same table puts actual data in file 1|jin|bailey|8-59 2|chloe|fry|2-18 3|abigail|cervantes|6-83 ... use these commands: .output filename; select * teachers; questin how did previous exporting in way - showing actual code of creating table , inserting data in it? you should able dump table so: .output filename .dump tablename it'll dumped current folder filename specify.

Eclipse Android Project - Google Maps won't update when zooming in -

Image
hi guys i've got problem :s map literally won't update when zoom it, without street names. i'm using eclipse build app , test using tablet runs on android 4.0.4. i've added in 1 marker test out if you're wondering why default code marker there. the code app follows: mainactivity.java: package com.chris.mymap; import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.mapfragment; import com.google.android.gms.maps.model.latlng; import com.google.android.gms.maps.model.markeroptions; import android.os.bundle; import android.app.activity; import android.view.menu; public class mainactivity extends activity { private googlemap map; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); map = ((mapfragment) getfragmentmanager().findfragmentbyid(r.id.map)).getmap(); map.addmarker(new

python - Using bootstrap and django -

i trying bootstrap working in django project , followed tutorial here did not work. when visit local project in browser shows blank page 4 blue links. not exaclty expecting. in pycharm (my ide) tells me have unresolved refrence static_url in template. think problem placing bootstrap in project , defining in settings wasnt enough. ideas? sorry, here how project set up. main_project/ app_1, app_2 , media/, templates/, main_project/ should put boostrap under first main_project, or second also here settings in case matters. static_root = os.path.join(site_root, 'static_files') # url prefix static files. # example: "http://media.lawrence.com/static/" static_url = '/static/' kevin here, author of article python diary. since posted tutorial have created other methods of enabling bootstrap in django project, including handy project template, can downloaded here: http://www.pythondiary.com/templates/bootstrap i have started project on bitbuck

android - Google Play In-App Purchase returns error code -1008: null puchaseData or dataSignature -

i attempting implement google play in-app purchase v3 , after implementing in v2. however, every single time attempt purchase 1 of real in-app products, receive following follow-up error: iab returned null purchasedata or datasignature (response -1008:unknown error) this coming iabhelper.java class, line 452 : if (purchasedata == null || datasignature == null) { logerror("bug: either purchasedata or datasignature null."); logdebug("extras: " + data.getextras().tostring()); result = new iabresult(iabhelper_unknown_error, "iab returned null purchasedata or datasignature"); if (mpurchaselistener != null) mpurchaselistener.oniabpurchasefinished(result, null); return true; } i have verified a) app signed, b) version of app matches draft version # on google play store, , c) user attempting purchase has been added test user. have tried across 3 test accounts , 4 in-app purchase subscription types. should concerned error code? i

Java Swing Scrolling By Dragging the Mouse -

i trying create hand scroller scroll drag mouse across jpanel. far cannot view change. here code: import java.awt.*; import java.awt.event.*; import javax.swing.*; public class handscroller extends jframe { public static void main(string[] args) { new handscroller(); } public handscroller() { setdefaultcloseoperation(exit_on_close); final jpanel background = new jpanel(); background.add(new jlabel("hand")); background.add(new jlabel("scroller")); background.add(new jlabel("test")); background.add(new jlabel("click")); background.add(new jlabel("to")); background.add(new jlabel("scroll")); final jscrollpane scrollpane = new jscrollpane(background); mouseadapter mouseadapter = new mouseadapter() { @override public void mousepressed(mouseevent e) { jviewport viewport = scrollpa

c# - Not Change app.config -

i want change connection string @ runtime in app.config the code wrote follows: var config = configurationmanager.openexeconfiguration(configurationuserlevel.none); connectionstringssection connectionstringssection = (connectionstringssection)config.getsection("connectionstrings"); connectionstringssection.connectionstrings["test"].connectionstring = "sadasd"; //config.connectionstrings.sectioninformation.forcesave = true; config.save(); configurationmanager.refreshsection("connectionstrings"); but app.config not change! you can try method used me , worked me on winforms , mysql project : private void editconstring(string connname, string user, string pwd, string server,string database) { var config = configurationmanager.openexeconfiguration(configurationuserlevel.none); var connectionstringssection = (connectionstringssection)config.getsection("connectionstrings"); con

android - GridView inside ListView giving OutOfMemoryError -

i creating , gallery in images grouped date. using listview has gridview @ each row. when gridview of row contains large amount of images 2000, app crashed giving outofmemoryerror . how fix ? adapter of listview: public class myadapter extends baseadapter { private arraylist<string> itemdetailsrraylist; context mcontext; private layoutinflater l_inflater; public myadapter(context context, arraylist<string> results) { itemdetailsrraylist = results; l_inflater = layoutinflater.from(context); mcontext = context; } public int getcount() { return itemdetailsrraylist.size(); } public object getitem(int position) { return itemdetailsrraylist.get(position); } public long getitemid(int position) { return position; } public view getview(int position, view convertview, viewgroup parent) { viewholder holder; if (convertview == null) { convertview = l_inflater.inflate(r.layout.settinglayout, null); holder = new viewho

c++ - How to take input from a text file into an object and use it in another classes constructor -

im making game , been taken in text files. weapons,rooms,players etc... question how take in single weapon text file of weapons: id: 1. weapon name: katana. damage: 20. weight: 6. id: 2. weapon name: longsword. damage: 17. weight: 9. id: 3. weapon name: waraxe. damage: 22. weight: 20. id: 4. weapon name: staff. damage: 9. weight: 6. and add player classes constructor. code have far: void weapons :: getweapon() { string filename = "weapons\\weapons.txt"; ifstream infile(filename); string garbage; int id; string weapon; int damage; int weight; while(infile>>garbage,infile>>id,infile>>garbage, infile>>garbage,infile>>garbage,infile>>weapon, infile>>garbage,infile>>damage,infile>>garbage, infile>>garbage,infile>>weight,infile>>garbage) { /*infile>>garbage; infile>>id; infile>>garbage;

jquery - Using "data-href" to load an image into a DIV -

i trying link that, when clicked, load image div. here's have far: http://jsfiddle.net/andymp/kgvux/ jquery $(function () { $(".link").click(function (e) { var url = $(this).data('href') $('.enclosure').load(url) return false; }); }); html .enclosure { width: 400px; height: 200px; border: 1px solid black; overflow: hidden; } .link { cursor: pointer; } html <div class="enclosure"> <img src="http://news.bbcimg.co.uk/media/images/67419000/jpg/_67419697_hull-getty.jpg"> </div> <div class="link" data-href="http://news.bbcimg.co.uk/media/images/67424000/jpg/_67424686_67424685.jpg">click me</div> you can't use .load() images. also, request fail either way due cross-origin restrictions. instead, change src property of image: $(function () { $(".link").click(function (e) { var url =

CSS trouble: Float drops to another line (all browsers) -

i understand float drops next line if parent container not wide enough. the site i'm working on magento 1.7.2 install themeforest theme (fortis). expected problem started when included twitter bootstrap (i did @ top of ). my div.header 960px wide. contains: div.header-top working fine. h1.logo floats left, , narrower needs (currently 200px, should 400px). div.header-left element empty, , has left margin of 20px. div.header-right element 485px wide , floats right. the problem if make h1.logo wider, div.header-right drop next line. i should able make div.header-left wide 455px without problem. missing? figured out. looks search bar on top has margin on bottom , pushing .header-right on left. right click , "inspect element" on search field , see mean. you have remove margin or adjust height on .header-top-search-wrapper .

javascript - Module/prototype and multiple instances -

i'm trying grip on "oop" javascript techniques, , began writing small test application today. basically, it's game loop , on each update coordinates increased html element moves. the problem want able run more 1 instance of app, , therefore i'm trying store instance data in this , saved in constructor , exec() method not available in private update() method. seems officer, problem? var jsloth = (function () { var jsloth = function () { var sloth = document.createelement('div'); var attr = document.createattribute('class'); attr.value = 'sloth'; sloth.setattributenode(attr); this.sloth = document.getelementsbytagname('body')[0].appendchild(sloth); }; var exec = function () { this.x = 0; this.y = 0; var = this; setinterval(function () { that.update(); }, 1000/10); }; var update = function () { this.x++;

c# - Windows Phone Develop error Error "Csc.exe" exited with code -1073741819 -

i'm running windows phone 8.0 project in visual studio , started running error when trying compile project after reboot. error 1 "csc.exe" exited code -1073741819. has seen error before? sometimes builds fine error, , wont. this happening me after updated computer on windows 8. fixed going control panel > programs > found instance of visual studio 2012 , repaired it.

java - Feedback on my Binary Search Algorithm -

i have written binary search algorithm, seems bit different other peoples i've seen. hoping community give me feedback whether or not i'm missing something, or doing wrong way. binary search: import java.util.arrays; public class binarysearch { public int[] numbers = new int[] {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}; /** * @param num * @param key * * function recursively searches sorted array of integers, finding specific number (key). * search looks @ midpoint of array, checking see if midpoint number being sought, * if not, depending of whether sought number greater than, or less than, midpoint * function copies upper, or lower, half of array , passes recursive * function call. * */ public int performsearch(int[] num, int key){ if(num.length == 0){ system.out.println("array empty"); return 0; }else{ int mid; in

c++ - How to store the vector.begin() iterator of template type in thrust? -

when attempt assign variable iterator, error: expected ";" , vec thrust::device_vector<my_type> , j int , , my_type template type: for (thrust::device_vector<my_type>::iterator = vec.begin(); < vec.end(); += j) foo(i); is correct way loop on vector? declaring i correct type? standard containers use iterators traversing through collection of other objects (i.e. elements), since iterator abstract concept implemented in standard containers, can implement iterators in following way: typename thrust::device_vector<my_type>::iterator = vec.begin(); (it; != vec.end(); = it+j) foo(*it); here's reference stl containers: http://www.cplusplus.com/reference/stl/

COM C#, How to use C++ to call COM -

i used online example of c# com , call through c++. following c# com code, 1 interface "icalc" , 1 class "calc". namespace comlib { [guid("f40d7bc9-cf53-4613-aa5e-f269ad73808f")] [interfacetype(cominterfacetype.interfaceisidispatch)] public interface icalc { [dispid(1)] long factorial(int n); } [guid("8ee38f2e-75be-4b45-87b6-3f6d15fdbbc5")] [classinterface(classinterfacetype.none)] [comsourceinterfaces(typeof(icalc))] [progid("mycalc")] public class calc : icalc { long icalc.factorial(int n) { long fact = 1; (int = 1; <= n; i++) fact *= i; return fact; } } } the following code in c++ call this function. worked. however, confused code in second line. "icalcptr" come from? or mechanism? coinitialize(null); comlib::icalcptr pcalc; hresult hres = pcalc.createinstance(__uuidof(comlib::calc)); if(failed(hres)) printf("icalcptr::createinsta

uisearchbar - searchBarSearchButtonClicked not firing -

i have researched question. looks common question nothing have tried has worked. new iphone app development , objective c. want @ point type in string in search bar field , return value in nslog() when search button on keypad tapped. my header file looks this: @interface listingmapviewcontroller : uiviewcontroller <uisearchbardelegate> @property (weak, nonatomic) iboutlet uisearchbar *searchbar; @end i have in class file: #import "listingmapviewcontroller.h" @interface listingmapviewcontroller () @end @implementation listingmapviewcontroller - (void)searchbarsearchbuttonclicked:(uisearchbar *)searchbar { searchbar.delegate =self; [self handlesearch:searchbar]; nslog(@"user searched %@", searchbar.text); } @end when click search button nothing outputs. missing? thanks. (answered in question edit. converted community wiki answer. see question no answers, issue solved in comments (or extended in chat) ) the op wrote: sol

jquery - Using $.css() without selector increases performance? -

jquery allows use $.css() method directly , pass raw dom element first parameter. example, if want set 'a' width of mydiv, jquery allows syntax: (option 1): var elem = document.getelementbyid('mydiv'); var = $.css(elem, 'width'); instead of (option 2): var = $('#mydiv').css('width'); option 1 not require selector, , appears rely on global jquery object instead of creating new one. can't find documentation in jquery api or online method. assume performance increase, when jquery objects required in animations. reason why shouldn't using method? thanks! edit: perf tests show option 1 bit faster. doesn't seem there's reason not use $.css() directly. answers! yeah, first 1 faster. can css value. i made perf test here: http://jsperf.com/jquery-css-signature may revise , test out other options. now facts set, @ these level of performance optimisation, don't think worth overhead. go more clear/main

c++ - strlen of a char array is greater than its size. How to avoid? -

i defined array: char arr[1480]; now, file, read 1480 chars , put arr (by doing arr[i]=c). know 1480 chars because use while loop read 1 char ar time (istream.get()) , stop when incrementing index = 1480. however, after that, strlen(array) , returns 1512. how come? happens in occasions, not in occasions, though every time read file, read 1480 chars. my doubt 1 char might occupy more 1 unit (units returned strlen(arr)). if so, how can fix this? thanks ps: asked problem earlier pointer gets garbaged, , cause when have buffer (arr) of length > 1480. the array size must include string terminator. since read size of array can't (and don't) add string terminator. strlen function, , other string functions, uses string terminator character find end of string. if it's not there continue until finds it. if may have no more 1480 characters in string, should have array of size 1481, last being string terminator '\0' .

javascript - Disabling a page's focus-checking function using GM -

this question has answer here: stop execution of javascript function (client side) or tweak it 4 answers i'm trying stop page stopping when thinks it's lost focus. how disabling function within webpage using gm? i'll try giving script on page, can me decipher better, lol. <script> var nmn=0,isa=0,pr=1,wc=1,clkt='ptc',clki=303250,clkc=634089,capt=1367698325,stimg='http://something.com/img/',fxp=0,timer=30,tfrac=188,wmw=640,wmh=320,txbop='******************************\nthis website attempting break out of frame.\nchoose stay on page otherwise won\'t paid.\n******************************',txtt='<table cellpadding=0 cellspacing=0><tr><td>',txet=txtt+'<img src="'+stimg+'error48.png" class=icon /><td>',txpb=txtt+'<img src="'+stimg+'clock48

javascript - select day and special date load by ajax to set in gldatepicker -

i using gldatepicker.i want load settings database ajax gldatepicker such day of week,special date etc.now have following js code this: $(document).ready(function () { loadallsettings(); }); var loadallsettings = function () { startdate = ''; enddate = ''; selectday = ''; offdays = ''; $.ajax({ url: "bs_client_function.php", type: "post", datatype: "json", data: { action: 'getdaterange' }, success: function (html) { // alert(html.start); startdate = date.parse(html.start); enddate = date.parse(html.end); } }); $.ajax({ url: "bs_client_function.php", type: "post", datatype: "json", data: { action: 'getoffdays' }, success: function (html) { = 0; offdays = &#

jpa - Spring LocalContainerEntityManagerFactoryBean scanForPackages and Hibernate package-level type definitions -

in spring 3.1 , higher localcontainerentitymanagerfactorybean supposed able configure jpa entitymanagerfactory without persistence.xml. configuration included in bean definition localcontainerentitymanagerfactorybean instead. when use packagestoscan method tell factory bean scan entity classes doesn't seem picking hibernate type definitions defined @ package level. package-info.java: @org.hibernate.annotations.typedefs({ @org.hibernate.annotations.typedef(name = "typea", typeclass = com.foo.type.a.class), @org.hibernate.annotations.typedef(name = "typeb", typeclass = com.foo.type.b.class) }) package com.foo.type; spring-jpa.xml: <bean id="entitymanagerfactory" class="org.springframework.orm.jpa.localcontainerentitymanagerfactorybean" lazy-init="true"> <property name="datasource" ref="datasource" /> <property name="persistenceproviderclass" value="

The regex for a simple case -

can give me regular expression validate string _ _._ _ _ numbers, point @ 3rd position. well, ^\d\d\.\d\d\d$ (or ^\d{2}\.\d{3}$ ), depending on regex engine you're using. depending on sort of matching function you're using, may not need ^ , $ (start , end) markers either. if engine older 1 doesn't recognise \d , can use [0-9] instead.

wpf - is it possible execute a method in the view when change a property in the view model with MVVM pattern? -

i open dialog in application , close view when property in view model changed. so thinking in ths way: 1.- in view.axml.cs (code behind) have method named close() execute method close of view. 2.- in view model have property called viewmodelclosing, bool. 3.- view, in way, don't know how, binding property of view model , execute method in code behind when property changed. is possible that? thanks. Álvaro garcía the simplest , imo best way accept icommand in viewmodel controller. since viewmodel should not dependent on view or matter viewcontroller, follwoing solution uses dependency injection / inversion of control. the delegatecommand (aka relaycommand) wrapper icommand i have kept code minimum focus on solution. public class viewcontroller { private view _view; private viewmodel _viewmodel; public viewcontroller() { icommand closeview = new delegatecommand(m => closeview()); this._view = new view();

linux - how to rename file when zipping it? -

i'm planning pack files zip file on ubuntu os. example, have files a, b , c. want put them new.zip file. these files have renamed a1, b1 , c1 in zip file. suggestions. thanks. you can use zipnote. use command : echo -e "@ myoldfilename.txt\n@=mynewfilename.txt" | zipnote -w myzip.zip

php - User rights in my cms -

i developing cms hobby , got stuck on something....in mysql db have different classes of users:admins, normal users, veterans, premium etc.....is there way create php file wich contains settings each user class? , use function or check if user has right to...create page example.... for moment checking users rights sessions... if($_session['user_type']=='admin'||$_session['user_type']=='premium'){ //do stuff }else if()......... { // .............. } but want that check_user_right(user_name); if ($can_create_page) == true{ do......}else{....} first of all, should know should storing user information in database. then, when logs in , verify login, can store or user id in session, , other user information, user_type , query database based on id. not sure if you're doing yet, should if aren't. as far user rights go, have 2 options. the oop way this 1 recommend. entails creating user class encapsulates of logic ret

arrays - vectorize operation in C with Cell BE -

i have following scenario: 1d array of dim size, , 2 arrays of dim/2 size. want copy elements of smaller arrays larger one. using following code(i running code on spu): unsigned char output_data1[dim/2] __attribute__ ((aligned(16))); unsigned char output_data2[dim/2] __attribute__ ((aligned(16))); unsigned char output_data[dim] __attribute__ ((aligned(16))); (ix = 0; ix < dim; ix++) { if (ix < dim / 2) { output_data[ix] = output_data1[ix]; } else { output_data[ix] = output_data2[ix - dim / 2]; } } i trying obtain same functionality, vectorizing above operation. have following code: vector unsigned char *v = (vector unsigned char*)output_data; vector unsigned char *v1 = (vector unsigned char*)output_data1; vector unsigned char *v2 = (vector unsigned char*)output_data2; int length=dim/(16/sizeof(unsigned char)); (j = 0; j < length; j++) { if (j < length / 2) { v[j