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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
648,156 | Backslashes in single quoted strings vs. double quoted strings | <p>If I add a backslash+space to the start of double and single quoted strings, I get different results:</p>
<pre><code>"\ text"
'\ text'
</code></pre>
<p>In the output for the double quoted string I see only a space.<br>
In the output for the single quoted string I see backslash+space.</p>
<p>What's happening there? Is this because <code>'\ '</code> is interpreted as a special character in the double quote string but in the single quoted string the characters are preserved as is?</p>
<p>If I change the strings to this, I see the same output, namely a single slash followed by a space and then the text:</p>
<pre><code>"\\ text"
'\\ text'
</code></pre>
<p>In both cases the backslash is escaped. I'm confused why they work the same way in this situation. </p>
<p>Is there some rule that would help to explain the fundamental difference between how single quoted strings and double quoted strings handle backslashes in Ruby?</p> | 648,187 | 6 | 1 | null | 2009-03-15 17:08:00.157 UTC | 7 | 2018-10-04 07:54:35.987 UTC | 2015-12-04 11:10:55.4 UTC | Tucker | 314,166 | Tucker | 78,308 | null | 1 | 29 | ruby|string|quotes|literals|backslash | 30,387 | <p>I'd refer you to "<a href="http://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes" rel="nofollow noreferrer">Ruby Programming/Strings</a>" for a very concise yet comprehensive overview of the differences.</p>
<p>From the reference:</p>
<blockquote>
<p><code>puts "Betty's pie shop"</code></p>
<p><code>puts 'Betty\'s pie shop'</code></p>
<p>Because "Betty's" contains an apostrophe, which is the same character as the single quote, in the second line we need to use a backslash to escape the apostrophe so that Ruby understands that the apostrophe is in the string literal instead of marking the end of the string literal. The backslash followed by the single quote is called an escape sequence.</p>
</blockquote> |
21,640 | .NET - Get protocol, host, and port | <p>Is there a simple way in .NET to quickly get the current protocol, host, and port? For example, if I'm on the following URL:</p>
<p><code>http://www.mywebsite.com:80/pages/page1.aspx</code></p>
<p>I need to return:</p>
<p><code>http://www.mywebsite.com:80</code></p>
<p>I know I can use <code>Request.Url.AbsoluteUri</code> to get the complete URL, and I know I can use <code>Request.Url.Authority</code> to get the host and port, but I'm not sure of the best way to get the protocol without parsing out the URL string.</p>
<p>Any suggestions?</p> | 22,361 | 7 | 1 | null | 2008-08-22 02:18:28.307 UTC | 41 | 2021-10-22 10:17:34.187 UTC | 2018-07-19 08:57:52.063 UTC | null | 133 | Jeremy Kratz | 2,076,253 | null | 1 | 258 | .net|asp.net|url|uri|authority | 182,962 | <p>The following (C#) code should do the trick</p>
<pre><code>Uri uri = new Uri("http://www.mywebsite.com:80/pages/page1.aspx");
string requested = uri.Scheme + Uri.SchemeDelimiter + uri.Host + ":" + uri.Port;
</code></pre> |
30,995,343 | String comparison in AngularJS | <p>I'm trying to compare two strings in AngularJS, and I've seen examples online. As I understand it, you can use angular.equals(str1, str2), you can use ===, you can use == if you're sure that both are strings...</p>
<p>I've tried all three, but I don't get the result. Something must be wrong in what I've done, but I don't know what it is. </p>
<p>When I run the code, the inc1() function is called. The first alert appears "inc1 called". But the second alert, "Inside for loop", executes only once. It should execute twice, shouldn't it?</p>
<p>And the alert inside of the if(condition) does not execute at all. If I remove the 'if' block, then the alert "Inside for loop" runs two times.</p>
<p>I'd be much obliged if someone could tell me what I'm doing wrong here. I've used angular.equals(), === and ==, but the same thing happens everytime. </p>
<p>This is how the HTML and AngularJS codes go:</p>
<p>HTML:</p>
<pre><code><a class="tab-item" ng-repeat = "x in items" ng-if="name==x.names" ng-click="inc1(name)">
<i class="icon ion-thumbsup"></i>
Like
</a>
</code></pre>
<p>AngularJS:</p>
<pre><code>$rootScope.items = [
{ id: 1, names: 'Dolphin', image: 'dolphin.jpg'}, { id: 2, names: 'Donkey', image: 'donkey.jpg'}];
$scope.inc1 = function(name) {
alert("inc1 called");
for(var i=0;i<$rootScope.items.length;i++)
{
alert("Inside for loop");
if (name === $rootScope.items.names[i])
{
alert("If condition satisfied");
}
}
}
</code></pre>
<p>//Say, name is 'Dolphin'</p> | 30,995,384 | 3 | 2 | null | 2015-06-23 06:27:29.497 UTC | null | 2015-06-23 07:02:57.727 UTC | null | null | null | null | 5,014,044 | null | 1 | 5 | javascript|json|angularjs|ionic-framework|string-comparison | 46,517 | <p>You are iterating over wrong node:)</p>
<pre><code>for(var i=0;i<$rootScope.items.length;i++)
{
alert("Inside for loop");
if (name === $rootScope.items[i].names) // you iterate over items, not names, which it an Json property inside item
{
alert("If condition satisfied");
}
}
</code></pre> |
37,728,087 | What does "rc" in matplotlib's rcParams stand for? | <p><code>matplotlibrc</code> configuration files are used to customize all kinds of properties in <code>matplotlib</code>. One can change the <code>rc</code> settings to customize the default parameters e.g:</p>
<pre><code>matplotlib.rcParams['font.family'] = 'times new roman'
</code></pre>
<p><strong>... but what does "<code>rc</code>" stand for?</strong></p>
<p>I can't find any explanation in <a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.rc.html" rel="noreferrer">the docs</a></p> | 37,728,339 | 1 | 5 | null | 2016-06-09 13:58:56.17 UTC | 23 | 2021-04-20 13:58:49.417 UTC | 2021-04-20 13:58:49.417 UTC | null | 9,067,615 | null | 2,050,686 | null | 1 | 69 | python|matplotlib|configuration|naming-conventions|configuration-files | 33,091 | <p>It's common to end configuration files in 'rc' - e.g. '.xinitrc', '.vimrc' and '.bashrc'.</p>
<p>It stems from practice of having your configs executable - they are automatically <strong>R</strong>un at startup and they <strong>C</strong>onfigure your stuff.</p>
<p>This started <a href="http://www.catb.org/jargon/html/R/rc-file.html" rel="noreferrer">long ago</a>, even before Unix:</p>
<blockquote>
<p>[Unix: from runcom files on the CTSS system 1962-63, via the startup script /etc/rc] Script file containing startup instructions for an application program (or an entire operating system), usually a text file containing commands of the sort that might have been invoked manually once the system was running but are to be executed automatically each time the system starts up.</p>
</blockquote> |
21,137,150 | Format / Suppress Scientific Notation from Pandas Aggregation Results | <p>How can one modify the format for the output from a groupby operation in pandas that produces scientific notation for very large numbers? </p>
<p>I know how to do string formatting in python but I'm at a loss when it comes to applying it here. </p>
<pre><code>df1.groupby('dept')['data1'].sum()
dept
value1 1.192433e+08
value2 1.293066e+08
value3 1.077142e+08
</code></pre>
<p>This suppresses the scientific notation if I convert to string but now I'm just wondering how to string format and add decimals. </p>
<pre><code>sum_sales_dept.astype(str)
</code></pre> | 21,140,339 | 8 | 3 | null | 2014-01-15 12:14:36.607 UTC | 68 | 2022-07-11 09:03:48.19 UTC | 2022-02-18 17:03:18.653 UTC | null | 355,230 | null | 2,329,714 | null | 1 | 244 | python|pandas|floating-point|scientific-notation|number-formatting | 322,811 | <p>Granted, the answer I linked in the comments is not very helpful. You can specify your own string converter like so.</p>
<pre><code>In [25]: pd.set_option('display.float_format', lambda x: '%.3f' % x)
In [28]: Series(np.random.randn(3))*1000000000
Out[28]:
0 -757322420.605
1 -1436160588.997
2 -1235116117.064
dtype: float64
</code></pre>
<p>I'm not sure if that's the preferred way to do this, but it works.</p>
<p>Converting numbers to strings purely for aesthetic purposes seems like a bad idea, but if you have a good reason, this is one way:</p>
<pre><code>In [6]: Series(np.random.randn(3)).apply(lambda x: '%.3f' % x)
Out[6]:
0 0.026
1 -0.482
2 -0.694
dtype: object
</code></pre> |
17,892,702 | How has soundcloud hidden the URL of streaming audio | <p>I am trying to hide the URL of my audio streams for my HTML5 player and was really struggling to think of a way to do so and then I realised, soundcloud must hide the URL's of their streams. So i went onto soundcloud, opened up the console and played a track but I couldn't see any obvious way that the URL is hidden. After this I took a look at the DOM tree to see if there was any kind of audio information in there but I found nothing! There's not even an ID for the player/audio so i'm very confused as to how soundcloud have done it. </p>
<p>Now I have done as best as I can so far with hiding the audio URL. I have put an ID in the DOM for the track, got that ID when the play button is clicked and retrieved the URL for that ID from the database. The obvious problem with that is that anyone willing enough can just go to the console and get the URL from the network events. </p>
<p>I am not trying to break past soundcloud's security to download tracks I shouldn't be. I'm just curious as to how they've hidden the URL. Now i'm also curious as to how each track is distinguished as there's nothing in the DOM distinguishing them (not that I found on my brief look anyway).</p>
<p>So, in short, does anyone have any ideas on how soundcloud has achieved this or how this could be achieved? </p> | 17,892,881 | 3 | 0 | null | 2013-07-26 23:43:33.05 UTC | 15 | 2016-11-04 22:33:11.347 UTC | null | null | null | null | 1,420,724 | null | 1 | 17 | javascript|html|audio|soundcloud | 19,084 | <p>Soundcloud is pretty much a pure JS site.</p>
<p>As you said, there is no ID of the song loaded with the HTML. The way songs are recognized is by the page URL. The is done via. this url (example):</p>
<p><code>https://api.sndcdn.com/resolve?url=https%3A//soundcloud.com/hoodinternet/joywave-tongues-hood-internet-remix&_status_code_map%5B302%5D=200&_status_format=json&client_id=YOUR_CLIENT_ID</code></p>
<p>This returns something like this:</p>
<p><code>{"status":"302 - Found","location":"https://api.soundcloud.com/tracks/100270342?client_id=YOUR_CLIENT_ID"}</code></p>
<p>Next up it loads the location URL, from the JSON above. This returns a bunch of information about the track, including:</p>
<p><code>stream_url: "https://api.soundcloud.com/tracks/100270342/stream"</code></p>
<p>Then it loads this URL:</p>
<p><code>https://api.sndcdn.com/i1/tracks/100270342/streams?client_id=YOUR_CLIENT_IT</code></p>
<p>Which returns a response like this:</p>
<p><code>{"http_mp3_128_url":"https://ec-media.soundcloud.com/2gNVBYiZ06bU.128.mp3?ff61182e3c2ecefa438cd021sdf02d0e385713f0c1faf3b0339595664fe070de810d30a8e3a1186eda958909e9ed97799adfeceabc135efac83aee4271217a108450591db3b88\u0026AWSAccessKeyId=AKIAsdfJ4IAZE5EOIdsf7PA7VQ\u0026Expires=1374883403\u0026Signature=%2B1%2B7dfdfLN4NWP3C3bNF3gizSEVIU%3D"}</code></p>
<p>So that's how they hide their stream URL's. The only non obvious part is that they find the song ID, by hitting an API with the URL as a parameter. Same can be done with download URL's on tracks that support it.</p> |
17,781,709 | How to Concat String in SQL WHERE clause | <p>I have declared two variables in RAW sql</p>
<pre><code>DECLARE @str nvarchar(max), @str1 nvarchar (max);
SET @str = " AND (c.BondSales_Confirmed <> -1)";
SET @str1 = " AND (c.BondSales_IssueType = 'REGULAR')";
</code></pre>
<p>My SQL query is:</p>
<pre><code>SELECT * From t_BondSales Where (BondSales_cType <> 'Institute') " + str1 + str "
</code></pre>
<p>Here I get the following error: </p>
<blockquote>
<p>Error: SQL Problems: Incorrect Syntax near "+ str1 + str"</p>
</blockquote>
<p>Can any one Please help me with the proper syntax about how to concat String in where clause?</p> | 17,781,833 | 3 | 1 | null | 2013-07-22 07:03:21.61 UTC | 1 | 2013-11-08 21:29:59.793 UTC | 2013-07-22 07:12:45.557 UTC | null | 135,566 | null | 1,891,088 | null | 1 | 11 | sql|sql-server|where-clause|string-concatenation | 82,872 | <p>Try this one -</p>
<pre><code>DECLARE
@str NVARCHAR(MAX)
, @str1 NVARCHAR (MAX);
SELECT
@str = ' AND c.BondSales_Confirmed != -1'
, @str1 = ' AND c.BondSales_IssueType = ''REGULAR''';
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
SELECT *
FROM t_BondSales
WHERE BondSales_cType != ''Institute'''
+ @str
+ @str1
PRINT @SQL
EXEC sys.sp_executesql @SQL
</code></pre> |
18,105,547 | How to find all SQL Agent Jobs that call a given stored-proc | <p>I'm in SQL 2008/R2. I want to run a query to see if there is a SQL Agent job calling a specified stored proc (there are too many to inspect manually). </p> | 18,105,671 | 3 | 2 | null | 2013-08-07 14:03:32.13 UTC | 8 | 2016-11-01 12:32:16.197 UTC | null | null | null | null | 160,245 | null | 1 | 26 | sql-server-2008|tsql|agent | 67,271 | <p>Here is a query that will give you that and more (look at the <code>WHERE</code> clause for the stored proc name):</p>
<pre><code>SELECT
[sJOB].[job_id] AS [JobID]
, [sJOB].[name] AS [JobName]
, [sJSTP].[step_uid] AS [StepID]
, [sJSTP].[step_id] AS [StepNo]
, [sJSTP].[step_name] AS [StepName]
, CASE [sJSTP].[subsystem]
WHEN 'ActiveScripting' THEN 'ActiveX Script'
WHEN 'CmdExec' THEN 'Operating system (CmdExec)'
WHEN 'PowerShell' THEN 'PowerShell'
WHEN 'Distribution' THEN 'Replication Distributor'
WHEN 'Merge' THEN 'Replication Merge'
WHEN 'QueueReader' THEN 'Replication Queue Reader'
WHEN 'Snapshot' THEN 'Replication Snapshot'
WHEN 'LogReader' THEN 'Replication Transaction-Log Reader'
WHEN 'ANALYSISCOMMAND' THEN 'SQL Server Analysis Services Command'
WHEN 'ANALYSISQUERY' THEN 'SQL Server Analysis Services Query'
WHEN 'SSIS' THEN 'SQL Server Integration Services Package'
WHEN 'TSQL' THEN 'Transact-SQL script (T-SQL)'
ELSE sJSTP.subsystem
END AS [StepType]
, [sPROX].[name] AS [RunAs]
, [sJSTP].[database_name] AS [Database]
, [sJSTP].[command] AS [ExecutableCommand]
, CASE [sJSTP].[on_success_action]
WHEN 1 THEN 'Quit the job reporting success'
WHEN 2 THEN 'Quit the job reporting failure'
WHEN 3 THEN 'Go to the next step'
WHEN 4 THEN 'Go to Step: '
+ QUOTENAME(CAST([sJSTP].[on_success_step_id] AS VARCHAR(3)))
+ ' '
+ [sOSSTP].[step_name]
END AS [OnSuccessAction]
, [sJSTP].[retry_attempts] AS [RetryAttempts]
, [sJSTP].[retry_interval] AS [RetryInterval (Minutes)]
, CASE [sJSTP].[on_fail_action]
WHEN 1 THEN 'Quit the job reporting success'
WHEN 2 THEN 'Quit the job reporting failure'
WHEN 3 THEN 'Go to the next step'
WHEN 4 THEN 'Go to Step: '
+ QUOTENAME(CAST([sJSTP].[on_fail_step_id] AS VARCHAR(3)))
+ ' '
+ [sOFSTP].[step_name]
END AS [OnFailureAction]
FROM
[msdb].[dbo].[sysjobsteps] AS [sJSTP]
INNER JOIN [msdb].[dbo].[sysjobs] AS [sJOB]
ON [sJSTP].[job_id] = [sJOB].[job_id]
LEFT JOIN [msdb].[dbo].[sysjobsteps] AS [sOSSTP]
ON [sJSTP].[job_id] = [sOSSTP].[job_id]
AND [sJSTP].[on_success_step_id] = [sOSSTP].[step_id]
LEFT JOIN [msdb].[dbo].[sysjobsteps] AS [sOFSTP]
ON [sJSTP].[job_id] = [sOFSTP].[job_id]
AND [sJSTP].[on_fail_step_id] = [sOFSTP].[step_id]
LEFT JOIN [msdb].[dbo].[sysproxies] AS [sPROX]
ON [sJSTP].[proxy_id] = [sPROX].[proxy_id]
WHERE [sJSTP].[command] LIKE '%MyStoredProc%'
ORDER BY [JobName], [StepNo]
</code></pre>
<p>Credit should go to the article <a href="http://www.mssqltips.com/sqlservertip/2561/querying-sql-server-agent-job-information/" rel="noreferrer">Querying SQL Server Agent Job Information</a> by Dattatrey Sindol for most of the above query.</p> |
18,118,021 | How to resize superview to fit all subviews with autolayout? | <p>My understanding of autolayout is that it takes the size of superview and base on constrains and intrinsic sizes it calculates positions of subviews.</p>
<p>Is there a way to reverse this process? I want to resize superview on the base of constrains and intrinsic sizes. What is the simplest way of achieving this?</p>
<p>I have view designed in Xcode which I use as a header for <code>UITableView</code>. This view includes a label and a button. Size of the label differs depending on data. Depending on constrains the label successfully pushes the button down or if there is a constrain between the button and bottom of superview the label is compressed.</p>
<p>I have found a few similar questions but they don’t have good and easy answers. </p> | 18,155,803 | 4 | 1 | null | 2013-08-08 04:39:56.937 UTC | 111 | 2015-05-28 16:32:38.203 UTC | 2014-06-26 16:22:29.863 UTC | null | 1,360,888 | null | 2,662,999 | null | 1 | 147 | ios|uitableview|autolayout | 111,649 | <p>The correct API to use is <code>UIView systemLayoutSizeFittingSize:</code>, passing either <code>UILayoutFittingCompressedSize</code> or <code>UILayoutFittingExpandedSize</code>.</p>
<p>For a normal <code>UIView</code> using autolayout this should just work as long as your constraints are correct. If you want to use it on a <code>UITableViewCell</code> (to determine row height for example) then you should call it against your cell <code>contentView</code> and grab the height. </p>
<p>Further considerations exist if you have one or more UILabel's in your view that are multiline. For these it is imperitive that the <code>preferredMaxLayoutWidth</code> property be set correctly such that the label provides a correct <code>intrinsicContentSize</code>, which will be used in <code>systemLayoutSizeFittingSize's</code> calculation.</p>
<p><strong>EDIT: by request, adding example of height calculation for a table view cell</strong></p>
<p>Using autolayout for table-cell height calculation isn't super efficient but it sure is convenient, especially if you have a cell that has a complex layout. </p>
<p>As I said above, if you're using a multiline <code>UILabel</code> it's imperative to sync the <code>preferredMaxLayoutWidth</code> to the label width. I use a custom <code>UILabel</code> subclass to do this:</p>
<pre><code>@implementation TSLabel
- (void) layoutSubviews
{
[super layoutSubviews];
if ( self.numberOfLines == 0 )
{
if ( self.preferredMaxLayoutWidth != self.frame.size.width )
{
self.preferredMaxLayoutWidth = self.frame.size.width;
[self setNeedsUpdateConstraints];
}
}
}
- (CGSize) intrinsicContentSize
{
CGSize s = [super intrinsicContentSize];
if ( self.numberOfLines == 0 )
{
// found out that sometimes intrinsicContentSize is 1pt too short!
s.height += 1;
}
return s;
}
@end
</code></pre>
<p>Here's a contrived UITableViewController subclass demonstrating heightForRowAtIndexPath:</p>
<pre><code>#import "TSTableViewController.h"
#import "TSTableViewCell.h"
@implementation TSTableViewController
- (NSString*) cellText
{
return @"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
}
#pragma mark - Table view data source
- (NSInteger) numberOfSectionsInTableView: (UITableView *) tableView
{
return 1;
}
- (NSInteger) tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger) section
{
return 1;
}
- (CGFloat) tableView: (UITableView *) tableView heightForRowAtIndexPath: (NSIndexPath *) indexPath
{
static TSTableViewCell *sizingCell;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sizingCell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell"];
});
// configure the cell
sizingCell.text = self.cellText;
// force layout
[sizingCell setNeedsLayout];
[sizingCell layoutIfNeeded];
// get the fitting size
CGSize s = [sizingCell.contentView systemLayoutSizeFittingSize: UILayoutFittingCompressedSize];
NSLog( @"fittingSize: %@", NSStringFromCGSize( s ));
return s.height;
}
- (UITableViewCell *) tableView: (UITableView *) tableView cellForRowAtIndexPath: (NSIndexPath *) indexPath
{
TSTableViewCell *cell = (TSTableViewCell*)[tableView dequeueReusableCellWithIdentifier: @"TSTableViewCell" ];
cell.text = self.cellText;
return cell;
}
@end
</code></pre>
<p>A simple custom cell:</p>
<pre><code>#import "TSTableViewCell.h"
#import "TSLabel.h"
@implementation TSTableViewCell
{
IBOutlet TSLabel* _label;
}
- (void) setText: (NSString *) text
{
_label.text = text;
}
@end
</code></pre>
<p>And, here's a picture of the constraints defined in the Storyboard. Note that there are no height/width constraints on the label - those are inferred from the label's <code>intrinsicContentSize</code>:</p>
<p><img src="https://i.stack.imgur.com/8d5qA.png" alt="enter image description here"></p> |
46,986,001 | Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1 | <p>Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 0 installs, 0 updates, 1 removal
- Removing genealabs/laravel-caffeine (0.3.12)
Writing lock file
Generating optimized autoload files</p>
<blockquote>
<p>Illuminate\Foundation\ComposerScripts::postAutoloadDump
@php artisan package:discover</p>
</blockquote>
<p>[Symfony\Component\Debug\Exception\FatalThrowableError]<br>
Class 'GeneaLabs\LaravelCaffeine\LaravelCaffeineServiceProvider' not found </p>
<p>Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1</p> | 49,467,840 | 24 | 5 | null | 2017-10-28 03:38:10.773 UTC | 12 | 2022-06-21 13:13:49.823 UTC | null | null | null | null | 8,367,090 | null | 1 | 62 | laravel-5.4 | 243,191 | <p>Add this in <code>composer.json</code>. Then dusk has to be installed explicitly in your project:</p>
<pre><code>"extra": {
"laravel": {
"dont-discover": [
"laravel/dusk"
]
}
},
</code></pre>
<p><a href="https://github.com/acacha/adminlte-laravel/issues/337" rel="noreferrer">I found this solution here</a></p> |
47,426,692 | Read data from a file into an array - C++ | <p>I want to read the data from my input file </p>
<pre><code>70 95 62 88 90 85 75 79 50 80 82 88 81 93 75 78 62 55 89 94 73 82
</code></pre>
<p>and store each value in an array. There's more to this particular problem (the other functions are commented out for now) but this is what's really giving me trouble. I looked for hours at the previous question about data and arrays but I can't find where I'm making the mistake.</p>
<p>Here's my code:</p>
<pre><code>#include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int SIZE = 22;
int grades[SIZE];
void readData() {
int i = 0;
int grades[i];
string inFileName = "grades.txt";
ifstream inFile;
inFile.open(inFileName.c_str());
if (inFile.is_open())
{
for (i = 0; i < SIZE; i++)
{
inFile >> grades[i];
cout << grades[i] << " ";
}
inFile.close(); // CLose input file
}
else { //Error message
cerr << "Can't find input file " << inFileName << endl;
}
}
/*
double getAverage() {
return 0;
}
void printGradesTable() {
}
void printGradesInRow() {
}
void min () {
int pos = 0;
int minimum = grades[pos];
cout << "Minimum " << minimum << " at position " << pos << endl;
}
void max () {
int pos = 0;
int maximum = grades[pos];
cout << "Maximum " << maximum << " at position " << pos << endl;
}
void sort() {
}
*/
int main ()
{
readData();
return 0;
}
</code></pre>
<p>and here's my output: </p>
<pre><code> 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
</code></pre>
<p>Thank you for your time. </p> | 47,426,984 | 3 | 9 | null | 2017-11-22 04:14:57.383 UTC | null | 2017-11-22 06:16:34.597 UTC | 2017-11-22 04:22:39.633 UTC | null | 2,227,961 | null | 2,227,961 | null | 1 | 2 | c++|file-io | 39,561 | <p>The issue is that you're declaring a local <code>grades</code> array with a size of 1, hiding the global <code>grades</code> array. Not only that, you are now accessing the array beyond the bounds, since the local <code>grades</code> array can only hold 1 item.</p>
<p>So get rid of the line:</p>
<pre><code>int grades[i];
</code></pre>
<p>However, it needs to be mentioned that this:</p>
<pre><code>int i = 0;
int grades[i];
</code></pre>
<p>is not valid C++ syntax. You just stumbled into this by mistake, but that code would not compile if compiled using a strict ANSI C++ compiler.</p>
<p>An array in C++ must be declared using a constant expression to denote the number of entries in the array, not a variable. You, by accident, are using a non-standard compiler extension called <em>Variable Length Arrays</em> or VLA's for short.</p>
<p>If this is for a school assignment, do not declare arrays this way (even if you meant to do it), as it is not officially C++. If you want to declare a dynamic array, that is what <code>std::vector</code> is for.</p> |
23,287,942 | Using View-Models with Repository pattern | <p>I'm using <a href="http://blogs.msdn.com/b/marblogging/archive/2011/05/23/domain-drive-design-n-layered-net-4-0-architecture-guide.aspx?Redirected=true" rel="noreferrer">Domain driven N-layered application architecture</a> with <code>EF code first</code> in my recent project, I defined my <code>Repository</code> contracts, In <code>Domain</code> layer.
A basic contract to make other <code>Repositories</code> less verbose:</p>
<pre><code>public interface IRepository<TEntity, in TKey> where TEntity : class
{
TEntity GetById(TKey id);
void Create(TEntity entity);
void Update(TEntity entity);
void Delete(TEntity entity);
}
</code></pre>
<p>And specialized <code>Repositories</code> per each <code>Aggregation root</code>, e.g:</p>
<pre><code>public interface IOrderRepository : IRepository<Order, int>
{
IEnumerable<Order> FindAllOrders();
IEnumerable<Order> Find(string text);
//other methods that return Order aggregation root
}
</code></pre>
<p>As you see, all of these methods depend on <code>Domain entities</code>.
But in some cases, an application's <code>UI</code>, needs some data that isn't <code>Entity</code>, that data may made from two or more enteritis's data(<code>View-Model</code>s), in these cases, I define the <code>View-Model</code>s in <code>Application layer</code>, because they are closely depend on an <code>Application's</code> needs and not to the <code>Domain</code>.</p>
<p>So, I think I have 2 way's to show data as <code>View-Models</code> in the <code>UI</code>:</p>
<ol>
<li>Leave the specialized <code>Repository</code> depends on <code>Entities</code> only, and map the results of <code>Repositories</code>'s method to <code>View-Models</code> when I want to show to user(in <code>Application Layer</code> usually).</li>
<li>Add some methods to my specialized <code>Repositories</code> that return their results as <code>View-Models</code> directly, and use these returned values, in <code>Application Layer</code> and then <code>UI</code>(these specialized <code>Repositories</code>'s contracts that I call them <code>Readonly Repository Contract</code>s, put in <code>Application Layer</code> unlike the other <code>Repositories</code>'e contract that put in <code>Domain</code>).
<img src="https://i.stack.imgur.com/ZLxvi.jpg" alt="enter image description here"></li>
</ol>
<p>Suppose, my <code>UI</code> needs a <code>View-Model</code> with 3 or 4 properties(from 3 or 4 <strong>big</strong> <code>Entities</code>).
It's data could be generate with simple projection, but in case 1, because my methods could not access to <code>View-Models</code>, I have to <strong>fetch all the fields of all 3 or 4 tables</strong> with sometimes, huge joins, and then map the results to <code>View-Models</code>.
But, in case 2, I could simply use projection and fill the <code>View-Model</code>s directly.</p>
<p>So, I think in performance point of view, the case 2 is better than case 1. but I read that <code>Repository</code> should depend on <code>Entities</code> and not <code>View-Models</code> in design point of view.</p>
<p>Is there any better way that does not cause the <code>Domain</code> Layer depend on the <code>Application layer</code>, and also doesn't hit the performance? or is it acceptable that for reading queries, my <code>Repositories</code> depend on <code>View-Models</code>?(case2)</p> | 23,375,062 | 3 | 2 | null | 2014-04-25 08:26:14.113 UTC | 10 | 2014-05-11 07:45:05.943 UTC | 2014-05-11 07:45:05.943 UTC | null | 1,594,487 | null | 1,594,487 | null | 1 | 21 | c#|entity-framework|ef-code-first|repository|viewmodel | 9,567 | <p>Perhaps using the <strong><a href="http://www.codeproject.com/Articles/555855/Introduction-to-CQRS">command-query separation</a></strong> (at the application level) might help a bit. </p>
<p>You should make your repositories dependent on entities only, and keep only the <em>trivial</em> retrieve method - that is, <em>GetOrderById()</em> - on your repository (along with create / update / merge / delete, of course). Imagine that the entities, the repositories, the domain services, the user-interface commands, the application services that handles those commands (for example, a certain web controller that handles POST requests in a web application etc.) represents your <strong>write model</strong>, the <strong>write-side</strong> of your application.</p>
<p>Then build a separate <strong>read model</strong> that could be as dirty as you wish - put there the joins of 5 tables, the code that reads from a file the number of stars in the Universe, multiplies it with the number of books starting with A (after doing a query against Amazon) and builds up a n-dimensional structure that etc. - you get the idea :) But, on the read-model, do not add any code that deals with modifying your entities. You are free to return any View-Models you want from this read model, but do trigger any data changes from here. </p>
<p>The <strong>separation of reads and writes</strong> should decrease the complexity of the program and make everything a bit more manageable. And you may also see that it won't break the design rules you have mentioned in your question (hopefully).</p>
<p>From a performance point of view, using a <strong>read model</strong>, that is, writing the code that <strong>reads</strong> data separately from the code that <strong>writes / changes</strong> data is as best as you can get :) This is because you can even mangle some SQL code there without sleeping bad at night - and SQL queries, if written well, will give your application a considerable speed boost.</p>
<p>Nota bene: I was joking a bit on what and how you can code your read side - the read-side code should be as <strong>clean</strong> and simple as the write-side code, of course :)</p>
<p>Furthermore, you may get rid of the <em>generic repository</em> interface if you want, as it just clutters the domain you are modeling and forces every concrete repository to expose methods that are not necessary :) See <a href="http://codebetter.com/gregyoung/2009/01/16/ddd-the-generic-repository/">this</a>. For example, it is highly probable that the Delete() method would never be used for the <em>OrderRepository</em> - as, perhaps, Orders should never be deleted (of course, as always, it depends). Of course you can keep the <em>database-row-managing</em> primitives in a single module and reuse those primitives in your concrete repositories, but to not expose those primitives to anyone else but the implementation of the repositories - simply because they are not needed anywhere else and may confuse a drunk programmer if publicly exposed.</p>
<p>Finally, perhaps it would be also beneficial to not think about <em>Domain Layer</em>, <em>Application Layer</em>, <em>Data Layer</em> or <em>View Models Layer</em> in a too strict manner. Please read <a href="http://butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod">this.</a> Packaging your software modules by their real-world meaning / purpose (<strong>or feature</strong>) is a bit better than packaging them based on an <em>unnatural</em>, <em>hard-to-understand</em>, <em>hard-to-explain-to-a-5-old-kid</em> criterion, that is, packaging them <strong>by layer</strong>.</p> |
23,155,637 | Change Background color of the action bar using AppCompat | <p>I found some questions about this problem around the web. Unfortunately, everything i try so far, has been unsuccessful.</p>
<p>Has the title say, i need to change the background color of my action bar.</p>
<p>The project have a min sdk of 9, and max sdk of 19.</p>
<p>I have create in my res/values folder, an xml file:</p>
<p>red_actionbar.xml</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light">
<item name="actionBarStyle">@style/MyActionBar</item>
</style>
<style name="MyActionBar"
parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="background">@color/red</item>
</style>
</resources>
</code></pre>
<p>the colors.xml stored in res/values</p>
<pre><code><resources>
<color name="red">#FF0000</color>
</resources>
</code></pre>
<p>and the part of the manifest where i change the theme</p>
<pre><code><application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/CustomActionBarTheme" >
</code></pre>
<p>But nothing changes. Where is the problem? The application accepts the code because if i change ths:</p>
<pre><code><style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light">
</code></pre>
<p>to</p>
<pre><code><style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light.DarkActionBar ">
</code></pre>
<p>it does change the theme of my app, so the problem is in the style but I don't know how to solve it.</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light">
<item name="android:actionBarStyle" tools:ignore="NewApi">@style/MyActionBar</item>
<item name="actionBarStyle">@style/MyActionBar</item>
</style>
<style name="MyActionBar"
parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="android:background" tools:ignore="NewApi">@color/red</item>
<item name="background">@color/red</item>
</style>
</resources>
</code></pre> | 23,156,002 | 4 | 3 | null | 2014-04-18 13:56:39.907 UTC | 11 | 2017-06-07 08:12:27.353 UTC | 2017-06-07 08:12:27.353 UTC | null | 1,863,229 | null | 2,030,307 | null | 1 | 48 | android|xml|android-actionbar | 60,700 | <pre><code><style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="android:background" tools:ignore="NewApi">@color/red</item>
<item name="background">@color/red</item>
</style>
<style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light">
<item name="android:actionBarStyle" tools:ignore="NewApi">@style/MyActionBar</item>
<item name="actionBarStyle">@style/MyActionBar</item>
</style>
</code></pre>
<p>you need both <code>android:background</code> and <code>background</code> items. The former is for newer versions of android that support ActionBar natively. The latter is for older android versions.</p>
<p>EDIT</p>
<p>instead of <code><resources></code> use </p>
<pre><code><resources xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android">
</code></pre>
<p>From SDK 21</p>
<p>to change Action Bar background color, add this to ActionBarTheme, and the two colours are to be different or it will not work (thanks to <code>@Dre</code> and <code>@lagoman</code>)</p>
<pre><code><item name="colorPrimary">@color/my_awesome_red</item>
<item name="colorPrimaryDark">@color/my_awesome_darker_red</item>
</code></pre> |
2,081,932 | Difference between a += 10 and a = a + 10 in java? | <p>Are <code>a += 10</code> and <code>a = a + 10</code> both the same, or is there some difference between them? I got this question while studying assignments in Java.</p> | 2,081,951 | 5 | 2 | null | 2010-01-17 17:37:24.11 UTC | 3 | 2015-11-10 23:38:47.82 UTC | 2015-11-10 23:38:47.82 UTC | null | 2,767,207 | null | 241,717 | null | 1 | 31 | java|variable-assignment | 6,716 | <p>As you've now mentioned casting... there is a difference in this case:</p>
<pre><code>byte a = 5;
a += 10; // Valid
a = a + 10; // Invalid, as the expression "a + 10" is of type int
</code></pre>
<p>From the Java Language Specification <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#5304" rel="noreferrer">section 15.26.2</a>:</p>
<blockquote>
<p>A compound assignment expression of the form <code>E1 op= E2</code> is equivalent to
<code>E1 = (T)((E1) op (E2))</code>, where <code>T</code> is the type of <code>E1</code>, except that <code>E1</code> is evaluated only once.</p>
</blockquote>
<p>Interestingly, the example they give in the spec:</p>
<pre><code>short x = 3;
x += 4.6;
</code></pre>
<p>is valid in Java, but <em>not</em> in C#... basically in C# the compiler performs special-casing of += and -= to ensure that the expression is either of the target type or is a literal within the target type's range.</p> |
1,964,934 | What does __contains__ do, what can call __contains__ function | <p>Here is my code:</p>
<pre><code>class a(object):
d='ddd'
def __contains__(self):
if self.d:return True
b=a()
print b.contains('d') # error
print contains(b,'d') # error
</code></pre> | 1,964,949 | 5 | 0 | null | 2009-12-27 01:49:02.623 UTC | 19 | 2022-04-08 18:40:32.23 UTC | 2016-01-13 05:10:16.47 UTC | null | 402,884 | null | 234,322 | null | 1 | 56 | python | 111,975 | <p>Like all special methods (with "magic names" that begin and end in <code>__</code>), <a href="https://docs.python.org/2/reference/datamodel.html#object.__contains__" rel="noreferrer"><code>__contains__</code></a> is <strong>not</strong> meant to be called directly (except in very specific cases, such as up=calls to the superclass): rather, such methods are called as part of the operation of built-ins and operators. In the case of <code>__contains__</code>, the operator in question is <code>in</code> -- the "containment check" operator.</p>
<p>With your class <code>a</code> as you present it (except for fixing your typo, and using <code>True</code> instead of <code>true</code>!-), and <code>b</code> as its instance, <code>print 'x' in b</code> will print <code>True</code> -- and so will any other containment check on <code>b</code>, since <code>b</code> always returns <code>True</code> (because <code>self.d</code>, a non-empty string, is true).</p> |
2,170,872 | Does Java casting introduce overhead? Why? | <p>Is there any overhead when we cast objects of one type to another? Or the compiler just resolves everything and there is no cost at run time?</p>
<p>Is this a general things, or there are different cases?</p>
<p>For example, suppose we have an array of Object[], where each element might have a different type. But we always know for sure that, say, element 0 is a Double, element 1 is a String. (I know this is a wrong design, but let's just assume I had to do this.)</p>
<p>Is Java's type information still kept around at run time? Or everything is forgotten after compilation, and if we do (Double)elements[0], we'll just follow the pointer and interpret those 8 bytes as a double, whatever that is?</p>
<p>I'm very unclear about how types are done in Java. If you have any reccommendation on books or article then thanks, too.</p> | 2,170,876 | 5 | 2 | null | 2010-01-31 07:10:42.753 UTC | 22 | 2016-11-10 18:07:21.24 UTC | null | null | null | null | 159,759 | null | 1 | 116 | java|performance|casting|static-typing | 45,379 | <p>There are 2 types of casting:</p>
<p><em>Implicit</em> casting, when you cast from a type to a wider type, which is done automatically and there is no overhead:</p>
<pre><code>String s = "Cast";
Object o = s; // implicit casting
</code></pre>
<p><em>Explicit</em> casting, when you go from a wider type to a more narrow one. For this case, you must explicitly use casting like that:</p>
<pre><code>Object o = someObject;
String s = (String) o; // explicit casting
</code></pre>
<p>In this second case, there is overhead in runtime, because the two types must be checked and in case that casting is not feasible, JVM must throw a ClassCastException.</p>
<p>Taken from <a href="http://www.javaworld.com/javaworld/jw-12-1999/jw-12-performance.html?page=2" rel="noreferrer">JavaWorld: The cost of casting</a></p>
<blockquote>
<p><em>Casting</em> is used to convert between
types -- between reference types in
particular, for the type of casting
operation in which we're interested
here. </p>
<p><em>Upcast</em> operations (also called
widening conversions in the Java
Language Specification) convert a
subclass reference to an ancestor
class reference. This casting
operation is normally automatic, since
it's always safe and can be
implemented directly by the compiler.</p>
<p><em>Downcast</em> operations (also called
narrowing conversions in the Java
Language Specification) convert an
ancestor class reference to a subclass
reference. This casting operation
creates execution overhead, since Java
requires that the cast be checked at
runtime to make sure that it's valid.
If the referenced object is not an
instance of either the target type for
the cast or a subclass of that type,
the attempted cast is not permitted
and must throw a
java.lang.ClassCastException.</p>
</blockquote> |
2,280,948 | Reading data metadata from JPEG, XMP or EXIF in C# | <p>I've been looking around for a decent way of reading metadata (specifically, the date taken) from JPEG files in C#, and am coming up a little short. Existing information, as far as I can see, shows code like the following;</p>
<pre><code>BitmapMetadata bmd = (BitmapMetadata)frame.Metadata;
string a1 = (string)bmd.GetQuery("/app1/ifd/exif:{uint=36867}");
</code></pre>
<p>But in my ignorance I have no idea what bit of metadata GetQuery() will return, or what to pass it.</p>
<p>I want to attempt reading XMP first, falling back to EXIF if XMP does not exist. Is there a simple way of doing this?</p>
<p>Thanks.</p> | 2,281,704 | 6 | 1 | null | 2010-02-17 13:26:50.967 UTC | 7 | 2022-09-04 13:07:36.277 UTC | 2019-11-11 21:00:03.163 UTC | null | 527,702 | null | 226,491 | null | 1 | 18 | c#|metadata|jpeg|exif|xmp | 67,830 | <p>The following seems to work nicely, but if there's something bad about it, I'd appreciate any comments.</p>
<pre><code> public string GetDate(FileInfo f)
{
using(FileStream fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
BitmapSource img = BitmapFrame.Create(fs);
BitmapMetadata md = (BitmapMetadata)img.Metadata;
string date = md.DateTaken;
Console.WriteLine(date);
return date;
}
}
</code></pre> |
2,227,182 | How can I find out a file's MIME type (Content-Type)? | <p>Is there a way to find out the MIME type (or is it called "Content-Type"?) of a file in a Linux bash script?</p>
<p>The reason I need it is because ImageShack appears to need it to upload a file, as for some reason it detects the .png file as an <code>application/octet-stream</code> file.</p>
<p>I’ve checked the file, and it really is a PNG image:</p>
<pre><code>$ cat /1.png
?PNG
(with a heap load of random characters)
</code></pre>
<p>This gives me the error:</p>
<pre><code>$ curl -F "fileupload=@/1.png" http://www.imageshack.us/upload_api.php
<links>
<error id="wrong_file_type">Wrong file type detected for file 1.png:application/octet-stream</error>
</links>
</code></pre>
<p>This works, but I need to specify a MIME-TYPE.</p>
<pre><code>$ curl -F "fileupload=@/1.png;type=image/png" http://www.imageshack.us/upload_api.php
</code></pre> | 2,227,201 | 6 | 0 | null | 2010-02-09 06:20:20.993 UTC | 17 | 2022-05-12 11:37:59.457 UTC | 2018-06-14 10:33:03.857 UTC | null | 209,139 | null | 138,541 | null | 1 | 153 | linux|bash|content-type|mime|mime-types | 147,658 | <p>Use <code>file</code>. Examples:</p>
<pre><code>> file --mime-type image.png
image.png: image/png
> file -b --mime-type image.png
image/png
> file -i FILE_NAME
image.png: image/png; charset=binary
</code></pre> |
2,308,188 | getResourceAsStream() vs FileInputStream | <p>I was trying to load a file in a webapp, and I was getting a <code>FileNotFound</code> exception when I used <code>FileInputStream</code>. However, using the same path, I was able to load the file when I did <code>getResourceAsStream()</code>.
What is the difference between the two methods, and why does one work while the other doesn't?</p> | 2,308,388 | 6 | 0 | null | 2010-02-22 00:52:38.627 UTC | 82 | 2019-01-16 10:50:47.123 UTC | 2016-03-19 08:54:03.627 UTC | null | 573,032 | null | 263,004 | null | 1 | 183 | java|file-io|web-applications|fileinputstream | 199,226 | <p>The <a href="http://docs.oracle.com/javase/8/docs/api/java/io/File.html" rel="noreferrer"><code>java.io.File</code></a> and consorts acts on the local disk file system. The root cause of your problem is that <em>relative</em> paths in <code>java.io</code> are dependent on the current working directory. I.e. the directory from which the JVM (in your case: the webserver's one) is started. This may for example be <code>C:\Tomcat\bin</code> or something entirely different, but thus <em>not</em> <code>C:\Tomcat\webapps\contextname</code> or whatever you'd expect it to be. In a normal Eclipse project, that would be <code>C:\Eclipse\workspace\projectname</code>. You can learn about the current working directory the following way:</p>
<pre><code>System.out.println(new File(".").getAbsolutePath());
</code></pre>
<p>However, the working directory is in no way programmatically controllable. You should really prefer using <em>absolute</em> paths in the <code>File</code> API instead of relative paths. E.g. <code>C:\full\path\to\file.ext</code>.</p>
<p>You don't want to hardcode or guess the absolute path in Java (web)applications. That's only portability trouble (i.e. it runs in system X, but not in system Y). The normal practice is to place those kind of resources in the <strong>classpath</strong>, or to add its full path to the classpath (in an IDE like Eclipse that's the <code>src</code> folder and the "build path" respectively). This way you can grab them with help of the <code>ClassLoader</code> by <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResource-java.lang.String-" rel="noreferrer"><code>ClassLoader#getResource()</code></a> or <a href="http://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResourceAsStream-java.lang.String-" rel="noreferrer"><code>ClassLoader#getResourceAsStream()</code></a>. It is able to locate files relative to the "root" of the classpath, as you by coincidence figured out. In webapplications (or any other application which uses multiple classloaders) it's recommend to use the <code>ClassLoader</code> as returned by <code>Thread.currentThread().getContextClassLoader()</code> for this so you can look "outside" the webapp context as well.</p>
<p>Another alternative in webapps is the <a href="http://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html#getResource-java.lang.String-" rel="noreferrer"><code>ServletContext#getResource()</code></a> and its counterpart <a href="http://docs.oracle.com/javaee/7/api/javax/servlet/ServletContext.html#getResourceAsStream-java.lang.String-" rel="noreferrer"><code>ServletContext#getResourceAsStream()</code></a>. It is able to access files located in the public <code>web</code> folder of the webapp project, including the <code>/WEB-INF</code> folder. The <code>ServletContext</code> is available in servlets by the inherited <a href="http://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getServletContext--" rel="noreferrer"><code>getServletContext()</code></a> method, you can call it as-is.</p>
<h3>See also:</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/2161054/where-to-place-and-how-to-read-properties-files-in-a-jsp-servlet-web-application">Where to place and how to read configuration resource files in servlet based application?</a></li>
<li><a href="https://stackoverflow.com/questions/12160639/what-does-servletcontext-getrealpath-mean-and-when-should-i-use-it">What does servletcontext.getRealPath("/") mean and when should I use it</a></li>
<li><a href="https://stackoverflow.com/questions/18664579/recommended-way-to-save-uploaded-files-in-a-servlet-application">Recommended way to save uploaded files in a servlet application</a></li>
<li><a href="https://stackoverflow.com/questions/31255366/java-io-filenotfoundexception-when-trying-to-save-generated-file-in-web-applicat">How to save generated file temporarily in servlet based web application</a></li>
</ul> |
1,833,796 | How to benchmark php/mysql site | <p>I would like to know how to benchmark a php/mysql site.</p>
<p>We have a web app almost completed and ready to go live, we know how many people are going to be using it in a years time but have absolutely no idea how much bandwidth the average user takes, to how much time they burn up on the database etc. We need to determine the correct servers to purchase.</p>
<p>Is there something server side linux that can monitor these statistics per user? So that we can then take this data and extrapolate it?</p>
<p>If I am going about this completely wrong please let me know but I believe that this is a frequent activity for new web apps. </p>
<p>EDIT: I may have asked for the incorrect information. We can see how long the database queries take and how long it takes to load the page but have no idea what load is placed on the server. The question I am asking is can we handle 100 users at once on average...1000? What type of server requirements are needed to hit 1M users. Etc.</p>
<p>Thanks for your help.</p> | 1,837,055 | 7 | 1 | null | 2009-12-02 15:52:35.163 UTC | 22 | 2016-09-18 15:11:04.02 UTC | 2015-11-26 20:52:06.273 UTC | null | 1,745,672 | null | 103,219 | null | 1 | 24 | php|mysql|benchmarking|load-testing | 16,166 | <p>A tool that I find fairly useful is <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">jmeter</a> which allows (at it's most basic) you to set your browser to use jmeter as a proxy then you wander all around your website and it will record everything you do.</p>
<p>Once you are happy that it's a decent test of most of your website you can then save the test in jmeter and tell it to run your test with a set number of threads and a number of loops per thread to simulate load on your website.</p>
<p>For example you can run 50 clients each running the testplan 10 times.</p>
<p>You can then ramp the numbers up and down to see the performance impact it has on the site, it graphs the response time for you.</p>
<p>This lets you tune different parameters, try different caching strategies and check the real world impact of those changes.</p> |
1,365,059 | Submitting a jQuery ajax form with two submit buttons | <p>I have a form that looks like this:</p>
<pre><code><form action="/vote/" method="post" class="vote_form">
<input type="hidden" name="question_id" value="10" />
<input type="image" src="vote_down.png" class="vote_down" name="submit" value="down" />
<input type="image" src="vote_up.png" class="vote_up" name="submit" value="up" />
</form>
</code></pre>
<p>When I bind to the form's submit (<code>$("vote_form").submit()</code>), I don't seem to have access to which image the user clicked on. So I'm trying to bind to clicking on the image itself (<code>$(".vote_down, .vote_up").click()</code>), which always submits the form, regardless of whether I try</p>
<ul>
<li>return false; </li>
<li>event.stopPropogation(); or </li>
<li>event.preventDefault();</li>
</ul>
<p>because all of those are form events.</p>
<ol>
<li><p>Should I attach my $.post() to the form.submit() event, and if so, how do I tell which input the user clicked on, or</p></li>
<li><p>Should I attach my $.post() to the image click, and if so, how do I prevent the form from submitting also.</p></li>
</ol>
<p>Here is what my jQuery code looks like now:</p>
<pre><code>$(".vote_up, .vote_down").click(function (event) {
$form = $(this).parent("form");
$.post($form.attr("action"), $form.find("input").serialize() + {
'submit': $(this).attr("value")
}, function (data) {
// do something with data
});
return false; // <--- This doesn't prevent form from submitting; what does!?
});
</code></pre> | 1,368,489 | 8 | 0 | null | 2009-09-01 22:57:52.583 UTC | 8 | 2019-09-17 11:08:09.32 UTC | 2013-04-03 07:26:20.463 UTC | null | 969,612 | null | 70,203 | null | 1 | 21 | jquery|ajax|forms|input|submit | 43,540 | <p>Based on Emmett's answer, my ideal fix for this was just to kill the form's submit with Javascript itself, like this:</p>
<pre><code>$(".vote_form").submit(function() { return false; });
</code></pre>
<p>And that totally worked.</p>
<p>For completeness, some of my JS code in the original post need a little love. For example, the way I was adding to the serialize function didn't seem to work. This did:</p>
<pre><code> $form.serialize() + "&submit="+ $(this).attr("value")
</code></pre>
<p>Here's my entire jQuery code:</p>
<pre><code>$(".vote_form").submit(function() { return false; });
$(".vote_up, .vote_down").click(function(event) {
$form = $(this).parent("form");
$.post($form.attr("action"), $form.serialize() + "&submit="+ $(this).attr("value"), function(data) {
// do something with response (data)
});
});
</code></pre> |
1,349,856 | How to add a separator to a WinForms ContextMenu? | <p>Inside my control, I have:</p>
<pre><code>ContextMenu = new ContextMenu();
ContextMenu.MenuItems.Add(new MenuItem("&Add Item", onAddSpeaker));
ContextMenu.MenuItems.Add(new MenuItem("&Edit Item", onEditSpeaker));
ContextMenu.MenuItems.Add(new MenuItem("&Delete Item", onDeleteSpeaker));
ContextMenu.MenuItems.Add( ??? );
ContextMenu.MenuItems.Add(new MenuItem("Cancel"));
</code></pre>
<p>How to add a separation line to this ContextMenu?</p> | 1,349,861 | 8 | 2 | null | 2009-08-28 23:24:32.01 UTC | 8 | 2019-10-28 00:06:53.303 UTC | 2019-08-29 15:12:15.107 UTC | null | 823,321 | null | 5,324 | null | 1 | 113 | c#|winforms|contextmenu|separator | 81,908 | <p>I believe it's just a dash:</p>
<pre><code>ContextMenu.MenuItems.Add("-");
</code></pre> |
1,781,868 | Internal implementation of java.util.HashMap and HashSet | <p>I have been trying to understand the internal implementation of <code>java.util.HashMap</code> and <code>java.util.HashSet</code>.</p>
<p>Following are the doubts popping in my mind for a while:</p>
<ol>
<li>Whats is the importance of the <code>@Override public int hashcode()</code> in a HashMap/HashSet? Where is this hash code used internally?</li>
<li>I have generally seen the key of the HashMap be a <code>String</code> like <code>myMap<String,Object></code>. Can I map the values against <code>someObject</code> (instead of String) like <code>myMap<someObject, Object></code>? What all contracts do I need to obey for this happen successfully?</li>
</ol>
<p>Thanks in advance !</p>
<p><strong>EDIT:</strong></p>
<ol>
<li>Are we saying that the hash code of the key (check!) is the actual thing against which the value is mapped in the hash table? And when we do <code>myMap.get(someKey);</code> java is internally calling <code>someKey.hashCode()</code> to get the number in the Hash table to be looked for the resulting value?</li>
</ol>
<p><strong>Answer:</strong> Yes.</p>
<p><strong>EDIT 2:</strong></p>
<ol start="2">
<li>In a <code>java.util.HashSet</code>, from where is the key generated for the Hash table? Is it from the object that we are adding eg. <code>mySet.add(myObject);</code> then <code>myObject.hashCode()</code> is going to decide where this is placed in the hash table? (as we don't give keys in a HashSet).</li>
</ol>
<p><strong>Answer:</strong> The object added becomes the key. The value is dummy!</p> | 1,781,950 | 9 | 0 | null | 2009-11-23 08:52:01.967 UTC | 12 | 2017-02-13 07:26:31.707 UTC | 2009-11-23 10:35:39.31 UTC | null | 133,830 | null | 133,830 | null | 1 | 19 | java|hashmap|hashcode|hashset|language-implementation | 48,150 | <p>The answer to question 2 is easy - yes you can use any Object you like. Maps that have String type keys are widely used because they are typical data structures for naming services. But in general, you can map any two types like <code>Map<Car,Vendor></code> or <code>Map<Student,Course></code>.</p>
<p>For the hashcode() method it's like answered before - whenever you override equals(), then you have to override hashcode() to obey the contract. On the other hand, if you're happy with the standard implementation of equals(), then you shouldn't touch hashcode() (because that could break the contract and result in identical hashcodes for unequal objects).</p>
<p>Practical sidenote: eclipse (and probably other IDEs as well) can auto generate a pair of equals() and hashcode() implementation for your class, just based on the class members.</p>
<p><strong>Edit</strong></p>
<p>For your additional question: yes, exactly. Look at the source code for HashMap.get(Object key); it calls key.hashcode to calculate the position (bin) in the internal hashtable and returns the value at that position (if there is one).</p>
<p>But be careful with 'handmade' hashcode/equals methods - if you use an object as a key, make sure that the hashcode doesn't change afterwards, otherwise you won't find the mapped values anymore. In other words, the fields you use to calculate equals and hashcode <em>should be final</em> (or 'unchangeable' after creation of the object).</p>
<p>Assume, we have a contact with <code>String name</code> and <code>String phonenumber</code> and we use both fields to calculate equals() and hashcode(). Now we create "John Doe" with his mobile phone number and map him to his favorite Donut shop. hashcode() is used to calculate the index (bin) in the hash table and that's where the donut shop is stored. </p>
<p>Now we learn that he has a new phone number and we change the phone number field of the John Doe object. This results in a new hashcode. And this hashcode resolves to a new hash table index - which usually isn't the position where John Does' favorite Donut shop was stored.</p>
<p>The problem is clear: In this case we wanted to map "John Doe" to the Donut shop, and not "John Doe with a specific phone number". So, we have to be careful with autogenerated equals/hashcode to make sure they're what we really want, because they might use unwanted fields, introducing trouble with HashMaps and HashSets.</p>
<p><strong>Edit 2</strong></p>
<p>If you add an object to a HashSet, the Object is the key for the internal hash table, the value is set but unused (just a static instance of Object). Here's the implementation from the openjdk 6 (b17):</p>
<pre><code>// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
private transient HashMap<E,Object> map;
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
</code></pre> |
1,833,252 | Java Stanford NLP: Part of Speech labels? | <p>The Stanford NLP, demo'd <a href="http://nlp.stanford.edu:8080/parser/" rel="noreferrer">here</a>, gives an output like this:</p>
<pre><code>Colorless/JJ green/JJ ideas/NNS sleep/VBP furiously/RB ./.
</code></pre>
<p>What do the Part of Speech tags mean? I am unable to find an official list. Is it Stanford's own system, or are they using universal tags? (What is <code>JJ</code>, for instance?)</p>
<p>Also, when I am iterating through the sentences, looking for nouns, for instance, I end up doing something like checking to see if the tag <code>.contains('N')</code>. This feels pretty weak. Is there a better way to programmatically search for a certain part of speech?</p> | 1,833,718 | 10 | 1 | null | 2009-12-02 14:30:50.16 UTC | 120 | 2020-10-08 15:30:56.37 UTC | 2015-08-11 03:27:32.027 UTC | null | 2,728,388 | null | 147,601 | null | 1 | 181 | java|nlp|stanford-nlp|part-of-speech | 102,169 | <p><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.9.8216&rep=rep1&type=pdf" rel="noreferrer">The Penn Treebank Project</a>. Look at the <a href="http://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html" rel="noreferrer">Part-of-speech tagging</a> ps.</p>
<p>JJ is adjective. NNS is noun, plural. VBP is verb present tense. RB is adverb.</p>
<p>That's for english. For chinese, it's the Penn Chinese Treebank. And for german it's the NEGRA corpus.</p>
<blockquote>
<ol>
<li>CC Coordinating conjunction </li>
<li>CD Cardinal number </li>
<li>DT Determiner </li>
<li>EX Existential there </li>
<li>FW Foreign word </li>
<li>IN Preposition or subordinating conjunction </li>
<li>JJ Adjective </li>
<li>JJR Adjective, comparative </li>
<li>JJS Adjective, superlative </li>
<li>LS List item marker </li>
<li>MD Modal </li>
<li>NN Noun, singular or mass </li>
<li>NNS Noun, plural </li>
<li>NNP Proper noun, singular </li>
<li>NNPS Proper noun, plural </li>
<li>PDT Predeterminer </li>
<li>POS Possessive ending </li>
<li>PRP Personal pronoun </li>
<li>PRP$ Possessive pronoun </li>
<li>RB Adverb </li>
<li>RBR Adverb, comparative </li>
<li>RBS Adverb, superlative </li>
<li>RP Particle </li>
<li>SYM Symbol </li>
<li>TO to </li>
<li>UH Interjection </li>
<li>VB Verb, base form </li>
<li>VBD Verb, past tense </li>
<li>VBG Verb, gerund or present participle </li>
<li>VBN Verb, past participle </li>
<li>VBP Verb, non3rd person singular present </li>
<li>VBZ Verb, 3rd person singular present </li>
<li>WDT Whdeterminer </li>
<li>WP Whpronoun </li>
<li>WP$ Possessive whpronoun </li>
<li>WRB Whadverb </li>
</ol>
</blockquote> |
8,893,111 | How do I disable input element whose type is submit? | <p>I know the following works:</p>
<pre><code><input type="text" disabled="disabled" />
<button disabled="disabled">
</code></pre>
<p>But how would you disable this?</p>
<pre><code><input type="submit" ....>
</code></pre>
<p>Any idea? Do I have to use javascript?</p>
<p>Thanks.</p>
<hr>
<p>Okay. It might have been my Firefox problem. I swear I did use the same synatx.
Thanks, and sorry for such a silly question?</p> | 8,893,126 | 3 | 2 | null | 2012-01-17 10:34:23.897 UTC | 2 | 2012-01-17 10:40:43.283 UTC | 2012-01-17 10:40:43.283 UTC | null | 230,884 | null | 230,884 | null | 1 | 16 | html|input | 61,194 | <p>You can use <code>disabled="disabled"</code> on <code>input</code>'s that are of type <code>submit</code>:</p>
<pre><code><input type="submit" disabled="disabled" />
</code></pre> |
46,629,838 | Unable to change Git account | <p>I tried to push to my repository, but I got the error below:</p>
<pre><code>git push origin master
remote: Permission to PhanVanLinh/phanvanlinh.github.io.git denied to edgarphan.
fatal: unable to access 'https://github.com/PhanVanLinh/phanvanlinh.github.io.git/': The requested URL returned error: 403
</code></pre>
<p>Before, I was using username <code>edgarphan</code>, but I have already changed it to <code>PhanVanLinh</code>, but it still keeps <code>edgarphan</code>.</p>
<p>I have tried to delete the project and clone again, uninstall Git and reinstall, but it won't work.</p>
<p><a href="https://i.stack.imgur.com/ycCTp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ycCTp.png" alt="Enter image description here" /></a></p>
<h3>Global configuration file</h3>
<p><a href="https://i.stack.imgur.com/VELUu.png" rel="noreferrer"><img src="https://i.stack.imgur.com/VELUu.png" alt="Enter image description here" /></a></p>
<p>How can I fix this issue?</p> | 46,679,813 | 3 | 3 | null | 2017-10-08 09:58:32.18 UTC | 14 | 2021-07-07 07:18:54.303 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 5,381,331 | null | 1 | 26 | git|github|window | 29,595 | <p>This has nothing to do with your <code>user.name</code>/<code>user.email</code> settings: those are for authorship in a commit. They are <em>not</em> used for authentication when you push to a repo.</p>
<p>If Git does <em>not</em> ask you for your GitHub (new) username/password, that means <a href="https://github.com/git-for-windows/git/releases" rel="noreferrer">Git for Windows</a> is using a Git credential helper called "manager" (do a <code>git config credential.helper</code> to confirm it)</p>
<p>Meaning: it is caching your old credentials and is reusing them automatically.</p>
<p>In that case, go to the Windows start menu (<a href="https://i.stack.imgur.com/XD1LM.png" rel="noreferrer"><img src="https://i.stack.imgur.com/XD1LM.png" alt="Windows start" /></a>), type "credential" and select the Windows tool "<a href="https://github.com/Microsoft/Git-Credential-Manager-for-Windows/releases/tag/v1.12.0" rel="noreferrer">Windows Credential Manager</a>".<br />
<a href="https://i.stack.imgur.com/ojoEp.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ojoEp.png" alt="enter image description here" /></a><br />
In it, you will find an entry <code>git.https://github.com</code>, which you can edit, and where you can enter your new GitHub username/password.
<a href="https://i.stack.imgur.com/Jv1Vr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Jv1Vr.png" alt="Enter new credentials" /></a></p>
<p>Then try and push again.</p>
<hr />
<p>With more recent Git version (2.32+, Q2 2021), assuming <code><C:\path\to\git>\usr\bin</code> and <code><C:\path\to\git>\mingw64\libexec\git-core</code> are in your <code>%PATH%</code>, you can do the same removal in command-line:</p>
<pre class="lang-sh prettyprint-override"><code>printf "protocol=https\nhost=github.com\nusername=xxx"| git-credential-manager-core erase
</code></pre> |
18,037,082 | Are Java primitives immutable? | <p>If a method has a local variable <code>i</code>:</p>
<pre><code>int i = 10;
</code></pre>
<p>and then I assign a new value:</p>
<pre><code>i = 11;
</code></pre>
<p>Will this allocate a new memory location? Or just replace the original value?</p>
<p>Does this mean that primitives are immutable?</p> | 18,037,544 | 6 | 10 | null | 2013-08-03 20:38:42.01 UTC | 16 | 2019-12-23 07:24:32.053 UTC | 2013-08-03 21:26:36.763 UTC | null | 978,917 | null | 2,628,157 | null | 1 | 56 | java|primitive | 36,384 | <blockquote>
<p>Will this allocate a new memory location? Or just replace the original value?</p>
</blockquote>
<p>Java does not really make any guarantees that variables will correspond to memory locations; for example, your method might be optimized in such a way that <code>i</code> is stored in a register — or might not even be stored at all, if the compiler can see that you never actually use its value, or if it can trace through the code and use the appropriate values directly.</p>
<p>But setting that aside . . . if we take the abstraction here to be that a local variable denotes a memory location on the call stack, then <code>i = 11</code> will simply modify the value at that memory location. It will not need to use a new memory location, because the variable <code>i</code> was the only thing referring to the old location.</p>
<blockquote>
<p>Does this mean that primitives are immutable?</p>
</blockquote>
<p>Yes and no: yes, primitives are immutable, but no, that's not because of the above.</p>
<p>When we say that something is mutable, we mean that it can be mutated: changed while still having the same identity. For example, when you grow out your hair, you are mutating yourself: you're still you, but one of your attributes is different.</p>
<p>In the case of primitives, all of their attributes are fully determined by their identity; <code>1</code> always means <code>1</code>, no matter what, and <code>1 + 1</code> is always <code>2</code>. You can't change that.</p>
<p>If a given <code>int</code> variable has the value <code>1</code>, you can change it to have the value <code>2</code> instead, but that's a total change of identity: it no longer has the same value it had before. That's like changing <code>me</code> to point to someone else instead of to me: it doesn't actually change <em>me</em>, it just changes <code>me</code>.</p>
<p>With objects, of course, you can often do both:</p>
<pre><code>StringBuilder sb = new StringBuilder("foo");
sb.append("bar"); // mutate the object identified by sb
sb = new StringBuilder(); // change sb to identify a different object
sb = null; // change sb not to identify any object at all
</code></pre>
<p>In common parlance, both of these will be described as "changing <code>sb</code>", because people will use "<code>sb</code>" both to refer the <em>variable</em> (which contains a reference) and to the <em>object</em> that it refers to (when it refers to one). This sort of looseness is fine, as long as you remember the distinction when it matters.</p> |
17,745,927 | Jquery select this + class | <p>How can I select a class from that object <code>this</code>?</p>
<pre><code>$(".class").click(function(){
$("this .subclass").css("visibility","visible");
})
</code></pre>
<p>I want to select a <code>$(this+".subclass")</code>. How can I do this with Jquery?</p> | 17,745,948 | 6 | 0 | null | 2013-07-19 12:19:49.98 UTC | 17 | 2021-07-20 06:15:19.513 UTC | null | null | null | null | 2,013,580 | null | 1 | 69 | jquery | 198,134 | <p>Use <a href="http://api.jquery.com/find/" rel="noreferrer"><code>$(this).find()</code></a>, or pass this in context, using jQuery <a href="http://api.jquery.com/jQuery/#jQuery1" rel="noreferrer">context with selector</a>.</p>
<p>Using $(this).find()</p>
<pre><code>$(".class").click(function(){
$(this).find(".subclass").css("visibility","visible");
});
</code></pre>
<p>Using <code>this</code> in context, <code>$( selector, context )</code>, it will internally call find function, so better to use find on first place.</p>
<pre><code>$(".class").click(function(){
$(".subclass", this).css("visibility","visible");
});
</code></pre> |
6,613,889 | How to start an Android application from the command line? | <p>How to start an Android application from the command line?</p>
<p>There are similar question asked, but I can not find good any answers.</p> | 6,613,947 | 3 | 0 | null | 2011-07-07 16:26:16.933 UTC | 29 | 2016-01-25 06:19:48.82 UTC | null | null | null | null | 428,024 | null | 1 | 68 | android|command-line | 136,098 | <pre><code>adb shell
am start -n com.package.name/com.package.name.ActivityName
</code></pre>
<p>Or you can use this directly:</p>
<pre><code>adb shell am start -n com.package.name/com.package.name.ActivityName
</code></pre>
<p>You can also specify actions to be filter by your intent-filters:</p>
<pre><code>am start -a com.example.ACTION_NAME -n com.package.name/com.package.name.ActivityName
</code></pre> |
6,486,805 | HTML - Cache control max age | <p>I'ld like to present always the latest website content to the user but also have it fast loaded. By researching I came across postings people suggesting to use the cache for speeding up loading. </p>
<p>So what do I need to add to my website to "overwrite" the cache after 3 days to display the latest content?</p> | 6,486,854 | 4 | 2 | null | 2011-06-26 21:17:04.677 UTC | 3 | 2012-11-08 19:23:18.937 UTC | null | null | null | null | 812,239 | null | 1 | 21 | html|cache-control | 59,653 | <p>There is more than one way to do this - but you need to consider exactly what you need to cache and what you don't. The biggest speed increases will likely come from making sure your assets (css, images, javascript) are cached, rather than the html itself. You then need to look at various factors (how often do these assets change, how will you force a user to download a new version of the file of you do change it?).</p>
<p>Often as part of a sites release process, new files (updated files) are given a new filename to force the users browser to redownload the file, but this is only one approach.</p>
<p>You should take a look at apache mod_expire, and the ability to set expiry times for assets using the .htaccess file.</p>
<p><a href="http://www.google.com/?q=apache+cache+control+htaccess#q=apache+cache+control+htaccess">http://www.google.com/?q=apache+cache+control+htaccess#q=apache+cache+control+htaccess</a></p> |
36,032,177 | Android new Bottom Navigation bar or BottomNavigationView | <p>Saw the new guideline came out, and used in <code>google photos</code> latest app.
Have no idea how to use the new Bottom Navigation Bar.
See through the new support lib, didn't find any lead.</p>
<p><img src="https://i.stack.imgur.com/6lcXBm.png" alt="enter image description here"></p>
<p>Can not find any official sample.</p>
<p>How to use the new Bottom bar? Don't want to do any customize.</p> | 36,033,640 | 14 | 3 | null | 2016-03-16 09:55:38.46 UTC | 67 | 2021-02-14 07:39:17.85 UTC | 2018-05-03 13:29:03.037 UTC | null | 3,152,529 | null | 1,371,814 | null | 1 | 144 | android|bottomnavigationview | 299,554 | <p><strong>I think you might looking for this.</strong></p>
<p><strong>Here's a quick snippet to get started:</strong></p>
<pre><code>public class MainActivity extends AppCompatActivity {
private BottomBar mBottomBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Notice how you don't use the setContentView method here! Just
// pass your layout to bottom bar, it will be taken care of.
// Everything will be just like you're used to.
mBottomBar = BottomBar.bind(this, R.layout.activity_main,
savedInstanceState);
mBottomBar.setItems(
new BottomBarTab(R.drawable.ic_recents, "Recents"),
new BottomBarTab(R.drawable.ic_favorites, "Favorites"),
new BottomBarTab(R.drawable.ic_nearby, "Nearby"),
new BottomBarTab(R.drawable.ic_friends, "Friends")
);
mBottomBar.setOnItemSelectedListener(new OnTabSelectedListener() {
@Override
public void onItemSelected(final int position) {
// the user selected a new tab
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mBottomBar.onSaveInstanceState(outState);
}
}
</code></pre>
<p><strong>Here is reference link.</strong></p>
<p><a href="https://github.com/roughike/BottomBar" rel="noreferrer">https://github.com/roughike/BottomBar</a></p>
<p><strong>EDIT New Releases.</strong></p>
<p>The Bottom Navigation View has been in the material design guidelines for some time, but it hasn’t been easy for us to implement it into our apps. Some applications have built their own solutions, whilst others have relied on third-party open-source libraries to get the job done. Now the design support library is seeing the addition of this bottom navigation bar, let’s take a dive into how we can use it!</p>
<blockquote>
<p>How to use ?</p>
</blockquote>
<p>To begin with we need to update our dependency!</p>
<pre><code>compile ‘com.android.support:design:25.0.0’
</code></pre>
<blockquote>
<p>Design xml.</p>
</blockquote>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Content Container -->
<android.support.design.widget.BottomNavigationView
android:id="@+id/bottom_navigation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
app:itemBackground="@color/colorPrimary"
app:itemIconTint="@color/white"
app:itemTextColor="@color/white"
app:menu="@menu/bottom_navigation_main" />
</RelativeLayout>
</code></pre>
<blockquote>
<p>Create menu as per your requirement.</p>
</blockquote>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/action_favorites"
android:enabled="true"
android:icon="@drawable/ic_favorite_white_24dp"
android:title="@string/text_favorites"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_schedules"
android:enabled="true"
android:icon="@drawable/ic_access_time_white_24dp"
android:title="@string/text_schedules"
app:showAsAction="ifRoom" />
<item
android:id="@+id/action_music"
android:enabled="true"
android:icon="@drawable/ic_audiotrack_white_24dp"
android:title="@string/text_music"
app:showAsAction="ifRoom" />
</menu>
</code></pre>
<blockquote>
<p>Handling Enabled / Disabled states. Make selector file.</p>
</blockquote>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_checked="true"
android:color="@color/colorPrimary" />
<item
android:state_checked="false"
android:color="@color/grey" />
</selector>
</code></pre>
<blockquote>
<p>Handle click events.</p>
</blockquote>
<pre><code>BottomNavigationView bottomNavigationView = (BottomNavigationView)
findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.action_favorites:
break;
case R.id.action_schedules:
break;
case R.id.action_music:
break;
}
return false;
}
});
</code></pre>
<p>Edit : <strong>Using Androidx you just need to add below dependencies.</strong></p>
<pre><code>implementation 'com.google.android.material:material:1.2.0-alpha01'
</code></pre>
<p><strong>Layout</strong></p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:layout_gravity="bottom"
app:menu="@menu/bottom_navigation_menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</FrameLayout>
</code></pre>
<p>If you want to read more about it's methods and how it works <a href="https://developer.android.com/reference/com/google/android/material/bottomnavigation/BottomNavigationView" rel="noreferrer">read this.</a></p>
<p><strong>Surely it will help you.</strong></p> |
5,270,188 | Backbone.js Event Binding | <p>I'm using Backbone.js have a segmented control-type UI element for each model's view. They are each made up of a ul with a few li elements. I want to bind an event such that when one of these elements is clicked, I can determine which one has been clicked and update the model with the appropriate value.</p>
<p>The problem is that Backbone binds the events (these are in the events hash of the view) such that "this" in the callback function refers to the view, not the li elements. This means that I can not determine which of the several li elements has been clicked. If I used a normal jQuery binding, I can have "this" bound to the li elements, but then I don't have track of the model anymore, so I can't update it.</p> | 5,273,224 | 2 | 0 | null | 2011-03-11 07:31:49.367 UTC | 11 | 2011-08-25 01:18:51.6 UTC | null | null | null | null | 315,102 | null | 1 | 17 | jquery|events|binding|callback|backbone.js | 19,011 | <p>jQuery's habit of setting <code>this</code> to whatever happens to be convenient at the time is a pretty nasty pattern, in my opinion -- fortunately, you never have to rely on it:</p>
<pre><code>onClick: function(e) {
this; // Still the view instance (as it should be).
e.target; // The element that was clicked.
e.currentTarget; // The element that was bound by the click event.
}
</code></pre>
<p>... You can use the <code>target</code> or <code>currentTarget</code> of the event object, as appropriate.</p> |
5,134,357 | how to include header files in other src folder | <p>I have a c++ project having two src folders. Source file in folder 1 may need to include header file in src folder 2. Is it possible? or how should I write my Makefiles? thanks</p> | 5,134,373 | 2 | 3 | null | 2011-02-27 16:30:40.66 UTC | 6 | 2011-02-27 16:34:32.34 UTC | null | null | null | null | 486,720 | null | 1 | 19 | c++|compilation | 48,963 | <p>Depending on how closely the two folders are related (eg, if they're the same project), then it can be as easy as:</p>
<pre><code>#include "../otherfolder/header.h"
</code></pre>
<p>If they're separate projects, then it's customary to simply add the other project's header directory to your project's header search path, and include the header like this:</p>
<pre><code>#include <header.h>
</code></pre>
<p>(In practice, the brackets/quotes don't matter, but it helps keep external vs. internal header imports separate)</p> |
5,566,685 | NLog LogException seems to ignore the exception | <p><code>LogException</code> or any of the derived functions like <code>ErrorException</code> etc. seem to totally ignore the exception parameter passed in.</p>
<p>Am I missing a format attribute in my <code>nlog.config</code> file?
I am using the boilerplate from the template that Nlog installs in VS.</p>
<p>I would expect information from the exception object AND inner exceptions to be added to the log file. Yet the only information added to the log file is the string parameter passed to the function.</p>
<p>Turns out that <code>ErrorException()</code> is actually less useful than <code>Error()</code></p>
<p>How can I get more in depth reporting. Particularly a full recursive dump of the <code>Message</code> property of all inner <code>Exceptions</code>?</p> | 5,566,843 | 2 | 0 | null | 2011-04-06 12:54:53.173 UTC | 5 | 2014-11-11 01:04:09.097 UTC | 2012-09-28 07:48:58.8 UTC | null | 162,671 | null | 200,669 | null | 1 | 36 | logging|nlog|exception-logging | 11,506 | <p>Add or replace the <code>${exception}</code> tag in the layout config to <code>${exception:format=tostring}</code></p>
<pre class="lang-xml prettyprint-override"><code> <targets>
<target name="errorLogFile" xsi:type="File" fileName="errors.txt"
layout="${message} ${exception:format=tostring}"/>
</targets>
</code></pre> |
16,180,265 | Automatically update Windows fully | <p>I'm working on a project where the goal is to be able to update a windows computer 100%. That means a program or a script that updates windows automatically with no user interaction at all. Ideally a standalone script that can be run from another script.</p>
<p>The reason: I need to update a lot of computers in my line of work. They can be at any patch level and everything from Windows XP to Windows 8. My goal is to start a script, wait/do something else and then find a fully patched computer.</p>
<p>I've solved a lot by finding ZTIWindowsUpdate.wsf in the <a href="http://technet.microsoft.com/en-us/solutionaccelerators/dd407791.aspx">MDT</a> <a href="http://technet.microsoft.com/en-us/library/bb693631.aspx">Task Sequence</a>. </p>
<p>This can be used like this from an admin cmd:</p>
<pre><code>cssript.exe ZTIWindowsUpdate.wsf
</code></pre>
<p>My problem so far is that the computer requires a reboot between some of the updates. Probably because of dependencies. ZTIWindowsUpdate.wsf needs to be run as administrator and i can't seem to find a solution to start it as administrator at reboot. Additionally if I get the script to run on startup, how do I stop it, and how do I know when its <em>time</em> to stop it?</p>
<p>Can someone help med with a foolproof solution to this problem?</p>
<p>Thanks!</p> | 16,226,640 | 6 | 0 | null | 2013-04-23 22:31:10.397 UTC | 2 | 2015-10-28 14:36:21.633 UTC | null | null | null | null | 1,470,227 | null | 1 | 6 | windows|batch-file|automation|windows-update|mdt | 74,941 | <p>The simplest solution to the problem you're describing is to get your script to configure automatic logon for the built-in Administrator account, then add itself to the Startup folder. You do need to know (or reset) the Administrator account password to use this option.</p>
<p>There are many other possibilities, some examples are: use a startup script and psexec; use srvany to create a service that runs your script; use task scheduler to schedule your script to run automatically, either interactively or non-interactively; disable WUA, configure automatic logon for the account you're using, and add your script to the Startup folder.</p>
<p>Note that you'll save time and bandwidth if you can set up a WSUS server or (even simpler, and cheaper if you don't already have a Windows server) a transparent caching proxy. However this won't avoid the need to reboot during the update sequence.</p>
<p>You may find <a href="http://www.scms.waikato.ac.nz/~harry/wsusupdate.vbs" rel="nofollow">my script</a> useful as an alternative starting point to ZTIWindowsUpdate.wsf, if only because it is smaller and simpler to understand.</p> |
539,199 | How to get a list of all SVN commits in a repository and who did what to what files? | <p>I'm needing to get a list with all the revisions and files modified in each one, and by who.</p>
<p>Is that possible?</p>
<p>I need to know who user did the most changes to the repo and what changes.</p> | 539,229 | 7 | 0 | null | 2009-02-11 22:41:32.367 UTC | 7 | 2012-06-28 05:12:29.67 UTC | null | null | null | Leandro Ardissone | 42,565 | null | 1 | 35 | svn|version-control|repository | 60,193 | <p>In the root of the working copy, type</p>
<pre><code>svn log -v
</code></pre>
<p>This will give you everything. If this is too much then use <code>--limit</code>:</p>
<pre><code>svn log -v --limit 100
</code></pre>
<p>See the <a href="http://svnbook.red-bean.com/en/1.5/svn.ref.svn.c.log.html" rel="noreferrer">log command</a> in the <a href="http://svnbook.red-bean.com/" rel="noreferrer">SVN Book</a>.</p> |
863,893 | Windows Callgrind results browser, alternative to KCacheGrind | <p>Is there any tool, other than KCacheGrind, being able to view callgrind results? Preferably for Windows platform?</p> | 897,453 | 7 | 5 | null | 2009-05-14 15:07:42.68 UTC | 19 | 2020-05-21 12:09:57.447 UTC | 2009-05-14 15:49:48.913 UTC | anon | null | anon | null | null | 1 | 35 | windows|valgrind|profiling|callgrind | 32,349 | <p><a href="http://alleyoop.sourceforge.net/" rel="nofollow noreferrer">alleyoop</a> and <a href="https://#" rel="nofollow noreferrer">valkyrie (broken link)</a> are alternative front ends.</p>
<p>May have enough suport for what you want, you can use mingw to compile for Windows native if SUA does not work out of the box.</p> |
1,276,294 | Getting IPV4 address from a sockaddr structure | <p>How can I extract an IP address into a string? I can't find a reference that tells me how <code>char sa_data[14]</code> is encoded.</p> | 1,276,307 | 7 | 0 | null | 2009-08-14 06:11:23.673 UTC | 17 | 2021-07-19 19:21:29.187 UTC | 2010-04-26 22:35:20.383 UTC | null | 164,901 | null | 127,590 | null | 1 | 62 | c|ip-address | 124,822 | <p>Once <code>sockaddr</code> cast to <code>sockaddr_in</code>, it becomes this:</p>
<pre><code>struct sockaddr_in {
u_short sin_family;
u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8];
};
</code></pre> |
916,051 | Are there any platforms where pointers to different types have different sizes? | <p>The C standard allows pointers to different types to have different sizes, e.g. <code>sizeof(char*) != sizeof(int*)</code> is permitted. It does, however, require that if a pointer is converted to a <code>void*</code> and then converted back to its original type, it must compare as equal to its original value. Therefore, it follows logically that <code>sizeof(void*) >= sizeof(T*)</code> for all types <code>T</code>, correct?</p>
<p>On most common platforms in use today (x86, PPC, ARM, and 64-bit variants, etc.), the size of all pointers equals the native register size (4 or 8 bytes), regardless of the pointed-to type. Are there any esoteric or embedded platforms where pointers to different types might have different sizes? I'm specifically asking about <em>data</em> pointers, although I'd also be interested to know if there are platforms where <em>function</em> pointers have unusual sizes.</p>
<p>I'm definitely <em>not</em> asking about C++'s pointer-to-members and pointer-to-member-functions. Those take on unusual sizes on common platforms, and can even vary within one platform, depending on the properties of the pointer-to class (non-polymorphic, single inheritance, multiple inheritance, virtual inheritance, or incomplete type).</p> | 1,539,196 | 7 | 8 | null | 2009-05-27 14:35:02.627 UTC | 23 | 2017-10-31 20:18:31.89 UTC | 2017-10-31 20:18:31.89 UTC | null | 9,530 | null | 9,530 | null | 1 | 67 | c|pointers|sizeof | 5,937 | <p><a href="http://c-faq.com/null/machexamp.html" rel="noreferrer">Answer from the C FAQ</a>:</p>
<blockquote>
<p>The Prime 50 series used segment 07777, offset 0 for the null pointer, at least for PL/I. Later models used segment 0, offset 0 for null pointers in C, necessitating new instructions such as TCNP (Test C Null Pointer), evidently as a sop to all the extant poorly-written C code which made incorrect assumptions. Older, word-addressed Prime machines were also notorious for requiring larger byte pointers (char *'s) than word pointers (int *'s).</p>
<p>The Eclipse MV series from Data General has three architecturally supported pointer formats (word, byte, and bit pointers), two of which are used by C compilers: byte pointers for char * and void *, and word pointers for everything else. For historical reasons during the evolution of the 32-bit MV line from the 16-bit Nova line, word pointers and byte pointers had the offset, indirection, and ring protection bits in different places in the word. Passing a mismatched pointer format to a function resulted in protection faults. Eventually, the MV C compiler added many compatibility options to try to deal with code that had pointer type mismatch errors.</p>
<p>Some Honeywell-Bull mainframes use the bit pattern 06000 for (internal) null pointers.</p>
<p>The CDC Cyber 180 Series has 48-bit pointers consisting of a ring, segment, and offset. Most users (in ring 11) have null pointers of 0xB00000000000. It was common on old CDC ones-complement machines to use an all-one-bits word as a special flag for all kinds of data, including invalid addresses.</p>
<p>The old HP 3000 series uses a different addressing scheme for byte addresses than for word addresses; like several of the machines above it therefore uses different representations for char * and void * pointers than for other pointers.</p>
<p>The Symbolics Lisp Machine, a tagged architecture, does not even have conventional numeric pointers; it uses the pair (basically a nonexistent handle) as a C null pointer.</p>
<p>Depending on the ``memory model'' in use, 8086-family processors (PC
compatibles) may use 16-bit data pointers and 32-bit function
pointers, or vice versa.</p>
<p>Some 64-bit Cray machines represent int * in the lower 48 bits of a
word; char * additionally uses some of the upper 16 bits to indicate a
byte address within a word.</p>
<p>Additional links: A <a href="http://c-faq.com/null/wierdptrs.ct.html" rel="noreferrer">message from Chris Torek</a> with more details
about some of these machines.</p>
</blockquote> |
210,567 | Package structure for a Java project? | <p>Whats the best practice for setting up package structures in a Java Web Application?</p>
<p>How would you setup your src, unit test code, etc?</p> | 210,576 | 7 | 0 | null | 2008-10-16 22:48:28.873 UTC | 63 | 2021-05-18 14:52:30.973 UTC | 2009-05-22 10:49:37.447 UTC | jjnguy | 56,285 | mawaldne | 24,717 | null | 1 | 140 | java|package | 197,320 | <p>You could follow maven's <a href="http://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html" rel="noreferrer">standard project layout</a>. You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since many open source projects are layed out this way,</p> |
537,308 | How to verify that method was NOT called in Moq? | <p>How do I verify that method was NOT called in <a href="http://code.google.com/p/moq/" rel="noreferrer">Moq</a>? </p>
<p>Does it have something like AssertWasNotCalled?</p>
<p>UPDATE: Starting from Version 3.0, a new syntax can be used:</p>
<pre><code>mock.Verify(foo => foo.Execute("ping"), Times.Never());
</code></pre> | 537,525 | 8 | 1 | null | 2009-02-11 15:24:21.093 UTC | 36 | 2022-02-07 03:02:04.643 UTC | 2014-08-28 21:36:58.343 UTC | alex | 76,337 | alex | 19,268 | null | 1 | 526 | c#|.net|moq | 99,326 | <p><strong>UPDATE</strong>: Since version 3, check the update to the question above or Dann's answer below.</p>
<p>Either, make your mock strict so it will fail if you call a method for which you don't have an expect</p>
<pre><code>new Mock<IMoq>(MockBehavior.Strict)
</code></pre>
<p>Or, if you want your mock to be loose, use the .Throws( Exception )</p>
<pre><code>var m = new Mock<IMoq>(MockBehavior.Loose);
m.Expect(a => a.moo()).Throws(new Exception("Shouldn't be called."));
</code></pre> |
1,181,421 | Is it possible to encrypt with private key using .net RSACryptoServiceProvider? | <p>I know that RSACryptoServiceProvider can encrypt with the public key, then it can be decrypted with the private key.</p>
<p>Is it possible to encrypt with the private key and decrypt with the public key using the RSACryptoServiceProvider ?</p> | 1,181,435 | 9 | 1 | null | 2009-07-25 06:51:48.02 UTC | 11 | 2019-07-10 04:40:38.583 UTC | 2014-07-02 07:31:09.517 UTC | null | 3,745,022 | null | 102,588 | null | 1 | 19 | .net|cryptography|rsa | 32,330 | <p>No. That's not how any public/private key encryption works. You can only encrypt with the public key, and only decrypt with the private key.</p>
<p>If you want to apply the private key to a message, maybe you're looking for a <a href="https://en.wikipedia.org/wiki/Digital_signature" rel="noreferrer">signature</a>, rather than encryption? This is a different cryptographic scheme that can also use RSA keys.</p> |
821,516 | Browser-independent way to detect when image has been loaded | <p>In IE, you can onreadystatechange. There's onload, but I read <a href="https://stackoverflow.com/questions/198892/img-onload-doesnt-work-well-in-ie7">scary things</a>. jQuery wraps up the DOM's load event quite nicely with "ready". It seems likely I am just ignorant of another nice library's implementation of image loading. </p>
<p>The context is that I am generating images dynamically (via server callbacks) that can take some time download. In my IE-only code I set the src of the img element, then when the onreadystatechange event fires with the "complete" status, I add it to the DOM so the user sees it.</p>
<p>I'd be happy with a "native" JavaScript solution, or a pointer to a library that does the work. There's so many libraries out there and I'm sure this is a case of me just not knowing about the right one. That said, we're already jQuery users, so I'm not eager to add a very large library just to get this functionality.</p> | 3,016,076 | 9 | 4 | null | 2009-05-04 19:17:54.53 UTC | 20 | 2019-09-04 01:44:40.093 UTC | 2017-05-23 12:10:16.147 UTC | null | -1 | null | 92,587 | null | 1 | 55 | javascript|dom | 48,112 | <p><strong>NOTE:</strong> I wrote this in 2010, the browsers in the wild were IE 8/9 beta, Firefox 3.x, and Chrome 4.x. Please use this for research purposes only, I doubt you could copy/paste this into a modern browser and have it work without issue.</p>
<p><strong>WARNING:</strong> It is 2017 now I still get points on this now and then, please only use this for research purposes. I currently have no idea how to detect image loading status, but there are probably much more graceful ways of doing it than this... at least I seriously hope there are. I highly recommend NOT using my code in a production environment without more research.</p>
<p><strong>WARNING Part Two Electric Boogaloo:</strong> It is 2019 now, most jQuery functionality is built into vanilla JS now. If you're still using it, it may be time to stop and consider heading over to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" rel="nofollow noreferrer">MDN</a> and reading up on some of the new and fun stuff vanilla JS has to offer.</p>
<hr>
<p>I'm a bit late to this party, maybe this answer will help someone else...</p>
<p>If you're using jQuery don't bother with the stock event handlers (onclick/onmouseover/etc), actually just stop using them altogether. Use the event methods they provided in their <a href="http://api.jquery.com/category/events/" rel="nofollow noreferrer">API</a>.</p>
<hr>
<p>This will alert, before the image is appended to the body, because load event is triggered when the image is loaded into memory. It is doing exactly what you tell it to: create an image with the src of test.jpg, when test.jpg loads do an alert, then append it to the body.</p>
<pre><code>var img = $('<img src="test.jpg" />');
img.load(function() {
alert('Image Loaded');
});
$('body').append(img);
</code></pre>
<hr>
<p>This will alert, after the image is inserted into the body, again, doing what you told it to: create an image, set an event (no src set, so it hasn't loaded), append the image to the body (still no src), now set the src... now the image is loaded so the event is triggered.</p>
<pre><code>var img = $('<img />');
img.load(function() {
alert('Image Loaded');
});
$('body').append(img);
$img.attr('src','test.jpg');
</code></pre>
<hr>
<p>You can of course also add an error handler and merge a bunch of events using bind().</p>
<pre><code>var img = $('<img />');
img.bind({
load: function() {
alert('Image loaded.');
},
error: function() {
alert('Error thrown, image didn\'t load, probably a 404.');
}
});
$('body').append(img);
img.attr('src','test.jpg');
</code></pre>
<hr>
<p>Per the request by @ChrisKempen ...</p>
<p>Here is a non-event driven way of determining if the images are broken after the DOM is loaded. This code is a derivative of code from an article by <a href="http://stereochro.me/ideas/detecting-broken-images-js" rel="nofollow noreferrer">StereoChrome</a> which uses naturalWidth, naturalHeight, and complete attributes to determine if the image exists.</p>
<pre><code>$('img').each(function() {
if (this.naturalWidth === 0 || this.naturalHeight === 0 || this.complete === false) {
alert('broken image');
}
});
</code></pre> |
734,689 | Sqlite primary key on multiple columns | <p>What is the syntax for specifying a primary key on more than 1 column in SQLITE ? </p> | 734,704 | 9 | 2 | null | 2009-04-09 15:17:31.807 UTC | 78 | 2020-12-28 16:40:46.34 UTC | 2018-04-10 14:46:49.643 UTC | null | 42,223 | null | 21,634 | null | 1 | 714 | sqlite|primary-key|ddl|composite-primary-key | 325,145 | <p>According to the <a href="http://www.sqlite.org/lang_createtable.html" rel="noreferrer">documentation</a>, it's</p>
<pre><code>CREATE TABLE something (
column1,
column2,
column3,
PRIMARY KEY (column1, column2)
);
</code></pre> |
639,393 | HTML Encoding in T-SQL? | <p>Is there any function to encode HTML strings in T-SQL? I have a legacy database which contains dodgey characters such as '<', '>' etc. I can write a function to replace the characters but is there a better way?</p>
<p>I have an ASP.Net application and when it returns a string it contains characters which cause an error. The ASP.Net application is reading the data from a database table. It does not write to the table itself.</p> | 1,476,575 | 10 | 3 | null | 2009-03-12 16:18:07.937 UTC | 2 | 2018-07-04 00:55:12.02 UTC | 2009-03-12 16:27:55.883 UTC | Leo Moore | 6,336 | Leo Moore | 6,336 | null | 1 | 19 | asp.net|sql|tsql | 59,017 | <p>We have a legacy system that uses a trigger and dbmail to send HTML encoded email when a table is entered, so we require encoding within the email generation. I noticed that Leo's version has a slight bug that encodes the & in <code>&lt;</code> and <code>&gt;</code> I use this version:</p>
<pre><code>CREATE FUNCTION HtmlEncode
(
@UnEncoded as varchar(500)
)
RETURNS varchar(500)
AS
BEGIN
DECLARE @Encoded as varchar(500)
--order is important here. Replace the amp first, then the lt and gt.
--otherwise the &lt will become &amp;lt;
SELECT @Encoded =
Replace(
Replace(
Replace(@UnEncoded,'&','&amp;'),
'<', '&lt;'),
'>', '&gt;')
RETURN @Encoded
END
GO
</code></pre> |
1,091,945 | What characters do I need to escape in XML documents? | <p>What characters must be escaped in XML documents, or where could I find such a list?</p> | 1,091,953 | 10 | 6 | null | 2009-07-07 12:07:42.727 UTC | 296 | 2021-12-04 01:13:38.787 UTC | 2014-09-04 14:44:26.15 UTC | null | 246,246 | null | 13,370 | null | 1 | 1,063 | xml|escaping|character | 1,162,909 | <p>If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation.</p>
<h1>XML escape characters</h1>
<p>There are only five:</p>
<pre><code>" &quot;
' &apos;
< &lt;
> &gt;
& &amp;
</code></pre>
<p>Escaping characters depends on where the special character is used.</p>
<p>The examples can be validated at the <a href="https://validator.w3.org/#validate_by_input" rel="noreferrer">W3C Markup Validation Service</a>.</p>
<h2>Text</h2>
<p>The safe way is to escape all five characters in text. However, the three characters <code>"</code>, <code>'</code> and <code>></code> needn't be escaped in text:</p>
<pre><code><?xml version="1.0"?>
<valid>"'></valid>
</code></pre>
<h2>Attributes</h2>
<p>The safe way is to escape all five characters in attributes. However, the <code>></code> character needn't be escaped in attributes:</p>
<pre><code><?xml version="1.0"?>
<valid attribute=">"/>
</code></pre>
<p>The <code>'</code> character needn't be escaped in attributes if the quotes are <code>"</code>:</p>
<pre><code><?xml version="1.0"?>
<valid attribute="'"/>
</code></pre>
<p>Likewise, the <code>"</code> needn't be escaped in attributes if the quotes are <code>'</code>:</p>
<pre><code><?xml version="1.0"?>
<valid attribute='"'/>
</code></pre>
<h2>Comments</h2>
<p>All five special characters <strong>must not</strong> be escaped in comments:</p>
<pre><code><?xml version="1.0"?>
<valid>
<!-- "'<>& -->
</valid>
</code></pre>
<h2>CDATA</h2>
<p>All five special characters <strong>must not</strong> be escaped in <a href="https://en.wikipedia.org/wiki/CDATA" rel="noreferrer">CDATA</a> sections:</p>
<pre><code><?xml version="1.0"?>
<valid>
<![CDATA["'<>&]]>
</valid>
</code></pre>
<h2>Processing instructions</h2>
<p>All five special characters <strong>must not</strong> be escaped in XML processing instructions:</p>
<pre><code><?xml version="1.0"?>
<?process <"'&> ?>
<valid/>
</code></pre>
<h1>XML vs. HTML</h1>
<p>HTML has <a href="http://www.escapecodes.info/" rel="noreferrer">its own set of escape codes</a> which cover a lot more characters.</p> |
60,805 | Getting random row through SQLAlchemy | <p>How do I select one or more random rows from a table using SQLAlchemy? </p> | 60,815 | 10 | 0 | null | 2008-09-13 19:58:02.897 UTC | 17 | 2021-10-12 17:18:57.267 UTC | 2020-06-16 04:54:17.6 UTC | null | 815,724 | cnu | 1,448 | null | 1 | 97 | python|sql|database|random|sqlalchemy | 45,487 | <p>This is very much a database-specific issue.</p>
<p>I know that PostgreSQL, SQLite, MySQL, and Oracle have the ability to order by a random function, so you can use this in SQLAlchemy:</p>
<pre><code>from sqlalchemy.sql.expression import func, select
select.order_by(func.random()) # for PostgreSQL, SQLite
select.order_by(func.rand()) # for MySQL
select.order_by('dbms_random.value') # For Oracle
</code></pre>
<p>Next, you need to limit the query by the number of records you need (for example using <code>.limit()</code>).</p>
<p>Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; <a href="http://www.depesz.com/index.php/2007/09/16/my-thoughts-on-getting-random-row/" rel="noreferrer">here</a> is good article about it.</p> |
27,065 | Tool to read and display Java .class versions | <p>Do any of you know of a tool that will search for .class files and then display their compiled versions?</p>
<p>I know you can look at them individually in a hex editor but I have a lot of class files to look over (something in my giant application is compiling to Java6 for some reason).</p> | 27,505 | 10 | 1 | null | 2008-08-25 22:52:02.667 UTC | 32 | 2021-12-10 15:46:45.45 UTC | 2016-08-24 19:30:11.557 UTC | null | 276,052 | SCdF | 1,666 | null | 1 | 124 | jvm-bytecode | 64,960 | <p>Use the <a href="http://java.sun.com/javase/6/docs/technotes/tools/solaris/javap.html" rel="noreferrer">javap</a> tool that comes with the JDK. The <code>-verbose</code> option will print the version number of the class file.</p>
<pre><code>> javap -verbose MyClass
Compiled from "MyClass.java"
public class MyClass
SourceFile: "MyClass.java"
minor version: 0
major version: 46
...
</code></pre>
<p>To only show the version:</p>
<pre><code>WINDOWS> javap -verbose MyClass | find "version"
LINUX > javap -verbose MyClass | grep version
</code></pre> |
128,623 | Disable all table constraints in Oracle | <p>How can I disable all table constrains in Oracle with a single command?
This can be either for a single table, a list of tables, or for all tables.</p> | 131,595 | 11 | 0 | null | 2008-09-24 17:45:09.573 UTC | 48 | 2022-07-22 11:05:01.633 UTC | null | null | null | oneself | 9,435 | null | 1 | 98 | sql|oracle | 239,003 | <p>It is better to avoid writing out temporary spool files. Use a PL/SQL block. You can run this from SQL*Plus or put this thing into a package or procedure. The join to USER_TABLES is there to avoid view constraints.</p>
<p>It's unlikely that you really want to disable all constraints (including NOT NULL, primary keys, etc). You should think about putting constraint_type in the WHERE clause.</p>
<pre><code>BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'ENABLED'
AND NOT (t.iot_type IS NOT NULL AND c.constraint_type = 'P')
ORDER BY c.constraint_type DESC)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" disable constraint ' || c.constraint_name);
END LOOP;
END;
/
</code></pre>
<p>Enabling the constraints again is a bit tricker - you need to enable primary key constraints before you can reference them in a foreign key constraint. This can be done using an ORDER BY on constraint_type. 'P' = primary key, 'R' = foreign key.</p>
<pre><code>BEGIN
FOR c IN
(SELECT c.owner, c.table_name, c.constraint_name
FROM user_constraints c, user_tables t
WHERE c.table_name = t.table_name
AND c.status = 'DISABLED'
ORDER BY c.constraint_type)
LOOP
dbms_utility.exec_ddl_statement('alter table "' || c.owner || '"."' || c.table_name || '" enable constraint ' || c.constraint_name);
END LOOP;
END;
/
</code></pre> |
1,063,513 | Getting unix timestamp in milliseconds in PHP5 and Actionscript3 | <p>In Actionscript, the Unix timestamp in milliseconds is obtainable like this:</p>
<pre><code>public static function getTimeStamp():uint
{
var now:Date = new Date();
return now.getTime();
}
</code></pre>
<p>The doc clearly states the following: </p>
<blockquote>
<p>getTime():Number Returns the number of
milliseconds since midnight January 1,
1970, universal time, for a Date
object.</p>
</blockquote>
<p>When I trace it, it returns the following:</p>
<pre><code>824655597
</code></pre>
<p>So, 824655597 / 1000 / 60 / 60 / 24 / 365 = 0.02 years.
This is obviously not correct, as it should be around 39 years.</p>
<p>Question #1: What's wrong here?</p>
<p>Now, onto the PHP part: I'm trying to get the timestamp in milliseconds there as well. The <code>microtime()</code> function returns either a string (0.29207800 1246365903) or a float (1246365134.01), depending on the given argument. Because I thought timestamps were easy, I was going to do this myself. But now that I have tried and noticed this float, and combine that with my problems in Actionscript I really have no clue.</p>
<p>Question #2: how should I make it returns the amount of milliseconds in a Unix timestamp?</p>
<p>Timestamps should be so easy, I'm probably missing something.. sorry about that. Thanks in advance.</p>
<p><strong>EDIT1:</strong> Answered the first question by myself. See below.<br>
<strong>EDIT2:</strong> Answered second question by myself as well. See below. Can't accept answer within 48 hours.</p> | 1,063,614 | 12 | 0 | null | 2009-06-30 12:54:15.193 UTC | 3 | 2019-07-07 10:04:01.9 UTC | 2012-06-02 15:04:28.403 UTC | null | 367,456 | null | 45,974 | null | 1 | 28 | php|actionscript-3|unix|timestamp | 68,118 | <p>For actionscript3, <code>new Date().getTime()</code> should work.</p>
<hr>
<p>In PHP you can simply call <a href="http://www.php.net/time" rel="noreferrer">time()</a> to get the time passed since January 1 1970 00:00:00 GMT in seconds. If you want milliseconds just do <code>(time()*1000)</code>.</p>
<p>If you use <a href="http://www.php.net/manual/en/function.microtime.php" rel="noreferrer">microtime()</a> multiply the second part with 1000 to get milliseconds. Multiply the first part with 1000 to get the milliseconds and round that. Then add the two numbers together. Voilá.</p> |
249,301 | Simple Random Samples from a Sql database | <p>How do I take an efficient simple random sample in SQL? The database in question is running MySQL; my table is at least 200,000 rows, and I want a simple random sample of about 10,000.</p>
<p>The "obvious" answer is to:</p>
<pre><code>SELECT * FROM table ORDER BY RAND() LIMIT 10000
</code></pre>
<p>For large tables, that's too slow: it calls <code>RAND()</code> for every row (which already puts it at O(n)), and sorts them, making it O(n lg n) at best. Is there a way to do this faster than O(n)?</p>
<p><em>Note</em>: As Andrew Mao points out in the comments, If you're using this approach on SQL Server, you should use the T-SQL function <code>NEWID()</code>, because RAND() <a href="http://msdn.microsoft.com/en-us/library/ms177610.asp" rel="noreferrer">may return the same value for all rows</a>.</p>
<p><em>EDIT: 5 YEARS LATER</em></p>
<p>I ran into this problem again with a bigger table, and ended up using a version of @ignorant's solution, with two tweaks:</p>
<ul>
<li>Sample the rows to 2-5x my desired sample size, to cheaply <code>ORDER BY RAND()</code></li>
<li>Save the result of <code>RAND()</code> to an indexed column on every insert/update. (If your data set isn't very update-heavy, you may need to find another way to keep this column fresh.)</li>
</ul>
<p>To take a 1000-item sample of a table, I count the rows and sample the result down to, on average, 10,000 rows with the the frozen_rand column:</p>
<pre><code>SELECT COUNT(*) FROM table; -- Use this to determine rand_low and rand_high
SELECT *
FROM table
WHERE frozen_rand BETWEEN %(rand_low)s AND %(rand_high)s
ORDER BY RAND() LIMIT 1000
</code></pre>
<p>(My actual implementation involves more work to make sure I don't undersample, and to manually wrap rand_high around, but the basic idea is "randomly cut your N down to a few thousand.")</p>
<p>While this makes some sacrifices, it allows me to sample the database down using an index scan, until it's small enough to <code>ORDER BY RAND()</code> again.</p> | 252,563 | 12 | 5 | null | 2008-10-30 04:48:02.847 UTC | 37 | 2020-10-30 16:20:28.923 UTC | 2020-10-16 18:06:46.43 UTC | chills42 | 20,760 | null | 20,760 | null | 1 | 122 | mysql|sql|postgresql|random | 183,353 | <p>There's a very interesting discussion of this type of issue here: <a href="http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/" rel="noreferrer"><a href="http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/" rel="noreferrer">http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/</a></a></p>
<p>I think with absolutely no assumptions about the table that your O(n lg n) solution is the best. Though actually with a good optimizer or a slightly different technique the query you list may be a bit better, O(m*n) where m is the number of random rows desired, as it wouldn't necesssarily have to sort the whole large array, it could just search for the smallest m times. But for the sort of numbers you posted, m is bigger than lg n anyway.</p>
<p>Three asumptions we might try out:</p>
<ol>
<li><p>there is a unique, indexed, primary key in the table</p></li>
<li><p>the number of random rows you want to select (m) is much smaller than the number of rows in the table (n)</p></li>
<li><p>the unique primary key is an integer that ranges from 1 to n with no gaps</p></li>
</ol>
<p>With only assumptions 1 and 2 I think this can be done in O(n), though you'll need to write a whole index to the table to match assumption 3, so it's not necesarily a fast O(n). If we can ADDITIONALLY assume something else nice about the table, we can do the task in O(m log m). Assumption 3 would be an easy nice additional property to work with. With a nice random number generator that guaranteed no duplicates when generating m numbers in a row, an O(m) solution would be possible. </p>
<p>Given the three assumptions, the basic idea is to generate m unique random numbers between 1 and n, and then select the rows with those keys from the table. I don't have mysql or anything in front of me right now, so in slightly pseudocode this would look something like:</p>
<pre><code>
create table RandomKeys (RandomKey int)
create table RandomKeysAttempt (RandomKey int)
-- generate m random keys between 1 and n
for i = 1 to m
insert RandomKeysAttempt select rand()*n + 1
-- eliminate duplicates
insert RandomKeys select distinct RandomKey from RandomKeysAttempt
-- as long as we don't have enough, keep generating new keys,
-- with luck (and m much less than n), this won't be necessary
while count(RandomKeys) < m
NextAttempt = rand()*n + 1
if not exists (select * from RandomKeys where RandomKey = NextAttempt)
insert RandomKeys select NextAttempt
-- get our random rows
select *
from RandomKeys r
join table t ON r.RandomKey = t.UniqueKey
</code></pre>
<p>If you were really concerned about efficiency, you might consider doing the random key generation in some sort of procedural language and inserting the results in the database, as almost anything other than SQL would probably be better at the sort of looping and random number generation required.</p> |
268,648 | How do I sort arrays using vbscript? | <p>I'm scanning through a file looking for lines that match a certain regex pattern, and then I want to print out the lines that match but in alphabetical order. I'm sure this is trivial but vbscript isn't my background</p>
<p>my array is defined as</p>
<pre><code>Dim lines(10000)
</code></pre>
<p>if that makes any difference, and I'm trying to execute my script from a normal cmd prompt</p> | 268,659 | 13 | 0 | null | 2008-11-06 13:16:41.94 UTC | 9 | 2021-11-29 09:21:57.547 UTC | 2020-08-07 19:33:39.55 UTC | Oskar | 2,756,409 | Oskar | 5,472 | null | 1 | 34 | vbscript|sorting | 124,357 | <p>From <a href="http://www.microsoft.com/technet/scriptcenter/funzone/games/tips08/gtip1130.mspx#E4C" rel="noreferrer">microsoft</a></p>
<p>Sorting arrays in VBScript has never been easy; that’s because VBScript doesn’t have a sort command of any kind. In turn, that always meant that VBScript scripters were forced to write their own sort routines, be that a bubble sort routine, a heap sort, a quicksort, or some other type of sorting algorithm.</p>
<p>So (using .Net as it is installed on my pc):</p>
<pre><code>Set outputLines = CreateObject("System.Collections.ArrayList")
'add lines
outputLines.Add output
outputLines.Add output
outputLines.Sort()
For Each outputLine in outputLines
stdout.WriteLine outputLine
Next
</code></pre> |
37,122 | Make browser window blink in task Bar | <p>How do I make a user's browser blink/flash/highlight in the task bar using JavaScript? For example, if I make an AJAX request every 10 seconds to see if the user has any new messages on the server, I want the user to know it right away, even if he is using another application at the time.</p>
<p><em>Edit: These users do want to be distracted when a new message arrives.</em></p> | 156,274 | 13 | 1 | null | 2008-08-31 21:22:51.93 UTC | 45 | 2021-02-13 17:55:56.87 UTC | 2015-04-17 21:19:22.247 UTC | erik | 3,889,449 | erik | 1,191 | null | 1 | 106 | javascript|browser | 114,269 | <p>this won't make the taskbar button flash in changing colours, but the title will blink on and off until they move the mouse. This should work cross platform, and even if they just have it in a different tab.</p>
<pre><code>newExcitingAlerts = (function () {
var oldTitle = document.title;
var msg = "New!";
var timeoutId;
var blink = function() { document.title = document.title == msg ? ' ' : msg; };
var clear = function() {
clearInterval(timeoutId);
document.title = oldTitle;
window.onmousemove = null;
timeoutId = null;
};
return function () {
if (!timeoutId) {
timeoutId = setInterval(blink, 1000);
window.onmousemove = clear;
}
};
}());
</code></pre>
<hr>
<p><em>Update</em>: You may want to look at using <a href="https://paulund.co.uk/how-to-use-the-html5-notification-api" rel="noreferrer">HTML5 notifications</a>.</p> |
1,011,938 | Loop that also accesses previous and next values | <p>How can I iterate over a list of objects, accessing the previous, current, and next items? Like this C/C++ code, in Python?</p>
<pre class="lang-c prettyprint-override"><code>foo = somevalue;
previous = next = 0;
for (i=1; i<objects.length(); i++) {
if (objects[i]==foo) {
previous = objects[i-1];
next = objects[i+1];
}
}
</code></pre> | 1,011,962 | 17 | 6 | null | 2009-06-18 10:23:38.443 UTC | 58 | 2022-06-24 09:49:02.01 UTC | 2021-04-08 19:01:04.093 UTC | null | 355,230 | null | 122,557 | null | 1 | 106 | python|loops|iteration | 267,325 | <p>This should do the trick.</p>
<pre><code>foo = somevalue
previous = next_ = None
l = len(objects)
for index, obj in enumerate(objects):
if obj == foo:
if index > 0:
previous = objects[index - 1]
if index < (l - 1):
next_ = objects[index + 1]
</code></pre>
<p>Here's the docs on the <a href="http://docs.python.org/library/functions.html#enumerate" rel="noreferrer"><code>enumerate</code></a> function.</p> |
1,005,523 | How to add one day to a date? | <p>I want to add one day to a particular date. How can I do that?</p>
<pre><code>Date dt = new Date();
</code></pre>
<p>Now I want to add one day to this date.</p> | 1,005,550 | 18 | 2 | null | 2009-06-17 07:11:34.883 UTC | 57 | 2021-07-09 09:24:37.11 UTC | 2009-06-18 08:29:17.647 UTC | null | 23,368 | null | 93,796 | null | 1 | 260 | java|datetime | 671,236 | <p>Given a <code>Date dt</code> you have several possibilities:</p>
<p><strong>Solution 1:</strong> You can use the <code>Calendar</code> class for that:</p>
<pre><code>Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(dt);
c.add(Calendar.DATE, 1);
dt = c.getTime();
</code></pre>
<p><strong>Solution 2:</strong> You should seriously consider using the <strong><a href="http://www.joda.org/joda-time/" rel="noreferrer">Joda-Time library</a></strong>, because of the various shortcomings of the <code>Date</code> class. With Joda-Time you can do the following:</p>
<pre><code>Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);
</code></pre>
<p><strong>Solution 3:</strong> With <strong>Java 8</strong> you can also use the new <strong>JSR 310</strong> API (which is inspired by Joda-Time):</p>
<pre><code>Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);
</code></pre> |
199,761 | How can you use optional parameters in C#? | <p><sup><strong>Note:</strong> This question was asked at a time when C# did not yet support optional parameters (i.e. before C# 4).</sup></p>
<p>We're building a web API that's programmatically generated from a C# class. The class has method <code>GetFooBar(int a, int b)</code> and the API has a method <code>GetFooBar</code> taking query params like <code>&a=foo &b=bar</code>. </p>
<p>The classes needs to support optional parameters, which isn't supported in C# the language. What's the best approach?</p> | 3,343,769 | 23 | 1 | null | 2008-10-14 01:55:23.053 UTC | 75 | 2022-07-25 01:55:18.86 UTC | 2017-03-20 17:38:25.193 UTC | null | 201,303 | kurious | 109 | null | 1 | 569 | c#|optional-parameters | 779,882 | <p>Surprised no one mentioned C# 4.0 optional parameters that work like this:</p>
<pre><code>public void SomeMethod(int a, int b = 0)
{
//some code
}
</code></pre>
<p><strong>Edit:</strong> I know that at the time the question was asked, C# 4.0 didn't exist. But this question still ranks #1 in Google for "C# optional arguments" so I thought - this answer worth being here. Sorry.</p> |
527,700 | What is a good desktop programming language to learn for a web developer? | <p>I'm want to learn a desktop programming language, preferably C, C++ or C#. I'm a PHP/HTML/CSS programmer and I would like to get into desktop applications. I need something pretty powerful and I would like to be able to create applications with Windows GUI's. </p>
<p>What would the Stack Overflow community recommend? Is there any knowledge I should have before diving into these languages?</p> | 527,736 | 26 | 4 | null | 2009-02-09 10:52:58.973 UTC | 9 | 2012-01-16 00:49:45.73 UTC | 2012-01-16 00:49:45.73 UTC | Roger Pate | 59,730 | Sam152 | 59,730 | null | 1 | 16 | c#|c++|c|programming-languages | 9,714 | <p>edit:</p>
<p>A <strong>web programmer</strong> wants to create <strong>Windows applications</strong> and you recommend C? <h2>What's wrong with you people?!</h2></p>
<p>/edit</p>
<h3>Obviously C#.</h3>
<p>C# will be easier to get into and will let you build Windows applications using WinForms or WPF and all the new Microsoft toys in .NET. If you know your way around PHP, you should already be familiar with the syntax, object oriented concepts, exception handling, etc. </p>
<p>I suggest you don't complicate your life with C and definitely not with C++ if all you want is to create Windows GUIs. They do provide a good educational experience and they are useful for more advanced things (cross platform development using other toolkits for instance) but at the price of a steeper learning curve and reduced productivity.</p>
<p>Also, if you are a <strong>web developer</strong>, C# is the <strong>only</strong> language among the 3 options that you can (realistically, heh) use for the web. ASP.NET is not a bad framework and might be worth investigating too.</p> |
6,865,690 | What's the point of a timestamp in OAuth if a Nonce can only be used one time? | <p>I had at first misinterpreted the timestamp implementation of OAuth into thinking that it meant a timestamp that was not within 30 seconds past the current time would be denied, it turned out this was wrong for a few reasons including the fact that we could not guarantee that each system clock was in sync enough down to the minutes and seconds regardless of time zone. Then I read it again to get more clarity:</p>
<blockquote>
<p>"Unless otherwise specified by the Service Provider, the timestamp is
expressed in the number of seconds since January 1, 1970 00:00:00 GMT.
The timestamp value MUST be a positive integer and MUST be <strong>equal or
greater than the timestamp used in previous requests</strong>."</p>
</blockquote>
<p>source: <a href="http://oauth.net/core/1.0/#nonce" rel="noreferrer">http://oauth.net/core/1.0/#nonce</a></p>
<p>Meaning the timestamps are only compared in relation to previous requests from the same source, not in comparison to my server system clock.</p>
<p>Then I read a more detailed description here: <a href="http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iii-security-architecture/" rel="noreferrer">http://hueniverse.com/2008/10/beginners-guide-to-oauth-part-iii-security-architecture/</a></p>
<p>(<strong>TL;DR?</strong> - skip to the bold parts below)</p>
<blockquote>
<p>To prevent compromised requests from being used again (replayed),
OAuth uses a nonce and timestamp. The term nonce means ‘number used
once’ and is a unique and usually random string that is meant to
uniquely identify each signed request. By having a unique identifier
for each request, the Service Provider is able to prevent requests
from being used more than once. <strong>This means the Consumer generates a
unique string for each request sent to the Service Provider, and the
Service Provider keeps track of all the nonces used to prevent them
from being used a second time.</strong> Since the nonce value is included in
the signature, it cannot be changed by an attacker without knowing the
shared secret.</p>
<p>Using nonces can be very costly for Service Providers as they demand
persistent storage of all nonce values received, ever. To make
implementations easier, OAuth adds a timestamp value to each request
which allows the Service Provider to only keep nonce values for a
limited time. <strong>When a request comes in with a timestamp that is older
than the retained time frame, it is rejected as the Service Provider
no longer has nonces from that time period.</strong> It is safe to assume that
a request sent after the allowed time limit is a replay attack. OAuth
provides a general mechanism for implementing timestamps but leaves
the actual implementation up to each Service Provider (an area many
believe should be revisited by the specification). From a security
standpoint, the real nonce is the combination of the timestamp value
and nonce string. Only together they provide a perpetual unique value
that can never be used again by an attacker.</p>
</blockquote>
<p>The reason I am confused is if the Nonce is only used once, why would the Service Provider ever reject based on timestamp? "Service Provider no longer has nonces from that time period" is confusing to me and sounds as if a nonce can be re-used as long as it is within 30 seconds of <em>the last time it was used.</em></p>
<p>So can anyone clear this up for me? What is the point of the timestamp if the nonce is a one time use and I am not comparing the timestamp against my own system clock (because that obviously would not be reliable). It makes sense that the timestamps will only be relative to each other, but with the unique nonce requirement it seems irrelevant.</p> | 6,876,907 | 4 | 0 | null | 2011-07-28 21:08:22.217 UTC | 14 | 2017-01-03 20:30:34.95 UTC | null | null | null | null | 18,309 | null | 1 | 41 | oauth|unix-timestamp|nonce | 25,331 | <p>The timestamp is used for allowing the server to optimize their storage of nonces. Basically, consider the read nonce to be the combination of the timestamp and random string. But by having a separate timestamp component, the server can implement a time-based restriction using a short window (say, 15 minutes) and limit the amount of storage it needs. Without timestamps, the server will need infinite storage to keep every nonce ever used.</p>
<p>Let's say you decide to allow up to 15 minutes time difference between your clock and the client's and are keeping track of the nonce values in a database table. The unique key for the table is going to be a combination of 'client identifier', 'access token', 'nonce', and 'timestamp'. When a new request comes in, check that the timestamp is within 15 minutes of your clock then lookup that combination in your table. If found, reject the call, otherwise add that to your table and return the requested resource. Every time you add a new nonce to the table, delete any record for that 'client identifier' and 'access token' combination with timestamp older than 15 minutes.</p> |
6,399,676 | How does OpenGL work at the lowest level? | <p>I understand how to write OpenGL/DirectX programs, and I know the maths and the conceptual stuff behind it, but I'm curious how the GPU-CPU communication works on a low level.</p>
<p>Say I've got an OpenGL program written in C that displays a triangle and rotates the camera by 45 degrees. When I compile this program, will it be turned into a series of ioctl-calls, and the gpu driver then sends the appropriate commands to the gpu, where all the logic of rotating the triangle and setting the appropriate pixels in the appropriate color is wired in? Or will the program be compiled into a "gpu program" which is loaded onto the gpu and computes the rotation etc.? Or something completely different?</p>
<p><strong>Edit</strong>:
A few days later I found this article series, which basically answers the question:
<a href="http://fgiesen.wordpress.com/2011/07/01/a-trip-through-the-graphics-pipeline-2011-part-1/" rel="noreferrer">http://fgiesen.wordpress.com/2011/07/01/a-trip-through-the-graphics-pipeline-2011-part-1/</a></p> | 6,401,607 | 4 | 1 | null | 2011-06-19 00:05:35.393 UTC | 65 | 2016-03-10 17:48:58.597 UTC | 2011-07-04 00:01:32.753 UTC | null | 92,560 | null | 92,560 | null | 1 | 95 | opengl|gpu | 39,495 | <p>This question is almost impossible to answer because OpenGL by itself is just a front end API, and as long as an implementations adheres to the specification and the outcome conforms to this it can be done any way you like.</p>
<p>The question may have been: How does an OpenGL driver work on the lowest level. Now this is again impossible to answer in general, as a driver is closely tied to some piece of hardware, which may again do things however the developer designed it.</p>
<p>So the question should have been: "How does it look on average behind the scenes of OpenGL and the graphics system?". Let's look at this from the bottom up:</p>
<ol>
<li><p>At the lowest level there's some graphics device. Nowadays these are GPUs which provide a set of registers controlling their operation (which registers exactly is device dependent) have some program memory for shaders, bulk memory for input data (vertices, textures, etc.) and an I/O channel to the rest of the system over which it recieves/sends data and command streams.</p></li>
<li><p>The graphics driver keeps track of the GPUs state and all the resources application programs that make use of the GPU. Also it is responsible for conversion or any other processing the data sent by applications (convert textures into the pixelformat supported by the GPU, compile shaders in the machine code of the GPU). Furthermore it provides some abstract, driver dependent interface to application programs.</p></li>
<li><p>Then there's the driver dependent OpenGL client library/driver. On Windows this gets
loaded by proxy through opengl32.dll, on Unix systems this resides in two places:</p>
<ul>
<li>X11 GLX module and driver dependent GLX driver</li>
<li>and /usr/lib/libGL.so may contain some driver dependent stuff for direct rendering</li>
</ul>
<p>On MacOS X this happens to be the "OpenGL Framework".</p>
<p>It is this part that translates OpenGL calls how you do it into calls to the driver specific functions in the part of the driver described in (2).</p></li>
<li><p>Finally the actual OpenGL API library, opengl32.dll in Windows, and on Unix /usr/lib/libGL.so; this mostly just passes down the commands to the OpenGL implementation proper.</p></li>
</ol>
<p>How the actual communication happens can not be generalized:</p>
<p>In Unix the 3<->4 connection may happen either over Sockets (yes, it may, and does go over network if you want to) or through Shared Memory. In Windows the interface library and the driver client are both loaded into the process address space, so that's no so much communication but simple function calls and variable/pointer passing. In MacOS X this is similar to Windows, only that there's no separation between OpenGL interface and driver client (that's the reason why MacOS X is so slow to keep up with new OpenGL versions, it always requires a full operating system upgrade to deliver the new framework).</p>
<p>Communication betwen 3<->2 may go through ioctl, read/write, or through mapping some memory into process address space and configuring the MMU to trigger some driver code whenever changes to that memory are done. This is quite similar on any operating system since you always have to cross the kernel/userland boundary: Ultimately you go through some syscall.</p>
<p>Communication between system and GPU happen through the periphial bus and the access methods it defines, so PCI, AGP, PCI-E, etc, which work through Port-I/O, Memory Mapped I/O, DMA, IRQs.</p> |
6,804,166 | What is the most efficient way to store a sort-order on a group of records in a database? | <p>Assume PHP/MYSQL but I don't necessarily need actual code, I'm just interested in the theory behind it.</p>
<p>A good use-case would be Facebook's photo gallery page. You can drag and drop a photo on the page, which fires an Ajax event to save the new sort order. I'm implementing something very similar.</p>
<p>For example, I have a database table "photos" with about a million records:</p>
<p><strong>photos</strong>
id : int,
userid : int,
albumid : int,
sortorder : int,
filename : varchar,
title : varchar</p>
<p>Let's say I have an album with 100 photos. I drag/drop a photo into a new location and the Ajax event fires off to save on the server.</p>
<p>Should I be passing the entire array of photo ids back to the server and updating every record? Assume input validation by "<code>WHERE userid</code>=<code>loggedin_id</code>", so malicious users can only mess with the sort order of their own photos</p>
<p>Should I be passing the photo id, its previous sortorder index and its new sortorder index, retrieve all records between these 2 indices, sort them, then update their orders?</p>
<p>What happens if there are thousands of photos in a single gallery and the sort order is changed?</p> | 6,804,302 | 5 | 0 | null | 2011-07-24 00:20:10.817 UTC | 22 | 2011-07-25 01:22:59.49 UTC | 2011-07-24 10:03:33.613 UTC | null | 684,229 | null | 582,581 | null | 1 | 20 | mysql|algorithm|database-design|performance | 9,521 | <p>What about just using an <code>integer</code> column which defines the order? By default you assign numbers * 1000, like 1000, 2000, 3000.... and if you move 3000 between 1000 and 2000 you change it to 1500. So in most cases you don't need to update the other numbers at all. I use this approach and it works well. You could also use <code>double</code> but then you don't have control about the precision and rounding errors, so rather don't use it.</p>
<p><strong>So the algorithm would look like</strong>: say you move B to position after A. First perform select to see the order of the record next to A. If it is at least +2 higher than the order of A then you just set order of B to fit in between. But if it's just +1 higher (there is no space after A), you select the bordering records of B to see how much space is on this side, divide by 2 and then add this value to the order of all the records between A and B. That's it! </p>
<p>(Note that you should use transaction/locking for any algorithm which contains more than a single query, so this applies to this case too. The easiest way is to use InnoDB transaction.)</p> |
6,403,716 | How to make a shortcut for moving between Vim windows? | <p>Let’s say I have single Vim tab displaying 9 buffers (equally separated, like a 3×3 table).</p>
<p>Currently, to get from the top left window to the bottom right one, I have to press <kbd>3</kbd>, <kbd>Ctrl</kbd>+<kbd>W</kbd>, <kbd>J</kbd>, and then <kbd>3</kbd>, <kbd>Ctrl</kbd>+<kbd>W</kbd>, <kbd>L</kbd>. This is cumbersome, and I would like to just be able to press <kbd>Ctrl</kbd>+<kbd>9</kbd> to go to the 9th window, and <kbd>Ctrl</kbd>+<kbd>3</kbd> to go to the 3rd window, etc.</p>
<p>Is there any easy way I can map something like this in Vim?</p> | 6,404,246 | 6 | 0 | null | 2011-06-19 16:45:35.743 UTC | 13 | 2021-01-26 04:54:56.56 UTC | 2021-01-26 04:54:28.233 UTC | null | 254,635 | null | 688,266 | null | 1 | 17 | vim|window|buffer | 12,358 | <p>There's a <em>much simpler</em> solution than using the mouse or hard-set movement mappings; they will break if the window numberings are different from what you have in mind for a 3x3 matrix, or if you decide to work with less than 9 windows. Here's how:</p>
<p>Include the following in your <code>.vimrc</code>:</p>
<pre><code>let i = 1
while i <= 9
execute 'nnoremap <Leader>' . i . ' :' . i . 'wincmd w<CR>'
let i = i + 1
endwhile
</code></pre>
<p>Now you can just press <code><Leader><number></code> and be taken to the window number you want. I wouldn't recommend going beyond 9, because IMO, the utility of having multiple viewports follows a <a href="http://en.wikipedia.org/wiki/Rayleigh_distribution" rel="noreferrer">Rayleigh distribution</a> and quickly becomes useless with too many viewports in one window.</p>
<p>It will be helpful if you have the window number displayed in your <code>statusline</code> to aid you in quickly figuring out which window you're on and which window you want to go to. To do that, use this little function and add it accordingly in your <code>statusline</code>.</p>
<pre><code>function! WindowNumber()
let str=tabpagewinnr(tabpagenr())
return str
endfunction
</code></pre>
<p>See it in action in your <code>statusline</code>:</p>
<pre><code>set laststatus=2
set statusline=win:%{WindowNumber()}
</code></pre>
<p>Note that the above line will replace your <code>statusline</code>. It was just meant for illustration purposes, to show how to call the function. You should place it where ever you think is appropriate in your <code>statusline</code>. Here's what mine looks like:</p>
<p><img src="https://i.stack.imgur.com/t82Ya.png" alt="enter image description here" /></p>
<hr />
<h3>Update</h3>
<p><a href="https://stackoverflow.com/users/546861/romainl">romainl</a> asked for my status line in the comments, so here it is:</p>
<pre><code>"statusline
hi StatusLine term=bold cterm=bold ctermfg=White ctermbg=235
hi StatusHostname term=bold cterm=bold ctermfg=107 ctermbg=235 guifg=#799d6a
hi StatusGitBranch term=bold cterm=bold ctermfg=215 ctermbg=235 guifg=#ffb964
function! MyGitBranchStyle()
let branch = GitBranch()
if branch == ''
let branchStyle = ''
else
let branchStyle = 'git:' . branch
end
return branchStyle
endfunction
function! WindowNumber()
let str=tabpagewinnr(tabpagenr())
return str
endfunction
set laststatus=2
set statusline=%#StatusLine#%F%h%m%r\ %h%w%y\ col:%c\ lin:%l\,%L\ buf:%n\ win:%{WindowNumber()}\ reg:%{v:register}\ %#StatusGitBranch#%{MyGitBranchStyle()}\ \%=%#StatusLine#%{strftime(\"%d/%m/%Y-%H:%M\")}\ %#StatusHostname#%{hostname()}
</code></pre>
<p>The last line should be a single line (be careful if your setup automatically breaks it into multiple lines). I know there are ways to keep it organized with incremental string joins in each step, but I'm too lazy to change it. :) The <code>GitBranch()</code> function (with other git capabilities) is provided by the <a href="https://github.com/motemen/git-vim" rel="noreferrer">git.vim plugin</a>. There's a bug in it as noted <a href="http://www.osnews.com/story/21556/Using_Git_with_Vim" rel="noreferrer">here</a> and I use the <a href="https://github.com/amjith/git-vim" rel="noreferrer">fork with the bug fix</a>. However, I'm leaving both links and the blog here to give credit to all.</p>
<p>Also, note that I use a dark background, so you might have to change the colours around a bit if you are using a light scheme (and also to suit your tastes).</p> |
6,675,905 | Which features make a class to be thread-safe? | <p>In MSDN some .NET classes described like this:</p>
<p>"<strong>This type is thread safe.</strong>" </p>
<p>or </p>
<p>"<strong>Public static (Shared in Visual Basic) members of this type are thread safe. Instance members are not guaranteed to be thread-safe.".</strong></p>
<p>My question is which features make a class to be thread-safe?</p>
<ul>
<li><p>Is there any standard, recommendation or guidelines for thread-safety programming?</p></li>
<li><p>When I use lock(C#) keyword, it means my class is thread-safe or not?</p></li>
<li><p>How to I evaluate thread-safety of a class? Is there any TESTS to be sure that a class is 100% thread safe?</p></li>
</ul>
<p>Example:</p>
<pre><code>public class MyClass
{
public void Method()
{
lock (this)
{
// Now, is my class 100% thread-safe like Microsoft classes?
}
}
type m_member1;
type m_member2;
}
</code></pre>
<p>thanks</p> | 6,675,972 | 6 | 3 | null | 2011-07-13 08:08:54.587 UTC | 14 | 2011-12-05 19:20:13.343 UTC | null | null | null | null | 309,798 | null | 1 | 26 | c#|multithreading|thread-safety | 14,079 | <p>A class is generally considered thread-safe if its methods can be invoked by multiple threads concurrently without corrupting the state of the class or causing unexpected side-effects. There are many reasons why a class may not be thread safe, although some common reasons are that it contains some state that would be corrupted on concurrent access.</p>
<p>There are a number of ways to make a class thread-safe:</p>
<ol>
<li>Make it immutable, if a class contains no state it is safe to use concurrently from multiple threads.</li>
<li>Employ locking to reduce concurrency. However, this is no guarantee of thread safety, it just ensures that a block of code will not be executed concurrently by multiple threads. If state is stored between method invocations this might still become inconsistent.</li>
</ol>
<p>How you create a thread-safe class really depends on what you want to do with the class in question.</p>
<p>You also need to ask yourself, do I need to make my class threadsafe? a common model of most UI frameworks is that there is a single UI thread. For example in WinForms, WPF and Silverlight the majority of your code will be executed from the UI thread which means you do not have to build thread-safety into your classes.</p> |
6,745,464 | Inverse Cosine in Python | <p>Apologies if this is straight forward, but I have not found any help in the python manual or google.</p>
<p>I am trying to find the inverse cosine for a value using python.</p>
<p>i.e. cos⁻¹(x)</p>
<p>Does anyone know how to do this?</p>
<p>Thanks</p> | 6,745,479 | 7 | 0 | null | 2011-07-19 10:05:28.33 UTC | 6 | 2020-12-12 17:18:24.837 UTC | 2020-08-04 23:19:17.9 UTC | null | 1,450,294 | null | 846,396 | null | 1 | 53 | python|math|trigonometry | 121,190 | <p>We have the <a href="http://docs.python.org/library/math.html#math.acos" rel="noreferrer"><code>acos</code> function</a>, which returns the angle in radians.</p>
<pre><code>>>> import math
>>> math.acos(0)
1.5707963267948966
>>> _ * 2 - math.pi
0.0
</code></pre> |
6,962,432 | Is it possible to change only the alpha of a rgba background colour on hover? | <p>I have a set of <code><a></code> tags with differing rgba background colours but the same alpha. Is it possible to write a single css style that will change only the opacity of the rgba attribute?</p>
<p>A quick example of the code:</p>
<pre><code> <a href="#"><img src="" /><div class="brown">Link 1</div></a>
<a href="#"><img src="" /><div class="green">Link 2</div></a>
</code></pre>
<p>And the styles</p>
<pre><code>a {display: block; position: relative}
.brown {position: absolute; bottom: 0; background-color: rgba(118,76,41,.8);}
.green {position: absolute; bottom: 0; background-color: rgba(51,91,11,.8);}
</code></pre>
<p>What I would like to do is write a single style that would change the opacity when the <code><a></code> is hovered over, yet keep the colour unchanged. </p>
<p>Something like</p>
<pre><code>a:hover .green, a:hover .brown {background-color: rgba(inherit,inherit,inherit,1);}
</code></pre> | 6,962,502 | 15 | 6 | null | 2011-08-05 20:45:52.497 UTC | 10 | 2021-05-08 19:32:22.383 UTC | null | null | null | null | 260,152 | null | 1 | 124 | css|hover|background-color|rgba | 67,987 | <p>This is now possible with custom properties:</p>
<pre><code>.brown { --rgb: 118, 76, 41; }
.green { --rgb: 51, 91, 11; }
a { display: block; position: relative; }
div { position: absolute; bottom: 0; background-color: rgba(var(--rgb), 0.8); }
a:hover div { background-color: rgba(var(--rgb), 1); }
</code></pre>
<p>To understand how this works, see <a href="https://stackoverflow.com/questions/40010597/how-do-i-apply-opacity-to-a-css-color-variable/41265350#41265350">How do I apply opacity to a CSS color variable?</a></p>
<p>If custom properties are not an option, see the original answer below.</p>
<hr>
<p>Unfortunately, no, you'll have to specify the red, green and blue values again for each individual class:</p>
<pre><code>a { display: block; position: relative; }
.brown { position: absolute; bottom: 0; background-color: rgba(118, 76, 41, 0.8); }
a:hover .brown { background-color: rgba(118, 76, 41, 1); }
.green { position: absolute; bottom: 0; background-color: rgba(51, 91, 11, 0.8); }
a:hover .green { background-color: rgba(51, 91, 11, 1); }
</code></pre>
<p>You can only use the <code>inherit</code> keyword alone as a value for the property, and even then the use of <code>inherit</code> isn't appropriate here.</p> |
12,111,355 | How to extract a PDF from an SWF player on a web page? | <p>There is a book on this page (<a href="http://img.docin.com/players/DocinViewer.swf?productId=463932528" rel="nofollow">http://img.docin.com/players/DocinViewer.swf?productId=463932528</a>), and it is inside a swf player. Previously there was a software which can extract all pages in the swf player and store them as a pdf file. </p>
<p>So there should be 3 steps:</p>
<ol>
<li>Find the file source inside the swf player</li>
<li>Extract all pages from the swf player.</li>
<li>Save them as a whole pdf file.</li>
</ol>
<p>How might one accomplish this?</p> | 12,112,478 | 1 | 6 | null | 2012-08-24 14:28:59.24 UTC | null | 2012-08-24 16:41:40.923 UTC | 2012-08-24 15:40:29.22 UTC | null | 220,155 | null | 601,862 | null | 1 | 1 | c#|pdf|flash | 41,412 | <p>I don't know the exact answer, but perhaps someone can expand. It seems to me that using these two references, you could search for the PDF in the stream you get back in the SWF to identify the SWF header, and structure, and the PDF header and footer and then reconstitute the PDF directly from the stream:</p>
<ul>
<li><a href="http://www.adobe.com/content/dam/Adobe/en/devnet/swf/pdf/swf_file_format_spec_v10.pdf" rel="nofollow noreferrer">http://www.adobe.com/content/dam/Adobe/en/devnet/swf/pdf/swf_file_format_spec_v10.pdf</a></li>
<li><a href="https://stackoverflow.com/questions/88582/structure-of-a-pdf-file">Structure of a PDF file?</a></li>
</ul>
<p>Alternatively maybe an existing tool will do the trick:</p>
<ul>
<li><a href="http://download.cnet.com/SWF-Printer-Pro/3000-10743_4-10740922.html" rel="nofollow noreferrer">http://download.cnet.com/SWF-Printer-Pro/3000-10743_4-10740922.html</a></li>
</ul>
<p>Or update the open source project below, mentioned by a commenter to the level you need, using the references for the newer SWF and PDF formats:</p>
<ul>
<li><a href="http://sourceforge.net/projects/swfdotnet/" rel="nofollow noreferrer">http://sourceforge.net/projects/swfdotnet/</a></li>
</ul> |
45,437,535 | Firebase Hosting: Needs Setup For Cloudflare DNS | <p>I am trying to set custom domain for my Firebase app.</p>
<p>Firebase hosted url : <a href="https://inventory-app-726af.firebaseapp.com/" rel="nofollow noreferrer">https://inventory-app-726af.firebaseapp.com/</a></p>
<p>Custom Domain: <strong>inv.agsft.com</strong></p>
<p>I have followed all instructions as part of setting custom domain but after verification step when I click on finish button, status will always be "<strong>Needs Setup</strong>".</p>
<p>I am managing DNS through cloudflare (<a href="https://www.cloudflare.com/" rel="nofollow noreferrer">https://www.cloudflare.com/</a>) and I am following Quick setup option.</p>
<p>Any pointers to resolve it?</p> | 45,474,159 | 12 | 5 | null | 2017-08-01 12:15:20.597 UTC | 15 | 2022-05-11 08:52:02.643 UTC | 2022-05-11 08:52:02.643 UTC | null | 466,862 | null | 4,514,129 | null | 1 | 54 | cloudflare|firebase-hosting | 25,594 | <p>I had the same problem, I was able to resolve it by toggling the DNS Status on cloudflare from <code>DNS and HTTP Proxy (CDN)</code> to just <code>DNS</code> on the two A records</p>
<p><a href="https://i.stack.imgur.com/1xCpJ.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1xCpJ.png" alt="enter image description here"></a></p>
<p>It started working right away. Hope that helps!</p> |
15,965,246 | How to upload video to youtube in android? | <p>I am Creating an application which records video and uploads it on YouTube and others Social sites.</p>
<p>For upload I use Droid share functionality and it works good. </p>
<p>In e-mail, Facebook, Skype, etc upload works perfect, but when I select YouTube, it does not upload my video.</p>
<p>Here is the code I use for video sharing.</p>
<pre><code>Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"SUBJECT_NAME");
sharingIntent.setType("video/*");
File newFile = new File(video_path);
sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM,Uri.fromFile(newFile));
startActivity(Intent.createChooser(sharingIntent,"Where you want to share?"));
</code></pre> | 16,057,492 | 8 | 6 | null | 2013-04-12 07:12:21.377 UTC | 11 | 2020-11-12 19:44:54.533 UTC | 2013-07-15 14:24:53.127 UTC | null | 1,516,879 | null | 1,516,879 | null | 1 | 14 | android|video|upload|youtube-api|share | 7,675 | <p>Try this code.</p>
<pre><code>ContentValues content = new ContentValues(4);
content.put(Video.VideoColumns.DATE_ADDED,
System.currentTimeMillis() / 1000);
content.put(Video.Media.MIME_TYPE, "video/mp4");
content.put(MediaStore.Video.Media.DATA, "video_path");
ContentResolver resolver = getBaseContext().getContentResolver();
Uri uri = resolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, content);
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Title");
sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM,uri);
startActivity(Intent.createChooser(sharingIntent,"share:"));
</code></pre>
<p>this code is <em>add</em> in your <strong>share button's onClick()</strong> <em>method</em> and get result.
pass the value in <strong>EXTRA_STREAM</strong> as an <strong>URI</strong> not as file. </p> |
15,725,884 | Return JSON file with ASP.NET Web API | <p>I am trying to return a JSON file using ASP.NET Web API (for testing).</p>
<pre><code>public string[] Get()
{
string[] text = System.IO.File.ReadAllLines(@"c:\data.json");
return text;
}
</code></pre>
<p>In Fiddler this does appear as a Json type but when I debug in Chrome and view the object it appears as and array of individual lines (left). The right image is what the object should look like when I am using it.</p>
<p><strong>Can anyone tell me what I should return to achieve a Json result in the correct format?</strong></p>
<p><a href="https://i.stack.imgur.com/ZHvam.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZHvam.png" alt="alt"></a>
</p> | 15,726,171 | 3 | 2 | null | 2013-03-31 02:59:27.593 UTC | 5 | 2019-09-01 17:09:36.61 UTC | 2019-09-01 17:09:36.61 UTC | null | 4,751,173 | null | 1,727,487 | null | 1 | 28 | c#|javascript|json|asp.net-web-api | 45,847 | <p>Does the file already has valid JSON in it? If so, instead of calling <code>File.ReadAllLines</code> you should call <code>File.ReadAllText</code> and get it as a single string. Then you need to parse it as JSON so that Web API can re-serialize it.</p>
<pre><code>public object Get()
{
string allText = System.IO.File.ReadAllText(@"c:\data.json");
object jsonObject = JsonConvert.DeserializeObject(allText);
return jsonObject;
}
</code></pre>
<p>This will:</p>
<ol>
<li>Read the file as a string</li>
<li>Parse it as a JSON object into a CLR object</li>
<li>Return it to Web API so that it can be formatted as JSON (or XML, or whatever)</li>
</ol> |
15,881,487 | SQL Update - Multiple Columns | <p>I would like to update multiple columns in a table based on values from a second table using a <code>Select</code> statement to obtain the values like this:</p>
<pre><code>UPDATE tbl1
SET (col1, col2, col3) = (SELECT colA, colB, colC
FROM tbl2
WHERE tbl2.id = 'someid')
WHERE tbl1.id = 'differentid'
</code></pre>
<p>However, it doesn't seem as though it's possible to 'SET' more than one column name - are there alternatives rather than writing separate update statements for each column?</p>
<pre><code>UPDATE tbl1
SET col1 = (SELECT colA FROM tbl2 WHERE tbl2.id = 'someid')
WHERE tbl1.id = 'differentid'
UPDATE tbl1
SET col2 = (SELECT colB FROM tbl2 WHERE tbl2.id = 'someid')
WHERE tbl1.id = 'differentid'
UPDATE tbl1
SET col3 = (SELECT colC FROM tbl2 WHERE tbl2.id = 'someid')
WHERE tbl1.id = 'differentid'
</code></pre> | 15,881,737 | 3 | 0 | null | 2013-04-08 14:16:33.12 UTC | 2 | 2020-01-28 14:21:54.387 UTC | 2013-04-08 15:37:13.96 UTC | null | 13,302 | null | 2,221,245 | null | 1 | 28 | sql|tsql|sql-server-2012 | 58,661 | <pre><code>update tbl1
set col1 = a.col1, col2 = a.col2, col3 = a.col3
from tbl2 a
where tbl1.Id = 'someid'
and a.Id = 'differentid'
</code></pre> |
16,015,933 | How can I show a hidden div when a select option is selected? | <p>I want to use plain JavaScript. I have a drop down list (<code><select></code> with a number of <code><option></code>s). When a certain option is selected I want a hidden div to display.</p>
<pre><code><select id="test" name="form_select">
<option value="0">No</option>
<option value ="1" onClick"showDiv()">Yes</option>
</select>
<div id="hidden_div" style="display: none;">Hello hidden content</div>
</code></pre>
<p>Then I'm trying it with this vanilla JavaScript code:</p>
<pre><code>function showDiv(){
document.getElementById('hidden_div').style.display = "block";
}
</code></pre>
<p>I'm guessing my problem is with the onClick trigger in my options but I'm unsure on what else to use?</p> | 38,716,707 | 10 | 0 | null | 2013-04-15 13:06:00.483 UTC | 14 | 2022-02-02 12:11:47.25 UTC | 2020-08-25 16:03:23.733 UTC | null | 2,756,409 | null | 1,005,169 | null | 1 | 40 | javascript|html|event-handling | 234,024 | <p>I think this is an appropriate solution:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="test" name="form_select" onchange="showDiv(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
<div id="hidden_div" style="display:none;">Hello hidden content</div>
<script type="text/javascript">
function showDiv(select){
if(select.value==1){
document.getElementById('hidden_div').style.display = "block";
} else{
document.getElementById('hidden_div').style.display = "none";
}
}
</script></code></pre>
</div>
</div>
</p> |
15,557,627 | heading with horizontal line on either side | <p>I am working on some CSS where the design calls for page titles (headings) to be centered with horizontal lines that are vertically centered on either side. Further, there is a background image on the page so the background of the title needs to be transparent. </p>
<p>I have centered the title and I can use pseudo class to create the line. But I need the line disappear when it cross the text of the title. </p>
<p>I considered using a background gradient that goes transparent where the words are, but since each title could be a different length, I wouldn't know where to put the stops. </p>
<p>Here is the CSS so far:</p>
<pre><code>h1 {
text-align: center;
position: relative;
font-size: 30px;
z-index: 1;
}
h1:after {
content: '';
background-color: red;
height: 1px;
display: block;
position: absolute;
top: 18px;
left: 0;
width: 100%;
}
</code></pre>
<p>Here is where I'm at:
<a href="http://jsfiddle.net/XWVxk/1/" rel="noreferrer">http://jsfiddle.net/XWVxk/1/</a></p>
<p>Can this be done with CSS without adding any extra HTML?</p> | 15,557,694 | 3 | 1 | null | 2013-03-21 20:39:24.43 UTC | 25 | 2021-01-28 10:21:30.683 UTC | 2018-01-15 13:53:10.913 UTC | null | 759,866 | null | 1,719,823 | null | 1 | 62 | html|css|pseudo-class | 116,366 | <p>Look at this <a href="http://blog.goetter.fr/post/36084887039/tes-pas-cap-premiere-edition" rel="noreferrer">http://blog.goetter.fr/post/36084887039/tes-pas-cap-premiere-edition</a> , here is your answer.</p>
<p>Here is your original code modified</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>h1 {
position: relative;
font-size: 30px;
z-index: 1;
overflow: hidden;
text-align: center;
}
h1:before, h1:after {
position: absolute;
top: 51%;
overflow: hidden;
width: 50%;
height: 1px;
content: '\a0';
background-color: red;
}
h1:before {
margin-left: -50%;
text-align: right;
}
.color {
background-color: #ccc;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>This is my Title</h1>
<h1>Another Similar Title</h1>
<div class="color"><h1>Just Title</h1></div></code></pre>
</div>
</div>
</p>
<p>Note: the article is not online anymore, here is the last good archived version:
<a href="http://web.archive.org/web/20140213165403/http://blog.goetter.fr/post/36084887039/tes-pas-cap-premiere-edition" rel="noreferrer">http://web.archive.org/web/20140213165403/http://blog.goetter.fr/post/36084887039/tes-pas-cap-premiere-edition</a></p> |
15,693,192 | Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch) | <p>I have my first node.js app (runs fine locally) - but I am unable to deploy it via heroku (first time w/ heroku as well). The code is below. SO doesn't let me write so much code, so I would just say that the running the code locally as well within my network shows no issue.</p>
<pre><code> var http = require('http');
var fs = require('fs');
var path = require('path');
http.createServer(function (request, response) {
console.log('request starting for ');
console.log(request);
var filePath = '.' + request.url;
if (filePath == './')
filePath = './index.html';
console.log(filePath);
var extname = path.extname(filePath);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
path.exists(filePath, function(exists) {
if (exists) {
fs.readFile(filePath, function(error, content) {
if (error) {
response.writeHead(500);
response.end();
}
else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
}
else {
response.writeHead(404);
response.end();
}
});
}).listen(5000);
console.log('Server running at http://127.0.0.1:5000/');
</code></pre>
<p>Any idea ?</p> | 15,693,371 | 38 | 1 | null | 2013-03-28 22:20:39.763 UTC | 116 | 2022-09-06 16:53:00.94 UTC | 2013-03-28 22:32:44.66 UTC | null | 428,900 | null | 428,900 | null | 1 | 622 | node.js|heroku | 361,402 | <p>Heroku dynamically assigns your app a port, so you can't set the port to a fixed number. Heroku adds the port to the env, so you can pull it from there. Switch your listen to this:</p>
<pre><code>.listen(process.env.PORT || 5000)
</code></pre>
<p>That way it'll still listen to port 5000 when you test locally, but it will also work on Heroku. <em>Important note</em> - <strong>PORT</strong> word must be capital.</p>
<p>You can check out the Heroku docs on Node.js <a href="https://devcenter.heroku.com/articles/nodejs" rel="noreferrer">here</a>.</p> |
67,953,945 | Refname is ambiguous | <p>Yesterday, I created a branch from a branch, pushed it to origin, and merged it back into master. You can see that here:</p>
<pre><code>$ history |less
8358 git co master
8359 commit # shortcut that adds all and commits
8360 push # shortcut that `git push`'s
8361 git lg # shortcut that logs my output
8362 git co 1600
8363 git co -b 1601
8364 npm run test
8365 npm run test
8366 npm run test
8367 npm run test
8368 npm run test
8369 npm run test
8370 npm run test
8371 npm run test
8372 npm run test
8373 npm run test
8374 npm run test
8375 npm run test
8376 npm run test
8377 ./release.sh
8378 ./release.sh
8379 commit
8380 push
8381 git push --set-upstream origin 1601
8382 git lg
8383 git co master
8384 git merge --no-ff -
8385 git st
8386 commit
8387 push
</code></pre>
<p>I'm including irrelevant stuff in this list so I don't accidentally cut out something that is relevant; as you can see, all of this history is sequential. Here is everything in my history that refers to 1601:</p>
<pre class="lang-sh prettyprint-override"><code>$ history | grep 1601
1601 npm run test
8363 git co -b 1601
8381 git push --set-upstream origin 1601
8438 git co 1601
8445 git co 1601
8446 git show-ref 1601
8447 history | grep 1601
8449 git show-ref | grep 1601
8458 git show-ref --heads --tags | grep 1601
8460 history | grep 1601
8461 history | grep (1601|merge)
8462 history | grep -p (1601|merge)
8464 history | grep -E (1601|merge)
8466 history | grep -E -e (1601|merge)
8467 history | grep -E -e \(1601|merge\)
8468 history | grep -E -e '(1601|merge)'
8469 history | grep -E -e '(1601|merge|master)'
8470 history | grep -E -e '(1601|1601|merge|master)'
8472 history | grep -E -e '(1601|1601|merge|master)'
8474 history | grep -E -e '(1601|1601|merge|master)'
8480 history | grep 1601
</code></pre>
<p>Somehow, after these steps, whenever I <code>git co 1601</code>, it gives me this warning:</p>
<pre class="lang-sh prettyprint-override"><code>$ git co 1601
warning: refname '1601' is ambiguous.
Already on '1601'
Your branch is up to date with 'origin/1601'.
</code></pre>
<p>I've been googling for a while, looking for others that have had this issue, but none of them seem to have the same situation. Here is what I've looked at that <em>hasn't</em> helped:</p>
<ol>
<li><a href="https://stackoverflow.com/questions/28192422/git-warning-refname-xxx-is-ambiguous">Git warning: refname 'xxx' is ambiguous</a></li>
<li><a href="https://stackoverflow.com/questions/12224773/git-refname-master-is-ambiguous">Git: refname 'master' is ambiguous</a></li>
<li><a href="https://stackoverflow.com/questions/26046698/git-refname-origin-master-is-ambiguous/26047558">git refname 'origin/master' is ambiguous</a></li>
<li><a href="http://thesimplesynthesis.com/post/git-error-warning-refname-originbranch-name-is-ambiguous" rel="noreferrer">http://thesimplesynthesis.com/post/git-error-warning-refname-originbranch-name-is-ambiguous</a></li>
</ol>
<p>The following output is to help with troubleshooting:</p>
<pre class="lang-sh prettyprint-override"><code>$ git show-ref | grep 1601
137b74c8ff6807f07bb32ba0d2f76a3ba287e981 refs/heads/1601
137b74c8ff6807f07bb32ba0d2f76a3ba287e981 refs/remotes/origin/1601
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ git tag -l
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ git show-ref --heads --tags | grep 1601
137b74c8ff6807f07bb32ba0d2f76a3ba287e981 refs/heads/1601
</code></pre>
<pre><code>cat .git/config
# this is the only place where it mentions 1601
[branch "1601"]
remote = origin
merge = refs/heads/1601
$ cat .git/config | grep 1601
[branch "1601"]
merge = refs/heads/1601
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ git checkout 1601 --
warning: refname '1601' is ambiguous.
Already on '1601'
Your branch is up to date with 'origin/1601'.
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ git ls-remote . \*1601*
beea6ee68d6fe6b4f5222c0efe0e206e23af993c refs/heads/1601
beea6ee68d6fe6b4f5222c0efe0e206e23af993c refs/remotes/origin/1601
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ git show 1601 # this only shows one log message
warning: refname '1601' is ambiguous.
commit beea6ee68d6fe6b4f5222c0efe0e206e23af993c (HEAD -> 1601, origin/1601)
...
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ git --version
git version 2.31.1
</code></pre>
<pre class="lang-sh prettyprint-override"><code>$ type git
git is hashed (/usr/bin/git)
</code></pre>
<p>FWIW, I am using cygwin on Windows.</p>
<p>Why am I getting this warning, how do I get rid of it, and how do I prevent it in the future?</p> | 67,955,051 | 4 | 4 | null | 2021-06-13 00:31:58.977 UTC | 2 | 2021-06-30 12:37:13.547 UTC | 2021-06-30 12:37:13.547 UTC | null | 452,775 | null | 61,624 | null | 1 | 36 | git | 5,136 | <p>I can get this behavior by giving a branch a name that matches the SHA1 prefix of a commit.</p>
<pre><code>$ git rev-list @ | egrep '^[0-9]{4}'
7802d6937673dbff4d26dc906c714a054c9e883e
81070af68e1b254c7f36eccb1261050a5a4a133a
7537dac08fd165845b6300f32c19a52fc7fa7299
$ git branch 7802
$ git branch 9999
$ git checkout 7802
warning: refname '7802' is ambiguous.
Switched to branch '7802'
$ git checkout 9999
Switched to branch '9999'
$
</code></pre>
<p>Since object id prefixes at least four digits long are legitimate ways of referring to objects, making a ref name that's also a four-or-more-long hex string is likely to produce this kind of ambiguity. So, don't do that. If you want to number something, include a type marker, like <code>bugfix/1601</code> or something.</p> |
25,404,088 | Math.pow yields different result depending on java version | <p>I'm running the following code on a JDK Version 1.7.0_60:</p>
<pre><code>System.out.println(Math.pow(1.5476348320352065, (0.3333333333333333)));
</code></pre>
<p>The result is: 1.1567055833133086</p>
<p>I'm running exactly the same code on a JDK Version 1.7.0.</p>
<p>The result is: 1.1567055833133089</p>
<p>I understand that double is not infinitely precise, but was there a change in the java spec that causes the difference?</p>
<p>PS: Because we use a legacy system, Big Decimal is not an option.</p>
<p>Edit: I was able to track down the time of the change: It was introduced in the JDK Version 1.7.0_40 (as compared to Version 1.7.0_25).</p> | 25,601,398 | 4 | 9 | null | 2014-08-20 11:56:33.353 UTC | 3 | 2014-09-01 08:06:25.74 UTC | 2014-08-20 19:13:02.573 UTC | null | 202,504 | null | 888,881 | null | 1 | 37 | java|math|floating-point|pow | 2,191 | <p>To produce consistent results between all Java versions, the solution was to use <code>StrictMath.pow()</code> instead of <code>Math.pow()</code>.</p>
<p>For background information on what might cause the difference, refer to <a href="https://stackoverflow.com/a/25404386/888881">this answer</a>.</p> |
38,028,384 | Beautifulsoup : Difference between .find() and .select() | <p>When you use <strong><em><a href="https://www.crummy.com/software/BeautifulSoup/bs4/doc/" rel="noreferrer">BeautifulSoup</a></em></strong> to scrape a certain part of a website, you can use </p>
<ul>
<li><code>soup.find()</code> and <code>soup.findAll()</code> or</li>
<li><code>soup.select()</code>.</li>
</ul>
<p>Is there a difference between the <code>.find()</code> and the <code>.select()</code> methods?
(e.g. In performance or flexibility, etc.) Or are they the same?</p> | 38,033,910 | 1 | 11 | null | 2016-06-25 12:09:28.32 UTC | 34 | 2020-06-11 15:36:40.817 UTC | 2020-06-11 15:36:40.817 UTC | null | 12,470,196 | null | 1,275,087 | null | 1 | 64 | python|python-3.x|beautifulsoup | 79,296 | <p>To summarise the comments:</p>
<ul>
<li><em>select</em> finds multiple instances and returns a list, <em>find</em> finds the first, so they don't do the same thing. <em>select_one</em> would be the equivalent to <em>find</em>. </li>
<li>I almost always use css selectors when chaining tags or using <em>tag.classname</em>, if looking for a single element without a class I use <em>find</em>. Essentially it comes down to the use case and personal preference.</li>
<li>As far as flexibility goes I think you know the answer, <code>soup.select("div[id=foo] > div > div > div[class=fee] > span > span > a")</code> would look pretty ugly using multiple chained <em>find/find_all</em> calls.</li>
<li>The only issue with the css selectors in bs4 is the very limited support, <em>nth-of-type</em> is the only pseudo class implemented and chaining attributes like a[href][src] is also not supported as are many other parts of css selectors. But things like <em>a[href</em>=..]* , <em>a[href^=]</em>, <em>a[href$=]</em> etc.. are I think much nicer than <code>find("a", href=re.compile(....))</code> but again that is personal preference.</li>
</ul>
<p>For performance we can run some tests, I modified the code from an <a href="https://stackoverflow.com/a/37541879/2141635">answer here</a> running on 800+ html files taken from <a href="https://github.com/johnlaudun/tedtalks/tree/master/html_files/talks" rel="noreferrer">here</a>, is is not exhaustive but should give a clue to the readability of some of the options and the performance:</p>
<p>The modified functions are:</p>
<pre><code>from bs4 import BeautifulSoup
from glob import iglob
def parse_find(soup):
author = soup.find("h4", class_="h12 talk-link__speaker").text
title = soup.find("h4", class_="h9 m5").text
date = soup.find("span", class_="meta__val").text.strip()
soup.find("footer",class_="footer").find_previous("data", {
"class": "talk-transcript__para__time"}).text.split(":")
soup.find_all("span",class_="talk-transcript__fragment")
def parse_select(soup):
author = soup.select_one("h4.h12.talk-link__speaker").text
title = soup.select_one("h4.h9.m5").text
date = soup.select_one("span.meta__val").text.strip()
soup.select_one("footer.footer").find_previous("data", {
"class": "talk-transcript__para__time"}).text
soup.select("span.talk-transcript__fragment")
def test(patt, func):
for html in iglob(patt):
with open(html) as f:
func(BeautifulSoup(f, "lxml")
</code></pre>
<p>Now for the timings:</p>
<pre><code>In [7]: from testing import test, parse_find, parse_select
In [8]: timeit test("./talks/*.html",parse_find)
1 loops, best of 3: 51.9 s per loop
In [9]: timeit test("./talks/*.html",parse_select)
1 loops, best of 3: 32.7 s per loop
</code></pre>
<p>Like I said not exhaustive but I think we can safely say the css selectors are definitely more efficient. </p> |
40,323,715 | In Visual Studio, is there a way to sort private methods by usage? | <p>In Visual Studio, with or without an extension, is there a way to automatically sort private methods inside a class based on the order of their usage (their location in the call stack)?</p>
<p>For example consider the following class:</p>
<pre><code>public class MyClass
{
public void MyMethod()
{
TestC();
}
private void TestA()
{
TestB();
}
private void TestB()
{
Console.WriteLine("Hello");
}
private void TestC()
{
TestA();
}
}
</code></pre>
<p>The public method in this class is <code>MyMethod</code>, it calls <code>TestC</code> which calls <code>TestA</code> which calls <code>TestB</code>. I would like to (automatically) order these methods by this order so that the class looks like this:</p>
<pre><code>public class MyClass
{
public void MyMethod()
{
TestC();
}
private void TestC()
{
TestA();
}
private void TestA()
{
TestB();
}
private void TestB()
{
Console.WriteLine("Hello");
}
}
</code></pre>
<p>I need to be able to select a class, request such method sorting, and have the methods sorted automatically. I.e., I don't want to manually sort these methods.</p>
<p>I understand that there are some nuances. For example, there could be a private method that is called from two methods which are at two different levels in the call stack. I guess in this case it makes sense to consider the smallest (call stack) distance from the public method.</p>
<p><strong>UPDATE:</strong></p>
<p>This idea of sorting the methods in this way comes from the Clean Code book by Robert C. Martin. In chapter 3, the Stepdown rule is defined which talks about having the higher level functions appear before the low level functions.</p>
<p>Doing a quick search for stepdown rule on google, I found a netbeans plugin at: <a href="http://plugins.netbeans.org/plugin/58863/stepdownruleplugin" rel="noreferrer">http://plugins.netbeans.org/plugin/58863/stepdownruleplugin</a></p>
<p>I would guess that it does something similar to what I need, but for netbeans.</p> | 40,473,268 | 5 | 9 | null | 2016-10-29 21:11:45.21 UTC | 3 | 2016-11-08 01:36:45.61 UTC | 2016-11-05 21:50:48.607 UTC | null | 2,290,059 | null | 2,290,059 | null | 1 | 28 | c#|visual-studio|refactoring | 3,647 | <p>The ReSharper Plugin "Greenkeeper" does the job:</p>
<p><a href="https://bitbucket.org/denniskniep/greenkeeper" rel="noreferrer">https://bitbucket.org/denniskniep/greenkeeper</a></p>
<p>The plugin can sort the methods in "newspapermode": Important code first and details at the bottom. The newspapermode has the same behaviour as the "Stepdown rule".</p>
<p><a href="https://bitbucket.org/denniskniep/greenkeeper/wiki/SortingDeclarations" rel="noreferrer">https://bitbucket.org/denniskniep/greenkeeper/wiki/SortingDeclarations</a></p> |
13,377,157 | Nested Fragments using support library v4 revision 11 | <p>The last revision of the support library from this morning (<a href="http://developer.android.com/tools/extras/support-library.html#Notes">Android Support Package v4 revision 11</a>) is supposed to support nested fragments.</p>
<p>In my project I have a fragment that contains a <a href="https://developer.android.com/reference/android/support/v4/view/ViewPager.html">ViewPager</a> and this ViewPager contains several fragments.</p>
<p>I'm calling <code>getSupportFragmentManager()</code> instead of <code>getFragmentManager</code> to use the <a href="https://developer.android.com/reference/android/support/v4/app/FragmentManager.html">FragmentManager</a> of the support library.</p>
<p>The problem is I'm still experiencing crashes like : </p>
<pre><code>java.lang.IllegalStateException: Recursive entry to executePendingTransactions
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:461)
at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
at android.support.v4.view.ViewPager.populate(ViewPager.java:1012)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:523)
at android.support.v4.view.ViewPager.setCurrentItemInternal(ViewPager.java:495)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1221)
at android.view.View.dispatchRestoreInstanceState(View.java:11910)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2584)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:2590)
at android.view.View.restoreHierarchyState(View.java:11888)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:417)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:933)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
</code></pre>
<p>Is there anything I'm doing wrong ? Or the support doesn't support nested fragments for real ?</p>
<p>My transactions are as simple as this:</p>
<pre><code>getSupportFragmentManager().beginTransaction()
.replace(R.id.content, new MyFragment()).commit();
</code></pre> | 13,466,829 | 1 | 4 | null | 2012-11-14 10:36:04.067 UTC | 8 | 2014-04-17 08:19:42.193 UTC | 2014-04-17 08:19:42.193 UTC | null | 2,668,136 | null | 781,588 | null | 1 | 13 | android|android-fragments|android-viewpager|android-support-library|android-nested-fragment | 8,994 | <p>Try using <code>getChildFragmentManager()</code> instead of <code>getSupportFragmentManager()</code>. this should help</p> |
13,425,298 | git submodule update fatal error: reference is not a tree | <pre><code>user$ sudo git submodule update
fatal: reference is not a tree: a094dcfeeb43fcd62a9e466156e05e7581026f33
Unable to checkout 'a094dcfeeb43fcd62a9e466156e05e7581026f33' in submodule path 'client/src/util'
</code></pre>
<p><strong>What do I do? I just want to get a clean copy of the latest code from the repo, i dont mind losing my changes.</strong> As you can tell, I clearly am not sure what is happening. I can only think that it is trying to checkout a file which means git detected a local change in a file on my local machine.</p>
<p>i am currently using OSX</p> | 13,425,990 | 5 | 1 | null | 2012-11-16 22:22:20.283 UTC | 16 | 2021-10-14 14:26:58.17 UTC | 2012-11-19 17:41:23.257 UTC | null | 1,864,976 | null | 1,416,058 | null | 1 | 37 | git|version-control | 37,469 | <p>This is the most common problem with submodules. The commit that you are on in the outer repository has a reference to a commit in the submodule that someone did not push up yet. It's a dependency problem. Always push from the inside-out. This is most likely not something you did wrong, but someone else that's working in the repository. They were sloppy and forgot to issue push on the submodule and just pushed the containing repository. Stuff works on their machine because they made the change and those commits exist there. Go slap them and tell them to push up their submodule changes :)</p>
<p>Otherwise, it could be your fault if you were working on another machine and you forgot to push the submodule changes. Now you're at the other location and are thinking "What is happening! These are my changes and they should work here too!"</p> |
13,584,135 | Combine two sql select queries (in postgres) with LIMIT statement | <p>I've got a table and I want a query that returns the last 10 records created plus the record who's id is x.</p>
<p>I'm trying to do - </p>
<pre><code>SELECT * FROM catalog_productimage
ORDER BY date_modified
LIMIT 10
UNION
SELECT * FROM catalog_productimage
WHERE id=5;
</code></pre>
<p>But it doesn't look like I can put <code>LIMIT</code> in there before <code>UNION</code>. I've tried adding another column and using it for sorting -</p>
<pre><code>SELECT id, date_modified, IF(false, 1, 0) as priority FROM catalog_productimage
UNION
SELECT, id, date_modified, IF(true, 1, 0) as priority FROM catalog_productimage
WHERE id=5
ORDER BY priority, date_modified
LIMIT 10;
</code></pre>
<p>but I'm not making much progress..</p> | 13,584,262 | 2 | 0 | null | 2012-11-27 12:20:22.98 UTC | 3 | 2014-09-12 14:47:08.023 UTC | null | null | null | null | 795,896 | null | 1 | 43 | sql|postgresql|select|limit|union | 22,874 | <p>Just checked that this will work:</p>
<pre><code>(SELECT * FROM catalog_productimage
ORDER BY date_modified
LIMIT 10)
UNION
SELECT * FROM catalog_productimage
WHERE id=5;
</code></pre> |
13,699,921 | ASP.NET Web Api: Project requires SQL Server Express | <p>I created a Web API project under VS 2010.
After I switched to VS 2012, I always get a warning:</p>
<blockquote>
<p>The Web project 'xxx' requires SQL Server Express, whcih is not
installed on this computer. [...]</p>
</blockquote>
<p>I do not want to install this SQL Server Express. I use IIS for debugging.
How can I disable this dependency?</p>
<p>I noticed also this in my web.config:</p>
<pre><code><connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|[...].mdf;Initial Catalog=[...];Integrated Security=True;User Instance=True" providerName="System.Data.SqlClient" />
</connectionStrings>
</code></pre>
<p>Who created this? Can I delete this?</p> | 13,710,135 | 3 | 1 | null | 2012-12-04 09:43:28.34 UTC | 5 | 2016-11-01 17:49:32.99 UTC | null | null | null | null | 437,899 | null | 1 | 45 | configuration|asp.net-web-api|sql-server-express | 29,237 | <p>It was created by Visual Studio to you. The reason is Web API projects are a sub class of MVC projects. And actually, Web API project can contain both: a web application and Web API itself.</p>
<p>As far as this project is a sub class of an MVC project you get all this extra features.</p>
<p>You can delete all that extra stuff as far as you don't need it. The things you can delete also:</p>
<p><strong>In WebConfig:</strong></p>
<ul>
<li>/configSections/section name="entityFramework"...</li>
<li>/connectionStrings</li>
<li>/system.web/pages</li>
<li>/system.web/profile</li>
<li>/system.web/membership</li>
<li>/system.web/roleManager</li>
<li>/entityFramework</li>
</ul>
<p>You probably would also want to delete</p>
<p><strong>NuGet packages:</strong></p>
<p>Everything except razor, MVC, Web Api packages like:</p>
<ul>
<li>jQuery</li>
<li>EntityFramework</li>
<li>jQuery Validation</li>
<li>jQuery UI</li>
<li>Modernizr</li>
<li>knockoutjs</li>
<li>MS Unobtrusive AJAX</li>
<li>MS Unobtrusive Validation</li>
</ul>
<p><strong>In Solution Explorer:</strong></p>
<ul>
<li>/App_Data</li>
<li>/Content</li>
<li>/Images</li>
<li>/Scripts</li>
<li>/Views</li>
</ul>
<p>But be cautious, because after that deletion you won't be able to add Web API Help page for example (which describes your API).</p> |
13,448,340 | How to use greater than operator with date? | <p>No idea what is going on here. Here is the query, right from phpMyAdmin:</p>
<pre><code>SELECT * FROM `la_schedule` WHERE 'start_date' >'2012-11-18';
</code></pre>
<p>But I consistently get all records in the table returned, including those with start date 2012-11-01. What gives?</p> | 13,448,367 | 7 | 1 | null | 2012-11-19 05:47:24.703 UTC | 11 | 2021-04-11 00:28:21.05 UTC | 2015-01-15 06:28:11.93 UTC | null | 2,487,549 | null | 1,634,595 | null | 1 | 138 | mysql|date|operators | 349,540 | <p>you have enlosed <code>start_date</code> with single quote causing it to become string, use <code>backtick</code> instead</p>
<pre><code>SELECT * FROM `la_schedule` WHERE `start_date` > '2012-11-18';
</code></pre>
<ul>
<li><a href="http://sqlfiddle.com/#!9/117cf/167/0" rel="noreferrer">SQLFiddle Demo</a></li>
</ul> |
51,982,417 | Pandas mask / where methods versus NumPy np.where | <p>I often use Pandas <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.mask.html" rel="noreferrer"><code>mask</code></a> and <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.where.html" rel="noreferrer"><code>where</code></a> methods for cleaner logic when updating values in a series conditionally. However, for relatively performance-critical code I notice a significant performance drop relative to <a href="https://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html" rel="noreferrer"><code>numpy.where</code></a>.</p>
<p>While I'm happy to accept this for specific cases, I'm interested to know:</p>
<ol>
<li>Do Pandas <code>mask</code> / <code>where</code> methods offer any additional functionality, <em>apart from</em> <code>inplace</code> / <code>errors</code> / <code>try-cast</code> parameters? I understand those 3 parameters but rarely use them. For example, I have no idea what the <code>level</code> parameter refers to.</li>
<li>Is there any non-trivial counter-example where <code>mask</code> / <code>where</code> outperforms <code>numpy.where</code>? If such an example exists, it could influence how I choose appropriate methods going forwards.</li>
</ol>
<p>For reference, here's some benchmarking on Pandas 0.19.2 / Python 3.6.0:</p>
<pre><code>np.random.seed(0)
n = 10000000
df = pd.DataFrame(np.random.random(n))
assert (df[0].mask(df[0] > 0.5, 1).values == np.where(df[0] > 0.5, 1, df[0])).all()
%timeit df[0].mask(df[0] > 0.5, 1) # 145 ms per loop
%timeit np.where(df[0] > 0.5, 1, df[0]) # 113 ms per loop
</code></pre>
<p>The performance appears to diverge <em>further</em> for non-scalar values:</p>
<pre><code>%timeit df[0].mask(df[0] > 0.5, df[0]*2) # 338 ms per loop
%timeit np.where(df[0] > 0.5, df[0]*2, df[0]) # 153 ms per loop
</code></pre> | 51,997,521 | 1 | 5 | null | 2018-08-23 09:22:53.277 UTC | 6 | 2018-08-27 08:18:36.103 UTC | 2018-08-23 09:26:07.693 UTC | null | 9,209,546 | null | 9,209,546 | null | 1 | 37 | python|pandas|performance|numpy|series | 5,504 | <p>I'm using pandas 0.23.3 and Python 3.6, so I can see a real difference in running time only for your second example.</p>
<p>But let's investigate a slightly different version of your second example (so we get<code>2*df[0]</code> out of the way). Here is our baseline on my machine:</p>
<pre><code>twice = df[0]*2
mask = df[0] > 0.5
%timeit np.where(mask, twice, df[0])
# 61.4 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit df[0].mask(mask, twice)
# 143 ms ± 5.27 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code></pre>
<p>Numpy's version is about 2.3 times faster than pandas.</p>
<p>So let's profile both functions to see the difference - profiling is a good way to get the big picture when one isn't very familiar with the code basis: it is faster than debugging and less error-prone than trying to figure out what's going on just by reading the code. </p>
<p>I'm on Linux and use <a href="https://perf.wiki.kernel.org/index.php/Tutorial#Sampling_with_perf_record" rel="noreferrer"><code>perf</code></a>. For the numpy's version we get (for the listing see appendix A):</p>
<pre><code>>>> perf record python np_where.py
>>> perf report
Overhead Command Shared Object Symbol
68,50% python multiarray.cpython-36m-x86_64-linux-gnu.so [.] PyArray_Where
8,96% python [unknown] [k] 0xffffffff8140290c
1,57% python mtrand.cpython-36m-x86_64-linux-gnu.so [.] rk_random
</code></pre>
<p>As we can see, the lion's share of the time is spent in <code>PyArray_Where</code> - about 69%. The unknown symbol is a kernel function (as matter of fact <code>clear_page</code>) - I run without root privileges so the symbol is not resolved.</p>
<p>And for pandas we get (see Appendix B for code):</p>
<pre><code>>>> perf record python pd_mask.py
>>> perf report
Overhead Command Shared Object Symbol
37,12% python interpreter.cpython-36m-x86_64-linux-gnu.so [.] vm_engine_iter_task
23,36% python libc-2.23.so [.] __memmove_ssse3_back
19,78% python [unknown] [k] 0xffffffff8140290c
3,32% python umath.cpython-36m-x86_64-linux-gnu.so [.] DOUBLE_isnan
1,48% python umath.cpython-36m-x86_64-linux-gnu.so [.] BOOL_logical_not
</code></pre>
<p>Quite a different situation:</p>
<ul>
<li>pandas doesn't use <code>PyArray_Where</code> under the hood - the most prominent time-consumer is <code>vm_engine_iter_task</code>, which is <a href="https://github.com/pydata/numexpr/blob/8b91a6d0eb4f5ad8a71aceefa17300120272d3c8/numexpr/interpreter.hpp#L104" rel="noreferrer">numexpr-functionality</a>.</li>
<li>there is some heavy memory-copying going on - <code>__memmove_ssse3_back</code> uses about <code>25</code>% of time! Probably some of the kernel's functions are also connected to memory-accesses.</li>
</ul>
<p>Actually, pandas-0.19 used <code>PyArray_Where</code> under the hood, for the older version the perf-report would look like:</p>
<pre><code>Overhead Command Shared Object Symbol
32,42% python multiarray.so [.] PyArray_Where
30,25% python libc-2.23.so [.] __memmove_ssse3_back
21,31% python [kernel.kallsyms] [k] clear_page
1,72% python [kernel.kallsyms] [k] __schedule
</code></pre>
<p>So basically it would use <code>np.where</code> under the hood + some overhead (all above data-copying, see <code>__memmove_ssse3_back</code>) back then. </p>
<p>I see no scenario where pandas could become faster than numpy in pandas' version 0.19 - it just adds overhead to numpy's functionality. Pandas' version 0.23.3 is an entirely different story - here numexpr-module is used, it is very possible that there are scenarios for which pandas' version is (at least slightly) faster.</p>
<p>I'm not sure this memory-copying is really called for/necessary - maybe one even could call it performance-bug, but I just don't know enough to be certain. </p>
<p>We could help pandas not to copy, by peeling away some indirections (passing <code>np.array</code> instead of <code>pd.Series</code>). For example:</p>
<pre><code>%timeit df[0].mask(mask.values > 0.5, twice.values)
# 75.7 ms ± 1.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code></pre>
<p>Now, pandas is only 25% slower. The perf says:</p>
<pre><code>Overhead Command Shared Object Symbol
50,81% python interpreter.cpython-36m-x86_64-linux-gnu.so [.] vm_engine_iter_task
14,12% python [unknown] [k] 0xffffffff8140290c
9,93% python libc-2.23.so [.] __memmove_ssse3_back
4,61% python umath.cpython-36m-x86_64-linux-gnu.so [.] DOUBLE_isnan
2,01% python umath.cpython-36m-x86_64-linux-gnu.so [.] BOOL_logical_not
</code></pre>
<p>Much less data-copying, but still more than in the numpy's version which is mostly responsible for the overhead.</p>
<p>My key take-aways from it:</p>
<ul>
<li><p>pandas has the potential to be at least slightly faster than numpy (because it is possible to be faster). However, pandas' somewhat opaque handling of data-copying makes it hard to predict when this potential is overshadowed by (unnecessary) data copying.</p></li>
<li><p>when the performance of <code>where</code>/<code>mask</code> is the bottleneck, I would use numba/cython to improve the performance - see my rather naive tries to use numba and cython further below.</p></li>
</ul>
<hr>
<p>The idea is to take</p>
<pre><code>np.where(df[0] > 0.5, df[0]*2, df[0])
</code></pre>
<p>version and to eliminate the need to create a temporary - i.e, <code>df[0]*2</code>.</p>
<p>As proposed by @max9111, using numba:</p>
<pre><code>import numba as nb
@nb.njit
def nb_where(df):
n = len(df)
output = np.empty(n, dtype=np.float64)
for i in range(n):
if df[i]>0.5:
output[i] = 2.0*df[i]
else:
output[i] = df[i]
return output
assert(np.where(df[0] > 0.5, twice, df[0])==nb_where(df[0].values)).all()
%timeit np.where(df[0] > 0.5, df[0]*2, df[0])
# 85.1 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%timeit nb_where(df[0].values)
# 17.4 ms ± 673 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
</code></pre>
<p>Which is about factor 5 faster than the numpy's version!</p>
<p>And here is my by far less successful try to improve the performance with help of Cython:</p>
<pre><code>%%cython -a
cimport numpy as np
import numpy as np
cimport cython
@cython.boundscheck(False)
@cython.wraparound(False)
def cy_where(double[::1] df):
cdef int i
cdef int n = len(df)
cdef np.ndarray[np.float64_t] output = np.empty(n, dtype=np.float64)
for i in range(n):
if df[i]>0.5:
output[i] = 2.0*df[i]
else:
output[i] = df[i]
return output
assert (df[0].mask(df[0] > 0.5, 2*df[0]).values == cy_where(df[0].values)).all()
%timeit cy_where(df[0].values)
# 66.7± 753 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
</code></pre>
<p>gives 25% speed-up. Not sure, why cython is so much slower than numba though.</p>
<hr>
<p>Listings:</p>
<p><strong>A:</strong> np_where.py:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(0)
n = 10000000
df = pd.DataFrame(np.random.random(n))
twice = df[0]*2
for _ in range(50):
np.where(df[0] > 0.5, twice, df[0])
</code></pre>
<p><strong>B:</strong> pd_mask.py:</p>
<pre><code>import pandas as pd
import numpy as np
np.random.seed(0)
n = 10000000
df = pd.DataFrame(np.random.random(n))
twice = df[0]*2
mask = df[0] > 0.5
for _ in range(50):
df[0].mask(mask, twice)
</code></pre> |
39,732,312 | Xcode 8 - IB Designables - Failed to render and update auto layout status, The agent crashed | <p>I recently upgraded to Xcode 8 and I am having issues with the Storyboard.</p>
<p>If I open the project and I don't have the Storyboard open, it will compile and run just fine. Once I open up the Storyboard, I get multiple errors about IB Designables as shown below.</p>
<p><a href="https://i.stack.imgur.com/vk3OU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vk3OU.png" alt="enter image description here"></a></p>
<p>These views are the only views that are using custom views from <code>TextFieldEffects</code> and <code>BEMCheckbox</code> that I imported using Cocoapods.</p> | 42,678,873 | 23 | 4 | null | 2016-09-27 18:54:39.887 UTC | 47 | 2022-06-21 14:23:36.677 UTC | 2018-06-28 09:31:29.483 UTC | null | 1,033,581 | null | 1,270,257 | null | 1 | 185 | ios|xcode8|xcode-storyboard | 107,817 | <p>You can try one of the following to figure out the cause:</p>
<ol>
<li>look for the <code>IBDesignablesAgentCocoaTouch</code> logs in this directory:
<code>~/Library/Logs/DiagnosticReports</code> and see the cause.</li>
</ol>
<blockquote>
<p>Note: for user with Catalina: look for
<code>IBDesignablesAgent-iOS_<DATE>-<MAC_NAME>.crash</code></p>
</blockquote>
<ol start="2">
<li><p>Go to the Editor -> Debug Selected View while selecting your <code>@IBDesignable UIView</code> in your storyboard, and see the stack trace.</p></li>
<li><p>Delete Derive Data folder. </p>
<pre><code>Xcode Preference -> Location -> Derived Data
/Users/YourMacName/Library/Developer/Xcode/DerivedData
</code></pre></li>
<li><p>Clean your project <code>Shift</code> <strong>+</strong> <code>Command</code> <strong>+</strong> <code>Alt</code> <strong>+</strong> <code>K</code>.</p></li>
<li><p>Build your project <code>Command</code> <strong>+</strong> <code>B</code>.</p></li>
</ol> |
24,018,758 | When should I use deinit? | <p>I came across a function called <code>deinit()</code> while reading <a href="https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/index.html" rel="noreferrer">The Swift Programming Language guide</a>, but I'm still wondering why and when we need to implement it since we don't really need to manage memory.</p> | 24,018,794 | 7 | 2 | null | 2014-06-03 15:12:24.5 UTC | 10 | 2021-06-08 13:01:35.737 UTC | 2019-03-20 09:50:11.713 UTC | null | 3,235,281 | null | 3,235,281 | null | 1 | 43 | swift | 37,791 | <p>It's not required that you implement that method, but you can use it if you need to do some action or cleanup before deallocating the object.</p>
<p>The <a href="https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Deinitialization.html#//apple_ref/doc/uid/TP40014097-CH19-XID_182">Apple docs</a> include an example:</p>
<pre><code>struct Bank {
static var coinsInBank = 10_000
static func vendCoins(var numberOfCoinsToVend: Int) -> Int {
numberOfCoinsToVend = min(numberOfCoinsToVend, coinsInBank)
coinsInBank -= numberOfCoinsToVend
return numberOfCoinsToVend
}
static func receiveCoins(coins: Int) {
coinsInBank += coins
}
}
class Player {
var coinsInPurse: Int
init(coins: Int) {
coinsInPurse = Bank.vendCoins(coins)
}
func winCoins(coins: Int) {
coinsInPurse += Bank.vendCoins(coins)
}
deinit {
Bank.receiveCoins(coinsInPurse)
}
}
</code></pre>
<p>So whenever the player is removed from the game, its coins are returned to the bank.</p> |
9,313,769 | nth-of-type vs nth-child | <p>I am a bit confused about the <code>nth-of-type</code> pseudo class, and how this is supposed to work - especially as compared to the <code>nth-child</code> class.</p>
<p>Maybe I have the wrong idea, but given this structure</p>
<pre><code><div class="row">
<div class="icon">A</div>
<div class="icon">B</div>
<div class="label">1</div>
<div class="label">2</div>
<div class="label">3</div>
</div>
</code></pre>
<p>..the third child element (first with class label) should (perhaps?) be selectable with</p>
<pre><code>.row .label:nth-of-type(1) {
/* some rules */
}
</code></pre>
<p>However, at least in chrome here, it doesn't select it. It only appears to work if it is the first child in the row, which is the same as <code>nth-child</code> - therefore, what is the difference between this and <code>nth-of-type</code>?</p> | 9,313,956 | 7 | 2 | null | 2012-02-16 15:13:36.763 UTC | 17 | 2020-02-12 20:26:13.62 UTC | 2020-02-12 20:26:13.62 UTC | null | 2,756,409 | null | 206,861 | null | 1 | 55 | css|css-selectors | 21,926 | <p>The <code>nth-child</code> pseudo-class refers to the "Nth matched child element", meaning if you have a structure as follows:</p>
<pre><code><div>
<h1>Hello</h1>
<p>Paragraph</p>
<p>Target</p>
</div>
</code></pre>
<p>Then <code>p:nth-child(2)</code> will select the second child which is also a p (namely, the <code>p</code> with "Paragraph").<br>
<code>p:nth-of-type</code> will select the second <strong>matched <code>p</code> element</strong>, (namely, our Target <code>p</code>).</p>
<p><strong><a href="http://css-tricks.com/the-difference-between-nth-child-and-nth-of-type/" rel="noreferrer">Here's a great article on the subject by Chris Coyier @ CSS-Tricks.com</a></strong></p>
<hr>
<p>The reason yours breaks is because type refers to the type of element (namely, <code>div</code>), but the first div doesn't match the rules you mentioned (<code>.row .label</code>), therefore the rule doesn't apply.</p>
<p>The reason is, <strong><a href="http://css-tricks.com/why-browsers-read-selectors-right-to-left/" rel="noreferrer">CSS is parsed right to left</a></strong>, which means the the browser first looks on the <code>:nth-of-type(1)</code>, determines it searches for an element of type <code>div</code>, which is also the first of its type, that matches the <code>.row</code> element, and the first, <code>.icon</code> element. Then it reads that the element should have the <code>.label</code> class, which matches nothing of the above.</p>
<p>If you want to select the first label element, you'll either need to wrap all of the labels in their own container, or simply use <code>nth-of-type(3)</code> (assuming there will always be 2 icons).</p>
<p>Another option, would (sadly) be to use... wait for it... jQuery:</p>
<pre><code>$(function () {
$('.row .label:first')
.css({
backgroundColor:"blue"
});
});
</code></pre> |
16,373,895 | Regular expression for specific number of digits | <p>I want to write a regular expression in C# that inputs only a specific number of only numbers.</p>
<p>Like writing a regular expression to validate 5 digits number like so "12345"</p> | 16,373,982 | 3 | 2 | null | 2013-05-04 11:42:41.12 UTC | 2 | 2013-05-08 07:07:26.197 UTC | 2013-05-08 07:07:26.197 UTC | null | 863,380 | null | 863,380 | null | 1 | 12 | c#|regex | 46,734 | <p>Use the following regex with <a href="http://msdn.microsoft.com/en-us/library/s19z3syh.aspx"><code>Regex.IsMatch</code></a> method</p>
<pre><code>^[0-9]{5}$
</code></pre>
<p><code>^</code> and <code>$</code> will anchors the match to the beginning and the end of the string (respectively) to prevent a match to be found in the middle of a long string, such as <code>1234567890</code> or <code>abcd12345efgh</code>.</p>
<p><code>[0-9]</code> indicates a character class that specifies a range of characters from <code>0</code> to <code>9</code>. The range is defined by the Unicode code range that starts and ends with the specified characters. The <code>{5}</code> followed behind is a <em>quantifier</em> indicating to repeat the <code>[0-9]</code> 5 times.</p>
<p>Note that the solution of <code>^\d{5}$</code> is only equivalent to the above solution, when <a href="http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regexoptions.aspx"><code>RegexOptions.ECMAScript</code></a> is specified, otherwise, <a href="http://msdn.microsoft.com/en-us/library/20bw873z.aspx#DigitCharacter">it will be equivalent to <code>\p{Nd}</code></a>, which matches any Unicode digits - here is <a href="http://www.fileformat.info/info/unicode/category/Nd/list.htm">the list of all characters in <code>Nd</code> category</a>. You should always check the documentation of the language you are using as to what the shorthand character classes actually matches.</p>
<p>I strongly suggest that you read through the <a href="http://msdn.microsoft.com/en-us/library/az24scfc.aspx">documentation</a>. You can use other resources, such as <a href="http://www.regular-expressions.info/">http://www.regular-expressions.info/</a>, but <strong>always</strong> check back on the documentation of the language that you are using.</p> |
16,243,855 | How to detect that a provisioning profile is for development or distribution, programmatically | <p>I would like to detect if a given provisioning profile is a development profile or a distribution (adhoc or app store) profile. I need to do this purely programmatically. </p>
<p>I already understand how to detect adhoc vs appstore. And am specifically interested in dev vs. distribution. </p>
<p>I've examined the plists internal to each type of profile and cannot find a discernable difference (via <code>security cms -D -i #{@profilePath}</code>). I've also looked into the <code>openssl</code> api and am using this for some certificate manipulation.</p>
<p>This is for a custom xcode automated build system. As part of pre-build validation I need to ensure that the specified profile is not for development. </p>
<p>Is this even possible? If so, how can I programmatically differentiate between the two?</p>
<p>Thanks in advance for any ideas!</p> | 16,268,904 | 4 | 3 | null | 2013-04-26 19:30:08.08 UTC | 8 | 2022-06-01 15:56:54.997 UTC | null | null | null | null | 922,200 | null | 1 | 29 | xcode|openssl|xcodebuild|provisioning-profile | 13,177 | <p>This was something I tackled in one of my own build systems for much the same purpose...let's take a trip back in time to Day 1 of the then 'iPhone Developer Program'. If you were around the community at that time, you may remember that the toolchain was...shall we say less friendly...than it is today.</p>
<p>When you wanted to build for the AppStore or for AdHoc builds you had to make this curious entitlements.plist file, then paste a blob of XML into the body of that file. You then ran the build and at that time what appeared to be magic occurred and the sheer presence of that file made the build work, allowed you to manually construct your IPA, and carry on with business as usual. Now that we are a few years older and hopefully a bit wiser than in those early days of the SDK, we have come to recognize that the magic XML blob wasn't actually so magical at all -- the 'get-task-allow' key is a setting to indicate if the binary should allow other processes (like perhaps a debugger) to attach to the binary. When signing apps using a Development Provisioning Profile, this key will be set to 'true' (and thus allow LLDB to attach and interact with your app)...and naturally when signing apps using a Distribution Provisioning Profile, this key will be set to 'false'.</p>
<p>Apple has provided some updates in <a href="https://developer.apple.com/legacy/library/technotes/tn2250/_index.html#//apple_ref/doc/uid/DTS40009933-CH1-TNTAG35" rel="noreferrer">Tech Note TN2250</a> about reading the XML (and by extension the entitlements) out of Provisioning Profiles: </p>
<blockquote>
<p>security cms -D -i /path/to/the.app/embedded.mobileprovision</p>
</blockquote>
<p>This will return the XML in the Provisioning profile -- from there you can parse out the key value pair for 'get-task-allow' and use that value to determine if the Provisioning Profile is Development or Distribution.</p>
<p>I absolutely agree that it would be nice to have a tool that would tell us that directly so we don't have to sniff through the profile for clues, but at the same time, at least we have a highly reliable, albeit roundabout way to make that distinction before running off and making a build we can't use.</p>
<p>Good luck and let me know if you need any more clarification or have other questions.</p> |
17,560,818 | Twitter Bootstrap: white space on left and right side in smaller screen widths? | <p>I have markup similar to this:</p>
<pre><code><div class="container-fluid">
<div class="container">
<div class="row">
<h1>Hello World!</h1>
</div>
</div>
</div>
</code></pre>
<p>Obviously, I want the <code>.container-fluid</code> to span the entire width of the screen. However, in smaller screen widths, it doesn't seem to do that. There appears a space on both sides of the screen, thus reducing the amount of screen real estate and affecting the overall look and feel I'm trying to achieve.</p>
<p>Is there a way to get rid of this space? I want <code>.container-fluid</code> to span the entire width of the screen regardless of the screen width.</p> | 17,560,929 | 7 | 0 | null | 2013-07-10 01:03:33.367 UTC | 1 | 2021-10-12 22:58:58.787 UTC | null | null | null | null | 253,976 | null | 1 | 13 | css|twitter-bootstrap | 53,457 | <p>In bootstrap-responsive.css, the body gets a 20px padding on the left and right at smaller windows sizes. If you don't want that at all, remove it from your version. It's at line 803 and looks like this:</p>
<pre><code>@media (max-width: 767px) {
/*body { These are the lines you want to remove
padding-right: 20px;
padding-left: 20px;
}*/
</code></pre>
<p>If you just want to remove the white space on a certain element or class, add these margins to it:</p>
<pre><code> margin-left:-20px;
margin-right:-20px;
</code></pre> |
24,579,276 | Can you inspect the byte code of a Java 8 lambda at runtime? | <p>If you have an anonymous class like</p>
<pre><code>Predicate<String> isEmpty = new Predicate<String>() {
public boolean test(String t) {
return t.isEmpty();
}
};
</code></pre>
<p>A library which is passed the reference to <code>isEmpty</code> can inspect the byte code to see what it does and possibly manipulate it. Is there a way you can do this for lambdas?</p>
<pre><code>Predicate<String> isEmpty = String::isEmpty;
</code></pre>
<p>e.g Say have this code and byte code</p>
<pre><code>public class Main {
public static void test(Predicate<String> tester) {
System.out.println("tester.getClass()= " + tester.getClass());
System.out.println("tester.getClass().getClassLoader()="+ tester.getClass().getClassLoader());
}
public static void main(String... args) {
Predicate<String> isEmpty = String::isEmpty;
test(isEmpty);
}
}
$ javap -cp . -c -private Main.class
Compiled from "Main.java"
public class Main {
public Main();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
public static void test(java.util.function.Predicate<java.lang.String>);
Code:
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: new #3 // class java/lang/StringBuilder
6: dup
7: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
10: ldc #5 // String tester.getClass()=
12: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: aload_0
16: invokevirtual #7 // Method java/lang/Object.getClass:()Ljava/lang/Class;
19: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/Object;)Ljava/lang/StringBuilder;
22: invokevirtual #9 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
25: invokevirtual #10 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
28: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
31: new #3 // class java/lang/StringBuilder
34: dup
35: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
38: ldc #11 // String tester.getClass().getClassLoader()=
40: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
43: aload_0
44: invokevirtual #7 // Method java/lang/Object.getClass:()Ljava/lang/Class;
47: invokevirtual #12 // Method java/lang/Class.getClassLoader:()Ljava/lang/ClassLoader;
50: invokevirtual #8 // Method java/lang/StringBuilder.append:(Ljava/lang/Object;)Ljava/lang/StringBuilder;
53: invokevirtual #9 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
56: invokevirtual #10 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
59: return
public static void main(java.lang.String...);
Code:
0: invokedynamic #13, 0 // InvokeDynamic #0:test:()Ljava/util/function/Predicate;
5: astore_1
6: aload_1
7: invokestatic #14 // Method test:(Ljava/util/function/Predicate;)V
10: return
}
</code></pre>
<p>With a reference to <code>tester</code> in <code>test</code> how do I find which method is called?</p> | 24,598,510 | 4 | 6 | null | 2014-07-04 18:21:26.307 UTC | 10 | 2017-02-26 19:54:25.063 UTC | 2014-07-04 22:36:47.633 UTC | null | 57,695 | null | 57,695 | null | 1 | 23 | java|lambda|java-8|bytecode | 2,696 | <p>If you just want to SEE the bytecode:</p>
<pre><code>javap -c -p -v classfile
^disassemble
^private methods
^verbose, including constant pool and bootstrap methods attribute
</code></pre>
<p>But if you want to try to do this at runtime, you're pretty much out of luck (by design, we don't have anything like Expression Trees), as the other answer suggests.</p> |
27,415,586 | Using LINQ to generate prime numbers | <p>Following is an interview question:</p>
<p>The following one-liner generates and displays the list of first 500 prime numbers. How would you optimize it using parallel LINQ while still keeping it a SINGLE C# STATEMENT:</p>
<pre><code>MessageBox.Show(string.Join(",",
Enumerable.Range(2, (int)(500 * (Math.Log(500) + Math.Log(System.Math.Log(500)) - 0.5)))
.Where(x => Enumerable.Range(2, x - 2)
.All(y => x % y != 0))
.TakeWhile((n, index) => index < 500)));
</code></pre>
<p>I tried introducing <code>AsParallel()</code> as well as <code>ParallelEnumerable</code> into the query, but did not see any tangible benefits on multi-core machines. The query still uses one CPU core heavily while other cores enjoy leisure time. Can someone suggest an improvement that would distribute the load equally on all cores and thus reduce execution time?</p>
<p><strong>For the enthusiast</strong>: The following formula returns an upper bound which is guaranteed to be greater than N prime numbers, i.e. if you check up to this number, you'll sure find N primes smaller than it:</p>
<pre><code>UpperBound = N * (Log(N) + Log(Log(N)) - 0.5) //Log is natural log
</code></pre> | 27,416,287 | 4 | 9 | null | 2014-12-11 04:53:33.743 UTC | 14 | 2017-11-27 17:25:23.47 UTC | 2017-11-27 17:25:04.073 UTC | null | 1,137,199 | null | 1,137,199 | null | 1 | 21 | c#|linq|optimization|parallel-processing|primes | 7,007 | <p>This does it nicely on my machine. I've never actually seen <em>all</em> my cores go to 100% until now. Thanks for giving me an excuse to play :)</p>
<p>I increased the numbers until I had a time slow enough to measure (20,000).</p>
<p>The key option that made the difference to me was setting the <a href="http://msdn.microsoft.com/en-us/library/dd642145(VS.100).aspx" rel="noreferrer">ExecutionMode</a> to ForceParallelism.</p>
<p>Because I use a NotBuffered merge option, I re-sort it when I'm done. This would not be necessary if you don't care about the order of the results (perhaps you're putting the results in a HashSet).</p>
<p>The DegreeOfParallelism and MergeOptions only provided minor gains (if any) to performance on my machine. This example shows how to use all the options in a single Linq statement, which was the original question.</p>
<pre><code>var numbers = Enumerable.Range(2, (int)(20000 * (Math.Log(20000) + Math.Log(System.Math.Log(20000)) - 0.5)))
.AsParallel()
.WithDegreeOfParallelism(Environment.ProcessorCount)
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.WithMergeOptions(ParallelMergeOptions.NotBuffered) // remove order dependancy
.Where(x => Enumerable.Range(2, x - 2)
.All(y => x % y != 0))
.TakeWhile((n, index) => index < 20000);
string result = String.Join(",",numbers.OrderBy (n => n));
</code></pre> |
21,605,579 | How true is "Want Speed? Pass by value" | <p>Correct me if I'm wrong. Say I have:</p>
<pre><code>struct X
{
std::string mem_name;
X(std::string name)
: mem_name(std::move(name))
{}
...
};
struct Y
{
std::string mem_name;
Y(const std::string &name)
: mem_name(name)
{}
...
};
</code></pre>
<p>In <code>X</code>'s ctor, <code>name</code> is obviously a copy of whatever argument got passed to <code>X</code>, <code>X</code> invokes the move ctor of <code>std::string</code> to initialize <code>mem_name</code>, right? </p>
<p>Let's call that a <em>copy-then-move on X*</em>; two operations: <strong>COPY, MOVE</strong>.</p>
<p>In <code>Y</code>'s ctor, <code>name</code> is a const ref, which means there's no actual copy of the element because we're dealing directly with the argument passed from wherever <code>Y</code>'s object needs to be created. But then we copied <code>name</code> to initialise <code>mem_name</code> in <code>Y</code>; one operation: <strong>COPY</strong>. Surely it should therefore be a lot faster (and preferable to me)?</p>
<p>In Scott Meyer's GN13 talk (around time-frame 8:10 and 8:56), he talks about <strong>"Want speed? Pass by value"</strong> and I was wondering is there any performance difference or loss in passing arguments (or strings to be precise) by reference and passing by value "in order to gain speed?" </p>
<p>I'm aware of the fact that passing arguments by value can be expensive, especially when dealing with large data. </p>
<p>Maybe (clearly?) there's something I'm missing from his talk?</p> | 21,605,827 | 3 | 6 | null | 2014-02-06 14:26:36.823 UTC | 29 | 2017-04-28 17:59:29.333 UTC | 2016-11-26 07:14:20.1 UTC | null | 4,115,625 | null | 1,493,876 | null | 1 | 54 | c++|c++11 | 15,837 | <p>The idea of <a href="http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/" rel="noreferrer">"Want speed? Pass by value"</a><sup>(1)</sup> is that sometimes, the copy can be elided. Taking your classes <code>X</code> and <code>Y</code>, consider this usecase:</p>
<pre><code>// Simulating a complex operation returning a temporary:
std::string foo() { return "a" + std::string("b"); }
struct X
{
std::string mem_name;
X(std::string name): mem_name(std::move(name)) {}
};
struct Y
{
std::string mem_name;
Y(const std::string &name): mem_name(name) {}
};
int main()
{
X(foo());
Y(foo());
}
</code></pre>
<p>Now let's analyse both the construction cases.</p>
<p><code>X</code> first. <code>foo()</code> returns a temporary, which is used to initialise the object <code>name</code>. That object is then moved into <code>mem_name</code>. Notice that the compiler can apply Return Value Optimisation and construct the return value of <code>foo()</code> (actually even the return value of <code>operator+</code>) <em>directly</em> in the space of <code>name</code>. So no copying actually happens, only a move.</p>
<p>Now let's analyse <code>Y</code>. <code>foo()</code> returns a temporary again, which is bound to the reference <code>name</code>. Now there's no "externally supplied" space for the return value, so it has to be constructed in its own space and bound to the reference. It is then copied into <code>mem_name</code>. So we are doing a copy, no way around it.</p>
<p>In short, the outcome is:</p>
<ul>
<li><p>If an lvalue is being passed in, both <code>X</code> and <code>Y</code> will perform a copy (<code>X</code> when initialising <code>name</code>, <code>Y</code> when initialising <code>mem_name</code>). In addition, <code>X</code> will perform a move (when initialising <code>mem_name</code>).</p></li>
<li><p>If an rvalue is being passed in, <code>X</code> will potentially only perform a move, while <code>Y</code> has to perform a copy.</p></li>
</ul>
<p>Generally, a move is expected to be an operation whose time requirements are comparable to those of passing a pointer (which is what passing by reference does). So in effect, <code>X</code> is no worse than <code>Y</code> for lvalues, and better for rvalues.</p>
<p>Of course, it's not an absolute rule, and must be taken with a grain of salt. When in doubt, profile.</p>
<hr>
<p>(1) The link is prone to being temporarily unavailable, and as of 11-12-2014, it seems broken (404). A copy of the contents (albeit with weird formatting) seems available at several blog sites:</p>
<ul>
<li><a href="http://m.blog.csdn.net/blog/CPP_CHEN/17528669" rel="noreferrer">blog on csdn.net</a></li>
<li><a href="https://joseluisestebanaparicio.blogspot.cz/2010/06/want-speed-pass-by-value.html" rel="noreferrer">blog on blogspot.cz</a></li>
</ul>
<p>Alternatively, the original content might be accessible through the <a href="https://web.archive.org/web/20140205194657/http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/" rel="noreferrer">wayback machine</a>.</p>
<p>Also note that the topic has in general stirred up quite a discussion. Googling the paper title brings up a lot of follow-ups and counter-points. To list an example of one of these, there's <a href="http://juanchopanzacpp.wordpress.com/2014/05/11/want-speed-dont-always-pass-by-value/" rel="noreferrer">"Want speed? Don't (always) pass by value"</a> by SO member <a href="https://stackoverflow.com/users/661519/juanchopanza">juanchopanza</a></p> |
17,440,517 | what is the best way to check variable type in javascript | <pre><code><script type="text/javascript">
function saveName (firstName) {
function capitalizeName () {
return firstName.toUpperCase();
}
var capitalized = capitalizeName();console.log(capitalized instanceof String);
return capitalized;
}
console.log(saveName("Robert")); // Returns "ROBERT"
</script>
</code></pre>
<p>Question:</p>
<p>I want to check the type of capitalized , so I use <code>capitalized instanceof String</code>? But it shows: <code>false</code> in console, I do not want to try <code>capitalized instanceof Function</code>, <code>Object</code>...It will take too much time, so what is the best way to detect a variable type?</p> | 17,440,547 | 8 | 2 | null | 2013-07-03 05:42:44.817 UTC | 7 | 2022-04-27 09:52:14.607 UTC | null | null | null | null | 2,507,818 | null | 1 | 44 | javascript | 96,425 | <p>The best way is to use the <code>typeof</code> keyword.</p>
<pre><code>typeof "hello" // "string"
</code></pre>
<p>The <code>typeof</code> operator maps an operand to one of six values: <code>"string"</code>, <code>"number"</code>, <code>"object"</code>, <code>"function"</code>, <code>"undefined"</code> and <code>"boolean"</code>. The <code>instanceof</code> method tests if the provided function's prototype is in the object's prototype chain.</p>
<p><a href="http://en.wikibooks.org/wiki/JavaScript/Variables_and_Types" rel="noreferrer">This Wikibooks article</a> along with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals" rel="noreferrer">this MDN articles</a> does a pretty good job of summing up JavaScript's types.</p> |
17,623,528 | How can Vagrant forward multiple ports on the same machine? | <p>I'm wondering how to setup a Vagrant file that will put up a machine with two ports forwarded.
This is my current Vagrantfile, which is forwarding the 8080 page:</p>
<pre><code>Vagrant.configure("2") do |config|
config.vm.box = "precise32"
config.vm.box_url = "http://files.vagrantup.com/precise32.box"
config.vm.provider "virtualbox"
config.vm.network :forwarded_port, guest: 8080, host: 8080
config.vm.provision :shell, :path => "start.sh", :args => "'/vagrant'"
config.vm.network :public_network
end
</code></pre>
<p>Thanks!</p> | 17,624,165 | 4 | 1 | null | 2013-07-12 20:30:32.923 UTC | 9 | 2019-07-21 16:19:00.82 UTC | 2013-11-06 16:46:49.113 UTC | null | 1,246,262 | null | 1,783,793 | null | 1 | 58 | vagrant|portforwarding | 31,859 | <p>If you want to forward two ports, you may simply add another line like this:</p>
<pre><code>config.vm.network :forwarded_port, guest: 8080, host: 8080
config.vm.network :forwarded_port, guest: 5432, host: 5432
</code></pre>
<p>A better way, in my opinion, is to setup a private network (or host-only network), so that you don't have to forward all the ports manually.</p>
<p>See my post here:
<a href="https://stackoverflow.com/questions/16244601/vagrant-reverse-port-forwarding/17012410#17012410">Vagrant reverse port forwarding?</a></p>
<h3>Additional tips</h3>
<p>If you use the <code>:id</code> feature when defining <code>:forward_port</code> entries you need to make sure that each is unique. Otherwise they'll clobber each other, and the last one defined will typically win out.</p>
<p>For example:</p>
<pre><code>config.vm.network "forwarded_port", guest: 8080, host: 8080, id: 'was_appserver_http'
config.vm.network "forwarded_port", guest: 9043, host: 9043, id: 'ibm_console_http'
config.vm.network "forwarded_port", guest: 9060, host: 9060, id: 'ibm_console_https'
</code></pre> |
17,167,636 | How to install an apk on the emulator in Android Studio? | <p>How do you install an apk on the emulator in Android Studio from the terminal? </p>
<p>In Eclipse we did </p>
<pre><code>/home/pcname/android-sdks/platform-tools/adb -s emulator-5554 install /home/pcname/Downloads/apkname.apk
</code></pre>
<p>Now how about in Android Studio?</p> | 17,173,794 | 14 | 2 | null | 2013-06-18 11:23:50.047 UTC | 36 | 2022-07-17 11:00:33.08 UTC | 2016-09-05 06:41:44.33 UTC | null | 3,681,880 | null | 2,309,948 | null | 1 | 118 | android|android-studio | 261,924 | <p><strong>EDIT:</strong> Even though this answer is marked as the correct answer (in 2013), currently, as answered by @user2511630 below, you can drag-n-drop apk files directly into the emulator to install them.</p>
<hr>
<p><strong>Original Answer:</strong></p>
<p>You can install <strong>.apk</strong> files to emulator regardless of what you are using (Eclipse or Android Studio)</p>
<p>here's what I always do: (For full beginners)</p>
<p>1- Run the emulator, and wait until it's completely started.</p>
<p>2- Go to your <strong>sdk</strong> installation folder then go to <strong>platform-tools</strong> (you should see an executable called <strong>adb.exe</strong>) </p>
<p>3- create a new file and call it <strong>run.bat</strong>, edit the file with notepad and write <strong>CMD</strong> in it and save it.</p>
<p>4- copy your desired apk to the same folder</p>
<p>5- now open run.bat and write <strong><code>adb install "your_apk_file.apk"</code></strong></p>
<p>6- wait until the installation is complete </p>
<p>7- voila your apk is installed to your emulator.</p>
<p><strong>Note:</strong> to re-install the application if it already existe use <strong><code>adb install -r "your_apk_file.apk"</code></strong></p>
<p>sorry for the detailed instruction as I said for full beginners</p>
<p>Hope this help.</p>
<p>Regards, </p>
<p>Tarek</p>
<p><img src="https://i.stack.imgur.com/ihGQP.jpg" alt="Example 1"></p>
<p><img src="https://i.stack.imgur.com/9x0R7.jpg" alt="Example 2"></p> |
17,534,661 | Make anchor link go some pixels above where it's linked to | <p>I'm not sure the best way to ask/search for this question:</p>
<p>When you click on an anchor link, it brings you to that section of the page with the linked-to area now at the VERY TOP of the page. I would like the anchor link to send me to that part of the page, but I would like some space at the top. As in, I don't want it to send me to the linked-to part with it at the VERY TOP, I would like 100 or so pixels of space there.</p>
<p>Does this make sense? Is this possible? </p>
<p>Edited to show code - it's just an anchor tag:</p>
<pre><code><a href="#anchor">Click me!</a>
<p id="anchor">I should be 100px below where I currently am!</p>
</code></pre> | 17,535,094 | 26 | 3 | null | 2013-07-08 19:42:57.42 UTC | 63 | 2022-07-27 10:02:24.24 UTC | 2013-07-08 19:48:56.433 UTC | null | 1,925,805 | null | 1,925,805 | null | 1 | 163 | javascript|html|css|anchor | 182,065 | <pre><code>window.addEventListener("hashchange", function () {
window.scrollTo(window.scrollX, window.scrollY - 100);
});
</code></pre>
<p>This will allow the browser to do the work of jumping to the anchor for us and then we will use that position to offset from.</p>
<p><strong>EDIT 1:</strong></p>
<p>As was pointed out by @erb, this only works if you are on the page while the hash is changed. Entering the page with a <code>#something</code> already in the URL does not work with the above code. Here is another version to handle that:</p>
<pre><code>// The function actually applying the offset
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);
// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).
</code></pre>
<p><em>NOTE:
To use jQuery, you could just replace <code>window.addEventListener</code> with <code>$(window).on</code> in the examples. Thanks @Neon.</em></p>
<p><strong>EDIT 2:</strong></p>
<p>As pointed out by a few, the above will fail if you click on the same anchor link two or more times in a row because there is no <code>hashchange</code> event to force the offset.</p>
<p>This solution is very slightly modified version of the suggestion from @Mave and uses jQuery selectors for simplicity</p>
<pre><code>// The function actually applying the offset
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
// Click events are captured before hashchanges. Timeout
// causes offsetAnchor to be called after the page jump.
window.setTimeout(function() {
offsetAnchor();
}, 0);
});
// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);
</code></pre>
<p>JSFiddle for this example is <a href="https://jsfiddle.net/ju5xLgkq/" rel="noreferrer">here</a></p> |
36,768,418 | How to make CORS-enabled HTTP requests in Angular 2? | <p>The error is the following:</p>
<blockquote>
<p>XMLHttpRequest cannot load <a href="http://some_url.herokuapp.com/api/some_api/" rel="nofollow noreferrer">http://some_url.herokuapp.com/api/some_api/</a>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<a href="http://localhost:3000" rel="nofollow noreferrer">http://localhost:3000</a>' is therefore not allowed access. The response had HTTP status code 503.</p>
</blockquote>
<p>when calling</p>
<pre><code>return this._http.post(requestUrl, JSON.stringify(requestBody), requestOptions)
</code></pre>
<p>I had troubles with CORS (when working with <strong>Angular 1</strong>) in the past and I remember that once CORS were activated server-side,I had to <strong>transform the http request to parse certain HTTP headers</strong>.</p>
<p>I am quite confused about how it should work, so any explanation is very welcome.</p> | 36,768,488 | 2 | 2 | null | 2016-04-21 11:37:02.04 UTC | 2 | 2020-02-26 11:14:54.29 UTC | 2020-02-26 10:37:23.253 UTC | null | 7,508,700 | null | 1,219,368 | null | 1 | 20 | angular|cors | 61,683 | <p>In fact, it's not an Angular2 issue but a problem at the server side. The preflighted OPTIONS request needs to return an <code>Access-Control-Allow-Origin</code> header in its response.</p>
<p>Sending the <code>Origin</code> header in the original request will enable the CORS support on the server side. This header is automatically added by the browser when it detects that the domain of the request isn't the same as the caller's.</p>
<p>Be careful when implementing the preflight OPTIONS request on the server side since <strong>credentials aren't sent at this level</strong>. They are only sent within the target request. It seems to be the problem since you have 503 error. You're trying to check if the OPTIONS request is authenticated but it's not actually the case...</p>
<p>See this article for more details:</p>
<ul>
<li><a href="http://restlet.com/blog/2015/12/15/understanding-and-using-cors/" rel="noreferrer">http://restlet.com/blog/2015/12/15/understanding-and-using-cors/</a></li>
</ul> |
5,018,391 | Finite State Machine Pattern - The One True Pattern? | <p>Could all Code ever written be improved by applying the State Machine Pattern?</p>
<p>I was working on a project that was a mass of horrendous awful, buggy, broken spaghetti code.
I copied <a href="http://www.informit.com/articles/article.aspx?p=1592379" rel="noreferrer">Martin Fowler's example State Machine code from this blog</a> and transformed the whole heap of crap into a series of statements.
Literally just a list of States, Events, Transitions and Commands.</p>
<p>I can't believe the transformation. The code is now clean, and works. Of course i was aware of State Machines before and have even implemented them
but in the Martin Fowler example the separation of model/configuration is amazing.</p>
<p>This makes me think that almost everything i've ever done could have benefitted in some way from this approach. I want this functionality in every language i use.
Maybe this should even be a language level feature.</p>
<p>Anyone think this is wrong?
Or anyone have a similar experience with a different pattern?</p> | 5,018,459 | 3 | 2 | null | 2011-02-16 15:33:30.633 UTC | 10 | 2021-03-30 23:43:17.31 UTC | 2011-02-16 15:50:35.803 UTC | null | 311,745 | null | 311,745 | null | 1 | 19 | design-patterns|architecture|state-machine | 9,635 | <p>Finite state machines (FSM's) and more specifically domain specific languages (DSL's) make it easier to match a problem to one specific solution domain, by describing the solution in a specialised language. </p>
<p>The limitations of the State Machine pattern is that it itself constitutes a programming language, but one for which you have to write your own execution, testing and debugging tools; and one which any maintainer has to learn. You have moved the complexity of your code into a complex FSM configuration. Occasionally, this is useful, but certainly not universally.</p>
<p>And since any von Neumann computer is itself a FSM, then certainly any program <strong>can</strong> be recast in this fashion. </p> |
5,212,994 | Official way to create iOS icons? | <p>I find it hard to believe that every developer creates their icons manually in various different ways but if that is the case, that is fine. I was wonder what the standard was for creating iOS icons (home screen icons, etc.)</p> | 5,213,066 | 3 | 4 | null | 2011-03-06 19:58:35.517 UTC | 13 | 2011-03-06 20:10:23.793 UTC | null | null | null | null | 67,179 | null | 1 | 26 | iphone|ipad|ios|xamarin.ios|ipod-touch | 36,550 | <p>Apple do have some guidelines for creating icon of app. Via:</p>
<p><a href="http://developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/MobileHIG/IconsImages/IconsImages.html" rel="noreferrer">http://developer.apple.com/library/ios/#DOCUMENTATION/UserExperience/Conceptual/MobileHIG/IconsImages/IconsImages.html</a></p>
<p>Doing some search, you'll find a lot of article talking about icon making experience. Such as:</p>
<p><a href="http://eddit.com/notebook/archive/iphone_app_icon_template/" rel="noreferrer">http://eddit.com/notebook/archive/iphone_app_icon_template/</a></p>
<p><a href="http://pixelresort.com/blog/iphone-app-icon-design-best-practises/" rel="noreferrer">http://pixelresort.com/blog/iphone-app-icon-design-best-practises/</a></p>
<p>And here's a tutorial on making icon:</p>
<p><a href="http://mobile.tutsplus.com/tutorials/mobile-design-tutorials/iphone-icon-design-creating-a-logo-for-bankapp/" rel="noreferrer">http://mobile.tutsplus.com/tutorials/mobile-design-tutorials/iphone-icon-design-creating-a-logo-for-bankapp/</a></p>
<p>I hope those links help.</p> |
5,070,100 | execute a main class from a jar | <p>I have a jar which contain two main class Class A and Class B. In the manifest i have mentioned Class A . Now i have to execute classB from the same jar . what should be the command. </p>
<p>I dont prefer to make two separate jars.</p>
<p>Thanks</p> | 5,070,133 | 3 | 0 | null | 2011-02-21 19:08:16.87 UTC | 4 | 2011-02-21 19:11:18.53 UTC | null | null | null | null | 67,476 | null | 1 | 28 | java|jar | 45,808 | <p>This will do the job: <code>java -classpath yourjar.jar youpackage.B</code></p> |
5,132,397 | Fast way to convert a two dimensional array to a List ( one dimensional ) | <p>I have a two dimensional array and I need to convert it to a List (same object). I don't want to do it with <code>for</code> or <code>foreach</code> loop that will take each element and add it to the List. Is there some other way to do it? </p> | 5,132,454 | 3 | 9 | null | 2011-02-27 09:26:50.657 UTC | 15 | 2019-09-04 13:40:57.85 UTC | 2018-09-17 14:06:56.753 UTC | null | 1,671,066 | null | 465,558 | null | 1 | 33 | c#|arrays|list|type-conversion | 67,026 | <p>To convert <code>double[,]</code> to <code>List<double></code>, if you are looking for a one-liner, here goes</p>
<pre><code>double[,] d = new double[,]
{
{1.0, 2.0},
{11.0, 22.0},
{111.0, 222.0},
{1111.0, 2222.0},
{11111.0, 22222.0}
};
List<double> lst = d.Cast<double>().ToList();
</code></pre>
<p><hr/>
<strong>But, if you are looking for something efficient, I'd rather say you don't use this code.</strong><br>
Please follow either of the two answers mentioned below. Both are implementing much much better techniques.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.