Posts

Showing posts from 2010

php - Display checkmark &#x2713 in tcpdf -

i'm using tcpdfs writehtml convert html-code pdf . works fine far except checkmark (&#x2713) converted questionmark instead of... well, checkmark ;-) pdf created utf-8, neither feeding checkmark nor hex-representation resulted in showing correct checkmark. tried used fonts helvetica , times , shipped tcpdf, both display ?. idea how checkmark pdf? try one html_entity_decode('✓', ent_xhtml,"iso-8859-1");

neo4j - How do I create multiple weighted edges between nodes -

Image
i want keep browse history, to calculate behaviour among browsing pages. so designed following graph show idea, as can see, there 4 edges between page a , page b , so how create kind of relationships , nodes ? how average browsing time ( 20min ) min browsing time max browsing time any suggestion , ideas? thanks i'm bit confused. relationship mean? represent amount of time spent on page before user browses page b? just going model , goals, maybe work? match (a:page)-[r:browsed_to]->(b:page) return avg(r.time_spent) for min , max time replace avg min , max

Display Image in android Imageview using Asynctask -

i have image being sent me through json string. want convert string image in android app , display image in imageview.i have problem, using asynctask , code in doinbackground method: protected boolean doinbackground(final string... args){ jsonparser jsonparser = new jsonparser(); jsonarray json = jsonparser.getjsonfromurl(url); if(json!=null){ (int = 0; < json.length(); i++){ try{ jsonobject c = json.getjsonobject(i); string displayimagefromurl = c.getstring(imageurl); string clearurl = displayimagefromurl.substring(displayimagefromurl.indexof(",")+1); byte[] decodingstring = base64.decode(clearurl, base64.default); bitmap = bitmapfactory.decodebytearray(decodingstring, 0 , decodingstring.length); string showcreateddate = c.getstring(createddate); string showarticletitle = c.g

php - Google Admin SDK: You are not authorized to access this API -

Image
since google login auth disabled since last week i'm trying oauth 2.0 working service account. want give users on our internal web application oppurtunity set there out of office. i downloaded lastest google apis client library php . in google developer console , have created new project application , created service account credentials. have enabled api service: admin sdk in developer console. i have granted account user id access correct scopes (i think): when use service-account.php example , change details, recieve json access token, when curl request (same before) e-mail settings user, error "you not authorized access api." occur. my code: <?php include_once "templates/base.php"; require_once realpath(dirname(__file__) . '/../src/google/autoload.php'); $client_id = '124331845-deletedpart-hbh89pbgl20citf6ko.apps.googleusercontent.com'; //client id $service_account_name = '124331845-deletedpart-89pbgl20citf6ko@devel

python - Installing eggs theme in django-oscar -

i found theme django-oscar here : https://github.com/eggforsale/oscar-eggs-theme there no documentation available install it. tried replacing appropriate files in oscar/templates directory doesn't work.

Display a scrollable image from a url in android studio -

i'm trying create activity display image obtained url. want width of image adapt screen height of image can longer screen image becomes scrollable (vertically). first of all, displayed image drawable folder , worked following code : <scrollview android:layout_width="fill_parent" android:id="@+id/scrollview1" android:layout_height="wrap_content" android:layout_alignparenttop="true" android:layout_alignparentleft="true" android:layout_alignparentright="true" android:scrollbaralwaysdrawverticaltrack="true"> <linearlayout android:id="@+id/linearlayout1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal"> <imageview android:src="@drawable/programme" android:layout_height="wrap_content&qu

scala - Using locks on Akka Actors -

i have actor goes (assume receive method overridden somewhere else): class myclass extends actor { def method1() = { ... } def method2() = { ... } def method3() = { this.synchronized { .... .... } } } what happens if have final field defined in actor as: private val locktype = new anyref i can use lock synchronize method3? difference? understanding using reference lock on method make reference unavailable until lock released. in above case, use lock can function independently of reference , lock when action on method3 made, while reference still available other threads? there's no need synchronization inside of actor. actor ever process single message @ time.

php - Laravel get model by hasManyThrough -

i have 3 classes - user, business , businessroleuser (and respective tables) (user) id | first_name | last_name (business) business_id | business_name (business_role_user) user_id | business_id | role_id i have combined role of user in same table multiple roles user's can have towards business i.e. admin, staff, etc. in business_roles table. i access business model through logged in user update fields i.e. $business = user::find(auth::id())->business(); $business->fill(input::all()); $business->save(); at present in user class have following (really each user associated 1 business): public function business() { return $this->hasmanythrough('app\business', 'app\businessroleuser', 'business_id', 'user_id'); } but if simple dd(user::find(auth::id())->business->business_name); it throws error business name undefined it's not finding business model associated user. i'v

python - logging.handler.TimedRotatingFileHandler never rotates the log -

a have script synchronizes time on linux servers( centos 6) , writes offset in log. want make after 10 days current log (ntp.log) copy old (ntp.log-date), not work. script continues write 1 file , not rotating. run cron every 5 minutes. using python version 2.6. set interval in seconds check. doing wrong? #!/usr/bin/env python import ntplib import logging logging.handlers import timedrotatingfilehandler time import ctime import os import socket hostname = socket.gethostname() loghandler = timedrotatingfilehandler('/root/ntp/log/ntp.log', when='s', interval=300) logformatter = logging.formatter('%(asctime)s %(message)s', datefmt='%d/%m/%y %h:%m:%s') loghandler.setformatter(logformatter) logger = logging.getlogger('mylogger') logger.addhandler(loghandler) logger.setlevel(logging.info) c = ntplib.ntpclient() response = c.request('1.rhel.pool.ntp.org') logger.info('| %s time offset | %s' % (hostname, response.offset)) datestr

tfs - What are Epics in regard of Features and Backlog Items in Team Foundation -

from this link assert feature set of backlog items, epic supposed ? the general consensus that: product backlog item can delivered in single sprint. feature can't delivered in single sprint, can delivered in single release. epic transcends releases. theme cross cutting concern. theme implemented tag in tfs , vsts. this practice in line scrum framework, nexus framework, , safe methodology.

Python requests proxy connection timeout -

i using code check proxy servers: def check_proxy(p): try: r = requests.get('https://httpbin.org/get', proxies={'https': 'https://%s' % p}, timeout=5) if r.status_code == 200: return true else: return false except: return false it works fine working proxy. fails bad proxy after several minutes: traceback (most recent call last): file "/home/me/desktop/general/test_proxyt.py", line 22, in check_proxy r = requests.get('https://httpbin.org/get', proxies={'https': 'https://%s' % p}, timeout=5) file "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 59, in return request('get', url, **kwargs) file "/usr/local/lib/python2.7/dist-packages/requests/api.py", line 48, in request return session.request(method=method, url=url, **kwargs) file "/usr/local/lib/python2.7/dist-packages/requests/sessions.py&qu

c++ - Linking against third-party libraries when doing cross-platform build in Visual Studio 2015 -

i trying compile shared object (.so) visual studio 2015 rc. i linking against opus codec libs in stdafx.h: #pragma comment(lib, "..\\..\\opus-1.1-beta\\win32\\vs2010\\win32\\debug\\celt.lib") #pragma comment(lib, "..\\..\\opus-1.1-beta\\win32\\vs2010\\win32\\debug\\opus.lib") #pragma comment(lib, "..\\..\\opus-1.1-beta\\win32\\vs2010\\win32\\debug\\silk_common.lib") #pragma comment(lib, "..\\..\\opus-1.1-beta\\win32\\vs2010\\win32\\debug\\silk_fixed.lib") #pragma comment(lib, "..\\..\\opus-1.1-beta\\win32\\vs2010\\win32\\debug\\silk_float.lib") i getting linker error: linker command failed exit code 1 (use -v see invocation) sharedobject1 c:\users\myuser\documents\visual studio 2015\projects\sharedobject1\sharedobject1\clang.exe 1 can tell me how investigate might have gone wrong there? state "-v"? and not ok use .libs in cross-platform project? wondering why talks .a files, .so, never .libs. e

android - Handling server errors with Retrofit -

it great if share knowledge me! here problem - have android app. , server. of calls client needs send obtained token server legit limited amount of time. if happens token not valid more, error returned sever, new token needs obtained , need retry request. but how can handle such behavior retrofit? thoughts? thank in advance! how try , make request callback, if callback failure , error message token needs obtained, request new token example: connectioninterface.getsomestuff(object, new callback<objectpojo>() { @override public void success(objectpojo objectpojo, response response) { //success } @override public void failure(retrofiterror error) { if (error.getlocalizedmessage().equals("token expire error") connectioninterface.gettoken(); } then in retrofit gettoken callback, if success redo getsomestuff method , if fail

fft - can't catch a tone frequency of 15k with microphone c# naudio -

i record sound naudio float array , after getting recorded audio want convert float array wav check it. i wrote method i'm not sure because: try record 15khz tone of 5 seconds , pass through fft check spectrum ensure 15k catched. these steps: i generate tone matlab firstly , record audacity right tone. audacity shows nice spectrum peak in 15k -30db. i try record naudio tone , converting recorded float array wav check in audacity. unfortunately, show nothing noise 12k , no more(-80db @ 12k). here regular recording convertion when data available: void mywavein_dataavailable(object sender, waveineventargs e) { mymemorystream.write(e.buffer, 0, e.bytesrecorded);//this playing mymemorystream (int index = 0; index < e.bytesrecorded; index += 2)//here convert in loop stream floating number samples { short sample = (short)((e.buffer[index + 1] << 8) | e.buffer[index + 0]); sam

Order of opening files when using tarfile.open() in Python -

i have simple question yet didn't manage find lot of information or understand well. when open tarfile in python using tarfile.open() method, how files in tarfile read? have tarfile data on people, each person has own folder , in folder data divided between different folders. will files accessed depending on internal structure or there way determine file accessed next when use tarfile.extractfile() ? thank in advance internal structure. tar stands "tape archive", , big design point ability work sequentially small ram, while writing (or reading from) sequential-access io device (also known tape): loading memory , processing in specific order not possible. thus, files extracted in order found in archive, reading archive in order.

Is arduino suitable for high frequency application? -

can use arduino application frequency of 4 mhz? i need create clk frequency , send , receive data on rising , falling edges. , not normal spi interface have own conditions need manually. if not suitable, technically possible? the maximum pwm generate arduino mega 2560 62500 hz. don't think can go beyond that. method you can use internal spi 16mhz oscillator have upto 16mhz (16/128)mhz. method

xcode - How to check a timeout occurred in ios url connection? -

i have used urlrequest fetch html file pc in wifi network. app fetches html file fileserver , filename number typed in app. have given 20 seconds timeout request. how can detect whether timeout occurred because have 2 situations, 1. file not exist 2. connection slow in urlrequest, there bool error,no description. suggest me method if possible. code below urlrequest -(void)gethtmlcontent{ [self.spinner startanimating]; nsstring *str = @"http://192.168.1.250/rec/"; // nsstring *str = @"file:///volumes/xampp/htdocs/"; str = [str stringbyappendingstring:numentered.text]; str = [str stringbyappendingstring:@".html"]; nsurl *url=[nsurl urlwithstring:str]; //self.htmlcontent = nil; nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:url]; //nsurlrequest *request = [nsurlrequest requestwithurl:url]; request.timeoutinterval = 20.0; nsurlsessionconfiguration *configuration = [nsurlsessionconfiguration ephemera

Do a https client check with java or android -

i got url https, has common certification (which means url visited browser , has https security badge). want info url using httpsurlconnection, how can certification check. i ssl beginner, did searching. , got this , self-signed check demo. i'm wondering if common https link should checked this. httpsurlconnection check, found on android developers: if application wants trust certificate authority (ca) certificates not part of system, should specify own x509trustmanager via sslsocketfactory set on httpsurlconnection. does means don't need check server certificate if can browse web browser? can validation web browser does? , can find trust store file, can make default key store? or can tell me how implement trustmanager(i want validation, not trust manager trust anything). maybe information httpcomponents

java - Detecting Jar file Tampering -

our scenario is, have exe in bundling jars , supplying client. signing exe along jars , meta-inf dir holds checksum values entries present inside jar. now issue, when jar file tampered like, adding or modifying class or changing content, goes undetected , still application launches. when alongside corresponding entries ar modified manually in meta-inf/manifest.mf, verify signature gets failed , certificate exception getting thrown. there way, when entries in jar files modified (by unzip jar manually), corresponding entry in manifest file altered automatically. you changes on jar file undetected. in fact root of problem. don't know how signed jar, java should deny loading jar if signature got appended jarsigner doesn't match contents.

How to configure ElastiCache Redis for Spring Data Access -

i trying setup elasticache use java application. have based setup based on documentation: https://docs.aws.amazon.com/amazonelasticache/latest/userguide/bestpractices.html the ec2 instance java (8) app runs in vpc. have tried elasticache instance both in vpc , no vpc. however, got, redis.clients.jedis.exceptions.jedisconnectionexception: java.net.connectexception: connection refused if install redis myself on ec2 instance , connect it, app able connect redis cache! i have setup proper authorization security-group ec2 cache-security no luck. can't make 'connection'. sample connection snippet helpful. redis setup way in app config: @bean public jedisconnectionfactory redisconnectionfactory() { jedisconnectionfactory redisconnectionfactory = new jedisconnectionfactory(); redisconnectionfactory.sethostname(<cache-node>); redisconnectionfactory.setport(6397); redisconnectionfactory.setusepool(true); redisconnectionfactory.settim

sql server - Select data from three table in sql -

i have 3 table like student : sid, sname, semail fees_type : fid, fname, fprice studentfees : sid( fk student ),fid( fk fees_type ), fdate data of each table : student : sid |sname | semail 1 | abc | abc@www.com 2 | xyz | xyz@www.com fees_type: fid | fname | fprice 1 | chess | 100 2 | cricket | 200 studentfees: sid | fid| fdate 1 | 1 | 5/2 1 | 2 | 6/2 2 | 1 | 7/2 2 | 2 | 8/2 1 | 1 | 6/2 now want data sid|sname|semail | total_chess_played|total_cricket_played | total_fees 1 | abc |abc@www.com | 2 | 1 | 400 2 | xyz |xyz@www.com | 1 | 1 | 300 i have tried these following query can not group or perfect result select s.sid, semail, sname, fname ,fprice student s inner join studentfees sf on s.sid = sf.eid inner join fees_type f on f.fid = sf.fid month(pr.tddate) = month(dateadd(dd,

mysql - Insert NULL value in db using Raw sql queries in rails -

i using raw sql queries in rails application. want insert null value in 1 rows, how active record using nil row when table.find_by_column(nil) . tried '#{nil}' entering nothing db column blank ' ' want null. you can try this. sql = "insert table_name (r_id, r_name) values (1, null)" records_array = activerecord::base.connection.execute(sql)

mime types - laravel validation doesnt work for .JPG -

in laravel5 validate picture following code: public function rules() { return [ 'name' => 'required', 'pic' => 'required|mimes:jpeg,png', ]; } it works files extensions filename.jpg , filename.jpeg doesn't filename.jpg . however, doesn't return wrong file extension missing file. can help? try 'pic' => 'required|image' , make sure form has enctype="multipart/form-data" attribute.

virtualization - Why do we have memory zones in linux? -

i reading on page that: because of hardware limitations, kernel cannot treat pages identical. pages, because of physical address in memory, cannot used tasks. because of limitation, kernel divides pages different zones. i wondering hardware limitation. can please explain me hardware limitation , give example. well, there software guide intel explaining this? also, read virtual memory divided 2 parts 1gb kernel space , 3gb user space. why give 1gb space in virtual space of processes kernel? how mapped actual physical pages? can please point me clean text explaining this? thanks in advance. the hardware limitations concern old devies. example, have zone_dma , 0 - 16mb . e.g. needed older isa devices, not capable of adressing above 16mb limit. have zone_normal , of kernel operations take place , adressed permanently kernels adress space. the 1gb , 3gb split simple. have virtual adresses here, application, memory adress starts @ 0x00000000 , reserved 1st gb

php - Sql date between query with a date and number of days -

i have table called renewals follows id | item_name | next_renewal_date | alert_before_days 2 | test | 2015-05-25 | 5 6 | test4 | 2015-05-12 | 2 7 | test7 | 2015-05-30 | 12 i read table alert_before_days. example, need rows upcoming renewals alert_before_days current date onwards. i'm using cakephp , tried following, nothing works. selects date 1970-01-01 'conditions'=>array('renewal.nextrenewaldate <=' => date('y-m-d', strtotime("+renewal.alertbeforedays days")) strtotime not recognize expression. mysql - 'conditions'=>array( 'renewal.nextrenewaldate <=' => 'date_add(now() + interval `renewal`.`nextrenewaldate` day)' )

typo3 - Sub page content rendering using vhs? -

Image
requirement simple , want render content of sub page in main page. is possible using vhs extension ? i want render sub-page content in [9]zweckverband parent page. requirement dynamic , sub-pages can increase , need render sub page content in parent [9] page. we can render menu using vhs , , can render page content using vhs. need combine both coding achieve requirement. thanks in advance ! you can render menu of subpages, instead rendering menu item each of them, render content (and maybe headline or something). rendering content of arbitrary page can done with <v:content.render pageuid="{currentpage}" column="0"/> other content retrieval viewhelpers should have pageuid parameter, use them well. one thing come caching: if subpage changed, rendering result of main page changes. typo3 won't recognize that, because content on main page didn't change. might want clearcachecmd , solve that.

ssis - Load data for yesterday's date and specific date -

i have ssis package, runs on date parameter. if dont specify date load data yesterday's date. , if give specific date '2015-05-10', should load date. how can achieve dynamically (using package configuration)? once load specific date, package should set yesterday's date dynamivally. please guide me achieve new ssis. thanks in advance add parameter package paramdate . parameter has manually provided value(e.g. 03-21-2015). leave blank(null value) if yesterday's date has considered. now define variable inside package vardate have expression vardate - isnull(@[$project::paramdate])?dateadd("day", -1, getdate()):@[$project::paramdate] i assuming loading data in dft. so in source query that, need add condition in where clause select ...... sometable loaddate = ? in "parameters..." section of source, assign variable vardate 0 . further details on how map parameters see here . hope helps. edit tagged under ssis 2012,m

php - Not able to set proper data position in FPDF -

scenario: i fetching data database , it's printing data in fpdf in loop. problem: i facing problem printing data in loop in left side of page. has set data when tried put data on left side of page, automatically skips line on right side of page. question: i not know why happened; maybe there problem setting position of x , y . the following code: <?php include ('config.php'); require ('fpdf/fpdf.php'); $pdf=new fpdf(); $pdf->addpage(); $pdf->setfont('times','',8); $sql = "select address,user_id contact left join address on address.contact_id = contact.contact_id"; $result = mysql_query($sql); while($rows=mysql_fetch_array($result)) { $pdf->cell(20,3,'name : '); $user_id = $rows['user_id']; $string = str_replace(' ', '', $user_id); $pdf->multicell(64,3, $string,0); $pdf -> setx(110); $pdf->cell(20,3,'name : '); $user_id = $ro

Publishing Outlook/Excel add to the office store -

i have developed outlook add-in , excel add-in , created there respective installers. now want publish these installers microsoft office store( https://store.office.com/ ). can provide me steps that? the office store apps (html/css + js). can publish add-in in windows store instead. note, need handle purchase process on web site. installers available on site well. windows store provides link web site purchasing , installing add-in.

Working with an array within an array - Swift -

i have array of books. books have title , characters. characters have name , age. both book , character structs. when app launches set of default books created (the user add own later. here basic code: (note: ???? placeholder code can't solve.) struct character { var name: string var age: int } struct book { var title: string var characters: [character] } var books: [book] = [] func createbooks() { books.append(book(title: "my book1", characters: ????) } i know create array of characters , assign books.append(book(title: "my book1", characters: [character[0], character[3]]) but i'm concerned handling 2 separate arrays become difficult in big list of books, not mention user created books. how best handle this? your question bit unclear here how this. struct character { var name: string var age: int } struct book { var title: string var characters: [character] } var books: [book] = [] fu

hadoop - Add Spark to Oozie shared lib -

by default, oozie shared lib directory provides libraries hive, pig, , map-reduce. if want run spark job on oozie, might better add spark lib jars oozie's shared lib instead of copy them app's lib directory. how can add spark lib jars (including spark-core , dependencies) oozie's shared lib? comment / answer appreciated. spark action scheduled released oozie 4.2.0, though doc seems bit behind. see related jira here : oozie jira - add spark action executor cloudera's release cdh 5.4 has though, see official doc here: cdh 5.4 oozie doc - oozie spark action extension with older version of oozie, jars shared various approaches. first approach may work best. complete listings anyway : below various ways include jar workflow: set oozie.libpath=/path/to/jars,another/path/to/jars in job.properties. this useful if have many workflows need same jar; can put in 1 place in hdfs , use many workflows. jars available actions in workflow. th

Specflow > Is there a way to execute some logic before the Scenario but AFTER the Background? -

i have scenario several steps , there's background outline inserts initial data database. right before scenario block executes want able start transaction. thing is, want transaction start after background has executed, if scenario fails , roll back, initial data inserted in background still there, because want asserts against data. i have tried decorating method (in begin transaction) [beforescenario] , [beforescenarioblock], fired @ beginning, before background. doesn't work. any ideas? i have feeling not possible @ moment. should able add [afterstep] binding called after steps in background , after last step in background work around though. i can't remember exactly, might have trouble working out step executing though in current version, there stuff in v2 version (which has beta available nuget feed here ) gives access scenariostepcontext might that. this seems reasonable feature though , don't think pull request hooks [beforebackground] ,

Google Custom Search JSON API -

i'm playing google custom search api custom search engine (cse) via json api. obtained search result, i'm clueless how obtain nextpagetoken . https://www.googleapis.com/customsearch/v1?key=my_api_key&cx=my_search_engine_id&q=testing the json response follow: { "kind": "customsearch#search", "url": { "type": "application/json", "template": "https://www.googleapis.com/customsearch/v1?q={searchterms}&num={count?}&start={startindex?}&lr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googlehost?}&c2coff={disablecntwtranslation?}&hq={hq?}&hl={hl?}&sitesearch={sitesearch?}&sitesearchfilter={sitesearchfilter?}&exactterms={exactterms?}&excludeterms={excludeterms?}&linksite={linksite?}&orterms={orterms?}&relatedsite={relatedsite?}&daterestrict={datere

MongoDB: find one document based on the order of $or values? -

findone() : if multiple documents satisfy query, method returns first document according natural order reflects order of documents on disk. i need similar effect above, except if multiple documents satisfy query, returns 1 comes earliest in $or array. db.collection.findone({ $or: [ {"apple": "blah"}, {"orange": "blah"}, {"grape": "blah"} ] }) for example, if these documents satisfy above query [ {"apple": "....", "orange": "....", "grape": "blah"}, {"apple": "....", "orange": "blah", "grape": "...."} ] it returns document matched orange (the second 1 above), because orange comes before grape in $or array. similarly, if document matched apple document returned because apple comes earlier in array. how can done? it sounds want assi

vb.net - Get current clock speed with ManagementObjectSearcher -

i'd current clock speed. search results suggest wmi. problem is, doesn't work. example, overclocked cpu test (increased 200 mhz). cpu-z reported correctly, 4.2 ghz. wmi incorrectly reported @ 4.0 ghz (the stock max clock speed). i've noticed system properties doesn't report clock speed right. assume pulling data using wmi. understand cpus don't run @ highest clock speed. in circumstance, running @ highest clock speed (according cpu-z). the reason want figure out compare current clock speed, , max clock speed (to determine if cpu overclocked in application). here's example of code. imports system.management public class form1 private sub button1_click(sender system.object, e system.eventargs) handles button1.click dim cpuspeed string = string.empty dim wmiobj managementobjectsearcher = new managementobjectsearcher("root\cimv2", "select * win32_processor") each element managementobject in wmiobj.get() cpuspeed =

how to use ruby code after its written, is it standalone or need to be in a web application? -

confused little on ruby. know makes .rb files, make exe or com files or used as web application? i know bit writing code, files after. the question bit broad. you have step , @ how source code in general ends being executed (i.e. used). in case of programming languages (e.g. c/c++) it's compiled native form , can executed directly afterwards; in case of other languages it's compiled intermediate form (e.g. java/c#) , executed vm (jvm/clr) in case of yet other languages interpreted @ runtime (e.g. ruby/python). so in specific case of ruby, have interpreter loads rb files , runs them. can in context of standalone apps or in th e context of web server, have interpreter making sense of ruby files. don't executable same way languages compiled machine code.

compilation - How to compile JAVA on Sublime text 2 using Mac OS X? -

Image
i've looked on internet finding complicated results , im not sure do. sublime text 2 has builtin java support: which means once have opened java source, have press command+b what described in comments bit different - should update post information! devin posted gist solution here : you should add new build-system going menu: tools --> build system --> new build system and add following json , save "java.sublime-build" default directory (which like: ~/library/application support/sublime text 2/packages/user/ ): { "cmd": ["javac", "$file_name"], "cmd": ["java", "$file_base_name"], "working_dir": "${project_path:${folder}}", "selector": "source.java" } next time want compile & run use "java.sublime-build" build-systems.

java - Adding a timer to KeyListener -

i extended jframe class , have own model , jpanel extended classes instance variables. implemented keylistener jframe , works arrow keys model moves extremely slow around frame when hold keys down. question how attach keylistener methods timer or make model move faster when hold keys. if possible, how can model move 2 directions @ once, left , up? public class gamecontroller extends jframe implements keylistener,actionlistener { private gamepieces p; private gamepanel panel; private timer timer; public gamecontroller() { super("balls"); setsize(800, 600); timer = new timer(10, this); setdefaultcloseoperation(jframe.exit_on_close); container c = getcontentpane(); c.setlayout(new borderlayout()); p = new gamepieces(); panel = new gamepanel(); p.addobserver(panel); c.add(panel); addkeylistener(this); panel.update(p, null); setresizable(false);

matlab - Using a clear portion of the picture to recreate a PSF -

Image
i'm trying unblur blurred segments of following picture. the original psf not given, proceeded analyse blurred part , see whether there word make out. found out make out "of" in blurred section. cropped out both the blurred "of" , counterpart in clear section -> seen below. i thought through lectures in fft divide blurred(frequency domain) particular blurring function(frequency domain) recreate original image. i thought if unblurred(frequency domain)\blurred(frequency domain), original psf retrieved. please advise on how this. this code. img = im2double(imread('c:\users\adhil\desktop\matlab pics\image1.jpg')); blurred = imcrop(img,[205 541 13 12]); unblurred = imcrop(img,[39 140 13 12]); ub = fftshift(unblurred); ub = fft2(ub); ub = ifftshift(ub); f_1a = zeros(size(b)); idx = 1 : size(blurred, 3) b = fftshift(blurred(:,:,idx)); b = fft2(b); b = ifftshift(b); uba = ub(:,:,idx); tmp = uba .

for loop - Android: Setting ID's for Array of Image Buttons -

i making android application allows users click either plus or minus image button change number displayed in text view. there 18 of text views , plus , minus image button each text view. the activity crashes when activity, because of section of code. have been unable produce helpful information when debugging code appreciated, thanks! at top of activity: int score = 0; imagebutton addbuttons[] = {(imagebutton)findviewbyid(r.id.hole1up), (imagebutton)findviewbyid(r.id.hole2up), (imagebutton)findviewbyid(r.id.hole3up), (imagebutton)findviewbyid(r.id.hole4up), (imagebutton)findviewbyid(r.id.hole5up), (imagebutton)findviewbyid(r.id.hole6up), (imagebutton)findviewbyid(r.id.hole7up), (imagebutton)findviewbyid(r.id.hole8up), (imagebutton)findviewbyid(r.id.hole9up), (imagebutton)findviewbyid(r.id.hole10up), (imagebutton)findviewbyid(r.id.hole11up), (imagebutton)findviewbyid(r.id.hole12up), (imagebutton)findviewbyid(r.id.hole13up), (imagebutton)findviewbyid(r.id.hole14up), (imagebut

python - How to generate random points in a circular distribution -

i wondering how generate random numbers appear in circular distribution. i able generate random points in rectangular distribution such points generated within square of (0 <= x < 1000, 0 <= y < 1000): how go upon generate points within circle such that: (x−500)^2 + (y−500)^2 < 250000 ? first answer: easy solution check see if result satisfies equation before proceeding. generate x, y (there ways randomize select range) check if ((x−500)^2 + (y−500)^2 < 250000) true if not, regenerate. the downside inefficiency. second answer: or, similar riemann sums approximating integrals. approximate circle dividing many rectangles. (the more rectangles, more accurate), , use rectangle algorithm each rectangle within circle.

Collisions reporting multiple times in Corona -

i building game in corona sdk involves 2 types of collisions 2 different types of objects. there 3 objects total in game, rocket ship, asteroid, , yellow sphere. when asteroid hits rocket ship, lose 1 life. when yellow sphere hits rocket ship, gain point. reason both asteroid , yellow sphere have multiple collisions rocket ship when colliding once. have re-evaluated code multiple times , cannot figure out problem is. please , if need sample code can post some. collisions have multiple phases. have test phases. collisions begin , end. there should event.phase tells phase in. there pre-collision events too.

Java Eclipse launch problems -

!session 2014-07-11 21:28:10.330 ---------------------------------------------- eclipse.buildid=unknown java.version=1.7.0_60 java.vendor=oracle corporation bootloader constants: os=win32, arch=x86, ws=win32, nl=en_us command-line arguments: -os win32 -ws win32 -arch x86 !entry org.eclipse.equinox.p2.touchpoint.eclipse 4 0 2014-07-11 21:28:16.695 !message unable load parent configuration from: c:\program files (x86)\java\jdk1.7.0_60\bin\configuration\org.eclipse.update\platform.xml -startup plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar --launcher.library plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.200.v20150204-1316 -product org.eclipse.epp.package.java.product --launcher.defaultaction openfile --launcher.xxmaxpermsize 256m -showsplash org.eclipse.platform --launcher.xxmaxpermsize 256m --launcher.defaultaction openfile -vm --c:\program files (x86)\java\jdk1.7.0_60\bin\javaw.exe launcher.appendvmargs -vmargs -dosgi.re

forms - I want to use regular expression in php -

i want know how give user error on form validation if < or > used in form fields. here script: $pattern = "<,>"; if (preg_match($pattern, $_post["u"])) { exit("this illegal, error!!!"); } use [<>] if (preg_match('/[<>]/', $_post["u"])) { // illegal char } however there no need use regular expressions. can use strpos: if (strpos($_post["u"], '<') !== false || strpos($_post["u"], '>') !== false) { // illegal char }

queue - NSArray is null when i create it in the completion whereas the first nsarray is not null -

this code trying create nsmutable array strings , store them in object property. nsarray *photos works not nsmutablearray thumbimageurl. when nslog debugging purposes null. please help, annoys me lot, cant find solution. lazy instantiated there no reason not have allocation in memory. lazy instantiation: -(void)setthumbimageurl:(nsmutablearray *)thumbimageurl { if (!_thumbimageurl) _thumbimageurl=[[nsmutablearray alloc] initwithcapacity:50]; _thumbimageurl=thumbimageurl; } my code: [pxrequest requestforphotofeature:pxapihelperphotofeaturepopular resultsperpage:50 page:1 photosizes:(pxphotomodelsizelarge | pxphotomodelsizethumbnail | pxphotomodelsizesmallthumbnail |pxphotomodelsizeextralarge) sortorder:pxapihelpersortordercreatedat completion:^(nsdictionary *results, nserror *error) { [[uiapplication sharedapplication] setnetworkactivityindicatorvisible:no]; if (results) { self.photos =[results valueforkey:@"photos"];

Wordpress - How to import html code into a page? -

what have html form place @ end of of pages. not planning have on every page, most. edit: realized after posting didn't make clear enough don't mean in footer, add on page itself. of course copy in full html , css code @ bottom of pages want on. know there better , cleaner way have html form , css in 1 file , either through making plugin, use of short code, html code or other option i'm not aware of, import html code page. so approach accomplish this? thanks help. a simple way create custom page template includes form , select template when need it. this approach not work if you're utilizing more 1 page template. see @hakem's answer if case.

java - Referencing a enum object in another class -

i'm trying use enum object in class cant figure out have done wrong. here lines of code in first class trying reference second class. model model = new model(); model.outcome outcome = new getgameoutcome(uchoice,cchoice); and here actual object trying reference in "model" class. public enum outcome{ win,loss,tie } public outcome getgameoutcome(string uchoice, string cchoice){ and continues rest. you aren't creating new instance, assigning return value of method. hence, not need new operator: model.outcome outcome = getgameoutcome(uchoice,cchoice);

caching - Cache and scratchpad memories -

could explain difference between cache memory , scratchpad memory? i'm learning computer architecture. a scratchpad place keep stuff. cache, memory talk through not talk at. scratchpad post note, write on , keep you. cache paper send off else instructions memo. cache can in various places, layers (l1, l2, l3...). both scratchpad , cache sram in chip, address , data bus , read/write/etc control signals. (as many other things in computer may or may not used addressable ram). during boot, before ram on far side (slower ram side, processor being near side) initialized (eventually dram typically if have cache otherwise why have cache) may possible access cache addressable ram. depends on system/design though, there may control register enables behave simple ram, or there may mode, or normal mode may such long dont address more size of ram based on alignment (perhaps 32k ram between 32k boundaries) may not try evict , generate bus cycles on dram/slow/far side of ca

php - How does a WebHook work? -

i'm implementing payments platform website wich similar stripe, still can't understand process or how should use webhooks since need specify 1 on account in payments platform. so let's person pays in website product costs $5, take them payment form introduce credit card details. when click "pay now" gets verified via javascript/jquery , sent server , i'm able charge user , see reflected on sandbox account on payment platform. or when should webhooks used or called, or why need them? thanks in advance webhooks way communicate application. many apis, send them request , api response included in response request. if request make asynchronous, or if reason api you're using wants able communicate application calling directly opposed waiting make request. with webhooks, you'd open endpoint on application other api / service can send requests can process requests. can think of push notifications web applications. with payments standard u