Posts

Showing posts from March, 2011

ruby on rails 4 - Field level permissions using CanCanCan or Pundit -

i using rails 4.1.14 cancancan 1.13.1 , defined granular permissions on model/record level. admins can manage articles users can edit articles authored. to prevent regular users editing specific fields make fields visible in rails_admin depending on role. visible bindings[:object].id == bindings[:view].current_user.roles.include? :admin end i using https://github.com/aasm/aasm gem , created custom actions user can move records new states. but want enable field level permissions depending on user's role / record. can't find docs on cancancan or https://github.com/elabs/pundit pages. does have experience that? you mean admin should allowed edit fields of record, editor allowed change fields x , y? yes, possible in pundit, since integrates strong parameters (which should using anyway). there's example in pundit readme (see: strong parameters). simplified example readme: # post_policy.rb def permitted_attributes if user.admin? [:title

python - Write to csv and I get error : _csv.Error: sequence expected -

please help. error when want write dict alllistinstance csv file. code: alllistinstance= {frozenset(['offense involving children']): [(95,), (96,), (35,), (80,), (100,)], frozenset(['battery', 'theft']): [(173, 209), (173, 224)]} open('test1.csv', 'wb') csv_file: key in alllistinstance.keys(): csv_writer = csv.writer(csv_file) csv_writer.writerow(len(alllistinstance[key])) y in range(len(key)): csv_writer.writerow([x[y] x in key]) csv_writer.writerow(x[y] x in alllistinstance[key]) output expected: 5 # len(alllistinstance["offense involving children"]) count of member offense involving children 95 96 35 80 100 2 # len(alllistinstance['battery','thief']) count of member battery thief 173 209 173 224 error: csv_writer.writerow(len(alllistinstance[key])) _csv.error: sequence expected solusion expected ouput: with open('test8.csv'

How to Install rsyslog v8.15 on Amazon Linux AMI -

im trying upgrade rsyslog 5.8.10 on amazon linux ami 2015.09 v8.15. here steps: vi /etc/yum.repos.d/rsyslog.repo [rsyslog_v8] name=adiscon centos-$releasever - local packages $basearch baseurl=http://rpms.adiscon.com/v8-stable/epel-7/$basearch enabled=0 gpgcheck=0 gpgkey=http://rpms.adiscon.com/rpm-gpg-key-adiscon protect=1 sudo yum install rsyslog --enablerepo=rsyslog_v8 --setopt=rsyslog_v8.priority=1 my error output: loaded plugins: priorities, update-motd, upgrade-helper amzn-main/latest | 2.1 kb 00:00 amzn-updates/latest | 2.3 kb 00:00 rsyslog_v8/x86_64

regex - How do I extract a range of lines from a text file using sed -n but in Python? -

say have file 10gb has 20,000 lines filled digits of pi. 123123 12312312 123123 123123 12312312 123123 how extract lines 10,000 20,000 using unix command sed -n ? i'd each line newline character export file using code below. so far, have following: com = "sed -n \' " + str(window[0]) + "," + str(window[1]) + "p\' " + "sample.txt" + ">" + "output.txt" os.system(com) but throwing concatenation errors. how should phrase command sed -n python in program below? inputfilename = "sample.txt" import itertools import linecache def sliding_window(window_size, step_size, last_window_start): in xrange(0, last_window_start, step_size): yield (i, + window_size) yield (last_window_start, total_pi_digits) def picrop(window_size, step_size): f = open(inputfilename, 'r') first_line = f.readline().split() total_pi_digits = int(first_line[0])

eclipse - Java: Proper organization of external libraries? -

so took coursera course had me work external libraries. 2 .jar files of weekly projects depended upon. i'm not entirely sure how eclipse compiles , runs files, , how links these external libraries -- proper way of organizing this? put copy of each .jar file in each project directory? is there another, cleaner way should organizing this? thanks -- as beginner programmer ok put in each project. consider ongoing work , @ time in future want upgrade new version of these external libraries. have copy everywhere. instead option store them in 1 place , add in classpath in each project. have 1 copy of it, better. now, if , when new version file names might change, still have change classpath of each project. but advise worry these , other such problems later. now, focus on programming related problems rather configuration.

language lawyer - C "observable behavior" in the context of UB "undefined behavior" -

(question prompted comments under answer are there race conditions in producer-consumer implementation? being asked here strictly c language perspective, without concurrency or multi-threading involved.) consider minimal code: #define bufsiz 10 char buf[bufsiz]; void f(int *pn) { buf[*pn]++; *pn = (*pn + 1) % bufsiz; } int main() { int n = 0; f(&n); return n; } question: c "as-if" rules allow compiler rewrite code follows? void f(int *pn) { int n = *pn; *pn = (*pn + 1) % bufsiz; buf[n]++; } on 1 hand, above not change observable behavior of program written. on other hand, f called invalid index, possibly translation unit: int g() { int n = -1001; f(&n); } in latter case, both variants of code invoke ub when accessing out-of-bounds array element. however, original code leave *pn @ value being passed f (= -1001) while rewritten code step ub-land after modifying *pn (to 0 ). would such difference coun

java - Filling a square with tiles -

Image
i have 2d tile game trying create brush sizes for. currently, code looks this: if (ismouseclicked0) { int grid_x = math.round(mousex / blocksize); int grid_y = math.round(mousey / blocksize); (int x = 0; x < brushsize; x++) { (int y = 0; y < brushsize; y++) { world.setat(grid_x, grid_y, b[inventoryselect]); grid_x += x; grid_y += y; } } } the setat() method looks this: public void setat(int x, int y, blocktype b) { if (x <= display.getwidth() / blocksize && y <= display.getheight() / blocksize) { blocks[x][y] = new baseblock(b, x * blocksize, y * blocksize); } render(); } this produces output: the tile above first tile on top left clicked mouse, can see next tile isn't rendering. i've been @ hours, i'm missing simple. help? edit: brush size 2 , should creating 4 tiles. blocksize 32 , it's how big blocks are. the problem : grid_x += x

android - Amazon ads integration not working -

i'm testing amazon ads first time , i'm following amazon quick start guide sample project given in sdk but still i'm getting these errors- logcat 01-16 12:37:11.359: e/amazonmobileads sisgeneratedidrequest webrequest httpurlconnectionwebrequest(6212): problem while creating output steam request body: aax-eu.amazon-adsystem.com/127.0.0.1:80 - connection refused 01-16 12:37:11.359: e/amazonmobileads adrequest webrequest httpurlconnectionwebrequest(6212): problem while creating output steam request body: aax-eu.amazon-adsystem.com/127.0.0.1:80 - connection refused 01-16 12:37:11.359: e/amazonmobileads adloader(6212): not contact ad server 01-16 12:37:11.367: w/simpleadsample(6212): ad failed load. code: network_error, message: not contact ad server here layout.xml - <?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:amazon="http://schemas.android.co

c - Why does some characters change? -

i'm programming c language in codeblocks gnu gcc compiler.i writing function create link list consisting token nodes.for example, below text file: main ( ) { int ; int b ; } the link list of tokens be main -> ( -> ) -> { -> int -> -> ; -> int -> b -> ; -> } for delimiter space character. decided make other link list called line . each line consisting successive tokens separated space finished ; character. example , @ same text file relevant tokens lines be: main ( ) { int ; -> int b ;-> } you see code below: //including related header files typedef struct token { char *tok; struct token *next; int tp; } token; typedef struct line { char *ls; struct line *next; int parent; } line; token *start; line *lstart; void addline (line * a); void showline (void); void setline (void); int main (void ) { int = 0; // next 4 lines allocates space start(pointer of type token) // , lstart(pointer

android - How to send string from one activity to another? -

so have string in activity2 string message = string.format( "current location \n longitude: %1$s \n latitude: %2$s", lat, lng); i want insert string text field in activity1. how can that? thank in advance. you can use intents, messages sent between activities. in intent can put sort of data, string, int, etc. in case, in activity2 , before going activity1 , store string message way : intent intent = new intent(activity2.this, activity1.class); intent.putextra("message", message); startactivity(intent); in activity1 , in oncreate() , can string message retrieving bundle (which contains messages sent calling activity) , call getstring() on : bundle bundle = getintent().getextras(); string message = bundle.getstring("message"); then can set text in textview : textview txtview = (textview) findviewbyid(r.id.your_resource_textview); txtview.settext(message); hope helps !

libreadline - readline: remapping \C-m (Ctrl+m) -

i want have custom binding \c-m in ~/.inputrc. however, moment replace can no longer enter commands. e.g., "\c-m": vi-forward-word the problem seems there exists default binding "\c-m": accept-line that not problem in appears other programs (the terminal?) send ^m (ctrl-m) indicate carriage return. in setup have urxvt tried xterm, behavior same (return no longer works once add "\c-m" vi-forward-word binding @ end of inputrc). now want changed, willing patch program/library involved. question is: should relevant pieces? checked readline source code not find indicating \c-m reused internally. similarly, checked urxvt cannot find mapping carriage return \c-m in code (which best guess happening cause behavior). interestingly there rxvt.7.pod containing kp_enter ^m esc o m and rxvt-unicode.termcap with ...:cr=^m:... however, both files seem documentation or @ least not installed. knowledge of terminfo files , involvement in overall

php - Autofill data gets overwritten by onchange event of javascript -

so facing annoying issue. have form empty field initially. user has option use default set of values choosing radio button 'yes' option. if user chooses use default set of values fill form fields default set of values using script. goes fine till now. the problem select drop-down not getting set default value. after debugging found out getting set on change event of js gets fired populating drop down dataset ajax response. how stop on-change event fired if user not clicked on drop down , changed something. <!doctype html> <html> <head> <title></title> </head> <body> <input type="radio" value="1" name="rdchoice"> yes! set default value <input type="radio" value="0" name="rdchoice"> no! have fill data <hr> first name : <input type="text" name="txtfirstname" id="txtfirstname"><br> last name : <

android - ANR's frameDelay(); -

getting anr's when framedelay(); being called. can on code , see going wrong stumped! p.s stackoverflow details needed silly input box error correction. public final class drawthread extends thread { private boolean mpause = false; private boolean mrun = true; @override public void run() { while (mrun) { framedelay(); canvas canvas = null; waitforbitmap(); try { while (mrun && mpause) { sleep(100); } canvas = surfaceholder.lockcanvas(null); if (canvas != null) { synchronized (surfaceholder) { if (mrun) { controller.draw(); canvas.drawcolor(color.ltgray); canvas.drawbitmap(mbitmap, panhelper.mrectsrc, panhelper.mrectdst, paint);

javascript - Syntax error: Unexpected number at Object.parse, PHP to AngularJS -

i have built contact form using angularjs frontend , php mail client sends email. want pass data php angular, telling angular whether or not email sent. however, when try that, "syntax error: unexpected number". my php: <?php require_once "../vendors/phpmailer-master/phpmailerautoload.php"; print_r($_post); $data = array(); $sender_name = isset($_post['sender_name']) ? $_post['sender_name'] : ''; $sender_email = isset($_post['sender_email']) ? $_post['sender_email'] : ''; $sender_tel = isset($_post['sender_tel']) ? $_post['sender_tel'] : ''; $sender_message = isset($_post['sender_message']) ? $_post['sender_message'] : ''; $mail = new phpmailer; //enable smtp debugging. $mail->smtpdebug = 3; //set phpmailer use smtp. $mail->issmtp(); //set smtp host nam

json - Creating a collection of nested resources in roar-rails -

i trying create new objects collection of nested resources. when post json, get: activerecord::associationtypemismatch: formlabel(#70306552439440) expected, got hash(#70306480154920) here's code: # form.rb class form < activerecord::base has_many :form_labels validates_presence_of :name end # form_label.rb class formlabel < activerecord::base belongs_to :form validates_presence_of :form validates_presence_of :text end # form_representer.rb module formrepresenter include roar::json property :id property :name collection :form_labels end # form_label_representer.rb module formlabelrepresenter include roar::json property :text end # form_controller.rb class formscontroller < applicationcontroller include roar::rails::controlleradditions def create form = form.new consume!(form) respond_with(form) end when debug, these params: 0> params => {"name"=>"address", "form_labels"=>[{

python - How to write in new line in a file? -

i need create program saves people's information e.g. name in text file depending on first letter of surname if surname starts k goes myfile1 . i need loop have done because it's unknown number of people want each person written in different line in text file there way this. the code @ bottom puts each separate information new line , don't want want each different person in new line. myfile1 = open("al.txt", "wt") myfile2 = open("mz.txt", "wt") mylistal = ([]) mylistmz = ([]) while 1: surname = input("enter surname name.") if surname[0] in ("a","b","c","d","e","f","g","h","i","j","k","l"): title = input("enter title.") mylistal.append(title); firstname = input("enter first name.") mylistal.append(firstname); mylistal.append(sur

javascript - jQuery scroll down pop up window page and not the main html page -

we have html page pop gets opened on button click. both html page , pop have scroll bar them. i want pop window scroll down on click of button inside pop up. i doing: $(window).scrolltop($('#suggestdetails').offset().top); the element #suggestdetails inside pop main html page scroll bar gets down on button click , not pop scroll bar. any idea how move down scroll bar/screen inside pop up? you need scroll popup/modal, not window. $('#yourmodal-id').scrolltop($('#suggestdetails').offset().top);

android - how to remove duplicate Element from Arraylist in java -

{ "744101", "744101","744101", "744102",744102","744102","744102","744102","744103","744103"} list<string> list2=new new arraylist<string>(); // arrays.sort(iarr); for(int k=0;k<iarr.length;k++) { list2.add(string.valueof(iarr[k])); } list li2 = new array list(new hashset(list2)); i'm unable result while trying sort array list. please correct me. the treeset both sorts elements , removes duplicates. string[] array = { "744101", "744101","744101", "744102","744102","744102","744102","744102","744103","744103"}; list<string> list = new arraylist<>(new treeset<>(arrays.aslist(array))); list.foreach((element)->{

python - Install lxml on Centos 7 - error: command 'gcc' failed with exit status 4 -

i'm using python 3.4 in virtual environment: (af)[root@domain backend]# pip --version pip 7.1.0 /home/af/af-stage/backend/.ves/af/lib/python3.4/site-packages (python 3.4) installation of lxml failed "error: command 'gcc' failed exit status 4": (af)[root@domain backend]# pip install lxml using pip version 7.1.0, version 7.1.2 available. should consider upgrading via 'pip install --upgrade pip' command. collecting lxml using cached lxml-3.5.0.tar.gz building wheels collected packages: lxml running setup.py bdist_wheel lxml complete output command /home/af/af-stage/backend/.ves/af/bin/python3.4 -c "import setuptools;__file__='/tmp/pip-build-tlogtyk2/lxml/setup.py';exec(compile(open(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" bdist_wheel -d /tmp/tmpod9hcw0ypip-wheel-: building lxml version 3.5.0. building without cython. using build configuration of libxslt 1.1.28 building agai

c link() function failing to execute -

i have question regarding link() function in c. using create hard link file on unix system. first, in home direcotry (the same problem happens in other directories) create test directory , cd it. inside execute program creates hard link file in .. directory (the parent directory). reason failes errno set on 2 (enoent). file exists -> name ../exercise3.c (the name exercise3.c resides in .. directory) , reason creating links files ../scr.c , others works, cant create link file. has same privilages other text files in directory. have tryed debbuging deleting file , recreating (did not work), printing name of file in program see if code fail somehow, not. strange thing if stay in parent directory can create link file, go test directory created , try create link (the file in question) path name ../exercise3.c fails. again ../scr.c creates link. int status = link(dest, name); if (status == 0) { exitstatus = 0; } else { exitstatus = errno; printf("failed: %s\n&qu

javascript - protractor unknown error, removing attribute from DOM -

im new protractor , trying remove attribute dom getting "unknown error", im not sure problem im having simple html custom directive.i trying remove test cases pass: <input type="text" name="rptdate" input-date placeholder="dd-mm-yyyy" data-ng-model="newpatreports.reportdate" /> commands ran are: browser.executescript( 'document.getelementsbyname("rptdate").removeattribute("input-date")' ); browser.driver.findelement(protractor.by.name('rptdate')).removeattr("input-date"); browser.executescript('document.queryselector("input[name='rptdate']").removeattribute("input-date");'); but none of them helped. locate element protractor , pass web element script: var elm = element(by.name("rptdate")); browser.executescript('arguments[0].removeattribute("input-date");', elm.getwebelement());

Pointers, Lists and Vectors attribute names necessary in the UML diagram? -

Image
i have short question: should name attributes of types list, arrays, vectors or pointers objects (not primitive type) in uml diagram or association/aggregation/composition arrows enough? example: of these diagrams correct? or in uml, second diagram correct if wrote property names @ far ends of associations. while uml properties allowed unnamed, not practice. use association ends indicate why relationship exists. more 1 association must exist between 1 pair of classes, different reasons. how tell them apart? the first diagram shows 2 properties of each type. 1 named , (at end of each association) unnamed. incorrect.

performance - Spatial index slowed down Query mysql -

hello have a question. i have table time index. select statement : select count(*) sometable time between @starttime , @endtime , st_intersects(location,@somepolygon); this query takes 60 seconds run. table contains more 50 million rows think okay. if add location , index query takes 90 seconds run. why slowing down ? instead of speeding ? //update hello 4 feedback. explain index id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | 1 | simple | q1_geo | null | range | ort, zeit | zeit | 5 | null | 6454092 | 100.00 | using index condition; using and without id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | 1 | simple | q1_geo | null | range | zeit | zeit | 5 | null | 6454092 | 100.00 | using index condition; using //update version : '5.7.5-m15' engien : myisam tab

IronMQ push queue subscribers as Heroku workers -

ironmq supports push queues , example heroku push queue subscriber implemented web dyno. feels awkward, because need single heroku project use web dynos serve web requests, , worker dynos process time-consuming needs. that's how heroku designed. the ironmq api indicates push queue subscriber should accessible via publicly-accessible url ; that's why web dynos necessary. is there (clean) way ironmq push queues publishers , subscribers within single heroku project? is there queue service support (even long-polling subscribers work)? if wanted use ironmq non-web-accessible server, best advice use pull queues. start worker dyno, , have pull down messages available every x seconds. 10 million requests free, you're using 26% of free quota if check messages every second. if still wanted push queues , had tcp port listening on worker dyno, use push queues , have each message start worker on ironworker translates message tcp connection instead of http connect

python - Why do I always run into EOF error? -

why run eof error simplest input. tried code , returned eof error: var = raw_input("please enter something: ") print "you entered", var what doing wrong? tried in several online ide codechef , ideone , gives same eof error... standard input empty on ideone, have provide input before run program. if want run program interactively, online interpreter ( repl.it that).

java - Why I can't access array element? -

i have class named "soldier" , have class named "army" containing array of soldier class objects. army class defined this: public class army { array<soldier> army; then, in army class constructor i'm creating soldier objects array this: public army(){ army = new array<soldier>(20); // here } so far iterating thru army array this: for (soldier soldier : army) { // soldier object } and worked well, when wanted nested iteration way (one loop inside one) messed - inner loop destroying outer loop iterator index. so, want "manual" iteration, simple loop , looks this: for (int i=0; i< army.army.size; i++) { soldier soldier = army.army.items[i]; but i'm getting run time error (exception): exception in thread "lwjgl application" com.badlogic.gdx.utils.gdxruntimeexception: java.lang.classcastexception: [ljava.lang.object; cannot cast [lcom.mgsoft.soldier; can please explain me what's goin

sql - How to restore table from dump to database? -

i create table dump using pg_dump: pg_dump -h server1 -u postgres -t np_points gisurfo > d:\np_point.sql after go in psql , says: -f d:\np_point.sql but list of standart postgresql tables. next try exequte np_point.sql in pgadmin , error: error: syntax error (near: "1") line 78: 1 Сухово 75244822005 75644000 Челябинская обл. Нязепетровски... its snippet of sql error: copy np_point (gid, full_name, okato, oktmo, obl_name, region_nam, the_geom) stdin; 1 Сухово 75244822005 75644000 Челябинская обл. Нязепетровский район 0101000020e6100000312a7936bd9f4d402a3c580de9ff4b40 how can restore table sql file? update postgresql 8.4 and first part of sql file. postgresql database dump set statement_timeout = 0; set client_encoding = 'utf8'; set standard_conforming_strings = off; set check_function_bodies = false; set client_min_messages = warning; set escape_string_warning = off; set search_path = public, pg_catalog; set default_tab

jquery - How to change a portion of Body background-color on mousemove? -

i want similar paint, when color page on mouse moving. did first : <script> $(document).mousemove(function(event){ var cordx = event.pagex; var cordy = event.pagey; $("<div></div>").addclass("circle").appendto("body").css({'top':cordy,'left':cordx}); }) </script> https://jsfiddle.net/4o1xkp3d/1/ but spamming body many <div> not eficient method. think can achieve same result if color portion of pixels on body background when move mouse cursour.of course, @ moment don't know how continuously change body background-color couple of pixel size on specific position relative mouse cursour. ideas?

centos - Magento Cron Job Fatal Error -

i using centos server magento website. somehow magento cron jobs not running, have checked using " crontab -l " command verify whether there cron configure or not, found nothing, have configured crontab using "crontab -e" command , enter magento cron.php path in crontab. ** error message e_error: allowed memory size of 134217728 bytes exhausted (tried allocate 32 bytes) stack trace …ement::fetchall called @ /var/www/vhosts/syspro/lib/zend/db/statement/ pdo.php (290) …do::fetchall called @ /var/www/vhosts/syspro/lib/zend/db/adapter/ abstract.php (735) …/www/vhosts/syspro/app/code/core/mage/eav/model/entity/collection/ abstract.php (1111) …vhosts/syspro/app/code/core/mage/catalog/model/resource/product/ collection.php (480) …/www/vhosts/syspro/app/code/core/mage/eav/model/entity/collection/ abstract.php (874) …abstract::load called @ /var/www/vhosts/syspro/lib/varien/data/ collection.php (741) …vhosts/syspro/app/code/core/mage/catalog/model/resource/product/ c

python - Why is it not writing a new line with every result? -

im trying write results text file, i've got write text file i'm trying write new line can add result, while true: results = read_temp() f = open('results.txt','w') f.truncate() f.write(str(results) + '\n') f.write('\n') f.close() print results time.sleep(1) but i'm getting @ moment 1 result in text file (20.0, 68.0) this result (20.0, 68.0) is print results or preview in e.g. notepad output file ? remember differents of new line unix/windows in files(!) and why truncate in loop ?

javascript - Webpack gzip compressed bundle not being served, the uncompressed bundle is -

i trying out webpack first time. i've been using gulp browserify time , pretty comfortable it. @ point, i'm testing out couple of webpack plugins. namely compression-webpack-plugin. i've never used compression before, bare me if i'm making noob mistake. below webpack.config.js. result main.js, main.js.gz, main.css , index.html. main.js injected index.html, if open index.html in browser, serves uncompressed main.js, not compressed main.js.gz. had read wouldn't need include .gz extension in script tag, , html-webpack-plugin doesn't include it, figured things working correctly, yet uncompressed main.js served, rather compressed one. var path = require('path'); var extracttextplugin = require('extract-text-webpack-plugin'); var htmlwebpackplugin = require('html-webpack-plugin'); var compressionplugin = require('compression-webpack-plugin'); module.exports = { entry: './app/scripts/main.js', output: { pa

Login users at the same time problemes in signalr -

im working on social network asp.net , signalr . have simple login page, if finds user in database creates application variable , redirect user profile page , in page invoke connect method declared in hub class , method takes userid in session , give frind list of user . works great when 2 or many users loged in @ different time. thing is, when 2 or several users logged in @ same time , connect method declared in hub takes last user id stored in application variable , give friend list of last user id , send user connected . i can't find correct approach. thanks in advance help. loggin page code : protected void btn_login_click(object sender, eventargs e) { tbl_user user = new tbl_user(); user = fonctioncommun.login(txt_username.text , txt_password.text); if (user != null) { application["userid"] = user.userid.tostring(); response.redirect

formula - How to use array and OR and AND in google spread sheet -

i've using formula in google sheet answer. somewhere logic wrong please suggest. logic applied seams wrong =arrayformula(sum(if(or(t:t="a",u:u="y"),1,0))) b x y x y b x answer should 2. pls wrong ? there ambiguity in question. in formula using, there or . either first column should have 'a' or second 1 should have 'y'. then, shouldn't answer 3? the formula looking in case is: =arrayformula(sum(if(add(if(a:a="a",true,false),if(b:b="y",true,false))>0,1,0))) but if looking and, formula is: =arrayformula(sum(if(multiply(if(a:a="a",true,false),if(b:b="y",true,false))>0,1,0))) the basic concept here in array expression, simple boolean should replaced add or multiply depending on if or or and

javascript - Hash link disables relative link in HTML -

i'm building webapp one-page webapp link part of app this: <a href="#internet"></a> this possible because used javascript contains animations , different stuff, problem somehow, method disables possibility link this: <a href="internet/index.html"></a> how can have both links, without disabling hash links? edit: honest dont know part of js causing behaviour because took template, here js: https://github.com/gomobile/template-list-view/blob/master/www/lib/appframework/appframework.ui.min.js i believe have code this $('a').on('click', function(e) { e.preventdefault(); }); you need have if if ($(this).attr('href').indexof('#') == 0) { e.preventdefault(); } or better change selector to: $("a[href^=#]").on('click', function(e) { e.preventdefault(); // animation here. }); this code apply anchor elements have h

php - How AsyncTask implement, in this code to refresh? -

the following code extract android mysql reading json data php how can do every 10 seconds , listview refreshed, app consulted database running php reread json code generated every 10 seconds, in advance or suggestions here's code: public class vera extends actionbaractivity { string myjson; private static final string tag_results="result"; private static final string tag_id = "id"; private static final string tag_name = "nombre"; private static final string tag_add ="telefono"; jsonarray peoples = null; arraylist<hashmap<string, string>> personlist; listview list; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); list = (listview) findviewbyid(r.id.listview); personlist = new arraylist<hashmap<string, string>>(); getdata(); } // metod show list protected void showlist(){ try { jsonobje

mysql string to date -

how can convert string/varchar '12-mar-2013' date 2013-03-12? i tried select str_to_date('12-mar-2013','%y-%m-%d'); select date_format('12-mar-2013','%y-%m-%d'); but both return null. my current database version 5.5.7-rc. use str_to_date . try select str_to_date('12-mar-2013','%d-%m-%y'); -> 2013-03-12

angularjs - How to convert this code from angular1 to angular2 -

there, want use ng-class="{active: isopen()}" in angular 2, don't know ,how convert code angular1 angular2, 1 me? thank much. code there: http://www.theme-guys.com/materialism/angular/#/apps/todo app.directive('menutoggle', ['$location', function($location) { return { restrict: 'a', transclude: true, replace: true, scope: { name: '@', icon: '@' }, templateurl: 'assets/tpl/directives/menu-toggle.html', link: function(scope, element, attrs) { icon = attrs.icon; if ( icon ) { element.children().first().prepend('<i class="' + icon + '"></i>&nbsp;'); } element.children().first().on('click', function(e) { e.preventdefault(); link = angular.element(e.currenttarget); if( link.hasclass('active') ) { link.removeclass('active');

image - Transforming raw pixel using rescale slope and rescale intercept in DIcom -

i used solution in post window width , center calculation of dicom image transform raw pixel, works of images, faced problem images. images having pixel value "24", rescale slope "1.0" , rescale intercept "-1024". when applied solution mentioned above new pixel value in negative(-1000). i can't find value new pixel value in lookup table created using window level , window width because table having positive values (0 65536). please me solve problem. you dealing ct images. rescaleintercept tag cts set -1024. negative -1000 value obtain makes perfect sense, corresponds air in hounsfield units (as anders said). if want visualize image, have apply transfer function map hu scale rgb instance.