Search Results

Search found 1421 results on 57 pages for 'arbitrary'.

Page 4/57 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Tweak Data in Doctrine Migration (say, by running some arbitrary queries)

    - by timdev
    I've got a migration that creates a couple of columns that act as foreign keys. In particular, I'm adding a creator_id and owner_id column to a model. These foreign keys indicate who created, and who currently owns, a particular kind of domain object. Users are managed by sfDoctrineGuardPlugin. What I'd like to do, for the purpose of the migration, is look up the (active) user with the lowest id, and default creator_id/owner_id to that. I don't see any particularly obvious/proper way to run arbitrary operations on the database during a migration. Does anyone know how?

    Read the article

  • ASP.net MVC 3 adding arbitrary text to the end of an ActionLink

    - by infensus
    Hi I have a question about Html.ActionLink. Imagine: @Html.ActionLink(item.title, "Singlet", new { id = item.blog_id }) produces http://[url]/[controller]/Singlet/[id] But what if I want to suffix some more arbitrary data at the end? For example: http://[url]/[controller]/Singlet/[id]/#comments To jump to the comments div. I know I can just make the string myself with something like: @( new HtmlString(String.Format("<a href=\"Blog/Singlet/{0}/#comments\">link to comments</a>", item.blog_id)) ) But I am hoping there is a cleaner way, perhaps with ActionLink? Thanks

    Read the article

  • Parsing and validating arbitrary date formats in ruby (on rails)

    - by Matt Briggs
    I have a requirement to handle custom date formats in an existing app. The idea is that the users have to do with multiple formats from outside sources they have very little control over. We will need to be able to take the format and both validate Dates against it, as well as parse strings specifically in that format. The other thing is that these can be completely arbitrary, like JA == January, FE == February, etc... to my understanding, chronic only handles parsing (and does it in a more magical way then I can use), and enter code here DateTime#strptime comes close, but doesn't really handle the whole two character month scenario, even with custom formatters. The 'nuclear' option is to write in custom support for edge cases like this, but I would prefer to use a library if something like this exists.

    Read the article

  • XNA 2d camera with arbitrary zoom center

    - by blooop
    I have a working 2D camera in XNA with these guts: ms = Mouse.GetState(); msv = new Vector2(ms.X, ms.Y); //screenspace mouse vecor pos = new Vector2(0, 0); //camera center of view zoom_center = cursor; //I would like to be able to define the zoom center in world coords offset = new Vector2(scrnwidth / 2, scrnheight / 2); transmatrix = Matrix.CreateTranslation(-pos.X, -pos.Y, 0) * Matrix.CreateScale(scale, scale, 1) * Matrix.CreateTranslation(offset.X, offset.Y, 0); inverse = Matrix.Invert(transmatrix); cursor = Vector2.Transform(msv, inverse); //the mouse position in world coords I can move the camera position around and change the zoom level (with other code that I have not pasted here for brevity). The camera always zooms around the center of the screen, but I would like to be able to zoom about an arbitrary zoom point (the cursor in this case), like the indie game dyson http://www.youtube.com/watch?v=YiwjjCMqnpg&feature=player_detailpage#t=144s I have tried all the combinations that make sense to me, but am completely stuck.

    Read the article

  • How to make a daemon which will accept arbitrary commands

    - by Jono
    Right now the program can be launched in a linux terminal. Once running you can type various commands and the program will do stuff on the machine until the user quits. I would like to make the program into a service that the user runs and it goes to the background. Then the user should be able to make commands to it. Like start and stop, and write something to a log and whatever else my program does. Note that I need to send it arbitrary commands that my program will handle, not just start and stop. Maybe this means it is no longer a daemon - I dont know. How do I do this? Also, if this is not too hard, I would like to be able to run multiple instances of this service. But it is not essential.

    Read the article

  • C++ associative array with arbitrary types for values

    - by Gerald Kaszuba
    What is the best way to have an associative array with arbitrary value types for each key in C++? Currently my plan is to create a "value" class with member variables of the types I will be expecting. For example: class Value { int iValue; Value(int v) { iValue = v; } std::string sValue; Value(std::string v) { sValue = v; } SomeClass *cValue; Value(SomeClass *v) { cValue = c; } }; std::map<std::string, Value> table; A downside with this is you have to know the type when accessing the "Value". i.e.: table["something"] = Value(5); SomeClass *s = table["something"].cValue; // broken pointer Also the more types that are put in Value, the more bloated the array will be. Any better suggestions?

    Read the article

  • A good way to look back arbitrary number of items in the Array.Fold in F#

    - by tk
    In the folder function of the Array.Fold operation, i want to look back arbitrary number of items. The only way i can figure out is like this. let aFolder (dataArray, curIdx, result) (dataItem) = let N = numItemsToLookBack(result, dataItem) let recentNitems = dataArray.[curIdx - n .. curIdx - 1] let result = aCalc(result, dataItem, recentNitems ) dataArray, curIdx + 1, result myDataArray | Array.fold aFolder (myDataArray, 0, initResult) As you can see, I passed the whole dataArray and index to the folder function to get the "recentNitems". But this way allows the folder function to access not only preceding data, but also the following data. Is there a better (or more functional) way?

    Read the article

  • Compute hex color code for an arbitrary string

    - by user222164
    Heading Is there a way to map an arbitrary string to a HEX COLOR code. I tried to compute the HEX number for string using string hashcode. Now I need to convert this hex number to six digits which are in HEX color code range. Any suggestions ? String [] programs = {"XYZ", "TEST1", "TEST2", "TEST3", "SDFSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS"}; for(int i = 0; i < programs.length; i++) { System.out.println( programs[i] + " -- " + Integer.toHexString(programs[i].hashCode())); }

    Read the article

  • Use a single freemarker template to display tables of arbitrary pojos

    - by Kevin Pauli
    Attention advanced Freemarker gurus: I want to use a single freemarker template to be able to output tables of arbitrary pojos, with the columns to display defined separately than the data. The problem is that I can't figure out how to get a handle to a function on a pojo at runtime, and then have freemarker invoke that function (lambda style). From skimming the docs it seems that Freemarker supports functional programming, but I can't seem to forumulate the proper incantation. I whipped up a simplistic concrete example. Let's say I have two lists: a list of people with a firstName and lastName, and a list of cars with a make and model. would like to output these two tables: <table> <tr> <th>firstName</th> <th>lastName</th> </tr> <tr> <td>Joe</td> <td>Blow</d> </tr> <tr> <td>Mary</td> <td>Jane</d> </tr> </table> and <table> <tr> <th>make</th> <th>model</th> </tr> <tr> <td>Toyota</td> <td>Tundra</d> </tr> <tr> <td>Honda</td> <td>Odyssey</d> </tr> </table> But I want to use the same template, since this is part of a framework that has to deal with dozens of different pojo types. Given the following code: public class FreemarkerTest { public static class Table { private final List<Column> columns = new ArrayList<Column>(); public Table(Column[] columns) { this.columns.addAll(Arrays.asList(columns)); } public List<Column> getColumns() { return columns; } } public static class Column { private final String name; public Column(String name) { this.name = name; } public String getName() { return name; } } public static class Person { private final String firstName; private final String lastName; public Person(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } } public static class Car { String make; String model; public Car(String make, String model) { this.make = make; this.model = model; } public String getMake() { return make; } public String getModel() { return model; } } public static void main(String[] args) throws Exception { final Table personTableDefinition = new Table(new Column[] { new Column("firstName"), new Column("lastName") }); final List<Person> people = Arrays.asList(new Person[] { new Person("Joe", "Blow"), new Person("Mary", "Jane") }); final Table carTable = new Table(new Column[] { new Column("make"), new Column("model") }); final List<Car> cars = Arrays.asList(new Car[] { new Car("Toyota", "Tundra"), new Car("Honda", "Odyssey") }); final Configuration cfg = new Configuration(); cfg.setClassForTemplateLoading(FreemarkerTest.class, ""); cfg.setObjectWrapper(new DefaultObjectWrapper()); final Template template = cfg.getTemplate("test.ftl"); process(template, personTableDefinition, people); process(template, carTable, cars); } private static void process(Template template, Table tableDefinition, List<? extends Object> data) throws Exception { final Map<String, Object> dataMap = new HashMap<String, Object>(); dataMap.put("tableDefinition", tableDefinition); dataMap.put("data", data); final Writer out = new OutputStreamWriter(System.out); template.process(dataMap, out); out.flush(); } } All the above is a given for this problem. So here is the template I have been hacking on. Note the comment where I am having trouble. <table> <tr> <#list tableDefinition.columns as col> <th>${col.name}</th> </#list> </tr> <#list data as pojo> <tr> <#list tableDefinition.columns as col> <td><#-- what goes here? --></td> </#list> </tr> </#list> </table> So col.name has the name of the property I want to access from the pojo. I have tried a few things, such as pojo.col.name and <#assign property = col.name/> ${pojo.property} but of course these don't work, I just included them to help convey my intent. I am looking for a way to get a handle to a function and have freemarker invoke it, or perhaps some kind of "evaluate" feature that can take an arbitrary expression as a string and evaluate it at runtime.

    Read the article

  • Mac OS X: Getting detailed process information (specifically its launch arguments) for arbitrary run

    - by Jasarien
    I am trying to detect when particular applications are launched. Currently I am using NSWorkspace, registering for the "did launch application" notification. I also use the runningApplications method to get apps that are currently running when my app starts. For most apps, the name of the app bundle is enough. I have a plist of "known apps" that I cross check with the name of that passed in the notification. This works fine until you come across an app that acts as a proxy for launching another application using command line arguments. Example: The newly released Portal on the Mac doesn't have a dedicated app bundle. Steam can create a shortcut, which serves as nothing more than to launch the hl2_osx app with the -game argument and portal as it's parameter. Since more Source based games are heading to the Mac, I imagine they'll use the same method to launch, effectively running the hl2_osx app with the -game argument. Is there a nice way to get a list of the arguments (and their parameters) using a Cocoa API? NSProcessInfo comes close, offering an `-arguments' method, but only provides information for its own process... NSRunningApplication offers the ability to get information about arbitrary apps using a PID, but no command line args... Is there anything that fills the gap between the two? I'm trying not to go down the route of spawning an NSTask to run ps -p [pid] and parsing the output... I'd prefer something more high level.

    Read the article

  • Storing Arbitrary Contact Information in Ruby on Rails

    - by Anthony Chivetta
    Hi, I am currently working on a Ruby on Rails app which will function in some ways like a site-specific social networking site. As part of this, each user on the site will have a profile where they can fill in their contact information (phone numbers, addresses, email addresses, employer, etc.). A simple solution to modeling this would be to have a database column per piece of information I allow users to enter. However, this seems arbitrary and limited. Further, to support allowing users to enter as many phone numbers as they would like requires the addition of another database table and joins. It seems to me that a better solution would be to serialize all the contact information entered by a user into a single field in their row. Since I will never be conditioning a SQL query on this information, such a solution wouldn't be any less efficient. Ideally, I would like to use a vCard as my serialization format. vCards are the standard solution to storing contact information across the web, and reusing tested solutions is a Good Thing. Alternative serialization formats would include simply marshaling a ruby hash, or YAML. Regardless of serialization format, supporting the reading and updating of this information in a rails-like way seems to be a major implementation challenge. So, here's the question: Has anyone seen this approach used in a rails application? Are there any rails plugins or gems that make such a system easy to implement? Ideally what I would like is an acts_as_vcard to add to my model object that would handle editing the vcard for me and saving it back to the database.

    Read the article

  • How to send arbitrary ftp commands in C#

    - by cchampion
    I have implemented the ability to upload, download, delete, etc. using the FtpWebRequest class in C#. That is fairly straight forward. What I need to do now is support sending arbitrary ftp commands such as quote SITE LRECL=132 RECFM=FB or quote SYST Here's an example configuration straight from our app.config: <!-- The following commands will be executed before any uploads occur --> <extraCommands> <command>quote SITE LRECL=132 RECFM=FB</command> </extraCommands> I'm still researching how to do this using FtpWebRequest. I'll probably try WebClient class next. Anyone can point me in the right direction quicker? Thanks! UPDATE: I've come to that same conclusion, as of .NET Framework 3.5 FtpWebRequest doesn't support anything except what's in WebRequestMethods.Ftp.*. I'll try a third party app recommended by some of the other posts. Thanks for the help!

    Read the article

  • Storing arbitrary data in HTML

    - by Rob Colburn
    What is the best way to embed data in html elements for later use? As an example, let's say we have jQuery returning some JSON from the server, and we want to dump that datat out to the user as paragraphs. However, we want to be able to attach meta-data to these elements, so we can events for these later. The way I tend to handle this, is with some ugly prefixing function handle_response(data) { var html = ''; for (var i in data) { html += '<p id="prefix_' + data[i].id + '">' + data[i].message + '</p>'; } jQuery('#log').html(html).find('p').click(function(){ alert('The ID is: ' + $(this).attr('id').substr(7)); }); } Alternatively, one can build a Form in the paragraph, and store your meta-data there. But, that often feels like overkill. This has been asked before in different ways, but I do not feel it's been answered well: http://stackoverflow.com/questions/432174/how-to-store-arbitrary-data-for-some-html-tags http://stackoverflow.com/questions/209428/non-standard-attributes-on-html-tags-good-thing-bad-thing-your-thoughts

    Read the article

  • Vim step-by-step: How do you line up arbitrary text by arbitrary delimiter?

    - by dreftymac
    Background: There are a lot of great tutorials and "tricks" pages for Vim, but one thing that is very difficult is to find specific instructions on how to do some arbitrary thing that one can easily do in one's own familiar text editor IDE. Therefore I am asking for step by step instructions on how you I would do something in Vim that I already know how to do in other text editors. I like Vim and the great built-in help and numerous on-line tutorials, but sometimes a human has to break down and ask another human. Question: Suppose I have the following code in my file, how can I use Vim to get from BEFORE, to AFTER? BEFORE: Lorem ipsum dolor | sit amet, consectetur | adipisicing elit, sed do eiusmod | tempor incididunt | ut labore et | dolore magna aliqua. | Ut enim ad minim veniam, quis nostrud | exercitation ullamco | laboris nisi ut | aliquip ex ea commodo | consequat. Duis aute irure AFTER: Lorem ipsum dolor | sit amet, consectetur | adipisicing elit, sed do eiusmod | tempor incididunt | ut labore et | dolore magna aliqua. | Ut enim ad minim veniam, quis nostrud | exercitation ullamco | laboris nisi ut | aliquip ex ea commodo | consequat. Duis aute irure

    Read the article

  • Good data structure for efficient insert/querying on arbitrary properties

    - by Juliet
    I'm working on a project where Arrays are the default data structure for everything, and every query is a linear search in the form of: Need a customer with a particular name? customer.Find(x => x.Name == name) Need a customer with a particular unique id? customer.Find(x => x.Id == id) Need a customer of a particular type and age? customer.Find(x => x is PreferredCustomer && x.Age >= age) Need a customer of a particular name and age? customer.Find(x => x.Name == name && x.Age == age) In almost all instances, the criteria for lookups is well-defined. For example, we only search for customers by one or more of the properties Id, Type, Name, or Age. We rarely search by anything else. Is a good data structure to support arbitrary queries of these types with lookup better than O(n)? Any out-of-the-box implementations for .NET?

    Read the article

  • How to find every possible combination of an arbitrary number of arrays in PHP

    - by Travis
    I have an arbitrary number of nested arrays in php. For example: Array ( [0] => Array ( [0] => 36 [0] => 2 [0] => 9 ) [1] => Array ( [0] => 95 [1] => 21 [2] => 102 [3] => 38 ) [2] => Array ( [0] => 3 [1] => 5 ) ) I want to find the most efficient way to combine all possible combinations of each of these nested arrays. I'd like to end up with something that looks like this... Array ( [0] => "36,95,3" [1] => "36,95,5" [2] => "36,21,3" [3] => "36,21,5" etc... ) The order the results are combined in is not important. That is to say, there is no difference between "3,95,36", "36,95,3", and "95,36,3". I would like to omit these redundant combinations. Any suggestions on how to go about this would be much appreciated. Thanks in advance,

    Read the article

  • Combine Arbitrary number of polygons together

    - by Jakobud
    I have an arbitrary number of polygons (hexes in this case) that are arranged randomly, but they are all touching another hex. Each individual hex has 6 x,y vertices. The vertex's are known for all the hexes. Can anyone point me in the direction of an algorithm that will combine all the hexes into a single polygon? Essentially I'm just looking for a function that spits out an array of vertex locations that are ordered in a way that when drawing lines from one to the next, it forms the polygon. This is my method so far: Create array of all the vertices for all the hexes. Determine the number of times a vertex occurs in the array If vertex is in the array 3+ times, delete the vertices from the array. If vertex is in the array 2 times, delete one of them. The next step is tricky though. I'm using canvas to draw out these polygons, which essentially involves drawing a line from one vertex to the next. So the order of the vertices in the final array is important. It can't be sorted arbitrarily. Also, I'm not looking for a "convex hull" algorithm, as that would not draw the polygon correctly. Are there any functions out there that do something like this? Am I on the right track or is there a better more efficient way?

    Read the article

  • How to store arbitrary data for some HTML tags

    - by nickf
    I'm making a page which has some interaction provided by javascript. Just as an example: links which send an AJAX request to get the content of articles and then display that data in a div. Obviously in this example, I need each link to store an extra bit of information: the id of the article. The way I've been handling it in case was to put that information in the href link this: <a class="article" href="#5"> I then use jQuery to find the a.article elements and attach the appropriate event handler. (don't get too hung up on the usability or semantics here, it's just an example) Anyway, this method works, but it smells a bit, and isn't extensible at all (what happens if the click function has more than one parameter? what if some of those parameters are optional?) The immediately obvious answer was to use attributes on the element. I mean, that's what they're for, right? (Kind of). <a articleid="5" href="link/for/non-js-users.html"> In my recent question I asked if this method was valid, and it turns out that short of defining my own DTD (I don't), then no, it's not valid or reliable. A common response was to put the data into the class attribute (though that might have been because of my poorly-chosen example), but to me, this smells even more. Yes it's technically valid, but it's not a great solution. Another method I'd used in the past was to actually generate some JS and insert it into the page in a <script> tag, creating a struct which would associate with the object. var myData = { link0 : { articleId : 5, target : '#showMessage' // etc... }, link1 : { articleId : 13 } }; <a href="..." id="link0"> But this can be a real pain in butt to maintain and is generally just very messy. So, to get to the question, how do you store arbitrary pieces of information for HTML tags?

    Read the article

  • replace XmlSlurper tag with arbitrary XML

    - by Misha Koshelev
    Dear All: I am trying to replace specific XmlSlurper tags with arbitrary XML strings. The best way I have managed to come up with to do this is: #!/usr/bin/env groovy import groovy.xml.StreamingMarkupBuilder def page=new XmlSlurper(new org.cyberneko.html.parsers.SAXParser()).parseText(""" <html> <head></head> <body> <one attr1='val1'>asdf</one> <two /> <replacemewithxml /> </body> </html> """.trim()) import groovy.xml.XmlUtil def closure closure={ bind,node-> if (node.name()=="REPLACEMEWITHXML") { bind.mkp.yieldUnescaped "<replacementxml>sometext</replacementxml>" } else { bind."${node.name()}"(node.attributes()) { mkp.yield node.text() node.children().each { child-> closure(bind,child) } } } } println XmlUtil.serialize( new StreamingMarkupBuilder().bind { bind-> closure(bind,page) } ) However, the only problem is the text() element seems to capture all child text nodes, and thus I get: <?xml version="1.0" encoding="UTF-8"?> <HTML>asdf<HEAD/> <BODY>asdf<ONE attr1="val1">asdf</ONE> <TWO/> <replacementxml>sometext</replacementxml> </BODY> </HTML> Any ideas/help much appreciated. Thank you! Misha p.s. Also, out of curiosity, if I change the above to the "Groovier" notation as follows, the groovy compiler thinks I am trying to access the ${node.name()} member of my test class. Is there a way to specify this is not the case while still not passing the actual builder object? Thank you! :) def closure closure={ node-> if (node.name()=="REPLACEMEWITHXML") { mkp.yieldUnescaped "<replacementxml>sometext</replacementxml>" } else { "${node.name()}"(node.attributes()) { mkp.yield node.text() node.children().each { child-> closure(child) } } } } println XmlUtil.serialize( new StreamingMarkupBuilder().bind { closure(page) } )

    Read the article

  • C# Memoization of functions with arbitrary number of arguments

    - by Lirik
    I'm trying to create a memoization interface for functions with arbitrary number of arguments, but I'm failing miserably. The first thing I tried is to define an interface for a function which gets memoized automatically upon execution: class EMAFunction:IFunction { Dictionary<List<object>, List<object>> map; class EMAComparer : IEqualityComparer<List<object>> { private int _multiplier = 97; public bool Equals(List<object> a, List<object> b) { List<object> aVals = (List<object>)a[0]; int aPeriod = (int)a[1]; List<object> bVals = (List<object>)b[0]; int bPeriod = (int)b[1]; return (aVals.Count == bVals.Count) && (aPeriod == bPeriod); } public int GetHashCode(List<object> obj) { // Don't compute hash code on null object. if (obj == null) { return 0; } // Get length. int length = obj.Count; List<object> vals = (List<object>) obj[0]; int period = (int) obj[1]; return (_multiplier * vals.GetHashCode() * period.GetHashCode()) + length;; } } public EMAFunction() { NumParams = 2; Name = "EMA"; map = new Dictionary<List<object>, List<object>>(new EMAComparer()); } #region IFunction Members public int NumParams { get; set; } public string Name { get; set; } public object Execute(List<object> parameters) { if (parameters.Count != NumParams) throw new ArgumentException("The num params doesn't match!"); if (!map.ContainsKey(parameters)) { //map.Add(parameters, List<double> values = new List<double>(); List<object> asObj = (List<object>)parameters[0]; foreach (object val in asObj) { values.Add((double)val); } int period = (int)parameters[1]; asObj.Clear(); List<double> ema = TechFunctions.ExponentialMovingAverage(values, period); foreach (double val in ema) { asObj.Add(val); } map.Add(parameters, asObj); } return map[parameters]; } public void ClearMap() { map.Clear(); } #endregion } Here are my tests of the function: private void MemoizeTest() { DataSet dataSet = DataLoader.LoadData(DataLoader.DataSource.FROM_WEB, 1024); List<String> labels = dataSet.DataLabels; Stopwatch sw = new Stopwatch(); IFunction emaFunc = new EMAFunction(); List<object> parameters = new List<object>(); int numRuns = 1000; long sumTicks = 0; parameters.Add(dataSet.GetValues("open")); parameters.Add(12); // First call for(int i = 0; i < numRuns; ++i) { emaFunc.ClearMap();// remove any memoization mappings sw.Start(); emaFunc.Execute(parameters); sw.Stop(); sumTicks += sw.ElapsedTicks; } Console.WriteLine("Average ticks not-memoized " + (sumTicks/numRuns)); sumTicks = 0; // Repeat call for (int i = 0; i < numRuns; ++i) { sw.Start(); emaFunc.Execute(parameters); sw.Stop(); sumTicks += sw.ElapsedTicks; } Console.WriteLine("Average ticks memoized " + (sumTicks/numRuns)); } The performance is confusing me... I expected the memoized function to be faster, but it didn't work out that way: Average ticks not-memoized 106,182 Average ticks memoized 198,854 I tried doubling the data instances to 2048, but the results were about the same: Average ticks not-memoized 232,579 Average ticks memoized 446,280 I did notice that it was correctly finding the parameters in the map and it going directly to the map, but the performance was still slow... I'm either open for troubleshooting help with this example, or if you have a better solution to the problem then please let me know what it is.

    Read the article

  • .NET invoking against an arbitrary control.

    - by kerkeslager
    I have a method which takes in a .NET control and calls invoke against it like so: Form.Invoke(Target); However, I've run into an issue numerous times calling this method where due to timing or whatever, the form handle on the form doesn't exist, causing a Invoke or BeginInvoke cannot be called on a control until the window handle has been created error. In frustration, I jokingly changed the code to: MainForm.Invoke(Target); where MainForm is the main window of the application (the form handle for the main form is created at startup and remains active for the entire life cycle of the application). I ran all the tests and manually tested the application and everything seems to work fine despite the fact that this is used everywhere. So my question is, what exactly is the meaning of invoking against a specific control? Is there any downside to just always invoking against a control you know will be active? If not, why does .NET have you invoke against a control in the first place (instead of just creating a static GuiThread.InvokeOnGuiThread(Blah);)?

    Read the article

  • Get Mechanize to handle cookies from an arbitrary POST (to log into a website programmatically)

    - by Horace Loeb
    I want to log into https://www.t-mobile.com/ programmatically. My first idea was to use Mechanize to submit the login form: However, it turns out that this isn't even a real form. Instead, when you click "Log in" some javascript grabs the values of the fields, creates a new form dynamically, and submits it. "Log in" button HTML: <button onclick="handleLogin(); return false;" class="btnBlue" id="myTMobile-login"><span>Log in</span></button> The handleLogin() function: function handleLogin() { if (ValidateMsisdnPassword()) { // client-side form validation logic var a = document.createElement("FORM"); a.name = "form1"; a.method = "POST"; a.action = mytmoUrl; // defined elsewhere as https://my.t-mobile.com/Login/LoginController.aspx var c = document.createElement("INPUT"); c.type = "HIDDEN"; c.value = document.getElementById("myTMobile-phone").value; // the value of the phone number input field c.name = "txtMSISDN"; a.appendChild(c); var b = document.createElement("INPUT"); b.type = "HIDDEN"; b.value = document.getElementById("myTMobile-password").value; // the value of the password input field b.name = "txtPassword"; a.appendChild(b); document.body.appendChild(a); a.submit(); return true } else { return false } } I could simulate this form submission by POSTing the form data to https://my.t-mobile.com/Login/LoginController.aspx with Net::HTTP#post_form, but I don't know how to get the resultant cookie into Mechanize so I can continue to scrape the UI available when I'm logged in. Any ideas?

    Read the article

  • Graph Algorithm To Find All Paths Between N Arbitrary Vertices

    - by russtbarnacle
    I have an graph with the following attributes: Undirected Not weighted Each vertex has a minimum of 2 and maximum of 6 edges connected to it. Vertex count will be < 100 I'm looking for paths between a random subset of the vertices (at least 2). The paths should simple paths that only go through any vertex once. My end goal is to have a set of routes so that you can start at one of the subset vertices and reach any of the other subset vertices. Its not necessary to pass through all the subset nodes when following a route. All of the algorithms I've found (Dijkstra,Depth first search etc.) seem to be dealing with paths between two vertices and shortest paths. Is there a known algorithm that will give me all the paths (I suppose these are subgraphs) that connect these subset of vertices?

    Read the article

  • Display arbitrary size 2d image in opengl

    - by Martin Beckett
    I need to display 2d images in opengl using textures. The image dimensions are not necessarily powers of 2. I thought of creating a larger texture and restricting the display to the part I was using but the image data will be shared with openCV so I don't want to copy data a pixel at a time into a larger texture. EDIT - it turns out that even the simplest Intel on board graphics under Windows supports none-power-of-2 textures.

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >