pid
int64 2.28k
41.1M
| label
int64 0
1
| text
stringlengths 1
28.3k
|
---|---|---|
29,295,880 | 0 | <p>Heres a tutorial-ish thing:</p> <p><a href="https://robots.thoughtbot.com/designing-for-ios-blending-modes" rel="nofollow">Blending Modes in iOS</a></p> <p>And here is the <a href="https://developer.apple.com/library/ios/documentation/GraphicsImaging/Reference/CGContext/index.html#//apple_ref/doc/c_ref/CGBlendMode" rel="nofollow">Apple Documentation</a> that covers blend modes. Should get you on the right track. The exact formulas are shown for each blend mode option.</p> <p>Finally, see this answer:</p> <p><a href="http://stackoverflow.com/a/8354632/2079103">How to get the color of a displayed pixel</a></p> |
23,215,562 | 0 | <p>The answer suggested in the comment by @h0lyalg0rithm is an option to go.</p> <p>However, primitive options are.</p> <ol> <li><p>Use setinterval in javascript to perform a task every x seconds. Say polling.</p></li> <li><p>Use jQuery or native ajax to poll for information to a controller/action via route and have the controller push data as JSON.</p></li> <li><p>Use document.getElementById or jQuery to update data on the page.</p></li> </ol> |
6,421,694 | 0 | Where to put the database access <p>I have an entity class which is persisted to a database via JPA and I have a Utility class which does the persisting and reading for me.</p> <p>Now I'm asking myself if that is really the way to go. Wouldn't it be clearer, if the data class would have methods for reading and writing to the database?</p> |
33,624,861 | 0 | <p>Try this one, it should do exactly what you want:</p> <pre><code>let date = NSDate() let dateFormetter = NSDateFormatter() dateFormetter.dateFormat = "h:mm a" dateFormetter.timeZone = NSTimeZone(name: "UTC") dateFormetter.locale = NSLocale(localeIdentifier: "en_GB") let timeString = dateFormetter.stringFromDate(date) // 7:34 a.m. </code></pre> |
4,751,734 | 0 | <p><strong>Example:</strong> <a href="http://jsfiddle.net/EpbVc/" rel="nofollow">http://jsfiddle.net/EpbVc/</a></p> <pre><code>var value = $('#personName').val().split(' '); var firstName = value.shift(); var restOfNames = value.join(' '); </code></pre> <p>Uses <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split" rel="nofollow"><code>.split()</code></a> to split on a single space. If there could be multiple spaces, you could use <code>.split(/\s+/)</code>. </p> <p>Then it uses <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/shift" rel="nofollow"><code>.shift()</code></a> to remove the first item from the Array, and assign it to <code>firstName</code>.</p> <p>Finally it uses <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/join" rel="nofollow"><code>.join()</code></a> to join the rest of the Array into a string using a single space as the separator.</p> |
38,504,311 | 0 | <p>You can simple parse that date as shown below.</p> <pre><code>package com.test; import java.text.ParseException; import java.text.SimpleDateFormat; public class Sample { public static void main(String[] args) throws ParseException { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); System.out.println(sdf.parse("2016-07-21T11:25:00.000+01:00")); } } </code></pre> |
19,316,023 | 0 | <p>Short Answer : <strong>No</strong></p> <p>Workaround : Use Javascript or jQuery using <code>.toggle()</code></p> <hr> <p>If you want to stick with CSS, you can do something like</p> <pre><code>div[style*="block"] + div { display: none; } </code></pre> <p><a href="http://jsfiddle.net/nvLvU/" rel="nofollow"><strong>Demo</strong></a></p> <p>The above selector will see whether <code>div</code> having an attribute of <code>style</code> contains a value called <code>block</code> if yes, than hide the <code>adjacent</code> <code>div</code> element using <code>+</code></p> |
17,969,161 | 0 | <pre><code>update player set productName= concat("super ",productName) </code></pre> |
2,328,836 | 0 | How to average elements in one array based on values in another array? <pre><code>let tiedArray = [|9.4;1.2;-3.4;-3.4;-3.4;-3.4;-10.0|]; let sortedArray = [|-10.0;-3.4;-3.4;-3.4;-3.4;1.2;9.4|]; let sortedArrayRanks = [|1.;2.;3.;4.;5.;6.;7.|]; let desired_ranked_array = [|1.;3.5;3.5;3.5;3.5;6.;7.|] </code></pre> <p>hello-</p> <p>I am trying to write a function that takes 2 arrays (sortedArray and sortedArrayRanks) and return an output array like the one below. The mapping function in this example would take 2,3,4, and 5 in sortedArrayRanks and see that they all have the same value in sortedArray, and instead replace all of those numbers in an output array with the average of them (which is 3.5)</p> <p>What's tripping me up is whether to use recursion or an imperative looping contruct, like loop through sorted array, and see if an item is the same one that preceded it, and then if it matches, check the one before it, etc. How can this be solved? Thanks!</p> |
7,810,136 | 0 | <p>Events are raised, delegates are called. So when the button is clicked, a <code>buttonClick</code> event is raised, meaning that each delegate subscribed to the event will be called, according to the subscription order.</p> |
2,156,746 | 0 | JavaScript regular expressions - match a series of hexadecimal numbers <p>Greetings JavaScript and regular expression gurus,</p> <p>I want to return all matches in an input string that are 6-digit hexadecimal numbers with any amount of white space in between. For example, "333333 e1e1e1 f4f435" should return an array:</p> <pre><code>array[0] = 333333 array[1] = e1e1e1 array[2] = f4f435 </code></pre> <p>Here is what I have, but it isn't quite right-- I'm not clear how to get the optional white space in there, and I'm only getting one match.</p> <blockquote> <p>colorValuesArray = colorValues.match(/[0-9A-Fa-f]{6}/);</p> </blockquote> <p>Thanks for your help,</p> <p>-NorthK</p> |
29,659,414 | 0 | <p>No there are no operators built-in to the language specifically for generating sequences, but you can re-purpose some existing methods for sequence generation. </p> <p>For example:</p> <pre><code>[...Array(5)].map((x, y) => y*2); // Array [ 0, 2, 4, 6, 8 ] </code></pre> |
25,529,862 | 0 | <p>Your glob for your watch seems to be wrong. Try this:</p> <pre><code>gulp.watch(['app/scripts/**/*.js', '!app/scripts/dist.js'], ['scripts']).on('change', function(evt) { changeEvent(evt); }); </code></pre> <p>Use the exclude pattern for your <code>dist.js</code> to avoid an infinite loop.</p> <p>Ciao Ralf</p> |
7,437,849 | 0 | <p>Maybe they (the authors) didn't mean for you to try to compile that code, but just to understand the example and maybe implement it yourself.</p> |
3,441,200 | 0 | Change management in WordPress <p>I have a beginner question. What is the best way to address the change management issues in WordPress? I have an all-pages WordPress installation. Suppose name of some event or an entity changes from A to B, then I have to go to all the pages to make that change. Is there any better way of doing it? Like externalization or something. Or the way similar to how WordPress handle blog name using bloginfo() function. You change blog name at one place and it is reflected everywhere.</p> <p>Thanks, Paras</p> |
29,720,401 | 0 | <p>Try using local storage in JavaScript. To store a string:</p> <pre><code>localStorage.setItem('Name of Value', JSON.stringify("Your String")); </code></pre> <p>To retrieve string:</p> <pre><code>var retrievedObject = JSON.parse(localStorage.getItem('Name of Value')); </code></pre> |
8,651,613 | 0 | <p>Use <code>.Distinct()</code>. Since you can't use the default comparer, you can implement one like this</p> <pre><code>class MyEqualityComparer : IEqualityComparer<Comment> { public bool Equals(Comment x, Comment y) { return x.Sender.Equals(y.Sender); } public int GetHashCode(Comment obj) { return obj.Sender.GetHashCode(); } } </code></pre> <p>And then just filter them like this. You don't need the <code>if</code> statement.</p> <pre><code>List<Comment> StreamItemComments = objStreamItem.GetComments() .Distinct(new MyEqualityComparer()) .Where(x => x.Sender != ClientUser.UserName) .ToList(); </code></pre> |
10,441,434 | 0 | <p>You haven't exactly defined how you want to use diagonal lines so you will have to write the final function as you need it, i suppose taking the path with shortest length of those that use diagonals, noting that path from a>c is shorter than path a>b>c for a,b,c in path</p> <pre><code>grid = [[False]*16 for i in range(16)] #mark grid of walls def rect(p1,p2): x1, y1 = p1 x2, y2 = p2 for x in range(x1, x2+1): for y in range(y1, y2+1): yield (x, y) rects = [((1,2),(5,5)), ((5,5),(14,15)), ((11,5),(11,11)), ((5,11),(11,11)), ((4,7),(5,13)), ((5,13),(13,13))] for p1,p2 in rects: for point in rect(p1,p2): x,y = point grid[x][y] = True start = (1,2) end = (12,13) assert(grid[start[0]][start[1]]) assert(grid[end[0]][end[1]]) def children(parent): x,y = parent surrounding_points = ((x1,y1) for x1 in range(x-1,x+2) for y1 in range(y-1,y+2) if x1>0 and y<15) for x,y in surrounding_points: if grid[x][y]: #not a wall grid[x][y] = False #set as wall since we have been there already yield x,y path = {} def bfs(fringe): if end in fringe: return new_fringe = [] for parent in fringe: for child in children(parent): path[child] = parent new_fringe.append(child) del fringe if new_fringe: bfs(new_fringe) bfs([start]) def unroll_path(node): if node != start: return unroll_path(path[node]) + [node] else: return [start] path = unroll_path(end) def get_final_path_length(path): #return length of path if using straight lines for i in range(len(path)): for j in range(i+1,len(path)): #if straight line between pathi and pathj return get_final_path(path[j+1:]) + distance_between_i_and_j </code></pre> |
5,124,407 | 0 | <p>You would have to create your own custom <code>DialogPreference</code> for this in Java. There is no way to accomplish it through the preference XML.</p> |
1,961,863 | 0 | Why does Ruby require .call for Proc invocation? <p>I just wondered whether there is any good reason for or even an advantage in having to invoke <code>Proc</code>s using <code>proc.call(args)</code> in Ruby, which makes higher-order function syntax much more verbose and less intuitive.</p> <p>Why not just <code>proc(args)</code>? Why draw a distinction between functions, lambdas and blocks? Basically, it's all the same thing so why this confusing syntax? Or is there any point for it I don't realize?</p> |
31,711,728 | 0 | <p>You can just use a Dart script for your settings. No point in using a different format if there is no specific reason. With a simple import you have it available in a typed way. </p> |
15,274,285 | 0 | <p>Why are you doing that, just append an image.</p> <pre><code>$("#target").append("<img src='img.jpg' />"); </code></pre> <p>other way</p> <pre><code>$('<img/>', { src: 'img.jpg' }).appendTo("#target"); </code></pre> |
23,329,738 | 0 | <p>Vinai published a great writeup on Magento and Composer <a href="http://magebase.com/magento-tutorials/composer-with-magento/" rel="nofollow noreferrer">here</a>. </p> <p>Quoting from there</p> <blockquote> <p>Composer will use packagist.org to look where to get the libraries. Because Magento modules aren’t listed there, you will have to add the packages.firegento.org repository to the configuration as follows [...]</p> </blockquote> <p>So you will need the repository</p> <pre><code> "repositories":[ { "type":"composer", "url":"http://packages.firegento.com" } ], </code></pre> <p>to get the magento composer installer.</p> <p>And yes composer offers replacements. On the packaging entry for <a href="https://packagist.org/packages/aoepeople/composer-installers" rel="nofollow noreferrer">aoepeople/composer-installers</a> you will notice the replaces section:</p> <p><img src="https://i.stack.imgur.com/HBiXf.png" alt="Package Screenshot"></p> <p>And since <code>magento-hackathon/magento-composer-installer</code> is not available on packagist composer will deliver you <code>aoepeople/composer-installers</code>.</p> |
10,896,509 | 0 | <p>Sorry, I didn't understand the question exactly then.</p> <p>If you want to embed .swf files using javascript, I'd recommend you to use swfobject.</p> <p>I made an example here:</p> <p><a href="http://jsfiddle.net/ZGGCj/" rel="nofollow">http://jsfiddle.net/ZGGCj/</a></p> <p>swfobject is documented pretty well here:</p> <p><a href="http://code.google.com/p/swfobject" rel="nofollow">http://code.google.com/p/swfobject</a></p> |
29,342,421 | 0 | <p>You can try the regex <code>\b$</code> which ensures there's a match where a 'word' ends, and replace with <code> - digit</code> (or <code>\b(\n|$)</code> with a replacement of <code> - digit$1</code> if you don't want to use multiline)</p> <p><a href="https://regex101.com/r/kZ1gX6/1" rel="nofollow">regex101 demo</a></p> |
380,986 | 0 | <p><a href="http://nerds.palmdrive.net/useragent/code.html" rel="nofollow noreferrer" title="User-Agent detection: The Code">User-Agent detection</a> code is quite old (stops at IE6) but should be easily extended. Should be combined with R. Gagnon code pointed by Filip, for better detection of real browser (some browsers allows to alter user agent string at will).<br> You might be interested by the <a href="http://www.useragentstring.com/pages/useragentstring.php" rel="nofollow noreferrer" title="UserAgentString.com - List of User Agent Strings">List of User Agent Strings</a> too.</p> |
22,047,607 | 0 | Github: "This email will not be used for commit blame" <p>How can I use a fake email address with Github?</p> <p>Following <a href="http://wayback.archive.org/web/20130124033702/https://help.github.com/articles/keeping-your-email-address-private">Github's since-changed instructions</a>, I had a fake email like [email protected] configured with git (<code>git config --global user.email "[email protected]"</code>) and registered on my <a href="https://github.com/settings/emails">email settings page</a>.</p> <p>It was linking my commits, but not since the past week or so, and it has a "(?)" tooltip saying:</p> <blockquote> <p>This email will not be used for commit blame</p> </blockquote> <p>My real email address is verified and blamable, but I want to keep it private.</p> <p>How can I use a fake one and still be blamed?</p> |
22,300,705 | 0 | <p>You can edit output name from <code>netbeans</code> project</p> <blockquote> <ol> <li>Right click on Library in netbeans</li> <li>Open Properties</li> <li>Build->Archiver->Output. At the end you will see name of lib (SomeName.a)</li> <li>Change it to suiltable name you need. </li> <li>Rebuild Project. You are good to go...</li> </ol> </blockquote> |
38,484,119 | 0 | <p>Like Sinan said, you need to give the form a width and height to match the image size. </p> <p>I think you can take Sinan's code and combine it with this to expand the form's width and height to match the image size.</p> <p>Let's say your image size is 1024x768, then:</p> <pre><code>form { display: block; margin: 0 auto; width: 1024px; height:768px; } </code></pre> |
14,912,924 | 0 | identify a solid pattern to abstract a network layer to allow testability <p>I've read various questions here on the argument like</p> <p><a href="http://stackoverflow.com/questions/741981/how-do-you-unit-test-a-tcp-server-is-it-even-worth-it">How do you unit-test a TCP Server? Is it even worth it?</a></p> <p>and others more specific questions as</p> <p><a href="http://stackoverflow.com/questions/1263581/has-anyone-successfully-mocked-the-socket-class-in-net">Has anyone successfully mocked the Socket class in .NET?</a></p> <p><a href="http://stackoverflow.com/questions/8092182/rhino-mocks-how-to-build-a-fake-socket">rhino mocks: how to build a fake socket?</a></p> <p>but I anyway feel to post the question.</p> <p>I need to design an <strong>abstract network layer</strong>. It should be abstract to decouple consumer code from depending upon a specific implementation and, last but not least, be completely testable with fakes.</p> <p>I'm ended up that I don't need to mock a <code>Socket</code> class, but rather define am higher level abstraction and mock it.</p> <pre><code>interface INetworkLayer { void OnConnect(Stream netwokStream); void OnException(Exception e); // doubts on this } </code></pre> <p>Has anyone done something close to this that can provide observations, comments or explain how may look the right direction?</p> |
22,929,141 | 0 | <p>The offending character here is “|” U+007C VERTICAL LINE, used by Google as a separator between font names; that’s a poor choice by them, since “|” is a reserved character, both by the <a href="http://url.spec.whatwg.org">“URL Living Standard”</a> (which is what the HTML5 CR cites) and by the Internet-standard STD 66 (<a href="http://tools.ietf.org/html/rfc3986">RFC 3986</a>).</p> <p>In practice, it works fine when you use “|” as such, but to conform to the standards and drafts, use percent encoding (% encoding, as defined in the URL specifications) for it, writing <code>%7c</code> (case insensitive) instead:</p> <pre><code><link rel="stylesheet" type="text/css" href= "http://fonts.googleapis.com/css?family=Orbitron%7cSpecial+Elite%7cOpen+Sans"> </code></pre> |
13,065,841 | 0 | |
25,522,969 | 0 | <p>null and [] are both false, a shorter and cleaner way</p> <pre><code>ng-show="myData.Address" </code></pre> |
36,840,150 | 0 | <p>Hide the button that appears inside the chart</p> <pre><code>chart: { resetZoomButton: { theme: { display: 'none' } } } </code></pre> <p>then use your own button:</p> <pre><code>$('#button2').click(function(){ chart.xAxis[0].setExtremes(Date.UTC(1970, 5, 9), Date.UTC(1971, 10, 9)); }); </code></pre> <p><a href="http://jsfiddle.net/udvcy1e0/" rel="nofollow">Updated Fiddle</a></p> |
11,965,812 | 0 | <p>You don't need to split anything, simply loop:</p> <pre><code>$.getJSON('data/data.json', function (ids) { for (var i = 0; i < ids.length; i++) { var id = ids[i]; console.log(id); } }); </code></pre> <p>jQuery will automatically parse the string returned from the server as a javascript array so that you could directly access its elements.</p> <p>You could split each element by the space if you want to retrieve the 2 tokens.</p> |
36,411,200 | 0 | <p>If using ASP.NET (this includes MVC and Web API, Web Forms, etc) and AutoFac you should register all your components using the extension method <code>.InstancePerRequest()</code>. The only exception is for components that are thread safe and where you do not have to worry about errors/unexpected results occurring from one request accessing the same (stale) data as another. An example might be a Factory or a Singleton.</p> <p>Example of use on a line of code:</p> <pre><code>builder.Register(c => new UserStore<ApplicationUser>(c.Resolve<ApplicationDataContext>())).AsImplementedInterfaces().InstancePerRequest(); </code></pre> <p>This ensures that every new incoming Http Request will get its own copy of that implementation (resolved and injected hopefully via an interface). Autofac will also cleanup the Disposable instances at the end of each request.</p> <p>This is the behavior you need. It ensures that there is no cross request interference (like one request manipulating data on a shared dbcontext on another request). It also ensures that data is not stale as it is cleaned up after each request ends.</p> <p>See <a href="http://docs.autofac.org/en/latest/lifetime/instance-scope.html#instance-per-request" rel="nofollow">the Autofac documentation</a> for more details (here an excerpt).</p> <blockquote> <h3>Instance Per Request</h3> <p>Some application types naturally lend themselves to “request” type semantics, for example ASP.NET web forms and MVC applications. In these application types, it’s helpful to have the ability to have a sort of “singleton per request.”</p> <p>Instance per request builds on top of instance per matching lifetime scope by providing a well-known lifetime scope tag, a registration convenience method, and integration for common application types. Behind the scenes, though, it’s still just instance per matching lifetime scope.</p> </blockquote> <p>Changing your DI definitions above to include this should resolve your issues (I think based on what you have provided). If not then it might be a problem with your Identity registration in which case you should post that code so it can be scrutinized.</p> |
14,483,471 | 0 | <p>The wildcard * has to be interpreted by the SHELL. When you run subprocess.call, by default it doesn't load a shell, but you can give it <code>shell=True</code> as an argument:</p> <pre><code>subprocess.call("mock *.src.rpm".split(), shell=True) </code></pre> |
27,302,366 | 0 | <p>What you are looking for is <code>UINavigationControllerDelegate</code>.</p> <p>I believe the method that gives you the message you need is </p> <pre><code>- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated; </code></pre> <p>And </p> <pre><code>- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated; </code></pre> <p>In your CustomViewController, you are going to want to conform to the <code>UINavigationControllerDelegate</code> protocol like this:</p> <pre><code>@interface CustomViewController : UIViewController <UINavigationControllerDelegate> </code></pre> <p>And then override the delegate methods above to get the messages you are looking for.</p> <p>Here is an complete implementation in Swift:</p> <pre><code>import UIKit class ViewController: UIViewController, UINavigationControllerDelegate { override func viewDidLoad() { super.viewDidLoad() navigationController?.delegate = self } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func navigationController(navigationController: UINavigationController, willShowViewController viewController: UIViewController, animated: Bool) { println(viewController) } } class FirstViewController: ViewController { } class SecondViewController: ViewController { } </code></pre> |
20,177,846 | 0 | <p>The book xUnit Test Patterns offers a lot of great insights into this very question. </p> |
4,827,507 | 0 | <p>Did you change the SDK location? That may cause this issue.<br> If possible please post exact error message.</p> |
40,266,033 | 0 | <p>The system defined <code>&&</code> operator only supports boolean operands. The <code>&</code> operator will work for enums (because it also works on all integer types, which the enums are based on). Of course, if you want an enum that represents the combination of two flag values then you'll want to OR them together (using <code>|</code>), not AND them together.</p> |
12,062,096 | 0 | SQL Connection String for another pc <p>I developed an application. It loads sql database on my pc with this connection string:</p> <pre><code>Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True private void Window_Loaded(object sender, RoutedEventArgs e) { DataSet ds = new DataSet(); SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Database\Books.mdf;Integrated Security=True;User Instance=True"); SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = new SqlCommand("SELECT * FROM Lessons", con); da.Fill(ds); grdPersonnel1.DataContext = ds.Tables[0]; con.Open(); } </code></pre> <p>but, my Database data doesn't load in another pc!</p> |
37,159,943 | 0 | How to perform heroku-like deployment on shared hosting? <p>For our production server we use shared hosting. Until now, we were using FTP system to manually upload changes.</p> <p>I am looking for a technique that lets me use git to push only changes from development to production server. </p> <p>For my private projects I was using GitHub as development remote and Heroku as production remote. I am looking for something that can do similar thing without using Heroku itself. (note that we use shared hosting). I want to have two remotes, development (to development server) and production remote (from development server to production server). <strong>Idea is to push from development server to production server using git.</strong></p> <p>Projects are mostly written in PHP.</p> |
16,977,873 | 0 | FrameLayout click event is not firing <p>I have used Framelayour for click event and It was working fine before 2 days but don't know wat happend now it is not working. <br> Please someone help me. <bR> My code is as below : <strong>Design :</strong></p> <pre><code><FrameLayout android:id="@+id/flWebpre" android:layout_width="fill_parent" android:layout_height="0dp" android:layout_weight="1" > <WebView android:id="@+id/wvWebsite" android:layout_width="fill_parent" android:layout_height="fill_parent" /> <ProgressBar android:id="@+id/pbWebsite" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@color/white" android:layout_gravity="center_horizontal" /> </FrameLayout> </code></pre> <p><strong>Code :</strong></p> <pre><code>FrameLayout flWebPre = (FrameLayout) findViewById(R.id.flWebpre); flWebPre.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub if (isExpanded) { isExpanded = false; new CollapseAnimation(slidingPanel, panelWidth, TranslateAnimation.RELATIVE_TO_SELF, 0.70f, TranslateAnimation.RELATIVE_TO_SELF, 0.0f, 0, 0.0f, 0, 0.0f); } } }); </code></pre> |
5,442,611 | 0 | <p>Try to read this articles:</p> <p><a href="http://www.devx.com/getHelpOn/Article/10202/1954" rel="nofollow">Use RTTI for Dynamic Type Identification</a></p> <p><a href="http://en.wikibooks.org/wiki/C++_Programming/RTTI" rel="nofollow">C++ Programming/RTTI</a></p> <p><a href="http://en.wikipedia.org/wiki/Run-time_type_information" rel="nofollow">Run-time type information</a></p> |
1,689,879 | 0 | <p>You can use a timout in Javascript or maybe the <a href="http://plugins.jquery.com/project/timers" rel="nofollow noreferrer">timer plugin</a> from jQuery. This will allow you to create a function that removes teh message after a period of time. I haven't used the timer plugin myself but it seems pretty stable.</p> <pre><code>$("#save-button").click(function() { //code to save etc $("your label").oneTime(10000, "hide", function() { $("Your Label").hide(); }); }); </code></pre> |
16,687,633 | 0 | <p>You can also try this code, applies for other file extensions too.</p> <pre><code>string ftpUrl = "ftp://server//foldername/fileName.ext"; string fileToUploaded = "c:/fileName.ext"; FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl); request.Proxy = new WebProxy(); //-----Proxy bypassing(The requested FTP command is not supported when using HTTP proxy) request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential(ftpUsername, ftpPassword); using (var requestStream = request.GetRequestStream()) { using (var input = File.OpenRead(fileToBeUploaded)) { input.CopyTo(requestStream); } } </code></pre> <p>Try streaming the data, instead of loading it all into memory separately. Also <code>using</code> statement helps to dispose the resources perfectly.</p> |
35,069,582 | 0 | Why google doesnt index my single page app properly? <p>Since some time google <a href="https://developers.google.com/webmasters/ajax-crawling/docs/learn-more" rel="nofollow">officially depreceated ajax crawling scheme</a> they came up with back in 2009 so I decided to get rid of generating snapshots in phantomJS for _escaped_fragment and rely on google to render my single page app like a modern browser and discover its content. <a href="https://googlewebmastercentral.blogspot.com.au/2015/10/deprecating-our-ajax-crawling-scheme.html" rel="nofollow">They describe it in here</a>. But now I seem to have a problem.</p> <p>Google indexed my page (at least I can see in webmastertools it has) but when using webmastertools I look at <code>google index-->content keywords</code> it shows non processed content of my angularJS templates only and names of my binded variable names e.g. <code>{{totalnewprivatemessagescount}}</code> etc. The keywords do not contain words that should should be generated by ajax calls when Javascript executes so e.g. <code>fighter</code> is not even in there and it should be all over the place.</p> <p>Now, when I use <code>Crawl-->Fetch as google-->Fetch and render</code> the snapshot what google bot sees is very much the same as what user sees and is clearly generated using Javascript. The Fetch HTML tab though shows only source without being processed using JS which I'm guessing is fine.</p> <p>Now my question is why google didn't index my website properly? Is there anything I implemented incorrectly somewhere? The website is live at <a href="https://www.fightersconnect.com" rel="nofollow">https://www.fightersconnect.com</a> and thanks for any advice.</p> |
7,919,538 | 0 | <ol> <li>you need to check the result from <code>[Model alloc] init]</code>, make sure value is not nil.</li> <li>check your property <code>model</code> of the cell, make sure it's not assign.</li> <li>if still the <code>model</code> of <code>cell</code> is nil, please posts more codes here. </li> </ol> |
19,519,833 | 0 | <p>In ARC assign it would be released anywhere. For pointer variable "strong" only more comfortable. I modified the code in .h file by below line</p> <p>@property (nonatomic, strong) NSString *username;</p> <p>Thanks Tamilarasan</p> |
40,517,134 | 0 | CPython multiprocess fork failing with gdb/lldb attached on OS X <p>Trying to run the following code in CPython 2.7.12 with either gdb or lldb attached fails:</p> <pre><code>import multiprocessing as mp mp.Manager() </code></pre> <p>The debugger sees something like:</p> <pre><code>$ lldb -f python (lldb) target create "/usr/local/bin/python" Current executable set to '/usr/local/bin/python' (x86_64). (lldb) r Process 1857 launched: '/usr/local/bin/python' (x86_64) Process 1857 stopped * thread #1: tid = 0x1afeb, 0x00007fff5fc01000 dyld`_dyld_start, stop reason = exec frame #0: 0x00007fff5fc01000 dyld`_dyld_start dyld`_dyld_start: -> 0x7fff5fc01000 <+0>: popq %rdi 0x7fff5fc01001 <+1>: pushq $0x0 0x7fff5fc01003 <+3>: movq %rsp, %rbp 0x7fff5fc01006 <+6>: andq $-0x10, %rsp (lldb) c Process 1857 resuming Python 2.7.12 (default, Oct 11 2016, 05:24:00) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import multiprocessing >>> multiprocessing.Manager() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/__init__.py", line 99, in Manager m.start() File "/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/managers.py", line 528, in start self._address = reader.recv() EOFError </code></pre> <p>Along with that output, I get the standard OS X crash dialog, from that, notably:</p> <pre><code>Crashed Thread: 0 Dispatch queue: com.apple.main-thread Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000002, 0x0000000000000000 Application Specific Information: dyld: in dlopen() crashed on child side of fork pre-exec Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0 dyld 0x00007fff5fc0d35b gdb_image_notifier(dyld_image_mode, unsigned int, dyld_image_info const*) + 1 1 ??? 000000000000000000 0 + 0 2 dyld 0x00007fff5fc0482a dyld::notifyBatchPartial(dyld_image_states, bool, char const* (*)(dyld_image_states, unsigned int, dyld_image_info const*)) + 755 3 dyld 0x00007fff5fc0e75d ImageLoader::link(ImageLoader::LinkContext const&, bool, bool, bool, ImageLoader::RPathChain const&) + 89 4 dyld 0x00007fff5fc04a12 dyld::link(ImageLoader*, bool, bool, ImageLoader::RPathChain const&) + 149 5 dyld 0x00007fff5fc0c29f dlopen + 450 6 libdyld.dylib 0x00007fff87ce279c dlopen + 59 7 org.python.python 0x00000001000b8182 _PyImport_GetDynLoadFunc + 309 8 org.python.python 0x00000001000a3230 _PyImport_LoadDynamicModule + 96 </code></pre> <p>This similarly happens in gdb regardless of the setting of <code>detach-on-fork</code>.</p> <p>How can I run CPython under a debugger with multiprocessing code?</p> |
32,308,650 | 0 | <p>Likely, with iOS8, the path that you have saved won't be valid across launches. </p> <p>The solution is to save the filename and not the complete path, and to recreate the URL or complete path, by getting the path to the Documents (or tmp) folder and appending the filename to it.</p> |
36,967,891 | 0 | <p>There are two main problems with your code:</p> <ol> <li>Enable HTML 5 mode for <a href="https://docs.angularjs.org/api/ng/provider/$locationProvider" rel="nofollow">pushState via $locationProvider</a> for URLs like <code>/dashboard</code> and <code>/page_3</code></li> <li>Fix the problem where route is configured for <code>/page_3</code> but having a <code>a</code> tag pointed to <code>/page_3.html</code></li> </ol> <p>To get a working example:</p> <ul> <li><p>Add a base tag</p> <pre><code><base href="/"> </code></pre></li> <li><p>Enable html5 mode via locationProvider in a <a href="https://docs.angularjs.org/guide/providers" rel="nofollow">config</a> block</p> <pre><code>$locationProvider.html5Mode(true); </code></pre></li> <li><p>Fix route in dashboard.html</p> <pre><code> <!-- below is dashboard.html page --> <div ng-controller="app"> <h1>Page_3</h1> <div><a href='page_3.html'>page_3</a></div> </div> </code></pre></li> </ul> <p><a href="http://jsbin.com/vakujokara" rel="nofollow">Click here for the demo / jsbin.</a></p> <p>Other/suggestions: as <a href="http://stackoverflow.com/users/1462603/zach-briggs">Zack Briggs</a> have suggested; using controller syntax in routes would help you come up with better code structure / design in router config, <a href="https://docs.angularjs.org/api/ng/service/$compile" rel="nofollow">directives</a>, or <a href="https://docs.angularjs.org/guide/component" rel="nofollow">components</a>. Also putting everything in one place is often a bad idea for a growing project.</p> |
14,775,851 | 0 | <p>I'm using JavaFX's WebPane at the moment. That's fine for my needs. Close?</p> |
21,100,155 | 0 | <p>You need to make this operation optional if <code>value</code> is empty:</p> <pre><code> if value: data.append((next(value), value)) </code></pre> <p>This change works for me:</p> <pre><code>if value: try: data.append(next(value), value) except StopIteration: pass </code></pre> |
3,454,578 | 0 | Need a way to pick a common bit in two bitmasks at random <p>Imagine two bitmasks, I'll just use 8 bits for simplicity:</p> <pre><code>01101010 10111011 </code></pre> <p>The 2nd, 4th, and 6th bits are both 1. I want to pick one of those common "on" bits at random. But I want to do this in O(1).</p> <p>The only way I've found to do this so far is pick a random "on" bit in one, then check the other to see if it's also on, then repeat until I find a match. This is still O(n), and in my case the majority of the bits are off in both masks. I do of course & them together to initially check if there's any common bits at all.</p> <p>Is there a way to do this? If so, I can increase the speed of my function by around 6%. I'm using C# if that matters. Thanks!</p> <p>Mike</p> |
28,205,392 | 0 | <p>Thanks to himmet-avsar!</p> <p>The filter can specified simply by using handlebars.</p> <pre><code><td ng-repeat="cell in structure" ng-bind="row[cell.key] | {{cell.filter}}: row[cell.rgmnt]"></td> </code></pre> <p>But, this assumes that the filter property is always specified. You can use another filter to specify if the pipe is shown and even pass arguments through it:</p> <pre><code><td ng-repeat="cell in structure" ng-bind="row[cell.key] {{cell.filter | isThereAFilter: row[cell.rgmnt]}}"></td> function isThereAFilter() { return function (input, arg1) { if (input != null) { return "| " + input + ": " + arg1; } } } </code></pre> |
13,197,498 | 0 | <p>This worked perfect for me:</p> <pre><code>#import <SystemConfiguration/CaptiveNetwork.h> CFArrayRef myArray = CNCopySupportedInterfaces(); CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0)); // NSLog(@"SSID: %@",CFDictionaryGetValue(myDict, kCNNetworkInfoKeySSID)); NSString *networkName = CFDictionaryGetValue(myDict, kCNNetworkInfoKeySSID); if ([networkName isEqualToString:@"Hot Dog"]) { self.storeNameController = [[StoreDataController alloc] init]; [self.storeNameController addStoreNamesObject]; } else { UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Connection Failed" message: @"Please connect to the Hot Dog network and try again" delegate: self cancelButtonTitle: @"Close" otherButtonTitles: nil]; [alert show]; </code></pre> |
40,641,967 | 0 | Parallax Background in div of Content <p>Is it possible to create a parallax background inside a div that has a certain width? Every tutorial I've seen has parallax backgrounds on full screen websites. My site is not full screen width, but I would still like to use the parallax effect within the content of my site. Obviously if I use the background-attachment: fixed; css property, the background becomes fixed to the body tag and not of the actual div.</p> <p>To understand what I'm trying to do, you can look at this simple jsfiddle: <a href="http://jsfiddle.net/yh02y6dy/" rel="nofollow noreferrer">http://jsfiddle.net/yh02y6dy/</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>//Parallax function simpleParallax() { //This variable is storing the distance scrolled var scrolled = $(window).scrollTop() + 1; //Every element with the class "scroll" will have parallax background //Change the "0.3" for adjusting scroll speed. $('.scroll').css('background-position', '0' + -(scrolled * 0.05) + 'px'); } //Everytime we scroll, it will fire the function $(window).scroll(function (e) { simpleParallax(); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.scroll { /*Set a css background */ background:url(http://cdn.wallpapersafari.com/63/15/o20clA.jpg) fixed; width:600px; height:250px; line-height:300px; margin:0 auto; margin-top:150px; text-align:center; color:#fff; } body { min-height:3000px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code><div class="scroll"> <h1>Text on parralax background</h1> </div></code></pre> </div> </div> </p> <p>You can see that the background image is fixed to the top left corner of the screen and not to the div. I want the background image to start where the div is starting.</p> <p>I'm not opposed to using jquery if that is what's needed to make this work.</p> <p>Thanks!</p> |
34,438,117 | 0 | <h2>AST</h2> <p>To avoid any chance of error in code manipulation using an <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree" rel="nofollow">Abstract Syntax Tree (AST)</a> type solution is best. One example implementation is in <a href="https://github.com/mishoo/UglifyJS2" rel="nofollow">UglifyJS2</a> which is a JavaScript parser, minifier, compressor or beautifier toolkit.</p> <h2>RegEx</h2> <p>Alternatively if an AST is over the top for your specific task you can use RegEx.</p> <p>But do you have to contend with comments too?</p> <p>The process might look like this:</p> <ol> <li>Use a carefully formed regex to <strong>split</strong> the JavaScript code string based on these in this order: <ul> <li>comment blocks</li> <li>comment lines</li> <li>quoted strings both single and double quotes (remembering to contend with escaping of characters).</li> </ul></li> <li>Iterate though the split components. If string (beings with <code>"</code> or <code>'</code>) or comment (begins with <code>//</code> or <code>/*</code>) ignore, otherwise run your replacement.</li> <li>(and the simple part) join array of strings back together.</li> </ol> |
21,588,596 | 0 | <p>Try this:</p> <pre><code>tt <- c(0, 1, 2, 3, 4, 5, 1, 2, 3, 4, 1, 2, 3, 4, 5) grp <- cumsum(c(FALSE, diff(tt) < 0)) </code></pre> <p>which gives:</p> <pre><code>> grp [1] 0 0 0 0 0 0 1 1 1 1 2 2 2 2 2 </code></pre> |
5,189,326 | 0 | <p>My problem was I was passing along the same old listAccts to the array list, without saying "new". Even when I did say "new" i was passing along the accounts inside of listAccts, so the arraylist would be new, but the accounts inside of the new array list would be the ones I wanted to have backups of. What I had to do was create a new object from a deep copy using this method.</p> <p><a href="http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2" rel="nofollow">http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2</a></p> <p>Thanks everyone who offered help.</p> |
33,305,397 | 0 | <p>Assuming you want to copy the values of the previous block when add button is clicked, you can do this:</p> <pre><code>$scope.cloneItem = function() { var food = $scope.foods[$scope.foods.length - 1]; var itemToClone = { "selectproduct": food.selectproduct, "Quantity1": food.Quantity1, "Quantity2": food.Quantity2 }; $scope.foods.push(itemToClone); } </code></pre> |
28,791,950 | 0 | <p>You are reading the list wrong; <a href="https://docs.python.org/2/library/stdtypes.html#file.readline" rel="nofollow"><code>readline</code></a> does not take the line number, but the <strong>maximum number of characters per line</strong>:</p> <blockquote> <p><code>file.readline([size])</code></p> <p>Read one entire line from the file. A trailing newline character is kept in the string (but may be absent when a file ends with an incomplete line). [6] <strong>If the size argument is present and non-negative, it is a maximum byte count (including the trailing newline) and an incomplete line may be returned.</strong> When size is not 0, an empty string is returned only when EOF is encountered immediately.</p> </blockquote> <p>Your code would work if you just did <code>file.readline()</code>:</p> <pre><code>for line in range(1,11): data = file.readline() list1.append(data) </code></pre> <p>The current code tries to read only 1, 2 and 3 characters of the <em>first</em> line, which results in <code>'1'</code>, <code>'00'</code> and the <code>'\n'</code> newline being read separately, followed by max 4 characters of line 2 (<code>'200\n'</code>) etc.</p> <hr> <p>However it is not very pythonic either; I would write it as:</p> <pre><code>with open("sample.txt") as file: list1 = [ int(line) for line in file ] sortedlist = list1.sort() print sortedlist </code></pre> <p><code>with</code> automatically closes the file at the end of indented block. <code>for</code> loop for a file automatically iterates over its lines; <code>[ expression for var in iterable ]</code> is a list comprehension, that is a shorter way of doing:</p> <pre><code>result = [] for var in iterable: result.append(expression) </code></pre> <p>Or as Jon Clements suggested, if you really want to sort the lines by their numerical value, but keeping them as string:</p> <pre><code>with open('sample.txt') as file: list1 = list(file) # all lines as a list print sorted(list1, key=int) </code></pre> |
2,739,196 | 0 | Login fails after upgrade to ASP.net 4.0 from 3.5 <p>I cannot log in using any of the membership accounts using .net 4.0 version of the app. It fails like it's the wrong password, and FailedPasswordAttemptCount is incremented in my_aspnet_membership table. (I am using membership with mysql membership provider.)</p> <p>I can create new users. They appear in the database. But I cannot log in using the new user credentials (yes, IsApproved is 1).</p> <p>One clue is that the hashed passwords in the database is longer for the users created using the asp.net 4.0 version, e.g 3lwRden4e4Cm+cWVY/spa8oC3XGiKyQ2UWs5fxQ5l7g=, and the old .net 3.5 ones are all like +JQf1EcttK+3fZiFpbBANKVa92c=. </p> <p>I can still log in when connecting to the same db with the .net 3.5 version, but only to the old accounts, not the new ones created with the .net 4.0 version. The 4.0 version cannot log in to any accounts.</p> <p>I tried dropping the whole database on my test system, the membership tables are then auto created on first run, but it's still the same, can create users, but can't log in.</p> |
25,979,700 | 0 | <p>PayPal is actually better than most in terms of enabling you to do testing. There's a complete testing sandbox solution (<a href="https://developer.paypal.com/webapps/developer/docs/classic/lifecycle/ug_sandbox/" rel="nofollow">support document</a>), and when adding/editing your REST API application, you can click the "Edit" link next to "App Redirect URLs" and specify both a testing URL and live URL for production. That should give you everything you need to test locally without exposing your site to the outside world.</p> <p>If it does end up giving you fits over using localhost, there's always services like <a href="http://readme.localtest.me" rel="nofollow">localtest.me</a>, that can let you get around it.</p> |
1,846,704 | 0 | <p>"Clear" JavaScript:</p> <pre><code><script type="text/javascript"> function myKeyPress(e){ var keynum; if(window.event) { // IE keynum = e.keyCode; } else if(e.which){ // Netscape/Firefox/Opera keynum = e.which; } alert(String.fromCharCode(keynum)); } </script> <form> <input type="text" onkeypress="return myKeyPress(event)" /> </form> </code></pre> <p>JQuery:</p> <pre><code>$(document).keypress(function(event){ alert(String.fromCharCode(event.which)); }); </code></pre> |
35,926,716 | 0 | <p><code>express</code> is a module that can be used to create more than one application.</p> <pre><code>var ex = require('express') </code></pre> <p>puts this module into the variable <code>ex</code>. Once you have a reference to the module, you can use it to create application. Each module has its own API. According to the expressjs documentation - <a href="http://expressjs.com/en/4x/api.html" rel="nofollow">http://expressjs.com/en/4x/api.html</a>, the module is in fact a function that can be used to create applications</p> <pre><code>var app1 = ex(); var app2 = ex(); </code></pre> <p>you could for example want to have several web applications listening on different ports.</p> <p>If you only want one application (but it would be less readable) you could write</p> <pre><code>var app = require('express')(); </code></pre> |
1,854,313 | 0 | <p>nothing to do with jQuery, just this:</p> <pre><code>window.location.href = 'whatever.html'; </code></pre> |
30,418,162 | 0 | ADDing Django's Q() objects and get two exclusive JOIN ONs <p>So this is the scenario:</p> <pre><code>class Person(models.Model): ... class Aktion(models.Model): ... class Aktionsteilnahme(models.Model): person = models.ForeignKey(Person) aktion = models.ForeignKey(Aktion) </code></pre> <p>The problem now is, that I'm dynamically constructing rather complex queries based on <code>Q()</code>-objects. They end up like this:</p> <pre><code>Person.objects.filter( Q((Q()|Q(aktionsteilnahme__aktion=302))& (Q()|Q(aktionsteilnahme__aktion=547))) ) </code></pre> <p>which can (and automatically will) be reduced to:</p> <pre><code>Person.objects.filter( Q(aktionsteilnahme__aktion=302)& Q(aktionsteilnahme__aktion=547) ) </code></pre> <p>The <strong>problem</strong> now is, that this results in a SQL like this:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM person LEFT OUTER JOIN aktionsteilnahme ON ( person.id = aktionsteilnahme.person_id ) WHERE (aktionsteilnahme.aktion = 2890 AND aktionsteilnahme.aktion = 5924) </code></pre> <p>What I would actually need however is:</p> <pre><code>Person.objects.filter(Q(aktionsteilnahme__aktion=302)) .filter(Q(aktionsteilnahme__aktion=547)) </code></pre> <p>resulting in what I would actually need:</p> <pre class="lang-sql prettyprint-override"><code>SELECT * FROM person INNER JOIN aktionsteilnahme ON ( person.id = aktionsteilnahme.person_id ) INNER JOIN aktionsteilnahme T4 ON ( person.id = T4.person_id ) WHERE (aktionsteilnahme.aktion = 302 AND T4.aktion = 547) </code></pre> <p>I can't use the proposed solution though because all of it is gonna be <code>OR</code>'ed again.</p> <p>I would have to be able to do something like:</p> <pre><code>Person.objects.filter( Q( Q(aktionsteilnahme__aktion=302)) .filter(Q(aktionsteilnahme__aktion=547)) ) | Q(other_q_filters) ) </code></pre> |
16,118,745 | 0 | <p>Welcome to the wonderful world of Event Dispatch Thread violation (and race conditions).</p> <p>Basically, you should never update (directly or indirectly) any UI component from any thread other then the EDT.</p> <p>Basically, when you update your <code>TableModel</code>, it is firing an event, which is been caught by the Table, which is trying to update itself, but the models state is in flux and does not make sense to the table...</p> <p>Instead, trying using a <code>SwingWorker</code> to update you model, using the publish and process methods to keep updates synchronised with the EDT</p> <p>Check out <a href="http://docs.oracle.com/javase/tutorial/uiswing/concurrency/" rel="nofollow">Concurrency in Swing</a> for more details and examples.</p> |
32,738,943 | 0 | VB6 read barcode while program is running in background <p>i have a problem to make a program that can read Barcode. What i want to do is a program (maybe a service? i don't know) that can capture barcode from a barcode scanner while is running in background.</p> <p>I have found that i can check if is plugged in a specific barcode scanner with his VID/PID, here some code:</p> <pre><code>Set wmi = GetObject("winmgmts://./root/cimv2") Dim VID As String Dim PID As String 'Barcode scanner VID = "VID_040B" PID = "PID_6510" 'REV = "REV_0120" For Each d In wmi.ExecQuery("SELECT * FROM Win32_USBControllerDevice") If InStr(d.Dependent, VID & "&" & PID) > 0 Then Debug.Print ("Barcode Scanner found it!") Debug.Print wmi.Get(d.Dependent).Description End If Next </code></pre> <p>How can I do that is read by my program only the input of my barcode scanner?</p> <p>Thank you in advance.</p> |
40,810,615 | 0 | <p>ok, I got it working consistently between the two accounts and the key was to set the UseMachineKeyStore flag.</p> <pre><code>private static RSACryptoServiceProvider CreateRsaCypher(string containerName = DefaultContainerName) { // Create the CspParameters object and set the key container // name used to store the RSA key pair. CspParameters cp = new CspParameters(); cp.KeyContainerName = containerName; cp.Flags = CspProviderFlags.UseExistingKey | CspProviderFlags.UseMachineKeyStore; // Create a new instance of RSACryptoServiceProvider that accesses // the key container MyKeyContainerName. return new RSACryptoServiceProvider(cp); } </code></pre> |
9,130,212 | 0 | <p>I prefer to set <strong><a href="https://docs.djangoproject.com/en/1.3/ref/settings/#date-input-formats">DATE_INPUT_FORMATS</a></strong> in settings.py and then define the field like:</p> <pre><code>dob = forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) </code></pre> <p>This more DRY than setting it on a per form field basis.</p> <p>If it's a text field input, I almost always put the accepted format(s) in the field's <code>help_text</code> so that the user can know what format(s) is(are) accepted.</p> |
14,255,220 | 0 | <p>You can try <a href="http://tumult.com/hype/" rel="nofollow">http://tumult.com/hype/</a> for creating interactive content for a wide range of devices. Also tell your client that almost nothing is available for every device imaginable ;-)</p> |
6,444,612 | 0 | <p><code>width, height = im.size</code></p> <p>According to the <a href="http://effbot.org/imagingbook/image.htm">documentation</a>.</p> |
25,723,954 | 0 | <p>Why not try wrapping your collection in an object (which acts as a service state) to allow binding to occur on the object, rather than by exposing functions. For example:</p> <pre><code>app.factory('healthService', function() { var state = { healths: [...] }; return { getState: function() { return state; }, updateHealths: function() { state.healths = [...]; } }; }); </code></pre> <p>Then inside your controller:</p> <pre><code>$scope.healthState = healthService.getState(); </code></pre> <p>Then to reference your healths from your html, use:</p> <pre><code><div ng-repeat="health in healthState.healths"></div> </code></pre> |
2,996,780 | 0 | <p>The response from the SOAP interface is already parsed. The englighten() method returns an XML string. When you call it with SOAP, this response is wrapped within even more XML. The SOAP library already parses the outer SOAP XML and returns the result of the enlighten() method, which is also XML.</p> |
16,122,623 | 0 | <p>If you want to run asynchronous process programmatically go for it. That is, use the lower level functions.</p> <pre><code>(set-process-sentinel (start-process "pdflatex" "*async pdflatex*" "pdflatex" filename) (lambda (process event) (cond ((string-match-p "finished" event) (kill-buffer "*async pdflatex*")) ((string-match-p "\\(exited\\|dumped\\)" event) (message "Something wrong happened while running pdflatex") (when (yes-or-no-p "Something wrong happened while running pdflatex, see the errors?") (switch-to-buffer "*async pdflatex*")))))) </code></pre> <p><code>start-process</code> starts a process asynchronously and <code>set-process-sentinel</code> defines the function triggered when the process status changes.</p> |
17,957,443 | 0 | <p>Well, for starters you'd have to avoid the client's navigation cache (often a back/forward doesn't actually pull the page back down).</p> <p>After that hurdle you can look at (ironically) using a session variable to store if it's been viewed [output] and only dump it to the page once.</p> <p>if that seems to much, you could just add a cookie check in the function so when it's run (and re-run) it checks for a cookie and, when absent, makes an alert and sets a cookie. Pseudocode:</p> <pre><code>function showAlert(msg){ if (cookie[msg] == null){ // a cookie doesn't exist for this msg alert(msg); // alert the msg cookie[msg] = true; // set the cookie so the next pass is ignored } } </code></pre> |
30,012,708 | 0 | <p>for data transfer you can use the library Emmet</p> <p><a href="https://github.com/florent37/emmet" rel="nofollow">https://github.com/florent37/emmet</a></p> <p>We can imagine a protocol like this</p> <pre><code>public interface SmartphoneProtocole{ void getStringPreference(String key); void getBooleanPreference(String key); } public interface WearProtocole{ void onStringPreference(String key, String value); void onBooleanPreference(String key, boolean value); } </code></pre> <p>wear/WearActivity.java</p> <pre><code>//access "MY_STRING" sharedpreference SmartphoneProtocole smartphoneProtocol = emmet.createSender(SmartphoneProtocole.class); emmet.createReceiver(WearProtocole.class, new WearProtocole(){ @Override void onStringPreference(String key, String value){ //use your received preference value } @Override void onBooleanPreference(String key, boolean value){ } }); smartphoneProtocol.getStringPreference("MY_STRING"); //request the "MY_STRING" sharedpreference </code></pre> <p>mobile/WearService.java</p> <pre><code>final WearProtocole wearProtocol = emmet.createSender(WearProtocole.class); emmet.createReceiver(SmartphoneProtocol.class, new SmartphoneProtocol(){ //on received from wear @Override void getStringPreference(String key){ String value = //read the value from sharedpreferences wearProtocol.onStringPreference(key,value); //send to wear } @Override void getBooleanPreference(String key){ } }); </code></pre> |
40,852,741 | 0 | <p>@jon-m answer needs to be updated to reflect the latest changes to paperclip, in order for this to work needs to change to something like:</p> <pre><code>class Document has_attached_file :revision def revision_contents(path = 'tmp/tmp.any') revision.copy_to_local_file :original, path File.open(path).read end end </code></pre> <p>A bit convoluted as @jwadsack mentioned using <code>Paperclip.io_adapters.for</code> method accomplishes the same and seems like a better, cleaner way to do this IMHO.</p> |
5,415,236 | 0 | <p>You can delete the files and/or directories prior to publishing like so:</p> <pre><code><RemoveDir Directories="$(MyDirectory)" Condition="Exists('$(TempDirectory)')" /> <Delete Files="$(MyFiles)" Condition="Exists('$(MyFiles)')" /> </code></pre> |
23,446,627 | 0 | <p>I did it. Thanks for your help</p> <pre><code> declare @name varchar(100) set @name='Sharma,Ravi,K' select CASE WHEN CHARINDEX(' ',REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1) >0 THEN SUBSTRING(REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1,(LEN(@name)-CHARINDEX(' ',REVERSE(REPLACE(@name,',',' '))))-CHARINDEX(' ',REPLACE(@name,',',' '))) else SUBSTRING(REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1,LEN(@name)) END AS 'FIRST NAME' ,CASE WHEN CHARINDEX(' ',REPLACE(@name,',',' '), CHARINDEX(' ',REPLACE(@name,',',' ')) + 1) >0 THEN SUBSTRING(REPLACE(@name,',',' '),LEN(@name)-CHARINDEX(' ',REVERSE(REPLACE(@name,',',' ')))+2,LEN(@name)) ELSE ' ' END AS 'MIDDLE NAME' , SUBSTRING(REPLACE(@name,',',' '), 1,CHARINDEX(' ',REPLACE(@name,',',' '))) </code></pre> |
4,170,290 | 0 | jQuery Templates and Razor? <p>Can someone shed some light on how these compare/complement each other in the context of an ASP.NET MVC application? </p> |
35,225,955 | 0 | Overlap of labels for MarkerWithLabel on custom marker on Google Maps <p>I initially used an InfoBox to create a label for a marker with a custom icon. For the scenario of overlapping markers, the labels became illegible and so I had to look for a solution or alternative. </p> <p>It was suggested in a <a href="http://stackoverflow.com/questions/35080536/how-to-solve-the-infobox-label-overlap-on-multiple-markers-on-google-map">previous question</a> that I should make use of MarkerWithLabel. It definitely helps, but if the markers overlap exactly, you can see the label still coming through even after setting the opacity to 1 and making the background the same as the custom marker. </p> <p><a href="https://i.stack.imgur.com/9Xdda.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9Xdda.png" alt="enter image description here"></a></p> <pre><code>.labels { background-color: #FF5959; } gmarker = new MarkerWithLabel({ position: someCenterPosition, icon: customImageURL, draggable: false, raiseOnDrag: false, map: map, title: someTitle, labelContent: aTitle, labelAnchor: new google.maps.Point(someOffsetX, someOffsetY), labelClass: "labels", // the CSS class for the label labelStyle: {opacity: 1} }); </code></pre> <p>The 2 is actually the marker behind's label and 15 should be displayed on the front marker. I need to have the 2 and its background behind the marker with the label of 15.</p> |
1,267,031 | 0 | What does fragmented memory look like? <p>I have a mobile application that is suffering from slow-down over time. My hunch, (In part fed by <a href="http://developer.sonyericsson.com/site/global/techsupport/tipstrickscode/java/p_avoidingmemoryfragment.jsp" rel="nofollow noreferrer">this article</a>,) is that this is due to fragmentation of memory slowing the app down, but I'm not sure. Here's a pretty graph of the app's memory use over time:</p> <p><img src="http://kupio.com/image-dump/fragmented.png" alt="fraggle rock"></p> <p>The 4 peaks on the graph are 4 executions of the exact same task on the app. I start the task, it allocates a bunch of memory, it sits for a bit (The flat line on top) and then I stop the task. At that point it calls System.gc(); and the memory gets cleaned up.</p> <p>As can be seen, each of the 4 runs of the exact same task take longer to execute. The low-points in the graph all return to the same level so there do not seem to be any memory leaks between task runs.</p> <p>What I want to know is, is memory fragmentation a feasible explanation or should I look elsewhere first, bearing in mind that I've already done a lot of looking? The low-points on the graph are relatively low so my assumption is that in this state the memory would not be very fragmented since there can't be a lot of small memory holes to be causing problems.</p> <p>I don't know how the j2me memory allocator works though, so I really don't know. Can anyone advise? Has anyone else had problems with this and recognises the memory profile of the app?</p> |
10,794,632 | 0 | List Sorted incorrectly <p>i have following code </p> <pre><code>List<TimeZoneInfo> timeZoneList = new List<TimeZoneInfo>(TimeZoneInfo.GetSystemTimeZones()); timeZoneList.Sort((item1, item2) => { return string.Compare(item2.Id, item1.Id); }); </code></pre> <p>but it does not sort the list correctly. (using linq.OrderBy() yields same result).<br> but the following code sorts correctly.</p> <pre><code>List<string> timeZoneList1 = new List<string>(); foreach (TimeZoneInfo timeZoneInfo in TimeZoneInfo.GetSystemTimeZones()) timeZoneList1.Add(timeZoneInfo.Id); timeZoneList1.Sort((item1, item2) => { return string.Compare(item1, item2); }); </code></pre> <p>what is the problem? what do i missing? </p> <p>really?<br> no one knows the answer?</p> <p>--------------------------- EDIT ------------------------------------<br> where as i assign the list to a Combobox, it will appears in the wrong order but it will be fixed when i set the DisplayMember of the Combobox. can any one explain this behavior? </p> |
2,598,329 | 0 | <p>They are buffered, but I don't know on what level or what the limit is.</p> <p><a href="http://tangentsoft.net/wskfaq/" rel="nofollow noreferrer">http://tangentsoft.net/wskfaq/</a> is a great resource you might find useful for any winsock related issue.</p> |
39,122,445 | 0 | <p>Constructor taking classes to register refreshes context internally - try to set class and refresh manually after setting parent context.</p> <pre><code>private void createChildContext() { final AnnotationConfigEmbeddedWebApplicationContext childContext = new AnnotationConfigEmbeddedWebApplicationContext(); childContext.setParent(this.applicationContext); childContext.setId(this.applicationContext.getId() + ":child"); childContext.register(ChildConfiguration.class); childContext.refresh(); } </code></pre> |
16,456,194 | 0 | <p>You may have to use a callback here</p> <pre><code>var list = document.getElementById('SomeList'); var items = list.getElementsByTagName('li'); var i = 0; var myFunction1 = function() { if ( i < items.length ) { // Do some code with items[i] i++; setTimeout(myFunction1, 1500); } else { // No more elements return; } } </code></pre> <p>This way your <code>myFunction1</code> will execute every 1.5 seconds.</p> |
15,863,381 | 0 | django formset - not able to update entries <p>I want to update a formset that can have different entries. I will able to present the formset pre populated with the correct data, however I'm doing something wrong since it does not update but creates a new instance..</p> <p>I'm seen <strong>inlineformset_factory</strong> however since I'm passing more than one value to the formset I was not able to work with it..</p> <p>If anyone has any pointer I will truly appreciate it!</p> <p>views.py</p> <pre><code> epis = Contact.objects.filter(episode=int(value)) ContactSet = formset_factory(Contact1Form, extra=len(epis), max_num=len(epis)) if request.method =='POST': formset = ContactSet(request.POST) if formset.is_valid(): for form in formset.forms: age = form.cleaned_data['age'] bcg = form.cleaned_data['bcg_scar'] radio = form.cleaned_data['radiology'] profile = form.save(commit=False) for i in epis: profile.contact = i fields = {'age': age, 'bcg_scar': bcg, 'radiology': radio} for key, value in fields.items(): if value == u'': setattr(profile, key, None) else: setattr(profile, key, value) profile.save() return render_to_response('success.html', {'location': location}) else: dic = [] for c in epis: aux = {} for f in c._meta.fields: if f.name not in ['contact_id', 'episode']: aux[f.name] = getattr(c, f.name) dic.append(aux) formset = ContactSet(initial=dic) return render_to_response('form.html', { 'msg': msg, 'location': location, 'formset': formset, 'word': word }) </code></pre> <p>forms.py </p> <pre><code> class ContactForm(forms.ModelForm): affinity = forms.ModelChoiceField(queryset=Affinity.objects.all(), label=ugettext("Affinity")) age = forms.IntegerField(label=ugettext("Age when diagnosed"), required=False) MAYBECHOICES = ( ('', '---------'), (ugettext('Yes'), ugettext('Yes')), (ugettext('No'), ugettext('No'))) bcg_scar = forms.ChoiceField(choices=MAYBECHOICES, label=ugettext( "BCG scar"), required=False) radiology = forms.ModelChoiceField(queryset=Radiology.objects.all(), label=ugettext("Radiology"),required=False) class Meta: model = Contact </code></pre> <p>Any pointers would be of great help!</p> <p><strong>EDIT</strong></p> <p>After some suggestions from Catherine</p> <pre><code> formset = ContactSet(request.POST, queryset=epis) </code></pre> <p>which gave me this error:</p> <pre><code> __init__() got an unexpected keyword argument 'queryset' </code></pre> <p>I try changing </p> <pre><code> from django.forms.models import modelformset_factory ContactSet = modelformset_factory(Contact1Form, extra=len(epis), max_num=len(epis)) </code></pre> <p>and this error appeared:</p> <pre><code>'ModelFormOptions' object has no attribute 'many_to_many' </code></pre> <p>and then saw that to solve this error I will need to use the name of the model instead.</p> <pre><code>ContactSet = modelformset_factory(Contact, extra=len(epis), max_num=len(epis)) </code></pre> <p>and I get a MultiValueDictKeyError</p> |
40,025,364 | 0 | Cannot perform LINQ complex object search in Entity Framework <p>I have entities in the DB which each contain a list of key value pairs as metadata. I want to return a list of object by matching on specified items in the metadata.</p> <p>Ie if objects can have metadata of KeyOne, KeyTwo and KeyThree, I want to be able to say "Bring me back all objects where KeyOne contains "abc" and KeyThree contains "de"</p> <p>This is my C# query</p> <pre><code> var objects = repository.GetObjects().Where(t => request.SearchFilters.All(f => t.ObjectChild.Any(tt => tt.MetaDataPairs.Any(md => md.Key.ToLower() == f.Key.ToLower() && md.Value.ToLower().Contains(f.Value.ToLower()) ) ) ) ).ToList(); </code></pre> <p>and this is my request class</p> <pre><code>[DataContract] public class FindObjectRequest { [DataMember] public IDictionary<string, string> SearchFilters { get; set; } } </code></pre> <p>And lastly my Metadata POCO</p> <pre><code>[Table("MetaDataPair")] public class DbMetaDataPair : IEntityComparable<DbMetaDataPair> { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } [Required] public string Key { get; set; } public string Value { get; set; } } </code></pre> <p>The error I get is</p> <blockquote> <p>Error was Unable to create a constant value of type 'System.Collections.Generic.KeyValuePair`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types or enumeration types are supported in this context.</p> </blockquote> |
37,687,231 | 0 | Java jersey validation <p>I'm using the validation in Java Jersey, and i'm building an application where it should be possible to save a draft of something. But before it is published, i would like it to be valid, using the annotations in the view model. When publishing, the same savemethod, for draft, is invoked. Therefor i cannot use the annotation in the method (methodName(@Valid ViewmodelName)). Can i somehow invoke a method to validate the annotations in the viewModel? Something like model->isValid(). Alternatively i could make two viewmodels; one for draft and one for published, but seems kind of double work.</p> <p>Best regards</p> |
24,696,399 | 0 | <p>Did you try:</p> <pre><code><base target="_parent" /> </code></pre> <p>?</p> |
604,885 | 0 | <p>Just check to see if the ID passed to the controller methods is an integer.</p> <pre><code>if params[:id].is_a?(Integer) @user = User.find params[:id] else @user = User.find_by_login params[:id] </code></pre> <p>No need to add special routes.</p> |
25,439,091 | 0 | Java matrix library using direct memory access <p>Are there any matrix libraries for Java/Scala that wrap blas/lapack and that use direct memory access, either ByteBuffers or unsafe.getFloat access? It seems like this approach would avoid all the copying of arrays that occurs when crossing the JNI boundary. </p> |
4,619,620 | 0 | <p>you can certainly do block selection by hold down the Alt key while doing a selection</p> |
15,267,182 | 0 | Trigger Disable User <p>I have a problem and question. The SQL trigger in my SQL Server has been disabled. And I want to learn who disable this triger. Is there any way to get username who disable MSSQL trigger? By SQL query or like that? Regards.</p> |
19,521,497 | 0 | Convert google map url to coordinates <p>I want to convert this google map url "http//maps.google.com/maps?f=q&q=14.674518%2C120.549043&z=16" to just value of latitude and longitude.</p> <p>Here's my code:</p> <pre><code>$string='http://maps.google.com/maps?f=q&q=14.674518%2C120.549043&z=16'; $regex=' , http://maps\.google\.com/maps\?q=\K[^&]+,'; preg_match($regex,$string,$m); echo $m[0].'<br />'; </code></pre> <p>Thanks!</p> |
Subsets and Splits