Posts

Showing posts from July, 2014

Linux Command: Find & Replace using regex not woking as expected -

i trying replace path in php files using regex command, isn't working expected! i want replace '/home/example/public_html $_server['document_root'] . ' i using below command in ssh: find /var/www/advertise/ -name '*.php' -type f -exec sed -i 's/\'\/home\/example\/public_html/\$\_server\[\'document\_root\'\]\ \.\ \'/g' {} \; when enter command , hit return, > sign follows like: > > > .. on keep hitting return execute command. where below command works (for replacing home/example/public_html var/www ): find /var/www/advertise/ -name '*.php' -type f -exec sed -i 's/home\/example\/public_html/var\/www/g' {} \; you're messing quotes. use separator other / don't need escape / you don't need escape in replacement since have ' in replacement, better use "s#..#..#" (i.e. double quotes). however, you'll need escape $ in replacement prevent shel

c++ - std::bind a member function to an instance at nullptr causing seemingly random this pointer -

i've tested following program on gcc-4.8 (via coliru) , on visual studio 2013 rc: #include <iostream> #include <functional> using namespace std; struct foo { void bar() { cout << "this = " << << endl; } }; int main() { try { foo *ptr = nullptr; function<void ()> fun = bind(&foo::bar, *ptr); fun(); } catch (const bad_function_call &e) { // never reached cout << "bad_function_call thrown: " << e.what() << endl; } cin.get(); } i understand i'm causing undefined behavior here dereferencing nullptr, don't understand output of code. in understanding should either cause bad_function_call (because should thrown when calling std::function, guessed) or @ least print "this = 0". it doesn't. output "this = " followed pointer not nullptr on both compilers tested. accessing causes segmentation faul

outlook vba - Extract AddressEntry object details for Exchange User -

is there way extract details in dialog box via vba? details dialog box http://i.msdn.microsoft.com/dynimg/ic84336.gif i need, content in e-mail address tab. i have go function of reading address-book: function get_mail(absender string) dim outapp outlook.application dim outti outlook.taskitem dim outrec outlook.recipient set outapp = new outlook.application set outti = outapp.createitem(3) outti.assign set outrec = outti.recipients.add(absender) outrec.resolve if outrec.resolved on error goto exit_function get_mail = outrec.addressentry.getexchangeuser.primarysmtpaddress end if exit_function: exit function set outapp = nothing set outti = nothing end function as far know can read out primary mail-address mail-addresses-tab; see else there ist delete part ".primarysmtpaddress", mahe dot , should list of other properties. i quite sure need reference on microsoft outlook 14.0 object library. the input "absender&quo

PHP: cannot pass single quoted string to mysqli query -

this question has answer here: mysql query not inserted when php variable contains single quotes 7 answers i fighting hours thing: $var=var; $result = "select column1, column2 $db column3 = '$var' "; the error is: have error in sql syntax; check manual corresponds mysql server version right syntax use near '\'var\'' @ line 1 names correct, works in mysql query. think tried possible quoting options, wrong? update: requested used escaping, error remains same $var=var; $var = $conn->real_escape_string($var); $result = "select column1, column2 {$db} column3 = '{$var}' "; there must $var = $mysqli->real_escape_string($var); $sql = "select column1, column2 {$db} column3 = '{$var}' "; instead of: $result = "select column1, column2 $db column3 = '$var' &qu

javascript - Temporarily animate input type text when hovering -

i want show contents of input type text if text wider current input width. when hover field, want text scroll left or similar, in order view hidden text. thank you. note: tell me if have add/change question's tags, please. i thought how , came with. on input hover i'm going take input value , put in div (or other element). width of div , compare width of input. if div wider input i'm going animate inputs text-indent difference of widths. $('input').hover(function(){ var temp = $('div').html($(this).val()).width(); if($(this).width() < temp){ $(this).animate({ textindent: $(this).width()-temp }, 100); } }); you can see full solution here: http://jsfiddle.net/taneleero/tb5c5/2/ should enough going.

ios - Issue migrating from AFNetworking 1.3 to AFNetworking 2.0 -

i'm trying migrate project afnetworking 1.3 afnetworking 2.0. in afnetworking 1.3 project have code: - (void) downloadjson:(id)sender { nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl urlwithstring:@"http://myserver/api/call?param1=string1&param2=string2"]]; afjsonrequestoperation *operation = [afjsonrequestoperation jsonrequestoperationwithrequest:request success:^(nsurlrequest *request, nshttpurlresponse *response, id json) { // handle success } failure:^(nsurlrequest *request, nshttpurlresponse *response, nserror *error, id json) { nslog(@"%ld", (long)[response statuscode]); nsdictionary *data = json; nsstring *errormsg = [data objectforkey:@"descriptiveerrormessage"]; // handle failure }]; [operation start]; } when client sends url not formatted or bad parameters server sends 400 error , includes json “descriptiveerrormessage” read in failure block. use

xml - Dropdownlist folder files php -

please, need help, how can load folder files uploader before in directory, dropdownlist on php??? now have code, doesnt work... <form action="" method="post"> <select name="seleccionarchivo"> <?php $dir = $_get["/repositorio"]; $files = scandir($dir); // prepare select box echo echo "<select name=\"files\">"; foreach ($files $file) { // return files if ( is_file($dir. $file) ) echo "<option value=\"$file\">$file</option>"; } echo "</select>"; ?> </select> <input type="submit" value="ir al examen"> </form> i try removing echo "" within php script. have select withi

java - Find insertion location -

i have sorted arraylist of integers. have new integer insert arraylist. new integer has inserted @ appropriate position keep arraylist in sorted order. i can add integer , sort using collections.sort(arraylist), arraylist big, sort taking time , need insert many times don't want end sorting multiple times eat away time. collections.sort() has o(nlogn) (uses mergesort). can have less time consuming, or can manually search position insert takes least time? time high priority. thanks in advance :) why not go through list , add element @ appropriate position. list sorted new list after insertion sorted , o(n) operation. there no need sort list on , on again. edit : - there 2 things here. 1 if need find location of element should inserted current list can binary search . inserting element in location require elements follow move 1 spot ahead create space inserted element think still more efficient inserting @ , sorting again.

c# - Unity 3D setting rotation and still use rigidbody -

i have been working on rts game , working on unit movement now. have finished path finding unit spacing, coming across big problem: when units (tanks in case) go on incline, stay parallel ground because setting rotation based on quaternion.lookrotation(distancetodestination); can rotation. is there way can rigidbody behave , still set unit's rotation? you have 2 simple-to-implement options. add enclosing empty playing role of rigidbody. allow lookat child item without affecting trajectory of main object. lock rotation of rigid body using constraints , manually override z axis normal of contact point; , y axis target's inverse vector. hope helps.

c# - Camera offest when following body -

Image
when moving object around, camera doesn't remain centered on object. i can't seem locate bug. please help. initial- `convertunits.todisplayunits(body.position)-(camera._screencenter- camera._cameraposition)` this returns zero. after movement changes. i using farseer physics engine 3.5 , moving body using force. body.applyforce(); this camera class- class camera { private static matrix _view; public static vector2 _cameraposition; public static vector2 _screencenter; private static float _zoom; private static float _rotation; public static void load(graphicsdevicemanager _graphics) { _view = matrix.identity; _cameraposition = vector2.zero; _screencenter = new vector2(_graphics.graphicsdevice.viewport.width / 2f, _graphics.graphicsdevice.viewport.height / 2f); _rotation = 0f; _zoom = 1.0f; } public static void handleinpu

rails 4 populate dropdown values from database -

i have dropdown in rails form: <%= f.select :lists, [["test1", 1], ["test2", 0]] %> this works fine how can make dynamic. (interacting model data) i have controller action containing @list = list.all how can populate id , name in combobox . i've been searching around, unclear it. can help> you can use options_from_collection_for_select . <% options = options_from_collection_for_select(@list, 'id', 'name') %> <%= f.select :all_val, options %>

java - Spring MVC passing object to JSP and back -

i've controller class initialize method adding list of string model , view. @requestmapping(value = "/my-site", method = requestmethod.get) public modelandview dostuff(httpservletrequest request){ modelandview modelandview = new modelandview("do-stuff"); ... list<string> list = arrays.aslist("abc", "cba"); modelandview.addobject("mylist", list); return modelandview; } question number 1: how access list in jsp file , use later in java script? trying like: var mylist = []; <c:foreach var="entry" items="'${mylist}'"> mylist.push("${entry}"); </c:foreach> but reason inside mylist object instead of having 2 elements: "abc" , "cba" have "[abc", " cba]" contains symbols. why? doing wrong , how fix issue? question number 2: have input button. <input type="button" id="executeb

android - css centering does not work in Phonegap -

i trying center image text underneath. works fine when display in chrome. works on emulator using opera mobile. when create phonegap app html/css files, image refuses center when run in android. here css: .centered { width: 100%; height: auto; position: fixed; top: 20%; text-align:center; } any ideas? thanks could issue position: fixed; ? try eg. .centered { width: 100%; height: auto; position: absolute; top: 20%; right: 0px; bottom: 20%; left: 0px; margin: auto; text-align: center; }

javascript - How to create a dynamic bar chart in d3.js? -

Image
here fiddle full app: http://jsfiddle.net/rg4eg/3/ here javascript: var hu = (function() { var data = [ {"time": "13:24:20", "level_1": "5553", "level_2": "4682", "level_3": "1005"}, {"time": "14:24:20", "level_1": "6553", "level_2": "5682", "level_3": "2005"}, {"time": "15:24:20", "level_1": "7553", "level_2": "6682", "level_3": "3005"}, {"time": "16:24:20", "level_1": "8553", "level_2": "7682", "level_3": "3131"}, {"time": "17:24:20", "level_1": "9953", "level_2": "5500", "level_3": "5005"}, {"time": "18:24:20&quo

asp.net mvc - HttpPost Action get empty Model on button Click -

scenario i have master/detail page master data on top , detail data loop in table format. i want id when user clicks on button. problem httppost action in called empty model. want saleid hiddenfield, not fields required my models // sales master model public class sales { [required] [display(name = "sale_id")] public long saleid { get; set; } [required] [display(name = "orderdate")] public datetime orderdate { get; set; } [required] [display(name = "name")] public string name { get; set; } } // detail model public class salesdetail { [required] [display(name = "sale_id")] public long saleid { get; set; } [required] [display(name = "pkg_dur")] public int pkgdur { get; set; } [required] [display(name = "m_name")] public string mname { get; set; } [display(name = "price")] public decimal price { get; set; } } // used displ

html - DIV height based on child image height adds few extra pixels at the bottom -

why parent div of image have few pixels @ bottom. how can remove pixels without hard code parent div height. http://jsfiddle.net/6x8dm/ html <div class="wrapper"> <div class="column"> <img src="http://www.lorempixel.com/200/200/" /> </div> </div> css .wrapper { width:200px; margin:0 auto; } .column { width:100%; background:#cc0000; } img { width:100%; } that space result of descender elements in fonts. can rid of in number of ways: add vertical-align:top rule image jsfiddle example add font-size:0; containing div jsfiddle example add display:block; image jsfiddle example

html - Multiple lines in a horizontally-floated list item -

i'm trying create navigation menu website, links aligned horizontally near top of page, , want each link have short description underneath. when user clicks on either main link text or description underneath, should take them right page. additionally, each menu item should have triangle-shaped icon bullet. this picture of i'm trying achieve. i can make list align horizontally when it's 1 line. breaks down when try add more. <nav id = "header-navigation"> <ul> <li> <a href="/"> home <span class = "subnavigation">foo!</span> </a> </li> <li> <a href="/contact"> contact <span class = "subnavigation">bar</span> </li> </ul> </nav><!-- header-navigation --> and in css: nav#header-navigation { margin-top: 160px; display: block; } nav#header-navigation

php - Setting Magento dropdown (select) value for product -

i have created quite big import script importing products csv magento. have 1 remaining issue resolve. i use dropdowns attributes. unfortunately can't set values attributes single product. did: created attribute set [php], added dropdown attribute values set [php], added new product in proper attribute set , tried set value attribute have created. i tried few methods, here one looking me: private function setoraddoptionattribute($product, $arg_attribute, $arg_value) { $attribute_model = mage::getmodel('eav/entity_attribute'); $attribute_options_model = mage::getmodel('eav/entity_attribute_source_table'); $attribute_code = $attribute_model->getidbycode('catalog_product', $arg_attribute); $attribute = $attribute_model->load($attribute_code); $attribute_options_model->setattribute($attribute); $options = $attribute_options_model->getalloptions(false); // determine if option exists $value_exists =

asp.net - change color of row selected in repeater with javascript -

i have repeater linkbutton. so, intend use javascript when click linkbutton, in addition able make data editing, can change color of selected row. but not know how this. can add onclientclick event? how can know line selected able change color? thank you... <asp:repeater id="repeater1" runat="server" > <headertemplate> <table> </headertemplate> <itemtemplate> <tr class="trclass" style="width:100px"> <td> <asp:linkbutton id="linkbtn1" oncommand="lbedit_command" commandargument='<%# eval("id")%>' commandname="edit" runat="server"> </asp:linkbutton> </td> </tr> </itemtemplate> <footertemplate> </table> </footertemplate> </asp:repeater> you can

math - Matrix Factorization In Matlab using Stochastic Gradient Descent -

Image
i have factorize matrix r[m n] 2 low-rank matrices (u[k m] , v[k*n]), predicting missing values of r u , v. the problem is, factorizing r can't use matlab factorization methods, have work on objective function minimizes sum-of-squared-errors enhancing factorization accuracy: details shown below: my question in post how minimize function f in matlab using stochastic gradient descent method decompose r u , v matrices. thanks help! finally figured out of this page :) explain approach in steps: create u[k*m] , v[k*n] , fill them arbitrarily compute derivatives objective function on ui , vj do gradient descent follows: while (your criteria satisfies(optimizing error function f)) { ui=ui+a(u'i); vj=vj+a(v'j); evaluate f using new values of ui , vj; } with minimum f , take u , v, compute transpose(u)*v , result estimated r ( a step size or learning rate )

javascript - Can I use select2 purely as a tokenizer, disabling the dropdown/search/match functionality? -

i have multiple instances of select2 elements in form, in 1 of them (which on hidden input) want tokenize input. i dont want dropdown ever show because shows "no matches found" , confuses users. need disable dropdown , use select2 tokenizer specific element. possible? (i know can out plugin want use plugin decorates tokens , removes icon , uniform other inputs use it) used approach described @paralife. found there option dropdowncss sets dropdown style. dropdowncss:{display:'none'} enough disable well.

c - Array declaration and initialization with structs -

i trying declare array of structs, possible initialize array entries default struct value? for example if struct typedef struct node { int data; struct node* next; }node; is there way decalre data 4 , next null? 0 , null? sure: node x[4] = { {0, null}, {1, null}, {2, null}, {3, null} }; even should fine: node y[4] = { {0, y + 1}, {1, y + 2}, {2, y + 3}, {3, null} };

selenium - How to test a website -

i've been looking ways perform basic automated tests: does given page have expected http status (typically 200) are there problems related files (http status on used files such js, css, images, fonts, ...) are there js errors while loading page many of commonly used tools (such selenium) don't seem support these tests, don't know start... know simple solution covering these tests ? we have succeeded in setting unit testing using mocha. website: http://visionmedia.github.io/mocha/ problem 1: checking http status i found alternative this: superagent https://github.com/visionmedia/superagent this module allows perform basic http requests , gives information might expect. can use check kind of header (ie. check if you're getting json data when set "accept-type: application/json" in request) request .get('http://mywebsite/') .end(function (res) { assert.strictequal(res.statuscode, 200);

c++ - Why could a function works fine in main() but not inside a class? -

i have move function call main class constructor. while function works fine in main, when moved class constructor generates error on compile time: cannot convert 'tile**' 'tile*' argument '1' 'bool set_tiles(tile*)' in function 'void moveobjects(tile**)' i don't understand how happen since both functions called identiacally. main() , class constructor: int main(){ tile *tiles[ total_tiles ]; if( set_tiles( tiles ) == false ) return 1; // setear los tiles currentstate = new overworld(); update_game(tiles); } overworld::overworld() { tile *tiles[ total_tiles ]; if( set_tiles( tiles ) == false ) exit(1); // error } bool set_tiles( tile *tiles[] ){ } void update_game(tile *tiles[]){ moveobjects(tiles); } also noticed error mentions function, i'm not sure how it's related i'll copy it's code: what doing wrong?

ruby - bad URI(is not URI?) when using click_link -

i have code line looks this: click_link "link page spaces" the link looks in html: <a href="page spaces">link page spaces</a> when line runs get: bad uri(is not uri?): page spaces /opt/rbenv/versions/2.0.0-p247/lib/ruby/2.0.0/uri/common.rb:176:in `split' i understand problem because link contains spaces not converted %20 i'm not sure on how solve it. could escape uri wherever it's being generated? require 'uri' uri.escape("page spaces") # => "page%20with%20spaces"

android - Strange bug in listfragment -

i wanted study android sqlite created instant tagging application in user can tag photos , upload them network (google+, fb, twitter) problem have listfragment in user can see tagging made, image elements in list stored on hidden folder , words stored in sqlite db.. problem while scrolling or down items switch randomly plus though have more 8 items them 8 first items shown repeatedly (i.e 1-8 instead of 9-12 see 1-4 again) problem might in adapter after sessions on sessions of debug fail find problem code adapter - public class flowadapter extends baseadapter { private activity activity; private arraylist<hashmap<string, list<string>>> data; private static layoutinflater layoutinflater = null; public flowadapter(activity activitycontext, arraylist<hashmap<string, list<string>>> data) { this.activity = activitycontext; this.data = data; this.layoutinflater = (layoutinflater) activity

c# - MonthCalendar - Disable days -

i'm doing application in c# visual studio, , i'm using windows forms. need user able select date specific range (for i'm using mindate , maxdate ), , days of week. example, want disable mondays . i'm using monthcalendar , haven't found way disable days of week... possible? you can't stop user picking date on calendar. no trouble complaining , offering better choice: private void monthcalendar1_datechanged(object sender, daterangeeventargs e) { if (e.start.dayofweek == dayofweek.monday) { messagebox.show("i hate mondays"); monthcalendar1.selectionstart = e.start.adddays(1); } } use boldeddates property make valid selections more obvious.

c# - How to share same address for multiple endpoints -

i have created rest service wcf , have different contracts(contract1, contract2, etc..). configuration in web.config <endpoint address="users" binding="webhttpbinding" behaviorconfiguration="web" contract="filminfoapi.service.iuserservice"/> <endpoint address="actors" binding="webhttpbinding" behaviorconfiguration="web" contract="filminfoapi.service.iactorservice"/> <endpoint address="films" binding="webhttpbinding" behaviorconfiguration="web" contract="filminfoapi.service.ifilmservice"/> it's example of contract. [operationcontract] [webget(uritemplate = "?offset={offset}&count={count}", responseformat = webmessageformat.json)] films getfilms(string offset, string count); so question how can use same address endpoints (localhost/rest). because need contract uritemplate more flexible, example if need retu

css - How to stop centering a div as soon as it hits the edge of the screen -

i want create flexible layout, have 1 div has have fixed width of 1000px. best solution had center div while there enough space available when screen became 1000px or smaller in width, div float:left . i'm aware using media queries, im using different dimensions right , wanted explore other options. have suggestions? you're pretty left media queries or javascript. mq best approach this.

Unix script giving error trying to assign variable? -

i'm extremely new unix, , driving me crazy. getting error: ./lines: line 21: [[: grep -c *.* $3: syntax error: operand expected (error toke n ".* $3") ./lines: line 26: [[: grep -c *.* $3: syntax error: operand expected (error toke n ".* $3") when running script: #!/bin/bash #lines <start> <finish> <file> prints lines start-finish of file if [[ $# != 3 ]] echo "command format: lines <starting line> <end line> <filename>" exit fi tlines='grep -c *.* $3' start=$1 finish=$2 if [[ $finish -lt $start ]] echo "$finish less $start. i'll go ahead , reverse you." start=$2 finish=$1 fi start=$((finish-start+1)) if [[ $tlines -lt $start ]] echo "$3 $tlines lines - that's less $start" exit fi if [[ $tlines -lt $finish ]] echo "3 $tlines line - that's less $finish" exit fi head -$finish $

Disable Combiner in hadoop -

i want make sure mapreduce program (in hadoop) not combining @ mapper side. know conf.setcombinerclass() sets combiner class class point to. if don't specify combiner class using set function, combining disabled or there still implicit default combiner applied anyways. if so, how disable combining? there no implicit combiner, have set explicitly.

java - multiply large no. in array -

multiply 2 numbers. numbers can extremely large (i.e. run hundreds of digits) , provided strings. the expected output string represents product of 2 numbers. example- multiply("268435456","524288")="140737488355328" multiply("12321412423524534534543","0")="0" use bigdecimal, has multiply method , constructor takes string . contains corresponding tostring() , toplainstring() methods result string. (if numbers whole numbers, use biginteger instead.)

amazon web services - Pull data from SimpleDB to iOS -

i trying familiarize myself both simpledb , ios. have situation have created database simpledb , pull items ios , populate. how doing this? sample code & libraries http://aws.amazon.com/code/amazon-simpledb/4083 see more details at http://simpledb.ios-aws.com/home/awsoperations/batchputattributes

How to draw a arc in android openGL ES1.1? -

Image
using 3 values ​​are given on 2d plane, shown below, , curve. starting point first draw (x, y, z). left angle. right angle. android opengl es above values ​​should drawn , how ask advice?

c# - Use an array to display a unique set of values -

i'm doing homework problem need write application inputs 5 numbers, each of between 10 , 100, inclusive. each number read, display if not duplicate of number read. provide worst case, in 5 numbers different. use smallest array possible in order solve problem , display complete set of unique values after user inputs each new value. what have far works correctly. only, keep getting unhandled error once program runs if 5 numbers unique. tells me index goes out of bounds of array. i'm not sure why , can't see errors in loop. using system; using system.collections.generic; using system.linq; using system.text; using system.threading.tasks; namespace ten_seven_thirteen { class program { static void main(string[] args) { const int size = 5; int[] nums = new int[size]; int a; int b; int c = 0; //c amount of numbers entered int number; console.writeline("input 5 numbers between 10 , 100 (inclusive): \n&quo

Run a C++ Project main() multiple times in Visual Studio? -

i have visual studio c++ project. if want run once, can manually input arguments of int main(int argc, char** argv) into debugging options , click debug . however now, wish run multiple times different parameters in 1 go . e.g. wish run this: for(i=0; i<10; i++) { main(i); } how may visual studio? i don't believe it's technically legal (per standard) call main . if were, you'd passing wrong parameters ( argc == 1 , argv == ${deity}_only_knows ). this problem perhaps solve cmd script. make sure program compiled, run like: @echo off cd \path\to\debug\dir rem bit can complex cmd.exe allows: /l %%a in (0,1,50) ( /l %%b in (0,1,10) ( echo data.txt result.txt %%a %%b ) ) this run command ( echo in case can see working should replace actual executable name, , modify cd command select proper directory) 561 times (51 x 11) first 2 arguments fixed , last 2 running 0-50 , 0-10, output of finishes: : : : : : : : : : : data.txt re

Python + SqlAlchemy 'init' with single table inheritance -

got problems sqlalchemy thing. i've defined database, relevant parts per below... class person(base): __tablename__ = 'person' # id = column(integer, primary_key=true) person_type = column(string(32), nullable=false) name = column(string(50)) address = column(string(120)) phonenum = column(string(20)) __mapper_args__ = {'polymorphic_on':person_type} # class student(person): __mapper_args__ = {'polymorphic_identity': 'student'} dob = column(date) i've other subclasses of 'person' too. i'm having problems way 'init' should look. last attempt was.. for 'person'.. def __init__(self, a_name, a_address, a_phonenum, a_person_type = none): self.name = a_name self.address = a_address self.phonenum = a_phonenum and 'student'.. def __init__ (self, a_name, a_address,a_phonenum, a_dob=none, a_stud_caregiver_id=none, a_person_type = 'student'):

java - How to validate whether or not a single input line is only integers? -

the program supposed receive 4 integers in single input user (eg 1 2 3 42). trying write code check whether or not input integers. however, when input 1 2 b, not enter while loop, , can't figure out why. appreciated. scanner scan = new scanner(system.in); system.out.print("please list @ least 1 , 10 integers: "); scan.hasnextint(); while(!scan.hasnextint()) { system.out.println("one or more of inputs not integer. please input integers: "); scan.next(); } you not progressing reading next int scanner . try input 1 b using following code: scan.hasnextint(); scan.nextint(); // or scan.next() read next integer while(!scan.hasnextint()) { system.out.println("one or more of inputs not integer. please input integers: "); scan.next(); } it print: one or more of inputs not integer. please input integers: only integers:one or mor

unable to query with friendly_id rails -

here controller before_action :seo_url_product,only: :product def seo_url_product if params[:id] @posts = post.friendly.where(sub_category_id: params[:id]).paginate(page: params[:page], per_page: 2).to_a end end here view <% category.sub_categories.each |sub_category| %> <li><%= link_to sub_category.name, controller: :posts, action: :product, id: sub_category %></li> <% end %> i can see friendly url when click sub_categories not see result. i think problem trying query slug not real id. know friendly_id use slug. should find real id first try query. insted of params[:id] in where query can use following. sub_category_id = sub_category.friendly.find(params[:id]) # find id insted of slug @posts = post.friendly.where(sub_category_id: sub_category_id).paginate(page: params[:page], per_page: 2).to_a

android - add headers google volley request? -

well, new in forum, please if me in this. searched not find how add headers volley request. have code , want add accept-encoding:gzip , api key. appreciate help. here code: type = "cafe"; url = "https://maps.googleapis.com/maps/api/place/search/json?location=" + global.location + "&radius=500&types=" + type + "&sensor=true&key="+placeskey; requestqueue rq = volley.newrequestqueue(context); jsonobjectrequest jsonrequest = new jsonobjectrequest(request.method.get, url, null, new response.listener<jsonobject>() { @override public void onresponse(jsonobject response) { list<review> reviews = new arraylist<review>(); reviews = parsing.parsereviews(response); } }, new response.errorlistener() { @override public void onerrorresponse(volleyerror error) { toast.maketext(context, error.tostring(), toast.length_short).show(); } }); rq.add(jsonrequest); jsonobjectrequest jsobjectrequest = new jsonobjec

C# Event Handler for a Timer Object -

what need have timer fire event handler (say every second) in class. small part of windows form program. i have tried using delegate "call" event handler, keep getting syntax errors. can steer me in correct direction simple code example? the code below start, commented portion works fine want event fire when windows timer fires. namespace windowsformsapplication3 { public partial class form1 : form { public form1() { initializecomponent(); } public event timerhandler tick; public eventargs e = null; public delegate void timerhandler(timer t, eventargs e); public class timer { public event timerhandler tick; public eventargs e = null; public delegate void timerhandler(timer t, eventargs e); } public class listener { public static int ticker = 0; public void subscribe(timer t) {

Determining variables stack or heap in C? -

let's have these variables , pointers. how determine in stack or heap? #include <stdio.h> #define size 5 int main( void ) { int *zlkr; int *alkr= null; void *slkr= null; int num, k; int a[size] = { 1, 2, 3, 4, 5 }; zlkr = a; } all variables have automatic scope. come "stack", in variables no longer valid once function returns. named function variables can never come "heap" in sense mean it. memory named function variable tied function scope (or innermost block scope within function in variable declared). a variable can assigned value obtained malloc() or similar dynamic allocation function. variable points object exists in "heap". however, named pointer variable not in "heap". sometimes "stack" dynamically allocated. such thread. then, memory used allocate function local variables running within thread in "heap". however, variables

cocoa - NSTextView live text highlighting -

Image
i want create text view support highlighting of basic things, links , hashtags. similar features can found in twitter.app: it not necessary support clicking on links, need highlight things while user editing contents of text view. the question is, best way that? don't want use heavy-weight syntax highlighting libraries, didn't find simple , small libraries highlight few things. should parse text , highlight myself? if should, libraries can use tokenise text, , libraries allow me make live highlighting? yes, if want light-weight use own parsing find relevant parts , use textstorage of nstextview change text attributes found range.

Javascript Not Working on PHP page -

i'm trying code checkbox must checked in order "submit" button on form enabled. first tried using linked file no avail; inserting script doesn't seem work. can help? entire code page posted below. in advance! <!doctype html public "-//w3c//dtd xhtml 1.0 strict//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="stylesheet.css" /> <script type="text/javascript" src="includes/imagetransition.js"></script> <script type="text/javascript" src="includes/checkenabledisable.js"></script> <script type="text/javascript"> var checker =

javascript - How to submit one html form to difference actions -

i have small form , links created this <a href="#" onclick="document.selectform.submit();">contact</a> | <a href="#">message</a> <form name="selectform" action="save.php" method="post" target="_blank"> name: <input type="text" name="test"/> <input type="submit" value="submit" name="sub"/> </form> when click "contact" link, form submit correctly, , if click "message" link how set form submit url for example: if click "message" link, want submit form edit.php , without using traget="_blank" you can change form action using attr() method of jquery, example $('#link1').click(function(){ $('#formid').attr('action', 'page1').submit(); }); $('#link2').click(function(){ $('#formid').attr('action'

iphone - UITableView count not increasing -

i have uitextview in viewcontroller. im passing textview viewcontroller1 uitableview. used nsuserdefaults store , retrieve text. in viewcontroller1 uitebleview not increasing updating text, replacing old text in first row. viewcontroller: -(void)save:(id)sender{ nsuserdefaults *userdata1 = [nsuserdefaults standarduserdefaults]; [userdata1 setobject:textview.text forkey:@"savetext"]; [userdata1 synchronize]; } viewcontroller1: -(void) viewwillappear:(bool)animated{ [super viewwillappear:animated]; textarray=[[nsmutablearray alloc]init]; txt=[[uitextview alloc]initwithframe:cgrectmake(0, 0, 320, 400)]; nsuserdefaults *prefs = [nsuserdefaults standarduserdefaults]; // getting nsstring nsstring *savedvalue = [prefs stringforkey:@"savetext"]; txt.text = [nsstring stringwithformat:@"%@", savedvalue]; myappdelegate = (appdelegate *)[[uiapplication sharedapplication]

generics - Types in Scala - lower bounds -

on code below. my expectation t must of type b or a , call lowerbound(new d) should not compile (?). similar experiments upperbound give me expected typecheck errors. thanks giving hint. object variancecheck { class { override def tostring = this.getclass.getcanonicalname } class b extends class c extends b class d extends c def lowerbound[t >: b](param: t) = { param } println(lowerbound(new d)) //> variancecheck.d } with implementation can write: scala> def lowerbound[t >: b](param: t) = { param } lowerbound: [t >: b](param: t)t scala> lowerbound(new anyref {}) res0: anyref = $anon$1@2eef224 where anyref super type of object/reference types (actually alias java object class). , right, t >: b expresses type parameter t or abstract type t refer supertype of type b . you have bad example tostring , cause method has object types, if change to, let's on somemethod , lowerbound won't

Django models. Retrieve the class of a model -

there project models.py looks this: class page(models.model) #fields class news(page) #no fields when want retrieve page or news page this: page = get_object_or_404(page, id=page_id) however, when give this: page.__class__ this: main.models.page . is there way know if page page class or news class without checking if page_id exists in news ? given page_id value there no way test whether or not id value exists entry in news table in addition page table other either trying retrieve (such page.news , , catching doesnotexist exception cases in not exist) or direct query against news manager. queries against page model's manager return page instances - have either know priori in view want news instead or test existence.

fragment - Android FragmentPagerAdapter showing up empty after cache clear -

i make fragmentpageradapter there fragment has pager. and pager show 3 fragments , works well. but, after application cache clearing, (it means... long time has passed application service backgrounded) only pager showing , 3 fragments have empty layout (white space). as result checking log, caught problem lines... after clearing cache, sectionspageradapter() constructure called then getitem() method never called. please me public class reviewfragment extends sherlockfragment { private sectionspageradapter msectionspageradapter; private viewpager mviewpager; @override public view oncreateview(layoutinflater inflater, viewgroup container, bundle savedinstancestate) { view rootview = inflater.inflate(r.layout.review_fragment, container, false); return rootview; } @override public void onactivitycreated(bundle savedinstancestate) { super.onactivitycreated(savedinstancestate); if (savedinstancestate == n

asp.net mvc - Redirect visitors first time visiting site -

so need redirect visitors first time enter site, regardless entrypoint site. i have implemented global filter search cookie , if cookie doesn't exist, create cookie , redirect desired page. it seems expensive way every action first check cookie. there better way achieve this? thanks! checking presence of cookie won't expensive operation run on every action. that's correct way implement feature , won't hurt performance of site. as alternative method, if client browsers support html5 local storage use javascript store value in local storage if user has visited site. then, once again, using javascript, on every page check presence of value in local storage , if not present redirect user landing page.

html - input array sum with jQuery -

hello have unknown quantity of inputs array name , class <input type="hidden" name="hidden[1]" class="sum" value="31"> <input type="hidden" name="hidden[2]" class="sum" value="21"> <input type="hidden" name="hidden[3]" class="sum" value="321"> <input type="hidden" name="hidden[4]" class="sum" value="-31"> <input type="hidden" name="hidden[5]" class="sum" value="31.12"> <input type="hidden" name="hidden[6]" class="sum" value="0"> question how sum values of fields try use .each() , getelementbyclassname wont work i tried using each, worked me. check if used parsefloat ... if have 'sum' class define elements must calculated, below code should work.... $(document).ready(function () {

sql - Query - definition of ( table , table ) in simple mysql inner join -

i'm reconstructing search query coz it's becoming redundant in "what see" , i'm wondering (albums_artists, artists) ( ) in join? boosting performance? a query uses simple inner joins, using old (sql-89) implicit join syntax: select ma_users.name, ma_users.username, albums.id album_id, albums.upc, albums.name album_name, albums.status, albuminfos.label, date_format(albums.created, '%y-%m-%d') created_date, concat(artists.name) artist_name, count(tracks.id) total_tracks, albumstatus.description album_status albums, albuminfos, ma_users , (albums_artists, artists) , tracks ,(albumstatus, albumtypes) albums.id = albuminfos.id , ma_users.id = albums.account_id , albums.id = albums_artists.artist_id , albums_artists.artist_id = artists.id , tracks.album_id = albums.id , albums.status = albumstatus.id , albumtypes.id = albums.albumtype_id , albumin

c# - Setting focus to listviews in the tabcontrol of a winform -

in project, in form there 2 list views in tabcontrol, unable set focus both list view items. using following code. problem able select 1 listview among both. please tell me alternative can select both listviews in form. private void tabcontrol1_selectedindexchanged(object sender, eventargs e) { binddata1(); if (listviewclients.items.count > 0) { listviewclients.items[0].selected = true; listviewclients.select(); } if (listview1.items.count > 0) { listview1.items[0].selected = true; listview1.select(); } } private void tabcontrol1_selectedindexchanged(object sender, eventargs e) { binddata1(); switch (this.tabcontrol1.selectedtab.name) { case "tpupdate": listviewclients.items[0].selected = true; listviewclients.select(); break; c

java - Why can't I instantiate and create Object without main method? ( Error)

my code: (causes stack overflow error) public class overloads { string uniqueid; overloads ov2=new overloads(); public static void main(string[] args) { system.out.println("in main"); } public void setuniqueid(string theid) { // ii lots of validation code, , then: uniqueid = theid; system.out.println(uniqueid); } } this code works fine: public class overloads { string uniqueid; public static void main(string[] args) { overloads ov2=new overloads(); system.out.println("in main"); } public void setuniqueid(string theid) { // ii lots of validation code, , then: uniqueid = theid; system.out.println(uniqueid); } } the presence of main method not relevant here. scope in have declared variables, however, important. have walked through happens in first version of code? create new instance of overloads ->