Posts

Showing posts from June, 2010

Execute shellcode by casting to function pointer in Visual C++ -

in gcc works fine. code goes like: unsigned char b[50] = "\xda\xd1 ... \x0"; //some shellcode terminating \x0 ( (void(*)())b )(); //cast b function pointer void void, run but when put in visual c++, spits out error message: 1>..\test.cpp(132): error c2440: 'type cast' : cannot convert 'unsigned char [50]' 'void (__cdecl *)(void)' 1> there no context in conversion possible anyone know why so? a proper debugger tell what's going wrong. can guess code causing access violation because buffer want jump not executable. probably you're on default- dep -enabled system vista or 7, have make sure shellcode executable. that, first use virtualalloc allocate new, executable buffer , copy shellcode it, execute it: void *exec = virtualalloc(0, sizeof b, mem_commit, page_execute_readwrite); memcpy(exec, b, sizeof b); ((void(*)())exec)(); by way, don't need null-terminate shellcode (c++ terminate string literal aut

c++ - How to convert int to const int to assign array size on stack? -

i trying allocate fixed size on stack integer array #include<iostream> using namespace std; int main(){ int n1 = 10; const int n = const_cast<const int&>(n1); //const int n = 10; cout<<" n="<<n<<endl; int foo[n]; return 0; } however, gives error on last line using n define fixed error c2057: expected constant expression . however, if define n const int n = 10 , code compiles fine. how should typecast n1 trat const int ? i tried : const int n = const_cast<const int>(n1) gives error. edit : using ms vc++ 2008 compile this... g++ compiles fine. how should typecast n1 treat const int ? you cannot, not purpose. the size of array must called integral constant expression (ice). value must computable @ compile-time. const int (or other const-qualified integer-type object) can used in integral constant expression if initialized integral constant expression. a non-const o

ruby on rails - How to find a specific row in csv -

i'm using ruby 1.9.2. csv file follows.., name, id, no, dept tom, 1, 12, cs hendry, 2, 35, ec bahamas, 3, 21, frank, 4, 61, ee i want print specific row ('tom'). tried out in many ways, didn't find exact result. recommended options "fastercsv". applicable version. also, noticed csv print field column wise. how print entire row using csv in rails. ruby code follows require 'csv' csv_text = file.read('sampler.csv') csv = csv.parse(csv_text, :headers => true) csv.each |row| puts "#{row[:name]},#{row[:id]},#{row[:no]},#{row[:dept]}" end puts csv.find {|row| row['name'] == 'tom'}

jquery bounce accelerates automatically -

i im not sure why bounce effect accelerating. i have effect on image, setinterval. starts perfectly, effect starts accelerate automatically. though problem of seconds in interval , bouncing time parameter, not correct. i have suspicion, problem start, when change tab or window. does had same problem or there way emulate bounce effect? here snippet: <div style="position:absolute; margin-left:675px; margin-top:50px; width:25px; height:25px;"> window.setinterval(function(){ $(".show-awards-new-image").effect("bounce", { times:2, direction:'up', distance:25 },200); },4000); </div> ty! as can see in fiddle: http://jsfiddle.net/qw9r5/1/ there no accelerate. you can use .animate() function jquery (no ui needed) simulate bounce effect rather easy.

Iphone page curl effect -

i using code page curl effect ....its work fine in simulator , device... not (settype:@"pagecurl") apple documented api , caused rejected iphone developer program during app store review process: animation = [catransition animation]; [animation setdelegate:self]; [animation setduration:1.0f]; animation.startprogress = 0.5; animation.endprogress = 1; [animation settimingfunction:uiviewanimationcurveeaseinout]; [animation settype:@"pagecurl"]; [animation setsubtype:@"fromright"]; [animation setremovedoncompletion:no]; [animation setfillmode: @"extended"]; [animation setremovedoncompletion: no]; [[imageview layer] addanimation:animation forkey:@"pageflipanimation"]; so changed , using [uiview beginanimations:nil context:null]; [uiview setanimationduration:1]; [uiview setanimationdelegate:self]; [uiview setanimationbeginsfromcurrentstate:yes]; [uiview setanimationcurve:uiviewanimationcurvelinear]; [u

java - Restartability for access to the database -

i'm trying access oracle database, see code below. the problem database cluster db if 1 down, can access other. has problem staying on 1 node possible me update java code , if fails check again until connection has been established? i'm using properties-file insert credential database. when connection has been established query entered , result returned. public static string connectdb(string configfile, string query) throws filenotfoundexception, ioexception, sqlexception, classnotfoundexception{ properties p = new properties(); p.load(new fileinputstream(configfile)); string servername = (p.getproperty("rms_dbservername")); string portnumber = (p.getproperty("rms_portnumber")); string sid = (p.getproperty("rms_sid")); string url = "jdbc:oracle:thin:@//" + servername + ":" + portnumber + "/" + sid; string username = (p.getproperty("rms_username")); string password =

ios - Hide label in TableViewCell when swipe to delete -

i want able hide label in uitableviewcell in order stop overlapping title whenever user swipes delete cell. i'm using following code initiate , handle swipe delete: - (void)tableview:(uitableview *)tableview commiteditingstyle:(uitableviewcelleditingstyle)editingstyle forrowatindexpath:(nsindexpath *)indexpath { if (editingstyle == uitableviewcelleditingstyledelete) { [self.tableview beginupdates]; // avoid nsinternalinconsistencyexception // delete project object swiped project *projecttodelete = [self.fetchedresultscontroller objectatindexpath:indexpath]; nslog(@"deleting (%@)", projecttodelete.name); [self.managedobjectcontext deleteobject:projecttodelete]; [self.managedobjectcontext save:nil]; // delete (now empty) row on table [self.tableview deleterowsatindexpaths:[nsarray arraywithobject:indexpath] withrowanimation:uitableviewrowanimationleft]; [self performfetch]; [s

mysql - Subpartitioning several partitions in a table -

i came here find solutions lot of times , found response fit perfect me. , decided write first question. is first time have mount db partitioning not simple partitioning, why didn't found solution in mysql official documentation. i have table: create table systemevents ( id int unsigned not null auto_increment primary key, receivedat datetime null, devicereportedtime datetime null, facility smallint null, priority smallint null, fromhost varchar(60) null, message text, ntseverity int null, eventsource varchar(60), eventuser varchar(60) null, eventcategory int null, eventid int null, infounitid int null , syslogtag varchar(60), eventlogtype varchar(60), ) and need make partitions "fromhost" key: partitiom list (fromhost) ( partition p01 values in ('server1'), partition p02 values in ('server2'), partition p03 values in ('server3', 'server4'), partition p04

vba - Remove selected numbers from a comma separated list management in Excel? -

this might little tricky, vba... i have comma separated lists in cells based on start times on 5 minutes intervals need remove times 5 apart. the numbers text, not time @ point. example, 1 list 2210, 2215, 2225, 2230, 2240 (the start times). in case, 2215 , 2230 should removed need remove opposite numbers (i.e.,2210 , 2225) in other cases (the end times). someone helped me specs: a cell contains times: t(1), t(2), t(3), ... t(n) . starting @ time t(1) , each value in list examined. if t(x) less 6 minutes after t(x-1) delete t(x) , renumber t(x+1) t(n) . input: 2210, 2215, 2225, 2230, 2240 output: column1: 2210 column2: 2240 this think require. option explicit sub deleteselectedtimes() dim rowcrnt long rowcrnt = 2 while cells(rowcrnt, 1).value <> "" cells(rowcrnt, 1).value = processsinglecell(cells(rowcrnt, 1).value, 1) cells(rowcrnt, 2).value = processsinglecell(cells(rowcrnt, 2).value, -1) rowcrnt = row

node.js - How should I structure my node/express/mongodb app? -

i'm curious how people structures node.js app? usually create models/ views/ controllers/ , that's simple that. i'm kinda new node.js scene , i'm trying learn as can how community works. any answer welcome, thanks! for it's worth, actual setup this, until come (or find) better: lib db index.js model.js ... handler index.js whatevermakessenseformyparticularwebsite.js ... router index.js model1restroutes.js model2restroutes.js iuroutes.js ... config.js (or folder multiple files if makes sense) server.js (main) public css img js test ... views ... so yes, models, views, separate routes , actual handlers' implementation. decoupling, dependency injection way. way more testable/mockable.

linux - Can't open more than 1023 sockets -

i'm developing code simulating network equipment. need run several thousand simulated "agents", , each needs connect service. problem after opening 1023 connections, connects start time out, , whole thing comes crashing down. the main code in go, i've written trivial python script reproduces problem. the 1 thing unusual need set local address on socket when create it. because equipment agents connecting expects apparent ip match should be. achieve this, have configured 10,000 virtual interfaces (eth0:1 eth0:10000). these assigned unique ip addresses in private network. the python script (only runs 2000 connnects): import socket = 0 b in range(10, 30): d in range(1, 100): += 1 ip = "1.%d.1.%d" % (b, d) print("conn %i %s" % (i, ip)) s = socket.create_connection(("1.6.1.1", 5060), 10, (ip, 5060)) if remove last argument socket.create_connection (the source address), can 2000 connections.

iphone - iOS 5.1 : -[UIColor colorWithPatternImage:] background color draws solid black -

Image
while testing application in today's release of ios 5.1 gm, noticed of views drawing solid black rather patterned background color. exact same code works fine on previous ios releases (tested on 4.2 - 5.0.1). see screenshots: has else experienced this? there workaround? answering own question (it took me few days debug this, saves else time ;) ): the root cause involves using patterned uicolor (via +[uicolor colorwithpatternimage:] ) background color on uiview above uiimageview same image. example: uiimageview *imageview = [[uiimageview alloc] initwithimage:animage]; [_containerview addsubview:imageview]; uicolor *patterncolor = [uicolor colorwithpatternimage:animage]; uiview *patternview = [[uiview alloc] initwithframe:frame]; [patternview setbackgroundcolor:patterncolor]; [_containerview addsubview:patternview]; both views draw black, , there appears caching issue other uses of image draws black until application suspended/resu

Calling App URL through Facebook IFrame -

i've been working on facebook app , have started think how i'm developing app. right have run php app executing facebook app url in turn calls url through iframe. when try skip 'call through facebook' step facebook php app credentials don't work. (blank user id) ideally launch app locally , let pull necessary credentials facebook. possible?

java - App is force closing when i run it? Unable to start activity -

when run app, , press on button force closes. fixed android manifest , cannot find problem. here logcat: 03-07 23:48:53.035: d/dalvikvm(5457): gc_external_alloc freed 43k, 49% free 2797k/5379k, external 1596k/2108k, paused 99ms 03-07 23:48:53.132: d/dalvikvm(5457): gc_external_alloc freed 1k, 49% free 2796k/5379k, external 3471k/4335k, paused 35ms 03-07 23:48:53.691: d/dalvikvm(5457): gc_external_alloc freed <1k, 48% free 2798k/5379k, external 5048k/5580k, paused 53ms 03-07 23:48:54.281: d/dalvikvm(5457): gc_external_alloc freed <1k, 48% free 2799k/5379k, external 8143k/8403k, paused 48ms 03-07 23:48:55.996: d/androidruntime(5457): shutting down vm 03-07 23:48:55.996: w/dalvikvm(5457): threadid=1: thread exiting uncaught exception (group=0x40015578) 03-07 23:48:56.039: e/androidruntime(5457): fatal exception: main 03-07 23:48:56.039: e/androidruntime(5457): android.content.activitynotfoundexception: unable find explicit activity class {izzy.n/izzy.n.main1}; have declared

python - How i can find DIR which is present in last in list -

import ftplib import re import string ftp = ftplib.ftp('') # access ftp link. ftp.login ("") ftpdir = ftp.cwd('') data=[] ftp.dir(data.append) line in data: string.find("dir","data") if "dir" in line: print line with code got list of dir names present in ftp server, how can find dir present in last in list. my output is: 12-09-11 10:04pm <dir> mcl_201147_hw79u_05 12-08-11 01:19am <dir> mcl_201148_hw79u_02 12-16-11 12:53pm <dir> mcl_201149_hw79u_07 12-25-11 12:11am <dir> mcl_201150_hw79u_05 01-07-12 12:00am <dir> mcl_201151_hw79u_04 01-07-12 11:37pm <dir> mcl_201152_hw79u_05 01-17-12 01:06am <dir> mcl_201201_hw79u_04 01-29-12 12:52am <dir> mcl_201202_hw79u_04 02-04-12 01:06am

javascript - Dll consumption in metro apps built using winJs -

can consume our own c# dlls in metro style apps built using html & win js? you can build new c# dlls winrt components , call them javascript. msdn has walkthrough that's relevent.

iphone - Disable Border Around System Image Located UINavigationBarItem -

Image
i want disable border around iphone sdk's add button, it's "+" button (no black bg): this seems simple task when it's located in toolbar, not when it's located in uinavigationbar. anyways, if knows how, or if it's possible, please share! here's current code in rootviewcontroller.m : self.title = @"code master"; addbutton = [[uibarbuttonitem alloc] initwithbarbuttonsystemitem:uibarbuttonsystemitemadd target:self action:@selector(addbuttonclicked:)]; self.navigationitem.rightbarbuttonitem = addbutton; edit @dee code works great, displays want! there problem i'll explain: edit button: left side of uinavigationbar done button: left side of uinavigationbar (hidden); when edit button clicked, replaces edit button "done" button plus button: right side of uinavigationbar; hides when in " edit mode ", shows when in " normal mode (when done button not visible) "

php - How do I output certain index values from a foreach array? -

this structure in database: items |itemlink ---------------------- kill bill|kill bill link preman |preman link this code: $db = new pdo("mysql:host=$hostname;dbname=$database", $username, $password); $items = 'select items menus'; $itemlink = 'select itemlink menus'; $itemquery = $db->query($items); $linkquery = $db->query($itemlink); $fetchitem = $itemquery->fetchall(pdo::fetch_assoc); $fetchlink = $linkquery->fetchall(pdo::fetch_assoc); $merged = array_merge($fetchitem,$fetchlink); foreach($merged $entry) { foreach( $entry $key => $value ) { } } from above code, how output items' datas? using example above answer question $result = mysql_query('select * names'); while ($row = mysql_fetch_array($result, mysql_assoc)) { echo $row["firstn

Where to download Eclipse Indigo SR1 - 3.7.1? -

where download download eclipse ide java , report developers indigo sr1? page: http://www.eclipse.org/downloads/ contains 3.7.2. page: http://wiki.eclipse.org/older_versions_of_eclipse links 3.7.0. page links platform/sdk: http://download.eclipse.org/eclipse/downloads/drops/r-3.7.1-201109091335/index.php but need report developers package feature list: http://www.eclipse.org/downloads/packages/eclipse-ide-java-and-report-developers/indigor for 3.7.1. try http://www.eclipse.org/downloads/packages/release/indigo/sr1

php - Magento, sort by YES/NO attribute -

i have load collection of products , sort them further display. originally collection sorted date. works flawlessly. had add new yes/no attribute products. worked out great well. the thing wasn't able figure out how sort collection attribute. collection have sorted new attribute date. i thought work: $collection->addattributetoselect('name'); $collection->addattributetoselect('yesnoattr'); $collection->addattributetoselect('special_to_date'); $collection->addattributetoselect('short_description'); $collection->addattributetoselect('image'); $collection->addattributetosort('yesnoattr', 'asc')->addattributetosort('special_to_date', 'asc'); $products = $collection->load(); it doesn't. tried set order: $collection->setorder('yesnoattr','asc'); i tried sorting new attribute, didn't work either, i'm pretty sure has nothing me trying sort 2

internationalization - How should I handle a template string in Xtext? -

i have following input: a: "a {foo foo}" where foo of type foo ; business layer provide value variable. after processing input, 2 files generated: properties file , java class: a=a {0} public static i18nmessage a( foo foo ) { return new i18nmessagebuilder().id( "a" ).args( foo ).build(); } the idea assign each message id gives me java class contains methods (where name == id) , accepts typed parameters complete messages. my question: how should handle text strings in xtext grammar? have code completion parameter types ( foo ) have no idea how handle rest of string can contain spaces , valid unicode character. suggestions? i found better solution gives pretty simple grammar , solves other problems: a(foo foo): "a " foo; so text message list of strings , parameters. way, code completion simple , there no need escape sequences if want add formatters: a(date d): "date " d( "short" );

scala - Why put a generic type next to a function? -

when @ scala libraries see code this. why put test [a] . def test[a](block : int => unit) : unit = { block(10) } test { u => println(u) } this valid suppose. runs same way. def test(block : int => unit) : unit = { block(10) } i've been curious reasoning(or design pattern) behind it. thanks. the type parameter a makes no sense here because not used. def test[a](block: int => a): = block(10) here a specifies return type.

multithreading - Thread-safe class in Java by means of synchronized blocks -

let's have simple java class myclass . public class myclass { private int number; public myclass(int number) { this.number = number; } public int getnumber() { return number; } public void setnumber(int number) { this.number = number; } } there 3 ways construct thread-safe java class has state: make immutable public class myclass { private final int number; public myclass(int number) { this.number = number; } public int getnumber() { return number; } } make field number volatile . public class myclass { private volatile int number; public myclass(int number) { this.number = number; } public int getnumber() { return number; } public void setnumber(int number) { this.number = number; } } use synchronized block. classic version of approach described in chapter 4.3.5 of java concurrency in practice. , funny thing has error in example mentioned in

php - Loop through array of DIV ids, and refresh those DIVS every x seconds -

say have 4 divs: <div id='blue'></div> <div id='refresh12'></div> <div id='red'></div> <div id='refresh23'></div> i'm putting every div on page begins 'refresh' array this: var divs = $('div[id^="refresh"]'); now, want do, refresh divs in array every 5 seconds. know need use setinterval, i'm not sure how start loop. also, divs aren't pulling content page, it's same page, dynamic data needs refresh every 5 seconds. appreciated. thanks. using setinterval not best idea , because if operation takes long , blocking, calls might stack up. you can use settimeout() calls achieve want: var divs = $('div[id^="refresh"]'); settimeout(function refreshthem () { //code refresh divs divs.xy(); settimeout(refreshthem, 5000); }, 5000); or if want first refresh run @ once: (function refreshthem () { //code refre

c++ string array initialization -

i know can in c++: string s[] = {"hi", "there"}; but there anyway delcare array way without delcaring string s[] ? e.g. void foo(string[] strarray){ // code } string s[] = {"hi", "there"}; // works foo(s); // works foo(new string[]{"hi", "there"}); // doesn't work in c++11 can. note beforehand: don't new array, there's no need that. first, string[] strarray syntax error, should either string* strarray or string strarray[] . , assume it's sake of example don't pass size parameter. #include <string> void foo(std::string* strarray, unsigned size){ // stuff... } template<class t> using alias = t; int main(){ foo(alias<std::string[]>{"hi", "there"}, 2); } note better if didn't need pass array size parameter, , thankfully there way: templates! template<unsigned n> void foo(int const (&arr)[n]){ // ... } note match s

ios - Is there a way to programmatically change the value of a UIStepper based on a calculation? -

let's have 3 uistepper s. when change value of one, values of other steppers change based on formula. stepper 1 value 10. stepper 2 value 5. stepper 3 value 3. if change stepper 10 +/- 1, might change value in stepper 2 +/- one. is possible? it absolutely possible. you can imagine scenario: uistepper *stepperone = [[uistepper alloc] initwithframe:frame]; [stepperone addtarget:self action:@selector(stepperonechanged:) forcontrolevents:uicontroleventvaluechanged]; - (void)stepperonechanged:(uistepper*)stepperone{ //this method called on target of first stepper on uicontroleventsvaluechanged //decrease value 1 steppertwo.value --; //or //increase value 1 steppertwo.value ++; }

Facebook graph api returns (#200) Requires extended permission: read_stream -

in facebook app have 7 test users , users mutually friends also. i have requested https://graph.facebook.com/me/home?access_token= 'mytestuseraccesstoken' but returns { "error": { "message": "(#200) requires extended permission: read_stream", "type": "oauthexception", "code": 200 } } facebook docs says give extended permissions eg:read_stream i gave it. still getting same error

javascript - How to detect if a page has fully rendered using jQuery? -

when using $(document).ready(functioon(){alert("loaded.")}); pops alert box says "loaded." before page has loaded (in other words there're loading still going on images). any thoughts? $(window).on('load', function() { //everything loaded });

SVN : Export modified files of revisions committed with specific comment -

i'm using svn commit comments associate keywords commited files. i'm trying find commited files - in revision - having specific keyword in comment. possible ? thanks advance ! edit more info : can use tortoisesvn (from local, windows 7 64bit) or command line (from our integration server, linux) edit again : "show log" in tortoise don't let me searching date. right can't search last year... 15/02/2012... way fix ? ============================================================================= final answer : made work wanted. wanted these logs use them svn exports. final script named exportallrevisionsfromkeyword.sh : #!/bin/sh if [ ! $1 ];then echo "no keyword specified. needs example ticket number : project-xxx. command : ./searchcommitsfromcomment.sh project-xxx";exit;fi cd /root/projets/myproject/ search=$1 echo "searching revisions committed keyword "$search svn log | awk '{ if ( $1 == &quo

c++ - MFC - Manually expand stringtable -

can provide explanation or link explains how stringtable in mfc resource file defined , can manually expanded? i tried it, failed in multi project solution. projects in said solution have own resource files , renamed resource.h-files. when application tries access string resources, error message 'resource string '22392' not found' shows up. 22392 id of string tried create. don't similar error message if use defined string id instead. using visual studio 2010's wizard add string resource didn't work either. shows correctly in listing of resource symbols , in string table editor. needless haven't participated in creation of solution. thanks help. [edit1] i excluded possibility of conflict performing ‘find in files’ value used , using other values well: 22390, 22391, 22393, 22394, 22395. got same result. [edit2] i repeated steps did in complex solution in new, clean , simple mfc application 1 project , worked without problems. therefo

c# - Draw travel distance in XNA 4 -

so creating xna game @ college , need cannot seem figure out myself , i'm pretty new this. basically have spaceship scrolling background of stars. have falling asteroids , point of game travel far possible without being hit said asteroids. i'm looking guidance how measure theoretical distance travelled ship , draw on screen? any appreciated. many thanks. solution a somewhere in code defining offset of backdrop each frame. invert* value , add total amount every frame: totaldistance += -backdropoffset; if offset defined in pixels have convert game world unit (kilometers, lightyears, ...) before displaying distance. * if ship moves forward, backdrop "slides" in other direction. solution b (more work less headaches) it not backdrop moving; it's ship. why not move ship , follow camera? you able kinds of motion. right have invert every movement of ship , apply backdrop. kind of counter-intuitive, don't think? going solution code

android - ViewPager Indicator with custom ListView -

first, apologise english since it's not good. thanks. application contains few listwiews adapters. data listviews taken parsed xml file located in internet. have 1 tabhost 3 tabs , different listviews in each tab. want change tabhost new , slighty method - viewpager indicator jake wharton (https://github.com/jakewharton/android-viewpagerindicator), 'cause there awsome sliding effect. i tried include code in sample project , it's running good. have listview in 1 fragment of viewpager , simple textview in 2 others fragments. it's working. code of viewpageradapter shown below: package com.formatbce.pager; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.map; import android.content.context; import android.os.parcelable; import android.support.v4.view.pageradapter; import android.support.v4.view.viewpager; import android.view.view; import android.widget.abslistview; import android.widget.abslistview.onscrolllistener;

Ruby service oriented architecture - how to ensure synchronization? -

i'm newbie writing service-oriented applications, might trivial question some. my current setup this: 1 - base rails app. contains routes , application logic. 2 - few services. have extracted these base rails app. resources db extensive or used no-sql solution. so, have ended doing this in rails app, have places controller responds basic crud operations on places. internally http call places service. def show req = typhoeus::request.new('http://127.0.0.1:7439/places/#{params[:id]}.json') @places = req.response.body end the problem is, if make more 1 service call, how make sure have response before rendering views ? also, 1 service call, how rails rendering process work ? example, if service takes long time respond, page gets rendered or wait infinitely response ? i cannot answer question typhoeus i've never used it, try answer more problem in soa , helpful. the common thread ui should composed many services , tolerant possibility of se