Posts

Showing posts from January, 2012

for loop - Connect four game board in C -

i writing program allows user play game connect 4 against computer. having trouble printing out correct dimensions board. tried using nested loops, output little off. here part of code: #include <stdio.h> #define board_size_vert 6 #define board_size_horiz 7 void display_board(int board[] [board_size_vert]); int main () { int board[board_size_horiz][board_size_vert] = {{0}}; display_board(board); return 0; } void display_board(int board[] [board_size_vert]) { int i,j; (i=0; i<board_size_horiz; i++) { printf ("+---+---+---+---+---+---+---+"); printf ("\n"); (j=0; j<board_size_vert; j++) printf ("| "); printf("\n"); } } this output: +---+---+---+---+---+---+---+ | | | | | | +---+---+---+---+---+---+---+ | | | | | | +---+---+---+---+---+---+---+ | | | | | | +---+---+---+---+---+---+---+ | | | | | | +---+---+---+---+---+---+---+ |

javascript - Issue on Passing Dom val() and html() to Polygon Options in Drawing -

Image
i trying pass values dom .val() , .html() this: $("#drawpolygon").on("click",function(){ var polyname = $("#polydatasetname").val(); var polycolor = $("#polyfillcolor").val(); var polytranc = ($("#polytrancparency").html()).slice(2); var polybordercolor = $("#polybordercolor").val(); var polybordersize = $("#polybordersize").html(); var polybordertranc = ($("#polybordertransparency").html()).slice(2); }); i tried alert result correct when pass them polygonoptions options like: polygonoptions: { fillcolor: polycolor, fillopacity: (polyfillcolor/100), strokecolor: polybordercolor, strokeweight:polybordersize, clickable: false, editable: true, zindex: 1 } i getting following error message can please let me know why happening , how can solve it? here code have drawing manager: <script>

utf 8 - Java code reads UTF-8 text incorrectly -

i'm having problem reading utf-8 characters in code (running on eclipse). i have file text has few lines in it, example: אך 1234 note : there \t before word, , word should appear on left, number on right... don't know how reverse them here, sorry. that is, hebrew word , number. i need separate word number somehow. tried this: bufferedreader br = new bufferedreader(new filereader(text)); string content; while ((content = br.readline()) != null) { string delims = "[ ]+"; string[] tokens = content.split(delims); } the problem reason, code reads content (the first line in file) follows: אך\t1234 ...meaning space isn't in correct place. i suppose tokenize text using \t , i'm not sure should it, file isn't being read correctly... does have idea why happens? thanks :-) i think matching space when there tab there? can try this: bufferedreader br = new bu

java - The method is undefined for the type Class<capture#3-of ? extends Command> -

i have abstract class package main; public abstract class command { protected final string key; public command(string key) { this.key = key; } public abstract void function(string[] args); public abstract void help(); } but when try call method function(string[] args) , albeit in confusing , overly complicated way, problems ensue. class<? extends command> x = (class<? extends command>) class.forname( "main.commands$" + string.valueof(command.tochararray()[0]).touppercase() + command.substring(1).tolowercase() ); x.function(args); gives me error the method function(string[]) undefined type class<capture#3-of ? extends command> i alternatively tried following: command x = (command) class.forname( "main.commands$" + string.valueof(command.tochararray([0]).touppercase() + command.substring(1).tolowercase() ); but gave me cannot cast class<capture#1-of

linux - Change Mysql Data Directory in Debian 7? -

i have separate partition holds both www , mysql folders. i have partition set automount @ boot, , apache2 starts fine, no errors. however, when removed traces of mysql-server-5.5, rebooted restarted it, work normally. but second make changes my.cnf point /media/server/mysql, , try start mysql error's out. here list of steps have followed far. advised, debian not have apparmor, far know, skipped step. stop mysql using following command: sudo /etc/init.d/mysql stop copy existing data directory (default located in /var/lib/mysql) using following command: sudo cp -r -p /var/lib/mysql /newpath edit mysql configuration file following command: gedit /etc/mysql/my.cnf entry datadir, , change path (which should /var/lib/mysql) new data directory. in terminal, enter command: sudo gedit /etc/apparmor.d/usr.sbin.mysqld lines beginning /var/lib/mysql. change /var/lib/mysql in lines new path. save , close file. restart apparmor profiles command: sudo /etc/init.d/apparmo

php - Cast as int or leave as string? -

i'm wondering if there reason cast variable, returned mysql string, int. i'm updating code , netbeans wants me use === instead of ==. problem === cares content type. i had: if($user['user_state']==1){...} so change this: if($user['user_state']==="1"){...} or can this: if((int)$user['user_state']===1){...} it doesn't make difference me if i've got int or str. won't doing math particular variable. , since i'll have rewrite conditionals in case, i'd rather right way. so, think question best practice? or 1 of wonderful questions answers end happy marriages single vs double quotes? the underlying reason netbeans suggest such thing this: "1abc" == 1 // true strengthening comparison applying (int) cast , using === satisfy editor , purists, since typically trust database schema, above cast won't necessary , can use loose comparison instead. to sum up, although strict comparisons practice

java - How to delete a file stored in my device using OnItemLongClickListener? -

i have listview display files inside folder. method delete file using onitemlongclicklistener? thank you. inside onitemlongclicklistener() method call method. here path.get(position) arraylist used. should change giving file location according requirement. public void dodeletefile(listview l, view v, int position, long id){ file filetodelete = new file(path.get(position)); if(!filetodelete.isdirectory()){ try{ if(filetodelete.delete()){ system.out.println("file deleted successfull !"); }else{ system.out.println("file delete operation failed"); } }catch(exception ex){ system.out.println("exception :"+ex.getmessage()); } }else{ system.out.println("it not file"); }

objective c - How to implement Game Center Leaderboards in iOS 7? -

i creating game ios 7 , trying implement game center leaderboards. got app open leaderboard when click button, says "no items". not sure right if problem submitting scores or retrieving leaderboards. appears problem submitting score because says app name on top of leaderboard, can't find error. code submit score: -(void)reportscore:(nsinteger ) highscore { if ([gklocalplayer localplayer].isauthenticated) { gkscore *scorereporter = [[gkscore alloc] initwithleaderboardidentifier:@"flapjacks1" forplayer:[gklocalplayer localplayer].playerid]; scorereporter.value = highscore; nslog(@"score reporter value: %@", scorereporter); [gkscore reportscores:@[scorereporter] withcompletionhandler:^(nserror *error) { if (error != nil) { nslog(@"error"); // handle reporting error } }]; } } this method retrieving leaderboard: -(void)displayleaderboard { //nsstring *_leaderboar

cordova - phonegap addEventListener trigger slowly for 2nd time execution -

<script> function onbattery() { window.addeventlistener("batterystatus", onbatterystatus, false); document.getelementbyid('log1').innerhtml+="clicked"; } function onbatterystatus(info) { document.getelementbyid('log2').innerhtml+="get"; document.getelementbyid('getbatstatus').innerhtml+="level: " + info.level + " isplugged: " + info.isplugged; } </script> <p id="log1">will display log1</p> <p id="log2">will display log2</p> <p id="getbatstatus">will display battery status</p> above code display current battery status. on 1st click showing fast. when want run again..it execute slowly... why happen? the reason why batterystatus event occurs when battery status changes (power level increases, decreases or plug device in) the first time call onbattery, gives current status waits system raise batterystatus ev

c# - Programmatically change ListBox DataTemplate -

hey guys wandering if can show me how programmatically change listboxdatatemplate. have datatemplate: <datatemplate x:key="datatemplate1"> <grid toolkit:tilteffect.istiltenabled="true" d:designwidth="446" width="446" d:designheight="108" height="108"> <textblock textwrapping="nowrap" text="{binding accounttitle}" verticalalignment="top" width="456" horizontalalignment="left" height="40" fontfamily="segoe wp" fontsize="28" /> <textblock textwrapping="nowrap" text="{binding accountusername}" verticalalignment="top" width="456" margin="0,33,0,0" horizontalalignment="left" height="35" fontfamily="segoe wp" fontsize="24" /> <textblock textwrapping="nowrap" text="{binding acc

python - How to set zoomFactor in selenium + phantomjs? -

phantomjs version : 1.9.7 selenium version : 2.40.0 setting zoomfactor works when directly call phamtomjs page.zoomfactor set in .js file: works well var page = require('webpage').create(); page.open('http://google.com', function () { page.zoomfactor = 0.25; page.render('test.png') phantom.exit(); }); however doesn't work when set in desired_capabilities in selenium: does not work desiredcapabilities.phantomjs['phantomjs.page.zoomfactor'] = 0.25 driver = selenium.webdriver.phantomjs() driver.get('http://google.com') driver.save_screenshot('test.png') driver.quit() i tried this, doesn't work either: driver = selenium.webdriver.phantomjs( desired_capabilities={'phantomjs.page.zoomfactor': 0.25} ) what doing wrong?

c - Modifying the array element in called function -

i trying understanding passing of string called function , modifying elements of array inside called function. void foo(char p[]){ p[0] = 'a'; printf("%s",p); } void main(){ char p[] = "jkahsdkjs"; p[0] = 'a'; printf("%s",p); foo("fgfgf"); } above code returns exception. know string in c immutable, know there difference between modifying in main , modifying calling function. happens in case of other date types? i know string in c immutable that's not true. correct version is: modifying string literals in c undefined behaviors. in main() , defined string as: char p[] = "jkahsdkjs"; which non-literal character array, can modify it. passed foo "fgfgf" , string literal. change to: char str[] = "fgfgf"; foo(str); would fine.

Access to Outlook's Public Folders: Java or C# -

i know programming language (java or c#) can used better access public folder microsoft outlook. new outlook , have done researches access outlook. and, have found c# used compared java. moreover, of apis not free use. there tutorial guides each programming language can follow , develop application? there open source libraries used? these things want develop: access public folders view available folders get data files folders i grateful precious help! =) in .net (c#, etc) can use exchange webservices apis access public folders adding nuget package microsoft exchange webservices application. you'll need instance of micrtosoft.exchange.webservices.data.exchangeservice work with, plus valid login server - passed in system.net.networkcredential . instance: exchangeservice exchange = new exchangeservice(); service.autodiscoverurl("myemail@mycompany.com"); service.credentials = new networkcredential("myemail", "mypassword", &qu

regex - List to String in Racket -

i've got list defined this: (define testlist '((dog <=> cat) (anne <=> dodd)) is there way turn: (car testlist) string can use regexp on search "<=>"? let me start extremely relevant jamie zawinski quote: some people, when confronted problem, think, “i know, i'll use regular expressions.” have two problems. you really don't want use regular expressions here. 1 thing, regexp-based solution break when have identifiers <=> in middle of them. for another, it's really easy solve problem without using regular expressions. there whole bunch of "right answers" here, depending on you're trying do, let me start pointing out can use "member" function see whether list contains symbol '<=> : #lang racket (define testlist '((dog <=> cat) (anne <=> dodd))) (cond [(member '<=> (car testlist)) "yep"]

email - How to set E-Mail configuraion on android device programmatically -

i want create app on android , make config e-mail setting on android device programmatically when setting data server. i have search around android code example can't find example , don't know start looking. can 1 suggest should start looking? thank you update sorry unclear question. i used method send email programmatically . can use this. you. //send email boolean sendmail(string from,string to) { boolean issend=false; properties props = system.getproperties(); string host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); //enable gmail props.put("mail.smtp.user", "abc@gmail.com"); props.put("mail.smtp.password", "abc"); props.put("mail.smtp.port", "587"); //gmail port address props.put("mail.smtp.auth", "true"); log.d("tag","props set&q

jquery - How do I populate values for multiple chosen plugin? -

Image
i using jquery plugin ( http://harvesthq.github.io/chosen/ ) , having trouble populating selected values textbox. based on options page, says $('.my_select_box').trigger('chosen:updated'); however have multiple select boxes, say <select id="select1" class="chzn-select" name="select1" data-placeholder="choose employee..." multiple="true" style="width: 350px; display: none;"></select> <select id="select2" class="chzn-select" name="select2" data-placeholder="choose employee..." multiple="true" style="width: 350px; display: none;"></select> <select id="select3" class="chzn-select" name="select3" data-placeholder="choose employee..." multiple="true" style="width: 350px; display: none;"></select> and in jquery script have $('.chzn-select',

r - Removing empty group spaces in barcharts of ggplot2/lattice -

Image
this follows on q&a regarding plotting defined groups using barchart in lattice. following solution little exercise, i've realised r plots data appears in dataframe , leaves spaces between each bar, when next row of data allocated space on barchart. if @ plot you'll understand mean: > data.frame(soexample2) study.id diagnosis level 1 1 cancer 1040.58 2 2 cancer 810.92 3 3 cancer 2087.80 4 4 cancer 3959.02 5 5 cancer 3648.48 6 6 cancer 1191.74 7 7 cancer 1156.90 8 8 cancer 2705.56 9 9 cancer 827.26 10 10 cancer 867.16 11 11 cancer 575.10 12 12 cancer 699.85 13 13 cancer 1121.86 14 14 cancer 1830.62 15 15 cancer 4203.01 16 16 cancer 874.59 17 17 cancer 1037.20 18 18 cancer 1398.56 19 19 cancer 910.49 20 20 cancer 725.60 21 21 cancer 894.05 22 2

c++ - Classes and Queue's -

i trying figure out how work queues , classes. how can insert information class queue? i created queue queue<processes> printerdevices how go insert stuff on queue class or reading it? class processes { public: void setpid (int a) { pid = a; } int retrievepid() { return pid; } void setfilename (string input) { filename = input; } string retrievefilename() { return filename; } void setmemstart (int a) { memstart = a; } int retrievememstart() { return memstart; } void setrw (char a) { rw = a; } int retrieverw() { return rw; } void setfilelength (string input) { filelength = input; } string retrievefilelength() { return f

ruby on rails - How to add a title when you don't know what you're asking for? -

i don't know how ask i'm asking ... i'd google if knew looking for! so, have set of carrierwave versions of images names image00, image01, image02 etc image25 stored as: @photo.main.image00 , @photo.main.image01 etc ... i want able use controller post these images out. have no idea how string request together. i've got objective-c, javascript, ruby , host of other languages fighting space in head, , ruby seems have lost out! i wish able make call such as: @photopiece = base64.strict_encode64(file.read(@photos.main.imagexx.current_path)) but have no idea how replace xx digit , still have file encoded. i tried: imagestring = "@photos.main.image#{sendpiece}.current_path" and then @photopiece = base64.strict_encode(file.read(imagestring)) but did nothing ... hear compiler laughing @ me (such paranoia now!) so, how photo names appear in form: @photos.main.imagexx.current_path such can parsed strict_encode? thanks in advance help!

html - 100% width header fixed with two div's -

i'm trying create fixed header sticks top on scroll. have 1 wrapper (#topbarwrapper) should fit 100% across entire browser. have div wrapper (.topbarcontentwrapper ) inside the(#topbarwrapper) includes logo , navigation (#mainnav). 1 floats left , other floats right. both float should seems if when browser resized, divs move. want 2 divs floating inside centered entire page. layout responsive body width 90%. spent several days trying figure out including research. appreciated. ideal goal have header 100% width fixed , centered. layout view: http://s30.postimg.org/so036qarl/screen_shot_2014_03_10_at_1_53_42_am.jpg html: <body> <div id="topbarwrapper"> <div class="topbarcontentwrapper"> <a href="http://link" title="fvfg" id="topbarlogo"></a> <nav id="mainnav" role="navigation"> <

php - How do I unset spl_autoload_register() and from where does it run? -

when using spl_autoload_register() , if understand correctly, once run it, php saves every file. the question have, , 3 questions, is: how remove function spl_autoload_register()? does spl_autoload_register() save functions autoloaded , restore them upon restarting php? does function in spl_autoload_register() run same location? go php.net/spl_autoload_register . on left side, under spl_autoload_register , says spl_autoload_unregister . it saves autoloders every time script runs (which every time visits page). if understand question then, yes. if tell find there (unless iffy).

linux - Forwarding logs to splunk/graylog from syslog-ng -

i want forward apache , tomcat logs central log server.(splunk/graylog) i have client systems syslog-ng running. how can forward logs? is necessary parse logs? can't forward logs are? have edit apache configuration also? i trying done last 1 week. had created question regarding this. no hep found. forwarding log via syslog-ng please this. update1: latest syslog-ng.conf source s_all { internal(); unix-stream("/dev/log"); file("/proc/kmsg" program_override("kernel: ")); file("/var/log/apache/access.log" follow_freq(1) flags(no-parse)); file("/var/log/apache/error.log" follow_freq(1) flags(no-parse)); }; destination d_splunk { udp("ec2-xxx.xxx.xxx.xxx.compute-1.amazonaws.com" port(514)); }; log { source(s_all); destination(d_splunk); }; install universal forwarder central log server (i'm assuming different box splunk instance). monitor path of syslog. don't know syslog-ng logs

How to achieve sliding animation from top to bottom in Android(need to push the content below as this animation happens)? -

my layout have following things: i have title (a linear layout) the first content block (a relative layout in gone state now) the second content block (again relative layout visible) i need animate first content block top bottom while pushing second content block below in same phase first content block moving. i tried many methods. in things second content block visble @ place , first content block moving upto top. kindly give me suggestions. you need give id layouts , create animation. here sample code. public void slidetoabove() { animation slide = null; slide = new translateanimation(animation.relative_to_self, 0.0f, animation.relative_to_self, 0.0f, animation.relative_to_self, 0.0f, animation.relative_to_self, -2.0f); slide.setduration(400); slide.setfillafter(true); slide.setfillenabled(true); rl_footer.startanimation(slide); slide.setanimationlistener(new animation

android - My TextView expands to hold larger amount of text but that distorts the layout? -

Image
here images of application 2 different inputs: 60! , 125! with 60! buttons not distorted. with 125! buttons gone. add android:maxlines , android:ellipsize attributes textview xml below... <textview android:layout_width="fill_parent" android:layout_height="wrap_content" android:maxlines="3" android:ellipsize="end" />

java - Uno Project: Making sure that a illegal plays return correctly? -

i writing chunk of program play uno other classes. uno project finished, need sure part checks make sure on moves after wild card played, play either legal card or return -1. here code: import java.util.*; public class alexal_unoplayer implements unoplayer { public int play(list<card> hand, card upcard, color calledcolor, gamestate state) { int play = -1; boolean havewild = false; boolean matcheswildcall = false; int indexofwild = 0; //turn number of cards players holding ints later use int[] array = state.getnumcardsinhandsofupcomingplayers(); int playernext = array[0]; int playertwonext = array[1]; int playerbefore = array[2]; color upcardcolor = upcard.getcolor(); for(int = 0; < hand.size(); i++) { //see if have wilds if(hand.get(i).getrank().equals(rank.wild) || hand.get(i).getrank().equals (rank.wild_d4)) { havewild = true; indexofwild = i; } //set upcard

mysql - SQL find and replace with wildcard -

starting position: have sql-db, contains several tables hunderts or tousends of entries. in several fields (columns) there urls, should shortened (to extract of original url) , added new parameter. thing is, there «find & replace» do: find (old) urls inside fields/columns of tables (stand-alone or inbetween text)… http://www.domain.com/click?p(abcdef)a(123456)url(http://www.url.com) … , replace old url (new) url: http://www.url.com/?at=uvwxyz … as can see need wildcard inside url-parameter … like http://www.domain.com/click?p(abcdef)a(123456)url(*) because old url ends ) , need extract of old url (the second url) plus new url-parameter. the url inside ( , ) in old url can vary … there maybe hunderts or tousands of different urls. the urls in several fields in several tables … inside , surrounded text , not stand-alone (see table below). there more one field/columns per entry none, 1 or more one urls per field/column should changed. table example: +-----

How to setup an Android development environment using STS, Android SDK, Maven and Spring Android -

this quick howto on setting android development environment including sts, android sdk, spring android, maven. 1) install latest sts (currently 3.4.0) 2) setup android development environment in sts per normal android development setup steps existing ide: http://developer.android.com/sdk/installing/index.html 3) above step, save time copying “android-sdk” folder developer has setup environment, , point sts android folder (window-->preferences-->android-->sdk location) 4) install m2e-android per: http://rgladwell.github.io/m2e-android/ create sample android application using maven 1) in sts, click on file-->new-->maven project 2) select workspace location , click next 3) maven archetype, select “android-quickstart” , click next. archetype should exist if added archetype according to: http://rgladwell.github.io/m2e-android/ 4) fill in desired maven project details , click next. 5) in pom.xml, set "platform.version" tag value 4.1.1.4 6) right clic

How do I get the application exit code from a Windows command line? -

i running program , want see return code (since returns different codes based on different errors). i know in bash can running echo $? what do when using cmd.exe on windows? a pseudo environment variable named errorlevel stores exit code: echo exit code %errorlevel% also, if command has special syntax: if errorlevel see if /? details. example @echo off my_nify_exe.exe if errorlevel 1 ( echo failure reason given %errorlevel% exit /b %errorlevel% ) warning: if set environment variable name errorlevel , %errorlevel% return value , not exit code. use (set errorlevel= ) clear environment variable, allowing access true value of errorlevel via %errorlevel% environment variable.

r - ggplot2 tile scale limits -

Image
this question has answer here: how multiple ggplot2 scale_fill_gradientn same scale? 2 answers apologies if bit of obvious question, can tell me how can set scale on heatmap drawn geom tile? want draw several heatmaps on same scale (e.g. drawn colours scaled maximum of 10 though on 2 of them maximum 5) , can't work out. an example: mydata<-expand.grid(x1=1:8,y1=1:5) z1<-floor(runif(40,min=0,max=6)) z2<-floor(runif(40,min=0,max=11)) mydata<-cbind(mydata,z1,z2) mydata<-data.frame(mydata) p1 <- ggplot(mydata, aes(x=x1, y=y1, z = z1)) p1 <- p +geom_tile(aes(fill = z1)) p2 <- ggplot(mydata, aes(x=x1, y=y1, z = z2)) p2 <- p +geom_tile(aes(fill = z2)) p1 scaled between 0 , 4 whereas p2 scaled between 0 , 10. i'd draw both of them colours on same scale - "4" has same colour in both heatmaps. thanks help sorry

How can I Get Google Map Api v3 key? -

Image
i'm trying google maps api v3 key. read lot of tutorials google map api v3 when go google api console , in services did not api. however, google map javascript api v3 lies there gives client id not api key. kindly guide me how can it? have seen this link ? visit apis console @ https://code.google.com/apis/console , log in google account. click services link left-hand menu. activate google maps api v3 service. click api access link left-hand menu. api key available api access page, in simple api access section. maps api applications use key browser apps. then have use in webpages <script async defer src="https://maps.googleapis.com/maps/api/js?key=your_api_key&callback=initmap"> and replace your_api_key api key generated. here, initmap name of method executed once googlemaps loaded ; can remove or rename parameter depending need do experience issue step-by-step ? worked me.

listview - Android: Where is the correct place to make a http request in a List Adapter -

i have list adapter listview in 1 activity, now want populate list view data obtain web service. correct place execute async request server obtain json data populate adapter? 1: before instantiate adapter , passing through constructor? dont know how refreshing work. 2: in adapter? 2.1: in adapters constructor? 2.2 in view? here adapter far: public class mydevicesadapter extends baseadapter { private context mcontext; private string tag = "mydevicesadapter"; // keep objects in array private arraylist<mydevice> devices; /** * constructor creating devices list adapter * * @param context * context of calling class */ public mydevicesadapter(context context) { mcontext = context; devices = new arraylist<mydevice>(); } @override public int getcount() { return devices.size(); } @override public object getitem(int position) { return devices.get(position); } @override public long getitemid(int position) {

php - how to find a element in a nested array and get its sub array index -

when searching element in nested array, it's 1st level nesting index. <?php static $cnt = 0; $name = 'victor'; $coll = array( 'dep1' => array( 'fy' => array('john', 'johnny', 'victor'), 'sy' => array('david', 'arthur'), 'ty' => array('sam', 'joe', 'victor') ), 'dep2' => array( 'fy' => array('natalie', 'linda', 'molly'), 'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'), 'ty' => array('sharon', 'julia', 'maddy') ) ); function recursive_search(&$v, $k, $search_query){ global $cnt; if($v == $search_query){ /* want sub array index returned */ } } ?> i.e say, if i'am searching 'victor', have 'dep1' return value. ??

python - Trouble with pyserial on cygwin -

Image
i have written program in python script requirement take input makey-makey keyboard w-a-s-d-f-g . i able input device, facing difficulty in cygwin. there try except block handle case when device not connected. problem in cygwin try except block not getting read. i understand port in cygwin not available, , also, device listed file . what problem , how overcome this: here's code: #python program capture # makey makey input # program read device connected # , based on keys connected # print approrpriate messages import os,sys import serial plat = sys.platform.lower() if plat == 'win32': #for windows operating system com_port = 'com2' print com_port elif plat == 'cygwin': # cygwin com_port = '/dev/ttys1' print "attempting open com port..." try: # check device com number ser = serial.serial(com_port, 9600, timeout = 10) print "successfully opened com port." print "your co

Java https works but C# doesn't for same request -

i'm converting java program send https post request 3rd party server in internet. java program run in pc , works fine , connect server. then run c# program. server returns 400 bad request response. then use fiddler , compare content of each http request java , c# programs, , both contents same. here cannot test using http because destination server allows https so i'm guessing can certificate issue of visual studio? have idea such case? code i posted code in question java vs c# http request json data if problem occurring in java version, i'd dismiss certificates cause. in java, certificate problem result in protocol error exception ... not http response code. sending http request https port (or vice versa) wouldn't give http response. therefore suspect there >>is<< different requests, or request headers. the other alternatives can think of are: the server giving responses depending on ip addresses, or depending on whethe

ios - How to animate UIView while hiding or unhiding -

i want animate uiview while hiding or unhiding it. i have button loads uiview "view.hidden=false"and hide "view.hidden=true". is there way of hiding/unhiding while animating it? use : default put alpha of view 0.0. yourviewobject.alpha = 0.0f; when trying unhide view use this: yourviewobject.hidden = no; [uiview animatewithduration:0.5f animations:^{ yourviewobject.alpha = 1.0; } completion:^(bool finished) { //done }]; and @ hiding use this [uiview animatewithduration:0.5f animations:^{ yourviewobject.alpha = 0.0; } completion:^(bool finished) { //done yourviewobject.hidden = yes; }];

sharedpreferences - Shared preferences are empty on initial set up of Android app -

i have code set shared preferences: scontext = getapplicationcontext(); configuration = new configurationdata(preferencemanager.getdefaultsharedpreferences(scontext)); but i'm finding mmap , hashmap table inside preferencemanager.getdefaultsharedpreferences(scontext) empty. why empty? think i've set preference screens , values correctly because working earlier today. i'm trying think of what's changed... timing issue? need occur before sharedpreferences load? how initialised? redeployed app emulator not long ago it's fresh install, maybe need populate hashmap? any ideas welcome, thank you.

tcl - First value from second column with the smallest value from column 1 -

i have file 2 1 12 2 34 1 56 1 45 3 33 2 77 1 83 2 62 3 75 3 i want take first value second column smallest value column 1 this 2 1 12 2 45 3 this can done linear scan , little bit of use of associative array, this: set f [open $filename] foreach line [split [read $f] "\n"] { # assume: valid tcl list of numbers lassign $line col1 col2 if {![info exists minima($col2)] || $minima($col2) > $col1} { set minima($col2) $col1 } } close $f foreach col2 [array names minima] { puts "$minima($col2) $col1" } imposing whatever sorts of parsing, sorting , formatting require left you.

Android Action Bar SearchView NullPointerException adjustDropDownSizeAndPosition -

the problem occurs when interacting searchview or when activity searchview loads. when using seticonifiedbydefault(true) problem occurs after activity loads when interacting searchview, when using seticonifiedbydefault(false) problem occurs when activity loads. the following error output in logcat: java.lang.nullpointerexception @ android.widget.searchview.adjustdropdownsizeandposition(searchview.java:1244) here code: exampleactivity.java public boolean oncreateoptionsmenu(menu menu) { getmenuinflater().inflate(r.menu.example, menu); if(build.version.sdk_int >= build.version_codes.honeycomb) { searchmanager manager = (searchmanager) getsystemservice(context.search_service); searchview search = (searchview) menu.finditem(r.id.search).getactionview(); search.setsearchableinfo(manager.getsearchableinfo(getcomponentname())); search.seticonifiedbydefault(true); search.setonquerytextlistener(new onquerytextlistener() {

deleting white space at the end of for loop output in php -

can body me how can delete white space @ end of output. might easy question honest took me more 45 minutes , still nothing. assignment write php script prints numbers number inputted on form zero. numbers should separated single space last number, zero, should not have space after it. if user inputs number smaller zero, print “the number should @ least zero!” used form looks this: luku: example output 5 4 3 2 1 0 my code: <?php $number=$_get["number"]; if ($number < 0){ echo "the number should @ least zero!"; } else { for($i=$number; $i>=0; $i=$i-1) { echo $i." "; } } ?> you can use trim() <?php $number=$_get["number"]; if ($number < 0){ echo "the number should @ least zero!"; } else { $num = ''; for($i=$number; $i>=0; $i=$i-1) { $num .= $i." "; } echo trim($num); } ?

php - mysql_num_rows() expects parameter 1 to be resource boolean given in -

this question has answer here: mysqli_fetch_array()/mysqli_fetch_assoc()/mysqli_fetch_row() expects parameter 1 resource or mysqli_result, boolean given 33 answers what wrong query? $check_select = mysql_num_rows(mysql_query("select * `user` user_id = '$user_fbid'")); if($check_select > 0){ mysql_query("insert `user` (user_id, name, photo) values ('$user_fbid', '$user_fnmae', '$user_image')"); } it returned mysql_num_rows() expects parameter 1 resource, boolean given in $row = mysql_query("select * user user_id = '{$user_fbid}'"); $check_select = mysql_fetch_array($row); if($check_select > 0){ mysql_query("insert user (user_id, name, photo) values ('{$user_fbid}', '{$user_fnmae}', '{$user_image}')"); } and stop work mysql! work mysqli

sql - MySQL string data truncated in group_concat and order by -

i have sql works fine truncates serialized data on string fields long more 1024bytes. tried change mysql variable group_concat_max_len, nothing has changed. there other session variables involved in? set session group_concat_max_len = 100000; select concat(area,';', colore,';', cast(percentuale char(20)),';', cast(trasparenza char(20)),';', date_format(data_misura,'%y%m%d'),';', ( select group_concat( concat( cast(x char(20)), ' ', cast(y char(20)) ) order progressivo_vertice separator ';') plan_poligoni id_imm = pp_gen.id_imm , scheda = pp_gen.scheda , progressivo = pp_gen.progressivo , if(data null,'',data) = if(pp_gen.data null,'',pp_gen.data)),'|') serialized_polygons plan_poligoni pp_gen scheda=1 , id_

AutoCompleteTextView using JSON in Android -

i'm trying extract json array autocompletetextview i'm getting each value twice in drop down. json: {"names":[{"id":"1","names":"jacob"},{"id":"2","names":"amy"},{"id":"3","names":"melissa"}],"success":1,"message":"successfully found "} class ajax: class ajax5 extends asynctask<string, string, string> {// json starts here // new createnewproduct().execute(); protected arraylist<namevaluepair> parameters; jsonobject json; public ajax5() { super(); parameters = new arraylist<namevaluepair>(); } @override protected void onpreexecute() { super.onpreexecute(); } protected string doinbackground(string... args) { jsonparser jparser = new jsonparser(); json = jparser .makehttprequest(

php - Solr comands not returning json output -

i going through php documentation solr , wanted try out basic example. expected output isn't received , blank page returned when try following code existing project. <?php include "bootstrap.php"; $options = array ( 'hostname' => solr_server_hostname, 'login' => solr_server_username, 'password' => solr_server_password, 'port' => solr_server_port, ); $client = new solrclient($options); $doc = new solrinputdocument(); $doc->addfield('id', 334455); //$doc->addfield('cat', 'software'); //$doc->addfield('cat', 'lucene'); $updateresponse = $client->adddocument($doc); print_r($updateresponse->getresponse()); ?> the bootstrap.php goes this: /* domain name of solr server */ define('solr_server_hostname', 'localhost'); /* whether or not run in secure mode */ define('solr_secure', false); /* http port connection */ define(&#