Posts

Showing posts from August, 2010

c# - byte array to string and back. Confused -

this question has answer here: asciiencoding.ascii.getbytes() returning unexpected value 3 answers what wrong code? why differences? byte [] data = new byte [] {0x21, 0x4b, 0x9b, 0xe1, 0x2d, 0xa7, 0x4b, 0x93, 0x1e, 0x3f, 0xda, 0x4f, 0xb1}; console.writeline(bitconverter.tostring(data)); string datastr = asciiencoding.ascii.getstring(data); byte[] ca = asciiencoding.ascii.getbytes(datastr); console.writeline(bitconverter.tostring(ca)); output: 21-4b-9b-e1-2d-a7-4b-93-1e-3f-da-4f-b1 21-4b-3f-3f-2d-3f-4b-3f-1e-3f-3f-4f-3f ascii doesn't define character codes above 7f , , seems asciiencoding.ascii.getstring() chooses replace invalid bytes 3f , represents character ? . you might want read joel spolsky's excellent article on encoding .

c# - Why isn't my background color binding updating? -

ok, sure have setup correctly... i have grid, shown here: <grid grid.row="1" grid.column="1" background="{binding crewselbg[1]}"> ok. have following array, here: private string[] crewselbg; public string[] crewselbg { { return crewselbg; } set { crewselbg = value; onpropertychanged("crewselbg"); } } i initialise values in array in constructor of viewmodel shown here: crewselbg = new string[26]; crewselbg = enumerable.repeat("#8a008a00", 26).toarray(); this initialises entire array green colour. (in fact green colour should #00000000 wanted see bound correctly). have checkbox, when clicked activates icommand. here checkbox: <checkbox grid.column="0" ischecked="{binding crewchecked[1]}" margin="5,0,0,0" command="{binding crewselectcheck}" commandparameter="01"/> and icommand calls setup here: private icomma

populating a string array dynamically from a column of phrases in an excel sheet -

i have 2 sheets. using user-defined function in sheet 1, in want use array compare strings. array comprised of contents of column of cells in second sheet (which named "phrases."). so (looking @ way) in "phrases" have 100 strings typed column p, cells 3 102. , want put of them array can use later. now, let me complicate little - intent users of spreadsheet able add new content column p, may 500 cells or more. want populate array dynamically. here's - , doesn't seem working: dim newarray() string dim long dim counter long counter = 0 = 0 5000 if worksheets("phrases").cells(i + 3, 16).value <> 0 newarray(counter) = worksheets("phrases").range(i + 3, 16).value counter = counter + 1 end if next where going wrong? please note - i've tried without .value - didn't seem work. i've tried .text instead of .value - didn't seem work. i've tried cstr(worksheets("phrases").rang

Code Design: How to avoid program control by catching an exception of a subroutine? -

today faced following problem @ our company: have 2 methods void a() {...} // can throw timeout exception void b() { try { a(); } catch(timeoutexception e) { ... // continue solving problem way } } method b calls a internally. if method a throws timeout exception, method b catches , continues solving problem algorithm. if consider method a isolated, throwing exception makes perfect sense. however, if consider method b , catching exception controlling logic looks code smell. question: how can 1 improve situation? at first glance, 1 think of predicate method pre-check whether method a can solve problem or not. in our situation not possible, because trying solve problem turns out if method a can or not. the smell possibly stems fact trying interpret same fact (exception thrown) error (isolated a ) part of business flow ( a called in b ). one of ways of making explicit introduce parameter: void a( bool throwsontimeout ) {...} this way be

xml - Name clashes when combining XSD via xsd:include? -

i presently reading professional xml bill evjen, kent sharkey, thiru thangarathinam, michael kay, alessandro vernet, sam ferguson. i beginner , trying basic structure of xml schema document. authors put forward concepts on how put xml schema documents together. import imports allow import entire xml schema document 1 working with. done if 2 varying xml schema documents utilize different namespaces. import done using <import> element , 2 attributes—namespace , schemalocation . include the <include> element used if other schema has same namespace or makes use of no namespace. quite similar <import> element , way combine 2 schemas little work. i find myself confused line, include element used if other schema has same namespace or makes use of no namespace. if have same namespace , wouldn't results in clash between same elements defined in both schemas ? if you're combining xsds same namespace or no namespace via xsd:i

sql server - Include A 0 Count if null or blank in pivot -

i need show data each part, , query working...almost. syntax select * ( select item [item], count(sold) [count], storename saleinfo group item, storename ) first pivot ( count([count]) item in ([brake pads], [rotors],[shoes],[drums] ) piv now issue having if count of 0 returned item omitted results. meaning if 0 brake pads sold brake pads not dispalyed in result set. how can have dispaly item if count returned 0? you use isnull or coalesce convert null 0 : select isnull([brake pads], 0) [brake pads], isnull([rotors], 0) [rotors], isnull([shoes], 0) [shoes], isnull([drums], 0) [drums] ( ...

javascript - Firebase - Push to pushed data -

here's data { "deck" : { "-jkpwaniekjqvsdtpd4m" : { "deck" : "deck 1", "user" : "simplelogin:1" }, "-jkq4unexm-qwho_u2yo" : { "deck" : "deck 2", "user" : "simplelogin:1" }, "-jkq5-ii1q5ym6w3ytmg" : { "deck" : "deck 3", "user" : "simplelogin:6" }, "-jks5mbmhmpb9mwnnocj" : { "deck" : "deck 4", "user" : "simplelogin:1" } } } if want add: cards: { "-generatedkey":{ "title":"foo", "text":"bar", } } to item deck "deck 2", how select object push it. end result be: { "deck" : { "-jkpwaniekjqvsdtpd4m" : { "deck" : "deck 1", &

ios - dequeueReusableCellWithIdentifier and custom cells -

ok, i’ve got table 3 different prototype cells (cellvaccination, celladmin, cellexpire). in cellforrowatindexpath method, i’m splitting core data object across 3 individual cells structurally table following: - drug 1 - drug 1 admin - drug 1 expire - drug 2 - drug 2 admin - drug 2 expire - drug 3 - drug 3 admin - drug 3 expire additionally, i’ve programmatically added uiswitch ‘top level’ cell (i.e. drug 1) switch might control secondary cells features (i.e. color, text, etc). here current cellforrowatindexpath looks like: - (vaccinetableviewcell *)tableview:(uitableview *)tableview cellforrowatindexpath:(nsindexpath *)indexpath { // need adjust indexpath because split single core data object 3 different rows nsindexpath *adjustedindexpath = [nsindexpath indexpathforrow:indexpath.row / 3 insection:indexpath.section]; vaccine *vaccine = [self.fetchedresultscontroller objectatindexpath:adjustedindexpath]; // define switch added primary table rows

MySQL table with 50+ million rows - how to speed up searching using indexes? -

my table structure follows: create table if not exists data_bussines ( bussines_id bigint(20) unsigned not null auto_increment, name varchar(50) not null, primary key (bussines) ) engine=innodb default charset=latin1 auto_increment=7059415 ; my selects on table have clauses 1 or more of 'name', 'searched on. slow. you can created clustered index on name. please see question more information mysql how create clustered index?

ubuntu - OpenCV-3.0.0-beta failure to build on 32-bits and 64-bits Ubuntu12.04 - IPP symbols undefined -

linking cxx executable ../../bin/opencv_perf_core ../../lib/libopencv_core.so.3.0.0: undefined reference ippitranspose_16u_c4ir' ../../lib/libopencv_core.so.3.0.0: undefined reference to ippimean_stddev_16u_c1r' ../../lib/libopencv_imgproc.so.3.0.0: undefined reference ippifiltersobelhorizborder_8u16s_c1r' ../../lib/libopencv_core.so.3.0.0: undefined reference to ippinorm_l2_32f_c4r' ../../lib/libopencv_imgproc.so.3.0.0: undefined reference ippimulc_16s_c1irsfs' ../../lib/libopencv_core.so.3.0.0: undefined reference to ippinormdiff_l1_8u_c4r' ../../lib/libopencv_imgproc.so.3.0.0: undefined reference ippiresizelinear_16u_c3r' ../../lib/libopencv_core.so.3.0.0: undefined reference to ippinormdiff_inf_32f_c1mr' ../../lib/libopencv_imgproc.so.3.0.0: undefined reference ippicopysubpixintersect_8u_c1r' ../../lib/libopencv_imgproc.so.3.0.0: undefined reference to ippierodeborder_8u_c1r' ../../lib/libopencv_imgproc.so.3.0.0: undefined reference `ippi

c++ - C# I/O vs C I/O -

i have c# program needs read tens hundreds of millions of records flat text file. there significant performance gain using p/invoke call unmanaged c/c++ dll handles of file input on separate thread, or insignificant gain in performance, such better handle file io in c#? there not significant performance gain in using c/c++ dll. c# runs in environment quite efficient jit compiler, guess code performance limited hard disk read speed of approximately 100 mb/s. of course, if have ssd, mileage may vary. do note if 1 record e.g. 1000 bytes , reading 100 million records, means 100 gigabytes. reading takes 1000 seconds, i.e. more 15 minutes, due slow speed of hard disk drive.

Entity Framework - The property cannot be configured as a navigation property -

i'm defining 2 entities following, strange behavior occurring: [table("clienttypes", schema="dbo")] public clienttype { [key] public int id { get; set; } public string name { get; set; } } [table("clients", schema="dbo")] public client { [key] public long id { get; set; } [foreignkey("clienttypeid")] public int clienttypeid { get; set; } public virtual clienttype clienttype { get; set; } } i'm getting clienttypeid property filled value, clienttype object filled nothing. can me this? thank all! the foreignkey attribute have on wrong property. the annotation may placed on foreign key property , specify associated navigation property name, or placed on navigation property , specify associated foreign key name. - source [foreignkey("clienttypeid")] should decorate public virtual clienttype clienttype instead, or change [foreignkey("clienttype"

rust - Unable to import/export macro -

i have module named macros.rs contains /// macro implement fromerror. /// from_error!(myerror, ioerror, myerror::ioerror) macro_rules! from_error { ( $t:ty, $err:ty, $name:path ) => { use std; impl std::error::fromerror<$err> $t { fn from_error(err: $err) -> $t { $name(err) } } } } in main.rs import module this #[macro_use] mod macros; when try use from_error in other modules of project, compiler says error: macro undefined: 'from_error!' . turns out order in declare modules matters. mod json; // json uses macros "macros" module. can't find them. #[macro_use] mod macros; #[macro_use] mod macros; mod json; // json uses macros "macros" module. everything's ok way.

c++ - Why does rdbuf() not print anything? -

in following example, ifstream myfile; myfile.open("example.txt", ios::binary); cout << myfile.rdbuf() << endl; myfile.close(); the contents of file printed, in entirety on 1 line. can this: ifstream myfile; myfile.open("example.txt", ios::binary); unsigned char character = myfile.get(); while(myfile){ cout << "one character = "; cout << character; character = myfile.get(); //gets each individual character, 1 @ time } myfile.close(); and print contents of file, 1 character @ time. however, if try methods 1 after other (in order), 1 method print anything. explain why, in following example, call rdbuf() won't print contents of file? ifstream myfile; myfile.open("example.txt", ios::binary); unsigned char character = myfile.get(); while(myfile){ cout << "one character = "; cout << character; character = myfile.get(); //gets each individual character, 1 @

generics - Java - Return different child classes based on input parameters -

given these classes: public class versionvov1 extends basevo { private string fieldone = null; public string getfieldone() { return fieldone; } public void setfieldone(string fieldone) { this.fieldone = fieldone; } public class versionvov2 extends basevo { private string fieldfour = null; public string getfieldfour() { return fieldfour; } public void setfieldfour(string fieldfour) { this.fieldfour = fieldfour; } } public class basevo { // common code here } i have calling method dosomething returns specific child class based upon input string: public basevo dosomething(string version) { basevo versionvo = dosomethingversioned(createversionvo(version)); return versionvo; } the remaining methods are: private basevo createversionvo(string version) { basevo versionvo = null; if (version.equalsignorecase("v1")) { versionvo = new versionvov1(); } else if

javascript - Incorrect syntax when filtering ng-options? -

i'm trying sort alphabetically 'long_name'. no avail. can't list change. missing something? <select ng-model="client.primary_contact" ng-options="provider.long_name provider in providers | orderby:'provider.long_name' track provider.uid"></select> i started here (angular docs on orderby). you should provide property name orderby filter. try this: ng-options="provider.long_name provider in providers | orderby:'long_name' track provider.uid" check documentation orderby filter, expression argument.

routes - using mDNS, no router, ipv6 on ubuntu gets "Invalid Argument" -

i'm trying set appliance announce service using mdns, , connect no infrastructure or router or dhcp. works between raspberry pi , osx. not between raspberry pi (running ubuntu hostname 'ubuntu.local') , ubuntu 14.02 on intel. here's run down of focused test, command line of ubuntu on intel, after clearing out routes on ubuntu. jeff@jeff-optiplex-sx280:~$ ip -6 route list jeff@jeff-optiplex-sx280:~$ sudo traceroute -i eth0 ubuntu.local traceroute ubuntu.local (fe80::ba27:ebff:fe1a:74e5), 30 hops max, 80 byte packets connect: network unreachable so -- no routes, right? let's add 1 , try again: jeff@jeff-optiplex-sx280:~$ sudo ip -6 route add fe80::/10 dev eth0 jeff@jeff-optiplex-sx280:~$ sudo traceroute -i eth0 ubuntu.local traceroute ubuntu.local (fe80::ba27:ebff:fe1a:74e5), 30 hops max, 80 byte packets 1 ubuntu.local (fe80::ba27:ebff:fe1a:74e5%eth0) 0.925 ms 0.988 ms 1.058 ms now have route , have demonstrated ubuntu on intel knows ipv6 add

visual c++ - fopen fwrite work but no file is created -

below here simple program. if run guest (not administrator) , file didn't exist @ moment of execution, program tells "ok" (that is, fopen , fwrite seem work) test.bin isn't created. expected fopen return null did not. correctly returns null if file created administrator , existed but, if there isn't file, tells ok file isn't created. win 7 professional, msvc 6.0 tommaso #include "stdafx.h" #include "stdio.h" #include "conio.h" int main(int argc, char* argv[]) { file *fp; fp=fopen("c:\\test.bin","w+b"); if (fp==null) printf("fopen returned null\n"); else { if (fwrite("hello",5,1,fp)!=1) printf("fwrite failed\n"); else printf("ok\n"); } if (fp) fclose(fp); getch(); return 0; } if have uac enabled on system , application not have manifest, uac virtualization system redirect writes protected locations. th

ios - Matrix multiplication and inverse problems with accelerate framework -

i trying multiply 2 matrices in objective-c. have imported accelerate framework project in xcode, compiles fine. did matrix multiplication on calculator , got correct values, however, when running code, not. how defined matrices.. float matrixa [3][3] = {{-.045, -.141, -.079}, {-.012, -.079, .0578}, {.112, -.011, -.0830}}; float matrixb [3][1] = {{40}, {-61}, {98}}; i used mmul function in accelerate framework.. vdsp_mmul(&matrixa[3][3], 1, &matrixb[3][1], 1, &results[3][1], 1, 3, 1, 3); the array results created doing following.. float results[3][1]; i placed in viewdidload method of empty project nslog results. when multiply matrixa matrixb should following results.. (-1, 10, -3). however, results in nslog show (-0.045, 0.000, 0.000). not correct , don't understand why. understanding function multiply 2 matrices together. not sure doing. inputing incorrectly , hoping me out. side note: matrixa inverse of matrix. however, can't find i

autocad - Plotting circles and arc without segmentation (PLT format) -

Image
i'm having problems plotting vector objects such arcs , circles autodesk without forcing them set of lines. plt (hpgl) file format supports both circles , arcs defined through various means, reason, output uses lines. the drawing i've created simple, testing purposes and output plotting (i've separated commands single lines it's more readable) .(;.i81;;17:.n;19:in; sc; pu; ro90; ip; iw; vs20,1vs20,2vs20,3vs20,4vs20,5vs20,6vs20,7vs20,8sp1; pu; pa0,0; sp1; lt; pa-4985,2256; pdpa-2985,256,-2985,-1744,-4985,256,-4985,2256; pupa-4967,-2572; pdpa-4862,-2569,-4757,-2563,-4653,-2552,-4549,-2538,-4446,-2520,-4343,-2498,-4241,-2473,-4141,-2443,-4041,-2410,-3943,-2373,-3846,-2333,-3751,-2289,-3657,-2241,-3566,-2190,-3476,-2136,-3388,-2078,-3303,-2017,-3219,-1953,-3139,-1886,-3060,-1816,-2985,-1744; pupa-1530,-26; pdpa-1472,-24,-1414,-18,-1357,-8,-1300,5,-1245,22,-1190,42,-1137,66,-1086,94,-1037,124,-989,158,-944,195,-902,235,-862,277,-825,322,-791,369,-761,419,-733,470,-

PHP 5.4 + Oracle 11.2g : return collection in a cursor -

assume, in oracle 11.2g the following type: create type a_type table of varchar2(30); the following record type: type a_record record(id number(18) ,a_collection a_type ); the following cursor type: type a_cursor ref cursor return a_record; the following stored proc definition function a_function return a_cursor; when executing function php 5.4 retrieve cursor, get: ora-00932: inconsistent datatypes: expected char got adt while know collections can returned individually using: oci_new_collection oci_bind_by_name ...it appears problem caused inclusion of a_collection in cursor. my question is: know whether way exists return a_collection in php 5.4 cursor oracle 11.2g?

windows - best way to find dll by name on c drive? -

what's best way find dll name on c drive? when use windows native search through file explorer on c:\ search using name of known dll on computer , search doesn't find it. is there 3rd party tool searching windows os file name? searchmyfiles 3rd party tool searching files containing text don't think searchmyfiles supports searching file text. here's command line method finding of occurrences of dll on c: drive dir c:\*<dllname> /s

java - Configure transaction in Spring 4.1.5 without XML -

i'm writing application connects oracle database. call function db inserts new records table. , after callback can decide want do: commit or rollback. unfortunalety i'm new in spring, have problems configuration. , what's more want make configuration in java class, not in xml. , here need help. updated code: applicationconfig code: @configuration @enabletransactionmanagement @componentscan("hr") @propertysource({"classpath:jdbc.properties", "classpath:functions.properties", "classpath:procedures.properties"}) public class applicationconfig { @autowired private environment env; @bean(name="datasource") public datasource datasource() { basicdatasource datasource = new basicdatasource(); datasource.setdriverclassname(env.getproperty("jdbc.driver")); datasource.seturl(env.getproperty("jdbc.url")); datasource.setusername(env.getproperty("jdbc.u

json - Crontab not properly executing a php file due to permissions -

i have version.php script writes on settings.json file (centos6). <? $new['time'] = time(); file_put_contents('settings.json', json_encode($new, json_numeric_check)); if login via ssh , execute (with root): php -q /www/cronjobs/version.php everything runs fine , settings updated properly. idea php file executed every 5 minutes cronjob, did this: crontab -e */5 * * * * /usr/bin/php -q /www/cronjobs/version.php >> /www/cronjobs/cron.log 2>&1 but after 5 minutes, settings.json not updated, , cron.log empty. how can add cronjob crontab list? perhaps has permissions? did root , msversion.php, settings.json , cron.log 755 chmoded.

Is test-unit incompatible with ruby 2.2.0? -

i'm new ruby. i'm starting play following this guide setting ruby, rvm, update mac current version, without problem. installed test-unit gem , try tdd script. running test nothing happen. run ruby "-d" option , happen. exception 'loaderror' @ /users/blacksheep/.rvm/rubies/ruby-2.2.0/lib/ruby/site_ruby/2.2.0/rubygems.rb:1222 - cannot load such file -- rubygems/defaults/operating_system exception 'loaderror' @ /users/blacksheep/.rvm/rubies/ruby-2.2.0/lib/ruby/site_ruby/2.2.0/rubygems.rb:1231 - cannot load such file -- rubygems/defaults/ruby exception `loaderror' @ /users/blacksheep/.rvm/rubies/ruby-2.2.0/lib/ruby/site_ruby/2.2.0/rubygems/core_ext/kernel_require.rb:54 - cannot load such file -- test/unit exception 'nomethoderror' @ /users/blacksheep/.rvm/rubies/ruby-2.2.0/lib/ruby/site_ruby/2.2.0/rubygems/specification.rb:1984 - undefined method `to_ary' # exception 'nomethoderror' @ /users/blacksh

rebol - How to compare to none -

i have following block of data: client: ["id" "1234" "name" "foobar" "custom_ip" none] strangely, comparing "none" never seems work. if none = (select client "custom_ip") [print "yay!"] though when print select client "custom_ip" returns "none". why this? can determine that value none? there difference between literal value of type none! , word! spelling none . one can (rightfully, imo) call bug console not differentiate these when giving output of expression: >> none ;-- word! looked value == none ;-- value, , it's *not* word! to less deceptive response console of value none word evaluated in case, can use mold/all >> print mold/all none == #[none] or can show type of result instead of result itself: >> type? none == none! although that's deceptive in sense similar reasons, looks word none! when it's datatype...

Celery monitoring on Heroku -

i have worker process in heroku app runs celery ( celery worker --app=myapp ). should use monitor workers? there built-in in django? or there 3rd-party service? you use flower , real-time web based monitor , administration tool celery. this repo contains guide on how run on heroku. configure app providing broker url , password logging flower: heroku config:set broker_url=redis://... heroku config:set flower_basic_auth="username:password"

arrays - Implementing Split function in C -

i'm trying write c function similar split in java. when @ main, instead of add function, works perfectly. couldn't understand why not work add function. #include <stdio.h> #include <string.h> char *words[50] = { null }; void add(const char *word) { static int = 0; words[i] = word; i++; } int main( void ) { char string[65]; char *tokenptr; fgets(string, 65, stdin); tokenptr = strtok( string, " " ); add(tokenptr); int = 0; while ( tokenptr != null ) { add(tokenptr); tokenptr = strtok( null, " " ); } int i; for(i = 0; words[i] != null; i++) puts(words[i]); return 0; } this little piece of actual code, there reasons why need in function. remove first add calling. fgets(string, 65, stdin); tokenptr = strtok( string, " " ); // add(tokenptr); // remove since you'll add first token in next while loop. also, should remove

node.js - What's the best way to handle insert unique, okay to overwrite? -

i want maintain collection of geographical info ip addresses. var ipaddressschema = new schema({ ip: { type: string, unique: true }, geo: object }, { strict: true }); ips should unique. , if ip exists, should overwrite document. function storegeotomongo() { emitter.on('inredis', function (geodata, ipstring) { console.log('.... store geoinfo mongodb ' + ipstring); ipaddress.findoneandupdate({ ip: ipstring }, { ip: ipstring, geo: geodata }, { upsert: true }, function (err, document) { if (err) { console.log(err); } else { console.log('successfully saved document'); } }); } ); } is there above should improved? (thanks, neil.)

How to make a portable Pyramid application -

i'm starting pyramid application on osx deployed on ubuntu. application need packages such boto , pymongo. need make application easy deploy on ubuntu? just follow of tutorials pyramid provides using scaffolds either on osx , on ubuntu. show how pyramid application requirements managed. abstracted defining requirements in setup.py or requirement.txt example. sqlalchemy + url dispatch wiki tutorial zodb + traversal wiki tutorial really, need start productive pyramid here getting started after finishing application may distribute source distribution/archive (*.tar.gz) distribute application install application on ubuntu pip , pass path local source archive. need install package development mode either using pip or setuptools . below find --editable option pip: $ pip install --help usage: pip install [options] <requirement specifier> ... pip install [options] -r <requirements file> ... pip install [options] [-e] <vcs proje

version control - What is the best Git workflow to use for an inexperienced team? -

i'm college student taking software development course have work in team develop finished product. i'm working in group 4 other people create crud web application using codeigniter. don't know source control, , none of them know how use git (which decided best vcs use). planning on using gui-based github client commit , push code. what best git workflow use in situation? thought giving each of them own personal branch work on, along dev branch testing changes , master production-ready code. after spending more time thinking it, think might not best idea. want them able keep local copy date possible while minimizing number of merge conflicts potentially occur. have ideas? perhaps use github flow simple work flow. https://guides.github.com/introduction/flow/ and original post on subject : http://scottchacon.com/2011/08/31/github-flow.html

javascript - Need help tracking download goals in SquareSpace using Google Analytics -

i'm trying track events when link clicked download mp3 file using google analytics. site hosted on squarespace. here code attempting record event data: $(document).ready(function(){ $('.download a').on('click', function (){ ga('send', 'event', 'audio', 'click', 'download'); }); }); the "logic" navigate div ("download") anchor when clicking before executing google analytics function. i'm pretty new google analytics , not javascript i'm doing wrong. appreciated.

c++ - How do I do this with switch instead of if esle? -

i taking first programming course , assignment redo previous program (this one) using switch statement. thought switch used compare single characters. the program receives string , counts numbers, letters, other characters, , total characters..... #include <iostream> using namespace std; int main() { char s[50]; int i; int total = 0; int letters = 0; int numbers = 0; int others = 0; cout << "enter continuous string of characters no blank spaces" << endl; cout << "(example: abc1234!@#$%)" << endl << endl; cout << "enter string: "; cin >> s; cout << endl; = 0; while (s[i] != 0) { if ((s[i] >= 'a' && s[i] <= 'z') || (s[i] >= 'a' && s[i] <= 'z')) letters++; else if ((s[i] >= '0' && s[i] <= '9')) numbers++;

jython - Finding length of list without using the 'len' function in python -

in high school assignment part of make function find average number in list of floating points. can't use len , such sum(numlist)/float(len(numlist)) isn't option me. i've spent hour researching , racking brain way find list length without using len function, , i've got nothing hoping either shown how or pointed in right direction. me stack overflow, hope. :) use loop add values list, , count them @ same time: def average(numlist): total = 0 count = 0 num in numlist: total += num count += 1 return total / count if might passed empty list, might want check first , either return predetermined value (e.g. 0 ), or raise more helpful exception zerodivisionerror you'll if don't checking. if you're using python 2 , list might integers, should either put from __future__ import division @ top of file, or convert 1 of total or count float before doing division (initializing 1 of them 0.0 work).

javascript - How to add extra info to copied web text -

some websites use javascript service tynt appends text copied content. if copy text site using , paste link original content @ bottom of text. tynt tracks happens. it's neat trick done. their script doing impressive - rather try manipulate clipboard (which older versions of ie lets them default , should turned off) manipulate actual selection. so when select block of text content added hidden <div> included in selection. when paste style ignored , link appears. this easy simple blocks of text, nightmare when consider selections possible across complex html in different browsers. i'm developing web application - don't want able track content copied , info contain contextual, rather link. tynt's service isn't appropriate in case. does know of open source javascript library (maybe jquery plug in or similar) provides similar functionality doesn't expose internal application data? there 2 main ways add info copied web text. 1. man

android - How do I programmatically launch the "Google Play Games Profile" Game Page -

Image
i want directly launch google play game page game programmatically when player hits button game screen: an example of page want launch is: https://drive.google.com/file/d/0b8xfkv7sp0jzdzjiwwpfwg8znhoydnmzwkwzzvjwzdjuuxzr/view?usp=sharing any thoughts/suggestions on doing this? ps. i've taken random awesome game "badland" example :). hope that's okay! it has been while don't know if found answer have been working on same thing today , figured share solution. found no sources on online , ended decompiling app @ expects intents launch it. intent intent = new intent(); //clear activity button returns app intent.addflags(intent.flag_activity_clear_top); //manually specify package , activity name intent.setcomponent(new componentname("com.google.android.play.games", "com.google.android.gms.games.ui.destination.api.apiactivity")); //not needed default happens if don't specify it. intent.addcategory(intent.category_defaul

objective c - How to remove Notification in Settings in iOS -

Image
using parse service, implemented apple push notification service in app. link referred: https://parse.com/tutorials/push-notifications however, changed mind not use now. , then, deleted of codes, still remains notifications in settings. does know how delete if eternity? turn off app in settings , delete , reinstall app on the device.

html5 - how to set correct date format for user view in angularjs editable-date -

basically have editable-date field in angular app shown user like: mm/dd/yyyy when field not selected but want show user as: dd/mm/yyyy . set format display user when field not selected ? make custom directive require ngmodel , changes model view value. (this in case i'm working breeze entities example, , don't want change value or affect entitystate) if doesn't bother you, use moment format date how like. (moment powerful js library advanced format options)

asp.net mvc - .net MVC Odata endpoint works on POST, but 404s on GET -

my question should have simple answer, after hours of experimentation , googling, have nothing i'm here. i working .net mvc 5 odata 2.0. trying create new odata endpoint works on get. i've created few endpoints work post, can't seem 1 works get. relevant code webapiconfig.cs odataconventionmodelbuilder builder = new odataconventionmodelbuilder(); builder.entityset<review>("reviews"); builder.entityset<strategy>("strategies"); actionconfiguration reviewsinstrategy = builder.entity<strategy>().action("reviewsinstrategy"); reviewsinstrategy.returnscollectionfromentityset<review>("reviews"); config.routes.mapodataserviceroute("odata", "odata", builder.getedmmodel()); strategiescontroller.cs [enablequery] public iqueryable<review> reviewsinstrategy([fromodatauri] guid key){ strategy strategy = db.strategies.find(key); return strategy.reviews } now go fiddler ,

c# - vs forms , show hidden form on form load -

(.net 3.5 compact) have form hidden(b) . when open new form(a), want display hidden form(b) hidden. if create button on form(a) , on click event .show() , works fine . if add ff load event , forms not come front , stays hidden.also tried adding after initializecomponent(); form not come front. reg.frmscanner.show(); i have read minimize trick here , there no minimize on mobile device to in foreground use reg.frmscanner.topmost = true;

javascript - Unloading data from a modal -

i using bootstrap 3.3.2 . how remove data modal ? want modal appear fresh loaded first time. for example modal : <div class="modal fade" id="pass" tabindex="-1" role="dialog" aria-labelledby="mypass" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <h4 class="modal-title text-center" id="mypass">characteristics</h4> <div class="modal-body"> <form class='form-inline'> <div class='form-group'> <label for='playernumber_pass'>player number</label> <input type='text' class='form-control' id='playernumber_pass' name='playernumber_pass'/> <

javascript - In angular, generate dynamic html content with ng-repeat -

my question generating dynamic html content ng-repeat contains multiple ng-model instances stored in array. but syntax error {{ in ng-model . is possible somehow? <div class="col-xs-12 col-md-12 col-sm-12 col-lg-12" ng-repeat="(key, antecedente) in antecedentes" > <div class="form-group"> <label class="col-md-3">{{antecedente.name}}</label> <div class="col-md-1"> si&nbsp;<input ng-model="historia.antecedentes[{{key}}].seleccionado" type="radio" value="s"></div> <div class="col-md-1"> no&nbsp;<input ng-model="historia.antecedentes[{{key}}].seleccionado" type="radio" value="n"></div> <div class="col-md-2">observaciones </div> <div class="col-md-5"><input ng-model="historia.antecedentes[{{key}}].observa

php - 404 errer due to .htaccess file -

i have website. in website have 404 file not found errors per google webmaster, although files present. follow: http://firstcovers.net/http//firstcovers.net/ http://firstcovers.net/category/1/http//firstcovers.net/ http://firstcovers.net/category/8/4/http//firstcovers.net/ http://firstcovers.net/category/17/2/http//firstcovers.net/ http://firstcovers.net/category/20/2/http//firstcovers.net/ http://firstcovers.net/facebook-cover/1317/privacy.php http://firstcovers.net/facebook-cover/1317/terms.php http://firstcovers.net/facebook-cover/1286/privacy.php http://firstcovers.net/facebook-cover/338/terms.php the structure of .htaccess file follow: directoryindex index.html.var index.htm index.html index.shtml index.xhtml index.wml index.perl index.pl index.plx index.ppl index.cgi index.jsp index.js index.jp index.php4 index.php3 index.php index.phtml default.htm default.html home.htm index.php5 default.html default.htm home.html # use php5 single php.ini default #addhandler fcgid-sc

apache - How to monitor hadoop cluster using Ambari on centos 7 -

i have small hadoop cluster i.e 1 master , 3 slave nodes. have monitor cluster. have found can use ambari. centos 7 installed on machines. please provide complete details how can ?. have found ambari can used new cluster i.e have install new cluster. not work running cluster? at moment ambari not support centos 7, that's not going work. however, ambari not perform cluster monitoring on own. uses nagios purpose. nagios independent software project can setup independently. said it's kinda painful do.

mysql - Error 1064 when updating a table -

when updating table error: my table speech values: no speec check 1 45 0 and structure : 1 -no int(100) no none auto_increment browse distinct values change drop primary unique index fulltext 2- speec varchar(100) latin1_swedish_ci no none browse distinct values change drop primary unique index fulltext 3 - check int(100) no none browse distinct values change drop primary unique index fulltext when updating using command : update speech set check=1 no=1 i error: 1064 - have error in sql syntax; check manual corresponds mysql server version right syntax use near 'check=1 no=1' @ line 1 please me in issue check reserved, word http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html you need escape using backtics as update speech set `check`=1 no=1

sql server - Format of the initialization string does not conform to specification starting at index 0 - where is the error? -

this connection string entered on configure page in azure portal on azure website: server=tcp:ghywv7yvsd.database.windows.net,1433;database=abcd;user id=abcd@ghywv7yvsd;password=applejuice1;trusted_connection=false;encrypt=true;connection timeout=30; the connection string taken azure sql dashboard , changed user id , password fields. i first created on azure sql server with: create login abcd password='applejuice1' --on master database create user abcd login abcd --on abcd database exec sp_addrolemember 'db_owner','abcd' is error (see subject line) caused error in connection string or wrong setting of login/user on database? parts of stack trace: [argumentexception: format of initialization string not conform specification starting @ index 0.] system.data.common.dbconnectionoptions.getkeyvaluepair(string connectionstring, int32 currentposition, stringbuilder buffer, boolean useodbcrules, string& keynam

ios - Subviewing an XIB having Auto-layout -

Image
i have created xib , used autolayout. showing if check in preview pan. now tried load nib , add subview viewcontroller using following code: mynibview = [[nsbundle mainbundle]loadnibnamed:@"customnib" owner:self options:nil].lastobject; mynibview.translatesautoresizingmaskintoconstraints = no; [self.view mynibview]; this time scattering views shown in image below. i enable logging , checked frame of subview, frame of xib(subview) changed per view of uiviewcontroller subviews of xib didn't arranged that. 2015-03-21 14:38:13.527 [3015:77723] newsubview.frame before = {{0, 0}, {420, 613}} 2015-03-21 14:38:13.633 [3015:77723] containerview.bounds after = {{0, 0}, {320, 504}} 2015-03-21 14:38:13.634 [3015:77723] newsubview.frame after = {{0, 0}, {320, 504}} is there idea, how add xib subview retaining auto layout constraints work there in xib ? do not use mynibview.translatesautoresizingmaskintoconstraints = no; because remove constrains view

Redmine cannot find rails -

i trying migrate working redmine instance server , running problems. background: copied redmine directory , database new server , attempted install corresponding ruby , rails versions necessary. installed passenger apt-get install libapache2-mod-passenger bundle installed gems in redmine folder. now, when try load site, cannot load such file -- rails/all (loaderror) /srv/redmine/config/application.rb:3:in `require' /srv/redmine/config/application.rb:3:in `<top (required)>' /srv/redmine/config/environment.rb:2:in `require' /srv/redmine/config/environment.rb:2:in `<top (required)>' config.ru:3:in `require' config.ru:3:in `block in <main>' /srv/redmine/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/builder.rb:51:in `instance_eval' /srv/redmine/vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/builder.rb:51:in `initialize' config.ru:1:in `new' config.ru:1:in `<main>' /usr/share/passenger/hel

java - OSGi slf4j logging in Apache Sling/felix -

Image
i trying use slf4j logger in osgi bundle apache sling. when adding dependency , import tag pom.xml, bundle remains in resolved state. am missing? activator.class import org.slf4j.logger; import org.slf4j.loggerfactory; public class activator implements bundleactivator { ... private final logger log = loggerfactory.getlogger(sampleserviceimpl.class); ... pom.xml <import-package>org.slf4j</import-package> ... <dependency> <groupid>org.slf4j</groupid> <artifactid>slf4j-api</artifactid> <version>1.7.6</version> <scope>provided</scope> </dependency> edit if comment out logger instantiation , remove imports activator.class service stays in resolved state. once remove lines regarding slf4 in pom, works. i suppose <import-package>org.slf4j</import-package> statement prevents other required

java - Using one authentication with several web applications inside ear -

i have jsf-based web application uses form-authentication. security-domain set in jboss config. have jax-rs application contains rest-api, , want of methods accessed users whis authenticated in first app. took on jasig cas seems little heavy purpose , suppose there simpler solution , maybe guys me find it. in advance. what need can solved oauth . your backend (rest-api) require authenticated access api operations. in turn, front-end (jsf-based web app) need issue authenticated requests when communicating backend. achieved sending access tokens . although seem complex, useful take @ stormpath . have quite straightforward solution this. please take @ using stormpath api authentication . as summary, solution this: you use stormpath java sdk delegate user-management needs. in front, when user presses login button, front end send credentials securely backend-end thorough rest api. 2.1. way, stormpath enhances possibilities here. instead of having own login pa

getAttribute() inside an attachedListener function() returns 'null' (CKEditor 4.4.8) -

in plugin insert input elements of type "button". give elements data attributes. testing purposes called "data-test". further on attach listener recommended in answer . when click button function() called. inside function() need retrieve "data-test" attribute further actions. but getattribute('data-test') returns null. guess variable "linkelement" not hold customer attributes. any hints how reference data attributes correctly ? .... var buttonelement = '<input type="button" value="click me" data-test="test attribute"></input>'; var linkelement = ckeditor.dom.element.createfromhtml(buttonelement, editor.document); editor.insertelement(linkelement); // attach listener capture clicks editor.editable().attachlistener( linkelement, 'click', function() { var attribute = linkelement.getattribute('data-test');

c - regarding the relation of close() and read() -

int main() { char *msg="hello"; char buff[max]; int p[2]; pipe(p); int i,pid=fork(); if(pid>0){ //close(p[1]); read(p[0],buff, max); } else { printf("child exiting\n"); } } why above code end blocking ? if remove comment , place close(p[1]) then why code end ? once create pipe, gets 4 ends: a reading end p[0] in parent process a writing end p[1] in parent process a reading end p[0] in child process a writing end p[1] in child process unix not deliver eof reader unless both writing ends have been closed, because knows pipe still writeable. when child process exits, closes both ends of pipe on side. however, parent still has 1 writeable end open, reading pipe blocks instead of delivering eof parent. why unix manual instructs close unused ends of pipe right away: an application uses pipe(2) , fork(2) should use suitable close(2) calls close unnecessary duplica

cordova - Phonegap Fade In/Out choppy but using hardware acceleration sometime crashes Android -

problem on how make smooth fadein/out or related type css/javascript animation on phonegap app. i working on example have multiple div in page, when button clicked, part fadeout , part fadein etc. everything working great when test on browser , simulator. when package app, fadein/fade out becomes choppy. had same problem before idangerous swiper when dynamic height. forced hardware acceleration on it. crashes app. i wondering if force using transform3d apply specific div? or hardware acceleration forced on whole time? and if there other way make smooth fadein/out animation on phonegap app? thanks edit: tried test part supposed fadein/out alone nothing else, still choppy. then tried use transform3d(0,0,0) force hardware acceleration , still choppy. after trying few things, there nothing couldnt find out except using velocity.js http://julian.com/research/velocity/ it helps, enough. not sure if idea keep adding plugins, might cause more vulnerability structu

version control - git pull on staging server failing because of local changes -

on staging server have cron job git pull every 2 minutes, of times works fine, notice changes pushed repo not pulled, when inspect issue , run git pull manually error: error: local changes following files overwritten merge: {the file(s) had pushed repo} please, commit changes or stash them before can merge. i don't understand how these changes being considered "local changes". help? i mentioned before (" cannot pull rebase ") git rebase learned --autostash option (git 1.8.5+). you combine reset --hard in order make sure end result of scheduled git upll clean state: git config rebase.autostash true git pull -rebase git reset --hard that assumes have no local commit or work in progress on repo updated git pull (or erased reset --hard ) the autostash option ensure untracked state of working tree (for whatever reason) not blocking git pull . , reset --hard should make sure working tree clean.

input - This java program produce unwanted results -

i wrote program read input , print out. public class inverse { public static void main (string arg[]) throws ioexception { int input1 = system.in.read(); system.out.println(input1); string temp= integer.tostring(input1); system.out.println(temp); int[] numtoarray =new int[temp.length()]; system.out.println(temp.length()); (int i=0 ;i<temp.length(); i++) {numtoarray[i]= temp.charat(i); system.out.println(numtoarray[i]+"*"); } }} but here when write 123456 print 49. should print 123456. cause problem? 123456 integer, system.in.read() reads next byte input not read integer expected. use scanner#nextint() method read integer: scanner input = new scanner(system.in); int input1 = input.nextint(); your numtoarray array print bytes, not individual characters of integer parsed string. print characters, change type char[] : char[] numtoarray = new char[temp.length()]; system.out.println(temp.length()); (int = 0;

java - Hibernate search collection total -

say have resolution arraylist collection of refund objects, integer of amount . the end result want search on resolution s on sum of refund 's amount s, without use of hql. currently doing summing in mysql clumsy, maintains normalisation , can guarantee correct. a way thought of doing having refundtotal in resolution , field in database. have private 0 argument setter loops through refund , sums amount , stores when flush happens. setter run on database retrieval, correct when comes out of database. getter ensures correct whenever needed should needed. private setrefundtotal(){ arraylist<refund> refunds = getrefunds(); integer refundtotalsum = 0; for(refunds refund refund){ refundtotalsum+=refund.getamount(); } this.refundtotal = refundtotalsum; } public integer getrefundtotal(){ this.setrefundtotal(); return totalrefund; } if update refund in isolation of resolution however, have , save resolution refundtotal stays consisten