Search Results

Search found 2947 results on 118 pages for 'params noob'.

Page 10/118 | < Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >

  • How to call regular JS function with params within jQuery ?

    - by Kim
    Is there another way to run a regular JS function with params passed than what I use below ? It seems redundant use a on-the-way function to do this. function regularJSfunc(param1,param2) { // do stuff } $(document).ready(function(){ $('#myId').change(function(){ regularJSfunc('data1','data2'); }); } Using a .bind event seems much better, however I am not sure how to access the params. Note: Example below doesnt work. $(document).ready(function(){ $('#myId').bind('change',{'data1','data2'},regularJSfunc); }

    Read the article

  • What's the best way to return stuff from a PHP function, and simultaneously trigger a jQuery action?

    - by Jack Webb-Heller
    So the title is a tad ambiguous, but I'll try and give an example. Basically, I have an 'awards' system (similar to that of StackOverflow's badges) in my PHP/CodeIgniter site, and I want, as soon as an award is earned, a notification to appear to the user. Now I'm happy to have this appear on the next page load, but, ideally I'd like it to appear as soon as the award is transactioned since my site is mostly Ajax-powered and there may not be page reloads very often. The way the system works currently, is: 1) If the user does something to trigger the earning of an award, CodeIgniter does this: $params['user_id'] = $this->tank_auth->get_user_id(); $params['award_id'] = 1; // (I have a database table with different awards in) $this->awards->award($params); 2) My custom library, $this->awards, runs the award function: function award($params) { $sql = $this->ci->db->query("INSERT INTO users_awards (user_id, award_id) VALUES ('".$params['user_id']."','".$params['award_id']."') ON DUPLICATE KEY UPDATE duplicate=duplicate+1"); $awardinfo = $this->ci->db->query("SELECT * FROM awards WHERE id = ".$params['award_id']); // If it's the 'first time' the user has gotten the award (e.g. they've earnt it) if ($awardinfo->row('duplicate') == 0) { $params['title'] = $awardinfo->row('title'); $params['description'] = $awardinfo->row('description'); $params['iconpath'] = $awardinfo->row('iconpath'); $params['percentage'] = $awardinfo->row('percentage'); return $params; } } So, it awards the user (and if they've earnt it twice, updates a useless duplicate field by one), then checks if it's the first time they've earnt it (so it can alert them of the award). If so, it gets the variables (title of the award, the award description, the path to an icon to display for the award, and finally the percentage of users who have also got this award) and returns them as an array. So... that's that. Now I'd like to know, what's the best way to do this? Currently my Award-giving bit is called from a controller, but I guess if I want this to trigger via Ajax, then the code should be placed in a View file...? To sum it up: I need the returned award data to appear without a page refresh. What's the best way of doing this? (I'm already using jQuery on my page). Thanks very much everybody! Jack

    Read the article

  • Javascript calls to an Ajax WebMethod. How to get multiple output params returned?

    - by George
    OK, I know how to call a simple old fashion asmx webservice webthod that returns a single value as a function return result. But what if I want to return multiple output params? My current approach is to separate the params by a dividing character and parse them on teh client. Is there a better way. Here's how I return a single function result. How do I return multiple output values? <asp:ScriptManager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="WebService.asmx" /> </Services> function CallHelloWebMethod() { WebService.Hello(OnComplete1, OnTimeOut, OnError); } function OnComplete1(arg) { alert(arg); } function OnTimeOut(arg) { } <WebMethod()> Public Function Hello(ByVal x As String) As String Return "Hello " & x End Function

    Read the article

  • Search object array for matching possible multiple values using different comparison operators

    - by Sparkles
    I have a function to search an array of objects for a matching value using the eq operator, like so: sub find { my ( $self, %params ) = @_; my @entries = @{ $self->{_entries} }; if ( $params{filename} ) { @entries = grep { $_->filename eq $params{filename} } @entries; } if ( $params{date} ) { @entries = grep { $_->date eq $params{date} } @entries; } if ( $params{title} ) { @entries = grep { $_->title eq $params{title} } @entries; } .... I wanted to also be able to pass in a qr quoted variable to use in the comparison instead but the only way I can think of separating the comparisons is using an if/else block, like so: if (lc ref($params{whatever}) eq 'regexp') { #use =~ } else { #use eq } Is there a shorter way of doing it? Because of reasons beyond my control I'm using Perl 5.8.8 so I can't use the smart match operator. TIA

    Read the article

  • How to know if a device can be disabled or not?

    - by user326498
    I use the following code to enable/disable a device installed on my computer: SP_PROPCHANGE_PARAMS params; memset(&params, 0, sizeof(params)); devParams.cbSize = sizeof(devParams); params.ClassInstallHeader.cbSize = sizeof(params.ClassInstallHeader); params.ClassInstallHeader.InstallFunction = DIF_PROPERTYCHANGE; params.Scope = DICS_FLAG_GLOBAL; params.StateChange = DICS_DISABLE ; params.HwProfile = 0; // current profile if(!SetupDiSetClassInstallParams(m_hDev, &m_hDevInfo,&params.ClassInstallHeader,sizeof(SP_PROPCHANGE_PARAMS))) { dwErr = GetLastError(); return FALSE; } if(!SetupDiCallClassInstaller(DIF_PROPERTYCHANGE,m_hDev,&m_hDevInfo)) { dwErr = GetLastError(); return FALSE; } return TRUE; This code works perfectly only for those devices that can also be disabled by using Windows Device Manager, and won't work for some un-disabled devices such as my cpu device: Intel(R) Pentium(R) Dual CPU E2160 @ 1.80GHz. So the problem is how to determine if a device can be disabled or not programmatically? Is there any API to realize this goal? Thank you!

    Read the article

  • Passing a Structure containing an array of String and an array of Integer into a C++ DLL

    - by DanJunior
    I'm having problems with marshaling in VB.NET to C++, here's the code : In the C++ DLL : struct APP_PARAM { int numData; LPCSTR *text; int *values; }; int App::StartApp(APP_PARAM params) { for (int i = 0; i < numLines; i++) { OutputDebugString(params.text[i]); } } In VB.NET : <StructLayoutAttribute(LayoutKind.Sequential)> _ Public Structure APP_PARAM Public numData As Integer Public text As System.IntPtr Public values As System.IntPtr End Structure Declare Function StartApp Lib "AppSupport.dll" (ByVal params As APP_PARAM) As Integer Sub Main() Dim params As APP_PARAM params.numData = 3 Dim text As String() = {"A", "B", "C"} Dim textHandle As GCHandle = GCHandle.Alloc(text) params.text = GCHandle.ToIntPtr(textHandle) Dim values As Integer() = {10, 20, 30} Dim valuesHandle As GCHandle = GCHandle.Alloc(values) params.values = GCHandle.ToIntPtr(heightHandle) StartApp(params) textHandle.Free() valuesHandle.Free() End Sub I checked the C++ side, the output from the OutputDebugString is garbage, the text array contains random characters. What is the correct way to do this?

    Read the article

  • [PHP] How to pass array as multiple parameters to function?

    - by vbklv
    I have a parameters array: $params[1] = 'param1'; $params[2] = 'param2'; $params[3] = 'param3'; ... $params[N] = 'paramN'; I have a caller to various functions: $method->$function( $params ); How can I parse the $params array, so multiple (and unlimited) parameters can be passed to any function: $method->$function( $param[1], $param[2], ..., $param[N] );

    Read the article

  • Undefined method 'total_entries' after upgrading Rails 2.2.2 to 2.3.5

    - by Trevor
    I am upgrading a Rails application from 2.2.2 to 2.3.5. The only remaining error is when I invoke total_entries for creating a jqgrid. Error: NoMethodError (undefined method `total_entries' for #<Array:0xbbe9ab0>) Code snippet: @route = Route.find( :all, :conditions => "id in (#{params[:id]})" ) { if params[:page].present? then paginate :page => params[:page], :per_page => params[:rows] order_by "#{params[:sidx]} #{params[:sord]}" end } respond_to do |format| format.html # show.html.erb format.xml { render :xml => @route } format.json { render :json => @route } format.jgrid { render :json => @route.to_jqgrid_json( [ :id, :name ], params[:page], params[:rows], @route.total_entries ) } end Any ideas? Thanks!

    Read the article

  • How can I get all the checked items from a submitted form with sinatra's params?

    - by 102405176597896213397
    I'm running Sinatra 1.0 with HAML, my form has a number of checkboxes, for example books I like, and you would select all the books you want. The checkbox name is "books". In sinatra params['books'] there should be an array of all the books that were checked, but it only has the last item that was checked, not an array. How can I get all the checked items? HAML: %form{:action => "/test", :method => 'post'} %input{:name=>'check',:type=>'checkbox',:value=>'item1'} item 1 %input{:name=>'check',:type=>'checkbox',:value=>'item2'} item 2 %input{:name=>'check',:type=>'checkbox',:value=>'item3'} item 3 %input{:type => "submit", :value => "send", :class => "button"} Sinatra get method post '/test' do puts params['check'] #should be an array but is last item checked end

    Read the article

  • PGU HTML Renderer can't render most sites

    - by None
    I am trying to make a web browser using pygame. I am using PGU for html rendering. It works fine when I visit simple sites, like example.com, but when I try and load anything more complex that uses an html form, like google, I get this error: UnboundLocalError: local variable 'e' referenced before assignment I looked in the PGU html rendering file and found this code segment: def start_input(self,attrs): r = self.attrs_to_map(attrs) params = self.map_to_params(r) #why bother #params = {} type_,name,value = r.get('type','text'),r.get('name',None),r.get('value',None) f = self.form if type_ == 'text': e = gui.Input(**params) self.map_to_connects(e,r) self.item.add(e) elif type_ == 'radio': if name not in f.groups: f.groups[name] = gui.Group(name=name) g = f.groups[name] del params['name'] e = gui.Radio(group=g,**params) self.map_to_connects(e,r) self.item.add(e) if 'checked' in r: g.value = value elif type_ == 'checkbox': if name not in f.groups: f.groups[name] = gui.Group(name=name) g = f.groups[name] del params['name'] e = gui.Checkbox(group=g,**params) self.map_to_connects(e,r) self.item.add(e) if 'checked' in r: g.value = value elif type_ == 'button': e = gui.Button(**params) self.map_to_connects(e,r) self.item.add(e) elif type_ == 'submit': e = gui.Button(**params) self.map_to_connects(e,r) self.item.add(e) elif type_ == 'file': e = gui.Input(**params) self.map_to_connects(e,r) self.item.add(e) b = gui.Button(value='Browse...') self.item.add(b) def _browse(value): d = gui.FileDialog(); d.connect(gui.CHANGE,gui.action_setvalue,(d,e)) d.open(); b.connect(gui.CLICK,_browse,None) self._locals[r.get('id',None)] = e I got the error in the last line, because e wasn't defined. I am guessing the reason for this is that the if statement that checks the type of the input and creates the e variable didn't match anything. I added a line to print the _type variable and I got 'hidden' when i tried google and apple. Is there any way to render form items that have the type 'hidden' with PGU?

    Read the article

  • Valgrind says "stack allocation," I say "heap allocation"

    - by Joel J. Adamson
    Dear Friends, I am trying to trace a segfault with valgrind. I get the following message from valgrind: ==3683== Conditional jump or move depends on uninitialised value(s) ==3683== at 0x4C277C5: sparse_mat_mat_kron (sparse.c:165) ==3683== by 0x4C2706E: rec_mating (rec.c:176) ==3683== by 0x401C1C: age_dep_iterate (age_dep.c:287) ==3683== by 0x4014CB: main (age_dep.c:92) ==3683== Uninitialised value was created by a stack allocation ==3683== at 0x401848: age_dep_init_params (age_dep.c:131) ==3683== ==3683== Conditional jump or move depends on uninitialised value(s) ==3683== at 0x4C277C7: sparse_mat_mat_kron (sparse.c:165) ==3683== by 0x4C2706E: rec_mating (rec.c:176) ==3683== by 0x401C1C: age_dep_iterate (age_dep.c:287) ==3683== by 0x4014CB: main (age_dep.c:92) ==3683== Uninitialised value was created by a stack allocation ==3683== at 0x401848: age_dep_init_params (age_dep.c:131) However, here's the offending line: /* allocate mating table */ age_dep_data->mtable = malloc (age_dep_data->geno * sizeof (double *)); if (age_dep_data->mtable == NULL) error (ENOMEM, ENOMEM, nullmsg, __LINE__); for (int j = 0; j < age_dep_data->geno; j++) { 131=> age_dep_data->mtable[j] = calloc (age_dep_data->geno, sizeof (double)); if (age_dep_data->mtable[j] == NULL) error (ENOMEM, ENOMEM, nullmsg, __LINE__); } What gives? I thought any call to malloc or calloc allocated heap space; there is no other variable allocated here, right? Is it possible there's another allocation going on (the offending stack allocation) that I'm not seeing? You asked to see the code, here goes: /* Copyright 2010 Joel J. Adamson <[email protected]> $Id: age_dep.c 1010 2010-04-21 19:19:16Z joel $ age_dep.c:main file Joel J. Adamson -- http://www.unc.edu/~adamsonj Servedio Lab University of North Carolina at Chapel Hill CB #3280, Coker Hall Chapel Hill, NC 27599-3280 This file is part of an investigation of age-dependent sexual selection. This code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with haploid. If not, see <http://www.gnu.org/licenses/>. */ #include "age_dep.h" /* global variables */ extern struct argp age_dep_argp; /* global error message variables */ char * nullmsg = "Null pointer: %i"; /* error message for conversions: */ char * errmsg = "Representation error: %s"; /* precision for formatted output: */ const char prec[] = "%-#9.8f "; const size_t age_max = AGEMAX; /* maximum age of males */ static int keep_going_p = 1; int main (int argc, char ** argv) { /* often used counters: */ int i, j; /* read the command line */ struct age_dep_args age_dep_args = { NULL, NULL, NULL }; argp_parse (&age_dep_argp, argc, argv, 0, 0, &age_dep_args); /* set the parameters here: */ /* initialize an age_dep_params structure, set the members */ age_dep_params_t * params = malloc (sizeof (age_dep_params_t)); if (params == NULL) error (ENOMEM, ENOMEM, nullmsg, __LINE__); age_dep_init_params (params, &age_dep_args); /* initialize frequencies: this initializes a list of pointers to initial frqeuencies, terminated by a NULL pointer*/ params->freqs = age_dep_init (&age_dep_args); params->by = 0.0; /* what range of parameters do we want, and with what stepsize? */ /* we should go from 0 to half-of-theta with a step size of about 0.01 */ double from = 0.0; double to = params->theta / 2.0; double stepsz = 0.01; /* did you think I would spell the whole word? */ unsigned int numparts = floor(to / stepsz); do { #pragma omp parallel for private(i) firstprivate(params) \ shared(stepsz, numparts) for (i = 0; i < numparts; i++) { params->by = i * stepsz; int tries = 0; while (keep_going_p) { /* each time through, modify mfreqs and mating table, then go again */ keep_going_p = age_dep_iterate (params, ++tries); if (keep_going_p == ERANGE) error (ERANGE, ERANGE, "Failure to converge\n"); } fprintf (stdout, "%i iterations\n", tries); } /* for i < numparts */ params->freqs = params->freqs->next; } while (params->freqs->next != NULL); return 0; } inline double age_dep_pmate (double age_dep_t, unsigned int genot, double bp, double ba) { /* the probability of mating between these phenotypes */ /* the female preference depends on whether the female has the preference allele, the strength of preference (parameter bp) and the male phenotype (age_dep_t); if the female lacks the preference allele, then this will return 0, which is not quite accurate; it should return 1 */ return bits_isset (genot, CLOCI)? 1.0 - exp (-bp * age_dep_t) + ba: 1.0; } inline double age_dep_trait (int age, unsigned int genot, double by) { /* return the male trait, a function of the trait locus, age, the age-dependent scaling parameter (bx) and the males condition genotype */ double C; double T; /* get the male's condition genotype */ C = (double) bits_popcount (bits_extract (0, CLOCI, genot)); /* get his trait genotype */ T = bits_isset (genot, CLOCI + 1)? 1.0: 0.0; /* return the trait value */ return T * by * exp (age * C); } int age_dep_iterate (age_dep_params_t * data, unsigned int tries) { /* main driver routine */ /* number of bytes for female frequencies */ size_t geno = data->age_dep_data->geno; size_t genosize = geno * sizeof (double); /* female frequencies are equal to male frequencies at birth (before selection) */ double ffreqs[geno]; if (ffreqs == NULL) error (ENOMEM, ENOMEM, nullmsg, __LINE__); /* do not set! Use memcpy (we need to alter male frequencies (selection) without altering female frequencies) */ memmove (ffreqs, data->freqs->freqs[0], genosize); /* for (int i = 0; i < geno; i++) */ /* ffreqs[i] = data->freqs->freqs[0][i]; */ #ifdef PRMTABLE age_dep_pr_mfreqs (data); #endif /* PRMTABLE */ /* natural selection: */ age_dep_ns (data); /* normalized mating table with new frequencies */ age_dep_norm_mtable (ffreqs, data); #ifdef PRMTABLE age_dep_pr_mtable (data); #endif /* PRMTABLE */ double * newfreqs; /* mutate here */ /* i.e. get the new frequency of 0-year-olds using recombination; */ newfreqs = rec_mating (data->age_dep_data); /* return block */ { if (sim_stop_ck (data->freqs->freqs[0], newfreqs, GENO, TOL) == 0) { /* if we have converged, stop the iterations and handle the data */ age_dep_sim_out (data, stdout); return 0; } else if (tries > MAXTRIES) return ERANGE; else { /* advance generations */ for (int j = age_max - 1; j < 0; j--) memmove (data->freqs->freqs[j], data->freqs->freqs[j-1], genosize); /* advance the first age-class */ memmove (data->freqs->freqs[0], newfreqs, genosize); return 1; } } } void age_dep_ns (age_dep_params_t * data) { /* calculate the new frequency of genotypes given additive fitness and selection coefficient s */ size_t geno = data->age_dep_data->geno; double w[geno]; double wbar, dtheta, ttheta, dcond, tcond; double t, cond; /* fitness parameters */ double mu, nu; mu = data->wparams[0]; nu = data->wparams[1]; /* calculate fitness */ for (int j = 0; j < age_max; j++) { int i; for (i = 0; i < geno; i++) { /* calculate male trait: */ t = age_dep_trait(j, i, data->by); /* calculate condition: */ cond = (double) bits_popcount (bits_extract(0, CLOCI, i)); /* trait-based fitness term */ dtheta = data->theta - t; ttheta = (dtheta * dtheta) / (2.0 * nu * nu); /* condition-based fitness term */ dcond = CLOCI - cond; tcond = (dcond * dcond) / (2.0 * mu * mu); /* calculate male fitness */ w[i] = 1 + exp(-tcond) - exp(-ttheta); } /* calculate mean fitness */ /* as long as we calculate wbar before altering any values of freqs[], we're safe */ wbar = gen_mean (data->freqs->freqs[j], w, geno); for (i = 0; i < geno; i++) data->freqs->freqs[j][i] = (data->freqs->freqs[j][i] * w[i]) / wbar; } } void age_dep_norm_mtable (double * ffreqs, age_dep_params_t * params) { /* this function produces a single mating table that forms the input for recombination () */ /* i is female genotype; j is male genotype; k is male age */ int i,j,k; double norm_denom; double trait; size_t geno = params->age_dep_data->geno; for (i = 0; i < geno; i++) { double norm_mtable[geno]; /* initialize the denominator: */ norm_denom = 0.0; /* find the probability of mating and add it to the denominator */ for (j = 0; j < geno; j++) { /* initialize entry: */ norm_mtable[j] = 0.0; for (k = 0; k < age_max; k++) { trait = age_dep_trait (k, j, params->by); norm_mtable[j] += age_dep_pmate (trait, i, params->bp, params->ba) * (params->freqs->freqs)[k][j]; } norm_denom += norm_mtable[j]; } /* now calculate entry (i,j) */ for (j = 0; j < geno; j++) params->age_dep_data->mtable[i][j] = (ffreqs[i] * norm_mtable[j]) / norm_denom; } } My current suspicion is the array newfreqs: I can't memmove, memcpy or assign a stack variable then hope it will persist, can I? rec_mating() returns double *.

    Read the article

  • GhostScript noob help - Breaking a multipage PDF file into many single page PS or EPS files.

    - by godzilla_g
    Hi, I'm trying to do the following with ghostscript: Turn one multipage PDF file (about 3,000 pages, 200mb file) into: One file per page of the PDF, and convert each (page/file) to EPS or PS (post script(preferably)). Example: hello.pdf (10 pages) would produce: hello1.ps (page 1 out of 10) hello2.ps hello3.ps ... hello10.ps How can I do this? I've been trying for 4 days, and can't figure it out. I have a script I've tried(won't work): Note: Windows(7) user here. gs -sDEVICE=epswrite -o documentname-%.eps documentname.pdf I also don't know how to navigate to the directory where my file resides (cannot figure that out, too). If you can, please show me how. A big thank you.

    Read the article

  • Noob with git repository on Windows Storage Server 2008?

    - by HibbyHoo
    I have a Western Digital Sentinel at home running Windows Storage Server 2008 R2 Essentials. I have several git repositories on it for my own personal projects, and have no problem pushing and pulling over my local network. I want to be able to access those repos remotely from anywhere. I am able to log in and remotely access folders and files on it, but I cannot clone repos using the same address. It hangs for a REALLY long time before finally failing with an error: git.exe clone --progress -v "https://myIpAddressHere/Remote/fs/files.aspx?path=%5C%5Cmydevicename%5Cmyreposfolder%5Cmyrepo.git" "D:\repo" Cloning into 'D:\repo'... error: Failed connect to myIpAddress:443; No error while accessing https://myIpAddress/Remote/fs/files.aspx?path=%5C%5Cmydevicename%5Cmyreposfolder%5Cmyrepo.git/info/refs fatal: HTTP request failed git did not exit cleanly (exit code 128) I'm not too privy to networking or web development, and I have only a rudimentary understanding of how to use git (with TortoiseGit). I'm having a hard time finding search results for this specific problem and a hard time interpreting generic tutorials for the general scope of this problem. TortoiseGit version: 1.7.13.0. git version: 1.7.10.mysysgit.1.

    Read the article

  • WMD editor freezes IE7 for 3 seconds on load

    - by dhruvbird
    Hello all, I am using the WMD editor's original code(not the stackoverflow version) since I need multiple of 'em on the same page and stackoverflow's version makes heavy use of element IDs internally since they aren't going to be having more than one editor instance per page. The code runs fin in FF 3.5, etc.. However, when I run it in IE8 (in IE7 compatibility mode), it freezes the whole browser for about 3 sec. before a new instance shows up. I tried profiling it with IE's dev. tools, and it seems that the getWidth() function on line 520 of the minified version of the code is taking up all the time. However, when I tried to hard-code the return (since it was always returning the same thing), the bottleneck shifted to the getHeight() function. I am attaching the code I am using to convert it to a jQuery plugin. jQuery.fn.wmd = function(params) { function createInstance(container, params) { /* Make sure WMD has finished loading */ if (!Attacklab || !Attacklab.wmd) { alert("WMD hasn't finished loading!"); return; } var defaultParams = { width : "600px", rows : 6, autogrow : false, preview : false, previewDivClassName: "wmd-preview-div" }; if (typeof(params) == "undefined") { var params = defaultParams; } else { var params = jQuery.extend({}, defaultParams, params); } /* Build the DOM elements */ var textarea = document.createElement("textarea"); textarea.style.width = params.width; textarea.rows = params.rows; jQuery(container).append(textarea); var previewDiv = document.createElement("div"); if (params.preview) { jQuery(previewDiv).addClass(params.previewDivClassName); jQuery(container).append(previewDiv); } /* Build the preview manager */ var panes = {input:textarea, preview:previewDiv, output:null}; var previewManager = new Attacklab.wmd.previewManager(panes); /* Build the editor and tell it to refresh the preview after commands */ var editor = new Attacklab.wmd.editor(textarea,previewManager.refresh); /* Save everything so we can destroy it all later */ var wmdInstance = {ta:textarea, div:previewDiv, ed:editor, pm:previewManager}; var wmdInstanceId = $(container).attr('postID'); wmdInstanceProcs.add(wmdInstanceId, wmdInstance); if (params.autogrow) { // $(textarea).autogrow(); } }; if (jQuery(this).html().length > 0) { var wmdInstanceId = jQuery(this).attr('postID'); var inst = wmdInstanceProcs.get(wmdInstanceId); jQuery(inst.ta).show(); } else { createInstance(this, params); } } jQuery.fn.unwmd = function(params) { var wmdInstanceId = $(this).attr('postID'); var inst = wmdInstanceProcs.get(wmdInstanceId); if (inst != null) { jQuery(inst.ta).hide(); } } wmdInstanceProcs = function() { var wmdInstances = { }; var getProc = function(wmdInstanceId) { var inst = wmdInstances[wmdInstanceId]; if (typeof(inst) != "undefined") { return inst; } else { return null; } }; var addProc = function(wmdInstanceId, wmdInstance) { wmdInstances[wmdInstanceId] = wmdInstance; }; return { add: addProc, get: getProc }; }(); Any help would be much appreciated.

    Read the article

  • Why does Keychain Services return the wrong keychain content?

    - by Graham Lee
    I've been trying to use persistent keychain references in an iPhone application. I found that if I created two different keychain items, I would get a different persistent reference each time (they look like 'genp.......1', 'genp.......2', …). However, attempts to look up the items by persistent reference always returned the content of the first item. Why should this be? I confirmed that my keychain-saving code was definitely creating new items in each case (rather than updating existing items), and was not getting any errors. And as I say, Keychain Services is giving a different persistent reference for each item. I've managed to solve my immediate problem by searching for keychain items by attribute rather than persistent references, but it would be easier to use persistent references so I'd appreciate solving this problem. Here's my code: - (NSString *)keychainItemWithName: (NSString *)name { NSString *path = [GLApplicationSupportFolder() stringByAppendingPathComponent: name]; NSData *persistentRef = [NSData dataWithContentsOfFile: path]; if (!persistentRef) { NSLog(@"no persistent reference for name: %@", name); return nil; } NSArray *refs = [NSArray arrayWithObject: persistentRef]; //get the data CFMutableDictionaryRef params = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue(params, kSecMatchItemList, refs); CFDictionaryAddValue(params, kSecClass, kSecClassGenericPassword); CFDictionaryAddValue(params, kSecReturnData, kCFBooleanTrue); CFDataRef item = NULL; OSStatus result = SecItemCopyMatching(params, (CFTypeRef *)&item); CFRelease(params); if (result != errSecSuccess) { NSLog(@"error %d retrieving keychain reference for name: %@", result, name); return nil; } NSString *token = [[NSString alloc] initWithData: (NSData *)item encoding: NSUTF8StringEncoding]; CFRelease(item); return [token autorelease]; } - (void)setKeychainItem: (NSString *)newToken forName: (NSString *)name { NSData *tokenData = [newToken dataUsingEncoding: NSUTF8StringEncoding]; //firstly, find out whether the item already exists NSDictionary *searchAttributes = [NSDictionary dictionaryWithObjectsAndKeys: name, kSecAttrAccount, kCFBooleanTrue, kSecReturnAttributes, nil]; NSDictionary *foundAttrs = nil; OSStatus searchResult = SecItemCopyMatching((CFDictionaryRef)searchAttributes, (CFTypeRef *)&foundAttrs); if (noErr == searchResult) { NSMutableDictionary *toStore = [foundAttrs mutableCopy]; [toStore setObject: tokenData forKey: (id)kSecValueData]; OSStatus result = SecItemUpdate((CFDictionaryRef)foundAttrs, (CFDictionaryRef)toStore); if (result != errSecSuccess) { NSLog(@"error %d updating keychain", result); } [toStore release]; return; } //need to create the item. CFMutableDictionaryRef params = CFDictionaryCreateMutable(NULL, 0, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFDictionaryAddValue(params, kSecClass, kSecClassGenericPassword); CFDictionaryAddValue(params, kSecAttrAccount, name); CFDictionaryAddValue(params, kSecReturnPersistentRef, kCFBooleanTrue); CFDictionaryAddValue(params, kSecValueData, tokenData); NSData *persistentRef = nil; OSStatus result = SecItemAdd(params, (CFTypeRef *)&persistentRef); CFRelease(params); if (result != errSecSuccess) { NSLog(@"error %d from keychain services", result); return; } NSString *path = [GLApplicationSupportFolder() stringByAppendingPathComponent: name]; [persistentRef writeToFile: path atomically: NO]; [persistentRef release]; }

    Read the article

  • Facebook invites partialy working..

    - by dugi007
    Hello! im new to facebook api and i have a litle problem.. i created iframe app and im using the folowing code to invite my friends. invitation screen renders and im able to send invitation. when someone accepts invitation it redirects them to the following link: http://www.facebook.com/reqs.php#!//apps.facebook.com/erste_app/ and nothing happens (only the facebook header apears and thats all)...when they manualy repost that link they are redirected to app and everything works... <?php include 'facebook.php'; define( 'FB_API_KEY', 'e23463********9c7ebfd6d34' ); define( 'FB_SECRET', '5f6************7efff5c8cb8' ); define( 'FB_APPID', '312*********23' ); define( 'FB_CANVAS_URL', 'http://apps.facebook.com/erste_app/' ); define( 'FB_APP_HOME_URL', 'http://www.bijelarukavica.com/test/' ); define( 'FB_APP_NAME', 'Zaigraj s Rokom' ); $bOK=SendStandardInvitation("", false); function SendStandardInvitation($to, $bNewStyle = true) { $typeword = FB_APP_NAME; // Warning: double quotes in the content string will screw up the invite signature process $content = '<fb:req-choice url=\' ' . FB_CANVAS_URL . '\' label=\'Check out ' . FB_APP_NAME . ' />'; // if your have post add routines take them to that add app URL instead. $actionText = 'Probaj jesi bolji od mene uz "' . FB_APP_NAME . '".'; $bOK = SendNewRequest($to, $typeword, $content, $actionText); return $bOK; } function SendNewRequest($to, $typeword, $content, $actionText, $bInvitation = true) { $facebook = new Facebook(FB_API_KEY,FB_SECRET); $to = implode(",", $facebook->api_client->friends_get('','')); $bInviteAll = (!$to || $to == "" ? true : false); $excludeFriends = null; if (!$bInviteAll) $excludeFriends = $facebook->api_client->friends_get(); else // Get all friends with the app $excludeFriends = $facebook->api_client->friends_getAppUsers(); $excludeFriendsStr = null; foreach ($excludeFriends as $userid) { $pos = strpos($to, (string)$userid); if ($pos !== false) continue; if ($excludeFriendsStr) $excludeFriendsStr .= ','; $excludeFriendsStr .= $userid; } $params = array(); $params['api_key'] = FB_API_KEY; $params['content'] = $content; // Don't use htmlentities() or urlencode() here $params['type'] = $typeword; $params['action'] = FB_CANVAS_URL ; $params['actiontext'] = $actionText; $params['invite'] = ($bInvitation ? 'true' : 'false'); $params['rows'] = '5'; $params['max'] = '20'; $params['exclude_ids'] = $excludeFriendsStr; $params['sig'] = $facebook->generate_sig($params, FB_SECRET); $qstring = null; foreach ($params as $key => $value) { if ($qstring) $qstring .= '&'; $qstring .= "$key=".urlencode($value); } $inviteUrl = 'http://www.facebook.com/multi_friend_selector.php?'; $facebook->redirect($inviteUrl . $qstring); return true; } $facebook->api_client->notifications_sendRequest function SendRequest($to, $typeword, $content, $bInvitation = true) { $facebook = new Facebook(FB_API_KEY,FB_SECRET); $image = FB_APP_HOME_URL . 'logo.gif'; $result = $facebook->api_client->notifications_sendRequest($to, $typeword, $content, $image, $bInvitation); $url = $result; if (isset($url) && $url) { $facebook->redirect($url . '&canvas=1&next=index.php'); return true; } $bOK = ($result && $result != ""); return $bOK; } SendStandardInvitation($to, $bNewStyle = false) ?>

    Read the article

  • Ultimate Get/Post with Android Thread for Dummies

    - by Jayomat
    Hi, I'm writing an app to check for the bus timetable's. Therefor I need to post some data to a html page, submit it, and parse the resulting page with htmlparser. Though it may be asked a lot, can some one help me identify if 1) this page does support post/get (I think it does) 2) which fields I need to use? 3) How to make the actual request? this is my code so far: String url = "http://busspur02.aseag.de/bs.exe?Cmd=RV&Karten=true&DatumT=30&DatumM=4&DatumJ=2010&ZeitH=&ZeitM=&Suchen=%28S%29uchen&GT0=&HT0=&GT1=&HT1="; String charset = "CP1252"; System.out.println("startFrom: "+start_from); System.out.println("goTo: "+destination); //String tag.v List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("HTO", start_from)); params.add(new BasicNameValuePair("HT1", destination)); params.add(new BasicNameValuePair("GTO", "Aachen")); params.add(new BasicNameValuePair("GT1", "Aachen")); params.add(new BasicNameValuePair("DatumT", day)); params.add(new BasicNameValuePair("DatumM", month)); params.add(new BasicNameValuePair("DatumJ", year)); params.add(new BasicNameValuePair("ZeitH", hour)); params.add(new BasicNameValuePair("ZeitM", min)); UrlEncodedFormEntity query = new UrlEncodedFormEntity(params, charset); HttpPost post = new HttpPost(url); post.setEntity(query); InputStream response = new DefaultHttpClient().execute(post).getEntity().getContent(); // Now do your thing with the facebook response. String source = readText(response,"CP1252"); Log.d(TAG_AVV,response.toString()); System.out.println("STREAM "+source); One person also gave me a hint to use firebug to read what's going on at the page, but I don't really understand what to look for, or more precisely, how to use the provided information. I also find it confusing, for example, that when I enter the data by hand, the url says, for example, "....HTO=Kaiserplatz&...", but in Firebug, the same Kaiserplatz is connected to a different field, in this case: \<\td class="Start3" Kaiserplatz <\/td (I inserted \ to make it visible) The last line in my code prints the html page, but without having send a request.. it's printed as if there was no input at all... My app is almost done, I hope someone can help me out to finish it! thanks in advance

    Read the article

  • Codeigniter or PHP Amazon API help

    - by faya
    Hello, I have a problem searching through amazon web servise using PHP in my CodeIgniter. I get InvalidParameter timestamp is not in ISO-8601 format response from the server. But I don't think that timestamp is the problem,because I have tryed to compare with given date format from http://associates-amazon.s3.amazonaws.com/signed-requests/helper/index.html and it seems its fine. Could anyone help? Here is my code: $private_key = 'XXXXXXXXXXXXXXXX'; // Took out real secret key $method = "GET"; $host = "ecs.amazonaws.com"; $uri = "/onca/xml"; $timeStamp = gmdate("Y-m-d\TH:i:s.000\Z"); $timeStamp = str_replace(":", "%3A", $timeStamp); $params["AWSAccesskeyId"] = "XXXXXXXXXXXX"; // Took out real access key $params["ItemPage"] = $item_page; $params["Keywords"] = $keywords; $params["ResponseGroup"] = "Medium2%2525COffers"; $params["SearchIndex"] = "Books"; $params["Operation"] = "ItemSearch"; $params["Service"] = "AWSECommerceService"; $params["Timestamp"] = $timeStamp; $params["Version"] = "2009-03-31"; ksort($params); $canonicalized_query = array(); foreach ($params as $param=>$value) { $param = str_replace("%7E", "~", rawurlencode($param)); $value = str_replace("%7E", "~", rawurlencode($value)); $canonicalized_query[] = $param. "=". $value; } $canonicalized_query = implode("&", $canonicalized_query); $string_to_sign = $method."\n\r".$host."\n\r".$uri."\n\r".$canonicalized_query; $signature = base64_encode(hash_hmac("sha256",$string_to_sign, $private_key, True)); $signature = str_replace("%7E", "~", rawurlencode($signature)); $request = "http://".$host.$uri."?".$canonicalized_query."&Signature=".$signature; $response = @file_get_contents($request); if ($response === False) { return "response fail"; } else { $parsed_xml = simplexml_load_string($response); if ($parsed_xml === False) { return "parse fail"; } else { return $parsed_xml; } } P.S. - Personally I think that something is wrong in the generation of the from the $string_to_sign when hashing it.

    Read the article

  • Why is cakephp form input stored in $this->data and POST data stored in $this->params['form'] ?

    - by spudnik1979
    the cakephp rest tutorial says that post data should be in $this-data, but I am finding that it is not, but instead inside $this-params['form'] However, when using cakephp form helper in a view, the data is in $this-data. Am I correct to have to check both locations in my controller? It just seems a bit of a waste of extra code. Shouldnt the data appear in one place for whether it came from a rest rest requestor or Cakephp form post? ps im using cakephp 1.3

    Read the article

  • Is this a good implementation of DefaultHttpClient and ThreadSafeClientConnManager in Android?

    - by johnrock
    In my Android app I am sharing one httpclient for all activities/threads. All requests are made by callling getHttpClient().execute(httpget) or getHttpClient().execute(httppost). Is this implementation complete/correct and safe for multiple threads? Is there anything else missing i.e. Do I have to worry about releasing connections at all? private static HttpClient httpclient ; public static HttpClient getHttpClient() { if(httpclient == null){ return getHttpClientNew(); } else{ return httpclient; } } public static synchronized HttpClient getHttpClientNew() { HttpParams params = new BasicHttpParams(); ConnManagerParams.setMaxTotalConnections(params, 100); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, "UTF_8"); HttpProtocolParams.setUseExpectContinue(params, false); HttpConnectionParams.setConnectionTimeout(params, 10000); HttpConnectionParams.setSoTimeout(params, 10000); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); httpclient = new DefaultHttpClient(cm, params); return httpclient; } This is an example of how the httpclient is used: private void update() { HttpGet httpget = new HttpGet(URL); httpget.setHeader(USER_AGENT, userAgent); httpget.setHeader(CONTENT_TYPE, MGUtils.APP_XML); HttpResponse response; try { response = getHttpClient().execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { // parse stuff } } catch (Exception e) { } }

    Read the article

  • Rails PDF Generation with Prawn in IE7

    - by fluid_chelsea
    I'm using Prawn and Prawnto to generate a PDF in a Ruby on Rails app (Rails version 2.2.2) which works great and generates PDFs happily and sends them to the user to download in Firefox. The problem is in IE7. I have a route set up like so: map.invoice_pdf '/invoices.pdf', :controller => 'invoices', :action => 'index', :format => 'pdf' Which I then have a link like so to call: invoice_pdf_path(:year => params[:year], :month => params[:month], :unpaid_only => params[:unpaid_only]) And the following in my controller: def index params[:year] = default params[:year] params[:month] = default params[:month] params[:page] ||= 1 @invoices = Arobl.find_invoices_for_customer(current_customer.strCustomerID, params) respond_to do |format| format.html{ render :action => 'index' } format.pdf{ prawnto :inline => false, :filename => "#{current_customer.strCustomerID}_invoice.pdf" end In FF this works as expected, when the link is clicked the show action is invoked with a format of .pdf, and responds with the correctly named PDF. When it's hit with IE7 it says that the file or website could not be found, and references "invoices.pdf" instead of the expected customer_id_invoice.pdf filename. Any idea what could be causing this behaviour? Thanks!

    Read the article

  • Rails add a param to the end of a search query

    - by bob
    Hello, I am trying to implement a sort on the returned results of a search with rails. Filter by: 'recent' % | 'lowest_price' % | 'highest_price' % here are my links. I would like to add a filter to the end of my search query. So for example, I submit a search and I get back results and in my url I have http://localhost:3000/junks?search=handbag&condition=&category=&main_submit=Go! I would then like the user to be able to click one of the above links and have the page come back with a new query (i have this set up in the controller like such) con_id = params[:condition] if params[:category].nil? || params[:category].empty? cat_id = params[:category] results = Junk.search params[:search], :with => { :category_id => cat_id, :condition_id => con_id } case params[:filter] when "lowest_price" @junks = results.lowest_price.paginate :page => params[:page], :per_page => 12 when "highest_price" @junks = results.highest_price.paginate :page => params[:page], :per_page => 12 else @junks = results.paginate :page => params[:page], :per_page => 12 end else I would like the user to be able to click on of the above links and append a filter param to the end of the search query so that my controller can pick it up and call the correct database queries as seen in the case statement above. I'm guessing the url will look like this http://localhost:3000/junks?search=handbag&condition=&category=&main_submit=Go!&filter="lowest_price" How can I do this? Is there a better way?

    Read the article

  • How to pass PHP variable as FlashVars via SWFObject

    - by Matt
    I am trying to take a PHP variable and pass it along to Flash via Flash vars. My end goal is to pass a string formatted as XML to Flash, but because I'm struggling I've stripped everything down to the basics. I'm just trying to pass a simple PHP string variable to Flash via FlashVars with SWFObject but something isn't right. The page won't load when I try to pass the variable inside of php tags, but it will load if I just pass a hard coded string. The basic structure of my page is that I have some PHP declared at the top like so: PHP <?php $test = "WTF"; ?> Some HTML (excluded here for simplicity sake) and then the JavaScript SWFObject Embed within my HTML: <script type="text/javascript" src="js/swfobject2.js"></script> <script type="text/javascript"> // <![CDATA[ var swfURL = "swfs/Init-Flash-PHP.swf"; var flashvars = {}; flashvars.theXML = <?php print $test ?>; var params = {}; //params.menu = "false"; params.scale = "showAll"; params.bgcolor = "#000000"; params.salign = "TL"; //params.wmode = "transparent"; params.allowFullScreen = "true"; params.allowScriptAccess = "always"; var attributes = {}; attributes.id = "container"; attributes.name = "container"; swfobject.embedSWF(swfURL, "container", '100%', '100%', "9.0.246", "elements/swfs/expressinstall.swf", flashvars, params, attributes); // ]]> </script> And the bare essentials of the ActionScript 3 Code: _paramObj = LoaderInfo(stage.loaderInfo).parameters; theText_txt.text = _paramObj['theXML']; How do I pass a PHP variable using SWFObject and FlashVars? Thanks.

    Read the article

  • Hiding Command Prompt with CodeDomProvider

    - by j-t-s
    Hi All I've just got my own little custom c# compiler made, using the article from MSDN. But, when I create a new Windows Forms application using my sample compiler, the MSDOS window also appears, and if I close the DOS window, my WinForms app closes too. How can I tell the Compiler? not to show the MSDOS window at all? Thank you :) Here's my code: using System; namespace JTS { public class CSCompiler { protected string ot, rt, ss, es; protected bool rg, cg; public string Compile(String se, String fe, String[] rdas, String[] fs, Boolean rn) { System.CodeDom.Compiler.CodeDomProvider CODEPROV = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("CSharp"); ot = fe; System.CodeDom.Compiler.CompilerParameters PARAMS = new System.CodeDom.Compiler.CompilerParameters(); // Ensure the compiler generates an EXE file, not a DLL. PARAMS.GenerateExecutable = true; PARAMS.OutputAssembly = ot; PARAMS.CompilerOptions = "/target:winexe"; PARAMS.ReferencedAssemblies.Add(typeof(System.Xml.Linq.Extensions).Assembly.Location); PARAMS.LinkedResources.Add("this.ico"); foreach (String ay in rdas) { if (ay.Contains(".dll")) PARAMS.ReferencedAssemblies.Add(ay); else { string refd = ay; refd = refd + ".dll"; PARAMS.ReferencedAssemblies.Add(refd); } } System.CodeDom.Compiler.CompilerResults rs = CODEPROV.CompileAssemblyFromFile(PARAMS, fs); if (rs.Errors.Count > 0) { foreach (System.CodeDom.Compiler.CompilerError COMERR in rs.Errors) { es = es + "Line number: " + COMERR.Line + ", Error number: " + COMERR.ErrorNumber + ", '" + COMERR.ErrorText + ";" + Environment.NewLine + Environment.NewLine; } } else { // Compilation succeeded. es = "Compilation Succeeded."; if (rn) System.Diagnostics.Process.Start(ot); } return es; } } }

    Read the article

< Previous Page | 6 7 8 9 10 11 12 13 14 15 16 17  | Next Page >