pid
int64
2.28k
41.1M
label
int64
0
1
text
stringlengths
1
28.3k
40,813,220
0
PHP open source multi user login <p>I've had, I believe, a great business idea so I’ve decided to try develop a minimum viable product myself.</p> <p>A long, long time ago I taught myself asp classic and built a couple of apps so I have some development experience. I haven't done much since (apart from a few basic php sites for friends) and I'm not a natural coder though and find it quite hard going.</p> <p>Bearing this in mind and considering the importance of proper security I'm trying to give myself a head start so have been looking for an open source (or paid if it’s not too much) PHP single-db multi-tenant framework or site template.</p> <p>The idea I am working on is aimed towards very small businesses and in a nutshell:</p> <p>User A should be able to login and add and retrieve data that only he/she can see. User B should be able to login and add and retrieve data that only he/she can see.</p> <p>It’s pretty standard stuff but as far as I can tell, everything I’ve found so far is aimed towards managing multiple users across a single secure area (e.g. User Frosting) rather than multiple users across their own secure areas </p> <p>Does such a template/framework exist?</p> <p>Alternatively, can somebody recommend a PHP framework that’s good for beginners with a decent supply of starter templates/tutorials? Innomatic keeps cropping up in my searches but I fear that it may be more advanced and more “full-featured” than necessary.</p> <p>Any advice, opinions or pointers towards relevant material would be massively appreciated.</p> <p>Thanks</p> <p>Stu</p>
39,281,786
0
jQuery change css background when y-axis scroll reaches a certain depth <p>After scrolling down 600px, I would like a css background-image to appear from no image to a decided background-image (image 1); however, above 600px, I would like to change to another image (image 2). I want this action to repeat itself without having to refresh the page, as well.</p> <p>Here is my code:</p> <p>jQuery:</p> <pre><code>$(window).scroll(function() { var y_scroll_pos = window.pageYOffset; var scroll_pos_test = 800; // set to whatever you want it to be if(y_scroll_pos &gt; scroll_pos_test) { $("square").css("background-image", "url(images/comp_rel/square.png)"); } else { $("square").css("background-image","url(images/comp_rel/Box.gif)"); } }); </code></pre> <p>I know I'm missing something simple, I just can't figure it out. Any thoughts? Thanks.</p>
40,159,956
0
Azure Service Bus: Which message type? <p>I'm going to write an app under Xamarin for iPhone/Android/WindowsPhone that gets continuus data from a server and also sends back continuus data (~ every 10 seconds). I'm going to use Microsoft Azure. I've found that the service bus could help me. What type of messages (relay / brokered) should I use?</p> <p>Imagine a service where you see the actual traffic situation. Every client sends it's anonymous traffic data to the server and it sends the state back to all receivers.</p> <p>I've viewed <a href="https://azure.microsoft.com/en-us/documentation/articles/service-bus-relay-tutorial/" rel="nofollow">this tutorial too</a>, ist says</p> <blockquote> <p>The main difference between a WCF and a Service Bus service is that the > endpoint is exposed in the cloud instead of locally on your computer.</p> </blockquote> <p>What does this mean? I need an endpoint locally on a smartphone. Is this usable?</p> <p>I've read <a href="https://azure.microsoft.com/en-us/documentation/articles/service-bus-messaging-overview/" rel="nofollow">this article</a>. I understand that for relayed messaging, both sender and receiver have to be online and it's a centralized (star-topology) communcation model. That would conver my needs. What confuses me is the word "relay". Does it mean, the messages are repeated somehow?</p> <p>The brokered messages don't fit what I want becaus in my case it's irrelevant for the receiver if it is offline. The messages don't have to be stored.</p>
3,589,043
0
<p>There are a few algorithms outlined on <a href="http://en.wikipedia.org/wiki/Algorithmics_of_sudoku" rel="nofollow noreferrer">Algorithmics of sudoku</a>. What you're describing sounds like a backtracking approach.</p>
17,686,717
0
<p>You can use <code>Control.Region</code> for this purpose</p> <pre><code>GraphicsPath path = new GraphicsPath(); path.AddEllipse(control.ClientRectangle); control.Region = new Region(path); </code></pre> <p>try this, you can create any shape using <code>GraphicsPath</code> and set it to <code>Region</code> for instance I created ellipse.</p> <p><strong>Edit</strong></p> <p>If you just want to set BackColor = Color.Transparent. for some reason some controls doesn't allow this. in such cases you can do the following </p> <pre><code>public class CustomControl1 : Control { public CustomControl1() { this.SetStyle(ControlStyles.SupportsTransparentBackColor, true); } } </code></pre> <p>Create a descendant of your control and set <code>this.SetStyle(ControlStyles.SupportsTransparentBackColor, true);</code> that should do the trick</p>
11,043,170
0
<p>I would also recommend sugarCRM because of the larger community and availability of third party plug ins, having worked with both i can say that sugarCRM's studio gives you a bit more flexibility. There are also many plug ins; I would recomend the ModernAqua theme to improve look and feel.</p> <p>I'll give you a warning however, sugarCRM is not always nice to work with. Its code is poorly documented and maintainance is a big hastle. upgrading with custom code is still error prone through version 6.x despite what they say and changes will be overwritten by the module builder.</p> <p>So in short, go with Sugar but think carefully before customizing it too much because it can be a pain to maintain.</p>
18,123,423
0
<p>It can be solved rather simply by assigning the border properties only to the <code>table tag</code> instead of assigning them to the <code>th tag</code> and <code>td tag</code>.</p> <pre><code>table { background: #ccc; border-top-left-radius: 20px; border-top-right-radius: 20px; border-top: 1px solid red; } th { width: 70px; } th, td { text-align: left; } </code></pre> <p><a href="http://jsfiddle.net/Tomer123/z5832/9/" rel="nofollow">http://jsfiddle.net/Tomer123/z5832/9/</a></p>
1,548,449
0
<p>Can you break the app into 2 separate web applications that run from the same root directory? Just put the complied C# dll in the bin with the compiled VB.net dll and place all of the aspx pages wherever they would need to be for your site structure.</p> <p>I haven't tried this myself, but it should work. You'll have to create a separate project and reference any data layers, etc. Just move the C# code to the new app and see how that goes. Not the best solution, but it beats converting from one language to another.</p>
13,452,552
0
<p>You can get help from following link </p> <p><a href="http://msdn.microsoft.com/en-us/library/610xe886%28v=vs.80%29.aspx?cs-save-lang=1&amp;cs-lang=vb#code-snippet-1" rel="nofollow">http://msdn.microsoft.com/en-us/library/610xe886%28v=vs.80%29.aspx?cs-save-lang=1&amp;cs-lang=vb#code-snippet-1</a></p>
22,035,915
0
How to specify the number of parallel tasks executed in Parallel.ForEach? <p>I have ~500 tasks, each of them takes ~5 seconds where most of the time is wasted on waiting for the remote resource to reply. I would like to define the number of threads that should be spawned myself (after some testing) and run the tasks on those threads. When one task finishes I would like to spawn another task on the thread that became available.</p> <p>I found <code>System.Threading.Tasks</code> the easiest to achieve what I want, but I think it is impossible to specify the number of tasks that should be executed in parallel. For my machine it's always around 8 (quad core cpu). Is it possible to somehow tell how many tasks should be executed in parallel? If not what would be the easiest way to achieve what I want? (I tried with threads, but the code is much more complex). I tried increasing <code>MaxDegreeOfParallelism</code> parameter, but it only limits the maximum number, so no luck here...</p> <p>This is the code that I have currently:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { class Program { private static List&lt;string&gt; _list = new List&lt;string&gt;(); private static int _toProcess = 0; static void Main(string[] args) { for (int i = 0; i &lt; 1000; ++i) { _list.Add("parameter" + i); } var w = new Worker(); var w2 = new StringAnalyzer(); Parallel.ForEach(_list, new ParallelOptions() { MaxDegreeOfParallelism = 32 }, item =&gt; { ++_toProcess; string data = w.DoWork(item); w2.AnalyzeProcessedString(data); }); Console.WriteLine("Finished"); Console.ReadKey(); } static void Done(Task&lt;string&gt; t) { Console.WriteLine(t.Result); --_toProcess; } } class Worker { public string DoWork(string par) { // It's a long running but not CPU heavy task (downloading stuff from the internet) System.Threading.Thread.Sleep(5000); return par + " processed"; } } class StringAnalyzer { public void AnalyzeProcessedString(string data) { // Rather short, not CPU heavy System.Threading.Thread.Sleep(1000); Console.WriteLine(data + " and analyzed"); } } } </code></pre>
14,242,298
0
Is there something wrong with my OnLocationChanged? <p>My location Logger Service class does not provide me with updated informations about my location. Is there something wrong with me OnLocationChanged?</p> <pre><code>public class LocationLoggerService extends Service implements LocationListener { Location location; // location String towers; // Declaring a Location Manager public LocationManager locationManager; @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { ourLocation(); Criteria crit = new Criteria(); towers = locationManager.getBestProvider(crit, false); location = locationManager.getLastKnownLocation(towers); // Just af test here: String hej1 = Double.toString(location.getLatitude()); String hej2 = Double.toString(location.getLongitude()); Toast.makeText(this, "Fra Oncreate: /nLat: " + hej1 + "Long: " + hej2, Toast.LENGTH_LONG).show(); } public void ourLocation() { // Find my current location locationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, this); } </code></pre> <p>onLocationChanged method does not provide me with new informations. I tried out with some test(toast), but its like it does not read this method.</p> <pre><code>@Override public void onLocationChanged(Location loc) { if (loc != null) { // Testing the position String hej3 = Double.toString(loc.getLatitude()); String hej4 = Double.toString(loc.getLongitude()); Toast.makeText(this, "loc: " + "Lat: " + hej3 + "Long: " + hej4, Toast.LENGTH_LONG).show(); } } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } @Override public void onStatusChanged(String s, int i, Bundle b) { } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); Toast.makeText(this, "MyAlarmService.onDestroy()", Toast.LENGTH_LONG) .show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // this service will run until we stop it return START_STICKY; } } </code></pre> <p>My manifest</p> <pre><code>&lt;uses-permission android:name="android.permission.INTERNET" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.VIBRATE" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_LOCATION" /&gt; &lt;uses-permission android:name="android.permission.ACCESS_GPS" /&gt; &lt;service android:name="LocationLoggerService" android:enabled="true" android:exported="false" android:label="LocationLoggerService" /&gt; &lt;/application&gt; </code></pre>
35,477,722
0
<p>I had the same problem and my issue was that I copied my autofac configuration from a MVC project and was registering my dependencies with <code>InstancePerRequest</code>. When I changed that to <code>InstancePerDependency</code> instead it solved the problem and <code>GetRequestLifetimeScope</code> was working.</p> <pre><code>builder.RegisterType&lt;X&gt;().As&lt;IX&gt;().InstancePerDependency(); </code></pre>
28,509,386
0
C# converting int to hex <p>This is a small snippet of the code I have written in Visual Studio. I need to convert the int <code>add</code> into an hex value (later into a string) as I am accessing the memory of a uC. But when I view the variable during debugging it displays it as a string "add16". What could I be doing wrong?</p> <pre><code>for (int add = 0; add &lt;= 0xfffff; ) { for (int X = 0; X &lt;= 15; X++) { string address = add.ToString("add16"); addr = Convert.ToString(address); port.WriteLine(String.Format("WRBK:{0}:{1}", addr, parts[X])); add++; } } </code></pre>
21,229,439
0
Loop through nested object in jquery <p>Iam newbie to jquery. I need to parse an JSON. I tried with $each statement but stuck with [object,object]looping. here is the code which i used for parsing the JSON. Help me out of this.</p> <pre><code>var myjson='[{"isTruncated": "false","nextMarker": "null","marker": "null","prefix": "Mymedia/mysys/","contents": [{"deviceInfo": "null","lastModified": "Thu Dec 26 16:36:42 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key":"Mymedia/mysys/audio_$folder$","size": "0"},{"deviceInfo": null,"lastModified": "Thu Dec 26 16:36:11 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key": "Mymedia/mysys/doc_$folder$","size": "0"},{ "deviceInfo": null,"lastModified": "Thu Dec 26 16:36:20 IST 2013", "etag": "d41d8cd98f00b204e9800998ecf8427e","key": "Mymedia/mysys/imge_$folder$","size": "0"},{"deviceInfo": null,"lastModified": "Thu Dec 26 16:36:56 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key":"Mymedia/mysys/others_$folder$","size": "0"},{"deviceInfo": null,"lastModified": "Thu Dec 26 16:36:32 IST 2013","etag": "d41d8cd98f00b204e9800998ecf8427e","key": "Mymedia/mysys/video_$folder$","size": "0"}],"name": "name", "statusCode": "200","statusMessage": "Success","error": null}]'; var dataobj = $.parseJSON(JSON.stringify(myjson)); $.each(dataobj, function (key, val) { alert(key + val); if (key == "contents") { $.each(val, function (mykey, values) { alert(mykey + values) }); $.each(values, function (key, pairs) {alert(pairs) }); } }); </code></pre> <p>Iam unable to loop through JSON object(contents) and to get the items inside it. I need to get key inside contents object.Point me where i went wrong.</p>
37,463,911
0
Does App store reject icons in the app for being shiny or glossy <p>I am designing icons to include in my app and was designing them to be glossy and shiny. Then found out that app store accepts flat icons without rounded corners by doing research across internet as I did not find much information in <code>iOS Human Interface Guidelines</code> about icons. I would appreciate if anyone can direct me or provide me guidelines about designing <code>icons in app</code> as well as <code>app icon</code> for app store. I am completely new to this and like to know whether there are any limitations on <code>background images</code> and <code>images</code> used in the app as well.</p>
17,250,003
0
Django, filter records from model method? <p>I'm trying to filter records using a model method but am unsure how to implement it in the view.</p> <p>Should it be done in this way, or completely in the view in some other manor?</p> <p>Here's my model below:</p> <pre><code>class Message(models.Model): msg_id = models.IntegerField(unique=True) user = models.ForeignKey(User) message = models.CharField(max_length=300) added = models.DateTimeField('added') def about_cats(self): matches = ['cat', 'kitty', 'meow'] return any(s in self.message for s in matches) def __unicode__(self): return self.message </code></pre>
34,976,193
0
<p>Removing the layout is not a solution.</p> <p>As you are only removing the layout defined by you. One of the indirect Superclass of MainActivity defines a default layout that get inflated when you call <code>super.onCreate(...)</code>. Basically it remove child views defined by you in layout.</p> <p>To avoid the activity from loading you need to remove its declaration the <code>AndroidManifest.xml</code>. The activity will not loaded than.</p> <pre><code>&lt;activity android:name=".MainActivity" android:label="@string/app_name" &gt; &lt;intent-filter&gt; &lt;action android:name="android.intent.action.MAIN" /&gt; &lt;category android:name="android.intent.category.LAUNCHER" /&gt; &lt;/intent-filter&gt; &lt;/activity&gt; </code></pre> <p>But to successfully run the app there should be at least one main activity with the <code>intent-filter</code> defined by above code otherwise Andorid system can not start your application.</p> <p>or</p> <p>You can create another activity in your application and change the name of <code>MainActivity</code> in <code>AndroidManifest.xml</code></p> <p>Hope it helps.</p>
2,090,043
0
<p>I think what you want to customize is <code>compilation-parse-errors-filename-function</code>, which is a function that takes a filename, and returns a modified version of the filename to be displayed. This is a buffer local variable, so you should set it in each buffer that will be displaying python errors (there is probably an appropriate hook to use, I do not have python mode installed so I cannot look it up). You would use <code>propertize</code> to return a version of the input filename that acts as a hyperlink to load the actual file. propertize is well documented in the elisp manual.</p> <p>If compilation-parse-errors-filename-function is not getting called, then you want to add a list to <code>compilation-error-regexp-alist-alist</code> (that does say alist-alist, that is not a typo) which is a list of mode names followed by regular expressions to match errors, and numerical indexes of the matching line number, filename etc. info in the error regexp match.</p>
40,431,541
0
Get child element distance from parent top <p><a href="https://i.stack.imgur.com/vlROs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vlROs.png" alt="Child distance from top parent"></a></p> <p>Let's say I have an <code>&lt;li&gt;</code> element inside a scrollable div and the scroll was set to show that element in the viewport. </p> <p>I need to get the distance between that element and its scrollable parent, as shown in the picture above, but both <code>element.getBoundingClientRect().top</code> and <code>element.offsetTop</code> give me the wrong values. Can that be done?</p> <p>I made a pen, to make things a little bit easier:</p> <p><a href="http://codepen.io/Darksoulsong/pen/LbYMex" rel="nofollow noreferrer">http://codepen.io/Darksoulsong/pen/LbYMex</a></p> <p>A piece of my code:</p> <pre><code>document.addEventListener("DOMContentLoaded", function(event) { var selectedEl = document.getElementById('consequatur-51'); var selectedElRect = selectedEl.getBoundingClientRect(); var sidebar = document.getElementById('sidebar'); sidebar.scrollTop = selectedEl.offsetTop - 60; document.getElementById('offsetTop').innerText = selectedEl.offsetTop; document.getElementById('rectTop').innerText = selectedElRect.top; }); </code></pre>
14,422,089
0
Max of set in Isabelle <p>How can I find the maximum element in a set of numbers (nat) in Isabelle. The max function doesn't work, as it is only defined to take the maximum of two elements. I have an idea of how I could implement it using a reduce like function, but I don't know how to pick one random element from a set.</p>
40,241,444
0
<p>As to why, look at the case of <code>36 + 'abc'</code> Should this convert <code>36</code> to a string and concatenate the strings, or should it convert <code>abc</code> to a numeric value and add the numbers? There's no right answer, and so Python doesn't guess unless it has specific rules about those two types.</p>
36,446,788
0
Downloading webpages programmatically <p>I need to download certain web pages from a web site for my research. I tried to download them using Darcy Wripper, WinHTTrack and C# WebClient method. It happens so that some of the pages get downloaded while (majority) others throw error. For example I have copied this error from Darcy Wripper. </p> <blockquote> <p>27 <a href="http://www.dawn.com/news/515958/animadversion-only-the-globes-looked-golden" rel="nofollow">http://www.dawn.com/news/515958/animadversion-only-the-globes-looked-golden</a> Error N/A N/A 500 0 403 - Request Aborted 11 <a href="http://www.dawn.com/news/813115/flavours-of-culture" rel="nofollow">http://www.dawn.com/news/813115/flavours-of-culture</a> Error N/A N/A 500 0 403</p> </blockquote> <p>The same webpage opens in Firefox (sometimes there is an error that we are in maintenance, but next try opens the page). My question: Is there a method in C# to download such problematic pages? I also tried to look for a Firefox Wrapper for .Net with no luck. I was under the impression that maybe a I can open these pages in Firefox using an array of links one by one and save them from a command line program. Any help or insight in this regard will be highly appreciated. Regards</p>
16,020,660
0
<p>If you're using <a href="http://www.eclipse.org/collections/" rel="nofollow">Eclipse Collections</a> (formerly GS Collections), you can use the <code>partition</code> method on all <code>RichIterables</code>.</p> <pre><code>MutableList&lt;Integer&gt; integers = FastList.newListWith(-3, -2, -1, 0, 1, 2, 3); PartitionMutableList&lt;Integer&gt; result = integers.partition(IntegerPredicates.isEven()); Assert.assertEquals(FastList.newListWith(-2, 0, 2), result.getSelected()); Assert.assertEquals(FastList.newListWith(-3, -1, 1, 3), result.getRejected()); </code></pre> <p>The reason for using a custom type, <code>PartitionMutableList</code>, instead of <code>Pair</code> is to allow covariant return types for getSelected() and getRejected(). For example, partitioning a <code>MutableCollection</code> gives two collections instead of lists.</p> <pre><code>MutableCollection&lt;Integer&gt; integers = ...; PartitionMutableCollection&lt;Integer&gt; result = integers.partition(IntegerPredicates.isEven()); MutableCollection&lt;Integer&gt; selected = result.getSelected(); </code></pre> <p>If your collection isn't a <code>RichIterable</code>, you can still use the static utility in Eclipse Collections.</p> <pre><code>PartitionIterable&lt;Integer&gt; partitionIterable = Iterate.partition(integers, IntegerPredicates.isEven()); PartitionMutableList&lt;Integer&gt; partitionList = ListIterate.partition(integers, IntegerPredicates.isEven()); </code></pre> <p><strong>Note:</strong> I am a committer for Eclipse Collections.</p>
1,857,477
0
<p>The 260 character limitation is not a limitation of the file system, but of the Win32 API. Win32 defines MAX_PATH as 260 which is what the API is using to check the length of the path passed into functions like FileCreate, FileOpen, etc. (which are used by .NET in the BCL).</p> <p><b>However, you can bypass the Win32 rules and create paths up to 32K characters.</b> Basically you need to use the "\\?\C:\MyReallyLongPath\File.txt" syntax which you may not have seen before. Last I checked, the File and FileInfo classes in .NET prevented you from using this type of path, but you can definitely do it from C/C++. Here's a link for more info.</p> <p><a href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx</a></p>
7,843,134
0
<p>Use this:</p> <pre><code>if (get_magic_quotes_gpc()) { $skill = stripslashes($row['skill']); $skill = mysql_real_escape_string($skill); } else { $skill = mysql_real_escape_string($row['skill']); } $sql = 'select * from table where column = "' . $skill . '"'; </code></pre> <p>EDIT: Sorry, I've just realised that <code>$row['skill']</code> probably hasn't come from GET/POST/COOKIE and so <code>get_magic_quotes_gpc()</code> is probably irrelevant. Just go straight for the <code>stripslashes()</code>:</p> <pre><code> $skill = stripslashes($row['skill']); $skill = mysql_real_escape_string($skill); $skill = mysql_real_escape_string($row['skill']); </code></pre>
21,278,384
0
<p>Have a look at <a href="http://phantomjs.org" rel="nofollow">PhantomJS</a> - a headless WebKit browser with full javascript support which you can call and interact with via PHP.</p>
36,548,567
0
symfony2: class loading/namespace handling - difference between prod/dev environments? <p>what's exactly the difference in class autoloading and namespace handling between symfony2's app_dev.php and app.php or dev/prod environment (symfony 2.8.4).</p> <p>When I run it in dev environment through app_dev.php all is fine, when I run it in prod through app.php I get an Internal Server error 500 (nothing written in symfony's prod.log). Looking into apache's error.log I see:</p> <pre><code>PHP Fatal error: Class 'SSMCRM\\Common\\ProductionTemplateMapper' not found in /var/[...] </code></pre> <p>And yes, I cleared the prod cache...</p> <p>app.php: <pre><code>use Symfony\Component\HttpFoundation\Request; /** * @var Composer\Autoload\ClassLoader */ $loader = require __DIR__.'/../app/autoload.php'; include_once __DIR__.'/../app/bootstrap.php.cache'; // Enable APC for autoloading to improve performance. // You should change the ApcClassLoader first argument to a unique prefix // in order to prevent cache key conflicts with other applications // also using APC. /* $apcLoader = new Symfony\Component\ClassLoader\ApcClassLoader(sha1(__FILE__), $loader); $loader-&gt;unregister(); $apcLoader-&gt;register(true); */ //require_once __DIR__.'/../app/AppCache.php'; $kernel = new AppKernel('prod', false); $kernel-&gt;loadClassCache(); //$kernel = new AppCache($kernel); // When using the HttpCache, you need to call the method in your front controller instead of relying on the configuration parameter //Request::enableHttpMethodParameterOverride(); $request = Request::createFromGlobals(); $response = $kernel-&gt;handle($request); $response-&gt;send(); $kernel-&gt;terminate($request, $response); </code></pre> <p>app_dev.php:</p> <pre><code>&lt;?php use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Debug\Debug; // If you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#checking-symfony-application-configuration-and-setup // for more information //umask(0000); // This check prevents access to debug front controllers that are deployed by accident to production servers. // Feel free to remove this, extend it, or make something more sophisticated. if (isset($_SERVER['HTTP_CLIENT_IP']) || isset($_SERVER['HTTP_X_FORWARDED_FOR']) || !(in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', 'fe80::1', '::1', '192.168.33.1', //for vagrant box )) || php_sapi_name() === 'cli-server') ) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } /** * @var Composer\Autoload\ClassLoader $loader */ $loader = require __DIR__.'/../app/autoload.php'; Debug::enable(); $kernel = new AppKernel('dev', true); $kernel-&gt;loadClassCache(); $request = Request::createFromGlobals(); $response = $kernel-&gt;handle($request); $response-&gt;send(); $kernel-&gt;terminate($request, $response); </code></pre> <p>in the autoload.php I added our legacy classes to the loader:</p> <pre><code>$loader-&gt;add('SSMCRM', __DIR__.'/../web/legacy/classes'); </code></pre>
37,869,574
0
How to mock up Blog and Post when one Blog contains many Posts <p>Say we have</p> <pre><code>public class BloggingContext : DbContext { public BloggingContext(DbContextOptions&lt;BloggingContext&gt; options) : base(options) { } public DbSet&lt;Blog&gt; Blogs { get; set; } public DbSet&lt;Post&gt; Posts { get; set; } } public class Blog { public int BlogId { get; set; } public string Url { get; set; } public List&lt;Post&gt; Posts { get; set; } } public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public int BlogId { get; set; } public Blog Blog { get; set; } } </code></pre> <p>I want to seed data for <code>Blog</code> and <code>Post</code> in unit test. However Blog contains Posts and Post contains Blog.</p> <p><strong>[EDIT]</strong></p> <p>I want to pass the <code>DbContext</code> to the controller. Therefore I have to mock up <code>DbContext</code> and <code>DbSet</code>. For the <code>DbSet</code>, I need to seed some dummy data.</p> <p>For example:<br> In asp.net mvc controller</p> <pre><code>public IActionResult GetBlog(int id) { Blog blog = _context.Blog.FirstOrDefault(x =&gt; x.BlogId == id); return View(Blog); } </code></pre> <p>In the test </p> <pre><code>[Fact] public void Get_blog_1_returns_google() { // Act var result = _controller.GetBlog(1) as ViewResult; // Assert Assert.IsType(typeof(Blog), result.ViewData.Model); Blog model = (Blog)result.ViewData.Model; Assert.Equal("google", model.Url); } </code></pre> <p>But I have to seed data for the test first.</p> <pre><code>public class BlogControllerTest { private BloggingContext _context; private BlogController _controller; public BlogControllerTest() { // Seed data _context.Blog.Add(new Blog() { BlogId = 1, Url = "google", // how about Post }); //..other code... } //...other code removed for brevity } </code></pre> <p>How to mock up them?</p>
6,339,689
0
<p>may be <a href="http://stackoverflow.com/questions/1404651/iphone-how-to-check-the-airplane-mode">this</a></p> <p>helps</p>
2,950,848
0
<p>You need to use a filter file, a filter file can say what file patterns to include, exclude among other things... There's documentation here <a href="http://findbugs.sourceforge.net/manual/filter.html" rel="nofollow noreferrer">http://findbugs.sourceforge.net/manual/filter.html</a></p>
7,424,804
0
Is there a way to use a keyword as a function in Common Lisp, as one does in Clojure? <p>In Clojure one can write</p> <pre><code>(:foo {:foo 3 :bar 5}) </code></pre> <p>which evaluates to 3. Is there any way to extend Common Lisp so that a keyword will act as a function that looks itself up?</p>
17,396,377
0
Error while implementing take for a Stream <p>I was trying to solve Exercise 2 from <a href="http://www.manning.com/bjarnason/" rel="nofollow">Functional Programming in Scala</a>. The question is as follows:</p> <blockquote> <p>EXERCISE 2: Write a function take for returning the first n elements of a Stream. def take(n: Int): Stream[A]</p> </blockquote> <p>My solution is as follows:</p> <pre><code> import Stream._ trait Stream[+A]{ def uncons:Option[(A,Stream[A])] def isEmpty:Boolean = uncons.isEmpty def toList:List[A] = { val listBuffer = new collection.mutable.ListBuffer[A] @annotation.tailrec def go(str:Stream[A]):List[A] = str uncons match { case Some((a,tail)) =&gt; listBuffer += a;go(tail) case _ =&gt; listBuffer.toList } go(this) } def take(n:Int):Stream[A] = uncons match { case Some((hd,tl)) if (n &gt; 0) =&gt; cons(hd,tl.take(n-1)) case _ =&gt; Stream() } } object Stream{ def empty[A]:Stream[A] = new Stream[A]{def uncons = None} def cons[A](hd: =&gt; A,tl: =&gt; Stream[A]):Stream[A] = new Stream[A]{ lazy val uncons = Some((hd,tl)) } def apply[A](as: A*):Stream[A] = { if(as.isEmpty) empty else cons(as.head,apply(as.tail: _ *)) } } </code></pre> <p>I store this as Stream2.scala and then from the REPL I execute the following:</p> <pre><code>:load Stream2.scala </code></pre> <p>When the REPL tries to load my script, it barfs with the following errors:</p> <p>scala> :load Stream2.scala</p> <pre><code>Loading Stream2.scala... import Stream._ &lt;console&gt;:24: error: type mismatch; found : Stream[A] required: scala.collection.immutable.Stream[?] case Some((hd,tl)) if (n &gt; 0) =&gt; cons(hd,tl.take(n-1)) ^ &lt;console&gt;:25: error: type mismatch; found : scala.collection.immutable.Stream[Nothing] required: Stream[A] case _ =&gt; Stream() ^ &lt;console&gt;:11: error: object creation impossible, since method tailDefined in class Stream of type =&gt; Boolean is not defined def empty[A]:Stream[A] = new Stream[A]{def uncons = None} ^ &lt;console&gt;:12: error: object creation impossible, since method tailDefined in class Stream of type =&gt; Boolean is not defined def cons[A](hd: =&gt; A,tl: =&gt; Stream[A]):Stream[A] = new Stream[A]{ </code></pre> <p>Can somebody point out what might be going wrong here?</p>
18,697,214
0
Why constructor returns nothing ? or it returns something? <p>I read in many java books that constructor have no returns type , it means that it does not return anything ? is it really happen ? or it may return something ? I want to know the reason.</p> <p>Please anyone give me the technical reason. </p>
25,480,922
0
bash: wait for specific command output before continuing <p>I know there are several posts asking similar things, but none address the problem I'm having.</p> <p>I'm working on a script that handles connections to different <code>Bluetooth low energy</code> devices, reads from some of their handles using <code>gatttool</code> and dynamically creates a <code>.json</code> file with those values.</p> <p>The problem I'm having is that <code>gatttool</code> commands take a while to execute (and are not always successful in connecting to the devices due to <code>device is busy</code> or similar messages). These "errors" translate not only in wrong data to fill the <code>.json</code> file but they also allow lines of the script to continue writing to the file (e.g. adding extra <code>}</code> or similar). An example of the commands I'm using would be the following:</p> <pre><code>sudo gatttool -l high -b &lt;MAC_ADDRESS&gt; --char-read -a &lt;#handle&gt; </code></pre> <p>How can I approach this in a way that I can wait for a certain output? In this case, the ideal output when you <code>--char-read</code> using <code>gatttool</code> would be:</p> <pre><code>Characteristic value/description: some_hexadecimal_data` </code></pre> <p>This way I can make sure I am following the script line by line instead of having these "jumps".</p>
37,148,517
0
<p>Unlike support for other frameworks, I cannot see GWT when I right click project root in Project tab and select "Add Framework support".</p> <p>However, It still works when I select </p> <blockquote> <p>Project Structure → Facets → Add → GWT</p> </blockquote> <p><a href="https://i.stack.imgur.com/Nt8yJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nt8yJ.png" alt="enter image description here"></a></p>
36,340,268
0
NullPointerException while setting LayoutParams <p>I want to add a button programmatically, which LayoutParams should be set too. Unfortunaly the app gives an exception: </p> <blockquote> <p>java.lang.NullPointerException: Attempt to write to field 'int android.view.ViewGroup$LayoutParams.height' on a null object reference</p> </blockquote> <p>I have no idea, why. Could you help me? Here is my code.</p> <pre><code> Button b = new Button(getApplicationContext()); b.setText(R.string.klick); ViewGroup.LayoutParams params = b.getLayoutParams(); params.height = ViewGroup.LayoutParams.MATCH_PARENT; params.height = ViewGroup.LayoutParams.WRAP_CONTENT; </code></pre>
25,116,142
0
How to render a Widget inside a TreeView cell with GTK# <p>I'm developing an application with Mono and Gtk#. Inside my app, I need to use the TreeView control. I'm looking for a way to render a widget inside a cell instead of drawing everything. I have custom widgets that I would like to use inside those cells and I don't want to draw them manually.</p> <p>I have looked over documentations and forums but haven't found a way to do this. I don't think this is impossible since CellRendererCombo and CellRendererToggle seems to render a Widget.</p> <p>Thanks</p>
32,067,338
0
Error: [$rootScope:infdig] 10 $digest() iterations reached <p>I'm trying to show the posts of my json output into my view but I'm getting an error. </p> <p><code>Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! Watchers fired in the last 5 iterations: []</code></p> <p>I did some research and it looks like I'm looping a loop which causes Angular to "crash" before my browser does. But I can't find the error in my code.</p> <p>This is my home state and if I comment out the line <code>return post.getAll();</code> I don't get the error, obviously.</p> <pre><code>.state('home', { url: '/home', templateUrl: '../assets/angular-app/templates/_home.html.haml', controller: 'mainCtrl', resolve: { postPromise: ['posts', function(posts){ return posts.getAll(); }] } }) </code></pre> <p>The getAll(); is referenced here in my service.</p> <pre><code>.factory('posts', [ '$http', function(){ var o = { }; return o; o.getAll = function() { return $http.get('/posts.json').success(function(data){ angular.copy(data, o.posts); }); }; } ]) </code></pre> <p>So I think the error should be in one of these codes, any ideas?</p> <p>I have 2 templates that I include,</p> <p>posts.html.haml</p> <pre><code>%div{"ng-repeat" =&gt; "comment in post.comments | orderBy:'-upvotes'"} {{comment.upvotes}} - by {{comment.author}} %span{:style =&gt; "font-size:20px; margin-left:10px;"} {{comment.body}} %form{"ng-submit" =&gt; "addComment()"} %h3 Add a new comment .form-group %input.form-control{"ng-model" =&gt; "body", :placeholder =&gt; "Comment", :type =&gt; "text"} %button.btn.btn-primary{:type =&gt; "submit"} Post %a{"ui-sref" =&gt; "home"} Home </code></pre> <p>And home.html.haml</p> <pre><code>%form{"ng-submit" =&gt; "addPost()"} %input{:type =&gt; "text", "ng-model" =&gt; "title"} %button{:type =&gt; "submit"} Post %h1 Posts %div{"ng-repeat" =&gt; "post in posts | orderBy: '-upvotes'"} {{ post.title }} - upvotes: {{ post.upvotes }} %a{:href =&gt; "#/posts/{{$index}}"} Comments </code></pre> <p>I've commented both files, and still the error is given.</p>
13,938,263
0
<p>Correct is in the eye of the beholder most of the time. There's often multiple ways to solve an issue. If you want to check for the presence of a bound function and the existence of a DOM Node, then you'll need to capture both after the <code>ready</code> function and compare the <code>typeof</code> variable to function to see if it's true.</p> <pre><code>$(function(){ if($('#flexslider').length &amp;&amp; typeof flexslider == 'function'){ } }); </code></pre>
19,523,949
0
Symbols in email headlines for pear mail <p>I'm trying to put a heart symbol ♥ into the headline of an email which should be sent via the php pear mail package.</p> <p>But the receiver gets a ? instead of the heart so there has to be some mistake. It works if I manually send the email with my mail client.</p> <p>My code is the following:</p> <pre><code>require_once "Mail.php"; $smtp = Mail::factory('smtp', array ('host' =&gt; 'host', 'port' =&gt; port, 'auth' =&gt; true, 'username' =&gt; 'username', 'password' =&gt; 'password'); $headers = array ('From' =&gt; 'sender', 'Subject' =&gt; '♥ test', 'Charset' =&gt; 'utf-8', ); $mail = $smtp-&gt;send($to, $headers, 'heart test'); </code></pre> <p>What do I need to change in order to make the heart display correctly for the receiver of the email?</p>
25,404,839
0
<p>You probably didn't add <code>feincms.module.page</code> to your <code>INSTALLED_APPS</code> as per the <a href="http://www.feinheit.ch/media/labs/feincms/installation.html#configuration" rel="nofollow">documentation</a>. If you follow the traceback, the error appears in <a href="https://github.com/feincms/feincms/blob/master/feincms/views/cbv/views.py#L27" rel="nofollow">get_object()</a> where it tries to access the page model.</p> <p>Are you using an older FeinCMS version? Newer versions raise a warning in that case.</p>
33,758,780
0
Connecting to MongoDB Replica Set behind a Load Balancer <p>I am a little confused on how MongoDB handles replica sets. I have the following setup:</p> <ul> <li>2 Replica set members to store data</li> <li>1 Arbiter</li> <li>Everything is in a Virtual Network</li> </ul> <p>There are two scenarios:</p> <p><strong>Scenario 1</strong></p> <ul> <li>No Load balancer. </li> <li>DataVM0 is accessible at public IP 123.123.12.1</li> <li>DataVM1 is accessible at public IP 123.123.12.2</li> <li>ArbiterVM is accessible public at IP 123.123.12.3</li> </ul> <p>Here, my connection string would look something like:</p> <pre><code>mongodb://123.123.12.1:27017,123.123.12.2:27017,123.123.12.3:27017/?replicaSet=samplereplicaset </code></pre> <p><strong>Scenario 2</strong></p> <ul> <li>Load balancer accessible at public IP 123.123.12.1. </li> <li>DataVM0 is not publicly accessible.</li> <li>DataVM1 is not publicly accessible.</li> <li>ArbiterVM is not publicly accessible.</li> <li>LoadBalancer port 27017 is forwarded to DataVM0 port 27017</li> <li>LoadBalancer port 27018 is forwarded to DataVM1 port 27017</li> <li>LoadBalancer port 27019 is forwarded to ArbiterVM port 27017</li> </ul> <p>Here, my connection string would look something like this:</p> <pre><code>mongodb://123.123.12.1:27017,123.123.12.1:27018,123.123.12.1:27019/?replicaSet=samplereplicaset </code></pre> <hr> <p>Are both these ways to connect equivalent in terms of replica sets? I ask this since in the connection string, I'm not directly connecting to any of the VMs.</p> <p>All VMs are accessible from every other VM in the virtual network. DNS and everything works properly.</p>
6,135,726
0
<p>what about trying</p> <pre><code>has_many :administrators, :class_name =&gt; "User", :conditions =&gt; "role_id = #{Role.find(:name =&gt; 'Admin')}" </code></pre> <p>Assuming the role table had a corresponding model. are you using a specific framework, or home baked authorization?</p>
29,959,309
0
Remove back button from SearchView in toolbar AppCompat <p><img src="https://i.stack.imgur.com/v5NfH.png" alt="enter image description here"></p> <p>How can I remove the back button icon when search view shows up in Toolbar (AppCompat)?</p> <pre><code>toolbar = (Toolbar) findViewById(R.id.tool_bar); // Set an OnMenuItemClickListener to handle menu item clicks toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { // Handle the menu item return true; } }); // Inflate a menu to be displayed in the toolbar toolbar.inflateMenu(R.menu.menu_main); toolbar.setTitle(""); setSupportActionBar(toolbar); actionBar = getSupportActionBar(); // this works for normal back button but not for one appears on tapping SearchView actionBar.setDisplayHomeAsUpEnabled(false); </code></pre>
19,301,798
0
Stripe card authentication passed from iPhone, failed on server <p>The card was validated by Stripe's iPhone code, where I create a card, send to their server and receive a stripe token.</p> <p>When I charge that token, the server receives an error from Stripe saying invalid CVC.</p> <p>I checked Zip code &amp; CVC verification required in my account settings.</p> <p>Is there a way to authenticate the credit card prior to charging it?</p>
22,547,433
1
python regex re.sub with strings <p>I am trying to use regex expressions to build a word filter. Currently, i have something in this form: </p> <pre><code>value = re.sub(r'(([q])[ ]*[w][ ]*[e][ ]*[r])', r'\2***', value, flags=re.IGNORECASE) </code></pre> <p>I would like to be able to do something like </p> <pre><code>value = regex_gen("qwer", value) </code></pre> <p>where my regex_gen function looks like: </p> <pre><code>def regex_gen(filter_word, string): first = 0 regex = "r'(" regex_result = "r'" for c in filter_word: if first == 0: regex += "([" + c + "])" regex_result += "\2" first += 1 else: regex += "[ ]*[" + c + "]" regex_result += "*" regex += ")'" regex_result += "'" final = re.sub(regex, regex_result, string, flags=re.IGNORECASE) return final </code></pre> <p>but my regex_gen function isn't working so far, i am only accounting for white spaces in between the characters and character case. if other approaches to a word filter are easier to implement than that would work too</p>
5,166,663
0
<p>try:</p> <pre><code>$myObjectCollection = ...; $minObject = $myObjectCollection[0]; // or reset($myObjectCollection) if you can't ensure numeric 0 index array_walk($myObjectCollection, function($object) use ($minObject) { $minObject = $object-&gt;distance &lt; $minObject-&gt;distance ? $object : $minObject; }); </code></pre> <p>but from the looks of your dump. <code>name</code> and <code>distance</code> are private. So you want be able to access them from the object directly using <code>-&gt;</code>. You'll need some kind of getter <code>getDistance()</code></p>
40,096,188
0
How to find the beginning and ending indices of groups of ones in a set of ones and zeros <p>How would I find the beginning and ending indices of the groups of ones. I've tried some convoluted attempts with nested if statements and have had no success. Is there an algorithm that deals with this type of problem or does it have a name. Thanks. </p> <pre><code>int arr[32] = {0,1,1,1,1,0,0,0, 1,1,1,0,0,0,0,0, 1,1,0,1,0,0,0,1, 0,0,0,0,0,1,1,1}; </code></pre>
35,778,779
0
<p>The problem is with this line:</p> <pre><code>mReceiver = new ResultReceiver(new Handler()); </code></pre> <p>Replace it with this:</p> <pre><code>mReceiver = intent.getParcelableExtra(Constants.RECEIVER); </code></pre> <p>The problem is that you're creating a new ResultReceiver instead of using the one that is presumably passed in as an Intent extra from this code:</p> <pre><code>protected void startIntentService() { Intent intent = new Intent(this, FetchAddressIntentService.class); intent.putExtra(Constants.RECEIVER, mResultReceiver); intent.putExtra(Constants.LOCATION_DATA_EXTRA, mLastLocation); startService(intent); } </code></pre> <p>So, just use the one passed in as an extra in the Intent, and it should work.</p>
746,880
0
FormsAuthentication.RedirectFromLoginPage is not working <p>I am working on a LoginPage.Everything related to database or C# code is working fine but after successul login I am unable to redirect to Home.aspx,am I missing Something? Pls help. <strong>Code:</strong></p> <p><strong>Web.Config:</strong></p> <p> </p> <pre><code>&lt;/authentication&gt; &lt;authorization&gt; &lt;deny users="*"/&gt; &lt;/authorization&gt; </code></pre> <p><strong>C# Code:</strong></p> <pre><code>protected void Button1_Click(object sender, EventArgs e) { string source = "server=localhost\\sqlexpress;Database=LogInDB;Trusted_Connection=True"; SqlConnection con = new SqlConnection(source); con.Open(); SqlCommand cmd = new SqlCommand("proc_LogIn", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ID", SqlDbType.Int).Value = TextBox1.Text; cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = TextBox2.Text; SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false); } else { Response.Write("Invalid credentials"); } } </code></pre>
28,602,081
0
<p>Send text file as array of bytes <code>byte[]</code> for 1st parameter or convert it while loading to <code>string</code>. <code>Stream</code> is the other option.</p>
18,660,234
0
<blockquote> <p>I was wondering, is it possible to enhance the speed of a page loading by decreasing the size of images within the page? Would this be possible via jQuery</p> </blockquote> <p>No. This would require that the browser download the large image over the network and then process it to reduce it in size.</p> <p>If you want to speed things up, you need to make the images smaller before they leave the server.</p> <p>You don't need to do this manually though. Image resizing can be done programatically. </p>
21,305,342
0
Java SQL Statement for selecting record from database and using as double variable <p>Java - Netbeans IDE</p> <p>I have this code but the variable Priceperitem is not found, can anyone explain? or show me an easier way of selecting a record from a table in a database and setting its value as a variable?</p> <p>Price P/Item is the name of column within the database table.</p> <pre><code> String sql = "SELECT Price P/Item FROM tblResources"; try { pst = conn.prepareStatement(sql); rs = pst.executeQuery(); while (rs.next()){ double Priceperitem = rs.getDouble("Price P/Item"); } } catch (Exception e) { JOptionPane.showMessageDialog(null, "Runtime Error"); } </code></pre> <p>and then :</p> <pre><code>try { Total = Quantity * Priceperitem; (This is where Priceperitem is not found.) btnCalculateTotal.setText("Total: £"+Total+"0"); }catch (Exception e){ System.out.println("Error Calculating Total"); } </code></pre>
23,312,674
0
<p>I think this may work</p> <pre><code> ScrollView sv = new ScrollView(this.getActivity()); sv.post(new Runnable() { @Override public void run() { // this is executed when it becomes visible for the first time } }); </code></pre> <p><strong>EDIT</strong> If you want this from an element inside the scrollView, If you are using an adapter then</p> <pre><code>// Adapter class ie ArrayAdapter public View getView(int position, View convertView, ViewGroup parent) { View myView; //.... myView.post(new Runnable() { @Override public void run() { // this is executed when it becomes visible for the first time } }); return myView; } </code></pre>
14,083,632
0
<p>Some comments requested further details about what I commented out to resolve this issue. I didn't think this was good to add as an edit to the question, since it specifically goes over the resolution. It's been a while since I've worked on this project, so it's not all at the top of my head &amp; I'm not sure I've done everything correctly ... I'll do my best to explain it, though.</p> <p>In the file <code>GameCenterManager.h</code>, it looks like <code>authenticateLocalUser</code> is being initialized:</p> <p><code>- (void) authenticateLocalUser;</code></p> <p>In the file <code>App_NameViewController.m</code>, <code>viewDidLoad</code> is checking to see if Game Center is available:</p> <pre><code>self.currentLeaderBoard = kLeaderboardID; if ([GameCenterManager isGameCenterAvailable]) { self.gameCenterManager = [[[GameCenterManager alloc] init] autorelease]; [self.gameCenterManager setDelegate:self]; [self.gameCenterManager authenticateLocalUser]; } else { // The current device does not support Game Center. } </code></pre> <p>In the file <code>GameCenterManager.m</code></p> <pre><code>- (void) authenticateLocalUser { if([GKLocalPlayer localPlayer].authenticated == NO) { [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error) { // report any unreported scores or achievements [self retrieveScoresFromDevice]; [self retrieveAchievementsFromDevice]; //[self callDelegateOnMainThread: @selector(processGameCenterAuth:) withArg: NULL error: error]; }]; } } </code></pre> <p>The line that I commented out, which moved me past the <code>Missed Method</code> error, was:</p> <p><code>[self callDelegateOnMainThread: @selector(processGameCenterAuth:) withArg: NULL error: error];</code></p> <p>I hope this helps!</p>
34,512,487
0
Compiling code in Android Studio, Google map view always shows blank? <p>I have a very annoying issue with a project I am working on in Android Studio.</p> <p>I have another developer working on code for me, and part of the app has a Google map view.</p> <p>When this other person sends me raw code, I can open the project in Android Studio, compile it, and run it on a device and everything works fine - except the Google map is blank - grey screen, with "Google" logo in bottom corner.</p> <p>If this person sends me an APK file, I can download it straight to my phone, and it works perfectly. Map shows and loads as it should.</p> <p>The APK he sends is compiled from the same code, but compiled at his end.</p> <p>I see several questions on SO asking about blank Google maps, with possible code solutions - but because the APK works fine, it surely cant be a code issue?</p> <p>I have made sure all my Android Studio is updated to the latest versions, but any time I compile the code on my machine, it shows this blank map.</p> <p>Any ideas of where to look to solve this? Is there something I need to do within my install of Android Studio to get the map loading, or is there an API I need to load or install?</p> <p>This is driving me nuts, because I cant make any changes directly to the code on my machine, and need to always get the other developer to make any small changes and then compile on his machine and send me the APK!</p> <p>(PS: We are in different locations, so just comparing both our installations is not an option!)</p>
26,667,878
0
How to display the json data in multiautocomplete textview? <p>I am new to android, am developing one application in which i have to get the data from the server need to store that data in sqlite, so every time i should not hit the server,when ever i want get from database,in this app i used fragment concept,when i enter the single character in multiautocomplete textview based on the names in <code>json</code> response it needs to show the email-ids which are matching to that character in drop down list. i have done the code am not getting errors but not getting the expected result in <code>textview</code></p> <p>when i debug the code the following block of code is not executing i don't know what is the problem in this can you please help me any one</p> <pre><code> new Handler().post(new Runnable() { public void run() { Cursor cursor = contactDataSource.getAllData(); if (BuildConfig.DEBUG) Log.d(TAG, "total contcat count :" + cursor.getCount()); while (cursor.moveToNext()) { if (BuildConfig.DEBUG) Log.d(TAG, "Contact from cursor:" + cursor.getString(cursor .getColumnIndex(ExistingContactTable.COL_NAME))); } customAdapter = new CustomContactAdapter(getActivity(), cursor); Log.i("Custom contact adapter", "" + customAdapter); if (customAdapter != null) editorIdSharableEmail.setAdapter(customAdapter); } }); </code></pre>
26,840,485
0
<blockquote> <p>The largest problem is that there it no knowing over the null behavior of the Java API.</p> </blockquote> <p>The lack of annotated libraries continues to be a problem with Eclipse's built in nullness cehcking.</p> <p>Another nullness-checking tool is the <a href="http://checkerframework.org/" rel="nofollow">Checker Framework</a>, which ships with thousands of annotated APIs from the JDK. The Checker Framework also does more accurate checking. Eclipse and FindBugs are bug detectors that find some null pointer errors, but the Checker Framework is a verifier that gives a guarantee of <a href="http://types.cs.washington.edu/checker-framework/current/checker-framework-manual.html#nullness-checker" rel="nofollow">no null pointer errors</a>. </p> <p>The Checker Framework has an Eclipse plugin. Eclipse' built-in nullness checking has slicker IDE integration, but you can use the Checker Framework Eclipse plugin if you want more powerful checking.</p>
23,793,919
0
Trying to get onLocationChanged from a service? <p>I have some sample service that implements LocationListener now i want to get the lat/lng every time the location has been changed from that service that listens when location has been changed . But i dont know how to call from the mainactivity to that service to particular onLocationChanged .</p> <p>This is what i'v tried:</p> <p>From the MainActivity:</p> <pre><code>GpsTracker gps; // I declared that at the start of the activity //and then..... gps = new GpsTracker(MainActivity.this); gps.onLocationChanged(gps.location { lat=gps.getLatitude(); lng=gps.getLongitude(); }); </code></pre> <p>and this is my service sample code:</p> <pre><code>public class GpsTracker extends Service implements LocationListener { private final Context mContext; // flag for GPS status boolean isGPSEnabled = false; // flag for network status boolean isNetworkEnabled = false; // flag for GPS status boolean canGetLocation = false; Location location; // location double latitude; // latitude double longitude; // longitude double patitude; double pongitude; // The minimum distance to change Updates in meters private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; // 10 meters // The minimum time between updates in milliseconds private static final long MIN_TIME_BW_UPDATES =0; // 1 minute // Declaring a Location Manager protected LocationManager locationManager; public GpsTracker(Context context) { this.mContext = context; getLocation(); } public Location getLocation() { try { locationManager = (LocationManager) mContext .getSystemService(LOCATION_SERVICE); // getting GPS status isGPSEnabled = locationManager .isProviderEnabled(LocationManager.GPS_PROVIDER); // getting network status isNetworkEnabled = locationManager .isProviderEnabled(LocationManager.NETWORK_PROVIDER); if (!isGPSEnabled &amp;&amp; !isNetworkEnabled) { // no network provider is enabled } else { this.canGetLocation = true; if (isNetworkEnabled) { locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("Network", "Network"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } // if GPS Enabled get lat/long using GPS Services if (isGPSEnabled) { if (location == null) { locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this); Log.d("GPS Enabled", "GPS Enabled"); if (locationManager != null) { location = locationManager .getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { latitude = location.getLatitude(); longitude = location.getLongitude(); } } } } } } catch (Exception e) { e.printStackTrace(); } return location; } /** * Stop using GPS listener * Calling this function will stop using GPS in your app * */ public void stopUsingGPS(){ if(locationManager != null){ locationManager.removeUpdates(GpsTracker.this); } } /** * Function to get latitude * */ public double getLatitude(){ if(location != null){ latitude = location.getLatitude(); } // return latitude return latitude; } /** * Function to get longitude * */ public double getLongitude(){ if(location != null){ longitude = location.getLongitude(); } // return longitude return longitude; } /** * Function to check GPS/wifi enabled * @return boolean * */ public boolean canGetLocation() { return this.canGetLocation; } /** * Function to show settings alert dialog * On pressing Settings button will lauch Settings Options * */ public void showSettingsAlert(){ AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); // Setting Dialog Title alertDialog.setTitle("GPS is settings"); // Setting Dialog Message alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); // On pressing Settings button alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); mContext.startActivity(intent); } }); // on pressing cancel button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } @Override public void onLocationChanged(Location location) { latitude=location.getLatitude(); longitude=location.getLongitude(); } @Override public void onProviderDisabled(String provider) { } @Override public void onProviderEnabled(String provider) { } @Override public void onStatusChanged(String provider, int status, Bundle extras) { } @Override public IBinder onBind(Intent arg0) { return null; } } </code></pre> <p>What i'v wrote on the MainActivity gives errors... Would be glad to get some help.</p>
6,070,707
0
<p>I think you have alot of boiler plate code you don't need. If you do it this way you can add Commands without having to add code as well.</p> <pre><code>public interface Command { } public enum Commands { ; public static Command[] parseCommand(String command) { for (Class type : new Class[]{CameraCommand.class, RoverCommand.class}) try { return new Command[]{(Command) Enum.valueOf(type, command)}; } catch (IllegalArgumentException ignored) { } throw new IllegalArgumentException("Unknown Command " + command); } } public enum CameraCommand implements Command { CLICK } public enum RoverCommand implements Command { L, R, M; } </code></pre>
17,097,659
0
<p>The only direction I can think about is running two angular applications, in parallel. The problem is obviously name collision, so you would have to patch angular code and have your own version. This of course is <strong><em>completely</em></strong> discouraged, but just for the sake of discussion <em>it seems</em> that since angular is enclosed in a closure, maybe a simple rename would work, and then you would use the renamed angular. ie maybe something like</p> <p>change angular = window.angular || (window.angular = {}),</p> <p>to angular = window.extAngular || (window.extAngular = {}),</p> <p>would work, or at least give you a starting point to work on a patch</p>
22,861,762
0
IronWorker is a service that provides to cloud developers a facility to queue / schedule jobs in a way that is meant to be simple and scalable.
36,980,223
0
<p>There is a conflict with concurrent gradle versions:</p> <blockquote> <p>java.util.concurrent.ExecutionException: org.gradle.tooling.BuildException: Could not execute build using Gradle distribution '<a href="https://services.gradle.org/distributions/gradle-2.9-all.zip" rel="nofollow">https://services.gradle.org/distributions/gradle-2.9-all.zip</a>'.</p> </blockquote> <p>In quoted <code>gradle.properties</code> you've changed gradle version (gradleWrapperVersion) which was set to 2.9 for Grails 3.1.6 projects:</p> <p><a href="https://github.com/grails/grails-core/tree/v3.1.6/gradle/wrapper" rel="nofollow">https://github.com/grails/grails-core/tree/v3.1.6/gradle/wrapper</a></p> <p>Change it to defualt value and clean&amp;build.</p>
31,601,719
0
jquery multiselect dropdown selected values <p>I'm very new to javascript and jquery. I'm trying to create a multi-select dropdown list with "Select All" button. I finally find this nice plugin: <a href="http://wenzhixin.net.cn/p/multiple-select/docs/" rel="nofollow">http://wenzhixin.net.cn/p/multiple-select/docs/</a> </p> <p>I followed the docs, and the dropdown is shown on the page. But I have trouble get the selected items. </p> <p><strong>Here is what I did ( in javascript file controller):</strong></p> <pre><code>$scope.testSelectValues = $('#ms').multipleSelect('getSelects', 'text')); </code></pre> <p>and in html file:</p> <pre><code>&lt;div class="form-group"&gt; &lt;label&gt;Month&lt;/label&gt; &lt;select id="ms" multiple="multiple"&gt; &lt;option value="1"&gt;January&lt;/option&gt; &lt;option value="2"&gt;February&lt;/option&gt; &lt;option value="3"&gt;March&lt;/option&gt; &lt;option value="4"&gt;April&lt;/option&gt; &lt;option value="5"&gt;May&lt;/option&gt; &lt;option value="6"&gt;June&lt;/option&gt; &lt;option value="7"&gt;July&lt;/option&gt; &lt;option value="8"&gt;August&lt;/option&gt; &lt;option value="9"&gt;September&lt;/option&gt; &lt;option value="10"&gt;October&lt;/option&gt; &lt;option value="11"&gt;November&lt;/option&gt; &lt;option value="12"&gt;December&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;script&gt; $(function() { $('#ms').change(function() { console.log($(this).val()); }).multipleSelect({ width: '100%' }); }); &lt;/script&gt; </code></pre> <p>This does not work. I don't get any testSelectValues with the proper selected values. Anyone knows what's the problem?</p>
18,432,851
0
Accuracy of GPS Timestamp in depending on position accuracy <p>In need to exploit in my application time obtained from GPS. I need position and I need to know a time stamp which I can globally trust. </p> <p>I'm getting information how accurate my position is, for instance 5m, 100m etc. But I would like to know how accurate it my timestamp depending on position accuracy. Of course I know that the accuracy of the position is correlated with accuracy of the timestamp (this is basic idea of gsp), but I would like know what error of the timestamp (in miliseconds) should I expect when I'm getting position with accuracy 5m ,50m, 100m etc. Is there easy way to calculate that?</p>
20,789,852
0
<p>Because layouts are typically constructed from left to right, it is common for the right side of the image to be cropped off when it's dimensions exceeds the width of it's containing parent.</p> <p>Unfortunately, it is difficult to adjust the size of the <code>&lt;img /&gt;</code> element if you want to keep the aspect ratio <strong>and</strong> fill out all the available space. The former can be easily done with <code>width: 100%; max-width: 100%;</code>, but the latter is more of a challenge.</p> <p>That brings us to the utility of background size. CSS now supports values of background-size such as <code>cover</code>, which dictates that the background image will fill out the container yet retain aspect ratio, cropping off parts that we don't need.</p> <p><strong>CSS:</strong></p> <pre><code>.ls_video { background-size: cover; background-position: center center; margin-left: auto; margin-right: auto; width: 100%; height: 420px; text-align: left; } </code></pre> <p><strong>JS:</strong></p> <pre><code>var videoSrc = "http://www.youtube.com/embed/MxuIrIZbbu0"; var videoParms = "?autoplay=1&amp;amp;fs=1&amp;amp;hd=1&amp;amp;wmode=transparent"; var youtubeVideo = "" + "&lt;iframe class='ls_video' src='" + videoSrc + videoParms + "'&gt;" + "&lt;/iframe&gt;"; var theThumbNail = "" + "&lt;div onclick=\"this.innerHTML = youtubeVideo;\" style=\"background-image: url(images/MLSFthumbnail.jpg);\"&gt;&lt;/div&gt;"; document.write (theThumbNail); </code></pre>
14,900,714
0
<p>This uses <code>MAX</code> and <code>MIN</code> to see to that all values are the same; one needs to add a <code>+ 0</code> to each bit to make it available to normal numeric aggregate functions (like <code>MIN</code>/<code>MAX</code>/<code>SUM</code>/...)</p> <pre><code>SELECT ProjectId, EmployeeId FROM Temp GROUP BY ProjectId, EmployeeId HAVING MAX(IsWarning + 0) = 0 AND MAX(IsExpired + 0) = 0 AND MIN(IsIncomplete + 0) = 1 </code></pre> <p><a href="http://sqlfiddle.com/#!6/27b07/2" rel="nofollow">An SQLfiddle for testing</a>.</p>
4,028,245
0
<p>Maybe this sounds so stupid but.. what about storing the info into an object and putting that object in the session?</p>
37,566,368
0
<p>There is no work around.</p> <p>The C++ language places restrictions on some operators. Notably, the indexing (operator[]), assignment and function call operators must be defined as a non-static member function.</p> <p>This means that there can never be an implicit conversion on the "left-hand-side" operand in an expression of the type <code>lhs[rhs]</code>. End of story.</p> <p>All EDSL frameworks I know have helper functions to decorate your "literal" expression as a domain expression, e.g. <code>boost::phoenix::val(x)</code> or <code>boost::spirit::x3::as_parser(x)</code>.</p>
3,850,337
0
<p>There are a few issues with your approach:</p> <ul> <li>It may under-count since you don't use a transaction to atomically update the counter.</li> <li>It is inefficient: <ul> <li>Contention may become a problem if you need to update this counter frequently. Since you only have one counter, it won't scale well. Datastore entities can only be written at a rate of at most 5 times per second.</li> <li>You're writing to the datastore twice every time you insert a record. If you end up using transactions to fix the above problem, then you'll be making two round-trips to the datastore every time you insert the record (once to insert, and once to update the counter). You might be able to use an approach which avoids this extra round-trip to the datastore.</li> </ul></li> </ul> <p>Here are some alternate approaches (from least accurate [and fastest] to most accurate [and slowest]):</p> <ul> <li>If you only need a rough count of the number of entities of particular kind in the datastore, then you can use the <a href="http://code.google.com/appengine/docs/python/datastore/stats.html">Stats API</a>. The counts you retrieve are not constantly updated, however.</li> <li>If you need more granularity but are okay with a small possibility of occasionally under-counting, then you could use a memcache-enhanced counter. There are several good implementations discussed in <a href="http://stackoverflow.com/questions/2769934/high-concurrency-counters-without-sharding">this question</a>. In particular, see the code in the comments in <a href="http://appengine-cookbook.appspot.com/recipe/high-concurrency-counters-without-sharding/">this recipe</a>.</li> <li>If you really want to avoid undercounting, then you should consider a <a href="http://code.google.com/appengine/articles/sharding_counters.html">sharded datastore counter</a>. This will eliminate the contention issue from above.</li> </ul>
31,784,778
0
<p>Previous posts are correct in that compatibility mode appears to be based entirely on file names. There is a simple method for determining precisely which name Windows expects:</p> <p>Right-click the file, select Properties and navigate to the Details tab. There should be an entry labelled "Original filename". Simply rename the file accordingly and it should run happily.</p> <p>Screenshot:</p> <p><a href="https://i.stack.imgur.com/nm0hM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nm0hM.png" alt=""></a></p>
21,157,684
0
Bind <div> to element of Angular controller <p>We have a somewhat complicated model on an AngularJS controller:</p> <pre><code>function controller($scope) { $scope.model = { childmodel1: { childmodel2: { property1: 'abc', property2: 3, property3: 0.5, property4: 'abc' } } } } </code></pre> <p>In the HTML markup, we don't want to repeat the whole access chain everytime we access <code>childmodel2</code>:</p> <pre><code>&lt;div ng-controller="ctrl"&gt; &lt;div&gt; &lt;input type="text" ng-model="model.childmodel1.childmodel2.property1" /&gt; &lt;input type="text" ng-model="model.childmodel1.childmodel2.property2" /&gt; &lt;input type="text" ng-model="model.childmodel1.childmodel2.property3" /&gt; &lt;input type="text" ng-model="model.childmodel1.childmodel2.property4" /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Is there an AngularJS directive that creates a sub-scope like this:</p> <pre><code>&lt;div ng-controller="ctrl"&gt; &lt;div ng-unknowndirective="model.childmodel1.childmodel2"&gt; &lt;input type="text" ng-model="property1" /&gt; &lt;input type="text" ng-model="property2" /&gt; &lt;input type="text" ng-model="property3" /&gt; &lt;input type="text" ng-model="property4" /&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>It's the same thing that's done on <code>ng-repeat</code>, but without the repetition :)</p> <p>We tried <code>ng-scope</code>, <code>ng-controller</code>, <code>ng-model</code>, none of them works this way. Googling didn't yield any results, we don't know the terminology to search for.</p>
1,061,995
0
<p>Write a Vim function in .vimrc using the <code>searchpair</code> built-in function:</p> <pre><code>searchpair({start}, {middle}, {end} [, {flags} [, {skip} [, {stopline} [, {timeout}]]]]) Search for the match of a nested start-end pair. This can be used to find the "endif" that matches an "if", while other if/endif pairs in between are ignored. [...] </code></pre> <p>(<a href="http://vimdoc.sourceforge.net/htmldoc/eval.html" rel="nofollow noreferrer">http://vimdoc.sourceforge.net/htmldoc/eval.html</a>)</p>
4,922,217
0
Can the SSMS editor be re-used in your own application, or is there an alternative? <p>I would like to have IntelliSence or code completion, and syntax highlighting for SQL queries in my own .NET application.</p> <ol> <li><p>Is it possible to use the SQL Server Management Studio's editor similar to the way you can use the SMO APIs? </p></li> <li><p>Are there open source control(s) that can be used?</p></li> </ol> <p>I have found code completion / syntax highlighting controls, but SQL is a funny beast because of the column / table aliases.</p>
14,900,756
0
<p>An array printed out with <strong>print_r</strong> cannot be parsed back into a variable.</p> <p>In your server.php do <code>echo json_encode($_POST);</code>. Then in your client.php</p> <pre><code>&lt;?php //... $output = curl_exec($curl_handle); // and now you can output it however you like if ($this-&gt;request_response_type == 'array') { //though i don't see why you would want that as output is now useless if someone ought to be using the variable $outputVar = json_decode($output); // that parses the string into the variable print_r((array)$outputVar); // or even better use serialize() echo serialize($outputVar); } else if ($this-&gt;request_response_type == 'json') { echo $output; //this outputs the original json } else if ($this-&gt;request_response_type == 'xml') { // do your xml magic with $outputVar which is a variable and not a string //xml conversion will be done here later. not ready yet. } </code></pre>
717,617
0
<p>If it's in our stack I can't find it :). It would be a good thing to add though :). You can, for now, use an Inline query to simply execute the statement you wrote (it takes straight SQL). I know it's fugly but...</p> <p>Rick - if you did get that to work I'd be interested in how. "Col2" will try and be parsed to a type and your query will fail.</p>
37,854,261
0
<p>This post should help you : <a href="http://stackoverflow.com/a/8996581/5941903">http://stackoverflow.com/a/8996581/5941903</a>.</p> <p>Before posting, please try to do some research. I just typed : android rotate imageview on Google...</p>
14,886,127
0
<p>To answer your question, for a pure css solution the answer would be no it is not possible.</p> <p>You could though serve the images from a server and use a scripting language like PHP to get the device information of the user and then serve the appropriate image based on that using PHP function header.</p>
31,535,043
0
<p>Yes, of course you can do.</p> <p>You need to create different layout directory for different density devices.</p> <p>For example <strong>layout-ldpi</strong>, <strong>layout-hdpi</strong>, etc. and define the required kind of layout inside these.</p> <pre><code>res/layout/my_layout.xml // layout for normal screen size ("default") res/layout-small/my_layout.xml // layout for small screen size res/layout-large/my_layout.xml // layout for large screen size res/layout-xlarge/my_layout.xml // layout for extra large screen size res/layout-xlarge-land/my_layout.xml // layout for extra large in landscape orientation </code></pre> <p>And inside the different my_layout.xml file define either one, two or three linearlayouts you need.</p>
31,456,279
0
<p>There are no tutorials on <code>ExoPlayer</code> right now. <code>ExoPlayer</code> is a the best alternative to <code>MediaPlayer</code> but is not very newbie friendly at the moment. </p> <p>What you have to do is go to the github page and take a look at the <code>DemoPlayer</code> class in the <code>demo</code> app. </p> <p>This app can open a lot of different formats including <code>hls</code>. </p>
30,781,032
0
Checking for exception type in try/catch block in C# <p>I have a rather basic question I've been thinking about.</p> <p>Refer to the following code snippet that uses a <strong>try/catch</strong> block:</p> <pre><code>public void doSomething() { try { doSomethingElse() } catch (Exception ex) { if (ex is IndexOutOfRangeException || ex is DivideByZeroException || ex is Exception) { Console.WriteLine(ex.Message); } } } </code></pre> <p>1) If all I want to do is output the exception message to the console, is it necessary to check in the <strong>if</strong> clause what type of Exception I'm getting, or can I just do </p> <pre><code>... catch (Exception ex) { Console.WriteLine(ex.Message); } ... </code></pre> <p>2) It is my understanding that checking the specific exception type should be used if I need to output a defined message to the console instead of using the exception message itself - something along the lines of</p> <pre><code>... catch (Exception ex) { switch (ex): { case IndexOutOfRangeException: Console.WriteLine("Personalized message #1"); break; case DivideByZeroException: Console.WriteLine("Personalized message #2"); break; case Exception: Console.WriteLine("Personalized message #3"); break; } } ... </code></pre> <p>Your comments on 1) and 2) are highly appreciated. Thanks for your time.</p>
19,342,876
0
<p>Ok I got the solution, I have remove the click functionality and use the follwing code :-</p> <pre><code>$('#pendulum-child').draggable( { start: function(event, ui) { $('.flush_handle').addClass('flush_handle1'); }, axis: 'y', revert: function( event, ui ) { $('.flush_handle').removeClass('flush_handle1'); $(this).data("uiDraggable").originalPosition = { top : '3px', left : '-74px' }; init() return true; } } ); </code></pre> <p><strong>CSS :-</strong></p> <pre><code>#pendulum-child { width:118px; height:255px; background-image:url(images/flush-chain.png); background-repeat:no-repeat; position:absolute; left:-74px; top:3px; } #pendulum-parent { width:22px; height:22px; } </code></pre>
32,534,860
0
Using Variable In JSON node.js <p>I am writing some code that allows me to send messages back and forth from two node instances using HTTP &amp; Express.</p> <p>Each client generates a UUID type of identification and then sends it to the main server for storage and authentication.</p> <p>Here is the client, you can see at the bottom that it generates what i beleive to be a json string, i assign a variable before that contains an ID, i am trying to use this ID to send to the server for proccessing.</p> <p>Client.js</p> <pre><code>var request = require('request'); var sendservlet = request.post; var fs = require('fs'); var path = require('path'); var crypto = require('crypto'); if (fs.existsSync('foo.txt')) { console.log('Found '); fs.readFile('foo.txt', "utf-8" , function (err, data) { if (err) throw err; console.log(data); }); } else { console.log("Did not find file, i must first register you to the server."); function randomValueHex (len) { return crypto.randomBytes(Math.ceil(len/2)) .toString('hex') .slice(0,len); } var ID = randomValueHex(7) console.log("Your New Identification Number Is: " + ID); sendservlet( 'http://192.168.1.225:3000', { form: { key: ID } }, function (error, response, body) { if (!error &amp;&amp; response.statusCode == 200) { console.log(body) console.log(ID) } } ); } </code></pre> <p>Server.JS</p> <pre><code>var express = require('express'); var bodyParser = require('body-parser') var app = express(); app.use(bodyParser.urlencoded({ extended: false })); var crypto = require('crypto'); app.post('/', function (req, res) { res.send('POST request to the homepage'); console.log(req.body.form.key); }); var server = app.listen(3000, function () { var host = server.address().address; var port = server.address().port; console.log('Example app listening at http://%s:%s', host, port); }); </code></pre> <p>The server cannot seem to be able to read it, i believe that i cannot call the variable like that. </p> <p>To help narrow this issue down, I am strictly asking why the ID variable cannot be transmitted in </p> <pre><code>sendservlet( 'http://192.168.1.225:3000', { form: { key: ID } }, </code></pre> <p>thank you very much for any advice available!</p>
19,644,515
0
<p>For only compiling part you can use following changes in the Makefile</p> <pre><code> file%.o:file%.c file%.h $(TOOLCHAIN_GCC) $(COMPILEOPTS) $&lt; </code></pre> <p>After this you need to make changes in linking of the object files to generate the final executable file.</p>
37,123,278
0
<p>This can be achieved by using a script (modify to suit your needs):</p> <pre><code>#!/bin/bash # Dynamic IP .htaccess file generator # Written by Star Dot Hosting # www.stardothosting.com dynDomain="$1" htaccessLoc="$2" dynIP=$(/usr/bin/dig +short $dynDomain) echo "dynip: $dynIP" # verify dynIP resembles an IP if ! echo -n $dynIP | grep -Eq "[0-9.]+"; then exit 1 fi # if dynIP has changed if ! cat $htaccessLoc | /bin/grep -q "$dynIP"; then # grab the old IP oldIP=`cat /usr/local/bin/htold-ip.txt` # output .htaccess file echo "order deny,allow" &gt; $htaccessLoc 2&gt;&amp;1 echo "allow from $dynIP" &gt;&gt; $htaccessLoc 2&gt;&amp;1 echo "allow from x.x.x.x" &gt;&gt; $htaccessLoc 2&gt;&amp;1 echo "deny from all" &gt;&gt; $htaccessLoc 2&gt;&amp;1 # save the new ip to remove next time it changes, overwriting previous old IP echo $dynIP &gt; /usr/local/bin/htold-ip.txt fi </code></pre> <p>Than just cron it to generate a new line on the .htaccess file:</p> <pre><code>*/15 * * * * /bin/sh /usr/local/bin/.sh yourhostname.no-ip.org /var/www/folder/.htaccess &gt; /dev/null 2&gt;&amp;1 </code></pre> <p>Source: <a href="https://www.stardothosting.com" rel="nofollow">https://www.stardothosting.com</a></p>
28,763,580
1
Passing a list of randomForest objects back to R with rpy2 <p>I am trying to combine a number of random forest models using rpy2. The <code>combine</code> command in R looks fairly straight forward but I am not sure how to pass the RF objects from python to R.</p> <p>Simple example:</p> <pre><code>import pandas as pd import numpy as np import sys if sys.version_info[0] &lt; 3: from string import lowercase else: from string import ascii_lowercase as lowercase import rpy2.robjects as robjects from rpy2.robjects import pandas2ri pandas2ri.activate() r = robjects.r r.library("randomForest") df = pd.DataFrame(data=np.random.random(size=(100, 10)), columns=[a for a in lowercase[:10]]) cols = df.columns RF = [] for _ in range(5): df['train'] = np.random.random(size=100) &lt; .75 rf = r.randomForest(robjects.Formula('a~.'), data=df[df.train][cols]) RF.append(rf) </code></pre> <p>When I try and <code>combine</code> RF models in R</p> <pre><code>RFall = r.combine(RF) </code></pre> <p>Returns the error:</p> <pre><code>Error in (function (...) : Argument must be a list of randomForest objects </code></pre> <p>I have looked at other functions in <code>robjects</code> but can't find the one that will do it.</p>
4,110,800
0
Silverlight ListBox control doesn't rebind correctly <p>I'm using a ListBox control with an ItemTemplate like so:</p> <pre><code>&lt;ListBox Name="lbItemsList" ItemsSource="{Binding}" &gt; &lt;ListBox.ItemTemplate&gt; &lt;DataTemplate&gt; &lt;StackPanel Orientation="Horizontal"&gt; &lt;TextBlock Text="{Binding ID}" Padding="5,0,0,0" /&gt; &lt;TextBlock Text=" - " Padding="5,0,0,0" /&gt; &lt;TextBlock Text="{Binding Description}" Padding="5,0,0,0" /&gt; &lt;/StackPanel&gt; &lt;/DataTemplate&gt; &lt;/ListBox.ItemTemplate&gt; &lt;/ListBox&gt; </code></pre> <p>Then, in the code I dynamically bind a collection to the ListBox like so:</p> <pre><code>lbItemssList.ItemsSource = _itemsList.Values; </code></pre> <p>But at times I need to rebind a different or modified list of items to the ListBox. When I do this, the ListBox doesn't update with the new list and it seems that the binding doesn't work correctly, unless I do this:</p> <pre><code>lbItemssList.ItemsSource = null; lbItemssList.ItemsSource = _itemsList.Values; </code></pre> <p>I've done the same thing with other ListBox controls and not had this problem. What am I missing here?</p>
35,678,039
0
windows.h files have hundreds of syntax error <p>When i try to make a WinApi it make a lot of errors or even crushes down. I tried the same code in CodeBlocks(it frozens) in Visual Studio(it's tha same) and also in Dev-Cpp, where i get a lot of errors.</p> <p><a href="https://i.stack.imgur.com/OQXlH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OQXlH.png" alt="enter image description here"></a></p> <p>I tried to reinstall the programs but it did not help, but when i installed codeblocks sometimes it wrote, it has some environment problems, but i could not find out what. I found later that the minGW file was missing but i get the same errors since. </p> <p>this is the code what i try to compile and run: </p> <pre><code>#include &lt;windows.h&gt; const char g_szClassName[] = "myWindowClass"; // Step 4: the Window Procedure LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: DestroyWindow(hwnd); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hwnd, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX wc; HWND hwnd; MSG Msg; //Step 1: Registering the Window Class wc.cbSize = sizeof(WNDCLASSEX); wc.style = 0; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_APPLICATION); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = g_szClassName; wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if(!RegisterClassEx(&amp;wc)) { MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } // Step 2: Creating the Window hwnd = CreateWindowEx( WS_EX_CLIENTEDGE, g_szClassName, "The title of my window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, NULL, NULL, hInstance, NULL); if(hwnd == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } ShowWindow(hwnd, nCmdShow); UpdateWindow(hwnd); // Step 3: The Message Loop while(GetMessage(&amp;Msg, NULL, 0, 0) &gt; 0) { TranslateMessage(&amp;Msg); DispatchMessage(&amp;Msg); } return Msg.wParam; } </code></pre>
16,941,648
0
<p>The old labels are stored in a graph attribute - node_labels.</p> <pre><code>print g2.node_labels {'a': 0, 'b': 1} </code></pre>
7,915,295
0
How can I get UIPickerView to select the first item? <p>I am encountering a funny problem with UIPickerView. My data source has 2 items:</p> <p>"All" and "Home"</p> <p>When I select one, I execute a certain task.</p> <p>By default All is selected. When I click on Home my task executes, and then when I choose the picker again, it is set to All. In order to select All, I have to scroll up a bit, so that the selection is off All, and then let go so it falls back down to All.</p> <p>What is the best way to be able to select All?</p>
32,259,121
0
Animated Gif Frames To Array of BufferedImages <p>I am trying to extract all the frames of an animated gif to an array of bufferedimages. I have been reading <a href="http://stackoverflow.com/questions/8933893/convert-each-animated-gif-frame-to-a-separate-bufferedimage">Convert each animated GIF frame to a separate BufferedImage</a> and it was fairly easy to write each frame to a seperate file. But my problem comes up when I try to fill an ArrayList with the frames instead of writing them. Every image in the ArrayList is just the last frame of the gif.</p> <p>To make it more clear, this code will write each frame to seperate files perfectly:</p> <pre><code> ArrayList&lt;BufferedImage&gt; frames = new ArrayList&lt;BufferedImage&gt;(); BufferedImage master = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); ImageReader ir = new GIFImageReader(new GIFImageReaderSpi()); ir.setInput(ImageIO.createImageInputStream(gif)); for (int i = 0; i &lt; ir.getNumImages(true); i++) { master.getGraphics().drawImage(ir.read(i), 0, 0, null); ImageIO.write(master, "gif", new File(dirGifs + "/frames" + i + ".gif")); } </code></pre> <p>However, this code will only gives me an ArrayList full of the same frame (being the last frame of the gif)</p> <pre><code> ArrayList&lt;BufferedImage&gt; frames = new ArrayList&lt;BufferedImage&gt;(); BufferedImage master = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB); ImageReader ir = new GIFImageReader(new GIFImageReaderSpi()); ir.setInput(ImageIO.createImageInputStream(gif)); for (int i = 0; i &lt; ir.getNumImages(true); i++) { master.getGraphics().drawImage(ir.read(i), 0, 0, null); frames.add(master); } </code></pre> <p>I thought that it was because I wasnt disposing of the graphics afterwards, but I tried creating a graphics object and disposing it and nothing changed. Need help!</p>
10,303,129
0
<p>Yes, you can; if the variable/parameter you are trying to compare is already populated with data. Something like this:</p> <pre><code>DECLARE v_num1 NUMBER := 5; v_num2 NUMBER := 3; v_temp NUMBER; BEGIN -- if v_num1 is greater than v_num2 rearrange their values IF v_num1 &gt; v_num2 THEN v_temp := v_num1; v_num1 := v_num2; v_num2 := v_temp; END IF; </code></pre> <p>Provide more information based on what you are actually trying to do.</p>
28,490,593
0
Error on using Vim-latex ("can't find file ~") <p>I'm not sure if this question is appropriate here but I have nowhere else to ask. I recently started to typeset some 'mathsy' stuff using Latex and it became a hobby for me. I've been using TeXnicCenter for this, but feeling that I've got familiar with Latex language, I decieded to improve 'efficiency' of typesetting by changing the editor.</p> <p>So I decided to use <strong>Vim</strong> (latest version, 7.4) with Suite-Latex. I've just installed Vim and Suite-Latex, following exactly what was instructed <a href="http://vim-latex.sourceforge.net/index.php?subject=download&amp;title=Download" rel="nofollow">here</a>. I made every necessary changes mentioned <a href="http://vim-latex.sourceforge.net/documentation/latex-suite/recommended-settings.html" rel="nofollow">here</a>, and it seemed to me that installation was successful (I got what was expected on Step 4)</p> <p>Then I started to work through <a href="http://vim-latex.sourceforge.net/documentation/latex-suite-quickstart/lsq-using-tutorial.html" rel="nofollow">this tutorial</a> and everything went fine until <a href="http://vim-latex.sourceforge.net/documentation/latex-suite-quickstart/lsq-inserting-reference.html" rel="nofollow">this section</a>.</p> <p>When I press F9 for autoreference, I see that Vim is working on something for split seconds and red error message refering to "can't find [some file name]" in my user/appdata/local/temp directory. The "file name" changes every time I do this (so its kind of temporary file as its directory suggests?). And then it produces a new window with title <strong>__ OUTLINE __</strong> where 2 empty lines are showing up.</p> <p>If I press n (in the new window described above) error message saying <strong>"E486: Pattern not found: rf"</strong> pops up and pressing j results in going down one row. If I press enter key, message <strong>":call Tex_FinishOutlineCompletion()"</strong> pops up.</p> <p>More frustratingly, if I try to compile a file by entering command \ll, a new window pops up where there are two lines saying:</p> <p>1.ll I can't find file `newfile.tex'. newfile.tex</p> <p>2.ll Emergency stop</p> <p>and below these is a message saying </p> <p><strong>[Quickfix list]: latex -interaction=nonstopmode -file-line-error-style newfile.tex</strong></p> <p>So I thought it maybe is something to do with VIM not being able to find files in my computer (so something wrong with grep?), and I tried to resolve it by downloading a software called "cygwin" on which developers said their tests were successful, but it changed nothing.</p> <p>But I think the two problems are related.</p> <p>As it is, I am completely newbie in this type of editing environment (or any kind of programming) but I really would like to learn some Vim seeing how efficient it is in typesetting etc. Sorry for not being a pro at typing codes here. Thanks for reading!</p>
12,396,565
0
<p>Well, you can create your form in html, give it and id and do it like this:</p> <pre><code>document.getElementById('myform').setAttribute('action', post_url); </code></pre>
6,206,177
0
<p>The plus: it's a super easy way to distribute the work that needs to be done.</p> <p>The minus: due to the way that Hadoop recovers from failures, you need to be very careful about managing what is and isn't run (which you can definitely do, it's just something to watch out for). If a reduce fails, for example, then all of the map jobs that feed that partition must also be rerun. Obviously this would most likely be a no-reducer job, but this is still true of mappers...what happens if half of the calls run, then the job fails, so it is rescheduled?</p> <p>You could use some sort of high-throughput system to manage the calls that are actually made or somesuch. But it definitely can be appropriately used for this.</p>
30,231,085
0
<p>What version of Android are you testing with? Can you adb shell in and see what these settings are (when you're on wifi)?</p> <pre><code>cat /proc/sys/net/ipv4/tcp_rmem cat /proc/sys/net/ipv4/tcp_wmem </code></pre> <p>And then if they are low (something like "4092 8760 11680"), then try setting them to larger values:</p> <pre><code>sudo echo "524288,1048576,2097152" &gt; /proc/sys/net/ipv4/tcp_rmem sudo echo "262144,524288,1048576" &gt; /proc/sys/net/ipv4/tcp_wmem </code></pre> <p>Then try your test again.</p> <p>This could be from a bug where the wifi buffers were being set too small in some cases (<a href="https://code.google.com/p/android/issues/detail?id=64706" rel="nofollow">https://code.google.com/p/android/issues/detail?id=64706</a>).</p>
25,891,050
0
Accuratly catch clicks on an iframe <p>I have an ad iframe being written onto my page dynamically. The advert inside may have another iframe itself and will "suck" click events through into it so cannot track them easily. I've used this great plugin by @Vince in the past:</p> <p><a href="https://github.com/finalclap/iframeTracker-jquery" rel="nofollow">https://github.com/finalclap/iframeTracker-jquery</a></p> <p>which seems to work fine until the window this is all running in IS ITSELF an iframe and focus is somewhere on the outermost page. I can see it getting the rollover/rollout events but it doesn't get the click unless focus is somewhere inside the first iframe's window.</p> <p>Has anyone found a solid way to do this? Thanks in advance if anyone can help.</p>
26,922,866
0
<p>I would also recommend checking out <a href="https://github.com/nicandris/com.example.forkbomb" rel="nofollow">this guy's github</a> for a good example of a fork bomb. Even though he uses an activity to launch it you could modify it to run in a service.</p>
24,585,265
0
getItemId function returns huge numbers - action bar buttons <p>I am trying to add submenus , I created xml:</p> <pre><code> &lt;menu xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;item android:id="@+id/action_overflow" android:icon="@drawable/ic_action_overflow" android:showAsAction="ifRoom" android:title="@string/action_overflow"&gt; &lt;menu&gt; &lt;item android:id="@+id/item1" android:title="test"&gt;&lt;/item&gt; &lt;item android:id="@+id/item2" android:title="test2"&gt;&lt;/item&gt; &lt;item android:id="@+id/item3" android:title="test3"&gt;&lt;/item&gt; </code></pre> <p> </p> <p></p> <pre><code>&lt;/menu&gt;&lt;/item&gt;&lt;/menu&gt; </code></pre> <p>in mainactivity.java:</p> <pre><code> @Override public boolean onOptionsItemSelected(MenuItem item) { // int menuid = item.getItemId(); Toast.makeText(MainActivity.this, "id: "+item.getItemId(), Toast.LENGTH_SHORT).show(); return true; } </code></pre> <p>it shows me numbers like 2131034200...... etc..</p> <p>please help :(</p>
29,706,013
0
<blockquote> <p>What is the point of the &amp;?</p> </blockquote> <p>The <code>&amp;</code> takes the reference of an object, as you surmised. However, there's a <a href="https://github.com/rust-lang/rust/blob/b7fb57529aded92c4f470568e6b5ea7a5a28f6a4/src/libcore/fmt/mod.rs#L783-L796" rel="nofollow"><code>Debug</code> implementation for references to <code>Debug</code> types</a> that just prints out the referred-to object. This is done because Rust tends to prefer value equality over reference equality:</p> <pre class="lang-rust prettyprint-override"><code>impl&lt;'a, T: ?Sized + $tr&gt; $tr for &amp;'a T { fn fmt(&amp;self, f: &amp;mut Formatter) -&gt; Result { $tr::fmt(&amp;**self, f) } } </code></pre> <p>If you'd like to print the memory address, you can use <code>{:p}</code>:</p> <pre><code>let v = vec![1,2,3]; println!("{:p}", &amp;v); </code></pre> <blockquote> <p>it looks like they are looping through a reference</p> </blockquote> <p>The <code>for i in foo</code> syntax sugar calls <code>into_iterator</code> on <code>foo</code>, and there's an <a href="https://github.com/rust-lang/rust/blob/b7fb57529aded92c4f470568e6b5ea7a5a28f6a4/src/libcollections/vec.rs#L1520-L1528" rel="nofollow">implementation of <code>IntoIterator</code> for <code>&amp;Vec</code></a> that returns an iterator of references to items in the iterator:</p> <pre class="lang-rust prettyprint-override"><code>fn into_iter(self) -&gt; slice::Iter&lt;'a, T&gt; { self.iter() } </code></pre>