Posts

Showing posts from July, 2015

responsive design - Using Jquery Cycle2 can I define a different slide effect for mobile? -

i have nice responsive slideshow going, using nice jquery cycle2 plugin. http://jquery.malsup.com/cycle2/ now, in case of desktop use, use subtle fade effect. setting these attributes on container div: <div class="cycle-slideshow" data-cycle-slides=".slide" data-cycle-swipe="true" data-cycle-pause-on-hover="true" data-cycle-auto-height="container" data-cycle-fx="fade"> but on mobile devices, since slider swipe-enabled, use scrollhorz (horizontally scrolling), since makes better sense when swiping. is possible? here's link api reference: http://jquery.malsup.com/cycle2/api/ thanks in advance. since html tag data-cycle-fx should set before initializing jquery cycle, , using php, looked determining user device server side. i've found $_server['http_user_agent'] reliable (i've heard it's not 100% foolproof, in case that's not problem). i created function, example here

pygame - Python access variable -

im new python , im trying pygame dont know how should this.. def addrect(x, y, width, height, color, surface): rect = pygame.rect(x, y, width, height) pygame.draw.rect(surface, color, rect) pygame.display.flip() thats creating rectangles question how should access ractangles create ? im trying . r1 = addrect(20, 40, 200, 200, (61, 61, 61), screen) but when try move using r1.move(10,10) i error r1.move(10,10) attributeerror: 'nonetype' object has no attribute 'move' how should access ? thanks- python functions have default return value of none . since, don't have return statement in function, returns none not have attribute move() . from the python docs in fact, functions without return statement return value, albeit rather boring one. value called none (it’s built-in name). >>> def testfunc(num): num += 2 >>> print testfunc(4) none you need add return statement return rect

Rails 4 and Leaflet: assets/images not found? -

i having problem should not problem. reason images have in app/assets/images not accessable. when request them 404. ./log/development.log:started "/assets/images/marker-shadow.png" 127.0.0.1 @ 2013-07-20 22:02:38 -0400 ./log/development.log:actioncontroller::routingerror (no route matches [get] "/assets/images/marker-shadow.png"): mike@sleepycat:~/projects/myapp$ ls app/assets/images/ marker-icon-2x.png marker-icon.png marker-shadow.png this should braindead easy fix... restarting server @ most. have restarted server, have checked file permissions make sure files have sane permissions on them... , still 404's when load page. what missing here? using rails 4. just image helper : image_path('marker-shadow.png') the path generated rails "/assets/marker-shadow.png" without 'images' folder.

hibernate - Tomcat connection pool fails, but nothing in log -

my java application running on tomcat 6 has problem caused following exception. uses hibernate , tomcat connection pooling. read problem connection pool, not database itself. right? to debug problem, configured jdbc connection this: <resource name="jdbc/mssqlrepositorycfl" auth="container" type="javax.sql.datasource" maxactive="50" maxidle="5" maxwait="10000" username="updatecfl" password="" validationquery="select 1" defaulttransactionisolation="read_committed" testonborrow="true" removeabandoned="true" removeabandonedtimeout="60" logabandoned="true" driverclassname="net.sourceforge.jtds.jdbc.driver" url="jdbc:jtds:sqlserver://some.server.cz:1433/repository

javascript - Trying to switch 0 for 1 in the end of the function but it doesnt work -

i having problem witht code. in end of function trying switch 1 0 or 0 1; this button should after each click change words hello or stop clicking me; big in advance function mediadropdown() { var hello="hello"; var stopclicking="stop clicking me"; var notclicked=1; if(notclicked < 1) { document.getelementbyid("mediaarea").innerhtml=hello; } if(notclicked > 0) { document.getelementbyid("mediaarea").innerhtml=stopclicking; } changepolarity(); } function changepolarity() { if(notclicked<1) { notclicked=1; } if(notclicked>0) { notclicked=0; } } the notclicked variable non-persistent; every time run mediadropdown function being redefined , set 1 see text "stop clicking". move outside of function retains value. var notclicked=1; function mediadr

python - New column based on conditional selection from the values of 2 other columns in a Pandas DataFrame -

i've got dataframe contains stock values. it looks this: >>>data open high low close volume adj close date 2013-07-08 76.91 77.81 76.85 77.04 5106200 77.04 when try make conditional new column following if statement: data['test'] =data['close'] if data['close'] > data['open'] else data['open'] i following error: traceback (most recent call last): file "<pyshell#116>", line 1, in <module> data[1]['test'] =data[1]['close'] if data[1]['close'] > data[1]['open'] else data[1]['open'] valueerror: truth value of array more 1 element ambiguous. use a.any() or a.all() i used a.all() : data[1]['test'] =data[1]['close'] if all(data[1]['close'] > data[1]['open']) else data[1]['open'] the result entire ['open'] column selected. didn't

package opencv was not found in the pkg-config search path for centos -

when go command: pkg-config --cflags opencv i following message: package opencv not found in pkg-config search path. perhaps should add directory containing `opencv.pc' pkg_config_path environment variable no package 'opencv' found i'm on cent os 6, have found solution linux ubuntu on internet , here on stack not cent os i tried under opencv specifications with pkg_config_path=/usr/share/opencv/lib/pkgconfig:${pkg_config_path} export pkg_config_path still doesn't work. how can sure opencv installed in directory, used whereis opencv , triggered me /usr/share/ hi first of use 'synaptic package manager'. need goto ubuntu software center , search synaptic package manager.. beauty of packages need available here. second automatically configures paths. install search opencv packages on there if found package green box installed else package not in right place need reinstall package manager time. if installed can only, need fill opencv_d

css3 - CSS transitions, moves by itself -

the div moves itself, movement don't want , didn't code. here problem: i'm using css transitions (want move background image): .mobile{ background: url(../img/galaxy.png) no-repeat 70px 32px; height: 480px; margin-top: -90px; margin-bottom: -70px; position: relative; } .mobile.animate { -webkit-transition: background-position 1s linear; -moz-transition: background-position 1s linear; -o-transition: background-position 1s linear; -ms-transition: background-position 1s linear; } .mobile:hover { background-position: 70px 20px; } it works, when hover background moves want, but, before hovering, on page load, div moves right , bottom, 20 pixels (why?) there solution worked, without sense, don't want that. if put following code inside html , tags works, without self moving: .mobile{ background: url(../img/galaxy.png) no-repeat 70px 32px; height: 480px; margin-top: -90px; margin-bottom: -70px; position: relative; } also if put co

java - Will new return the named function constructor instance-? -

var foo = function () { return new moo(); } var moo = function () { return this; } if execute statement new foo() will instance of moo? seems @ both same time obvious , non-intuitive. functionally, should happen, @ same time not-expected if didn't know internals. edit: realized seems unintuitive b.c. in java constructors can not return anything. this similar constructor pattern jquery uses. yes instance of moo. non-intuitiveness because of fact can return other object in javascvipt constructor.this possible because functions in fact objects in js. in languages java , c# that's not possible, constructor returns object constructor belongs to. can cannot call contructors without new keyword in such languages. not returning constructor same thins return this; in js thing(assuming it's used constructor) adds little confusion.

ruby - Rails Join Table with Model Assoc -

i have model relies on associations of 2 other models so: class inventoryitem < activerecord::base attr_accessible :vendor_id, :price, :upc has_many :items belongs_to :vendor end my question this: if have these associations in join model, need specify these associations again in migration create inventory_items table in includes attributes :items , :vendor? here current migration (hasn't run yet) create table: class createinventoryitems < activerecord::migration def change create_table :inventory_items |t| t.integer :upc t.decimal :price t.integer :vendor_id end end end browsing sqlit3 db leads me believe need somehow. best way that? i'm newish ror, feedback welcome , appreciated. your models need know associations, migrations don't care associations. long have foreign keys in child model, that's need in migration set associations on database level. with rails, idea little possible on database level, , as

python - How create valueless column In Cassandra By CQLEngine -

i have question how can create valueless column in cassandra cqlengine. mean want store information in column name instead of column value purpose. in cqlengine should define column name before run project in model file. help. what asking traditionally accomplished using thrift api , wide rows, defining own column names. not how cql3 works. if want work way, can use pycassa, or can create columns compound keys. for example, cql3: create table ratings ( user_id uuid, item_id uuid, rating int, primary key (user_id, item_id)); you'd create wide row, user_id key, , columns have item_id, , rating value. compound primary keys, rows transposed columns. you might want read this: http://brianoneill.blogspot.com/2012/09/composite-keys-connecting-dots-between.html

How to create an object attribute from polymorphic type in scala -

i trying create object store instances object created , avoid re-load. tried create mutable map on object store it, compilation error. this code: class bar class foobar extends bar object foo { val loaded = scala.collection.mutable.map[string, bar]() def apply[t <: bar](implicit m: manifest[t]): t = { val classname = m.tostring() if (loaded.contains(classname)) { return loaded(classname) } val instance = m.runtimeclass.newinstance().asinstanceof[t] loaded(classname) = instance instance } } but when try compile error: error: type mismatch; found : bar required: t return loaded(classname) there way create map dynamically , pass t? or solve differently? your problem in returning loaded(classname) of type bar , not t required function type signature. unfortunately, cannot encode such dependence between types of map keys , values, @ least not standard map collection. have perfor

c++ - Serial port not reading complete transmission -

i attempted modify teunis van beelen's rs232 library, polling event driven , non-overlapped suit project. rs232 library i expect receive blocks of data (roughly 100 200 chars) every 200ms. problem having received data inconsistent, cut off @ random points, , incomplete. i readfile() return after reading 1 whole block of data.( or effect) i feel problem time out settings, because altering figures different results, cant right, best result far has been set time out values 0 , let readfile() expect 150 bytes, way readfile() dose not return unless reads 150 chars, go out of sync after few transmissions, have no idea how data expect. these main changes polling function in teunis's code , besides time out settings, other settings unchanged: //using ev_rxchar flag notify thread byte arrived @ port dword dwerror = 0; //use setcommmask , waitcommevent see if byte has arrived @ port //setcommmask sets desired events cause notification. if(!setcommmask(cport[comport_num

corona - save a DisplayObjects to be reused between scenes -

how can save displayobjects reused between scenes? example: scene1 contains displayobject drawing. in scene:exitscene save storyboard.state.scene1.drawing then when scene in scene:enterscene do: drawing = storyboard.state.scene1.drawing self.view:insert(drawing) but error if drawing invalid. given store reference displayobject in variable, this no tested idea should work. fromscene: local displayobj=yourdisplayobject -- when time change scene, this: local options={ local params ={ dispobj = displayobj, }, } storyboard.gotoscene(targetscene, options) --- targetscene: scene:createscene(event) local params=event.params local displayobj=params.dispobj --and whatever want displayobj ... ... end doing in ways requires not nullify, or remove, display object in destroyscene of first scene.

Python Import Statement and Recursion- need function available in module namespace -

i have function foo() in main.py. in main.py, import create.py. there function in create.py needs foo() main. can't import main.py create.py because main.py errors out...i assume kind of race condition. how can make foo() available in create.py namespace? seems kind of inefficient make foo() module , imported both main.py , create.py 1 function. the easy answer move foo() foo.py , import there or move create.py , import there main.py - if there things in main.py needs move too. other option pass foo main create function parameter needed.

SQL-like window functions in PANDAS: Row Numbering in Python Pandas Dataframe -

i come sql background , use following data processing step frequently: partition table of data 1 or more fields for each partition, add rownumber each of rows ranks row 1 or more other fields, analyst specifies ascending or descending ex: df = pd.dataframe({'key1' : ['a','a','a','b','a'], 'data1' : [1,2,2,3,3], 'data2' : [1,10,2,3,30]}) df data1 data2 key1 0 1 1 1 2 10 2 2 2 3 3 3 b 4 3 30 i'm looking how pandas equivalent sql window function: rn = row_number() on (partition key1, key2 order data1 asc, data2 desc) data1 data2 key1 rn 0 1 1 1 1 2 10 2 2 2 2 3 3 3 3 b 1 4 3

sprite - cocos2d-iphone. Spritesheet depending on a screen resolution? -

cocos2d adds suffixes resources similar way "@2x" works usual ios apps. want place these pictures spritesheet. the problem default cocos2d spritesheet represented 1 png , 1 plist file sprite frames. so how force cocos2d engine apply these suffixes plist files when necessary? cocos2d suports suffixes plist files. if have "example-hd.plist" should use usual frame names inside (without "-hd" suffix)

javascript - Is there a more concise way to initialize empty multidimensional arrays? -

i've been trying find reasonably concise way set dimensions of empty multidimensional javascript array, no success far. first, tried initialize empty 10x10x10 array using var thearray = new array(10, 10 10) , instead, created 1-dimensional array 3 elements. i've figured out how initialize empty 10x10x10 array using nested for-loops, it's extremely tedious write array initializer way. initializing multidimensional arrays using nested for-loops can quite tedious: there more concise way set dimensions of empty multidimensional arrays in javascript (with arbitrarily many dimensions)? //initializing empty 10x10x10 array: var thearray = new array(); for(var = 0; < 10; a++){ thearray[a] = new array(); for(var b = 0; b < 10; b++){ thearray[a][b] = new array(); for(var c = 0; c < 10; c++){ thearray[a][b][c] = 10 } } } console.log(json.stringify(thearray)); adapted this answer : function createarray(length

c++ - Cast of pointer to vector of different types -

i have function requires pointer vector of type uint16_t . function fills vector data. have object should hold data in form of vector of type uint8_t . code looks following: void fill1(vector<uint16_t> *data); void fill2(vector<uint64_t> *data); class object { uint32_t data_depth; vector<uint8_t> data; } object object1; object1.data_depth = 16; fill1((vector<uint16_t>*) &object1.data); object object2; object2.data_depth = 64; fill2(vector<uint64_t>*) &object2.data); // somewhere later in code if (object1.data_depth == 16) vector<uin16_t> * v = (vector<uint16_t>)(&objec1.data); is save way of pointer conversion of vector of different types? you this: template <typename t> void fill(vector<unsigned char>& data) { assert(data.size() % sizeof(t) == 0); t* preinterpreted = reinterpret_cast<t*>(&data[0]); size_t count = data.size() / sizeof(t); // stuff array of

android - Can abstracted CountDownTimer class modify layout view objects linked to an activity? -

i computer hobbyist working on simple trivia game. in order increase difficulty of game, i'm adding countdown timer. initially, defined new countdown timer within gameactivity file, overriding ontick code swap in new imageview content each tick. worked fine long player waited timer finish. however, if player guessed answer before timer finishes, .cancel() method caused entire app crash. in attempt solve problem, created new class (gametimer.java) extends countdowntimer class. call instance of class appropriate locations within gameactivity file. works swimmingly when timer's ontick method counting down time system.out.println. but, when try to access imageview on layout, can see findviewbyid() not defined class (code appended). once layout inflated activity, possible external class access/change items on layout? understand findviewbyid method of android.app.activity class, , countdown timer extending java object. i'm appending code countdown timer, suspect not h

c# - Methods that return meaningful return values -

i work in c#, i've posted under c# although may question can answered in programming language. sometimes create method such log user website. times return boolean method, causes problems because boolean return value doesn't convey context. if error occurs whilst logging user in have no way of knowing caused error. here example of method use, change returns more 0 or 1. public bool logintotwitter(string username, string password) { // code log user in } the above method can return true or false. works because can call following: if(http.logintotwitter(username, password)) { // logged in } else { // not logged in } but problem have no way of knowing why user wasn't logged in. number of reasons exist such as: wrong username/password combination, suspended account, account requires users attention etc. using following method, , logic, isn't possible know this. what alternative approaches have? you create , return enum expected loginr

javascript - how to convert/transform an HTML table tbody (with rowspans) TO json? -

i have html table combined row td's, or how say, don't know how express myself (i not @ english), show it! table: <table border="1"> <thead> <tr> <th>line</th> <th>value1</th> <th>value2</th> </tr> </thead> <tbody> <tr> <td rowspan="2">1</td> <td>1.1</td> <td>1.2</td> </tr> <tr> <td>1.3</td> <td>1.4</td> </tr> <tr> <td rowspan="2">2</td> <td>2.1</td> <td>2.2</td> </tr> <tr> <td>2.3</td> <td>2.4</td> </tr> </tbody> </table> (you can check here )

parsing - How does an LALR(1) grammar differentiate between a variable and a function call? -

given following input: int x = y; and int x = y(); is there way lalr(1) grammar avoid shift/reduce conflict? shift/reduce conflict deciding reduce @ y or continue ( . (this assuming variable name can set of alphanumeric characters, , function call set of alphanumeric characters following parentheses.) it's not shift-reduce conflict unless possible identifier followed ( without being function call. that's not case, although in c-derived languages, there problem of differentiating cast expressions (type)(value) parenthesized-function calls (function)(argument) . if grammar not exhibit particular c wierdness, lalr (1) grammar can decide between shifting , reducing based on (1) token lookahead: if lookahead token ( , shifts identifier; otherwise, can reduce.

Dynamically changing top border line C# -

so i'm building multiplication table c# class. i've got code table complete, , works advertised. issue need dynamically changing top border, because table wide number user enters width digit, @ 5 character spacing. thoughts? static void main(string[] args) { int width, height; //int tablewidth; console.write("how wide want multiplication table? "); width = convert.toint32(console.readline()); console.write("how high want multiplication table? "); height = convert.toint32(console.readline()); console.write(" x|"); (int x = 1; x <= width; x++) console.write("{0, 5}", x); console.writeline(); (int row = 1; row <= height; row++) { console.write("{0, 5}|", row); (int column = 1; column <= height; ++column) { console.write("{0, 5}", row

java - Would anonymous Handler or Runnable create a memory leak? -

new handler().postdelayed(new runnable(){ @override public void run() { // stuff }}, 100); if call activity (oncreate or onresume or elsewhere) can cause memory leak? i've read new runnable() should static instance, true? yes. code may cause memory leak. for long anonymous class based on runnable in queue (100 milliseconds in example), keeps reference outer activity class. such memory leak not problem of course, depending on code inside run executed, may create bigger problems, crashing application when e.g. try show dialog after activity killed. in such situations see nice informational exceptions: illegalargumentexception: can not perform action after onsaveinstancestate or badtokenexception: unable add window - ... activity running?

eclipse - Why is android.R.menu_search giving me an error? -

i'm trying add search widget action bar , reason i'm getting "android.r.menu_search cannot resolved or not field". code i'm using @override public boolean oncreateoptionsmenu(menu menu) { // inflate menu; adds items action bar if present. getmenuinflater().inflate(r.menu.geolocation_search, menu); //get searchview , set searchable configuration searchmanager searchmanager = (searchmanager) getsystemservice(context.search_service); searchview searchview = (searchview) menu.finditem(android.r.layout.menu_search).getactionview(); //assumes current activity searchable activity searchview.setsearchableinfo(searchmanager.getsearchableinfo(getcomponentname())); //searchview.seticonifiedbydefault(false); return true; } the xml file <menu xmlns:android="http://schemas.android.com/apk/res/android" > <item android:id="@+id/action_settings"

When do jQuery submit functions link themselves to HTML forms? -

i have several forms in html page submission facilitated jquery functions. work well. however, having issues forms dynamically created. rather being submitted via jquery, being posted current html page. for instance, have table dynamically created php. table can updated enclosed in form. here's code generating table: //display table echo "<form id=\"updateusers\" method=\"post\">"; echo "<table> <thead> <tr> <th>user id </th> <th>first name</th> <th>last name</th> <th>current publisher</th> <th>user priveleges</th> </tr> </thead> <tbody> <tr>"; foreach($publishers $row) foreach($row

javascript - How to start with fabric.js -

i beginner study js. encounter issue start fabric.js needs help. <!doctype html> <html> <head> <title>fabric_test</title> <script type="text/javascript" src="all.js"></script> </head> <body> <canvas id="canvas" width="512" height="512" style="background-color: rgb(222, 222, 222)"> browser not support canvas tag! </canvas> <script type="text/javascript"> var canvas = new fabric.canvas('canvas'); // create rectangle object var rect = new fabric.rect({ left: 100, top: 100, fill: 'red', width: 20, height: 20 }); // "add" rectangle onto canvas canvas.add(rect); </script> </body> </html> my question is: why rectangle doesn't draw on canvas when open saved html f

html - php file upload not working returns empty result -

below html code.... <form enctype="multipart/form-data" action="some.php" method="post"> <label for="file">filename:</label> <input type="file" name="file" id="file"><br> <input type="submit" name="submit" value="submit"> </form> and some.php code... print_r($_files); print_r($_post); if ($_files["file"]["error"] > 0) { echo "error: " . $_files["file"]["error"] . "<br>"; } else { echo "upload: " . $_post["file"]["name"] . "<br>"; echo "type: " . $_files["file"]["type"] . "<br>"; echo "size: " . ($_files["file"]["size"] / 1024) . " kb&

Blackberry cfg file not found when device connects to computer and Desktop Manager open -

i storing config details test.cfg file in blackberry device. every time when start application, app check if test.cfg exists. if exists, loads configuration file , if not, app show config page, user can enter config details , proceed further. the above working fine except 1 scenario. when device plugged in system , open desktop manager , user opens application, directly shows configuration page if test.cfg exists in device. does know solution this? or idea why behaving this? my guess when connect device computer via usb cable, computer mounting sdcard external drive. when this, device lose access sdcard. needs this, because device software , desktop computer's software don't want simultaneously modifying same files. are saving test.cfg on sdcard? if so, might want save file device's internal storage instead, for example, in persistentstore . you turn off mass storage feature makes sdcard available pc, if prefer have media card available app. (if

php - How to combine jquery form validation with codeigniter? -

hello guys have little problem. problem want use jquery form validation plugin codeigniter. of can validate form using jquery validation rules. checking required fields, checking length of input, checking valid email, etc... checking availability of data in database got error. used remote function can't validate form. here's code hope can me. addnewitem.php <script type="text/javascript"> (function($,w,d){ var jquery4u = {}; jquery4u.util = { setupformvalidation: function() { $("#login-form").validate({ rules: { name: { required: true, remote: { type: 'post', url: <?php echo site_url('category_model/checkname'); ?>, data: { 'name': $('#name').val() },

java - How to find a reasonable size for a database connection pool and how to verify it? -

i wondering reasonable number connection.pool_size? aspects related? need know how test application once size defined it. my application going used @ least 100 users concurrently, has more 20 tables in database. database mysql , @ least 12 systems using application @ same time. please let me know if need know more. i have found following helps define connection pool size still not sure reasonable number is. hibernate's own connection pooling algorithm is, however, quite rudimentary. intended started , not intended use in production system, or performance testing. should use third party pool best performance , stability. replace hibernate.connection.pool_size property connection pool specific settings. turn off hibernate's internal pool. example, might use c3p0. connection.pool_size indicates maximum number of pooled connections. better keep @ logical count. depends on application , db how can handle. 10 reasonable count typic

k means - kmeans prediction using R -

km <- kmeans(iris,3) predict.kmeans <- function(km, data) {k <- nrow(km$centers) n <- nrow(data) d <- as.matrix(dist(rbind(km$centers, data)))[-(1:k),1:k] out <- apply(d, 1, which.min) return(out)} predict.kmeans(km,iris[1,]) # error:apply(d, 1, which.min) : dim(x) must have positive length i have problems simple code here,what's wrong it? kmeans works on numerical matrices only. @thelatemail pointed out, column 5 of iris isn't numeric. you use use cl_predict clue instead of predict.kmeans

java - Wait for radio change -

okay trying wait user select different selection , hit continue button before program reads his/her answer. currently program doesn't wait for user change answer , hit "choose" button. it doesnt change option text yet different road names currently have this: import java.awt.event.actionlistener; import java.awt.event.containerevent; import java.awt.event.containerlistener; import java.io.filewriter; import java.io.filereader; import java.io.filewriter; import java.io.ioexception; import java.util.scanner; import java.util.logging.level; import java.util.logging.logger; public class gamescreen extends javax.swing.jframe implements actionlistener, containerlistener { static string classstring; static int classint = 0; // 1- wiz 2-warr 3-arch 4-lock static int option; public static void classstore() throws ioexception { filewriter classchose = new filewriter("classchose.txt"); system.out.print(classint); system.out.prin