id
int64
4
73.8M
title
stringlengths
10
150
body
stringlengths
17
50.8k
accepted_answer_id
int64
7
73.8M
answer_count
int64
1
182
comment_count
int64
0
89
community_owned_date
stringlengths
23
27
creation_date
stringlengths
23
27
favorite_count
int64
0
11.6k
last_activity_date
stringlengths
23
27
last_edit_date
stringlengths
23
27
last_editor_display_name
stringlengths
2
29
last_editor_user_id
int64
-1
20M
owner_display_name
stringlengths
1
29
owner_user_id
int64
1
20M
parent_id
null
post_type_id
int64
1
1
score
int64
-146
26.6k
tags
stringlengths
1
125
view_count
int64
122
11.6M
answer_body
stringlengths
19
51k
13,182,921
jQuery input value focus and blur
<p>I have the following code so that when a users selects an input box the value will disappear, but the default value will then be re-inserted once a user clicks off it.</p> <pre><code> $(function() { var defaultText = ''; $('input[id=input]').focus(function() { defaultText = $(this).val(); $(this).val(''); }); $('input[id=input]').blur(function() { $(this).val(defaultText); }); }); </code></pre> <p>However, that's not exactly how I want it. If a user inserts text I don't want the default text to then override what the user has put. I'm also fairly new to jQuery so any help would be greatly appreciated.</p>
13,182,951
3
2
null
2012-11-01 18:01:56.343 UTC
2
2016-03-02 13:56:52.773 UTC
2014-03-04 16:07:25.943 UTC
null
352,672
null
1,729,734
null
1
10
javascript|jquery|focus|blur|placeholder
65,661
<p>In your <code>focus()</code> method you should check to see if it equals the <code>defaultText</code> before clearing it, and in your <code>blur()</code> function, you just need to check if the <code>val()</code> is empty before setting the <code>defaultText</code>. If you are going to be working with multiple inputs, it's better to use a class rather than ID, so your selector would be <code>input.input</code> when the class is "input". Even if it was an ID, you would reference it as <code>input#input</code>.</p> <pre><code>// run when DOM is ready() $(document).ready(function() {     $('input.input').on('focus', function() { // On first focus, check to see if we have the default text saved // If not, save current value to data() if (!$(this).data('defaultText')) $(this).data('defaultText', $(this).val()); // check to see if the input currently equals the default before clearing it         if ($(this).val()==$(this).data('defaultText')) $(this).val('');     }); $('input.input').on('blur', function() { // on blur, if there is no value, set the defaultText if ($(this).val()=='') $(this).val($(this).data('defaultText')); }); }); </code></pre> <p>Set it in action in <a href="http://jsfiddle.net/hhDwW/" rel="noreferrer">this jsFiddle</a>.</p>
13,175,268
AJAX content in a jQuery UI Tooltip Widget
<p>There is a new Tooltip Widget in jQuery UI 1.9, whose <a href="http://api.jqueryui.com/tooltip/" rel="noreferrer">API docs</a> hint that AJAX content can be displayed in it, but without any further details. I guess I can accomplish something like that with a synchronous and blocking request, but this isn't what I want.</p> <p>How do I make it display any content that was retrieved with an asynchronous AJAX request?</p>
14,018,569
4
0
null
2012-11-01 10:36:08.667 UTC
16
2016-07-06 18:22:37.3 UTC
null
null
null
null
93,540
null
1
31
ajax|jquery-ui|jquery
48,412
<p>Here is a ajax example of jqueryui tootip widget from <a href="http://html5beta.com/jquery-2/a-little-guide-about-jqueryui-tooltip-ajax-callback/">my blog</a>.hope it helps.</p> <pre><code>$(document).tooltip({ items:'.tooltip', tooltipClass:'preview-tip', position: { my: "left+15 top", at: "right center" }, content:function(callback) { $.get('preview.php', { id:id }, function(data) { callback(data); //**call the callback function to return the value** }); }, }); </code></pre>
12,992,320
When running unit tests in ReSharper, how can I see the overall execution time?
<p>I'd like to know how long all my tests took to run? Is that possible?</p>
12,997,633
4
3
null
2012-10-20 20:19:47.26 UTC
1
2022-02-15 14:28:40.3 UTC
2019-01-16 14:08:53.557 UTC
null
1,371,040
null
884,754
null
1
33
resharper
4,512
<p>You're probably looking to profile your unit tests, and since you're running them with ReSharper, the natural choice would be to install <a href="http://www.jetbrains.com/profiler/features/" rel="nofollow">dotTrace Performance</a> and <a href="http://www.jetbrains.com/profiler/webhelp/Profiling_Guidelines__Profiling_Unit_Tests.html" rel="nofollow">profile unit tests</a> using this combination.</p>
13,125,825
zsh: update prompt with current time when a command is started
<p>I have a <code>zsh</code> prompt I rather like: it evaluates the current time in <code>precmd</code> and displays that on the right side of the prompt:</p> <pre><code>[Floatie:~] ^_^ cbowns% [9:28:31 on 2012-10-29] </code></pre> <p>However, this isn't <em>exactly</em> what I want: as you can see below, this time is actually the time the previous command exited, not the time the command was started:</p> <pre><code>[Floatie:~] ^_^ cbowns% date [9:28:26 on 2012-10-29] Mon Oct 29 09:28:31 PDT 2012 [Floatie:~] ^_^ cbowns% date [9:28:31 on 2012-10-29] Mon Oct 29 09:28:37 PDT 2012 [Floatie:~] ^_^ cbowns% [9:28:37 on 2012-10-29] </code></pre> <p>Is there a hook in <code>zsh</code> to run a command just <em>before</em> the shell starts a new command so I can update the prompt timestamp then? (I saw <a href="https://stackoverflow.com/questions/2187829/constantly-updated-clock-in-zsh-prompt">Constantly updated clock in zsh prompt?</a>, but I don't need it <em>constantly</em> updated, just updated when I hit enter.)</p> <p>(The <code>^_^</code> is based on the previous command's return code. It shows <code>;_;</code> in red when there's a nonzero exit status.)</p>
26,585,789
6
2
null
2012-10-29 16:34:41.17 UTC
14
2017-03-06 22:05:50.22 UTC
2017-05-23 10:30:01.887 UTC
null
-1
null
774
null
1
42
zsh|prompt|zsh-zle
15,069
<p>I had a struggle to make this:</p> <p>It displays the date on the right side when the command has been executed. It does not overwrite the command shown. Warning: it may overwrite the current RPROMPT.</p> <pre><code>strlen () { FOO=$1 local zero='%([BSUbfksu]|([FB]|){*})' LEN=${#${(S%%)FOO//$~zero/}} echo $LEN } # show right prompt with date ONLY when command is executed preexec () { DATE=$( date +"[%H:%M:%S]" ) local len_right=$( strlen "$DATE" ) len_right=$(( $len_right+1 )) local right_start=$(($COLUMNS - $len_right)) local len_cmd=$( strlen "$@" ) local len_prompt=$(strlen "$PROMPT" ) local len_left=$(($len_cmd+$len_prompt)) RDATE="\033[${right_start}C ${DATE}" if [ $len_left -lt $right_start ]; then # command does not overwrite right prompt # ok to move up one line echo -e "\033[1A${RDATE}" else echo -e "${RDATE}" fi } </code></pre> <p>Sources:</p> <ul> <li><a href="http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html" rel="noreferrer">http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x361.html</a></li> <li><a href="https://stackoverflow.com/a/10564427/238913">https://stackoverflow.com/a/10564427/238913</a></li> </ul>
12,694,455
JavaScript parseFloat in Different Cultures
<p>I have a question about the default behavior of JavaScript's parseFloat function in different parts of the world. </p> <p>In the US, if you call parseFloat on a string "123.34", you'd get a floating point number 123.34. </p> <p>If I'm developing code in say Sweden or Brazil and they use a comma instead of a period as the decimal separator, does the parseFloat function expect "123,34" or "123.34". </p> <p>Please note that I'm not asking how to parse a different culture's number format in the US. I'm asking does parseFloat in Sweden or Brazil behave the same way it does inside the US, or does it expect a number in its local format? Or to better think about this, does a developer in Brazil/Sweden have to convert strings to English format before it can use parseFloat after extracting text from a text box?</p> <p>Please let me know if this doesn't make sense.</p>
12,694,511
5
0
null
2012-10-02 16:33:24.067 UTC
5
2022-07-27 09:01:38.027 UTC
null
null
null
null
1,714,916
null
1
62
javascript|culture
40,368
<p><code>parseFloat</code> doesn't use your locale's definition, but the definition of a decimal literal. </p> <p>It only parses <code>.</code> not <code>,</code></p> <p>I'm brazilian and I have to replace comma with dot before parsing decimal numbers.</p> <p><a href="http://es5.github.com/#x15.1.2.3" rel="noreferrer">parseFloat specification</a></p>
12,765,636
The requested resource does not support HTTP method 'GET'
<p>My route is correctly configured, and my methods have the decorated tag. I still get "The requested resource does not support HTTP method 'GET'" message?</p> <pre><code>[System.Web.Mvc.AcceptVerbs("GET", "POST")] [System.Web.Mvc.HttpGet] public string Auth(string username, string password) { // Décoder les paramètres reçue. string decodedUsername = username.DecodeFromBase64(); string decodedPassword = password.DecodeFromBase64(); return "value"; } </code></pre> <p>Here are my routes:</p> <pre><code>config.Routes.MapHttpRoute( name: "AuthentificateRoute", routeTemplate: "api/game/authentificate;{username};{password}", defaults: new { controller = "Game", action = "Auth", username = RouteParameter.Optional, password = RouteParameter.Optional }, constraints: new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) } ); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { controller = "Home", id = RouteParameter.Optional } ); </code></pre>
12,766,431
5
0
null
2012-10-07 02:35:41.34 UTC
13
2020-09-03 15:06:55.657 UTC
2014-05-28 13:42:43.42 UTC
null
3,365,233
null
575,065
null
1
105
c#|routing|asp.net-web-api
155,700
<p>Please use the attributes from the System.Web.<strong>Http</strong> namespace on your WebAPI actions:</p> <pre><code> [System.Web.Http.AcceptVerbs("GET", "POST")] [System.Web.Http.HttpGet] public string Auth(string username, string password) {...} </code></pre> <p>The reason why it doesn't work is because you were using the attributes that are from the <strong>MVC</strong> namespace <code>System.Web.Mvc</code>. The classes in the <code>System.Web.Http</code> namespace are for <strong>WebAPI</strong>.</p>
37,156,574
Why does a generator expression need a lot of memory?
<h2>Problem</h2> <p>Let's assume that I want to find <code>n**2</code> for all numbers smaller than <code>20000000</code>.</p> <h3>General setup for all three variants that I test:</h3> <pre><code>import time, psutil, gc gc.collect() mem_before = psutil.virtual_memory()[3] time1 = time.time() # (comprehension, generator, function)-code comes here time2 = time.time() mem_after = psutil.virtual_memory()[3] print "Used Mem = ", (mem_after - mem_before)/(1024**2) # convert Byte to Megabyte print "Calculation time = ", time2 - time1 </code></pre> <h3>Three options to calculate these numbers:</h3> <p><strong>1. Creating a list of via comprehension:</strong></p> <pre><code>x = [i**2 for i in range(20000000)] </code></pre> <p>It is really slow and time consuming:</p> <pre><code>Used Mem = 1270 # Megabytes Calculation time = 33.9309999943 # Seconds </code></pre> <p><strong>2. Creating a generator using <code>'()'</code>:</strong></p> <pre><code>x = (i**2 for i in range(20000000)) </code></pre> <p>It is much faster than option 1, but still uses a lot of memory:</p> <pre><code>Used Mem = 611 Calculation time = 0.278000116348 </code></pre> <p><strong>3. Defining a generator function (most efficient):</strong></p> <pre><code>def f(n): i = 0 while i &lt; n: yield i**2 i += 1 x = f(20000000) </code></pre> <p>Its consumption:</p> <pre><code>Used Mem = 0 Calculation time = 0.0 </code></pre> <h3>The questions are:</h3> <ol> <li>What's the difference between the first and second solutions? Using <code>()</code> creates a generator, so why does it need a lot of memory?</li> <li>Is there any built-in function equivalent to my third option?</li> </ol>
37,156,765
2
7
null
2016-05-11 08:06:40.687 UTC
6
2018-10-03 10:12:21.543 UTC
2018-10-03 10:12:21.543 UTC
null
5,997,596
null
6,228,520
null
1
29
python|python-2.7|generator
6,293
<ol> <li><p>As others have pointed out in the comments, <code>range</code> creates a <code>list</code> in Python 2. Hence, it is not the generator per se that uses up the memory, but the <code>range</code> that the generator uses:</p> <pre><code>x = (i**2 for i in range(20000000)) # builds a 2*10**7 element list, not for the squares , but for the bases &gt;&gt;&gt; sys.getsizeof(range(100)) 872 &gt;&gt;&gt; sys.getsizeof(xrange(100)) 40 &gt;&gt;&gt; sys.getsizeof(range(1000)) 8720 &gt;&gt;&gt; sys.getsizeof(xrange(1000)) 40 &gt;&gt;&gt; sys.getsizeof(range(20000000)) 160000072 &gt;&gt;&gt; sys.getsizeof(xrange(20000000)) 40 </code></pre> <p>This also explains why your second version (the generator expression) uses around half the memory of the first version (the list comprehension) as the first one builds two lists (for the bases and the squares) while the second only builds one list for the bases.</p></li> <li><p><code>xrange(20000000)</code> thus, greatly improves memory usage as it returns a lazy iterable. This is essentially the built-in memory efficient way to iterate over a range of numbers that mirrors your third version (with the added flexibility of <code>start</code>, <code>stop</code> and <code>step</code>):</p> <pre><code>x = (i**2 for i in xrange(20000000)) </code></pre> <p>In Python 3, <code>range</code> is essentially what <code>xrange</code> used to be in Python 2. However, the Python 3 <code>range</code> object has some nice features that Python 2's <code>xrange</code> doesn't have, like <code>O(1)</code> slicing, contains, etc.</p></li> </ol> <h2>Some references:</h2> <ul> <li><a href="https://docs.python.org/2/library/functions.html#xrange">Python2 xrange docs</a></li> <li><a href="https://docs.python.org/3/library/stdtypes.html#ranges">Python3 range docs</a></li> <li><a href="/q/135041">Stack Overflow - "Should you always favor xrange() over range()?"</a></li> <li><a href="/a/30081318/4850040">Martijn Pieters excellent answer to "Why is 1000000000000000 in range(1000000000000001) so fast in Python 3?"</a></li> </ul>
16,861,127
Onion Architecture: Business Services Interfaces and Implementation
<p>I am learning about the Onion Architecture. I have a confusion about the service layer, because I see some people saying that the core layer should only contain:</p> <ul> <li>Models</li> <li>Repository interfaces</li> <li>Services interfaces</li> </ul> <p>But others express that it also should implement the services interfaces. So what layer should implement the services interfaces? </p> <p>I thought that the infrastructure layer should implement:</p> <ul> <li>Repository Interfaces</li> <li>Services Interfaces</li> </ul> <p>And inject them to UI layer and Test layer when requested.</p> <p>Thank you!</p>
16,959,061
2
3
null
2013-05-31 15:44:55.77 UTC
8
2021-06-20 18:20:03.867 UTC
2013-05-31 15:52:27.943 UTC
null
13,302
null
257,068
null
1
13
asp.net-mvc|ninject|onion-architecture
5,552
<p>The core layer should contain:</p> <ul> <li>Models/Entities/POCOs/Whatever_the_name... it's all about domain objects </li> <li><strong>ALL</strong> the interfaces (including repositories and services) </li> <li>Your core business services implementation <strong>(*)</strong></li> </ul> <p><strong>(*)</strong> If your business is about handling orders, then the implementation of your <code>IWorkOrderService</code> should be in the core layer. If your <code>WorkOrderService</code> needs to access let's say a <code>ShippingService</code> (which is not your business), then it will only manipulate the <code>IShippingService</code> defined in the core layer and the <code>IShippingService</code> implementation will be somewhere in the infrastructure layer.</p> <p>If your <code>WorkOrderService</code> needs an <code>OrderRepository</code> it will be done excatly the same way.</p> <p>Here's a code example:</p> <pre><code>namespace MyBusiness.Core.Services { internal class WorkOrderService: IWorkOrderService { public WorkOrderService(IOrderRepository orderRepository, IShippingService shippingService) { _orderRepository = orderRepository; _shippingService = shippingService; } ... } } </code></pre> <p>This will be up to the outermost layer of your onion architecture - the Dependency Resolution Layer - to bound all your interfaces with the right service implementation at run time.</p> <pre><code>For&lt;IWorkOrderService&gt;().Use&lt;Core.Services.WorkOrderService&gt;(); For&lt;IShippingService&gt;().Use&lt;Infrastructure.Services.ShippingService&gt;(); For&lt;IOrderRepository&gt;().Use&lt;Infrastructure.Data.OrderRepository&gt;(); </code></pre>
17,011,528
How to integrate Pinterest in ios application
<p>I want to integrate <strong>pinterest</strong> in my application. i want to add button of pinterest in my app through which i can upload image on pinterest I refer <a href="http://developers.pinterest.com/">their Developers site</a> but it doesnt help me.</p> <p>I include SDK and tried their code but it doesnt work for me.</p> <pre><code> #import &lt;Pinterest/Pinterest.h&gt; UIButton* pinItButton = [Pinterest pinItButton]; [pinItButton addTarget:self action:@selector(pinIt:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:pinItButton]; - (void)pinIt:(id)sender { [_pinterest createPinWithImageURL:@"http://placekitten.com/500/400" sourceURL:@"http://placekitten.com" description:@"Pinning from Pin It Demo"]; } </code></pre> <p>please any help will be appreciated.</p> <p>Thanks in advance.</p>
17,011,726
1
0
null
2013-06-09 16:08:07.39 UTC
15
2014-05-06 10:44:51.087 UTC
null
null
null
null
2,456,220
null
1
14
iphone|ios|objective-c|ipad|pinterest
9,344
<p>I dont understand whats your actual problem but here i provide some easy step to integrate pinterest to your app</p> <p><strong>step : 1</strong> Register for a Client ID from <a href="http://developers.pinterest.com/manage/" rel="noreferrer">here</a> </p> <p><strong>step : 2</strong> Download the SDK from <a href="https://pinterest-ota-builds.s3.amazonaws.com/Pinterest.embeddedframework.zip" rel="noreferrer">here</a> and drag and drop into your project.</p> <p><strong>step : 3</strong> You will then need to add a URL type to support opening your app from the Pinterest app , so add URL type to your plist file </p> <pre><code>Example if your client id is 18571937652947: pin18571937652947 is the URL Scheme you need to support. </code></pre> <p><strong>step : 4</strong> To use the Pinterest framework you will need to import it into your file.</p> <pre><code> #import &lt;Pinterest/Pinterest.h&gt; </code></pre> <p>and declare its object in your .h file</p> <pre><code> Pinterest *pinterest </code></pre> <p><strong>step : 5</strong> initialise Pinterest object</p> <pre><code> pinterest = [[Pinterest alloc]initWithClientId:@"your app client id"] </code></pre> <p><strong>step : 6</strong> To use the standard PinIt Button in a view add it as so:</p> <pre><code> UIButton* pinItButton = [Pinterest pinItButton]; [pinItButton addTarget:self action:@selector(pinIt:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:pinItButton]; </code></pre> <p><strong>step : 7</strong> You will need to handle the action an example of this is below: </p> <pre><code>- (void)pinIt:(id)sender { NSURL *imageURL = [NSURL URLWithString:@"http://placekitten.com/500/400"]; NSURL *sourceURL = [NSURL URLWithString:@"http://placekitten.com"]; [pinterest createPinWithImageURL:imageURL sourceURL:sourceURL description:@"Pinning from Pin It Demo"]; } </code></pre> <p><strong>Note</strong> : pinterest app should be installed in your device otherwise this code redirect to itunes to download pinterest app</p>
16,977,898
MySQL optimizing INSERT speed being slowed down because of indices
<p><a href="http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html" rel="noreferrer">MySQL Docs</a> say :</p> <p>The size of the table slows down the insertion of indexes by log N, assuming B-tree indexes.</p> <p>Does this mean that for insertion of each new row, the insertion speed will be slowed down by a factor of log N where N, I assume is number of rows? even if I insert all rows in just one query? i.e. :</p> <pre><code>INSERT INTO mytable VALUES (1,1,1), (2,2,2), (3,3,3), .... ,(n,n,n) </code></pre> <p>Where n is ~70,000</p> <p>I currently have ~1.47 million rows in a table with the following structure :</p> <pre><code>CREATE TABLE mytable ( `id` INT, `value` MEDIUMINT(5), `date` DATE, PRIMARY_KEY(`id`,`date`) ) ENGINE = InnoDB </code></pre> <p>When I insert in the above mentioned fashion in a transaction, the commit time taken is ~275 seconds. How can I optimize this, since new data is to be added everyday and the insert time will just keep on slowing down.</p> <p>Also, is there anything apart from just queries that might help? maybe some configuration settings?</p> <h1>Possible Method 1 - Removing Indices</h1> <p>I read that removing indices just before insert might help insert speed. And after inserts, I add the index again. But here the only index is primary key, and dropping it won't help much in my opinion. Also, while the primary key is <em>dropped</em> , all the select queries will be crippling slow.</p> <p><del>I do not know of any other possible methods.</del></p> <p><strong>Edit :</strong> Here are a few tests on inserting ~60,000 rows in the table with ~1.47 mil rows:</p> <p><strong>Using the plain query described above :</strong> 146 seconds</p> <p><strong>Using MySQL's LOAD DATA infile :</strong> 145 seconds</p> <p><strong>Using MySQL's LOAD DATA infile and splitting the csv files as suggested by David Jashi in his answer:</strong> 136 seconds for 60 files with 1000 rows each, 136 seconds for 6 files with 10,000 rows each</p> <p><strong>Removing and re-adding primary key :</strong> key removal took 11 seconds, 0.8 seconds for inserting data BUT 153 seconds for re-adding primary key, totally taking ~165 seconds</p>
16,988,019
5
10
null
2013-06-07 06:47:43.55 UTC
9
2020-07-07 20:00:42.417 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,412,255
null
1
17
mysql|sql|insert|indexing
47,204
<p>If you want fast inserts, first thing you need is proper hardware. That assumes sufficient amount of RAM, an SSD instead of mechanical drives and rather powerful CPU.</p> <p>Since you use InnoDB, what you want is to optimize it since default config is designed for slow and old machines.</p> <p><a href="https://www.percona.com/blog/2007/11/01/innodb-performance-optimization-basics/" rel="noreferrer">Here's a great read about configuring InnoDB</a></p> <p>After that, you need to know one thing - and that's how databases do their stuff internally, how hard drives work and so on. I'll simplify the mechanism in the following description:</p> <p>A transaction is MySQL waiting for the hard drive to confirm that it wrote the data. That's why transactions are slow on mechanical drives, they can do 200-400 input-output operations per second. Translated, that means you can get 200ish insert queries per second using InnoDB on a mechanical drive. Naturally, <strong>this is simplified explanation</strong>, just to outline what's happening, <strong>it's not the full mechanism behind transaction</strong>.</p> <p>Since a query, especially the one corresponding to size of your table, is relatively small in terms of bytes - you're effectively wasting precious IOPS on a single query.</p> <p>If you wrap multiple queries (100 or 200 or more, there's no exact number, you have to test) in a single transaction and then commit it - you'll instantly achieve more writes per second.</p> <p>Percona guys are achieving 15k inserts a second on a relatively cheap hardware. Even 5k inserts a second isn't bad. The table such as yours is small, I've done tests on a similar table (3 columns more) and I managed to get to 1 billion records without noticeable issues, using 16gb ram machine with a 240GB SSD (1 drive, no RAID, used for testing purposes).</p> <p>TL;DR: - follow the link above, configure your server, get an SSD, wrap multiple inserts in 1 transactions and profit. And don't turn indexing off and then on, it's not applicable always, because at some point you will spend processing and IO time to build them.</p>
17,011,121
ggplot2: Logistic Regression - plot probabilities and regression line
<p>I have a data.frame containing a continuous predictor and a dichotomous response variable. </p> <pre><code>&gt; head(df) position response 1 0 1 2 3 1 3 -4 0 4 -1 0 5 -2 1 6 0 0 </code></pre> <p>I can easily compute a logistic regression by means of the <code>glm()</code>-function, no problems up to this point. </p> <p>Next, <strong>I want to create a plot with <code>ggplot</code>, that contains both the empiric probabilities</strong> for each of the overall 11 predictor values, <strong>and the fitted regression line</strong>. </p> <p>I went ahead and computed the probabilities with <code>cast()</code> and saved them in another data.frame</p> <pre><code>&gt; probs position prob 1 -5 0.0500 2 -4 0.0000 3 -3 0.0000 4 -2 0.2000 5 -1 0.1500 6 0 0.3684 7 1 0.4500 8 2 0.6500 9 3 0.7500 10 4 0.8500 11 5 1.0000 </code></pre> <p>I plotted the probabilities:</p> <pre><code>p &lt;- ggplot(probs, aes(x=position, y=prob)) + geom_point() </code></pre> <p>But when I try to add the fitted regression line</p> <pre><code>p &lt;- p + stat_smooth(method="glm", family="binomial", se=F) </code></pre> <p>it returns a warning: <code>non-integer #successes in a binomial glm!</code>. I know that in order to plot the <code>stat_smooth</code> "correctly", I'd have to call it on the original <code>df</code> data with the dichotomous variable. However if I use the <code>df</code>data in <code>ggplot()</code>, I see no way to plot the probabilities. </p> <p><strong>How can I combine the probabilities and the regression line in one plot</strong>, in the way it's meant to be in ggplot2, i.e. without getting any warning or error messages? </p>
17,011,659
1
1
null
2013-06-09 15:24:51.503 UTC
9
2017-11-06 09:11:35.247 UTC
null
null
null
null
2,468,413
null
1
19
r|ggplot2|regression
58,688
<p>There are basically three solutions:</p> <h2>Merging the data.frames</h2> <p>The easiest, after you have your data in two separate <code>data.frame</code>s would be to merge them by <code>position</code>:</p> <pre><code>mydf &lt;- merge( mydf, probs, by="position") </code></pre> <p>Then you can call <code>ggplot</code> on this <code>data.frame</code> without warnings:</p> <pre><code>ggplot( mydf, aes(x=position, y=prob)) + geom_point() + geom_smooth(method = "glm", method.args = list(family = "binomial"), se = FALSE) </code></pre> <p><img src="https://i.stack.imgur.com/oFAFe.png" alt="enter image description here"></p> <h2>Avoiding the creation of two data.frames</h2> <p>In future you could directly avoid the creation of two separate data.frames which you have to merge later. Personally, I like to use the <code>plyr</code> package for that:</p> <pre><code>librayr(plyr) mydf &lt;- ddply( mydf, "position", mutate, prob = mean(response) ) </code></pre> <h2>Edit: Use different data for each layer</h2> <p>I forgot to mention, that you can use for each layer another <code>data.frame</code> which is a strong advantage of <code>ggplot2</code>:</p> <pre><code>ggplot( probs, aes(x=position, y=prob)) + geom_point() + geom_smooth(data = mydf, aes(x = position, y = response), method = "glm", method.args = list(family = "binomial"), se = FALSE) </code></pre> <p>As an additional hint: Avoid the usage of the variable name <code>df</code> since you override the built in function <code>stats::df</code> by assigning to this variable name.</p>
16,778,425
Pass variables between two PHP pages without using a form or the URL of page
<p>I want to pass a couple of variables from one PHP page to another. I am not using a form. The variables are some messages that the target page will display if something goes wrong. How can I pass these variables to the other PHP page while keeping them <strong>invisible</strong>?</p> <p>e.g. let's say that I have these two variables:</p> <pre><code>//Original page $message1 = "A message"; $message2 = "Another message"; </code></pre> <p>and I want to pass them from page1.php to page2.php. I don't want to pass them through the URL.</p> <pre><code>//I don't want 'page2.php?message='.$message1.'&amp;message2='.$message2 </code></pre> <p>Is there a way (maybe through $_POST?) to send the variables? If anyone is wondering why I want them to be invisible, I just don't want a big URL address with parameters like "&amp;message=Problem while uploading your file. This is not a valid .zip file" and I don't have much time to change the redirections of my page to avoid this problem.</p>
16,778,482
6
1
null
2013-05-27 18:07:35.773 UTC
12
2021-11-25 06:30:28.477 UTC
2018-03-19 06:29:52.32 UTC
null
5,933,150
null
1,860,791
null
1
22
php|variables|post
163,900
<p>Sessions would be good choice for you. Take a look at these two examples from <a href="http://php.net/manual/en/function.session-start.php" rel="nofollow noreferrer">PHP Manual</a>:</p> <blockquote> <p>Code of page1.php</p> </blockquote> <pre><code>&lt;?php // page1.php session_start(); echo 'Welcome to page #1'; $_SESSION['favcolor'] = 'green'; $_SESSION['animal'] = 'cat'; $_SESSION['time'] = time(); // Works if session cookie was accepted echo '&lt;br /&gt;&lt;a href="page2.php"&gt;page 2&lt;/a&gt;'; // Or pass along the session id, if needed echo '&lt;br /&gt;&lt;a href="page2.php?' . SID . '"&gt;page 2&lt;/a&gt;'; ?&gt; </code></pre> <blockquote> <p>Code of page2.php</p> </blockquote> <pre><code>&lt;?php // page2.php session_start(); echo 'Welcome to page #2&lt;br /&gt;'; echo $_SESSION['favcolor']; // green echo $_SESSION['animal']; // cat echo date('Y m d H:i:s', $_SESSION['time']); // You may want to use SID here, like we did in page1.php echo '&lt;br /&gt;&lt;a href="page1.php"&gt;page 1&lt;/a&gt;'; ?&gt; </code></pre> <p>To clear up things - <a href="http://php.net/manual/en/session.constants.php" rel="nofollow noreferrer">SID is PHP's predefined constant</a> which contains session name and its id. Example SID value:</p> <pre><code>PHPSESSID=d78d0851898450eb6aa1e6b1d2a484f1 </code></pre>
50,732,321
Artisan command for clearing all session data in Laravel
<p>What is the artisan command for clearing all session data in Laravel, I'm looking for something like:</p> <pre><code>$ php artisan session:clear </code></pre> <p>But apparently it does not exist. How would I clear it from command line?</p> <p>I tried using </p> <pre><code>$ php artisan tinker ... \Session::flush(); </code></pre> <p>But it flushes session of only one user, I want to flush all sessions for all users. How can I do it?</p> <p>I tried this:</p> <pre><code>artisan cache:clear </code></pre> <p>But it does not clear session, again.</p>
50,732,675
10
3
null
2018-06-07 02:59:22.21 UTC
8
2022-05-01 19:41:12.417 UTC
2018-06-07 03:04:59.147 UTC
null
2,005,680
null
2,005,680
null
1
29
laravel|session|laravel-artisan
81,048
<hr> <p>UPDATE: This question seems to be asked quite often and many people are still actively commenting on it.</p> <p>In practice, it is a horrible idea to flush sessions using the </p> <pre><code>php artisan key:generate </code></pre> <p>It may wreak all kinds of havoc. The best way to do it is to clear whichever system you are using. </p> <hr> <p>The Lazy Programmers guide to flushing all sessions:</p> <pre><code>php artisan key:generate </code></pre> <p>Will make all sessions invalid because a new application key is specified</p> <p>The not so Lazy approach</p> <pre><code>php artisan make:command FlushSessions </code></pre> <p>and then insert </p> <pre><code>&lt;?php namespace App\Console\Commands; use Illuminate\Console\Command; use DB; class flushSessions extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'session:flush'; /** * The console command description. * * @var string */ protected $description = 'Flush all user sessions'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { DB::table('sessions')-&gt;truncate(); } } </code></pre> <p>and then </p> <pre><code>php artisan session:flush </code></pre>
10,150,642
Draw text in circular view?
<p>I want to draw a string say "stackoverflow" in circular view like below image can any one suggest how to do it. And also i need click event on each characer.</p> <p><img src="https://i.stack.imgur.com/dquNa.jpg" alt="IMAGE"></p>
10,150,970
2
4
null
2012-04-14 02:55:14.88 UTC
8
2013-09-23 06:47:13.113 UTC
2012-04-14 05:01:02.73 UTC
null
1,286,723
null
1,286,723
null
1
9
android
8,393
<p>You need to make a customized view for this. in onDraw method, create a path object, add circle to that object, and then use Canvas Object to draw text on that path.</p> <pre><code>Path path = new Path(); path.addCircle(x, y, radius, Path.Direction.CW); myCanvas.drawTextOnPath(myText, path, offset, 0, myPaint); </code></pre> <p>Edit:</p> <p>use this line of code when using os 4.0 and above:</p> <pre><code>setLayerType(View.LAYER_TYPE_SOFTWARE, null); </code></pre>
9,651,467
How can I get my page headers to resize using responsive layout?
<p>So I have a site that I need to be functional both on mobile devices and on computers. I'm using bootstrap-responsive and have gotten a lot of things to work. Currently I'm working on the hero-unit for the front page. I have a page header that I would like to auto-scale according to screen size. The main bootstrap site (http://twitter.github.com/bootstrap/) makes use of something like what I want to do with their main page header. Any help is appreciated.</p> <p>Relevant Code:</p> <pre><code>&lt;div class="container"&gt; &lt;div class="hero-unit"&gt; &lt;div class="page-header"&gt; &lt;h1&gt;Page Header&lt;/h1&gt; &lt;/div&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris arcu dolor, dictum scelerisque gravida nec, vulputate in odio. Pellentesque sagittis ipsum et mauris elementum vitae molestie ipsum blandit. Mauris tempus hendrerit arcu, sed vestibulum justo tempor a. Praesent sit amet odio ligula. Morbi sit amet leo vestibulum neque bibendum ullamcorper sed ut ante. Vestibulum id diam quis ipsum aliquet vestibulum. Donec vulputate auctor pharetra.&lt;/p&gt; &lt;a href="#" class="btn btn-large btn-primary"&gt;Learn More&lt;/a&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>EDIT: Here's another example of it. <a href="http://www.screenlight.tv/">http://www.screenlight.tv/</a> If you resize your window on that page, the header resizes accordingly. I've tried looking at the source and I'm having a hard time finding it.</p>
9,651,754
4
3
null
2012-03-11 00:42:36.687 UTC
5
2015-05-26 03:57:19.867 UTC
2012-03-11 01:13:32.537 UTC
null
392,271
null
392,271
null
1
13
css|twitter-bootstrap
48,615
<p>Okay I've figured this one out. For future reference, this is done using the <code>@media(max-width: )</code> property. So for instance, you would do:</p> <pre><code>@media(max-width: 480px) { h1 { font-size: 12pt; } } </code></pre> <p>Or whatever you need to do. Hope this helps someone in the future! Cheers!</p>
9,861,990
SQLAlchemy: How to order query results (order_by) on a relationship's field?
<h1>Models</h1> <pre class="lang-default prettyprint-override"><code>from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, ForeignKey from sqlalchemy import Integer from sqlalchemy import Unicode from sqlalchemy import TIMESTAMP from sqlalchemy.orm import relationship BaseModel = declarative_base() class Base(BaseModel): __tablename__ = 'base' id = Column(Integer, primary_key=True) location = Column(Unicode(12), ForeignKey("locationterrain.location"), unique=True,) name = Column(Unicode(45)) ownerid = Column(Integer,ForeignKey("player.id")) occupierid = Column(Integer, ForeignKey("player.id")) submitid = Column(Integer,ForeignKey("player.id")) updateid = Column(Integer,ForeignKey("player.id")) owner = relationship("Player", primaryjoin='Base.ownerid==Player.id', join_depth=3, lazy='joined') occupier= relationship("Player", primaryjoin='Base.occupierid==Player.id', join_depth=3, lazy='joined') submitter = relationship("Player", primaryjoin='Base.submitid== Player.id', join_depth=3, lazy='joined') updater= relationship("Player", primaryjoin='Base.updateid== Player.id', join_depth=3, lazy='joined') class Player(BaseModel): __tablename__ = 'player' id = Column(Integer, ForeignKey("guildmember.playerid"), primary_key=True) name = Column(Unicode(45)) </code></pre> <h1>Searching</h1> <pre class="lang-default prettyprint-override"><code>bases = dbsession.query(Base) bases = bases.order_by(Base.owner.name) </code></pre> <p>This doesn't work .... I've searched everywhere and read the documentation. But I just don't see how I can sort my (Base) query on their 'owner' relationship's name.</p> <p>It always results in: </p> <pre><code> AttributeError: Neither 'InstrumentedAttribute' object nor 'Comparator' object has an attribute 'name' </code></pre> <p>This must be easy... but I don't see it. Also looked into Comparators, which seemed logical, but I don't see where the query part for the ORDER BY is generated or what I should be returning since everything is generated dynamically. And making a comparator for each of my 'player' relationships to do a simple thing seems over complicated.</p>
9,862,111
1
0
null
2012-03-25 16:45:36.99 UTC
4
2012-03-25 17:00:47.627 UTC
null
null
null
null
1,291,498
null
1
25
python|sqlalchemy|sql-order-by|field|relationship
40,958
<p>SQLAlchemy wants you to think in terms of SQL. If you do a query for "Base", that's:</p> <pre><code>SELECT * FROM base </code></pre> <p>easy. So how, in SQL, would you select the rows from "base" and order by the "name" column in a totally different table, that is, "player"? You use a join:</p> <pre><code>SELECT base.* FROM base JOIN player ON base.ownerid=player.id ORDER BY player.name </code></pre> <p>SQLAlchemy has you use the identical thought process - you join():</p> <pre><code>session.query(Base).join(Base.owner).order_by(Player.name) </code></pre>
9,940,859
Fastest way to pack a list of floats into bytes in python
<p>I have a list of say 100k floats and I want to convert it into a bytes buffer.</p> <pre><code>buf = bytes() for val in floatList: buf += struct.pack('f', val) return buf </code></pre> <p>This is quite slow. How can I make it faster using only standard Python 3.x libraries.</p>
9,941,024
9
4
null
2012-03-30 10:03:52.97 UTC
8
2020-01-03 03:43:27.43 UTC
2012-03-30 10:16:19.817 UTC
null
500,584
null
536,607
null
1
38
python|struct|python-3.x
62,088
<p>Just tell <code>struct</code> how many <code>float</code>s you have. 100k floats takes about a 1/100th of a second on my slow laptop.</p> <pre><code>import random import struct floatlist = [random.random() for _ in range(10**5)] buf = struct.pack('%sf' % len(floatlist), *floatlist) </code></pre>
10,047,802
'public static final' or 'private static final' with getter?
<p>In Java, it's taught that variables should be kept private to enable better encapsulation, but what about static constants? This:</p> <pre><code>public static final int FOO = 5; </code></pre> <p>Would be equivalent in result to this:</p> <pre><code>private static final int FOO = 5; ... public static getFoo() { return FOO; } </code></pre> <p>But which is better practice?</p>
10,047,926
7
1
null
2012-04-06 18:45:39.45 UTC
23
2012-04-06 22:25:41.817 UTC
2012-04-06 22:25:41.817 UTC
null
1,318,051
null
1,318,051
null
1
58
java|static|private|public|final
30,280
<p>There's one reason to not use a constant directly in your code.</p> <p>Assume FOO may change later on (but still stay constant), say to <code>public static final int FOO = 10;</code>. Shouldn't break anything as long as nobody's stupid enough to hardcode the value directly right?</p> <p>No. The Java compiler will inline constants such as Foo above into the calling code, i.e. <code>someFunc(FooClass.FOO);</code> becomes <code>someFunc(5);</code>. Now if you recompile your library but not the calling code you can end up in surprising situations. That's avoided if you use a function - the JIT will still optimize it just fine, so no real performance hit there.</p>
9,769,434
How to count all files inside a folder, its subfolder and all . The count should not include folder count
<p>How to count all files inside a folder, its subfolder and all . The count should not include folder count.</p> <p>I want to do it in MAC</p>
9,769,492
2
1
null
2012-03-19 11:36:26.44 UTC
11
2012-03-19 11:40:37.11 UTC
null
null
null
null
824,301
null
1
82
linux|command-line
106,705
<p><code>find . -type f | wc -l</code> will recursively list all the files (<code>-type f</code> restricts to only files) in the current directory (replace <code>.</code> with your path). The output of this is piped into <code>wc -l</code> which will count the number of lines.</p>
9,732,084
How do you represent a graph in Haskell?
<p>It's easy enough to represent a tree or list in haskell using algebraic data types. But how would you go about typographically representing a graph? It seems that you need to have pointers. I'm guessing you could have something like</p> <pre><code>type Nodetag = String type Neighbours = [Nodetag] data Node a = Node a Nodetag Neighbours </code></pre> <p>And that would be workable. However it feels a bit decoupled; The links between different nodes in the structure don't really "feel" as solid as the links between the current previous and next elements in a list, or the parents and children of a node in a tree. I have a hunch that doing algebraic manipulations on the graph as I defined it would be somewhat hindered by the level of indirection introduced through the tag system.</p> <p>It is primarily this feeling of doubt and perception of inelegance that causes me to ask this question. Is there a better/more mathematically elegant way of defining graphs in Haskell? Or have I stumbled upon something inherently hard/fundamental? Recursive data structures are sweet, but this seems to be something else. A self referential data structure in a different sense to how trees and lists are self referential. It's like lists and trees are self referential at the type level, but graphs are self referential at the value level.</p> <p>So what's really going on?</p>
9,732,413
7
2
null
2012-03-16 04:53:07.23 UTC
53
2016-08-10 18:53:41.18 UTC
null
null
null
null
877,603
null
1
132
haskell|types|graph|functional-programming|algebraic-data-types
36,939
<p>I also find it awkward to try to represent data structures with cycles in a pure language. It's the cycles that are really the problem; because values can be shared any ADT that can contain a member of the type (including lists and trees) is really a DAG (Directed Acyclic Graph). The fundamental issue is that if you have values A and B, with A containing B and B containing A, then neither can be created before the other exists. Because Haskell is lazy you can use a trick known as <a href="http://www.haskell.org/haskellwiki/Tying_the_Knot">Tying the Knot</a> to get around this, but that makes my brain hurt (because I haven't done much of it yet). I've done more of my substantial programming in Mercury than Haskell so far, and Mercury is strict so knot-tying doesn't help.</p> <p>Usually when I've run into this before I've just resorted to additional indirection, as you're suggesting; often by using a map from ids to the actual elements, and having elements contain references to the ids instead of to other elements. The main thing I didn't like about doing that (aside from the obvious inefficiency) is that it felt more fragile, introducing the possible errors of looking up an id that doesn't exist or trying to assign the same id to more than one element. You can write code so that these errors won't occur, of course, and even hide it behind abstractions so that the only places where such errors <em>could</em> occur are bounded. But it's still one more thing to get wrong.</p> <p>However, a quick google for "Haskell graph" led me to <a href="http://www.haskell.org/haskellwiki/The_Monad.Reader/Issue5/Practical_Graph_Handling">http://www.haskell.org/haskellwiki/The_Monad.Reader/Issue5/Practical_Graph_Handling</a>, which looks like a worthwhile read.</p>
7,984,280
Android SQLite - what does SQLiteDatabase.replace() actually do?
<p>I need to do a INSERT or UPDATE IF EXIST type of procedure with my database. I read that <code>.replace()</code> was the way to go. It inserts new records just fine, but if the record already exists, it doesn't appear to update it.</p> <p>I have something like this:</p> <pre><code>ContentValues values = new ContentValues(); values.put(ID, 1); values.put(NAME, "bob"); values.put(VISIBLE, true); db.replace("peopleTable", null, values); </code></pre> <p>If I run this code when this record isn't in the database, it appears to create the record just fine, as if I did an <code>insert()</code>. But if I change NAME to "john" or something like that, and run the <code>replace()</code> again, it doesn't appear to update the record.</p> <p>According to the docs, here is the syntax:</p> <pre><code>public long replace (String table, String nullColumnHack, ContentValues initialValues) </code></pre> <p>Why is it called <code>initalValues</code>? Does that mean those values are only used when the record doesn't exist and it's going to be inserted? If so, how do you use the method to update a record? Where do you specify the new values?</p> <p>If I am misunderstanding what <code>replace()</code> does altogether, can someone explain what it's purpose is?</p>
7,984,552
3
1
null
2011-11-02 16:57:44.927 UTC
5
2021-05-19 02:07:41.747 UTC
null
null
null
null
172,350
null
1
32
java|android|sqlite
21,218
<p>As I understand it <code>replace()</code> works much like the SQLite <a href="http://sqlite.org/lang_replace.html" rel="noreferrer">REPLACE</a> keyword - a row will be updated if a unique constraint violation occurs for the insert. So the ID column in your example would need to have a PRIMARY KEY constraint in the database schema for the row to be updated.</p>
8,336,607
How to check if the value is integer in java?
<p>I'm using some API by restTemplate. The API returns a key whose type is integer. </p> <p>But I'm not sure of that value, so I want to check whether the key is really an integer or not. I think it might be a string. </p> <p>What is the best way of checking if the value is really integer?</p> <p>added: I mean that some API might return value like below. {id : 10} or {id : "10"}</p>
8,336,631
4
6
null
2011-12-01 04:40:43.767 UTC
2
2013-10-15 07:16:39.46 UTC
2011-12-01 04:57:41.527 UTC
null
889,158
null
889,158
null
1
3
java|integer
72,377
<pre><code>Object x = someApi(); if (x instanceof Integer) </code></pre> <p>Note that if <code>someApi()</code> returns type <code>Integer</code> the only possibilities of something returned are:</p> <ul> <li>an <code>Integer</code></li> <li><code>null</code></li> </ul> <p>In which case you can:</p> <pre><code>if (x == null) { // not an Integer } else { // yes an Integer } </code></pre>
11,820,934
How to pop back to root view controller but then push to a different view?
<p>I am writing a simple application that has 3 view controllers. The root view controller is an <code>item listing</code>, basic table view. Off of this view controller, I push two different view controllers based on some user interaction - a <code>create item</code> view controller or a <code>view item</code> view controller.</p> <p>So, the storyboard segues just look like a V, or something.</p> <p>On my <code>create item</code> view controller, I would like it to pop back to the root view controller when the user creates a new item, but then push to the <code>view item</code> controller so that I can look at the newly created item.</p> <p>I can't seem to get this to work. It's easy enough to pop back to the root view controller, but I'm unable to push that <code>view item</code> controller.</p> <p>Any ideas? I've pasted my code, below. The pop function works, but the new view never appears.</p> <pre><code>- (void) onSave:(id)sender { CLLocation *currentLocation = [[LocationHelper sharedInstance] currentLocation]; // format the thread object dictionary NSArray* location = @[ @(currentLocation.coordinate.latitude), @(currentLocation.coordinate.longitude) ]; NSDictionary* thread = @{ @"title": _titleField.text, @"text": _textField.text, @"author": @"mustached-bear", @"location": location }; // send the new thread to the api server [[DerpHipsterAPIClient sharedClient] postPath:@"/api/thread" parameters:thread success:^(AFHTTPRequestOperation *operation, id responseObject) { // init thread object Thread *thread = [[Thread alloc] initWithDictionary:responseObject]; // init view thread controller ThreadViewController *viewThreadController = [[ThreadViewController alloc] init]; viewThreadController.thread = thread; [self.navigationController popToRootViewControllerAnimated:NO]; [self.navigationController pushViewController:viewThreadController animated:YES]; } failure:^(AFHTTPRequestOperation *operation, NSError *error) { [self.navigationController popToRootViewControllerAnimated:YES]; }]; } </code></pre>
11,821,532
8
1
null
2012-08-05 23:18:57.96 UTC
7
2018-05-04 18:16:20.29 UTC
null
null
null
null
294,120
null
1
18
ios|xcode|cocoa|uiviewcontroller|uinavigationcontroller
44,285
<p>An easy way to accomplish what you want to do is to build some simple logic into your main root view controllers -(void)viewWillAppear method and use a delegate callback to flip the logic switch. basically a "back reference" to the root controller. here is a quick example.</p> <p>main root controller (consider this controller a) - well call it controllerA set a property to keep track of the jump status</p> <pre><code>@property (nonatomic) BOOL jumpNeeded; </code></pre> <p>setup some logic in </p> <pre><code>- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; self.jumpNeeded ? NSLog(@"jump needed") : NSLog(@"no jump needed"); if (self.jumpNeeded) { NSLog(@"jumping"); self.jumpNeeded = NO; [self performSegueWithIdentifier:@"controllerC" sender:self]; } } </code></pre> <p>Now, in your main root controller,when a tableview row is selected do something like this when pushing to controllerB in your tableView did select method</p> <pre><code>[self performSegueWithIdentifer@"controllerB" sender:self]; </code></pre> <p>then implement your prepare for segue method</p> <pre><code>- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { //setup controller B if([segue.identifier isEqualTo:@"controllerB"]){ ControllerB *b = segue.destinationViewController; b.delegate = self; //note this is the back reference } //implement controller c here if needed } </code></pre> <p>Now move on to controllerB you need to set a property called "delegate" to hold the back reference and you need to import the header file from the root controller</p> <pre><code>#import "controllerA" @property (nonatomic,weak) controllerA *delegate; </code></pre> <p>then just before you pop back to controllerA, you set the flag</p> <pre><code> self.delegate.jumpNeeded = YES; [self.navigationController popViewControllerAnimated:YES]; </code></pre> <p>and that is about it. You don't have to do anything with controllerC. There are a few other ways to do, but this is pretty straight forward for your needs. hope it works out for you.</p>
11,487,797
Python Matplotlib Basemap overlay small image on map plot
<p>I am plotting data from an aircraft on a map and I would like to insert this 75px by 29px PNG image of an airplane at the coordinates of the latest data point on the plot.</p> <p><a href="https://i.stack.imgur.com/Q5tbO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q5tbO.png" alt="airplane" /></a></p> <p>As far as I know and have read, <code>pyplot.imshow()</code> is the best way to accomplish this. However, I am getting hung up on step 1, getting the image to even display. Using a normal plot instead of Basemap, it is easy enough to get the image to appear using imshow, but when using Basemap, I can't get it to show up at all. See the example code.</p> <p>If I can get the image to display on the map, I am assuming that I can, by trial and error, set its position and some proper dimensions for it using the <code>extent</code> attribute of <code>imshow()</code>, with the plot coordinates converted from the map coordinates <code>x,y = m(lons,lats)</code>.</p> <p>Here is the example code (to try it you may want to download the airplane image above).</p> <pre><code>from matplotlib import pyplot as plt from mpl_toolkits.basemap import Basemap import Image from numpy import arange lats = arange(26,29,0.5) lons = arange(-90,-87,0.5) m = Basemap(projection='cyl',llcrnrlon=min(lons)-2,llcrnrlat=min(lats)-2, urcrnrlon=max(lons)+2,urcrnrlat=max(lats)+2,resolution='i') x,y = m(lons,lats) u,v, = arange(0,51,10),arange(0,51,10) barbs = m.barbs(x,y,u,v) m.drawcoastlines(); m.drawcountries(); m.drawstates() img = Image.open('c130j_75px.png') im = plt.imshow(img, extent=(x[-1],x[-1]+50000,y[-1],y[-1]+50000)) plt.show() </code></pre> <p>Here's the resulting image, which doesn't contain a trace of the airplane. I have tried several different sizes using <code>extent</code>, thinking I may have just made it too small, but with no success. I also tried setting <code>zorder=10</code>, but also with no luck. Any help would be appreciated.</p> <p><a href="https://i.stack.imgur.com/cuDNs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cuDNs.png" alt="result" /></a></p> <p>Update: I can now get the image to at least appear by using <code>m.imshow</code> instead of <code>plt.imshow</code>, since the former passes in the map's axes instance, but the <code>extent</code> argument seems to have no effect on the dimensions of the image, as it always fills up the entire plot no matter how small I make <code>extent</code> dimensions, even if I set them to zero. How can I scale the airplane image appropriately and position it near the last data point?</p> <p><code>im = m.imshow(img, extent=(x[-1],x[-1]+5,y[-1],y[-1]+2))</code></p> <p><a href="https://i.stack.imgur.com/G9K3b.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G9K3b.png" alt="result2" /></a></p>
11,497,850
2
0
null
2012-07-14 22:17:25.797 UTC
11
2019-08-22 07:05:48.07 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
1,144,565
null
1
27
python|image|matplotlib|overlay|matplotlib-basemap
18,459
<p>Actually, for this you want to use a somewhat undocumented feature of matplotlib: the <code>matplotlib.offsetbox</code> module. There's an example here: <a href="http://matplotlib.sourceforge.net/trunk-docs/examples/pylab_examples/demo_annotation_box.html" rel="noreferrer">http://matplotlib.sourceforge.net/trunk-docs/examples/pylab_examples/demo_annotation_box.html</a></p> <p>In your case, you'd do something like this:</p> <pre><code>import matplotlib.pyplot as plt import numpy as np import Image from mpl_toolkits.basemap import Basemap from matplotlib.offsetbox import OffsetImage, AnnotationBbox # Set up the basemap and plot the markers. lats = np.arange(26, 29, 0.5) lons = np.arange(-90, -87, 0.5) m = Basemap(projection='cyl', llcrnrlon=min(lons) - 2, llcrnrlat=min(lats) - 2, urcrnrlon=max(lons) + 2, urcrnrlat=max(lats) + 2, resolution='i') x,y = m(lons,lats) u,v, = np.arange(0,51,10), np.arange(0,51,10) barbs = m.barbs(x,y,u,v) m.drawcoastlines() m.drawcountries() m.drawstates() # Add the plane marker at the last point. plane = np.array(Image.open('plane.jpg')) im = OffsetImage(plane, zoom=1) ab = AnnotationBbox(im, (x[-1],y[-1]), xycoords='data', frameon=False) # Get the axes object from the basemap and add the AnnotationBbox artist m._check_ax().add_artist(ab) plt.show() </code></pre> <p><img src="https://i.stack.imgur.com/gf47Y.png" alt="enter image description here"></p> <p>The advantage to this is that the plane is in axes coordinates and will stay the same size relative to the size of the figure when zooming in. </p>
11,607,009
What is antiJARLocking attribute?
<p>what does the attribute <code>antiJARLocking</code> mean ? What is it's significance when I turn it to <em>true / false</em> ?</p> <p>I have seen this attribute in <code>context.xml</code> file of web-application :</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;Context antiJARLocking="true" path="/poll"&gt; &lt;Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource" // etc etc &lt;/context&gt; </code></pre>
11,607,185
2
1
null
2012-07-23 05:42:02.817 UTC
3
2019-05-20 00:00:57.093 UTC
2019-05-20 00:00:57.093 UTC
null
139,985
null
648,138
null
1
36
java|jakarta-ee|tomcat
34,242
<h1>Tomcat 7</h1> <p>From the <a href="http://tomcat.apache.org/tomcat-7.0-doc/config/context.html" rel="noreferrer">Tomcat 7.0 documentation for Context Configuration</a>:</p> <blockquote> <p><em>"antiJARLocking - If true, the Tomcat classloader will take extra measures to avoid JAR file locking when resources are accessed inside JARs through URLs. This will impact startup time of applications, but could prove to be useful on platforms or configurations where file locking can occur. If not specified, the default value is false."</em></p> </blockquote> <p>(The problem they are trying to address … I think … is that a locked JAR file will stop things like hot redeployment from working.)</p> <p>Read the documentation for more information.</p> <h1>Tomcat 8 and later</h1> <p>The <code>antiJARLocking</code> attribute is replaced by the <a href="http://tomcat.apache.org/tomcat-8.0-doc/config/context.html#Standard_Implementation" rel="noreferrer"><code>antiResourceLocking</code></a> attribute in Tomcat 8 and later. The documentation mentions some noteworthy side-effects of setting this attribute.</p> <hr> <p>See also:</p> <ul> <li><a href="http://stackoverflow.com/q/22480442/642706">http://stackoverflow.com/q/22480442/642706</a> ... which notes that turning on this feature may be enabling a permgen (or in Java 8+ a metaspace) memory leak if you perform hot redeploys.</li> </ul>
11,499,110
.increment vs += 1
<p>I have a Picture model that contains a variable for a view count (integer). The view count is incremented by +1 every time someone views the Picture object.</p> <p>In getting this done, what is the difference between</p> <pre><code> @picture.view_count += 1 @picture.save </code></pre> <p>and</p> <pre><code> @picture.increment(:view_count, 1) </code></pre> <p>also if i use increment, is .save necessary?</p>
11,499,194
3
2
null
2012-07-16 06:30:27.797 UTC
8
2018-06-13 15:03:42.45 UTC
2018-06-13 15:03:42.45 UTC
null
9,084
null
1,320,543
null
1
42
ruby-on-rails|ruby|increment
41,640
<p>The source of <code>increment</code> is below, which initializes attribute to zero if nil and adds the value passed as by (default is 1), it does not do save, so <code>.save</code> is still necessary.</p> <pre><code>def increment(attribute, by = 1) self[attribute] ||= 0 self[attribute] += by self end </code></pre>
11,753,000
How to open the Google Play Store directly from my Android application?
<p>I have open the Google Play store using the following code </p> <pre><code>Intent i = new Intent(android.content.Intent.ACTION_VIEW); i.setData(Uri.parse("https://play.google.com/store/apps/details?id=my packagename ")); startActivity(i);. </code></pre> <p>But it shows me a Complete Action View as to select the option (browser/play store). I need to open the application in Play Store directly.</p>
11,753,070
25
1
null
2012-08-01 05:27:10.423 UTC
214
2022-04-16 12:19:00.257 UTC
2019-01-09 09:33:20.573 UTC
null
9,855,678
null
1,097,668
null
1
660
android|android-intent|google-play
868,588
<p>You can do this using the <a href="https://developer.android.com/distribute/tools/promote/linking.html" rel="noreferrer"><code>market://</code> prefix</a>.</p> <h2>Java</h2> <pre><code>final String appPackageName = getPackageName(); // getPackageName() from Context or Activity object try { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(&quot;market://details?id=&quot; + appPackageName))); } catch (android.content.ActivityNotFoundException anfe) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(&quot;https://play.google.com/store/apps/details?id=&quot; + appPackageName))); } </code></pre> <h2>Kotlin</h2> <pre><code>try { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(&quot;market://details?id=$packageName&quot;))) } catch (e: ActivityNotFoundException) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(&quot;https://play.google.com/store/apps/details?id=$packageName&quot;))) } </code></pre> <p>We use a <code>try/catch</code> block here because an <code>Exception</code> will be thrown if the Play Store is not installed on the target device.</p> <p><strong>NOTE</strong>: any app can register as capable of handling the <code>market://details?id=&lt;appId&gt;</code> Uri, if you want to specifically target Google Play check the <em>Berťák</em> answer</p>
20,194,722
Can You Get A Users Local LAN IP Address Via JavaScript?
<p>I know the initial reaction to this question is &quot;no&quot; and &quot;it can't be done&quot; and &quot;you shouldn't need it, you are doing something wrong&quot;. What I'm trying to do is get the users LAN IP address, and display it on the web page. Why? Because that's what the page I'm working on is all about, showing as much information as possible about you, the visitor: <a href="https://www.whatsmyip.org/more-info-about-you/" rel="noreferrer">https://www.whatsmyip.org/more-info-about-you/</a></p> <p>So I'm not actually DOING anything with the IP, other than showing it to the user for informational purposes. I used to do this by using a small Java applet. It worked pretty well. But these days, browser make you hit agree and trust so many times, to run even the most minor java applet, that I'd rather not run one at all.</p> <p>So for a while I just got rid of this feature, but I'd like it back if possible. It was something that I, as a computer consultant, would actually use from time to time. It's faster to go to this website to see what IP range a network is running on, than it is to go into System Preferences, Networking, and then whatever interface is active.</p> <p>So I'm wondering, hoping, if there's some way to do it in javascript alone? Maybe some new object you can access, similar to the way javascript can ask the browser where is geographic location on earth is. Maybe theres something similar for client networking information? If not, perhaps theres some other way entirely to do it? The only ways I can think of are a java applet, or a flash object. I'd rather not do either of those.</p>
26,850,789
9
6
null
2013-11-25 13:46:30.323 UTC
64
2021-10-18 16:59:18.59 UTC
2020-09-29 09:39:11.143 UTC
null
1,778,940
null
1,778,940
null
1
124
javascript|ip-address
246,389
<p>As it turns out, the recent WebRTC extension of HTML5 allows javascript to query the local client IP address. A proof of concept is available here: <a href="http://net.ipcalf.com/">http://net.ipcalf.com</a></p> <p>This feature is apparently <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=959893">by design</a>, and is not a bug. However, given its controversial nature, I would be cautious about relying on this behaviour. Nevertheless, I think it perfectly and appropriately addresses your intended purpose (revealing to the user what their browser is leaking). </p>
3,247,373
How to measure program execution time in ARM Cortex-A8 processor?
<p>I'm using an ARM Cortex-A8 based processor called as i.MX515. There is linux Ubuntu 9.10 distribution. I'm running a very big application written in C and I'm making use of <code>gettimeofday();</code> functions to measure the time my application takes.</p> <pre><code>main() { gettimeofday(start); .... .... .... gettimeofday(end); } </code></pre> <p>This method was sufficient to look at what blocks of my application was taking what amount of time. But, now that, I'm trying to optimize my code very throughly, with the gettimeofday() method of calculating time, I see a lot of fluctuation between successive runs (Run before and after my optimizations), so I'm not able to determine the actual execution times, hence the impact of my improvements.</p> <p>Can anyone suggest me what I should do?</p> <p>If by accessing the cycle counter (<strong>Idea suggested on ARM website for Cortex-M3</strong>) can anyone point me to some code which gives me the steps I have to follow to access the timer <strong>registers on Cortex-A8</strong>?</p> <p>If this method is not very accurate then please suggest some alternatives.</p> <p>Thanks</p> <hr> <h2>Follow ups</h2> <p><strong>Follow up 1: Wrote the following program on Code Sorcery, the executable was generated which when I tried running on the board, I got - Illegal instruction message :(</strong></p> <pre><code>static inline unsigned int get_cyclecount (void) { unsigned int value; // Read CCNT Register asm volatile ("MRC p15, 0, %0, c9, c13, 0\t\n": "=r"(value)); return value; } static inline void init_perfcounters (int32_t do_reset, int32_t enable_divider) { // in general enable all counters (including cycle counter) int32_t value = 1; // peform reset: if (do_reset) { value |= 2; // reset all counters to zero. value |= 4; // reset cycle counter to zero. } if (enable_divider) value |= 8; // enable "by 64" divider for CCNT. value |= 16; // program the performance-counter control-register: asm volatile ("MCR p15, 0, %0, c9, c12, 0\t\n" :: "r"(value)); // enable all counters: asm volatile ("MCR p15, 0, %0, c9, c12, 1\t\n" :: "r"(0x8000000f)); // clear overflows: asm volatile ("MCR p15, 0, %0, c9, c12, 3\t\n" :: "r"(0x8000000f)); } int main() { /* enable user-mode access to the performance counter*/ asm ("MCR p15, 0, %0, C9, C14, 0\n\t" :: "r"(1)); /* disable counter overflow interrupts (just in case)*/ asm ("MCR p15, 0, %0, C9, C14, 2\n\t" :: "r"(0x8000000f)); init_perfcounters (1, 0); // measure the counting overhead: unsigned int overhead = get_cyclecount(); overhead = get_cyclecount() - overhead; unsigned int t = get_cyclecount(); // do some stuff here.. printf("\nHello World!!"); t = get_cyclecount() - t; printf ("function took exactly %d cycles (including function call) ", t - overhead); get_cyclecount(); return 0; } </code></pre> <p><strong>Follow up 2: I had written to Freescale for support and they have sent me back the following reply and a program <em>(I did not quite understand much from it)</em></strong></p> <p><em>Here is what we can help you with right now: I am sending you attach an example of code, that sends an stream using the UART, from what your code, it seems that you are not init correctly the MPU.</em> </p> <pre><code>(hash)include &lt;stdio.h&gt; (hash)include &lt;stdlib.h&gt; (hash)define BIT13 0x02000 (hash)define R32 volatile unsigned long * (hash)define R16 volatile unsigned short * (hash)define R8 volatile unsigned char * (hash)define reg32_UART1_USR1 (*(R32)(0x73FBC094)) (hash)define reg32_UART1_UTXD (*(R32)(0x73FBC040)) (hash)define reg16_WMCR (*(R16)(0x73F98008)) (hash)define reg16_WSR (*(R16)(0x73F98002)) (hash)define AIPS_TZ1_BASE_ADDR 0x70000000 (hash)define IOMUXC_BASE_ADDR AIPS_TZ1_BASE_ADDR+0x03FA8000 typedef unsigned long U32; typedef unsigned short U16; typedef unsigned char U8; void serv_WDOG() { reg16_WSR = 0x5555; reg16_WSR = 0xAAAA; } void outbyte(char ch) { while( !(reg32_UART1_USR1 &amp; BIT13) ); reg32_UART1_UTXD = ch ; } void _init() { } void pause(int time) { int i; for ( i=0 ; i &lt; time ; i++); } void led() { //Write to Data register [DR] *(R32)(0x73F88000) = 0x00000040; // 1 --&gt; GPIO 2_6 pause(500000); *(R32)(0x73F88000) = 0x00000000; // 0 --&gt; GPIO 2_6 pause(500000); } void init_port_for_led() { //GPIO 2_6 [73F8_8000] EIM_D22 (AC11) DIAG_LED_GPIO //ALT1 mode //IOMUXC_SW_MUX_CTL_PAD_EIM_D22 [+0x0074] //MUX_MODE [2:0] = 001: Select mux mode: ALT1 mux port: GPIO[6] of instance: gpio2. // IOMUXC control for GPIO2_6 *(R32)(IOMUXC_BASE_ADDR + 0x74) = 0x00000001; //Write to DIR register [DIR] *(R32)(0x73F88004) = 0x00000040; // 1 : GPIO 2_6 - output *(R32)(0x83FDA090) = 0x00003001; *(R32)(0x83FDA090) = 0x00000007; } int main () { int k = 0x12345678 ; reg16_WMCR = 0 ; // disable watchdog init_port_for_led() ; while(1) { printf("Hello word %x\n\r", k ) ; serv_WDOG() ; led() ; } return(1) ; } </code></pre>
3,250,835
4
2
null
2010-07-14 14:52:25.343 UTC
43
2015-12-07 14:44:37.163 UTC
2010-07-17 06:44:11.35 UTC
null
49,246
null
317,331
null
1
30
c|arm|performancecounter|time-measurement|cortex-a8
44,882
<p>Accessing the performance counters isn't difficult, but you have to enable them from kernel-mode. By default the counters are disabled. </p> <p>In a nutshell you have to execute the following two lines inside the kernel. Either as a loadable module or just adding the two lines somewhere in the board-init will do:</p> <pre><code> /* enable user-mode access to the performance counter*/ asm ("MCR p15, 0, %0, C9, C14, 0\n\t" :: "r"(1)); /* disable counter overflow interrupts (just in case)*/ asm ("MCR p15, 0, %0, C9, C14, 2\n\t" :: "r"(0x8000000f)); </code></pre> <p>Once you did this the cycle counter will start incrementing for each cycle. Overflows of the register will go unnoticed and don't cause any problems (except they might mess up your measurements).</p> <p>Now you want to access the cycle-counter from the user-mode: </p> <p>We start with a function that reads the register:</p> <pre><code>static inline unsigned int get_cyclecount (void) { unsigned int value; // Read CCNT Register asm volatile ("MRC p15, 0, %0, c9, c13, 0\t\n": "=r"(value)); return value; } </code></pre> <p>And you most likely want to reset and set the divider as well:</p> <pre><code>static inline void init_perfcounters (int32_t do_reset, int32_t enable_divider) { // in general enable all counters (including cycle counter) int32_t value = 1; // peform reset: if (do_reset) { value |= 2; // reset all counters to zero. value |= 4; // reset cycle counter to zero. } if (enable_divider) value |= 8; // enable "by 64" divider for CCNT. value |= 16; // program the performance-counter control-register: asm volatile ("MCR p15, 0, %0, c9, c12, 0\t\n" :: "r"(value)); // enable all counters: asm volatile ("MCR p15, 0, %0, c9, c12, 1\t\n" :: "r"(0x8000000f)); // clear overflows: asm volatile ("MCR p15, 0, %0, c9, c12, 3\t\n" :: "r"(0x8000000f)); } </code></pre> <p><code>do_reset</code> will set the cycle-counter to zero. Easy as that.</p> <p><code>enable_diver</code> will enable the 1/64 cycle divider. Without this flag set you'll be measuring each cycle. With it enabled the counter gets increased for every 64 cycles. This is useful if you want to measure long times that would otherwise cause the counter to overflow.</p> <p>How to use it:</p> <pre><code> // init counters: init_perfcounters (1, 0); // measure the counting overhead: unsigned int overhead = get_cyclecount(); overhead = get_cyclecount() - overhead; unsigned int t = get_cyclecount(); // do some stuff here.. call_my_function(); t = get_cyclecount() - t; printf ("function took exactly %d cycles (including function call) ", t - overhead); </code></pre> <p>Should work on all Cortex-A8 CPUs..</p> <p>Oh - and some notes:</p> <p>Using these counters you'll measure the exact time between the two calls to <code>get_cyclecount()</code> including everything spent in other processes or in the kernel. There is no way to restrict the measurement to your process or a single thread.</p> <p>Also calling <code>get_cyclecount()</code> isn't free. It will compile to a single asm-instruction, but moves from the co-processor will stall the entire ARM pipeline. The overhead is quite high and can skew your measurement. Fortunately the overhead is also fixed, so you can measure it and subtract it from your timings. </p> <p>In my example I did that for every measurement. Don't do this in practice. An interrupt will sooner or later occur between the two calls and skew your measurements even further. I suggest that you measure the overhead a couple of times on an idle system, ignore all outsiders and use a fixed constant instead.</p>
3,426,265
PHP string replace match whole word
<p>I would like to replace just complete words using php</p> <p>Example : If I have </p> <pre><code>$text = "Hello hellol hello, Helloz"; </code></pre> <p>and I use</p> <pre><code>$newtext = str_replace("Hello",'NEW',$text); </code></pre> <p>The new text should look like</p> <blockquote> <p>NEW hello1 hello, Helloz</p> </blockquote> <p>PHP returns</p> <blockquote> <p>NEW hello1 hello, NEWz</p> </blockquote> <p>Thanks.</p>
3,426,309
4
0
null
2010-08-06 17:37:38.847 UTC
11
2020-07-14 22:04:15.14 UTC
2016-07-20 06:12:01.41 UTC
null
450,504
null
450,504
null
1
37
php|string|replace|str-replace
59,872
<p>You want to use regular expressions. The <code>\b</code> matches a word boundary.</p> <pre><code>$text = preg_replace('/\bHello\b/', 'NEW', $text); </code></pre> <hr> <p>If <code>$text</code> contains UTF-8 text, you'll have to add the Unicode modifier "u", so that non-latin characters are not misinterpreted as word boundaries:</p> <pre><code>$text = preg_replace('/\bHello\b/u', 'NEW', $text); </code></pre>
3,781,512
WCF 4.0 : WebMessageFormat.Json not working with WCF REST Template
<p>Downloaded the WCF REST Template from <a href="http://visualstudiogallery.msdn.microsoft.com/en-us/fbc7e5c1-a0d2-41bd-9d7b-e54c845394cd" rel="noreferrer">this</a> location. </p> <p>The default response format is XML, which works great. However, when I try to get a JSON response, I still get XML.</p> <p>This is my modified code -</p> <pre><code>[WebGet(UriTemplate = "",ResponseFormat = WebMessageFormat.Json)] public List&lt;SampleItem&gt; GetCollection() { // TODO: Replace the current implementation to return a collection of SampleItem instances return new List&lt;SampleItem&gt;() { new SampleItem() { Id = 1, StringValue = "Hello" } }; } </code></pre> <p>Note the ResponseFormat=WebMessageFormat.Json. That is the only change I did to that template.</p> <p>What am I missing?</p> <p>Thanks!</p>
3,781,739
5
0
null
2010-09-23 18:44:01.74 UTC
15
2015-09-08 08:39:15.737 UTC
null
null
null
null
456,534
null
1
30
wcf
19,050
<p>Figured out. <code>automaticFormatSelectionEnabled</code> property for standardendpoint should be set to <code>false</code> and defaultOutgoingReponseFormat should be set to <code>Json</code>.</p> <pre><code>&lt;standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="false" defaultOutgoingResponseFormat ="Json" /&gt; </code></pre>
3,392,099
Windows Workflow Foundation 4.0 Tutorials / Introductions
<p>Pretty much all of the tutorials/introductions to Windows Workflow Foundation seem to be targeted at versions prior to 4.0, or are <a href="http://msmvps.com/blogs/theproblemsolver/archive/2009/06/22/getting-started-with-windows-workflow-foundation-4.aspx" rel="noreferrer">somewhat simplistic</a> and don't really show me anything about WHAT the real strengths of Workflows are.</p> <p>Could someone point me in the direction of some slightly meatier tutorials (clearly my google-fu is failing me), as Workflow is one of the things that I've seen the templates for in VS but never had the time or inkling to have a play with until now.</p> <p><strong>Note:</strong> No video tutorials/introductions/guides, please. I find them impossible to learn from.</p>
3,392,156
5
1
null
2010-08-02 21:52:29.563 UTC
17
2012-11-20 20:35:17.427 UTC
2010-08-07 20:13:01.917 UTC
null
7,872
null
7,872
null
1
33
.net-4.0|workflow-foundation-4
25,008
<p>I've discovered recently myself that there's not a lot of online content available. Check out the <a href="http://msdn.microsoft.com/en-us/netframework/dd980560.aspx" rel="noreferrer">Workflow Foundation 4 Resources and Community</a> site on MSDN for some good articles and labs. Also, download the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=35ec8682-d5fd-4bc3-a51a-d8ad115a8792&amp;displaylang=en" rel="noreferrer">WF4 Samples</a>. I've learned a lot from poking through these samples and trying things out locally. </p> <p>As for the WHY of Workflow, you can read David Chappell's take <a href="http://msdn.microsoft.com/en-us/library/dd851337.aspx" rel="noreferrer">here</a>. I don't agree with some of what he claims (a bit too pie in the sky for me), but it's a good primer on the goals and rationale of WF.</p> <p>Hope that helps!</p>
3,462,058
How do I automate CPAN configuration?
<p>The first time you run cpan from the command line, you are prompted for answers to various questions. How do you automate cpan and install modules non-interactively from the beginning?</p>
3,462,743
5
0
null
2010-08-11 19:27:17.08 UTC
11
2012-12-14 03:07:27.087 UTC
null
null
null
null
10,415
null
1
49
perl|cpan
20,293
<p>Since it hasn't been mentioned yet, <a href="http://search.cpan.org/dist/App-cpanminus" rel="noreferrer">cpanminus</a> is a zero-conf cpan installer. And you can download a self-contained executable if it isn't available for your version control.</p> <p>The cpanm executable is easily installed (as documented in the executable itself) with:</p> <pre><code>curl -L http://cpanmin.us | perl - --self-upgrade # or wget -O - http://cpanmin.us | perl - --self-upgrade </code></pre>
3,957,055
console.log browser in android emulator
<p>How to see <code>console.log</code> messages of a website using android emulator?</p>
5,810,719
7
0
null
2010-10-18 06:49:05.78 UTC
9
2022-09-08 06:52:38.777 UTC
2018-03-15 15:39:21.953 UTC
null
515,189
null
277,696
null
1
30
android-emulator|console.log
40,727
<p>From Rich Chetwynd's short article &quot;Javascript debugging on Android browser&quot;.</p> <blockquote> <p>You can log javascript errors and console messages from your Android device or emulator. To do this you first need to install the Android SDK and USB drivers and enable USB debugging on the actual device.</p> <p>To check if the device is connected correctly you can run the following cmd from your Android SDK tools directory and you should see a device in the list</p> <p><code>c:\android sdk..\platform-tools\adb devices</code></p> <p>You can then use the Android Debug Bridge to filter debug messages so that you only see browser related messages by running the following cmd.</p> <p><code>c:\android sdk..\platform-tools\adb logcat browser:V *:S</code></p> <p>By default the log is written to stdout so you will see any Javascript errors or console.log messages etc written to the cmd window.</p> </blockquote> <p>Further details: <a href="https://developer.android.com/studio/command-line/logcat.html" rel="noreferrer">Logcat CLI tool docs</a>.</p>
4,034,719
What do braces after C# new statement do?
<p>Given the code below, what is the difference between the way <code>position0</code> is initialized and the way <code>position1</code> is initialized? Are they equivalent? If not, what is the difference?</p> <pre><code>class Program { static void Main(string[] args) { Position position0 = new Position() { x=3, y=4 }; Position position1 = new Position(); position1.x = 3; position1.y = 4; } } struct Position { public int x, y; } </code></pre>
4,034,749
7
0
null
2010-10-27 15:07:56.837 UTC
13
2016-08-02 17:49:05.98 UTC
2016-08-02 17:49:05.98 UTC
null
238,260
null
238,260
null
1
69
c#|.net|new-operator
34,247
<p>Object and collection initializers, used to initialize fields on an object.</p> <p><a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/bb384062.aspx</a></p> <p>They produce <em>nearly</em> equivalent IL. Jon Skeet has the answer on what is really going on.</p>
3,930,884
Array even & odd sorting
<p>I have an array where I have some numbers. Now I want to sort even numbers in a separate array and odd numbers in a separate. Is there any API to do that? I tried like this</p> <pre><code>int[] array_sort={5,12,3,21,8,7,19,102,201}; int [] even_sort; int i; for(i=0;i&lt;8;i++) { if(array_sort[i]%2==0) { even_sort=Arrays.sort(array_sort[i]);//error in sort System.out.println(even_sort); } } </code></pre>
3,931,128
8
1
null
2010-10-14 07:11:53.933 UTC
1
2021-09-23 08:46:39.973 UTC
2021-03-31 00:28:57.353 UTC
null
815,724
null
471,927
null
1
5
java
43,793
<p>Plain and simple.</p> <pre><code>int[] array_sort = {5, 12, 3, 21, 8, 7, 19, 102, 201 }; List&lt;Integer&gt; odd = new ArrayList&lt;Integer&gt;(); List&lt;Integer&gt; even = new ArrayList&lt;Integer&gt;(); for (int i : array_sort) { if ((i &amp; 1) == 1) { odd.add(i); } else { even.add(i); } } Collections.sort(odd); Collections.sort(even); System.out.println("Odd:" + odd); System.out.println("Even:" + even); </code></pre>
3,687,046
Python Sphinx autodoc and decorated members
<p>I am attempting to use Sphinx to document my Python class. I do so using autodoc:</p> <pre><code>.. autoclass:: Bus :members: </code></pre> <p>While it correctly fetches the docstrings for my methods, those that are decorated:</p> <pre><code> @checkStale def open(self): """ Some docs. """ # Code </code></pre> <p>with <code>@checkStale</code> being</p> <pre><code>def checkStale(f): @wraps(f) def newf(self, *args, **kwargs): if self._stale: raise Exception return f(self, *args, **kwargs) return newf </code></pre> <p>have an incorrect prototype, such as <code>open(*args, **kwargs)</code>.</p> <p>How can I fix this? I was under the impression that using <code>@wraps</code> would fix up this kind of thing.</p>
3,696,342
8
4
null
2010-09-10 17:59:59.02 UTC
4
2022-06-10 02:29:29.583 UTC
2020-01-23 00:52:00.58 UTC
null
10,794,031
null
315,974
null
1
32
python|decorator|python-sphinx|autodoc
12,814
<p>To expand on my comment:</p> <blockquote> <p>Have you tried using the decorator package and putting @decorator on checkStale? I had a similar issue using epydoc with a decorated function.</p> </blockquote> <p>As you asked in your comment, the decorator package is not part of the standard library.</p> <p>You can fall back using code something like the following (untested):</p> <pre><code>try: from decorator import decorator except ImportError: # No decorator package available. Create a no-op "decorator". def decorator(f): return f </code></pre>
3,872,236
Rails Object to hash
<p>I have the following object that has been created</p> <pre><code>@post = Post.create(:name =&gt; 'test', :post_number =&gt; 20, :active =&gt; true) </code></pre> <p>Once this is saved, I want to be able to get the object back to a hash, e.g. by doing somthing like:</p> <pre><code>@object.to_hash </code></pre> <p>How is this possible from within rails?</p>
3,872,253
10
0
null
2010-10-06 12:10:00.767 UTC
25
2020-07-28 17:58:10.247 UTC
2011-12-08 10:01:08.677 UTC
null
249,630
null
467,919
null
1
172
ruby-on-rails|ruby
127,719
<p>If you are looking for only attributes, then you can get them by:</p> <pre><code>@post.attributes </code></pre> <p>Note that this calls <a href="https://apidock.com/rails/v6.0.0/ActiveModel/AttributeSet/to_hash" rel="noreferrer"><code>ActiveModel::AttributeSet.to_hash</code></a> every time you invoke it, so if you need to access the hash multiple times you should cache it in a local variable:</p> <pre><code>attribs = @post.attributes </code></pre>
3,341,485
How to make a HTML Page in A4 paper size page(s)?
<p>Is it possible to make a HTML page behave, for example, like a A4-sized page in MS Word?</p> <p>Essentially, I want to be able to show the HTML page in the browser, and outline the content in the dimensions of an A4 size page. </p> <p>For the sake of simplicity, I'm assuming that the HTML page will only contain text (no images etc.) and there will be no <code>&lt;br&gt;</code> tags for example.</p> <p>Also, when the HTML page is printed, it would come out as A4-sized paper pages.</p>
21,795,173
15
4
null
2010-07-27 07:26:37.34 UTC
214
2021-12-05 03:14:46.71 UTC
2015-08-03 05:25:06.283 UTC
null
2,432,317
null
382,818
null
1
476
html|css|printing
817,498
<p>Ages ago, in November 2005, AlistApart.com published an article on how they published a book using nothing but HTML and CSS. See: <a href="http://alistapart.com/article/boom" rel="noreferrer">http://alistapart.com/article/boom</a></p> <p>Here's an excerpt of that article:</p> <blockquote> <p>CSS2 has a notion of paged media (think sheets of paper), as opposed to continuous media (think scrollbars). Style sheets can set the size of pages and their margins. Page templates can be given names and elements can state which named page they want to be printed on. Also, elements in the source document can force page breaks. Here is a snippet from the style sheet we used:</p> </blockquote> <pre class="lang-css prettyprint-override"><code>@page { size: 7in 9.25in; margin: 27mm 16mm 27mm 16mm; } </code></pre> <blockquote> <p>Having a US-based publisher, we were given the page size in inches. We, being Europeans, continued with metric measurements. CSS accepts both.</p> </blockquote> <blockquote> <p>After setting the up the page size and margin, we needed to make sure there are page breaks in the right places. The following excerpt shows how page breaks are generated after chapters and appendices:</p> </blockquote> <pre class="lang-css prettyprint-override"><code>div.chapter, div.appendix { page-break-after: always; } </code></pre> <blockquote> <p>Also, we used CSS2 to declare named pages:</p> </blockquote> <pre class="lang-css prettyprint-override"><code>div.titlepage { page: blank; } </code></pre> <blockquote> <p>That is, the title page is to be printed on pages with the name “blank.” CSS2 described the concept of named pages, but their value only becomes apparent when headers and footers are available.</p> </blockquote> <p>Anyway…</p> <p>Since you want to print A4, you'll need different dimensions of course:</p> <pre class="lang-css prettyprint-override"><code>@page { size: 21cm 29.7cm; margin: 30mm 45mm 30mm 45mm; /* change the margins as you want them to be. */ } </code></pre> <p>The article dives into things like setting page-breaks, etc. so you might want to read that completely.</p> <p>In your case, the trick is to create the print CSS first. Most modern browsers (&gt;2005) support zooming and will already be able to display a website based on the print CSS.</p> <p>Now, you'll want to make the web display look a bit different and adapt the whole design to fit most browsers too (including the old, pre 2005 ones). For that, you'll have to create a web CSS file or override some parts of your print CSS. When creating CSS for web display, remember that a browser can have ANY size (think: “mobile” up to “big-screen TVs”). Meaning: for the web CSS your page-width and image-width is best set using a variable width (%) to support as many display devices and web-browsing clients as possible.</p> <p><strong>EDIT (26-02-2015)</strong></p> <p>Today, I happened to stumble upon another, more recent <a href="http://www.smashingmagazine.com/2015/01/07/designing-for-print-with-css/" rel="noreferrer">article at SmashingMagazine</a> which also dives into designing for print with HTML and CSS… just in case you could use yet-another-tutorial.</p> <p><strong>EDIT (30-10-2018)</strong></p> <p>It has been brought to my attention in that <code>size</code> is not valid CSS3, which is indeed correct — I merely repeated the code quoted in the article which (as noted) was good old CSS2 (which makes sense when you look at the year the article and this answer were first published). Anyway, here's the valid CSS3 code for your copy-and-paste convenience:</p> <pre class="lang-css prettyprint-override"><code>@media print { body{ width: 21cm; height: 29.7cm; margin: 30mm 45mm 30mm 45mm; /* change the margins as you want them to be. */ } } </code></pre> <p>In case you think you really need pixels (<strong>you should actually avoid using pixels</strong>), you will have to take care of choosing the correct DPI for printing:</p> <ul> <li>72 dpi (web) = 595 X 842 pixels</li> <li>300 dpi (print) = 2480 X 3508 pixels</li> <li>600 dpi (high quality print) = 4960 X 7016 pixels</li> </ul> <p>Yet, I would avoid the hassle and simply use <code>cm</code> (centimeters) or <code>mm</code> (millimeters) for sizing as that avoids rendering glitches that can arise depending on which client you use.</p>
3,496,269
How to put a border around an Android TextView?
<p>Is it possible to draw a border around an Android <code>TextView</code>?</p>
3,496,310
23
3
null
2010-08-16 18:50:27.807 UTC
202
2022-05-18 01:19:29.423 UTC
2022-05-18 01:19:29.423 UTC
null
16,136,190
null
69,983
null
1
803
android|android-layout|textview|border|android-shapedrawable
875,256
<p>You can set a shape drawable (a rectangle) as background for the view.</p> <pre><code>&lt;TextView android:text="Some text" android:background="@drawable/back"/&gt; </code></pre> <p>And rectangle drawable back.xml (put into res/drawable folder):</p> <pre><code>&lt;shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" &gt; &lt;solid android:color="@android:color/white" /&gt; &lt;stroke android:width="1dip" android:color="#4fa5d5"/&gt; &lt;/shape&gt; </code></pre> <p>You can use <code>@android:color/transparent</code> for the solid color to have a transparent background. You can also use padding to separate the text from the border. for more information see: <a href="http://developer.android.com/guide/topics/resources/drawable-resource.html" rel="noreferrer">http://developer.android.com/guide/topics/resources/drawable-resource.html</a></p>
7,703,434
JSoup character encoding issue
<p>I am using JSoup to parse content from <a href="http://www.latijnengrieks.com/vertaling.php?id=5368" rel="noreferrer">http://www.latijnengrieks.com/vertaling.php?id=5368</a> . this is a third party website and does not specify proper encoding. i am using the following code to load the data:</p> <pre><code>public class Loader { public static void main(String[] args){ String url = "http://www.latijnengrieks.com/vertaling.php?id=5368"; Document doc; try { doc = Jsoup.connect(url).timeout(5000).get(); Element content = doc.select("div.kader").first(); Element contenttableElement = content.getElementsByClass("kopje").first().parent().parent(); String contenttext = content.html(); String tabletext = contenttableElement.html(); contenttext = Jsoup.parse(contenttext).text(); contenttext = contenttext.replace("br2n", "\n"); tabletext = Jsoup.parse(tabletext.replaceAll("(?i)&lt;br[^&gt;]*&gt;", "br2n")).text(); tabletext = tabletext.replace("br2n", "\n"); String text = contenttext.substring(tabletext.length(), contenttext.length()); System.out.println(text); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } </code></pre> <p>this gives the following output:</p> <pre><code>Aeneas dwaalt rond in Troje en zoekt Cre?sa. Cre?sa is echter op de vlucht gestorven Plotseling verschijnt er een schim. Het is de schim van Cre?sa. De schim zegt:'De oorlog woedt!' Troje is ingenomen! Cre?sa is gestorven:'Vlucht!' Aeneas vlucht echter niet. Dan spreekt de schim:'Vlucht! Er staat jou een nieuw vaderland en een nieuw koninkrijk te wachten.' Dan pas gehoorzaamt Aeneas en vlucht. </code></pre> <p>is there any way the ? marks can be the original (ü) again in the output?</p>
7,716,688
4
2
null
2011-10-09 12:17:40.593 UTC
9
2016-08-08 14:24:17.007 UTC
null
null
null
null
974,477
null
1
23
java|jsoup
46,796
<p>The <code>charset</code> attribute is missing in HTTP response <code>Content-Type</code> header. Jsoup will resort to platform default charset when parsing the HTML. The <code>Document.OutputSettings#charset()</code> won't work as it's used for presentation only (on <code>html()</code> and <code>text()</code>), not for parsing the data (in other words, it's too late already).</p> <p>You need to read the URL as <code>InputStream</code> and manually specify the charset in <code>Jsoup#parse()</code> method.</p> <pre><code>String url = "http://www.latijnengrieks.com/vertaling.php?id=5368"; Document document = Jsoup.parse(new URL(url).openStream(), "ISO-8859-1", url); Element paragraph = document.select("div.kader p").first(); for (Node node : paragraph.childNodes()) { if (node instanceof TextNode) { System.out.println(((TextNode) node).text().trim()); } } </code></pre> <p>this results here in</p> <pre class="lang-none prettyprint-override"><code>Aeneas dwaalt rond in Troje en zoekt Creüsa. Creüsa is echter op de vlucht gestorven Plotseling verschijnt er een schim. Het is de schim van Creüsa. De schim zegt:'De oorlog woedt!' Troje is ingenomen! Creüsa is gestorven:'Vlucht!' Aeneas vlucht echter niet. Dan spreekt de schim:'Vlucht! Er staat jou een nieuw vaderland en een nieuw koninkrijk te wachten.' Dan pas gehoorzaamt Aeneas en vlucht. </code></pre>
7,996,629
How do I read the Nth line of a file and print it to a new file?
<p>I have a folder called foo. Foo has some other folders which might have sub folders and text files. I want to find every file which begins with the name year and and read its Nth line and print it to a new file. For example foo has a file called year1 and the sub folders have files called year2, year3 etc. The program will print the 1st line of year1 to a file called writeout, then it will print the 2nd line of year2 to the file writeout etc.</p> <p>I also didn't really understand how to do a for loop for a file.</p> <p>So far I have:</p> <pre><code>#!/bin/bash for year* in ~/foo do Here I tried writing some code using the sed command but I can't think of something else. done </code></pre> <p>I also get a message in the terminal which says `year*' not a valid identifier. Any ideas?</p>
7,996,841
7
1
null
2011-11-03 14:31:55.423 UTC
4
2015-01-23 15:53:45.12 UTC
null
null
null
null
702,968
null
1
17
bash|shell|unix
60,427
<p>Sed can help you.</p> <p>Recall that sed will normally process all lines in a file AND print each line in the file.</p> <p>You can turn off that feature, and have sed only print lines of interest by matching a pattern or line number.</p> <p>So, to print the 2nd line of file 2, you can say</p> <pre><code>sed -n '2p' file2 &gt; newFile2 </code></pre> <p>To print the 2nd line and then stop processing add the q (for quit) command (you also need braces to group the 2 commands together), i.e. </p> <pre><code>sed -n '2{p;q;}' file2 &gt; newFile2 </code></pre> <p>(if you are processing large files, this can be quite a time saving).</p> <p>To make that more general, you can change the number to a variable that will hold a number, i.e.</p> <pre><code> lineNo=3 sed -n "${lineNo}{p;q;}" file3 &gt; newFile3 </code></pre> <p>If you want all of your sliced lines to go into 1 file, then use the shells 'append-redirection', i.e.</p> <pre><code> for lineNo in 1 2 3 4 5 ; do sed -n "${lineNo}{p;q;}" file${lineNo} &gt;&gt; aggregateFile done </code></pre> <p>The other postings, with using the results of <code>find ...</code> to drive your filelist, are an excellent approach.</p> <p>I hope this helps.</p>
4,518,560
Group by in subquery and base query sql server
<p>I want to know if the following is possible.</p> <p>I have one table of which I want to retrieve 3 columns of data:</p> <p>Day, Sum of hours worked, Sum of hours worked with condition</p> <p>My query is</p> <pre><code>SELECT Day, SUM(Regular + Extra + Overtime) AS [Potential Hours], (SELECT SUM(Extra + Regular + Overtime) AS Expr1 FROM dbo.TICPlus_Effort_Billable_Only WHERE (Manager NOT LIKE '%manager1%')) AS [Billed Hours] FROM Billable AS Billable1 GROUP BY Day </code></pre> <p>With this query I get the sum of all the data in the subquery for each row, but I would like to have the subquery that includes the constraint to be grouped by day. Is it possible to have a group by in the subquery to do this so I get the daily sum with condition on a daily basis?</p>
4,518,604
3
0
null
2010-12-23 12:02:14.1 UTC
2
2021-01-06 23:02:45.283 UTC
2020-07-25 22:49:37.95 UTC
null
11,407,695
null
552,349
null
1
14
sql-server|group-by|subquery
67,451
<p>No, you will not be able to do that as the SUB QUERY in the SELECT list will then return more that 1 Value.</p> <p>You need to do it in a SUB Query in the FROM clause</p> <p>Something like</p> <pre><code> SELECT Day, SUM(Regular + Extra + Overtime) AS [Potential Hours], SubSum AS [Billed Hours] FROM Billable AS Billable1 LEFT JOIN ( SELECT Day, SUM(Extra + Regular + Overtime) AS SubSum FROM dbo.TICPlus_Effort_Billable_Only WHERE (Manager NOT LIKE '%manager1%') GROUP BY Day ) s ON Billable1.Day = s.Day GROUP BY Day </code></pre>
4,748,014
Updating XML node with PHP
<p>I've an XML file test.xml</p> <pre><code>&lt;?xml version="1.0"?&gt; &lt;info&gt; &lt;user&gt; &lt;name&gt; &lt;firstname&gt;FirstName&lt;/firstname&gt; &lt;lastname&gt;Last Name&lt;/lastname&gt; &lt;nameCoordinate&gt; &lt;xName&gt;125&lt;/xName&gt; &lt;yName&gt;20&lt;/yName&gt; &lt;/nameCoordinate&gt; &lt;/name&gt; &lt;/user&gt; &lt;/info&gt; </code></pre> <p>I'm trying to update the node xName &amp; yName using PHP on a form submission. So, I've loaded the file using simplexml_load_file(). The PHP form action code is below</p> <pre><code>&lt;?php $xPostName = $_POST['xName']; $yPostName = $_POST['yName']; //load xml file to edit $xml = simplexml_load_file('test.xml'); $xml-&gt;info-&gt;user-&gt;name-&gt;nameCoordinate-&gt;xName = $xPostName; $xml-&gt;info-&gt;user-&gt;name-&gt;nameCoordinate-&gt;yName = $yPostName; echo "done"; ?&gt; </code></pre> <p>I want to update the node values but the above code seems to be incorrect. Can anyone help me rectify it??</p> <p>UPDATE: My question is somewhat similar to this <a href="https://stackoverflow.com/questions/171539/updating-a-xml-file-using-php">Updating a XML file using PHP</a> but here, I'm loading the XML from an external file and also I'm updating an element, not an attribute. That's where my confusion lies.</p>
4,748,307
3
3
null
2011-01-20 14:00:40.84 UTC
6
2019-12-27 12:47:47.153 UTC
2017-05-23 11:46:27.603 UTC
null
-1
null
383,393
null
1
14
php|xml|simplexml
39,597
<p>You're not accessing the right node. In your example, <code>$xml</code> holds the root node <code>&lt;info/&gt;</code>. Here's a great tip: <strong>always name the variable that holds your XML document after its root node</strong>, it will prevent such confusion.</p> <p>Also, as Ward Muylaert pointed out, you need to save the file.</p> <p>Here's the corrected example:</p> <pre><code>// load the document // the root node is &lt;info/&gt; so we load it into $info $info = simplexml_load_file('test.xml'); // update $info-&gt;user-&gt;name-&gt;nameCoordinate-&gt;xName = $xPostName; $info-&gt;user-&gt;name-&gt;nameCoordinate-&gt;yName = $yPostName; // save the updated document $info-&gt;asXML('test.xml'); </code></pre>
4,354,257
Can I stop all processes using CUDA in Linux without rebooting?
<p>Is it possible to stop all running processing using the GPU via CUDA, without restarting the machine?</p>
4,571,250
4
1
null
2010-12-04 15:30:57.077 UTC
17
2021-09-24 06:24:51.227 UTC
2018-07-02 20:27:57.537 UTC
null
1,593,077
null
518,386
null
1
26
cuda|restart|kill-process
30,044
<p>The lsof utility will help with this. You can get a list of processes accessing your NVIDIA cards with:</p> <pre><code>lsof /dev/nvidia* </code></pre> <p>Then use kill or pkill to terminate the processes you want. Note that you may not want to kill X if it's running. On my desktop system, both X and kwin are also accessing the GPU.</p>
4,699,166
Where to change highlight color for selected occurrences in Eclipse?
<p>When a method or variable is selected it is highlighted in Eclipse with some color. Can anyone advice where to change that color? I'm working under Windows OS.</p>
4,699,258
4
1
null
2011-01-15 10:50:13.94 UTC
13
2017-07-08 14:10:36.357 UTC
2015-03-09 12:11:37.01 UTC
null
895,245
null
397,991
null
1
34
eclipse
23,503
<p>I've found where to change it:</p> <p>Preferences -> General -> Editors -> Text Editors -> Annotations and there you have to change both "Occurrences" and "Write occurrences".</p>
4,230,483
Ruby current class
<p>How do I determine the current open class in Ruby?</p>
4,230,563
5
0
null
2010-11-20 00:08:27.883 UTC
4
2020-09-21 15:55:10.883 UTC
2010-11-20 00:41:56.463 UTC
null
223,196
null
223,196
null
1
29
ruby
21,304
<p>Inside of a <code>class</code> definition body, <code>self</code> refers to the class itself. <code>Module#name</code> will tell you the name of the class/module, but only if it actually has one. (In Ruby, there is no such thing as a "class name". Classes are simply objects just like any other which get assigned to variables just like any other. It's just that if you happen to assign a class object to a constant, then the <code>name</code> method will return the name of that constant.)</p> <p>Example:</p> <pre><code>puts class Foo name end # Foo </code></pre> <p>But:</p> <pre><code>bar = Class.new bar.name # =&gt; nil BAR = bar bar.name #=&gt; 'BAR' </code></pre>
4,065,379
How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain
<p>I'm writing an Android app that requires SSL client authentication. I know how to create a JKS keystore for a desktop Java application, but Android only supports the BKS format. Every way I've tried to create the keystore results in the following error:<br> <code>handling exception: javax.net.ssl.SSLHandshakeException: null cert chain</code></p> <p>So it looks like the client is never sending a proper certificate chain, probably because I'm not creating the keystore properly. I'm unable to enable SSL debugging like I can on the desktop, so that's making this much more difficult than it should be.</p> <p>For reference the following is the command that IS working to create a BKS <strong>truststore</strong>:<br> <code>keytool -importcert -v -trustcacerts -file "cacert.pem" -alias ca -keystore "mySrvTruststore.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "bcprov-jdk16-145.jar" -storetype BKS -storepass testtest</code></p> <hr> <p>Here is the command I've tried that is NOT working to create a BKS client <strong>keystore</strong>:</p> <pre><code>cat clientkey.pem clientcert.pem cacert.pem &gt; client.pem keytool -import -v -file &lt;(openssl x509 -in client.pem) -alias client -keystore "clientkeystore" -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath "bcprov-jdk16-145.jar" -storetype BKS -storepass testtest </code></pre>
10,026,598
7
1
null
2010-10-31 22:05:46.23 UTC
54
2018-09-11 00:22:25.56 UTC
2018-09-11 00:22:25.56 UTC
null
299,262
null
299,262
null
1
54
java|android|ssl
111,460
<p><strong>Detailed Step by Step instructions I followed to achieve this</strong></p> <ul> <li>Download bouncycastle JAR from <a href="http://repo2.maven.org/maven2/org/bouncycastle/bcprov-ext-jdk15on/1.46/bcprov-ext-jdk15on-1.46.jar">http://repo2.maven.org/maven2/org/bouncycastle/bcprov-ext-jdk15on/1.46/bcprov-ext-jdk15on-1.46.jar</a> or take it from the "doc" folder.</li> <li>Configure BouncyCastle for PC using one of the below methods. <ul> <li>Adding the BC Provider Statically (Recommended) <ul> <li>Copy the bcprov-ext-jdk15on-1.46.jar to each <ul> <li>D:\tools\jdk1.5.0_09\jre\lib\ext (JDK (bundled JRE)</li> <li>D:\tools\jre1.5.0_09\lib\ext (JRE)</li> <li>C:\ (location to be used in env variable)</li> </ul></li> <li>Modify the java.security file under <ul> <li>D:\tools\jdk1.5.0_09\jre\lib\security</li> <li>D:\tools\jre1.5.0_09\lib\security</li> <li>and add the following entry <ul> <li>security.provider.7=org.bouncycastle.jce.provider.BouncyCastleProvider</li> </ul></li> </ul></li> <li>Add the following environment variable in "User Variables" section <ul> <li>CLASSPATH=%CLASSPATH%;c:\bcprov-ext-jdk15on-1.46.jar</li> </ul></li> </ul></li> <li>Add bcprov-ext-jdk15on-1.46.jar to CLASSPATH of your project and Add the following line in your code <ul> <li>Security.addProvider(new BouncyCastleProvider());</li> </ul></li> </ul></li> <li>Generate the Keystore using Bouncy Castle <ul> <li>Run the following command <ul> <li>keytool -genkey -alias myproject -keystore C:/myproject.keystore -storepass myproject -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider</li> </ul></li> <li>This generates the file C:\myproject.keystore</li> <li>Run the following command to check if it is properly generated or not <ul> <li>keytool -list -keystore C:\myproject.keystore -storetype BKS</li> </ul></li> </ul></li> <li><p>Configure BouncyCastle for TOMCAT</p> <ul> <li><p>Open D:\tools\apache-tomcat-6.0.35\conf\server.xml and add the following entry</p> <ul> <li>&lt;Connector port="8443" keystorePass="myproject" alias="myproject" keystore="c:/myproject.keystore" keystoreType="BKS" SSLEnabled="true" clientAuth="false" protocol="HTTP/1.1" scheme="https" secure="true" sslProtocol="TLS" sslImplementationName="org.bouncycastle.jce.provider.BouncyCastleProvider"/&gt;</li> </ul></li> <li><p>Restart the server after these changes.</p></li> </ul></li> <li>Configure BouncyCastle for Android Client <ul> <li>No need to configure since Android supports Bouncy Castle Version 1.46 internally in the provided "android.jar".</li> <li>Just implement your version of HTTP Client (MyHttpClient.java can be found below) and set the following in code <ul> <li>SSLSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);</li> </ul></li> <li>If you don't do this, it gives an exception as below <ul> <li>javax.net.ssl.SSLException: hostname in certificate didn't match: &lt;192.168.104.66> != </li> </ul></li> <li>In production mode, change the above code to <ul> <li>SSLSocketFactory.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);</li> </ul></li> </ul></li> </ul> <p><strong>MyHttpClient.java</strong></p> <pre><code>package com.arisglobal.aglite.network; import java.io.InputStream; import java.security.KeyStore; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.SingleClientConnManager; import com.arisglobal.aglite.activity.R; import android.content.Context; public class MyHttpClient extends DefaultHttpClient { final Context context; public MyHttpClient(Context context) { this.context = context; } @Override protected ClientConnectionManager createClientConnectionManager() { SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // Register for port 443 our SSLSocketFactory with our keystore to the ConnectionManager registry.register(new Scheme("https", newSslSocketFactory(), 443)); return new SingleClientConnManager(getParams(), registry); } private SSLSocketFactory newSslSocketFactory() { try { // Get an instance of the Bouncy Castle KeyStore format KeyStore trusted = KeyStore.getInstance("BKS"); // Get the raw resource, which contains the keystore with your trusted certificates (root and any intermediate certs) InputStream in = context.getResources().openRawResource(R.raw.aglite); try { // Initialize the keystore with the provided trusted certificates. // Also provide the password of the keystore trusted.load(in, "aglite".toCharArray()); } finally { in.close(); } // Pass the keystore to the SSLSocketFactory. The factory is responsible for the verification of the server certificate. SSLSocketFactory sf = new SSLSocketFactory(trusted); // Hostname verification from certificate // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506 sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sf; } catch (Exception e) { throw new AssertionError(e); } } } </code></pre> <p>How to invoke the above code in your Activity class:</p> <pre><code>DefaultHttpClient client = new MyHttpClient(getApplicationContext()); HttpResponse response = client.execute(...); </code></pre>
4,751,923
Difference between one-to-one and one-to-many relationship in database
<p>This is probably a basic(dumb) question but when having a one-to-one relationship in a database the other table has a foreign key ID(in this example). And in a one-to-many relationship the table contains many foreign keys. </p> <p>But the database does not know whether this is a one-to-one or one-to-many relationship right? The relationships that I make in an ER-Diagram is only to indicate where it should be foreign keys when making the actual tables?</p> <p>I do not completely grasp the idea of the relationships, even though I have read many tutorials about this.</p> <p>Thanks in advance.</p>
4,751,987
8
0
null
2011-01-20 19:59:18.14 UTC
9
2014-11-20 08:55:48.64 UTC
null
null
null
null
454,049
null
1
22
database|database-design
72,594
<p>In a sense, all the relationships we talk about are not <em>known</em> to the database, they are constructs we have invented to better understand how to design the tables.</p> <p>The big difference in terms of table structure between one-to-one and one-to-many is that in one-to-one it is possible (but not necessary) to have a bidirectional relationship, meaning table A can have a foreign key into table B, and table B can have a foreign key into the associated record in table A. This is not possible with a one-to-many relationship.</p> <p>One-to-one relationships associate one record in one table with a single record in the other table. One-to-many relationships associate one record in one table with many records in the other table.</p>
14,798,767
Canvas - good rendering practices?
<p>I've been using the Canvas a lot lately for little Java games and i've noticed a lot of strange things can happen. For example, earlier today I created a little game in which the objective is to shoot enemy ships and get points. The game draws tiny 32x32 images on the screen (sometimes slightly bigger) and for a reason I am oblivious to, the game renders oddly.</p> <p>For example, my ship has a health bar above it's head:</p> <p><img src="https://i.stack.imgur.com/DWxHR.png" alt="enter image description here"></p> <p>As you can see by the image, the textures are really small. Despite this, the game lags and sometimes things render incorrectly like this for example:</p> <p><img src="https://i.stack.imgur.com/aeW4M.png" alt="enter image description here"></p> <p>If you look closely at the top of the health bar, you can see that it's been shifted upwards slightly, it puzzles me how his happens as all of my rendering is buffered.</p> <p>My rendering code:</p> <pre><code>public void render(){ BufferStrategy bs = getBufferStrategy(); if(bs == null){ createBufferStrategy(3); return; } Graphics2D g = (Graphics2D)bs.getDrawGraphics(); toDrawG.setColor(new Color(0x222222)); toDrawG.fillRect(0, 0, WIDTH, HEIGHT); draw((Graphics2D)toDrawG); g.drawImage(toDraw, 0, 0, null); g.dispose(); bs.show(); } public void draw(Graphics2D g){ if(Settings.planets){ renderer.renderPlanets(); } if(level != null){ for(int i = 0 ; i &lt; level.entityList.size(); i++){ if(level.entityList.get(i) != null){ level.entityList.get(i).render(renderer); } } } renderer.overlayString("Space Game", 20, 20, 24, 0xFFFFFF); renderer.overlayString(VERSION, 20, 50, 24, 0xFFFFFF); renderer.overlayString("FPS: " + renderer.fps, 20, 70, 24, 0xFFFFFF); renderer.overlayString("Ships spawned: " + level.shipsSpawned, 20, 90, 24, 0xFFFFFF); renderer.overlayString("Time Survived: " + level.time / 100 + "s", 20, 110, 24, 0xFFFFFF); renderer.overlayString("Physics FPS: " + fps, 20, 130, 24, 0xFFFFFF); if(currentGui != null){ currentGui.render(renderer); }else{ map.drawMinimap(SpaceGame.WIDTH-Minimap.WIDTH-20, SpaceGame.HEIGHT- Minimap.HEIGHT-30); } } </code></pre> <p>And my "Render.class" if you need to study it:</p> <pre><code>package com.maestrum; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.image.BufferedImage; import java.awt.image.ConvolveOp; import java.awt.image.Kernel; import java.util.Random; public class Render implements Runnable{ public Graphics2D g2d; public double xScroll,yScroll; public int frames; public int fps; public long lastTime; public int[] pSequence = new int[40]; public SpaceGame game; public Entity trackedEntity; public Random rand; public Render(SpaceGame game, Graphics2D g){ this.game = game; this.g2d = g; this.rand = new Random(); for(int i = 0 ; i &lt; 40; i++){ pSequence[i] = rand.nextInt(15) + 1; } } @Override public void run() { renderLoop(); } public void renderLoop(){ while(true){ game.render(); if(System.currentTimeMillis() - lastTime &gt;= 1000){ fps = frames; frames = 0; lastTime = System.currentTimeMillis(); } frames++; } } public void renderPlanets(){ overlayImage(ImageHandler.background, 0, 0, 1.5); for(int i = 0 ; i &lt; 20; i++){ overlayImage(ImageHandler.planets[pSequence[i]/4][pSequence[i]%4], i * 400 - xScroll/pSequence[i], i * pSequence[i]*40 - yScroll/pSequence[i]*2, pSequence[i]); } } private class PlanetRenderer { } public void overlayString(String s, double x, double y, int fontSize, int colour){ drawString(s, x+xScroll, y+yScroll, fontSize, colour); } public void overlayRectangle(double x, double y, int xs, int ys, int colour){ drawRectangle(x+xScroll, y+yScroll, xs, ys, colour); } public void overlayBlurred(BufferedImage img, double x, double y, double scale){ drawImageBlurred(img, x+xScroll, y+yScroll, scale); } public void overlayImage(BufferedImage img, double x, double y, double scale){ drawImage(img, x+xScroll, y+yScroll, scale); } public BufferedImage execute(BufferedImage img) { // TODO Auto-generated method stub float weight = 1.0f/2.0f; float [] elements = {weight, weight, weight, weight, weight, weight, weight, weight, weight}; Kernel k = new Kernel (3,3,elements); ConvolveOp op = new ConvolveOp(k); BufferedImage dest = new BufferedImage(img.getWidth(), img.getHeight(), img.getType()); op.filter(img, dest); return dest; } public void drawImageBlurred(BufferedImage img, double x, double y, double scale){ x -= xScroll; y -= yScroll; BufferedImage image = new BufferedImage((int)(img.getWidth()*scale), (int)(img.getHeight()*scale), BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); g.drawImage(img, 0, 0, (int)(img.getWidth()*scale), (int)(img.getHeight()*scale), null); execute(image); g2d.drawImage(image, (int)x, (int)y, null); g.dispose(); } public void drawString(String s, Vector2D pos, int fontSize, int colour){ drawString(s, pos.x, pos.y, fontSize, colour); } public void drawString(String s, double x, double y, int fontSize, int colour){ if(s == null){ return; } x -= xScroll; y -= yScroll; BufferedImage img = new BufferedImage(s.length()*fontSize+1, fontSize*2, BufferedImage.TYPE_INT_ARGB); Graphics g = img.getGraphics(); g.setColor(new Color(colour)); g.setFont(new Font("Consolas", Font.BOLD, fontSize)); g.drawString(s, 0, img.getHeight()/2); g2d.drawImage(img, (int)x, (int)y, null); g.dispose(); } public void drawImage(BufferedImage img, Vector2D pos, double scale){ drawImage(img, pos.x, pos.y, scale); } public void drawLine(Vector2D v1, Vector2D v2, int colour, int width){ drawLine(v1.x, v1.y, v2.x, v2.y, colour, width); } public void drawLine(double x1, double y1, double x2, double y2, int colour, int lWidth){ x1 -= xScroll; y1 -= yScroll; x2 -= xScroll; y2 -= yScroll; g2d.setColor(new Color(colour)); g2d.setStroke(new BasicStroke(lWidth)); g2d.drawLine((int)x1, (int)y1, (int)x2, (int)y2); } public void drawImage(BufferedImage img, double x, double y, double scale){ x -= xScroll; y -= yScroll; BufferedImage image = new BufferedImage((int)(img.getWidth()*scale), (int)(img.getHeight()*scale), BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); g.drawImage(img, 0, 0, (int)(img.getWidth()*scale), (int)(img.getHeight()*scale), null); g2d.drawImage(image, (int)x, (int)y, null); g.dispose(); } public void drawRectangle(Vector2D pos, int xs, int ys, int colour){ drawRectangle(pos.x, pos.y, xs, ys, colour); } public void drawRectangle(double x, double y, int xs, int ys, int colour){ if(xs &lt;= 0){ return; } x -= xScroll; y -= yScroll; BufferedImage image = new BufferedImage(xs, ys, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) image.getGraphics(); g.setColor(new Color(colour)); g.fillRect(0, 0, xs, ys); g2d.drawImage(image, (int)x, (int)y, null); g.dispose(); } public void drawImageRotated(BufferedImage img, Vector2D pos, double scale, double angle) { drawImageRotated(img, pos.x, pos.y, scale, angle); } public void drawImageRotated(BufferedImage img, double x, double y, double scale, double angle) { x -= xScroll; y -= yScroll; BufferedImage image = new BufferedImage((int)(img.getWidth() * 1.5D), (int)(img.getHeight() * 1.5D), 2); Graphics2D g = (Graphics2D)image.getGraphics(); g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g.rotate(Math.toRadians(angle), image.getWidth() / 2, image.getHeight() / 2); g.drawImage(img, image.getWidth() / 2 - img.getWidth() / 2, image.getHeight() / 2 - image.getHeight() / 2, null); g2d.drawImage(image, (int)(x-image.getWidth()*scale/2), (int)(y-image.getHeight()*scale/2), (int)(image.getWidth()*scale), (int)(image.getHeight()*scale), null); g.dispose(); } </code></pre> <p>}</p> <p>As you can see in the rendering class, the render process is done as many times a second as possible. This is to give the game the highest possible FPS. If you missed the point of what I'm asking; What good practices should I take into account when rendering stuff using Java? And, what could possibly be causing the space ships health bar to render like so?</p> <p>NOTE: take a look at this video, I ran that program and got 80FPS with 50000 particles, however with my rendering code (which is obviously of a much lower quality) I can render only a mere 100 or so particles, before things start messing up.</p> <p><a href="http://www.youtube.com/watch?v=6M3Ze4Eu87Y" rel="noreferrer">http://www.youtube.com/watch?v=6M3Ze4Eu87Y</a></p> <p>This is my tick() function, it gets called every game tick (10ms)</p> <pre><code>public void tick(){ if(System.currentTimeMillis() - lastTime &gt;= 1000){ fps = frames; frames = 0; lastTime = System.currentTimeMillis(); } frames++; if(renderer.trackedEntity != null){ renderer.xScroll = renderer.trackedEntity.pos.x-SpaceGame.WIDTH/2; renderer.yScroll = renderer.trackedEntity.pos.y-SpaceGame.HEIGHT/2; } if(level != null &amp;&amp; !paused){ level.tick(); } if(currentGui != null &amp;&amp; currentGui.pausesGame()){ paused = true; }else{ paused = false; } } </code></pre>
14,956,723
2
6
null
2013-02-10 14:31:17.763 UTC
8
2013-02-19 23:20:23.533 UTC
2013-02-19 21:14:18.01 UTC
null
577,306
null
1,276,856
null
1
18
java|rendering
6,394
<p>i think the answer by @mantrid should fix your problem. as far as performance goes ... there are some obvious "sins" in your code: </p> <p><strong>Don't draw an image into an image to draw an image</strong></p> <pre><code>public void drawImage(BufferedImage img, double x, double y, double scale){ x -= xScroll; y -= yScroll; BufferedImage image = new BufferedImage((int)(img.getWidth()*scale), (int)(img.getHeight()*scale), BufferedImage.TYPE_INT_ARGB); Graphics g = image.getGraphics(); g.drawImage(img, 0, 0, (int)(img.getWidth()*scale), (int)(img.getHeight()*scale), null); g2d.drawImage(image, (int)x, (int)y, null); g.dispose(); } </code></pre> <p>I don't see the point of this. Why not just do this: </p> <pre><code>public void drawImage(BufferedImage img, double x, double y, double scale){ g2d.drawImage(img, (int)(x-xScroll), (int)(y-yScroll), (int)(img.getWidth()*scale), (int)(img.getHeight()*scale), null); } </code></pre> <p><strong>AAAAAAAAAAAAA</strong></p> <p>The next one actually burnt my eyes </p> <pre><code>public void drawRectangle(double x, double y, int xs, int ys, int colour){ if(xs &lt;= 0){ return; } x -= xScroll; y -= yScroll; BufferedImage image = new BufferedImage(xs, ys, BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D) image.getGraphics(); g.setColor(new Color(colour)); g.fillRect(0, 0, xs, ys); g2d.drawImage(image, (int)x, (int)y, null); g.dispose(); } </code></pre> <p>Why? This is so much simpler and quicker: </p> <pre><code>public void drawRectangle(double x, double y, int xs, int ys, int colour){ if(xs &lt;= 0) return; g2d.setColor(new Color(colour)); g2d.fillRect((int)(x-xScroll), (int)(y-yScroll), xs, ys); } </code></pre> <p>The same goes for the <code>drawImageRotated</code> and <code>drawString</code>. Just draw to the g2d buffer directly, what are you afraid of? </p> <p><strong>drawImageBlurred</strong></p> <p>First of all... you're doing it again! Second: You seem to be applying a convolve operation to an image on each frame, why not just do that operation once (e.g. at the start of the app, or even better yet, in an image editing program). </p> <p>I don't mean this in a bad way at all, but you are clearly not very experienced with programming in general. I think you could take a look at processing (<a href="http://processing.org">http://processing.org</a>). I'm sort of biased here because i'm using it myself almost everyday. It is a great learning and prototyping environment written in java that should allow you to stop thinking about implementation details (like flipping buffers) and focus on what you really care for (make a game!). </p> <p>Alright, hope what i said makes sense. Good luck with your coding! :) </p>
14,670,985
Adding a circle mask layer on an UIImageView
<p>I'm building a Photo filter app (like Instagram, Camera+ and many more..), may main screen is a <code>UIImageView</code> that presenting the image to the user, and a bottom bar with some filters and other options.<br> One of the option is <strong>blur</strong>, where the user can use his fingers to pinch or move a circle that represent the non-blur part (radius and position) - all the pixels outside of this circle will be blurred. </p> <p>When the user touch the screen I want to add a semi transparent layer above my image that represent the blurred part, with a fully transparent circle that represent the non-blur part. </p> <p>So my question is, how do I add this layer? I suppose I need to use some view above my image view, and to use some mask to get my circle shape? I would really appreciate a good tip here. </p> <p><strong>One More Thing</strong><br> I need the circle will not be cut straight, but have a kind of gradient fade. something like Instagram:<br> <img src="https://i.stack.imgur.com/A8Z6x.jpg" alt="enter image description here"> </p> <p>And what's <strong>very important</strong> is to get this effect with good performance, I'd succeed getting this effect with <code>drawRect:</code> but the performance was very bad on old devices (iphone 4, iPod) </p>
15,429,140
3
3
null
2013-02-03 09:12:39.283 UTC
34
2019-05-19 05:49:19.09 UTC
2013-03-22 12:48:46.313 UTC
null
106,435
null
954,267
null
1
30
ios|objective-c|core-graphics
16,678
<h1>Sharp Mask</h1> <p>Whenever you want to draw a path that consists of a shape (or series of shapes) as a hole in another shape, the key is almost always using an 'even odd winding rule'.</p> <p>From the <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaDrawingGuide/Paths/Paths.html#//apple_ref/doc/uid/TP40003290-CH206-BAJIJJGD" rel="nofollow noreferrer">Winding Rules</a> section of the <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CocoaDrawingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40003290-CH201-SW1" rel="nofollow noreferrer">Cocoa Drawing Guide</a>:</p> <blockquote> <blockquote> <p>A winding rule is simply an algorithm that tracks information about each contiguous region that makes up the path's overall fill area. A ray is drawn from a point inside a given region to any point outside the path bounds. The total number of crossed path lines (including implicit lines) and the direction of each path line are then interpreted using rules which determine if the region should be filled.</p> </blockquote> </blockquote> <p>I appreciate that description isn't really helpful without the rules as context and diagrams to make it easier to understand so I urge you to read the links I've provided above. For the sake of creating our circle mask layer the following diagrams depict what an even odd winding rule allows us to accomplish:</p> <h3>Non Zero Winding Rule</h3> <p><img src="https://i.stack.imgur.com/UNtiW.png" alt="Non Zero Winding Rule"></p> <h3>Even Odd Winding Rule</h3> <p><img src="https://i.stack.imgur.com/3FcVp.png" alt="Even Odd Winding Rule"></p> <p>Now it's simply a matter of creating the translucent mask using a <a href="https://developer.apple.com/documentation/quartzcore/cashapelayer" rel="nofollow noreferrer">CAShapeLayer</a> that can be repositioned and expanded and contracted through user interaction.</p> <h2>Code</h2> <pre><code>#import &lt;QuartzCore/QuartzCore.h&gt; @interface ViewController () @property (strong, nonatomic) IBOutlet UIImageView *imageView; @property (strong) CAShapeLayer *blurFilterMask; @property (assign) CGPoint blurFilterOrigin; @property (assign) CGFloat blurFilterDiameter; @end @implementation ViewController // begin the blur masking operation. - (void)beginBlurMasking { self.blurFilterOrigin = self.imageView.center; self.blurFilterDiameter = MIN(CGRectGetWidth(self.imageView.bounds), CGRectGetHeight(self.imageView.bounds)); CAShapeLayer *blurFilterMask = [CAShapeLayer layer]; // Disable implicit animations for the blur filter mask's path property. blurFilterMask.actions = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNull null], @"path", nil]; blurFilterMask.fillColor = [UIColor blackColor].CGColor; blurFilterMask.fillRule = kCAFillRuleEvenOdd; blurFilterMask.frame = self.imageView.bounds; blurFilterMask.opacity = 0.5f; self.blurFilterMask = blurFilterMask; [self refreshBlurMask]; [self.imageView.layer addSublayer:blurFilterMask]; UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [self.imageView addGestureRecognizer:tapGesture]; UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)]; [self.imageView addGestureRecognizer:pinchGesture]; } // Move the origin of the blur mask to the location of the tap. - (void)handleTap:(UITapGestureRecognizer *)sender { self.blurFilterOrigin = [sender locationInView:self.imageView]; [self refreshBlurMask]; } // Expand and contract the clear region of the blur mask. - (void)handlePinch:(UIPinchGestureRecognizer *)sender { // Use some combination of sender.scale and sender.velocity to determine the rate at which you want the circle to expand/contract. self.blurFilterDiameter += sender.velocity; [self refreshBlurMask]; } // Update the blur mask within the UI. - (void)refreshBlurMask { CGFloat blurFilterRadius = self.blurFilterDiameter * 0.5f; CGMutablePathRef blurRegionPath = CGPathCreateMutable(); CGPathAddRect(blurRegionPath, NULL, self.imageView.bounds); CGPathAddEllipseInRect(blurRegionPath, NULL, CGRectMake(self.blurFilterOrigin.x - blurFilterRadius, self.blurFilterOrigin.y - blurFilterRadius, self.blurFilterDiameter, self.blurFilterDiameter)); self.blurFilterMask.path = blurRegionPath; CGPathRelease(blurRegionPath); } ... </code></pre> <p><img src="https://i.stack.imgur.com/owwr1.png" alt="Code Conventions Diagram"></p> <p>(This diagram may help understand the naming conventions in the code)</p> <hr> <h1>Gradient Mask</h1> <p>The <a href="https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_shadings/dq_shadings.html#//apple_ref/doc/uid/TP30001066-CH207-TPXREF101" rel="nofollow noreferrer">Gradients section</a> of Apple's <a href="https://developer.apple.com/library/archive/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/Introduction/Introduction.html#//apple_ref/doc/uid/TP40007533-SW1" rel="nofollow noreferrer">Quartz 2D Programming Guide</a> details how to draw radial gradients which we can use to create a mask with a feathered edge. This involves drawing a <a href="https://developer.apple.com/documentation/quartzcore/calayer" rel="nofollow noreferrer">CALayer</a>s content directly by subclassing it or implementing its drawing delegate. Here we subclass it to encapsulate the data related to it i.e. origin and diameter.</p> <h2>Code</h2> <blockquote> <p>BlurFilterMask.h</p> </blockquote> <pre><code>#import &lt;QuartzCore/QuartzCore.h&gt; @interface BlurFilterMask : CALayer @property (assign) CGPoint origin; // The centre of the blur filter mask. @property (assign) CGFloat diameter; // the diameter of the clear region of the blur filter mask. @end </code></pre> <blockquote> <p>BlurFilterMask.m</p> </blockquote> <pre><code>#import "BlurFilterMask.h" // The width in points the gradated region of the blur filter mask will span over. CGFloat const GRADIENT_WIDTH = 50.0f; @implementation BlurFilterMask - (void)drawInContext:(CGContextRef)context { CGFloat clearRegionRadius = self.diameter * 0.5f; CGFloat blurRegionRadius = clearRegionRadius + GRADIENT_WIDTH; CGColorSpaceRef baseColorSpace = CGColorSpaceCreateDeviceRGB(); CGFloat colours[8] = { 0.0f, 0.0f, 0.0f, 0.0f, // Clear region colour. 0.0f, 0.0f, 0.0f, 0.5f }; // Blur region colour. CGFloat colourLocations[2] = { 0.0f, 0.4f }; CGGradientRef gradient = CGGradientCreateWithColorComponents (baseColorSpace, colours, colourLocations, 2); CGContextDrawRadialGradient(context, gradient, self.origin, clearRegionRadius, self.origin, blurRegionRadius, kCGGradientDrawsAfterEndLocation); CGColorSpaceRelease(baseColorSpace); CGGradientRelease(gradient); } @end </code></pre> <blockquote> <p>ViewController.m (Wherever you are implementing the blur filer masking functionality)</p> </blockquote> <pre><code>#import "ViewController.h" #import "BlurFilterMask.h" #import &lt;QuartzCore/QuartzCore.h&gt; @interface ViewController () @property (strong, nonatomic) IBOutlet UIImageView *imageView; @property (strong) BlurFilterMask *blurFilterMask; @end @implementation ViewController // Begin the blur filter masking operation. - (void)beginBlurMasking { BlurFilterMask *blurFilterMask = [BlurFilterMask layer]; blurFilterMask.diameter = MIN(CGRectGetWidth(self.imageView.bounds), CGRectGetHeight(self.imageView.bounds)); blurFilterMask.frame = self.imageView.bounds; blurFilterMask.origin = self.imageView.center; blurFilterMask.shouldRasterize = YES; [self.imageView.layer addSublayer:blurFilterMask]; [blurFilterMask setNeedsDisplay]; self.blurFilterMask = blurFilterMask; UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)]; [self.imageView addGestureRecognizer:tapGesture]; UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)]; [self.imageView addGestureRecognizer:pinchGesture]; } // Move the origin of the blur mask to the location of the tap. - (void)handleTap:(UITapGestureRecognizer *)sender { self.blurFilterMask.origin = [sender locationInView:self.imageView]; [self.blurFilterMask setNeedsDisplay]; } // Expand and contract the clear region of the blur mask. - (void)handlePinch:(UIPinchGestureRecognizer *)sender { // Use some combination of sender.scale and sender.velocity to determine the rate at which you want the mask to expand/contract. self.blurFilterMask.diameter += sender.velocity; [self.blurFilterMask setNeedsDisplay]; } ... </code></pre> <p><img src="https://i.stack.imgur.com/jyBYR.png" alt="Code Conventions Diagram"></p> <p>(This diagram may help understand the naming conventions in the code)</p> <hr> <h3>Note</h3> <p>Ensure the <code>multipleTouchEnabled</code> property of the <code>UIImageView</code> hosting your image is set to <code>YES</code>/<code>true</code>:</p> <p><img src="https://i.stack.imgur.com/F10lH.png" alt="multipleTouchEnabled"></p> <hr> <h3>Note</h3> <p>For sake of clarity in answering the OPs question this answer continues to use the naming conventions originally used. This may be slightly misleading to others. 'Mask' is this context does not refer to an image mask but mask in a more general sense. This answer doesn't use any image masking operations.</p>
14,794,885
Can't access Eclipse marketplace
<p>I can't seem to access the Eclipse marketplace. I'm using Juno 4.2. I tried deleting eclipse and removing all plugins, deleting my .metadata, and deleting the eclipse app data.</p> <p>I've tried switching my default browser from firefox to chrome, I've tried turning on and completely off Windows firewall. I'm at home.</p> <p>I was able to get eclipse updates, though. When I try to report a bug for the marketplace I get a different error.</p> <p>When I try to connect, I receive quite a few errors. </p> <p>First one is a warning:</p> <pre><code>Connection to http://marketplace.eclipse.org/catalogs/api/p failed on Connection reset. Retry attempt 0 started </code></pre> <p>Second is an error:</p> <pre><code>Cannot install remote marketplace locations.: </code></pre> <p>Third is another error:</p> <pre><code>Unexpected exception </code></pre> <p>Here are the stack traces in order received:</p> <pre><code>java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:189) at java.net.SocketInputStream.read(SocketInputStream.java:121) at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) at java.io.BufferedInputStream.read(BufferedInputStream.java:254) at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:78) at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:106) at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1116) at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.readLine(MultiThreadedHttpConnectionManager.java:1413) at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1973) at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098) at org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer$GzipGetMethod.execute(HttpClientRetrieveFileTransfer.java:120) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:346) at org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer.performConnect(HttpClientRetrieveFileTransfer.java:1129) at org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer.openStreams(HttpClientRetrieveFileTransfer.java:699) at org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer.sendRetrieveRequest(AbstractRetrieveFileTransfer.java:879) at org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer.sendRetrieveRequest(AbstractRetrieveFileTransfer.java:570) at org.eclipse.ecf.provider.filetransfer.retrieve.MultiProtocolRetrieveAdapter.sendRetrieveRequest(MultiProtocolRetrieveAdapter.java:106) at org.eclipse.equinox.internal.p2.transport.ecf.FileReader.sendRetrieveRequest(FileReader.java:422) at org.eclipse.equinox.internal.p2.transport.ecf.FileReader.read(FileReader.java:273) at org.eclipse.equinox.internal.p2.transport.ecf.RepositoryTransport.stream(RepositoryTransport.java:172) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.eclipse.epp.internal.mpc.core.util.AbstractP2TransportFactory.invokeStream(AbstractP2TransportFactory.java:35) at org.eclipse.epp.internal.mpc.core.util.TransportFactory$1.stream(TransportFactory.java:69) at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:141) at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:80) at org.eclipse.epp.internal.mpc.core.service.DefaultCatalogService.listCatalogs(DefaultCatalogService.java:36) at org.eclipse.epp.internal.mpc.ui.commands.MarketplaceWizardCommand$3.run(MarketplaceWizardCommand.java:200) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) java.lang.reflect.InvocationTargetException at org.eclipse.epp.internal.mpc.ui.commands.MarketplaceWizardCommand$3.run(MarketplaceWizardCommand.java:203) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) Caused by: org.eclipse.core.runtime.CoreException: Unable to read repository at http://marketplace.eclipse.org/catalogs/api/p. at org.eclipse.equinox.internal.p2.transport.ecf.RepositoryTransport.stream(RepositoryTransport.java:181) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.eclipse.epp.internal.mpc.core.util.AbstractP2TransportFactory.invokeStream(AbstractP2TransportFactory.java:35) at org.eclipse.epp.internal.mpc.core.util.TransportFactory$1.stream(TransportFactory.java:69) at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:141) at org.eclipse.epp.internal.mpc.core.service.RemoteMarketplaceService.processRequest(RemoteMarketplaceService.java:80) at org.eclipse.epp.internal.mpc.core.service.DefaultCatalogService.listCatalogs(DefaultCatalogService.java:36) at org.eclipse.epp.internal.mpc.ui.commands.MarketplaceWizardCommand$3.run(MarketplaceWizardCommand.java:200) ... 1 more Caused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:189) at java.net.SocketInputStream.read(SocketInputStream.java:121) at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) at java.io.BufferedInputStream.read(BufferedInputStream.java:254) at org.apache.commons.httpclient.HttpParser.readRawLine(HttpParser.java:78) at org.apache.commons.httpclient.HttpParser.readLine(HttpParser.java:106) at org.apache.commons.httpclient.HttpConnection.readLine(HttpConnection.java:1116) at org.apache.commons.httpclient.MultiThreadedHttpConnectionManager$HttpConnectionAdapter.readLine(MultiThreadedHttpConnectionManager.java:1413) at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1973) at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735) at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098) at org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer$GzipGetMethod.execute(HttpClientRetrieveFileTransfer.java:120) at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:398) at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397) at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:346) at org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer.performConnect(HttpClientRetrieveFileTransfer.java:1129) at org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer.openStreams(HttpClientRetrieveFileTransfer.java:699) at org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer.sendRetrieveRequest(AbstractRetrieveFileTransfer.java:879) at org.eclipse.ecf.provider.filetransfer.retrieve.AbstractRetrieveFileTransfer.sendRetrieveRequest(AbstractRetrieveFileTransfer.java:570) at org.eclipse.ecf.provider.filetransfer.retrieve.MultiProtocolRetrieveAdapter.sendRetrieveRequest(MultiProtocolRetrieveAdapter.java:106) at org.eclipse.equinox.internal.p2.transport.ecf.FileReader.sendRetrieveRequest(FileReader.java:422) at org.eclipse.equinox.internal.p2.transport.ecf.FileReader.read(FileReader.java:273) at org.eclipse.equinox.internal.p2.transport.ecf.RepositoryTransport.stream(RepositoryTransport.java:172) ... 11 more java.lang.reflect.InvocationTargetException at org.eclipse.jface.operation.ModalContext.run(ModalContext.java:421) at org.eclipse.jface.wizard.WizardDialog.run(WizardDialog.java:1028) at org.eclipse.equinox.internal.p2.ui.discovery.wizards.CatalogViewer.updateCatalog(CatalogViewer.java:563) at org.eclipse.epp.internal.mpc.ui.wizards.MarketplaceViewer.updateCatalog(MarketplaceViewer.java:453) at org.eclipse.epp.internal.mpc.ui.wizards.MarketplacePage$6.run(MarketplacePage.java:332) at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35) at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135) at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4144) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3761) at org.eclipse.jface.window.Window.runEventLoop(Window.java:825) at org.eclipse.jface.window.Window.open(Window.java:801) at org.eclipse.epp.internal.mpc.ui.commands.MarketplaceWizardCommand.execute(MarketplaceWizardCommand.java:171) at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:290) at org.eclipse.ui.internal.handlers.E4HandlerProxy.execute(E4HandlerProxy.java:76) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.eclipse.e4.core.internal.di.MethodRequestor.execute(MethodRequestor.java:56) at org.eclipse.e4.core.internal.di.InjectorImpl.invokeUsingClass(InjectorImpl.java:229) at org.eclipse.e4.core.internal.di.InjectorImpl.invoke(InjectorImpl.java:210) at org.eclipse.e4.core.contexts.ContextInjectionFactory.invoke(ContextInjectionFactory.java:131) at org.eclipse.e4.core.commands.internal.HandlerServiceImpl.executeHandler(HandlerServiceImpl.java:171) at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.executeItem(HandledContributionItem.java:814) at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.handleWidgetSelection(HandledContributionItem.java:707) at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem.access$7(HandledContributionItem.java:691) at org.eclipse.e4.ui.workbench.renderers.swt.HandledContributionItem$4.handleEvent(HandledContributionItem.java:630) at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84) at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053) at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4169) at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3758) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1029) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:923) at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:86) at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:588) at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332) at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:543) at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149) at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124) at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110) at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353) at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:601) at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629) at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584) at org.eclipse.equinox.launcher.Main.run(Main.java:1438) Caused by: java.lang.IllegalStateException at org.eclipse.equinox.internal.p2.discovery.Catalog.performDiscovery(Catalog.java:64) at org.eclipse.epp.internal.mpc.ui.catalog.MarketplaceCatalog.performDiscovery(MarketplaceCatalog.java:255) at org.eclipse.equinox.internal.p2.ui.discovery.wizards.CatalogViewer$6.run(CatalogViewer.java:569) at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:121) </code></pre>
14,795,075
11
0
null
2013-02-10 05:03:35.877 UTC
10
2019-09-03 10:57:28.463 UTC
null
null
null
null
1,313,268
null
1
33
eclipse|eclipse-marketplace
174,070
<p>Considering this as a <em>general</em> programming problem, some possible causes are:</p> <ul> <li><p>The service could be temporarily broken</p></li> <li><p>You could have a problem with a firewall. These could be local or they could be implemented by your ISPs.</p></li> <li><p>Your proxy HTTP settings (if you need one) could be incorrect. <a href="https://stackoverflow.com/a/25337453/139985">This Answer</a> explains how to adjust the Eclipse-internal proxy settings ... if that is where the problem lies.</p></li> <li><p>It is possible that your access may be blocked by over-active antivirus software.</p></li> <li><p>The service could have blacklisted some net range and your hosts IP address is "collateral damage".</p></li> </ul> <p>Try connecting to that URL with a web browser to try to see if it is just Eclipse that is affected ... or a broader problem.</p> <hr> <p>Considering this in the context of the Eclipse Marketplace service, first address any local proxy / firewall / AV issues, if they apply. If that doesn't help, the best thing that you can do is to be patient.</p> <ul> <li><p>It has been observed that the Eclipse Marketplace service <strong>does</strong> sometimes go down. It doesn't happen often, and when it does happen the problem does get fixed relatively quickly. (Hours, not days ...)</p></li> <li><p>I can't find a "service status" page or feed or similar for the Eclipse services. (If you know of one, please add it as a comment below.) </p></li> <li><p>There may be an "outage" notice on the Eclipse front page. Check for that.</p></li> <li><p>Try to connect to the service URL (refer to the exception message!) using a web browser and/or from other locations. If you succeed, the real problem may be a networking issue at your end.</p></li> <li><p>If you feel the need to complain about Eclipse's services, <em>please don't do it here!!</em> (It is off topic.)</p></li> </ul>
14,648,504
Show active plugins in Sublime Text and disable them
<p>I just installed sublime text 2 and was overwhelmed by the php plugins that I installed ALL of them. Now auto-complete is crazy, a million unnecessary suggestions and I dont remember which plugin does what or which ones I installed. Is there a way to see all active plugins for a particular file so I can disable some?</p>
14,648,907
3
2
null
2013-02-01 14:29:06.207 UTC
9
2022-02-08 17:12:11.077 UTC
2022-02-08 17:12:11.077 UTC
null
4,561,887
null
1,106,420
null
1
41
plugins|sublimetext2|sublimetext
25,284
<p>I'm not sure about the active plugin on a file part, but you can quickly go in and remove plugins that are installed by opening the Command Pallete (Cmd-Shift-P on Mac) and typing remove if you have Package Control installed.</p> <p>You will see <strong>Package Control: Remove Package**</strong></p> <p><strong>Once the list of installed plugins shows up you can click these and remove them and then test out your code.</strong> </p> <p>You can do the reverse and quickly re-install the packages if something you needed was missing.</p> <p>You probably already knew this so I am not sure that this will be helpful or not.</p> <p><em>BTW: Sublime Text 3 Beta just came out and is available to licensed users. I have not done much with it yet, but it loads almost instantly.</em></p>
14,756,222
Multiple aggregate functions in HAVING clause
<p>Due to the nature of my query i have records with counts of 3 that would also fit the criteria of having count of 2 and so on. I was wondering is it possible to query 'having count more than x and less than 7' ? How could I write this. Here is my current code.</p> <pre><code>GROUP BY meetingID HAVING COUNT( caseID )&lt;4 </code></pre> <p>I'd like something like</p> <pre><code>GROUP BY meetingID HAVING COUNT( caseID )&lt;4 AND &gt;2 </code></pre> <p>That way it would only count for exactly 3</p>
14,756,255
6
0
null
2013-02-07 16:37:53.93 UTC
4
2017-12-07 00:37:48.107 UTC
2013-02-07 16:39:33.77 UTC
null
42,346
null
1,842,443
null
1
48
mysql|sql|count
157,221
<pre><code>GROUP BY meetingID HAVING COUNT(caseID) &lt; 4 AND COUNT(caseID) &gt; 2 </code></pre>
14,584,393
Why getting error mongod dead but subsys locked and Insufficient free space for journal files on Linux?
<p>I have installed <strong>mongo-10gen mongo-10gen-server</strong> on Linux CentOS server.</p> <p>I followed the steps from <a href="http://docs.mongodb.org/manual/tutorial/install-mongodb-on-redhat-centos-or-fedora-linux/"><strong>Link</strong></a>.</p> <p>I have configured <strong>/etc/mongod.conf</strong> as - </p> <pre><code>logpath=/var/log/mongo/mongod.log port=27017 dbpath=/var/lib/mongo </code></pre> <p>I have set port 27017 for mongo in <strong>iptables</strong>. To start mongo I used commands - </p> <pre><code>service mongod start and mongo </code></pre> <p>It get started well, but after few days I am getting the error - </p> <pre><code>Tue Jan 29 08:41:54 [initandlisten] ERROR: Insufficient free space for journal files Tue Jan 29 08:41:54 [initandlisten] Please make at least 3379MB available in /var/lib/mongo/journal or use --smallfiles Tue Jan 29 08:41:54 [initandlisten] Tue Jan 29 08:41:54 [initandlisten] exception in initAndListen: 15926 Insufficient free space for journals, terminating Tue Jan 29 08:41:54 dbexit: Tue Jan 29 08:41:54 [initandlisten] shutdown: going to close listening sockets... Tue Jan 29 08:41:54 [initandlisten] shutdown: going to flush diaglog... Tue Jan 29 08:41:54 [initandlisten] shutdown: going to close sockets... Tue Jan 29 08:41:54 [initandlisten] shutdown: waiting for fs preallocator... Tue Jan 29 08:41:54 [initandlisten] shutdown: lock for final commit... Tue Jan 29 08:41:54 [initandlisten] shutdown: final commit... Tue Jan 29 08:41:54 [initandlisten] shutdown: closing all files... Tue Jan 29 08:41:54 [initandlisten] closeAllFiles() finished Tue Jan 29 08:41:54 [initandlisten] journalCleanup... Tue Jan 29 08:41:54 [initandlisten] removeJournalFiles Tue Jan 29 08:41:54 [initandlisten] shutdown: removing fs lock... Tue Jan 29 08:41:54 dbexit: really exiting now </code></pre> <p>When I execute the command - </p> <pre><code>service mongod status </code></pre> <p>It gives Error - </p> <pre><code>mongod dead but subsys locked </code></pre> <p>Please help me to solve the problem of <strong><em>mongod dead but subsys locked</em></strong> and <strong><em>Insufficient free space for journals, terminating</em></strong></p>
17,630,510
7
2
null
2013-01-29 13:44:15.67 UTC
28
2019-08-05 10:32:19.58 UTC
null
null
null
null
1,147,080
null
1
68
linux|mongodb|journal
61,857
<p>You can add following to the config file provided when running <code>mongod --config mongod.conf</code></p> <p>For MongoDB <strong>3.x</strong> (latest version)</p> <pre><code>storage: mmapv1: smallFiles: true </code></pre> <p>For version <strong>2.6+</strong></p> <pre><code>storage: smallFiles: true </code></pre> <p>For version <strong>2.4</strong> and less</p> <pre><code>smallfiles = true </code></pre> <p>Then just execute mongod to accept your config file (here it assumes that location of the config is <em>/etc/mongodb.conf</em>):</p> <pre><code>mongod -f /etc/mongodb.conf </code></pre> <p><a href="http://docs.mongodb.org/manual/reference/configuration-options/#storage.mmapv1.smallFiles">Documentation</a> for <strong>smallfiles</strong> parameter:</p> <pre><code>Set to true to modify MongoDB to use a smaller default data file size. Specifically, smallfiles reduces the initial size for data files and limits them to 512 megabytes. The smallfiles setting also reduces the size of each journal files from 1 gigabyte to 128 megabytes. </code></pre>
2,759,059
Where I can download the REAL Full .Net Framework 4 Standalone Installer?
<p>I found that links:</p> <ol> <li><a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=9cfb2d51-5ff4-4491-b0e5-b386f32c0992&amp;displaylang=en" rel="noreferrer">Microsoft .NET Framework 4 (Web Installer)</a></li> <li><a href="http://www.microsoft.com/downloads/details.aspx?displaylang=en&amp;FamilyID=0a391abd-25c1-4fc0-919f-b21f31ab88b7" rel="noreferrer">Microsoft .NET Framework 4 (Standalone Installer)</a></li> <li><a href="http://www.microsoft.com/downloads/details.aspx?familyid=E5AD0459-CBCC-4B4F-97B6-FB17111CF544&amp;displaylang=en" rel="noreferrer">Microsoft .NET Framework 4 Client Profile (Standalone Installer)</a></li> </ol> <p>Note that (2) the size is 48.0 MB and the (3) the size is 41.0 MB. It's not the REAL .Net 4 Full Standalone. :(</p> <p>I want that installer in a usb pen drive because my app need of features of <strong>.Net 4 Full Framework (like MSBuild)</strong> and I will install in a enviroment without Internet access.</p> <p>PS: I tested the (2) and really is the Client Profile with another name... :(</p>
2,759,122
2
4
null
2010-05-03 15:16:22.597 UTC
3
2013-02-24 12:52:34.693 UTC
2010-05-03 15:42:31.46 UTC
null
48,729
null
48,729
null
1
12
.net-4.0
47,056
<p>Actually, you already found the full .NET 4 SDK. Microsoft put in a lot of effort to decrease the size.</p> <blockquote> <p>The Microsoft .NET Framework 4 redistributable package installs the .NET Framework runtime and associated files that are required to run and develop applications to target the .NET Framework 4.</p> </blockquote> <p>Have a look at this <a href="http://www.hanselman.com/blog/TowardsASmallerNET4DetailsOnTheClientProfileAndDownloadingNET.aspx" rel="nofollow noreferrer">hanselpost</a>.</p> <p><img src="https://www.hanselman.com/blog/content/binary/WindowsLiveWriter/5adeaaabcd39_D919/image_2_8b229535-3246-46df-be9a-4dfe47e035f2.png" alt="alt text"></p>
27,122,564
Which version of linux has support for Dolby Advanced Audio v2?
<p>I am using LENEVO G500 Laptop and my sound card has support for Dolby Advanced Audio v2 that works nicely in Windows OS (i.e. Windows 7, 8 and 8.1). However I have failed to enable Dolby sound effect in my Linux OS (have tried it with Linux Mint 17, Fedora 20).</p> <p>Does anyone have an idea which linux version has support for this feature or how I can enable in a linux OS.</p> <p>I would appreciate if you could direct me to the right direction.</p> <p>Thanks.</p>
30,428,589
4
0
null
2014-11-25 09:08:38.53 UTC
8
2021-09-01 04:03:16.443 UTC
null
null
null
null
3,989,365
null
1
7
linux|audio|dolby
28,626
<p>After a bit of research I found this explanation that seems to have satisfied my query. It generally says ...</p> <blockquote> <p>There isn't going to be an easy fix for this, unless Dolby releases a Linux driver or publishes more information on what exactly their software is doing (which is unlikely).</p> </blockquote> <p><a href="https://github.com/leoluk/thinkpad-stuff/wiki/Haswell-ThinkPad-problems#linux-low-audio-quality" rel="nofollow">Haswell-ThinkPad-problems, linux-low-audio-quality</a></p>
38,764,176
Difference between chr(13) and chr(10)
<p>What is the difference between <code>chr(13)</code> and <code>chr(10)</code> in Crystal Reports?</p> <p>I know <code>chr(13)</code> is used as a line break. But one of our reports uses this line:</p> <pre><code>{Address1} + chr(13) + chr(10) + {Address2} </code></pre>
38,792,168
1
0
null
2016-08-04 09:58:16.27 UTC
6
2020-12-01 11:17:28.887 UTC
2018-06-07 21:20:44.837 UTC
null
1,464,444
null
5,002,839
null
1
24
crystal-reports
149,967
<p><code>Chr(10)</code> is the Line Feed character and <code>Chr(13)</code> is the Carriage Return character. </p> <p>You <em>probably</em> won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.</p> <hr> <p>Historically, Line Feed would move down a line but not return to column 1:</p> <pre><code>This is a test. </code></pre> <p>Similarly Carriage Return would return to column 1 but <em>not</em> move down a line:</p> <pre><code>This is a test. </code></pre> <p>Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.</p>
49,483,713
setExactAndAllowWhileIdle() for alarmmanager is not working properly
<p>I am developing an app which needs to perform particular action on the exact time which user has set. For this i am using <code>setExactAndAllowWhileIdle()</code> method because <a href="https://developer.android.com/training/monitoring-device-state/doze-standby.html" rel="noreferrer">this documentation</a> says that android devices having android 6.0 or above has doze mode concept in which if devices remains idle for some times then it will enter into doze mode and doze mode restricts alarms. If i want to fire my alarm when device is into doze mode then i have <code>setExactAndAllowWhileIdle()</code> method as documentation says. This documentation also contains manual way to enter device into doze mode for testing purpose. so, i am testing using that way but my alarm is not fired when device is into doze mode and when i stops doze mode via terminal command my past alarm will fires instantly. </p> <p>So, my problem is that <code>setExactAndAllowWhileIdle()</code> this method is not working in doze mode but it should have to work as said in documentation. I know limitation of this method that i can only fire one alarm per 9 minutes and i am following this rule. So, i can't understand where is the problem.</p> <p><strong>My Code:</strong></p> <pre><code>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC, d.getTime(), pendingIntent); else if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) alarmManager.setExact(AlarmManager.RTC, d.getTime(), pendingIntent); else alarmManager.set(AlarmManager.RTC, d.getTime(), pendingIntent); </code></pre> <p>Is it a method problem or i am doing it in a wrong way??</p>
49,504,928
3
0
null
2018-03-26 03:55:26.853 UTC
10
2020-02-27 13:19:11.633 UTC
2018-03-26 06:51:39.673 UTC
null
5,594,218
null
7,804,719
null
1
13
java|android|alarmmanager
8,542
<p>I've found the solution for my problem so, i am posting my own answer here which worked for me.</p> <p>Using <strong>setAlarmClock()</strong> method has solved my problem. If you set alarm using setAlarmClock() method then this will not allow the system to go into doze mode before 1 hour of your alarm's time. I had tested this by manually forcing my device to go into doze mode after setting my alarm. Let me explain full scenario.</p> <ol> <li>First of all i set alarm after 5 minutes from current time and then tried to putting my device into doze mode manually by using following command.</li> </ol> <blockquote> <p>adb shell dumpsys deviceidle force-idle</p> </blockquote> <p>It Shows </p> <blockquote> <p>unable to enter into doze mode</p> </blockquote> <ol start="2"> <li>After that i set alarm after 1 hour and 1 minute from current time and then i have tried to put my device into doze mode and it enters into doze mode successfully. Then i have done nothing on my device and it fires alarm exactly on time even it was in a doze mode.</li> </ol> <p>Hence, i conclude that setAlarmClock() method prevents your device from entering to doze mode if there is a small amount of timestamp between current time and your alarm time. Otherwise if your device is already in doze mode then it will gets exit from doze mode before some time of your alarm so, your alarm works fine.</p> <p><strong>Updated code:</strong></p> <pre><code>if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.M) alarmManager.setAlarmClock(new AlarmManager.AlarmClockInfo(d.getTime(),pendingIntent),pendingIntent); else if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.LOLLIPOP) alarmManager.setExact(AlarmManager.RTC, d.getTime(), pendingIntent); else alarmManager.set(AlarmManager.RTC, d.getTime(), pendingIntent); </code></pre>
29,351,665
Command grouping (&&, ||, ...)
<p>We are currently in the /home/student/ directory. We execute the following commands:</p> <pre><code>pwd; (ls) || { cd .. &amp;&amp; ls student/; } &amp;&amp; cd student || cd / &amp;&amp; cd ; </code></pre> <p>The commands that are executed are: pwd, ls, cd student, cd /, cd</p> <p>Here is what I think:</p> <ul> <li><p>pwd is executed, because it's the first command</p></li> <li><p>(ls) is executed in a subshell, because the commands are seperated<br> with ";"</p></li> <li>the code on the right of || isn't executed, since the code on the<br> left of || was executed</li> </ul> <p>So far everything clear, I guess. But I have no idea why other commands are executed? If someone could break it down for me, I'd appreciate it.</p>
29,351,781
2
0
null
2015-03-30 16:41:09.333 UTC
8
2021-10-12 04:17:48.487 UTC
2019-03-06 00:24:09.46 UTC
null
6,862,601
null
4,178,269
null
1
16
bash|syntax|operator-precedence
9,587
<p>Operator precedence for <code>&amp;&amp;</code> and <code>||</code> is strictly left-to-right.</p> <p>Thus:</p> <pre><code>pwd; (ls) || { cd .. &amp;&amp; ls student/; } &amp;&amp; cd student || cd / &amp;&amp; cd ; </code></pre> <p>...is equivalent to...</p> <pre><code>pwd; { { { (ls) || { cd .. &amp;&amp; ls student/; }; } &amp;&amp; cd student; } || cd /; } &amp;&amp; cd ; } </code></pre> <p>...breaking that down graphically:</p> <pre><code>pwd; { # 1 { # 2 { (ls) || # 3 { cd .. &amp;&amp; # 4 ls student/; # 5 }; # 6 } &amp;&amp; cd student; # 7 } || cd /; # 8 } &amp;&amp; cd ; # 9 </code></pre> <ol> <li><code>pwd</code> happens unconditionally</li> <li>(Grouping only)</li> <li><code>ls</code> happens (in a subshell) unconditionally.</li> <li><code>cd ..</code> happens if (3) failed.</li> <li><code>ls student/</code> happens if (3) failed and (4) succeeded</li> <li>(Grouping only)</li> <li><code>cd student</code> happens if either (3) succeeded or both (4) and (5) succeeded.</li> <li><code>cd /</code> happens if either [both (3) and one of (4) or (5) failed], or [(7) failed].</li> <li><code>cd</code> happens if (7) occurred and succeeded, or (8) occurred and succeeded.</li> </ol> <hr> <p>Using explicit grouping operators is wise to avoid confusing yourself. Avoiding writing code as hard to read as this is even wiser.</p>
31,850,379
Angularjs Filter data with dropdown
<p>I am kinda new in angularjs and javascript so please be kind, I have two dropdown items (Ionic Select) both of them holds data from a service. The issue is that I need to filter them in order to work together like: if I choose a company in the first dropdown list, only the reps inside of that company should display in the other dropdown list.</p> <p>I tried using <code>| filter: byID</code> as I followed in Angularjs documentation but I do not think it is the right way of doing this don't know. </p> <p>HTML:</p> <pre><code>&lt;label class="item item-input item-select""&gt; &lt;div class="input-label"&gt; Company: &lt;/div&gt; &lt;select&gt; &lt;option ng-repeat="x in company"&gt;{{x.compname}}&lt;/option&gt; &lt;option selected&gt;Select&lt;/option&gt; &lt;/select&gt; &lt;/label&gt; &lt;div class="list"&gt; &lt;label class="item item-input item-select"&gt; &lt;div class="input-label"&gt; Rep: &lt;/div&gt; &lt;select&gt; &lt;option ng-repeat="x in represent"&gt;{{x.repname}}&lt;/option&gt; &lt;option selected&gt;Select&lt;/option&gt; &lt;/select&gt; &lt;/label&gt; </code></pre> <p>Javascript:</p> <pre><code>/*=========================Get All Companies=========================*/ $http.get("http://localhost:15021/Service1.svc/GetAllComp") .success(function(data) { var obj = data; var SComp = []; angular.forEach(obj, function(index, element) { angular.forEach(index, function(indexN, elementN) { SComp.push({compid: indexN.CompID, compname: indexN.CompName}); $scope.company = SComp; }); }); }) /*=========================Get All Companies=========================*/ /*=========================Get All Reps=========================*/ $http.get("http://localhost:15021/Service1.svc/GetAllReps") .success(function(data) { var obj = data; var SReps = []; angular.forEach(obj, function(index, element) { angular.forEach(index, function(indexN, elementN) { SReps.push({repid: indexN.RepID, repname: indexN.RepName, fkc :indexN.fk_CompID}); $scope.represent = SReps; }); }); }) /*=========================Get All Reps=========================*/ </code></pre>
31,853,843
2
0
null
2015-08-06 08:16:54.11 UTC
3
2019-05-07 10:49:50.427 UTC
2015-08-06 09:39:59.25 UTC
null
978,655
user2413453
null
null
1
7
javascript|angularjs|ionic-framework
39,436
<p>You may solve this problem like my solution process: my solution like your problem. at first show <strong>District</strong> list and show <strong>Thana</strong> list according to <strong>selected District</strong>. using <strong>filter</strong> expression</p> <p><strong>In HTML:</strong></p> <pre><code>&lt;div&gt; &lt;form class="form-horizontal"&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-3"&gt;&lt;label&gt;&lt;i class="fa fa-question-circle fa-fw"&gt;&lt;/i&gt; District List&lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;select class="form-control" ng-model="selectedDist" ng-options="district.name for district in districts"&gt; &lt;option value=""&gt;Select&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;div class="col-md-3"&gt;&lt;label&gt;&lt;i class="fa fa-question-circle fa-fw"&gt;&lt;/i&gt; Thana List&lt;/label&gt;&lt;/div&gt; &lt;div class="col-md-4"&gt; &lt;select class="form-control" ng-model="selectedThana" ng-options="thana.name for thana in thanas | filter: filterExpression"&gt; &lt;option value=""&gt;Select&lt;/option&gt; &lt;/select&gt; &lt;/div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; </code></pre> <p><strong>In controller:</strong></p> <pre><code> $scope.selectedDist={}; $scope.districts = [ {id: 1, name: 'Dhaka'}, {id: 2, name: 'Goplaganj'}, {id: 3, name: 'Faridpur'} ]; $scope.thanas = [ {id: 1, name: 'Mirpur', dId: 1}, {id: 2, name: 'Uttra', dId: 1}, {id: 3, name: 'Shahabag', dId: 1}, {id: 4, name: 'Kotalipara', dId: 2}, {id: 5, name: 'Kashiani', dId: 2}, {id: 6, name: 'Moksedpur', dId: 2}, {id: 7, name: 'Vanga', dId: 3}, {id: 8, name: 'faridpur', dId: 3} ]; $scope.filterExpression = function(thana) { return (thana.dId === $scope.selectedDist.id ); }; </code></pre> <p><strong><em>N.B:</em></strong> Here <strong>filterExpression</strong> is a custom function that return values when selected district id equal dId in thana.</p>
27,092,833
UnicodeEncodeError: 'charmap' codec can't encode characters
<p>I'm trying to scrape a website, but it gives me an error.</p> <p>I'm using the following code:</p> <pre><code>import urllib.request from bs4 import BeautifulSoup get = urllib.request.urlopen("https://www.website.com/") html = get.read() soup = BeautifulSoup(html) print(soup) </code></pre> <p>And I'm getting the following error:</p> <pre><code>File "C:\Python34\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode characters in position 70924-70950: character maps to &lt;undefined&gt; </code></pre> <p>What can I do to fix this?</p>
27,093,194
10
0
null
2014-11-23 18:47:01.413 UTC
89
2022-09-08 13:51:46.757 UTC
null
null
null
null
4,132,850
null
1
418
python|beautifulsoup|urllib
795,969
<p>I fixed it by adding <code>.encode("utf-8")</code> to <code>soup</code>.</p> <p>That means that <code>print(soup)</code> becomes <code>print(soup.encode("utf-8"))</code>.</p>
40,620,804
How do I sort a list with positives coming before negatives with values sorted respectively?
<p>I have a list that contains a mixture of positive and negative numbers, as the following</p> <pre><code>lst = [1, -2, 10, -12, -4, -5, 9, 2] </code></pre> <p>What I am trying to accomplish is to sort the list with the positive numbers coming before the negative numbers, respectively sorted as well. </p> <p><strong>Desired output:</strong></p> <pre><code>[1, 2, 9, 10, -12, -5, -4, -2] </code></pre> <p>I was able to figure out the first part sorting with the positive numbers coming before the and negative numbers, unfortunately this does not respectively sort the positive and negative numbers. </p> <pre><code>lst = [1, -2, 10, -12, -4, -5, 9, 2] lst = sorted(lst, key=lambda o: not abs(o) == o) print(lst) &gt;&gt;&gt; [1, 10, 2, 9, -2, -12, -4, -5] </code></pre> <p>How may I achieve my desired sorting with a pythonic solution?</p>
40,620,838
11
2
null
2016-11-15 22:23:32.903 UTC
3
2016-12-04 04:21:45.673 UTC
2016-12-04 04:21:45.673 UTC
null
2,063,361
null
1,040,092
null
1
31
python|list|sorting
4,152
<p>You could just use a regular sort, and then bisect the list at 0:</p> <pre><code>&gt;&gt;&gt; lst [1, -2, 10, -12, -4, -5, 9, 2] &gt;&gt;&gt; from bisect import bisect &gt;&gt;&gt; lst.sort() &gt;&gt;&gt; i = bisect(lst, 0) # use `bisect_left` instead if you want zeroes first &gt;&gt;&gt; lst[i:] + lst[:i] [1, 2, 9, 10, -12, -5, -4, -2] </code></pre> <p>The last line here takes advantage of a slice invariant <code>lst == lst[:n] + lst[n:]</code></p> <p>Another option would be to use a tuple as a sort key, and rely on <a href="https://en.wikipedia.org/wiki/Lexicographical_order" rel="noreferrer">lexicographical</a> ordering of tuples:</p> <pre><code>&gt;&gt;&gt; sorted(lst, key=lambda x: (x&lt;0, x)) # use &lt;= instead if you want zeroes last [1, 2, 9, 10, -12, -5, -4, -2] </code></pre>
34,117,191
tsconfig.json - Only build ts files from folder
<p>I am currently trying to build my ts files into a single ts files. The issue I'm getting is that my code below isn't doing what I thought it would. I used sourceRoot to attempt to set the only place it could get the source from but that didn't work. I have also tried putting a . infront of the directory but it still pulls from everywhere :(</p> <pre class="lang-js prettyprint-override"><code>{ "compilerOptions": { "target": "ES5", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "out": "www/js/app.js", "sourceMap": true, "sourceRoot": "www/app" } } </code></pre> <p>all files including those not inside of www/app build :(</p> <p>for now I've moved back to manually specifying the files:</p> <pre class="lang-js prettyprint-override"><code>{ "compilerOptions": { "target": "ES5", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "out": "www/js/app.js", "sourceMap": true }, "files": [ "./www/app/app.ts", "./www/app/menu/menuController.ts", "./www/app/playlists/playlistsController.ts" ] } </code></pre> <p>is it possible to restrict the source directories to be only www/app?</p> <p>Thanks</p>
34,121,884
4
0
null
2015-12-06 12:03:41.387 UTC
0
2019-08-10 09:21:29.933 UTC
null
null
null
null
1,332,999
null
1
22
typescript
49,250
<p>Yes,it is possible. Please use <code>rootDir</code> like <code>'rootDir': 'app'</code>, if <code>www</code> is your root dir of your application.</p> <p><code>rootDir</code> description from <a href="http://www.typescriptlang.org/docs/handbook/compiler-options.html" rel="noreferrer">typescript compiler options</a>:</p> <blockquote> <p>Specifies the root directory of input files. </p> </blockquote>
21,166,679
When to use imshow over pcolormesh?
<p>I often find myself needing to create heatmap-style visualizations in Python with matplotlib. Matplotlib provides several functions which apparently do the same thing. <code>pcolormesh</code> is recommended instead of <code>pcolor</code> but what is the difference (from a practical point of view as a data plotter) between <code>imshow</code> and <code>pcolormesh</code>? What are the pros/cons of using one over the other? In what scenarios would one or the other be a clear winner?</p>
21,169,703
1
0
null
2014-01-16 15:58:38.277 UTC
26
2014-01-16 18:16:37.29 UTC
null
null
null
null
837,451
null
1
54
python|matplotlib
25,697
<p>Fundamentally, <code>imshow</code> assumes that all data elements in your array are to be rendered at the same size, whereas <code>pcolormesh</code>/<code>pcolor</code> associates elements of the data array with rectangular elements whose size may vary over the rectangular grid.</p> <p>If your mesh elements are uniform, then <code>imshow</code> with interpolation set to "nearest" will look very similar to the default <code>pcolormesh</code> display (without the optional <code>X</code> and <code>Y</code> args). The obvious differences are that the <code>imshow</code> y-axis will be inverted (w.r.t. <code>pcolormesh</code>) and the aspect ratio is maintained, although those characteristics can be altered to look like the <code>pcolormesh</code> output as well.</p> <p>From a practical point of view, <code>pcolormesh</code> is more convenient if you want to visualize the data array as cells, particularly when the rectangular mesh is non-uniform or when you want to plot the boundaries/edges of the cells. Otherwise, <code>imshow</code> is more convenient if you have a fixed cell size, want to maintain aspect ratio, want control over pixel interpolation, or want to specify RGB values directly.</p>
38,788,721
How do I stream response in express?
<p>I've been trying to get a express app to send the response as stream.</p> <pre><code>var Readable = require('stream').Readable; var rs = Readable(); app.get('/report', function(req,res) { res.statusCode = 200; res.setHeader('Content-type', 'application/csv'); res.setHeader('Access-Control-Allow-Origin', '*'); // Header to force download res.setHeader('Content-disposition', 'attachment; filename=Report.csv'); rs.pipe(res); rs.push(&quot;USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD\n&quot;); for (var i = 0; i &lt; 10; i++) { rs.push(&quot;23,John Doe,1234,500,SUBSCRIPITON,100,ACTIVE,30\n&quot;); } rs.push(null); }); </code></pre> <p>It does print in the console when I replace &quot;rs.pipe(res)&quot; by &quot;rs.pipe(process.stdout)&quot;. But how to make it work in an express app?</p> <pre><code>Error: not implemented at Readable._read (_stream_readable.js:465:22) at Readable.read (_stream_readable.js:341:10) at Readable.on (_stream_readable.js:720:14) at Readable.pipe (_stream_readable.js:575:10) at line &quot;rs.pipe(res);&quot; </code></pre>
38,789,462
3
2
null
2016-08-05 11:58:54.82 UTC
13
2020-12-27 17:00:28.693 UTC
2020-12-27 17:00:28.693 UTC
null
1,783,163
null
6,608,003
null
1
52
javascript|node.js|csv|express
70,545
<p>You don't need a readable stream instance, just use <code>res.write()</code>:</p> <pre><code>res.write("USERID,NAME,FBID,ACCOUNT,SUBSCRIPTION,PRICE,STATE,TIMEPERIOD\n"); for (var i = 0; i &lt; 10; i++) { res.write("23,John Doe,1234,500,SUBSCRIPITON,100,ACTIVE,30\n"); } res.end(); </code></pre> <p>This works because in Express, <code>res</code> is based on Node's own <a href="https://nodejs.org/api/http.html#http_class_http_serverresponse" rel="noreferrer"><code>http.serverResponse</code></a>, so it inherits all its methods (like <a href="https://nodejs.org/api/http.html#http_response_write_chunk_encoding_callback" rel="noreferrer"><code>write</code></a>).</p>
58,656,747
Elasticsearch: Job for elasticsearch.service failed
<p>I am currently trying to setup <strong>Elasticsearch</strong> for a project. I have installed <code>Elasticsearch 7.4.1</code> and I have also installed <strong>Java</strong>, that is <code>openjdk 11.0.4</code>. </p> <p>But when I try to start <strong>Elasticsearch</strong> using the command</p> <pre><code>sudo systemctl start elasticsearch </code></pre> <p>I get the error below</p> <blockquote> <p>Job for elasticsearch.service failed because the control process exited with error code.</p> <p>See "systemctl status elasticsearch.service" and "journalctl -xe" for details.</p> </blockquote> <p>And when I try to run the command</p> <pre><code>systemctl status elasticsearch.service </code></pre> <p>I get the error message</p> <blockquote> <p>● elasticsearch.service - Elasticsearch</p> <p>Loaded: loaded (/usr/lib/systemd/system/elasticsearch.service; disabled; vend</p> <p>Active: failed (Result: exit-code) since Fri 2019-11-01 06:09:54 UTC; 12s ago</p> <pre><code>Docs: http://www.elastic.co </code></pre> <p>Process: 5960 ExecStart=/usr/share/elasticsearch/bin/elasticsearch -p ${PID_DI</p> <p>Main PID: 5960 (code=exited, status=1/FAILURE)</p> </blockquote> <p>I have removed/purged <strong>Elasticsearch</strong> from my machine and re-installed several times, but it doesn't seem to fix the issue.</p> <p>I have tried to modify the default <code>network.host</code> and <code>host.port</code> settings in <code>/etc/default/elasticsearch</code> to <code>network.host: 0.0.0.0</code> and <code>http.port: 9200</code> to fix the issue, but no luck yet.</p> <p>I need some assistance. Thanks in advance.</p>
58,656,748
11
0
null
2019-11-01 09:19:04.69 UTC
26
2022-04-05 11:58:35.8 UTC
2020-02-15 14:54:18.417 UTC
null
10,907,864
null
10,907,864
null
1
44
elasticsearch
97,102
<p><strong>Here's how I solved</strong></p> <p>Firstly, Open <code>/etc/elasticsearch/elasticsearch.yml</code> in your nano editor using the command below:</p> <pre><code>sudo nano /etc/elasticsearch/elasticsearch.yml </code></pre> <p>Your network settings should be:</p> <pre><code># Set the bind address to a specific IP (IPv4 or IPv6): # network.host: 127.0.0.1 # # Set a custom port for HTTP: # http.port: 9200 </code></pre> <p>In order for <strong>Elasticsearch</strong> to allow connections from localhost, and to also listen on port <code>9200</code>.</p> <p>Next, run the code below to determine the cause of the error:</p> <pre><code>journalctl -xe </code></pre> <p><strong>Error 1</strong></p> <blockquote> <p>There is insufficient memory for the Java Runtime Environment to continue</p> </blockquote> <p><strong>Solution</strong></p> <p>As a JVM application, the <strong>Elasticsearch</strong> main server process only utilizes memory devoted to the JVM. The required memory may depend on the JVM used (32- or 64-bit). The memory used by JVM usually consists of:</p> <ul> <li><strong>heap space</strong> (configured via <code>-Xms</code> and <code>-Xmx</code>)</li> <li><strong>metaspace</strong> (limited by the amount of available native memory)</li> <li><strong>internal JVM</strong> (usually tens of Mb)</li> <li>OS-dependent memory features like <strong>memory-mapped files</strong>.</li> </ul> <p>Elasticsearch mostly depends on the <strong>heap memory</strong>, and this setting manually by passing the <code>-Xms</code> and <code>-Xmx</code>(heap space) option to the JVM running the <strong>Elasticsearch</strong> server.</p> <p><strong>Solution</strong></p> <p>Open <code>/etc/elasticsearch/jvm.options</code> in your nano editor using the command below:</p> <pre><code>sudo nano /etc/elasticsearch/jvm.options </code></pre> <p>First, un-comment the value of <code>Xmx</code> and <code>Xms</code></p> <p>Next, modify the value of <code>-Xms</code> and <code>-Xmx</code> to no more than 50% of your physical RAM. The value for these settings depends on the amount of RAM available on your server and Elasticsearch requires memory for purposes other than the JVM heap and it is important to leave space for this.</p> <p><strong>Minimum requirements</strong>: If your physical RAM is <strong>&lt;= 1 GB</strong></p> <p>Then, your settings should be:</p> <pre><code># Xms represents the initial size of total heap space # Xmx represents the maximum size of total heap space -Xms128m -Xmx128m </code></pre> <p>OR</p> <pre><code># Xms represents the initial size of total heap space # Xmx represents the maximum size of total heap space -Xms256m -Xmx256m </code></pre> <p><strong>Medium requirements</strong>: If your physical RAM is <strong>&gt;= 2 GB</strong> but <strong>&lt;= 4 GB</strong></p> <p>Then, your settings should be:</p> <pre><code># Xms represents the initial size of total heap space # Xmx represents the maximum size of total heap space -Xms512m -Xmx512m </code></pre> <p>OR</p> <pre><code># Xms represents the initial size of total heap space # Xmx represents the maximum size of total heap space -Xms750m -Xmx750m </code></pre> <p><strong>Large requirements</strong>: If your physical RAM is <strong>&gt;= 4 GB</strong> but <strong>&lt;= 8 GB</strong></p> <p>Then, your settings should be:</p> <pre><code># Xms represents the initial size of total heap space # Xmx represents the maximum size of total heap space -Xms1024m -Xmx1024m </code></pre> <p>OR</p> <pre><code># Xms represents the initial size of total heap space # Xmx represents the maximum size of total heap space -Xms2048m -Xmx2048m </code></pre> <p><strong>Note</strong>: If your physical RAM is <strong>&gt;= 8 GB</strong> you can decide how much heap space you want to allocate to Elasticsearch. You can allocate <code>-Xms2048m</code> and <code>-Xmx2048m</code> OR <code>-Xms4g</code> and <code>-Xmx4g</code> or even higher for better performance based on your available resources.</p> <p><strong>Error 2</strong></p> <blockquote> <p>Initial heap size not equal to the maximum heap size</p> </blockquote> <p><strong>Solution</strong></p> <p>Ensure the value of <code>-Xms</code> and <code>Xmx</code> are equal. That is, say, you are using the <strong>minimum requirements</strong> since your physical RAM is <strong>&lt;= 1 GB</strong>, instead of this:</p> <pre><code># Xms represents the initial size of total heap space # Xmx represents the maximum size of total heap space -Xms128m -Xmx256m </code></pre> <p>it should be this:</p> <pre><code># Xms represents the initial size of total heap space # Xmx represents the maximum size of total heap space -Xms128m -Xmx128m </code></pre> <p>OR this:</p> <pre><code># Xms represents the initial size of total heap space # Xmx represents the maximum size of total heap space -Xms256m -Xmx256m </code></pre> <p><strong>Error 3</strong></p> <blockquote> <p>the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_master_nodes] must be configured</p> </blockquote> <p><strong>Solution</strong></p> <p>Open <code>/etc/elasticsearch/elasticsearch.yml</code> in your nano editor using the command below:</p> <pre><code>sudo nano /etc/elasticsearch/elasticsearch.yml </code></pre> <p>Your discovery settings should be:</p> <pre><code># Pass an initial list of hosts to perform discovery when this node is started: # The default list of hosts is [&quot;127.0.0.1&quot;, &quot;[::1]&quot;] # discovery.seed_hosts: [] </code></pre> <p>Once all the errors are fixed run the command below to start and confirm the status of <strong>Elasticsearch</strong>:</p> <pre><code>sudo systemctl start elasticsearch sudo systemctl status elasticsearch </code></pre> <p>That's all.</p> <p><strong>I hope this helps</strong></p>
6,020,545
Send/redirect/route java.util.logging.Logger (JUL) to Logback using SLF4J?
<p>Is it possible to have a typical call to <code>java.util.logging.Logger</code> and have it route to Logback using SLF4J? This would be nice since I wouldn't have to refactor the old jul code line by line.</p> <p>EG, say we have this line:</p> <pre><code>private static Logger logger = Logger.getLogger(MahClass.class.getName()); //... logger.info("blah blah blah"); </code></pre> <p>It would be nice to configure this to call through SLF4J.</p>
20,407,321
1
4
null
2011-05-16 16:41:14.157 UTC
10
2018-08-05 23:02:18.323 UTC
2017-06-25 12:37:21.187 UTC
null
1,078,886
null
17,675
null
1
30
java|logging|slf4j
21,841
<p>It's very easy and not a performance issue anymore.</p> <p>There are two ways documented in the <a href="https://www.slf4j.org/legacy.html#jul-to-slf4j" rel="noreferrer">SLF4J manual</a>. There are also precise examples in the <a href="https://www.slf4j.org/api/org/slf4j/bridge/SLF4JBridgeHandler.html" rel="noreferrer">Javadocs</a></p> <p>Add jul-to-slf4j.jar to your classpath. Or through maven dependency:</p> <pre><code>&lt;dependency&gt; &lt;groupId&gt;org.slf4j&lt;/groupId&gt; &lt;artifactId&gt;jul-to-slf4j&lt;/artifactId&gt; &lt;version&gt;1.7.0&lt;/version&gt; &lt;/dependency&gt; </code></pre> <p>If you don't have logging.properties (for java.util.logging), add this to your bootstrap code:</p> <pre><code>SLF4JBridgeHandler.removeHandlersForRootLogger(); SLF4JBridgeHandler.install(); </code></pre> <p>If you have logging.properties (and want to keep it), add this to it:</p> <pre><code>handlers = org.slf4j.bridge.SLF4JBridgeHandler </code></pre> <p>In order to avoid performance penalty, add this contextListener to logback.xml (as of logback version 0.9.25):</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"&gt; &lt;!-- reset all previous level configurations of all j.u.l. loggers --&gt; &lt;resetJUL&gt;true&lt;/resetJUL&gt; &lt;/contextListener&gt; ... &lt;/configuration&gt; </code></pre>
52,946,110
U-net low contrast test images, predict output is grey box
<p>I am running the unet from <a href="https://github.com/zhixuhao/unet" rel="nofollow noreferrer">https://github.com/zhixuhao/unet</a> but when I run the unet the predicted images are all grey. I get an error saying low contrast image for my test data, any one had or resolved this problem?</p> <p>I am training with 50 ultrasound images and get around 2000/3000 after augmentation, on 5 epochs with 300 steps per epoch and batch size of 2.</p> <p>Many thanks in advance Helena</p>
54,031,459
1
0
null
2018-10-23 09:51:51.043 UTC
9
2019-11-27 14:28:53.427 UTC
2019-01-04 06:37:54.25 UTC
null
5,763,590
null
8,375,248
null
1
4
python|tensorflow|keras|conv-neural-network|image-segmentation
4,884
<blockquote> <p>After you made sure that your data pipeline is correct. There are a few things to consider here, I hope one of the bellow mentioned helps:</p> </blockquote> <p><strong>1. Choose the right loss function</strong> Binary crossentropy might lead your network in the direction of optimizing for all labels, now if you have an unbalanced amount of labels in your image, it might draw your network to just give back either white, gray or black image predictions. Try using the dice coefficient loss</p> <p><strong>2. Change the line in testGenerator</strong> A thing that seems to be an issue in <code>data.py</code> and the <code>testGenerator</code> method is the following line:</p> <pre><code>img = img / 255 </code></pre> <p>Change it to:</p> <pre><code>img /=255. </code></pre> <p><strong>3. Reduce learning rate</strong> if your learning rate is too high you might converge in non-sufficient optima, which also tend to optimize for gray, black or white predictions only. Try a learning rate around <code>Adam(lr = 3e-5)</code> and train for a sufficient amount of epochs, you should print dice loss and not accuracy to check your convergence.</p> <p><strong>4. Do not use activation functions for the last set of convolutions</strong> For the last set of convolutions, that is 128-> 64 -> 64 -> 1, the activation function should not be used! The activation function causes the values to vanish!</p> <p><strong>5. Your saving method could have a "bug"</strong> make sure you scale your image to values between 0 and 255 before saving. Skimage usually warns you with a low contrast image warning.</p> <pre><code>from skimage import img_as_uint io.imsave(os.path.join(save_path,"%d_predict.tif"%(i)),img_as_uint(img)) </code></pre> <p><strong>6. Your saving format could have a "bug"</strong> make sure you save your image in a proper format. I experienced that saving as .png gives only black or gray images, whereas .tif works like a charm.</p> <p><strong>7. You might just not train enough</strong> often you'll just freak out when your network does not do as you would like it to and abort the training. Chance is, additional training epochs is exactly what it would have needed.</p>
37,957,404
Using TypeScript super()
<p>I am trying to extend a class in TypeScript. I keep receiving this error on compile: 'Supplied parameters do not match any signature of call target.' I have tried referencing the artist.name property in the super call as super(name) but is not working. </p> <p>Any ideas and explanations you may have will be greatly appreciated. Thanks - Alex.</p> <pre><code>class Artist { constructor( public name: string, public age: number, public style: string, public location: string ){ console.log(`instantiated ${name}, whom is ${age} old, from ${location}, and heavily regarded in the ${style} community`); } } class StreetArtist extends Artist { constructor( public medium: string, public famous: boolean, public arrested: boolean, public art: Artist ){ super(); console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`); } } interface Human { name: string, age: number } function getArtist(artist: Human){ console.log(artist.name) } let Banksy = new Artist( "Banksy", 40, "Politcal Graffitti", "England / Wolrd" ) getArtist(Banksy); </code></pre>
37,957,484
1
0
null
2016-06-22 02:08:27.973 UTC
8
2016-06-22 08:11:22.32 UTC
null
null
null
null
4,621,842
null
1
39
javascript|oop|typescript
75,610
<p>The super call must supply all parameters for base class. The constructor is not inherited. Commented out artist because I guess it is not needed when doing like this.</p> <pre><code>class StreetArtist extends Artist { constructor( name: string, age: number, style: string, location: string, public medium: string, public famous: boolean, public arrested: boolean, /*public art: Artist*/ ){ super(name, age, style, location); console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`); } } </code></pre> <p>Or if you intended the art parameter to populate base properties, but in that case I guess there isn't really a need for using public on art parameter as the properties would be inherited and it would only store duplicate data.</p> <pre><code>class StreetArtist extends Artist { constructor( public medium: string, public famous: boolean, public arrested: boolean, /*public */art: Artist ){ super(art.name, art.age, art.style, art.location); console.log(`instantiated ${this.name}. Are they famous? ${famous}. Are they locked up? ${arrested}`); } } </code></pre>
44,673,957
Kubernetes: how to debug CrashLoopBackOff
<p>I have the following setup:</p> <p>A docker image <code>omg/telperion</code> on docker hub A kubernetes cluster (with 4 nodes, each with ~50GB RAM) and plenty resources</p> <p>I followed tutorials to pull images from dockerhub to kubernetes</p> <pre><code>SERVICE_NAME=telperion DOCKER_SERVER="https://index.docker.io/v1/" DOCKER_USERNAME=username DOCKER_PASSWORD=password DOCKER_EMAIL="[email protected]" # Create secret kubectl create secret docker-registry dockerhub --docker-server=$DOCKER_SERVER --docker-username=$DOCKER_USERNAME --docker-password=$DOCKER_PASSWORD --docker-email=$DOCKER_EMAIL # Create service yaml echo "apiVersion: v1 \n\ kind: Pod \n\ metadata: \n\ name: ${SERVICE_NAME} \n\ spec: \n\ containers: \n\ - name: ${SERVICE_NAME} \n\ image: omg/${SERVICE_NAME} \n\ imagePullPolicy: Always \n\ command: [ \"echo\",\"done deploying $SERVICE_NAME\" ] \n\ imagePullSecrets: \n\ - name: dockerhub" &gt; $SERVICE_NAME.yaml # Deploy to kubernetes kubectl create -f $SERVICE_NAME.yaml </code></pre> <p>Which results in the pod going into a <code>CrashLoopBackoff</code></p> <p><code>docker run -it -p8080:9546 omg/telperion</code> works fine.</p> <p>So my question is <strong>Is this debug-able?, if so, how do i debug this?</strong></p> <p>Some logs:</p> <pre><code>kubectl get nodes NAME STATUS AGE VERSION k8s-agent-adb12ed9-0 Ready 22h v1.6.6 k8s-agent-adb12ed9-1 Ready 22h v1.6.6 k8s-agent-adb12ed9-2 Ready 22h v1.6.6 k8s-master-adb12ed9-0 Ready,SchedulingDisabled 22h v1.6.6 </code></pre> <p>.</p> <pre><code>kubectl get pods NAME READY STATUS RESTARTS AGE telperion 0/1 CrashLoopBackOff 10 28m </code></pre> <p>.</p> <pre><code>kubectl describe pod telperion Name: telperion Namespace: default Node: k8s-agent-adb12ed9-2/10.240.0.4 Start Time: Wed, 21 Jun 2017 10:18:23 +0000 Labels: &lt;none&gt; Annotations: &lt;none&gt; Status: Running IP: 10.244.1.4 Controllers: &lt;none&gt; Containers: telperion: Container ID: docker://c2dd021b3d619d1d4e2afafd7a71070e1e43132563fdc370e75008c0b876d567 Image: omg/telperion Image ID: docker-pullable://omg/telperion@sha256:c7e3beb0457b33cd2043c62ea7b11ae44a5629a5279a88c086ff4853828a6d96 Port: Command: echo done deploying telperion State: Waiting Reason: CrashLoopBackOff Last State: Terminated Reason: Completed Exit Code: 0 Started: Wed, 21 Jun 2017 10:19:25 +0000 Finished: Wed, 21 Jun 2017 10:19:25 +0000 Ready: False Restart Count: 3 Environment: &lt;none&gt; Mounts: /var/run/secrets/kubernetes.io/serviceaccount from default-token-n7ll0 (ro) Conditions: Type Status Initialized True Ready False PodScheduled True Volumes: default-token-n7ll0: Type: Secret (a volume populated by a Secret) SecretName: default-token-n7ll0 Optional: false QoS Class: BestEffort Node-Selectors: &lt;none&gt; Tolerations: &lt;none&gt; Events: FirstSeen LastSeen Count From SubObjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 1m 1m 1 default-scheduler Normal Scheduled Successfully assigned telperion to k8s-agent-adb12ed9-2 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Created Created container with id d9aa21fd16b682698235e49adf80366f90d02628e7ed5d40a6e046aaaf7bf774 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Started Started container with id d9aa21fd16b682698235e49adf80366f90d02628e7ed5d40a6e046aaaf7bf774 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Started Started container with id c6c8f61016b06d0488e16bbac0c9285fed744b933112fd5d116e3e41c86db919 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Created Created container with id c6c8f61016b06d0488e16bbac0c9285fed744b933112fd5d116e3e41c86db919 1m 1m 2 kubelet, k8s-agent-adb12ed9-2 Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "telperion" with CrashLoopBackOff: "Back-off 10s restarting failed container=telperion pod=telperion_default(f4e36a12-566a-11e7-99a6-000d3aa32f49)" 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Started Started container with id 3b911f1273518b380bfcbc71c9b7b770826c0ce884ac876fdb208e7c952a4631 1m 1m 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Created Created container with id 3b911f1273518b380bfcbc71c9b7b770826c0ce884ac876fdb208e7c952a4631 1m 1m 2 kubelet, k8s-agent-adb12ed9-2 Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "telperion" with CrashLoopBackOff: "Back-off 20s restarting failed container=telperion pod=telperion_default(f4e36a12-566a-11e7-99a6-000d3aa32f49)" 1m 50s 4 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Pulling pulling image "omg/telperion" 47s 47s 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Started Started container with id c2dd021b3d619d1d4e2afafd7a71070e1e43132563fdc370e75008c0b876d567 1m 47s 4 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Pulled Successfully pulled image "omg/telperion" 47s 47s 1 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Normal Created Created container with id c2dd021b3d619d1d4e2afafd7a71070e1e43132563fdc370e75008c0b876d567 1m 9s 8 kubelet, k8s-agent-adb12ed9-2 spec.containers{telperion} Warning BackOff Back-off restarting failed container 46s 9s 4 kubelet, k8s-agent-adb12ed9-2 Warning FailedSync Error syncing pod, skipping: failed to "StartContainer" for "telperion" with CrashLoopBackOff: "Back-off 40s restarting failed container=telperion pod=telperion_default(f4e36a12-566a-11e7-99a6-000d3aa32f49)" </code></pre> <p>Edit 1: Errors reported by kubelet on master:</p> <pre><code>journalctl -u kubelet </code></pre> <p>.</p> <pre><code>Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: E0621 10:28:49.798140 1809 fsHandler.go:121] failed to collect filesystem stats - rootDiskErr: du command failed on /var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce with output Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: , stderr: du: cannot access '/var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce/merged/proc/13122/task/13122/fd/4': No such file or directory Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: du: cannot access '/var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce/merged/proc/13122/task/13122/fdinfo/4': No such file or directory Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: du: cannot access '/var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce/merged/proc/13122/fd/3': No such file or directory Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: du: cannot access '/var/lib/docker/overlay/5cfff16d670f2df6520360595d7858fb5d16607b6999a88e5dcbc09e1e7ab9ce/merged/proc/13122/fdinfo/3': No such file or directory Jun 21 10:28:49 k8s-master-ADB12ED9-0 docker[1622]: - exit status 1, rootInodeErr: &lt;nil&gt;, extraDiskErr: &lt;nil&gt; </code></pre> <p>Edit 2: more logs</p> <pre><code>kubectl logs $SERVICE_NAME -p done deploying telperion </code></pre>
44,674,153
3
0
null
2017-06-21 10:47:27.697 UTC
15
2022-01-03 06:12:42.723 UTC
2017-06-21 10:59:17.74 UTC
null
2,134,957
null
2,134,957
null
1
80
bash|docker|kubernetes
81,875
<p>You can access the logs of your pods with</p> <pre><code>kubectl logs [podname] -p </code></pre> <p>the -p option will read the logs of the previous (crashed) instance</p> <p>If the crash comes from the application, you should have useful logs in there.</p>
48,399,903
What is partition key in AWS Kinesis all about?
<p>I was reading about <code>AWS Kinesis</code>. In the following program, I write data into the stream named <code>TestStream</code>. I ran this piece of code 10 times, inserting 10 records into the stream.</p> <pre><code>var params = { Data: 'More Sample data into the test stream ...', PartitionKey: 'TestKey_1', StreamName: 'TestStream' }; kinesis.putRecord(params, function(err, data) { if (err) console.log(err, err.stack); // an error occurred else console.log(data); // successful response }); </code></pre> <p>All the records were inserted successfully. What does <code>partition key</code> really mean here? What is it doing in the background? I read its <a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Kinesis.html#putRecord-property" rel="noreferrer">documentation</a> but did not understand what it meant.</p>
48,400,535
2
0
null
2018-01-23 10:52:44.313 UTC
8
2022-04-01 12:01:48.873 UTC
null
null
null
null
648,138
null
1
55
node.js|amazon-web-services|stream|amazon-kinesis
32,859
<p>Partition keys only matter when you have multiple shards in a stream (but they're required always). Kinesis computes the MD5 hash of a partition key to decide what shard to store the record on (if you describe the stream you'll see the hash range as part of the shard decription).</p> <p>So why does this matter?</p> <p>Each shard can only accept 1,000 records and/or 1 MB per second (see <a href="https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html" rel="noreferrer">PutRecord</a> doc). If you write to a single shard faster than this rate you'll get a <code>ProvisionedThroughputExceededException</code>.</p> <p>With multiple shards, you scale this limit: 4 shards gives you 4,000 records and/or 4 MB per second. Of course, there are caveats.</p> <p>The biggest is that you must use different partition keys. If all of your records use the same partition key then you're still writing to a single shard, because they'll all have the same hash value. How you solve this depends on your application: if you're writing from multiple processes then it might be sufficient to use the process ID, server's IP address, or hostname. If you're writing from a single process then you can either use information that's in the record (for example, a unique record ID) or generate a random string.</p> <p>Second caveat is that the partition key counts against the total write size, and is stored in the stream. So while you could probably get good randomness by using some textual component in the record, you'd be wasting space. On the other hand, if you have some random textual component, you could calculate your own hash from it and then stringify that for the partition key.</p> <p>Lastly, if you're using <a href="https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecords.html" rel="noreferrer">PutRecords</a> (which you should, if you're writing a lot of data), individual records in the request may be rejected while others are accepted. This happens because those records went to a shard that was already at its write limits, and you have to re-send them (after a delay).</p> <hr /> <p>The other answer points out that records are ordered within a partition, and claims that this is the real reason for a partition key. However, this ordering reflects the order in which Kinesis <em>accepted</em> the records, which is not necessarily the order that the client intended.</p> <ul> <li>If the client is single-threaded and uses the <a href="https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecord.html" rel="noreferrer">PutRecord</a> API, then yes, ordering should be consistent between client and partition.</li> <li>If the client is multi-threaded, then all of the standard distributed systems causes of disorder (internal thread scheduling, network routing, service scheduling) could cause inconsistent ordering.</li> <li>If the client uses the <a href="https://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecords.html" rel="noreferrer">PutRecords</a> API, individual records from a batch can be rejected and must be resent. The doc is very clear that this API call does not preserve ordering. And in a high-volume environment, this is the API that you will use.</li> </ul> <p>In addition to inconsistent ordering when writing, a reshard operation introduces the potential for inconsistencies when reading. You must follow the chain from parent to child(ren), recognizing that there may be more or fewer children and that the split may not be even. A naive &quot;one thread per shard&quot; approach (such as used by Lambda) won't work.</p> <p>So, bottom line: yes, shards provide ordering. However, relying on that order may introduce hard-to-diagnose bugs into your application.</p> <p>In most cases, it won't matter. But if you need guaranteed order (such as when processing a transaction log), then you <em>must</em> add your own ordering information into your record when it's written, and ensure that records are properly ordered when read.</p>
20,989,458
Select2 open dropdown on focus
<p>I have a form with multiple text inputs and some select2 elements. Using the keyboard to tab between fields works fine - the Select2 element behaves like a form element and receives focus when tabbing. I was wondering if it is possible to open the dropdown when the Select2 element gets focus.</p> <p>Here's what I've tried so far:</p> <pre><code>$("#myid").select2().on('select2-focus', function(){ $(this).select2('open'); }); </code></pre> <p>But using this code makes the dropdown to open again after a selection is made. </p>
49,261,426
17
0
null
2014-01-08 07:29:26.48 UTC
16
2021-05-03 04:44:41.25 UTC
2019-12-12 09:39:51.39 UTC
null
1,135,971
null
1,135,971
null
1
43
javascript|jquery|jquery-select2|jquery-select2-4
132,796
<h2>Working Code for v4.0+ <sup><sup>*(<em>including 4.0.7)</em></sup></sup></h2> <p>The following code will open the menu on the <em>initial</em> focus, but won't get stuck in an infinite loop when the selection re-focuses after the menu closes.</p> <pre class="lang-js prettyprint-override"><code>// on first focus (bubbles up to document), open the menu $(document).on('focus', '.select2-selection.select2-selection--single', function (e) { $(this).closest(".select2-container").siblings('select:enabled').select2('open'); }); // steal focus during close - only capture once and stop propogation $('select.select2').on('select2:closing', function (e) { $(e.target).data("select2").$selection.one('focus focusin', function (e) { e.stopPropagation(); }); }); </code></pre> <h2>Explanation</h2> <h3>Prevent Infinite Focus Loop</h3> <p><strong>Note</strong>: The <code>focus</code> event is <em>fired twice</em></p> <ol> <li>Once when tabbing into the field</li> <li>Again when tabbing with an open dropdown to restore focus</li> </ol> <p><img src="https://i.stack.imgur.com/WrHwd.gif" alt="focus menu states"></p> <p>We can prevent an infinite loop by looking for differences between the types of focus events. Since we only want to open the menu on the initial focus to the control, we have to somehow distinguish between the following raised events:</p> <p><a href="https://i.stack.imgur.com/6PLVr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6PLVr.png" alt="event timeline"></a></p> <p>Doing so it a cross browser friendly way is hard, because browsers send different information along with different events and also Select2 has had many minor changes to their internal firing of events, which interrupt previous flows. </p> <p>One way that seems to work is to attach an event handler during the <a href="https://select2.org/programmatic-control/events" rel="noreferrer"><code>closing</code></a> event for the menu and use it to capture the impending <code>focus</code> event and prevent it from bubbling up the DOM. Then, using a delegated listener, we'll call the actual focus -> open code only when the <code>focus</code> event bubbles all the way up to the <code>document</code></p> <h3>Prevent Opening Disabled Selects</h3> <p>As noted in this github issue <a href="https://github.com/select2/select2/issues/4025" rel="noreferrer">#4025 - Dropdown does not open on tab focus</a>, we should check to make sure we only call <code>'open'</code> on <code>:enabled</code> select elements like this:</p> <pre class="lang-js prettyprint-override"><code>$(this).siblings('select<b>:enabled</b>').select2('open');</code></pre> <h3>Select2 DOM traversal</h3> <p>We have to traverse the DOM a little bit, so here's a map of the HTML structure generated by Select2</p> <p><a href="https://i.stack.imgur.com/1NAg3.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1NAg3.png" alt="Select2 DOM"></a></p> <h3>Source Code on GitHub</h3> <p>Here are some of the relevant code sections in play:</p> <p><a href="https://github.com/select2/select2/blob/4.0.7/src/js/select2/selection/single.js#L41" rel="noreferrer"><code>.on('mousedown'</code> ... <code>.trigger('toggle')</code></a><br> <a href="https://github.com/select2/select2/blob/4.0.5/dist/js/select2.full.js#L5290" rel="noreferrer"><code>.on('toggle'</code> ... <code>.toggleDropdown()</code></a><br> <a href="https://github.com/select2/select2/blob/4.0.5/dist/js/select2.full.js#L5496" rel="noreferrer"><code>.toggleDropdown</code> ... <code>.open()</code></a><br> <a href="https://github.com/select2/select2/blob/4.0.7/src/js/select2/selection/base.js#L46" rel="noreferrer"><code>.on('focus'</code> ... <code>.trigger('focus'</code></a><br> <a href="https://github.com/select2/select2/blob/4.0.7/src/js/select2/selection/base.js#L84" rel="noreferrer"><code>.on('close'</code> ... <code>$selection.focus()</code></a> </p> <p>It used to be the case that opening select2 fired twice, but it was fixed in <a href="https://github.com/select2/select2/issues/3503" rel="noreferrer">Issue #3503</a> and that should prevent some jank</p> <p><a href="https://github.com/select2/select2/pull/5357" rel="noreferrer">PR #5357</a> appears to be what broke the previous focus code that was working in 4.05</p> <h3><a href="https://jsfiddle.net/KyleMit/hbeon3g2/" rel="noreferrer">Working Demo in jsFiddle</a> &amp; Stack Snippets:</h3> <p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false"> <div class="snippet-code snippet-currently-hidden"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$('.select2').select2({}); // on first focus (bubbles up to document), open the menu $(document).on('focus', '.select2-selection.select2-selection--single', function (e) { $(this).closest(".select2-container").siblings('select:enabled').select2('open'); }); // steal focus during close - only capture once and stop propogation $('select.select2').on('select2:closing', function (e) { $(e.target).data("select2").$selection.one('focus focusin', function (e) { e.stopPropagation(); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.css" rel="stylesheet"/&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"&gt;&lt;/script&gt; &lt;script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.js"&gt;&lt;/script&gt; &lt;select class="select2" style="width:200px" &gt; &lt;option value="1"&gt;Apple&lt;/option&gt; &lt;option value="2"&gt;Banana&lt;/option&gt; &lt;option value="3"&gt;Carrot&lt;/option&gt; &lt;option value="4"&gt;Donut&lt;/option&gt; &lt;/select&gt;</code></pre> </div> </div> </p> <p>Tested on Chrome, FF, Edge, IE11</p>
7,476,220
Image Source Completion for Sublime Text 2
<p>First of all, I'm not entirely sure if this fits into stackoverflow, or should rather be placed into programmers or superuser. If I posted into the wrong page, I'm sorry.</p> <p>To the question:</p> <p>In Aptana Studio, for example, there's a very nice feature for the <code>src</code>-attribute for <code>&lt;img&gt;</code>-tags. When typing into the src-attribute, a directory-listing is shown in the autocomplete-contextmenu, so you can directly select image files and the path is inserted into the attribute.</p> <p>Here is what I mean:</p> <p><img src="https://i.stack.imgur.com/INI62.jpg" alt="Aptana Img src"></p> <p>Is there any way, a plugin or something alike, so I can get this behaviour into Sublime Text 2? Preferably working for HTML-Markup and CSS background-images?</p> <p><strong>edit</strong>: Meanwhile I posted this on the sublime userecho, maybe something will come up trough this. I'll keep this question updated.</p> <p><a href="http://sublimetext.userecho.com/topic/61330-image-source-completion/" rel="noreferrer">Sublime Userecho</a></p>
8,856,513
1
4
null
2011-09-19 19:27:00.277 UTC
10
2014-08-06 15:45:13.363 UTC
2011-10-07 13:41:35.387 UTC
null
809,950
null
809,950
null
1
10
html|autocomplete|aptana|sublimetext
11,020
<p>I just created a plugin to do this. You can find it here: <a href="https://gist.github.com/1608287">https://gist.github.com/1608287</a></p> <p>EDIT: the plugin is now available through Package Control. Just search for "AutoFileName."</p>
41,873,717
How to use logic operators in jinja template on salt-stack (AND, OR)
<p>I am using a jinja template to generate a state file for salt. I added some conditionals and would like to express: <code>if A or B</code>. However, it seems I cannot get any logical operator working.</p> <p>It doesn't like <code>||, |, &amp;&amp;</code>(which I understand doesn't apply here), but also not <code>and, or</code> and not even grouping with <code>()</code>, which should be working according to the <a href="http://jinja.pocoo.org/docs/2.9/templates/#logic" rel="noreferrer">jinja documentation</a>. I couldn't find any information on this in the salt docs, but I feel I must be making some stupid mistake?</p> <p>My code:</p> <pre><code>{% if grains['configvar'] == 'value' OR grains['configvar'] == 'some other value' %} </code></pre> <p>Error:</p> <pre><code>Data failed to compile: Rendering SLS 'base:mystate' failed: Jinja syntax error: expected token 'end of statement block', got 'OR'; line 3 </code></pre>
41,875,784
1
0
null
2017-01-26 12:43:09.107 UTC
1
2017-01-26 14:32:08.017 UTC
null
null
null
null
4,259,346
null
1
28
jinja2|salt-stack
56,505
<p>You are doing it right but the logic operators <strong>need</strong> to be <strong>lower cased</strong>.</p> <p>Try switching all your operators to lower case.</p>
41,870,411
Object index key type in Typescript
<p>I defined my generic type as</p> <pre><code>interface IDictionary&lt;TValue&gt; { [key: string|number]: TValue; } </code></pre> <p>But TSLint's complaining. How am I supposed to define an object index type that can have either as key? I tried these as well but no luck.</p> <pre><code>interface IDictionary&lt;TKey, TValue&gt; { [key: TKey]: TValue; } interface IDictionary&lt;TKey extends string|number, TValue&gt; { [key: TKey]: TValue; } type IndexKey = string | number; interface IDictionary&lt;TValue&gt; { [key: IndexKey]: TValue; } interface IDictionary&lt;TKey extends IndexKey, TValue&gt; { [key: TKey]: TValue; } </code></pre> <p><strong>None of the above work.</strong></p> <h2>So how then?</h2>
41,870,915
3
0
null
2017-01-26 09:32:48.107 UTC
10
2020-04-06 06:37:41.367 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
75,642
null
1
73
typescript|typescript-generics
137,683
<p>You can achieve that just by using a <code>IDictionary&lt;TValue&gt; { [key: string]: TValue }</code> since numeric values will be automatically converted to string.</p> <p>Here is an example of usage:</p> <pre><code>interface IDictionary&lt;TValue&gt; { [id: string]: TValue; } class Test { private dictionary: IDictionary&lt;string&gt;; constructor() { this.dictionary = {} this.dictionary[9] = "numeric-index"; this.dictionary["10"] = "string-index" console.log(this.dictionary["9"], this.dictionary[10]); } } // result =&gt; "numeric-index string-index" </code></pre> <p>As you can see string and numeric indices are interchangeable.</p>
46,018,883
Best Practice for Updating AWS ECS Service Tasks
<p>I'm currently attempting to set up a simple CI that will rebuild my project, create a new docker image, push the new image to an amazon ecr repo, create a new revision of an existing task definition with the latest docker image, update a running service with the new revision of the task definition, and finally stop the existing task running the old revision and start one running the new revision.</p> <p>Everything is working fine except for starting the new revision of the task.</p> <p>From a bash script, the final command I call is:</p> <pre><code>aws ecs update-service --cluster "$CLUSTER" --service "$SERVICE" --task-definition "$TASK_DEFINITION":"$REVISION" </code></pre> <p>This results in an event error of:</p> <pre><code>(service rj-api-service) was unable to place a task because no container instance met all of its requirements. The closest matching (container-instance bbbc23d5-1a09-45e7-b344-e68cc408e683) is already using a port required by your task. </code></pre> <p>And this makes sense because the container I am replacing is exactly sthe same as the new one and will be running on the same port, it just contains the latest version of my application.</p> <p>I was under the impression the <code>update-service</code> command would stop the existing task, and start the new one, but it looks like it starts the new one first, and if it succeeds stops the old one.</p> <p>What is the best practice for handling this? Should I stop the old task first? Should I just delete the service in my script first and recreate the entire service each update?</p> <p>Currently I only need 1 instance of the task running, but I don't want to box my self in if I need this to be able to auto scale to multiple instances. Any suggestions on the best way to address this?</p>
46,029,034
5
1
null
2017-09-02 22:49:09.5 UTC
18
2022-09-04 06:49:54.377 UTC
null
null
null
null
3,168,265
null
1
48
amazon-web-services|docker|amazon-ec2
42,350
<p>The message that you are getting is because ECS is trying to do a blue-green deployment. It means that it is trying to allocate your new task revision without stopping the current task to avoid downtime in your service. Once the newest task is ready (steady state), the old one will be finally removed. </p> <p>The problem with this type of deployment is that you need to have enough <strong>free resources</strong> in your cluster in order maintain up and running the 2 tasks (old and new one) for a period of time. For example, if you are deploying a task with 2GB of memory and 2 CPUs, your cluster will need to have that amount of free resources in order to update the service with a new task revision. </p> <p>You have 2 options:</p> <ol> <li>Scale up your cluster by adding a new EC2 instance so you can have enough free resources and perform the deployment.</li> <li>Change your service configuration in order to do not perform a blue-green deployment (allow only 1 task at the same time in your cluster).</li> </ol> <p>In order to perform option number 2 you only need to set the following values:</p> <ul> <li><strong>Minimum healthy percent</strong>: 0</li> <li><strong>Maximum percent</strong>: 100</li> </ul> <p><em>Example</em></p> <p><a href="https://i.stack.imgur.com/WeDlN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/WeDlN.png" alt="Example"></a></p> <p>Which means that you only want to have 100% of your desired tasks running (and no more!) and you are willing to have a downtime while you deploy a new version (0% of healthy service).</p> <p><em>In the example I am assuming that you only want 1 desired task, but the <strong>Minimum healthy percent</strong> and <strong>Maximum percent</strong> values will work for any amount of desired tasks you want.</em></p> <p>Hope it helps! Let me know if you have any other doubt.</p>
39,174,824
In tableau, how do you modify the number of decimals of a percentage label?
<p>In tableau, how do you modify the number of decimals of a percentage label? On bar charts, histograms, maps, etc. </p>
39,178,454
3
1
null
2016-08-26 21:25:21.197 UTC
1
2020-05-02 00:46:23.213 UTC
null
null
null
null
6,763,084
null
1
9
formatting|decimal|tableau-api
76,576
<p>Right Click on the measure dropped under Marks Card and Click on "Format". You will be provided with the options to change the format of the numbers in "Pane". Select "Numbers" and Click on the "Percentage" and increase/decrease the Percentage Decimals.</p> <p>If you want that format choice to be the default for occurrences of that field on all worksheets, set the default property number format by right clicking on the field in the data pane (left margin) instead of on a shelf</p>
2,443,811
What is the difference between Managed C++ and C++/CLI?
<p>What is exactly the difference between the "old" Managed C++ and the "new" C++/CLI? </p>
2,443,819
3
0
null
2010-03-14 21:12:45.113 UTC
6
2017-09-22 13:58:15.243 UTC
2015-03-09 20:28:56.823 UTC
null
3,204,551
null
140,937
null
1
32
.net|visual-c++|c++-cli|managed-c++
7,557
<p>Managed C++ is the version in VS2002 and VS2003. It had race conditions and other serious bugs, as well as being confusing. It's no longer supported.</p> <p>In VS2005, Microsoft introduced C++/CLI, which has also been accepted as an ISO standard. It's also supported in VS2008 and the upcoming VS2010.</p> <p>Both of them had the same goal, which is to create .NET assemblies using the C++ language. The syntax is different (C++/CLI managed code is a lot easier to differentiate from standard C++ at a glance) and C++/CLI also has syntax for .NET 2.0 features such as generics.</p>
2,842,667
How to create a semi transparent window in WPF that allows mouse events to pass through
<p>I am trying to create an effect similar to the Lights out /lights dim feature in Adobe Lightroom (<a href="http://www.youtube.com/watch?v=87hNd3vaENE" rel="noreferrer">http://www.youtube.com/watch?v=87hNd3vaENE</a>) except in WPF.</p> <p>What I tried was to create another window over-top of my existing window, make it transparent and put a semi transparent Path geometry on it. But I want mouse events to be able to pass through this semi transparent window (on to windows below). </p> <p>This is a simplified version of what I have: </p> <pre><code>&lt;Window x:Class="LightsOut.MaskWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" AllowsTransparency="True" WindowStyle="None" ShowInTaskbar="False" Topmost="True" Background="Transparent"&gt; &lt;Grid&gt; &lt;Button HorizontalAlignment="Left" Height="20" Width="60"&gt;click&lt;/Button&gt; &lt;Path IsHitTestVisible="False" Stroke="Black" Fill="Black" Opacity="0.3"&gt; &lt;Path.Data&gt; &lt;RectangleGeometry Rect="0,0,1000,1000 "/&gt; &lt;/Path.Data&gt; &lt;/Path&gt; &lt;/Grid&gt; </code></pre> <p></p> <p>The window is fully transparent, so on places where the Path doesn't cover, mouse events pass right through. So far so good. The IsHitTestvisible is set to false on the path object. So mouse events will pass through it to other controls on the same form (ie you can click on the Button, because it is on the same form). </p> <p>But mouse events wont pass through the Path object onto windows that are below it.</p> <p>Any ideas? Or better ways to solve this problem?</p> <p>Thanks. </p>
3,367,137
3
0
null
2010-05-16 05:13:11.67 UTC
27
2018-01-28 01:26:50.633 UTC
null
null
null
null
165,148
null
1
39
wpf|transparency
22,803
<p>I've had similar problem and found a solution:</p> <pre><code>public static class WindowsServices { const int WS_EX_TRANSPARENT = 0x00000020; const int GWL_EXSTYLE = (-20); [DllImport("user32.dll")] static extern int GetWindowLong(IntPtr hwnd, int index); [DllImport("user32.dll")] static extern int SetWindowLong(IntPtr hwnd, int index, int newStyle); public static void SetWindowExTransparent(IntPtr hwnd) { var extendedStyle = GetWindowLong(hwnd, GWL_EXSTYLE); SetWindowLong(hwnd, GWL_EXSTYLE, extendedStyle | WS_EX_TRANSPARENT); } } </code></pre> <p>for your window set:</p> <pre><code>WindowStyle = None Topmost = true AllowsTransparency = true </code></pre> <p>in code behind for the window add:</p> <pre><code>protected override void OnSourceInitialized(EventArgs e) { base.OnSourceInitialized(e); var hwnd = new WindowInteropHelper(this).Handle; WindowsServices.SetWindowExTransparent(hwnd); } </code></pre> <p>and voila - click-through window! See original answer in: <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a3cb7db6-5014-430f-a5c2-c9746b077d4f" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/a3cb7db6-5014-430f-a5c2-c9746b077d4f</a></p>
3,199,388
Getting assembly language programming skills
<p>I am a DSP, embedded software programmer, looking to improve my assembly language programming skills. For 7 years of my career I have been programming in C, Matlab, little bit of assembly language coding. (ARM assembly, DSP processor assembly).</p> <p>Now I want to improve my assembly language coding skills(it can be any assembly language, doesn't matter) by a big quantum, and take it to an 'expert level'. I know that programming more in it would be the way to it, but what I am asking here is: </p> <ul> <li><p>People's experience in coding in assembly languages(any),which they have gained over years of coding in assembly language.</p></li> <li><p>Guidelines to keep in mind while learning new assembly language</p></li> <li><p>Specific tips and tricks to code efficiently and correctly in assembly languages</p></li> <li><p>How to efficiently convert a given C code into a optimal assembly code</p></li> <li><p>How to clearly understand a given assembly code</p></li> <li><p>How does one keep track of the registers which would have operands in it, stack pointer, program counters, how to be closer in understanding the underlying architecture and the resources it provides for a programmer, etc..</p></li> </ul> <p>Basically I want to get some "real life" tips from people who have done exhaustive and intensive assembly language programming.</p> <p>thank you.</p> <p>-AD</p>
3,199,685
4
6
null
2010-07-07 22:27:10.85 UTC
10
2016-11-14 15:01:38.607 UTC
2013-08-17 20:14:11.007 UTC
null
234,175
null
2,759,376
null
1
9
assembly
4,830
<p>A good place to start would be Jeff Duntemann's book, <em><a href="http://www.duntemann.com/assembly.htm" rel="noreferrer">Assembly Language Step-by-Step</a></em>. The book is about x86 programming under Linux. As I recall, a previous version of the book covered programming under Windows. It's a beginner's book in that it starts at the beginning: bits, bytes, binary arithmetic, etc. You can skip that part if you like, but it might be a good idea to at least skim it.</p> <p>I think the best way to learn ASM coding is by 1) learning the basics of the hardware and then 2) studying others' code. The book I mentioned above is worthwhile. You might also be interested in <a href="http://www.arl.wustl.edu/~lockwood/class/cs306/books/artofasm/toc.html" rel="noreferrer">The Art of Assembly Language Programming</a>.</p> <p>I've done quite a bit of assembly language programming in my time, although not much in the last 15 years or so. As one commenter pointed out, the slight size and performance gains are hard to justify when I take into account the increased development and maintenance time compared to a high level language.</p> <p>That said, I wouldn't discourage you from your quest to become more efficient with ASM. Becoming more familiar with how a processor works at that level can only improve your HLL programming skills, as well.</p>
1,101,174
Difference between using Trace and TraceSource
<p>Anyone knows the difference between <code>System.Diagnostic.Trace</code> and <code>System.Diagnostic.TraceSource</code> classes?</p> <p>I've been using Trace for most of my projects and I just happen to found out about <code>TraceSource</code> the other day. They seems to offer similar API, is one better than the other?</p>
1,101,191
2
0
null
2009-07-08 23:55:57.11 UTC
2
2018-05-21 10:10:36.987 UTC
2016-02-15 15:39:52.977 UTC
null
4,390,133
null
89,299
null
1
34
.net|logging|system.diagnostics|tracesource
9,501
<p>TraceSource is the newer version (since .NET 2) and Trace is the older version, more info is available here:</p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/3b05b16e-a566-4909-8e37-f3d8999d5977" rel="noreferrer">Clarification on TraceSource/Trace</a></p>
2,624,145
Should class IOException in Java have been an unchecked RuntimeException?
<p>Do you agree that the designers of Java class <code>java.io.IOException</code> should have made it an unchecked run-time exception derived from <code>java.lang.RuntimeException</code> instead of a checked exception derived only from <code>java.lang.Exception</code>?</p> <p>I think that class <code>IOException</code> should have been an unchecked exception because there is little that an application can do to resolve problems like file system errors. However, in <a href="http://www.ibm.com/developerworks/java/library/j-ce/index.html" rel="noreferrer">When You Can't Throw An Exception</a>, <a href="http://www.ibm.com/developerworks/java/library/j-ce/index.html#author1" rel="noreferrer">Elliotte Rusty Harold</a> claims that most I/O errors are transient and so you can retry an I/O operation several times before giving up:</p> <blockquote> <p>For instance, an IOComparator might not take an I/O error lying down, but — because many I/O problems are transient — you can retry a few times, as shown in Listing 7:</p> </blockquote> <p>Is this generally the case? Can a Java application correct I/O errors or wait for the system to recover? If so, then it is reasonable for IOException to be checked, but if it is not the case, then IOException should be unchecked so that business logic can delegate handling of this exception to a separate system error handler.</p>
2,624,237
6
9
null
2010-04-12 17:51:37.067 UTC
7
2016-05-17 17:00:49.737 UTC
2010-04-12 19:07:30.46 UTC
null
107,158
null
107,158
null
1
28
java|exception|exception-handling
17,738
<p>I completely disagree. To me the model is correct. A RuntimeException is one which most typically denotes a serious error in the logic of the programming (such as ArrayIndexOutOfBounds, NullPointer, or IllegalArgument) or something that the runtime has otherwise determined really shouldn't be happening (such as SecurityException). </p> <p>Conversely IOException and its derivatives are exceptions that could reasonably occur during normal execution of a program, and common logic would dictate that either those problems should be dealt with, or at least the programmer should be aware that they can occur. For example with Files if your application logger can't write its data would you rather be forced to catch a potential IOException and recover, or have something that may not be critical to your app bring down the whole JVM because no one thought to catch the unchecked Exception (as you may have guessed, I'll choose the former).</p> <p>I think that there are many situations in which an IOException is either recoverable, or at the least the programmer should be explicitly aware of the potential so that if it is not recoverable the system might be able to crash more "gently". </p> <p>As far your thought of if the system can not recover there are always alternatives with a checked exception. You can always have your methods declare it in their throws, throw a runtime exception of their own or crash the JVM violently:</p> <pre><code>public void doit() throws IOException { try{ }catch(IOException e){ // try to recover ... // can't recover throw e; } } public void doit() { try{ }catch(IOException e){ // try to recover ... // can't recover throw new RuntimeException(e); } } public void doit() { try{ }catch(IOException e){ // try to recover ... // OH NO!!!! System.exit(Constant.UNRECOVERABLE_IO_ERROR); } } </code></pre>
2,673,075
How to get span tag inside a div in jQuery and assign a text?
<p>I use the following ,</p> <pre><code>&lt;div id='message' style="display: none;"&gt; &lt;span&gt;&lt;/span&gt; &lt;a href="#" class="close-notify"&gt;X&lt;/a&gt; &lt;/div&gt; </code></pre> <p>Now i want to find the span inside the div and assign a text to it...</p> <pre><code>function Errormessage(txt) { $("#message").fadeIn("slow"); // find the span inside the div and assign a text $("#message a.close-notify").click(function() { $("#message").fadeOut("slow"); }); } </code></pre>
2,673,081
6
0
null
2010-04-20 06:36:53.867 UTC
7
2021-05-23 06:29:00.78 UTC
2010-04-20 06:39:45.967 UTC
null
126,039
null
207,556
null
1
31
jquery|find|elements
180,129
<p>Try this:</p> <pre><code>$("#message span").text("hello world!"); </code></pre> <p>See it in your code!</p> <pre><code>function Errormessage(txt) { var m = $("#message"); // set text before displaying message m.children("span").text(txt); // bind close listener m.children("a.close-notify").click(function(){ m.fadeOut("slow"); }); // display message m.fadeIn("slow"); } </code></pre>
3,158,004
How do I set the height of a ComboBox?
<p>I have a ComboBox on a form, and its default height is 21. How do I change it?</p>
3,158,801
7
0
null
2010-07-01 12:59:50.3 UTC
3
2019-06-22 08:37:28.607 UTC
2015-05-17 11:30:27.847 UTC
null
63,550
null
290,621
null
1
33
c#|.net|winforms|combobox
68,982
<p>ComboBox auto-sizes to fit the font. Turning that off is not an option. If you want it bigger then give it a bigger font.</p>
2,339,735
fabric password
<p>Every time fabric runs, it asks for root password, can it be sent along same for automated proposes.</p> <pre><code>fab staging test </code></pre>
2,339,767
7
2
null
2010-02-26 05:48:50.043 UTC
16
2018-12-29 11:58:55.493 UTC
null
null
null
null
196,169
null
1
41
python|fabric
44,552
<p><code>fab -h</code> will show you all the options, you can also read them <a href="http://docs.fabfile.org/en/1.10/usage/fab.html#command-line-options" rel="noreferrer">here</a>.</p> <p>In particular, and I quote,</p> <blockquote> <p>-p PASSWORD, --password=PASSWORD</p> <p>Sets env.password to the given string; it will then be used as the default password when making SSH connections or calling the sudo program.</p> </blockquote>
2,445,756
How can I calculate audio dB level?
<p>I want to calculate room noise level with the computer's microphone. I record noise as an audio file, but how can I calculate the noise dB level?</p> <p>I don't know how to start!</p>
9,812,267
8
3
null
2010-03-15 08:05:20.79 UTC
45
2022-02-14 06:32:21.983 UTC
2012-03-21 20:27:36.433 UTC
null
968,261
null
293,790
null
1
62
audio|signal-processing
97,565
<p>All the previous answers are correct if you want a technically accurate or scientifically valuable answer. But if you just want a general estimation of comparative loudness, like if you want to check whether the dog is barking or whether a baby is crying and you want to specify the threshold in dB, then it's a relatively simple calculation.</p> <p>Many wave-file editors have a vertical scale in decibels. There is no calibration or reference measurements, just a simple calculation:</p> <pre><code>dB = 20 * log10(amplitude) </code></pre> <p>The amplitude in this case is expressed as a number between 0 and 1, where 1 represents the maximum amplitude in the sound file. For example, if you have a 16 bit sound file, the amplitude can go as high as 32767. So you just divide the sample by 32767. (We work with absolute values, positive numbers only.) So if you have a wave that peaks at 14731, then:</p> <pre><code>amplitude = 14731 / 32767 = 0.44 dB = 20 * log10(0.44) = -7.13 </code></pre> <p><br/> But there are very important things to consider, specifically the answers given by the others.</p> <p>1) As Jörg W Mittag says, dB is a relative measurement. Since we don't have calibrations and references, this measurement is only relative to itself. And by that I mean that you will be able to see that the sound in the sound file at this point is 3 dB louder than at that point, or that this spike is 5 decibels louder than the background. But you cannot know how loud it is in real life, not without the calibrations that the others are referring to.</p> <p>2) This was also mentioned by PaulR and user545125: Because you're evaluating according to a recorded sound, you are only measuring the sound at the specific location where the microphone is, biased to the direction the microphone is pointing, and filtered by the frequency response of your hardware. A few feet away, a human listening with human ears will get a totally different sound level and different frequencies.</p> <p>3) Without calibrated hardware, you cannot say that the sound is 60dB or 89dB or whatever. All that this calculation can give you is how the peaks in the sound file compares to other peaks in the same sound file.</p> <p>If this is all you want, then it's fine, but if you want to do something serious, like determine whether the noise level in a factory is safe for workers, then listen to Paul, user545125 and Jörg.</p>
2,819,340
Does anyone know a light Vim scheme which makes coding more readable and pleasant?
<p>I know a lot of nice dark schemes for Vim which makes coding more readable and pleasant such as <strong>ir_black, wombat, zenburn</strong>. Its weird but I haven't seen so many popular light themes (white background).</p> <p>Does anyone knows a light Vim scheme which makes code more readable and pleasant to see? (that makes code less confusing to distinguish, something like Visual studio's default scheme?)</p>
2,820,214
9
4
null
2010-05-12 13:44:28.153 UTC
11
2018-04-23 16:54:17.403 UTC
2010-05-12 14:14:00.587 UTC
null
298,479
null
122,536
null
1
27
vim|color-scheme
30,196
<p>With all due bias-based disclaimers and caveats (I am the author of the color scheme), I find that <a href="http://jeetworks.org/post/mayansmoke/" rel="nofollow noreferrer">Mayan Smoke</a> both highly ergonomic as well as aesthetically pleasing (<a href="http://jeetworks.org/post/mayansmoke/" rel="nofollow noreferrer">screenshot</a>). Download page: <a href="http://www.vim.org/scripts/script.php?script_id=3065" rel="nofollow noreferrer">http://www.vim.org/scripts/script.php?script_id=3065</a>.</p> <p>As alternative, you should also have a look at the immensely popular <a href="http://www.vim.org/scripts/script.php?script_id=1492" rel="nofollow noreferrer">Pyte</a>, which is eerily similar to <a href="http://www.vim.org/scripts/script.php?script_id=3065" rel="nofollow noreferrer">Mayan Smoke</a> (development was independent, and the similarity is convergence, I swear!), though the syntax colors are a lot more muted.</p>
3,133,243
How do I get the path to the current script with Node.js?
<p>How would I get the path to the script in Node.js?</p> <p>I know there's <code>process.cwd</code>, but that only refers to the directory where the script was called, not of the script itself. For instance, say I'm in <code>/home/kyle/</code> and I run the following command:</p> <pre><code>node /home/kyle/some/dir/file.js </code></pre> <p>If I call <code>process.cwd()</code>, I get <code>/home/kyle/</code>, not <code>/home/kyle/some/dir/</code>. Is there a way to get that directory?</p>
3,133,313
15
1
null
2010-06-28 14:31:01.823 UTC
174
2022-09-20 13:05:00.943 UTC
2016-12-17 12:03:54.433 UTC
null
63,550
null
135,180
null
1
1,202
node.js
1,000,284
<p>I found it after looking through the documentation again. What I was looking for were the <a href="https://nodejs.org/docs/latest/api/modules.html#modules_filename" rel="noreferrer"><code>__filename</code></a> and <a href="https://nodejs.org/docs/latest/api/modules.html#modules_dirname" rel="noreferrer"><code>__dirname</code></a> module-level variables.</p> <ul> <li><code>__filename</code> is the file name of the current module. This is the resolved absolute path of the current module file. (ex:<code>/home/kyle/some/dir/file.js</code>)</li> <li><code>__dirname</code> is the directory name of the current module. (ex:<code>/home/kyle/some/dir</code>)</li> </ul>
2,865,863
Removing all whitespace lines from a multi-line string efficiently
<p>In C# what's the best way to remove blank lines i.e., lines that contain only whitespace from a string? I'm happy to use a Regex if that's the best solution.</p> <p>EDIT: I should add I'm using .NET 2.0.</p> <hr> <p><em>Bounty update</em>: I'll roll this back after the bounty is awarded, but I wanted to clarify a few things.</p> <p>First, any Perl 5 compat regex will work. This is not limited to .NET developers. The title and tags have been edited to reflect this.</p> <p>Second, while I gave a quick example in the bounty details, it isn't the <em>only</em> test you must satisfy. Your solution <strong>must</strong> remove <strong>all</strong> lines which consist of nothing but whitespace, <strong>as well as the last newline</strong>. If there is a string which, after running through your regex, ends with "/r/n" or <em>any whitespace characters</em>, it fails. </p>
2,865,931
19
4
null
2010-05-19 13:26:22.697 UTC
6
2018-11-12 11:07:53.61 UTC
2017-03-10 18:54:12.227 UTC
null
450,913
null
332,460
null
1
31
c#|regex|string
43,862
<p>If you want to remove lines containing any whitespace (tabs, spaces), try:</p> <pre><code>string fix = Regex.Replace(original, @"^\s*$\n", string.Empty, RegexOptions.Multiline); </code></pre> <p>Edit (for @Will): The simplest solution to trim trailing newlines would be to use <a href="http://msdn.microsoft.com/en-us/library/system.string.trimend.aspx" rel="noreferrer"><code>TrimEnd</code></a> on the resulting string, e.g.:</p> <pre><code>string fix = Regex.Replace(original, @"^\s*$\n", string.Empty, RegexOptions.Multiline) .TrimEnd(); </code></pre>
2,499,794
How to fix a locale setting warning from Perl
<p>When I run <code>perl</code>, I get the warning:</p> <pre>perl: warning: Setting locale failed. perl: warning: Please check that your locale settings: LANGUAGE = (unset), LC_ALL = (unset), LANG = "en_US.UTF-8" are supported and installed on your system. perl: warning: Falling back to the standard locale ("C").</pre> <p>How do I fix it?</p>
2,510,548
47
4
null
2010-03-23 12:27:18.667 UTC
233
2022-09-12 07:45:01.993 UTC
2020-12-04 18:12:47.053 UTC
null
63,550
null
253,944
null
1
743
perl|locale
688,113
<p>Your OS doesn't know about <code>en_US.UTF-8</code>.</p> <p>You didn't mention a specific platform, but I can reproduce your problem:</p> <pre>% uname -a OSF1 hunter2 V5.1 2650 alpha % perl -e exit perl: warning: Setting locale failed. perl: warning: Please check that your locale settings: LC_ALL = (unset), LANG = "en_US.UTF-8" are supported and installed on your system. perl: warning: Falling back to the standard locale ("C").</pre> <p>My guess is you used ssh to connect to this older host from a newer desktop machine. It's common for <code>/etc/ssh/sshd_config</code> to contain</p> <pre><code>AcceptEnv LANG LC_* </code></pre> <p>which allows clients to propagate the values of those environment variables into new sessions.</p> <p>The warning gives you a hint about how to squelch it if you don't require the full-up locale:</p> <pre>% env LANG=C perl -e exit %</pre> <p>or with Bash:</p> <pre>$ LANG=C perl -e exit $ </pre> <p>For a permanent fix, choose one of</p> <ol> <li>On the older host, set the <code>LANG</code> environment variable in your shell's initialization file.</li> <li>Modify your environment on the client side, <em>e.g.</em>, rather than <code>ssh hunter2</code>, use the command <code>LANG=C ssh hunter2</code>.</li> <li>If you have administrator rights, stop ssh from sending the environment variables by commenting out the <code>SendEnv LANG LC_*</code> line in the <em>local</em> <code>/etc/ssh/ssh_config</code> file. (Thanks to <a href="https://askubuntu.com/questions/144235/locale-variables-have-no-effect-in-remote-shell-perl-warning-setting-locale-f/144448#144448">this answer</a>. See <a href="https://bugzilla.mindrot.org/show_bug.cgi?id=1285#c2" rel="noreferrer">Bug 1285</a> for OpenSSH for more.)</li> </ol>
33,883,615
Can I upgrade to the current version of Ruby (2.2.3) on OS X v10.6.8?
<p>I'm looking at "<a href="http://railsapps.github.io/installrubyonrails-mac.html" rel="noreferrer">Install Ruby on Rails · Mac OS X Yosemite</a>", and in the instructions it says to update your OS which I don't really want to do because my computer is getting old.</p> <p>I also found "<a href="https://stackoverflow.com/questions/3696564/how-to-update-ruby-to-1-9-x-on-mac">How to update Ruby to 1.9.x on Mac?</a>". As far as I can tell, I don't have RVM and I'm afraid of yet another install, in case my system requirements still aren't good enough.</p> <p>Ultimately, I'm trying to update Jekyll, but I need to update my system a little bit first. I need Ruby 1.9.3 or later. Will "How to update Ruby to 1.9.x on Mac?" work? I'm running Ruby 1.8.7 (2012-02-08 patchlevel 358) [universal-darwin10.0]'. </p> <p>EDIT: I did end up getting RVM installed. For those who find this page in the future, I ran into these issues/help pages:</p> <ul> <li><a href="https://stackoverflow.com/questions/27041885/how-to-resolve-gpg-command-not-found-error-during-rvm-installation">How to resolve &quot;gpg: command not found&quot; error during RVM installation?</a></li> <li><a href="https://stackoverflow.com/questions/19636779/os-x-mavericks-install-rvm-warning">OS X Mavericks install rvm WARNING</a> <code>* WARNING: You have '~/.profile' file...</code></li> <li><a href="https://stackoverflow.com/questions/16427711/rvm-installation-missing-path">RVM installation missing $PATH</a> <code>* WARNING: Above files contains</code>PATH=<code>with no</code>$PATH<code>inside</code></li> </ul>
33,883,667
4
2
null
2015-11-24 00:54:29.873 UTC
24
2017-07-13 10:28:05.93 UTC
2017-05-23 11:55:01.607 UTC
null
-1
null
5,590,856
null
1
69
ruby|macos|terminal
99,136
<p>I suggest that you use <a href="https://rvm.io" rel="noreferrer">RVM</a> to install Ruby.</p> <pre><code>curl -sSL https://get.rvm.io | bash -s stable --ruby </code></pre> <p>You need to restart the terminal in order to run rvm:</p> <pre><code>rvm install 2.2 rvm use 2.2 --default </code></pre>
10,295,371
Finding all the markers inside a given radius
<p>Input: Given a specific co-ordinate (latitude and longitude) and radius Output: Displaying all the markers which reside under that circle from given list of markers.</p> <p>How can I do this in google maps? </p>
10,295,501
5
0
null
2012-04-24 09:40:48.95 UTC
29
2020-02-04 21:43:58.277 UTC
2012-04-24 11:08:42.713 UTC
null
100,339
null
1,324,389
null
1
25
javascript|algorithm|google-maps
75,140
<p>Just iterate all the markers you have and use the following function to get the distance from the specific co-ordinate to the marker: <code>computeDistanceBetween()</code>:</p> <blockquote> <p>To compute this distance, call computeDistanceBetween(), passing it two LatLng objects.</p> </blockquote> <p>I found it over <a href="https://developers.google.com/maps/documentation/javascript/geometry?hl=en#Distance" rel="noreferrer">here</a>. Then just filter out all the markers that turn out to be close enough.</p>
10,741,609
Copy file remotely with PowerShell
<p>I am writing a <em>PowerShell</em> script that I want to run from Server A. I want to connect to Server B and copy a file to Server A as a backup.</p> <p>If that can't be done then I would like to connect to Server B from Server A and copy a file to another directory in Server B.</p> <p>I see the <a href="https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Management/Copy-Item" rel="noreferrer"><code>Copy-Item</code></a> command, but I don't see how to give it a computer name.</p> <p>I would have thought I could do something like</p> <pre><code>Copy-Item -ComputerName ServerB -Path C:\Programs\temp\test.txt -Destination (not sure how it would know to use ServerB or ServerA) </code></pre> <p>How can I do this?</p>
10,743,531
5
0
null
2012-05-24 16:30:38.363 UTC
33
2021-07-20 18:54:45.07 UTC
2019-06-24 16:41:44.557 UTC
null
63,550
null
130,015
null
1
112
powershell|powershell-2.0
411,387
<p>Simply use the administrative shares to copy files between systems. It's much easier this way.</p> <pre><code>Copy-Item -Path \\serverb\c$\programs\temp\test.txt -Destination \\servera\c$\programs\temp\test.txt; </code></pre> <p>By using UNC paths instead of local filesystem paths, you help to ensure that your script is executable from any client system with access to those UNC paths. If you use local filesystem paths, then you are cornering yourself into running the script on a specific computer.</p>
6,032,709
How to center-align an HTML child table within a parent table via CSS
<p>I have the following HTML table format:</p> <pre><code>&lt;table style="width: 100%;"&gt; &lt;tr&gt; &lt;td&gt; //How to center this table within the parent-table cell? &lt;table style="width: 760px;"&gt; &lt;tr&gt; &lt;td&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>Since HTML5 doesn't support the 'align=center' for tables, I am trying to figure out how to simulate the 'align=center' in CSS for the sub-table in my example above.</p> <p>I've tried messin' around with the CSS margin attribute to no avail. </p> <p>How do I center the sub-table in the example above?</p>
6,032,784
2
0
null
2011-05-17 14:52:37.193 UTC
null
2018-09-06 09:45:43.213 UTC
null
null
null
null
171,142
null
1
5
css|html|formatting
42,211
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>table {border:solid 1px #0f0} table table {border:solid 1px #f00;margin: 0 auto}</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;table style="width: 100%;"&gt; &lt;tr&gt; &lt;td&gt; //How to center this table within the parent-table cell? &lt;table style="width: 760px;"&gt; &lt;tr&gt; &lt;td&gt; Center This Table Dawg &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt;</code></pre> </div> </div> </p> <p><code>margin:0 auto;</code> worked in this example, tested/worked in IE 7-9, FF 4, Chrome 11</p>
31,088,292
Laravel php artisan db:seed leads to "use" statement error
<p>When I try to run <code>php artisan db:seed</code> I get the following error:</p> <p><code>The use statement with non-compound name 'DB' has no effect</code></p> <p>I have written my own seeder file which I have included below, based on a <a href="http://laravel.com/docs/5.1/seeding#writing-seeders" rel="noreferrer">snippet from the doc</a>. As you can see I am using the <code>use DB</code> shortcut - is this what the problem is?</p> <pre><code>&lt;?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; use DB; class ClassesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { DB::table('classes')-&gt;delete(); DB::table('classes')-&gt;insert([ 'class_name' =&gt; 'Test course 111', 'class_id' =&gt; '1', 'location_name' =&gt; 'Barnes', 'location_id' =&gt; '1', 'date' =&gt; '2015-06-22', 'month' =&gt; '06/2015', 'start_time' =&gt; '08:00', 'end_time' =&gt; '16:00', 'places' =&gt; '19', 'places_left' =&gt; '19', 'price' =&gt; '155.00' ]); } } </code></pre>
31,088,350
5
0
null
2015-06-27 11:35:26.647 UTC
4
2021-08-10 07:20:49.84 UTC
2015-08-15 17:59:50.287 UTC
null
158,074
null
3,595,549
null
1
28
php|laravel|laravel-5|laravel-artisan
27,381
<p>In PHP the <strong>use</strong> statement is more of an <strong>alias</strong> than import. So since the <strong>ClassesTableSeeder</strong> class isn't in a defined namespace, you don't need to import the DB class. As a result you can remove <strong>use DB</strong> entirely.</p>
30,864,619
Does JSON-LD have to be embedded?
<p>We are currently using the Microdata format to expose data to search engines and we are looking at exposing more info to be able to support some more advanced Google Search features. As I'm working my way through the fields I'm finding I need information that we currently load asynchronously so it is not a part of the initial response. </p> <p>JSON-LD looks like its what Google prefers but all the examples I've seen have it embedded in the page. Could you have a link to a JS file so it gets loaded as a separate call? Something like</p> <pre class="lang-html prettyprint-override"><code>&lt;script type="application/ld+json" src="/myid123/jsonld.js"&gt;&lt;/script&gt; </code></pre>
30,880,613
1
1
null
2015-06-16 10:11:23.677 UTC
11
2016-02-12 13:37:50.983 UTC
2015-06-17 00:55:23.9 UTC
null
1,591,669
null
2,268,479
null
1
28
html|google-search|json-ld
8,206
<p>If you are using the <a href="http://www.w3.org/TR/2014/REC-html5-20141028/scripting-1.html#the-script-element" rel="noreferrer"><code>script</code> element</a> as data block, "the <code>src</code> attribute must not be specified".</p> <p>If the <code>script</code> element is <em>not</em> used as data block, it has to be "used to include dynamic scripts". But a JSON-LD document is not a dynamic script.</p> <p>For linking to another resource, just like you do it with external stylesheets or Favicons, you can use the <code>link</code> element in the <code>head</code> (or the corresponding HTTP header):</p> <pre class="lang-html prettyprint-override"><code>&lt;link href="/myid123/jsonld.js" rel="alternate" type="application/ld+json" /&gt; </code></pre> <p>In principle, consumers could follow this reference (possibly only if a certain <a href="https://stackoverflow.com/a/12450872/1591669">link type</a> is specified), and make use of data, just like they do it with embedded JSON-LD, Microdata, or RDFa. </p> <p>However, consumers don’t <em>have</em> to do this, of course, and many probably don’t.<br> Google Search in particular does not claim to support it for consuming Schema.org in the JSON-LD format. However, they claim to <a href="https://stackoverflow.com/a/29066759/1591669">support "dynamically injected" JSON-LD data blocks</a>.</p>
52,403,065
Argparse optional boolean
<p>I am trying to get the following behaviour:</p> <ul> <li><code>python test.py</code> ⟹ store <code>foo=False</code></li> <li><code>python test.py --foo</code> ⟹ store <code>foo=True</code></li> <li><code>python test.py --foo bool</code> ⟹ store <code>foo=bool</code></li> </ul> <p>It works when I use</p> <pre class="lang-py prettyprint-override"><code>parser.add_argument('--foo', nargs='?', default=False, const=True) </code></pre> <p>However, it breaks if I add <code>type=bool</code>, trying to enforce casting to boolean. In this case</p> <pre class="lang-sh prettyprint-override"><code>python test.py --foo False </code></pre> <p>Actually ends up storing <code>foo=True</code>. What's going on??</p>
52,403,318
2
1
null
2018-09-19 09:53:50.917 UTC
5
2022-01-21 16:12:41.38 UTC
2022-01-21 16:12:41.38 UTC
null
9,318,372
null
9,318,372
null
1
44
python|python-3.x|argparse
49,530
<p>Are you <em>sure</em> you need that pattern? <code>--foo</code> and <code>--foo &lt;value&gt;</code>, together, for a boolean switch, is not a common pattern to use.</p> <p>As for your issue, remember that the command line value is a <em>string</em> and, <code>type=bool</code> means that you want <code>bool(entered-string-value)</code> to be applied. For <code>--foo False</code> that means <code>bool(&quot;False&quot;)</code>, producing <code>True</code>; all non-empty strings are true! See <a href="https://stackoverflow.com/questions/41655897/why-is-argparse-not-parsing-my-boolean-flag-correctly">Why is argparse not parsing my boolean flag correctly?</a> as well.</p> <p>Instead of supporting <code>--foo</code> / <code>--foo &lt;string value&gt;</code>, I would <em>strongly</em> recommend you use <code>--foo</code> to mean <code>True</code>, drop the argument value, and instead add a <code>--no-foo</code> option to explicitly set <code>False</code>:</p> <pre><code>parser.add_argument('--foo', default=False, action='store_true') parser.add_argument('--no-foo', dest='foo', action='store_false') </code></pre> <p>The <code>dest='foo'</code> addition on the <code>--no-foo</code> switch ensures that the <code>False</code> value it stores (via <code>store_false</code>) ends up on the same <code>args.foo</code> attribute.</p> <p>As of Python 3.9, you can also use the <code>argparse.BooleanOptionalAction</code> action class:</p> <pre><code>parser.add_argument(&quot;--foo&quot;, action=argparse.BooleanOptionalAction) </code></pre> <p>and it'll have the same effect, handling <code>--foo</code> and <code>--no-foo</code> to set and clear the flag.</p> <p>You'd only need a <code>--foo / --no-foo</code> combination if you have some other configuration mechanism that would set <code>foo</code> to <code>True</code> and you needed to override this again with a command-line switch. <code>--no-&lt;option&gt;</code> is a widely adopted standard to invert a boolean command-line switch.</p> <p>If you <em>don't</em> have a specific need for a <code>--no-foo</code> inverted switch (since just <em>omitting</em> <code>--foo</code> would already mean 'false'), then just stick with the <code>action='store_true'</code> option. This keeps your command line simple and clear!</p> <p>However, if your use case or other constraints specifically require that your command line <em>must</em> have some king of <code>--foo (true|false|0|1)</code> support, then add your own converter:</p> <pre><code>def str_to_bool(value): if isinstance(value, bool): return value if value.lower() in {'false', 'f', '0', 'no', 'n'}: return False elif value.lower() in {'true', 't', '1', 'yes', 'y'}: return True raise ValueError(f'{value} is not a valid boolean value') parser.add_argument('--foo', type=str_to_bool, nargs='?', const=True, default=False) </code></pre> <ul> <li>the <code>const</code> value is used for <code>nargs='?'</code> arguments where the argument value is omitted. Here that sets <code>foo=True</code> when <code>--foo</code> is used.</li> <li><code>default=False</code> is used when the switch is not used at all.</li> <li><code>type=str_to_bool</code> is used to handle the <code>--foo &lt;value&gt;</code> case.</li> </ul> <p>Demo:</p> <pre><code>$ cat so52403065.py from argparse import ArgumentParser parser = ArgumentParser() def str_to_bool(value): if value.lower() in {'false', 'f', '0', 'no', 'n'}: return False elif value.lower() in {'true', 't', '1', 'yes', 'y'}: return True raise ValueError(f'{value} is not a valid boolean value') parser.add_argument('--foo', type=str_to_bool, nargs='?', const=True, default=False) print(parser.parse_args()) $ python so52403065.py Namespace(foo=False) $ python so52403065.py --foo Namespace(foo=True) $ python so52403065.py --foo True Namespace(foo=True) $ python so52403065.py --foo no Namespace(foo=False) $ python so52403065.py --foo arrbuggrhellno usage: so52403065.py [-h] [--foo [FOO]] so52403065.py: error: argument --foo: invalid str_to_bool value: 'arrbuggrhellno' </code></pre>
21,570,751
Difference between CLOB and BLOB from DB2 and Oracle Perspective?
<p>I have been pretty much fascinated by these two data types. According to <strong><a href="http://docs.oracle.com/cd/E35137_01/doc.32/e18460/oracle_db2_compared.htm">Oracle Docs</a></strong>, they are presented as follows :</p> <p><strong>BLOB :</strong> Variable-length binary large object string that can be up to 2GB (2,147,483,647) long. Primarily intended to hold non-traditional data, such as voice or mixed media. BLOB strings are not associated with a character set, as with FOR BIT DATA strings.</p> <p><strong>CLOB :</strong> Variable-length character large object string that can be up to 2GB (2,147,483,647) long. A CLOB can store single-byte character strings or multibyte, character-based data. A CLOB is considered a character string.</p> <p>What I don't know, is whether there is any difference between the two from DB2 and Oracle perspective? I mean, what are the differences between DB2 CLOB and Oracle CLOB, also between DB2 BLOB and Oracle BLOB? What is the maximum size of both in DB2 and Oracle? Is it just 2 GB ?</p>
42,073,438
3
0
null
2014-02-05 07:09:10.837 UTC
28
2017-02-06 17:10:46.213 UTC
2016-09-06 15:04:15.727 UTC
null
4,823,977
null
1,697,798
null
1
116
database|oracle|db2|blob|clob
212,445
<p><strong>BLOB</strong> is for binary data (<strong>videos, images, documents, other</strong>)</p> <p><strong>CLOB</strong> is for large text data (<strong>text</strong>)</p> <p>Maximum size on MySQL 2GB</p> <p>Maximum size on Oracle 128TB</p>
54,299,958
How can I set the AWS API Gateway timeout higher than 30 seconds?
<p>I read here that I can set my Lambda function timeout for 15 minutes (<a href="https://aws.amazon.com/about-aws/whats-new/2018/10/aws-lambda-supports-functions-that-can-run-up-to-15-minutes/" rel="noreferrer">https://aws.amazon.com/about-aws/whats-new/2018/10/aws-lambda-supports-functions-that-can-run-up-to-15-minutes/</a>)</p> <p>However, when I try to set API Gateway inside the Integration Request settings, it does not allow me to set it higher than 29seconds:</p> <p><a href="https://i.stack.imgur.com/FeDTz.png" rel="noreferrer"><img src="https://i.stack.imgur.com/FeDTz.png" alt="Timeout max is 29 seconds"></a></p> <p>How can I have a function that lasts 15 minutes, but a Gateway that time outs after 30 seconds?</p>
54,300,708
5
0
null
2019-01-22 01:20:09.34 UTC
6
2022-02-18 13:30:00.047 UTC
2019-01-22 01:38:45.587 UTC
null
688,266
null
688,266
null
1
35
aws-lambda
38,124
<p>Unfortunately there isn't a way to increase the API Gateway timeout to longer than 29 seconds. This is a limitation of the gateway. The reason you can set the lambda function longer is because this can be plugged into other AWS resources that allow a higher threshold for timeout processing.</p> <p>Here's some options you could explore to get around this and/or work with the limitation:</p> <ol> <li><p>Split your function out into smaller functions and chain those together to see if you get a performance increase. Before doing so you could use AWS X-Ray to debug the function and see what part is taking the most time to target what needs to be split out.</p></li> <li><p>Increase the memory used by the function. Higher memory allocation could result in faster execution. I have used this option before and was able to work around timeout limits.</p></li> <li><p>Instead of using API Gateway you could just use AWS SDK to call 'invoke()' which will invoke your lambda function. This will bypass the timeout threshold.</p></li> </ol> <p>Hopefully one or a mix of those will help out :)</p>