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
10,763,640
C# Windows Form Application Transparent button
<p>I'm new to C#. I'd like to create an invisible button, but they are click-able in C# windows form application. Is there a way? I tried BackColor to Transparent, but that does not change the fact that it is transparent</p>
31,697,399
6
4
null
2012-05-26 04:41:17.78 UTC
1
2022-07-11 11:41:12.053 UTC
null
null
null
null
1,418,608
null
1
13
c#|button
51,191
<p>Its simple try this.</p> <p>Click the button that you want to make transparent. Select <code>FlatStyle</code> from Properties and set it to <strong>popup</strong> Now change the <code>BackColor</code> property to <code>Transparent</code>.</p> <p>This will make the button transparent. </p> <p>However if you want to make it transparent over a <code>PictureBox</code> this method wont work..</p> <p>It works only on normal backgrounds and background images. Hope it works....</p>
10,570,884
How to get the current Time and TimeZone from Locale?
<p>I have this weird problem, when I create a calendar with a locale, the TimeZone just reverts to the local one</p> <pre><code>public void start(Locale locale){ String s = locale.getDisplayName(); System.err.println(s); Calendar c = new GregorianCalendar(locale); System.err.println(c.getTimeZone()); } </code></pre> <p>And this is the output:</p> <pre><code> español (Argentina) sun.util.calendar.ZoneInfo[id="Europe/Bucharest", //etc more useless date here.... </code></pre> <p>How can i get the proper time from a specific locale ?</p>
10,571,144
2
5
null
2012-05-13 10:04:05.94 UTC
5
2020-06-05 06:32:40.783 UTC
2017-03-08 17:05:17.43 UTC
null
184,201
null
1,022,048
null
1
26
java|time|timezone|locale
79,510
<p>The short answer: you can't.</p> <p>The long answer: There is no such thing as "proper time zone for a locale". That's just because there are a few countries that have more than one time zone (for example United States). Time zone is a different concept.</p> <p>Anyway, you are looking to solve your problem. I am guessing that you are writing a web application and you see that the time zone is reverting to the server default. That's a typical situation. Both <code>Locale.getDefault()</code> and <code>TimeZone.getDefault()</code> will return server-related information. The JVM has no way of knowing the "proper" time zone. So what can you do about it?</p> <ol> <li>You can add time zone information to user profile (if you have one), or create a time zone combo box (so that the user can switch at runtime). Then you can assign an appropriate object to <code>DateFormat</code> instance and it will convert time zone automatically.</li> <li>You can read the <strong><em>current</em></strong> time zone offset from the client via JavaScript Date Object's <a href="http://www.w3schools.com/jsref/jsref_gettimezoneoffset.asp" rel="noreferrer">getTimezoneOffset()</a> function and somehow (AJAX) send it to the server. The problem with this method is that there are several time zones with that offset, and the selected time zone might be inappropriate for other dates. Of course you can guess the time zone by polling the data around time change date, but this is probably not what you want to do.</li> <li>You can send the unformatted time to the client (for example written as <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601 date-time format</a> or as a <a href="http://en.wikipedia.org/wiki/Unix_time" rel="noreferrer">Unix time of the epoch</a> in relation to UTC) and have <a href="https://github.com/jquery/globalize" rel="noreferrer">Globalize</a> or <a href="http://dojotoolkit.org/" rel="noreferrer">Dojo</a> format date and time for you.</li> </ol> <p>Out of these three possible choices, I always opt for number 1. By putting time zone information to user profile, you know for sure what his/her preferred time zone is, regardless of their current web browser, etc. Please keep in mind that some users might want to use your application while visiting other countries...</p>
10,492,037
The application was unable to start correctly (0xc000007b)
<p>I have a client/server app which I have been developing on a single PC. Now it needs two serial ports, so I borrowed a PC from a friend.</p> <p>When I build my app and try to run or debug it (whether in the Delphi IDE or from Windows File manager), it errors "The application was unable to start correctly (0xc000007b)".</p> <p>Googling doesn't bring up much, but seems to indicate that this is nothing Delphi specific and happens with other apps. It seems to be caused by calling into a 32 bit DLL from a 64 bit app or vice versa.</p> <ul> <li>both PCs are Windows 7, 64 bit</li> <li>both have Delphi Xe2 starter edition which can only handle 32 bits</li> <li>The app runs fine on my PC, but not on my friend's</li> <li>Other Delphi apps run just fine on both PCs</li> </ul> <p>Can anyone give me a hint as to how to track this down?</p>
10,493,137
19
7
null
2012-05-08 03:08:20.457 UTC
27
2022-04-19 07:35:53.73 UTC
2016-12-08 11:05:01.14 UTC
null
192,910
null
192,910
null
1
176
windows|delphi|64-bit
418,661
<p>Normally we get the <code>0xC000007B</code> error-code (which means <code>STATUS_INVALID_IMAGE_FORMAT</code>), if:</p> <ul> <li>If a 32-bit app tried to load a 64-bit DLL.</li> <li>Or if a 64-bit app tried to load a 32-bit DLL.</li> </ul> <p>To really know, I would suggest to test whether there is a problem between your application and its dependencies using <a href="http://www.dependencywalker.com/" rel="nofollow noreferrer">dependency walker</a></p> <blockquote> <p><strong>Note</strong> that all you need to do is open your App using said tool, and issues appear as red log-entries at buttom of screen.</p> <p>(At least, at time of writting, namely 2022)</p> <p>Also, make sure you run the correct version of Dependency Walker, for example, the x86 version will display incorrect results when openning x64 binaries.</p> </blockquote>
53,225,106
Why doesn't my compiler recognise "Bond() = default;"?
<p>Please look at this code</p> <pre><code>class Bond { public: Bond(int payments_per_year, int period_lengths_in_months); Bond() = default; private: const int payments_per_year; const int period_length_in_months; }; int main() { Bond b; // Error here } </code></pre> <p>When attempting to compile I get an error:</p> <blockquote> <p>error C2280: 'Bond::Bond(void)': attempting to reference a deleted function".</p> </blockquote> <p>It's not a "rule of 3" violation since I've added the default constructor back.</p> <p>Why doesn't the compiler recognise <code>Bond() = default;</code>?</p>
53,227,269
3
4
null
2018-11-09 11:42:18.893 UTC
0
2018-11-15 08:04:50.013 UTC
2018-11-10 07:01:02.92 UTC
null
63,550
null
10,628,642
null
1
39
c++|c++11
3,371
<p>You are being affected by section <a href="http://eel.is/c++draft/class.default.ctor#2" rel="noreferrer">[class.default.ctor]p2</a> of the draft C++ standard (or <a href="https://timsong-cpp.github.io/cppwp/n3337/class.ctor#5.3" rel="noreferrer">[class.ctor]p5</a> in C++11) which says:</p> <blockquote> <p>A defaulted default constructor for class X is defined as deleted if:<br> ...<br> - any non-variant non-static data member of const-qualified type (or array thereof) with no brace-or-equal-initializer does not have a user-provided default constructor,<br> ...</p> </blockquote> <p>They possible key to fixing your issue is with the phrase <em>with no brace-or-equal-initializer</em> so if you provide <em>brace-or-equal-initializer</em> that will fix your issue e.g.:</p> <pre><code>const int payments_per_year{12}; const int period_length_in_months{48}; </code></pre> <p><a href="http://eel.is/c++draft/dcl.init#nt:brace-or-equal-initializer" rel="noreferrer">brace-or-equal-initializer</a> does not require braces, we can see this the grammar:</p> <pre><code>brace-or-equal-initializer: = initializer-clause braced-init-list </code></pre> <p>but using uniform initialization has some advantages such as making <a href="https://stackoverflow.com/a/31685448/1708801">narrowing conversions ill-formed</a> that it is worth getting used to using them.</p> <p>Both gcc and clang provide more meaningful diagnostics for this <a href="https://godbolt.org/z/ghX21z" rel="noreferrer">see the live godbolt session</a>. Sometimes it can be helpful to try your code on multiple compilers, especially if you have a minimal test case like this e.g. clang says:</p> <pre><code> warning: explicitly defaulted default constructor is implicitly deleted [-Wdefaulted-function-deleted] Bond() = default; ^ note: default constructor of 'Bond' is implicitly deleted because field 'payments_per_year' of const-qualified type 'const int' would not be initialized const int payments_per_year; ^ ... </code></pre>
35,709,497
Anaconda Python: where are the virtual environments stored?
<p>I am new to Anaconda Python and I am setting up a project in Sublime Text 3. I have installed Anaconda and created a virtual environment using:</p> <pre><code>conda create -n python27 python=2.7 anaconda conda create -n python35 python=3.5 anaconda </code></pre> <p>I am having trouble setting up the Virtualenvs plugin for SublimeText 3. </p> <p>When I try, it asks me for a virtualenvs path which I give:</p> <pre><code>~/users/../anaconda/envs/python27 </code></pre> <p>Then it asks for what I'm assuming is a path to a python distribution because it lists file paths for the system versions of python -- but not the anaconda install.</p> <p>I have no real desire to use the plug in, I just want to be able to use both versions of python. Could I use a project settings file to set the version of python instead?</p>
47,277,111
9
5
null
2016-02-29 20:58:11.477 UTC
19
2020-07-18 08:13:22.147 UTC
2019-08-07 17:59:47.037 UTC
null
1,048,186
null
2,106,088
null
1
71
python|virtualenv|sublimetext3|osx-yosemite|anaconda
122,552
<p>If you activate the environment you're interested in, you can find that answer in the environment variables.</p> <p>on MacOS/Linux:</p> <pre><code>source activate python35 echo $CONDA_PREFIX </code></pre> <p>on Windows:</p> <pre><code>conda activate python35 echo %CONDA_PREFIX% </code></pre> <p>You can also run <code>conda info --envs</code>, and that will show the paths to all your environments.</p> <p>To get the path to the instance of python being used by a particular environment, do the following:</p> <p>on MacOS/Linux:</p> <pre><code>source activate python35 which python </code></pre> <p>on Windows:</p> <pre><code>conda activate python35 where python </code></pre> <p>That should return the path you're looking for. </p>
35,602,939
MySQL 1292 Incorrect datetime value
<p>I am getting this error when I try to insert '2011/03/13 02:53:50.000000000' into a timestamp column. If I change the 13 to a 15, 14, 12 or 11 it works no problem. I've also tried changing the /'s to -'s and still no-go.</p> <p>I've looked through some of the other threads related to this error but none seem to apply.</p> <p>I'm running version 5.7.9.</p>
35,964,177
4
7
null
2016-02-24 13:01:10.727 UTC
2
2020-03-06 08:19:42.603 UTC
2019-01-14 11:22:05.017 UTC
null
1,426,539
null
3,586,878
null
1
17
mysql|sql-timestamp|mysql-error-1292
74,414
<p>It took me a while to figure this out...</p> <p>The problem is that '2011-03-13 02:53:50' is illegal because of daylight saving time switch between 2 and 3 AM, so all time values between 2 and 3 am on any DST introduction day are invalid. Same for '2016-03-13 02:32:21', etc.</p> <p>Change the system timezone to the one that does not use DST and you should be fine.</p>
13,601,366
EntityFrameWork and TableValued Parameter
<p>I'm trying to call a stored procedure from <strong>EntityFramework</strong> which uses <strong>Table-value</strong> parameter.</p> <p>But when I try to do function import I keep getting a warning message saying -</p> <blockquote> <p>The function 'InsertPerson' has a parameter 'InsertPerson_TVP' at parameter index 0 that has a data type 'table type' which is currently not supported for the target .NET Framework version. The function was excluded.</p> </blockquote> <p>I did a initial search here and found few posts which says It's possible in EntityFrameWork with some work arounds and <a href="https://stackoverflow.com/questions/2837350/table-valued-parameter-in-stored-procedure-and-the-entity-framework-4-0">few</a> saying it's not supported in current versions. </p> <p>Does any one know a better approach or solution for this problem?</p>
14,578,900
3
1
null
2012-11-28 09:04:34.57 UTC
9
2017-10-18 04:52:29.883 UTC
2017-10-18 04:52:29.883 UTC
null
1,251,376
null
1,251,376
null
1
11
entity-framework|stored-procedures|bulkinsert|table-valued-parameters
10,078
<p>I ended up doing this, Please note we are working on EF <code>DataContext</code>(not <code>ObjectContext</code>)</p> <p><strong>Executing a Stored procedure with output parameter</strong></p> <pre><code> using (DataContext context = new DataContext()) { ////Create table value parameter DataTable dt = new DataTable(); dt.Columns.Add("Displayname"); dt.Columns.Add("FirstName"); dt.Columns.Add("LastName"); dt.Columns.Add("TimeStamp"); DataRow dr = dt.NewRow(); dr["Displayname"] = "DisplayName"; dr["FirstName"] = "FirstName"; dr["LastName"] ="LastName"; dr["TimeStamp"] = "TimeStamp"; dt.Rows.Add(dr); ////Use DbType.Structured for TVP var userdetails = new SqlParameter("UserDetails", SqlDbType.Structured); userdetails.Value = dt; userdetails.TypeName = "UserType"; ////Parameter for SP output var result = new SqlParameter("ResultList", SqlDbType.NVarChar, 4000); result.Direction = ParameterDirection.Output; context.Database.ExecuteSqlCommand("EXEC UserImport @UserDetails, @ResultList OUTPUT", userdetails, result); return result == null ? string.Empty : result.Value.ToString(); } </code></pre> <p>My <strong>Table-Value-Parameter</strong> (UDT Table) script looks like this:</p> <pre><code>CREATE TYPE [dbo].[UserType] AS TABLE ( [DisplayName] NVARCHAR (256) NULL, [FirstName] NVARCHAR (256) NULL, [LastName] NVARCHAR (256) NULL, [TimeStamp] DATETIME NULL ) </code></pre> <p>And my <strong>store procedure</strong> begins like</p> <pre><code>CREATE PROCEDURE UserImport -- Add the parameters for the stored procedure here @UserDetails UserType Readonly, @ResultList NVARCHAR(MAX) output AS </code></pre> <p>For Stored procedure without <code>output</code> parameter we don't need any ouput parameter added/passed to SP.</p> <p>Hope it helps some one.</p>
13,436,553
How to get cell value of DataGridView by column name?
<p>I have a WinForms application with a <code>DataGridView</code>, which DataSource is a DataTable (filled from SQL Server) which has a column of <code>xxx</code>. The following code raises the exception of </p> <blockquote> <p>ArgumentException was unhandled. Column named xxx cannot be found.</p> </blockquote> <pre><code>foreach (DataGridViewRow row in Rows) { if (object.Equals(row.Cells["xxx"].Value, 123)) } </code></pre> <p>Is it possible to get the cell values by column name?</p>
13,436,750
8
0
null
2012-11-18 01:15:57.4 UTC
6
2021-10-24 13:08:10.897 UTC
2017-09-14 14:40:23.87 UTC
null
6,760,571
null
825,920
null
1
27
c#|winforms|datagridviewcolumn
90,507
<p><code>DataGridViewColumn</code> objects have a <code>Name</code> (shown only in the forms designer) and a <code>HeaderText</code> (shown in the GUI at the top of the column) property. The indexer in your example uses the column's <code>Name</code> property, so since you say that isn't working I assume you're really trying to use the column's header.</p> <p>There isn't anything built in that does what you want, but it's easy enough to add. I'd use an extension method to make it easy to use:</p> <pre><code>public static class DataGridHelper { public static object GetCellValueFromColumnHeader(this DataGridViewCellCollection CellCollection, string HeaderText) { return CellCollection.Cast&lt;DataGridViewCell&gt;().First(c =&gt; c.OwningColumn.HeaderText == HeaderText).Value; } } </code></pre> <p>And then in your code:</p> <pre><code>foreach (DataGridViewRow row in Rows) { if (object.Equals(row.Cells.GetCellValueFromColumnHeader("xxx"), 123)) { // ... } } </code></pre>
13,588,565
Spring Data JPA - Why are changes to a returned Entity automatically persisted?
<p>I present the question with an example.</p> <p>Assert that we have a Repository such as the below:</p> <pre><code>public interface ExampleObjectRepository extends CrudRepository&lt;ExampleObject, Long&gt; { } </code></pre> <p>By extending the <code>JpaRepository</code> interface, the <code>ExampleObject</code> repository inherits the following method:</p> <pre><code>T findOne(ID id); </code></pre> <p>Now, I have observed that, if I receive a reference to an ExampleObject after a call to this method, any manipulations that I make to this method are automatically saved to the database, for example:</p> <pre><code>ExampleObject pointInCase = exampleObjectRepository.findOne(1L); pointInCase.setName("Something else"); </code></pre> <p>Reading around the subject, I understand this this signfies that <code>ExampleObject</code> instance is <code>not detached</code>.</p> <p>This goes against my expectations. I would have expected that I would need to use the save method inherited from <code>CrudRepository</code> in order to save the changes:</p> <pre><code>T save(T entity); </code></pre> <p>Would anyone be kind enough to confirm that objects returned from a Spring Data JPA Repository remain attached as standard, and explain how to use the API to mark a method in the repository such that it only returns detached references?</p> <p>I imagine that changing the entity's state may also change its definition when it is used with said <code>save(T entity)</code> method, so I would also appreciate an understanding of how identity for updates are handled.</p>
13,589,352
3
1
null
2012-11-27 16:22:42.733 UTC
13
2019-02-12 06:35:36.643 UTC
2012-11-27 17:01:58.49 UTC
null
653,708
null
653,708
null
1
38
spring|jpa|spring-data-jpa
18,854
<p>That's a fundamental principle of JPA. You work with attached (managed) entities, and every modification made on these managed entities is automatically made persistent. </p> <p>If you don't want your changes to be persistent, then don't make changes, or rollback the transaction.</p> <p>Working on detached entities would be a nightmare, because it would prevent lazy-loading all the associations. You can always call <code>EntityManager.detach()</code> on your entities, but I really wouldn't do that. Just try to understand how it works and deal with it. There are much more benefits than disadvantages. One of them being that you don't even have to think about saving all the changes that a complex business logic might do, since it's all done for you by JPA, transparently.</p>
13,704,789
Can I use complex HTML with Twitter Bootstrap's Tooltip?
<p>If I check <a href="http://twitter.github.com/bootstrap/javascript.html#tooltips">official documentation</a>, I can see a property called HTML:</p> <pre><code>Name | Type | default | Description ---------------------------------------------------------------------------- html | boolean | false | Insert html into the tooltip. If false, jquery's text method will be used to insert content into the dom. Use text if you're worried about XSS attacks. </code></pre> <p>It says, "insert html into the tooltip", but the type is boolean. How can I use complex html inside a Tooltip?</p>
13,705,417
6
0
null
2012-12-04 14:09:08.073 UTC
33
2021-10-09 14:18:56.84 UTC
2016-12-06 19:10:45.597 UTC
null
1,407,478
null
1,575,153
null
1
151
javascript|html|twitter-bootstrap-3|tooltip
199,924
<p>This parameter is just about whether you are going to use complex html into the tooltip. Set it to <code>true</code> and then hit the html into the <code>title</code> attribute of the tag.</p> <p>See this fiddle <a href="http://jsfiddle.net/44khF/200/" rel="noreferrer">here</a> - I've set the html attribute to true through the <code>data-html="true"</code> in the <code>&lt;a&gt;</code> tag and then just added in the html ad hoc as an example.</p>
13,437,727
How to write to an Excel spreadsheet using Python?
<p>I need to write some data from my program to an Excel spreadsheet. I've searched online and there seem to be many packages available (xlwt, XlsXcessive, openpyxl). Others suggest writing to a .csv file (never used CSV and don't really understand what it is).</p> <p>The program is very simple. I have two lists (float) and three variables (strings). I don't know the lengths of the two lists and they probably won't be the same length.</p> <p>I want the layout to be as in the picture below:</p> <p><a href="https://i.stack.imgur.com/Ih3fa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ih3fa.png" alt="Layout sample" /></a></p> <p>The pink column will have the values of the first list and the green column will have the values of the second list.</p> <p>So what's the best way to do this?</p> <p>I am running Windows 7 but I won't necessarily have Office installed on the computers running this program.</p> <pre class="lang-py prettyprint-override"><code>import xlwt x=1 y=2 z=3 list1=[2.34,4.346,4.234] book = xlwt.Workbook(encoding=&quot;utf-8&quot;) sheet1 = book.add_sheet(&quot;Sheet 1&quot;) sheet1.write(0, 0, &quot;Display&quot;) sheet1.write(1, 0, &quot;Dominance&quot;) sheet1.write(2, 0, &quot;Test&quot;) sheet1.write(0, 1, x) sheet1.write(1, 1, y) sheet1.write(2, 1, z) sheet1.write(4, 0, &quot;Stimulus Time&quot;) sheet1.write(4, 1, &quot;Reaction Time&quot;) i=4 for n in list1: i = i+1 sheet1.write(i, 0, n) book.save(&quot;trial.xls&quot;) </code></pre> <p>I wrote this using all your suggestions. It gets the job done but it can be slightly improved.</p> <p>How do I format the cells created in the for loop (<code>list1</code> values) as scientific or number?</p> <p>I do not want to truncate the values. The actual values used in the program would have around 10 digits after the decimal.</p>
13,437,772
12
3
null
2012-11-18 05:20:53.67 UTC
96
2022-05-22 06:03:10.243 UTC
2022-05-22 06:03:10.243 UTC
null
2,745,495
null
1,818,975
null
1
184
python|excel|csv
697,558
<pre><code>import xlwt def output(filename, sheet, list1, list2, x, y, z): book = xlwt.Workbook() sh = book.add_sheet(sheet) variables = [x, y, z] x_desc = 'Display' y_desc = 'Dominance' z_desc = 'Test' desc = [x_desc, y_desc, z_desc] col1_name = 'Stimulus Time' col2_name = 'Reaction Time' #You may need to group the variables together #for n, (v_desc, v) in enumerate(zip(desc, variables)): for n, v_desc, v in enumerate(zip(desc, variables)): sh.write(n, 0, v_desc) sh.write(n, 1, v) n+=1 sh.write(n, 0, col1_name) sh.write(n, 1, col2_name) for m, e1 in enumerate(list1, n+1): sh.write(m, 0, e1) for m, e2 in enumerate(list2, n+1): sh.write(m, 1, e2) book.save(filename) </code></pre> <p>for more explanation: <a href="https://github.com/python-excel" rel="noreferrer">https://github.com/python-excel</a></p>
20,609,206
setNeedsLayout vs. setNeedsUpdateConstraints and layoutIfNeeded vs updateConstraintsIfNeeded
<p>I know that the auto layout chain consists in basically 3 different process.</p> <ol> <li>updating constraints</li> <li>layout views (here is where we get calculation of frames)</li> <li>display</li> </ol> <p>What's is not totally clear to me is the inner difference between <code>-setNeedsLayout</code> and <code>-setNeedsUpdateConstraints</code>. From Apple Docs:<br> </p> <p><a href="https://developer.apple.com/reference/uikit/uiview/1622601-setneedslayout" rel="noreferrer"><strong>setNeedsLayout</strong></a></p> <blockquote> <p>Call this method on your application’s main thread when you want to adjust the layout of a view’s subviews. This method makes a note of the request and returns immediately. Because this method does not force an immediate update, but instead waits for the next update cycle, you can use it to invalidate the layout of multiple views before any of those views are updated. This behavior allows you to consolidate all of your layout updates to one update cycle, which is usually better for performance. <br></p> </blockquote> <p><a href="https://developer.apple.com/reference/uikit/uiview/1622450-setneedsupdateconstraints" rel="noreferrer"><strong>setNeedsUpdateConstraints</strong></a></p> <blockquote> <p>When a property of your custom view changes in a way that would impact constraints, you can call this method to indicate that the constraints need to be updated at some point in the future. The system will then call updateConstraints as part of its normal layout pass. Updating constraints all at once just before they are needed ensures that you don’t needlessly recalculate constraints when multiple changes are made to your view in between layout passes.</p> </blockquote> <p>When I want to animate a view after modifying a constraint and animate the changes I usually call for instance:</p> <pre><code>[UIView animateWithDuration:1.0f delay:0.0f usingSpringWithDamping:0.5f initialSpringVelocity:1 options:UIViewAnimationOptionCurveEaseInOut animations:^{ [self.modifConstrView setNeedsUpdateConstraints]; [self.modifConstrView layoutIfNeeded]; } completion:NULL]; </code></pre> <p>I've found out that if I use <code>-setNeedsLayout</code> instead of <code>-setNeedsUpdateConstraints</code> everything work as expected, but if I change <code>-layoutIfNeeded</code> with <code>-updateConstraintsIfNeeded</code>, the animation won't happen.<br> I've tried to make my own conclusion:</p> <ul> <li><code>-updateConstraintsIfNeeded</code> only update constraints but doesn't force the layout to come into the process, thus original frames are still preserved</li> <li><code>-setNeedsLayout</code> calls also <code>-updateContraints</code> method</li> </ul> <p>So when is ok to use one instead of the other? and about the layout methods, do I need to call them on the view that has a change in a constraint or on the parent view?</p>
20,927,069
2
3
null
2013-12-16 10:58:17.013 UTC
197
2018-10-16 14:44:06.983 UTC
2017-10-16 20:57:17.46 UTC
null
5,175,709
null
395,897
null
1
245
ios|objective-c|autolayout|nslayoutconstraint
102,754
<p><strong>Your conclusions are right.</strong> The basic scheme is:</p> <ul> <li><code>setNeedsUpdateConstraints</code> makes sure a future call to <code>updateConstraintsIfNeeded</code> calls <code>updateConstraints</code>.</li> <li><code>setNeedsLayout</code> makes sure a future call to <code>layoutIfNeeded</code> calls <code>layoutSubviews</code>.</li> </ul> <p>When <code>layoutSubviews</code> is called, it also calls <code>updateConstraintsIfNeeded</code>, so calling it manually is rarely needed in my experience. In fact, I have never called it except when debugging layouts.</p> <p>Updating constraints using <code>setNeedsUpdateConstraints</code> is pretty rare too, <a href="http://www.objc.io/issue-3/advanced-auto-layout-toolbox.html">objc.io–a must read about autolayouts–says</a>:</p> <blockquote> <p>If something changes later on that invalidates one of your constraints, you should remove the constraint immediately and call setNeedsUpdateConstraints. <strong>In fact, that’s the only case where you should have to trigger a constraint update pass.</strong></p> </blockquote> <p>In addition, in my experience, I have never had to invalidate constraints, and not set the <code>setNeedsLayout</code> in the next line of the code, because new constraints pretty much are asking for a new layout. </p> <p>The rules of thumb are:</p> <ul> <li>If you manipulated constraints directly, call <code>setNeedsLayout</code>.</li> <li>If you changed some conditions (like offsets or smth) which <em>would</em> change constraints in your overridden <code>updateConstraints</code> method (a recommended way to change constraints, btw), call <code>setNeedsUpdateConstraints</code>, and most of the time, <code>setNeedsLayout</code> after that.</li> <li>If you need any of the actions above to have immediate effect—e.g. when your need to learn new frame height after a layout pass—append it with a <code>layoutIfNeeded</code>.</li> </ul> <p>Also, in your animation code, I believe <code>setNeedsUpdateConstraints</code> is unneeded, since constraints are updated before the animation manually, and the animation only re-lays-out the view based on differences between the old and new ones.</p>
3,822,058
Use enum in h:selectManyCheckbox
<p>I want to use enum values in a <code>&lt;h:selectManyCheckbox&gt;</code>. The checkboxes get populated correctly, however, when selecting some values and submitting them, their runtime type is <code>String</code>, and not enum. My code:</p> <pre><code>&lt;h:selectManyCheckbox value="#{userController.roles}" layout="pageDirection"&gt; &lt;f:selectItems value="#{userController.rolesSelectMany}" /&gt; &lt;/h:selectManyCheckbox&gt; </code></pre> <p>UserController class (SecurityRole is an enum type):</p> <pre><code>public SelectItem[] getRolesSelectMany() { SelectItem[] items = new SelectItem[SecurityRole.values().length]; int i = 0; for (SecurityRole role : SecurityRole.values()) { items[i++] = new SelectItem(role, role.toString()); } return items; } public List&lt;SecurityRole&gt; getRoles() { getCurrent().getRoles(); } public void setRoles(List&lt;SecurityRole&gt; roles) { getCurrent().setRoles(roles); } </code></pre> <p>When JSF calls the setRoles method, it contains a list of type String, and not the enum type. Any ideas? Thanks!</p>
3,823,776
2
0
null
2010-09-29 13:30:01.263 UTC
13
2014-06-18 09:15:49.207 UTC
2014-06-18 09:15:49.207 UTC
null
157,882
null
461,769
null
1
20
jsf|jsf-2|enums|selectmanycheckbox
24,835
<p>This problem is not specifically related to enums. You would have the same problem with other <code>List</code> types for which JSF has builtin converters, e.g. <code>List&lt;Integer&gt;</code>, <code>List&lt;Double&gt;</code>, etcetera.</p> <p>The problem is that EL operates runtime and that generic type information is lost during runtime. So in essence, JSF/EL doesn't know anything about the parameterized type of the <code>List</code> and defaults to <code>String</code> unless otherwise specified by an explicit <code>Converter</code>. In theory, it would have been possible using nasty reflection hacks with help of <a href="http://download.oracle.com/javase/6/docs/api/java/lang/reflect/ParameterizedType.html#getActualTypeArguments%28%29" rel="noreferrer"><code>ParameterizedType#getActualTypeArguments()</code></a>, but the JSF/EL developers may have their reasons for not doing this.</p> <p>You really need to explicitly define a converter for this. Since JSF already ships with a builtin <a href="http://docs.oracle.com/javaee/6/api/javax/faces/convert/EnumConverter.html" rel="noreferrer"><code>EnumConverter</code></a> (which isn't useable standalone in this particular case because you have to specify the enum type during runtime), you could just extend it as follows:</p> <pre><code>package com.example; import javax.faces.convert.EnumConverter; import javax.faces.convert.FacesConverter; @FacesConverter(value="securityRoleConverter") public class SecurityRoleConverter extends EnumConverter { public SecurityRoleConverter() { super(SecurityRole.class); } } </code></pre> <p>And use it as follows:</p> <pre><code>&lt;h:selectManyCheckbox value="#{userController.roles}" converter="securityRoleConverter"&gt; &lt;f:selectItems value="#{userController.rolesSelectMany}" /&gt; &lt;/h:selectManyCheckbox&gt; </code></pre> <p>or</p> <pre><code>&lt;h:selectManyCheckbox value="#{userController.roles}"&gt; &lt;f:converter converterId="securityRoleConverter" /&gt; &lt;f:selectItems value="#{userController.rolesSelectMany}" /&gt; &lt;/h:selectManyCheckbox&gt; </code></pre> <hr> <p>A bit more generic (and hacky) solution would be to storing the enum type as component attribute.</p> <pre><code>package com.example; import javax.faces.application.FacesMessage; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import javax.faces.convert.Converter; import javax.faces.convert.ConverterException; import javax.faces.convert.FacesConverter; @FacesConverter(value="genericEnumConverter") public class GenericEnumConverter implements Converter { private static final String ATTRIBUTE_ENUM_TYPE = "GenericEnumConverter.enumType"; @Override public String getAsString(FacesContext context, UIComponent component, Object value) { if (value instanceof Enum) { component.getAttributes().put(ATTRIBUTE_ENUM_TYPE, value.getClass()); return ((Enum&lt;?&gt;) value).name(); } else { throw new ConverterException(new FacesMessage("Value is not an enum: " + value.getClass())); } } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public Object getAsObject(FacesContext context, UIComponent component, String value) { Class&lt;Enum&gt; enumType = (Class&lt;Enum&gt;) component.getAttributes().get(ATTRIBUTE_ENUM_TYPE); try { return Enum.valueOf(enumType, value); } catch (IllegalArgumentException e) { throw new ConverterException(new FacesMessage("Value is not an enum of type: " + enumType)); } } } </code></pre> <p>It's useable on all kinds of <code>List&lt;Enum&gt;</code> using converter ID <code>genericEnumConverter</code>. For <code>List&lt;Double&gt;</code>, <code>List&lt;Integer&gt;</code>, etc one would have used the builtin converters <code>javax.faces.Double</code>, <code>javax.faces.Integer</code> and so on. The builtin Enum converter is by the way unsuitable due to the inability to specify the target enum type (a <code>Class&lt;Enum&gt;</code>) from the view side on. The JSF utility library <a href="http://omnifaces.org" rel="noreferrer">OmniFaces</a> offers exactly this converter <a href="http://showcase.omnifaces.org/converters/GenericEnumConverter" rel="noreferrer">out the box</a>.</p> <p>Note that for a normal <code>Enum</code> property, the builtin <code>EnumConverter</code> already suffices. JSF will instantiate it automagically with the right target enum type.</p>
28,746,744
Passing capturing lambda as function pointer
<p>Is it possible to pass a lambda function as a function pointer? If so, I must be doing something incorrectly because I am getting a compile error.</p> <p>Consider the following example</p> <pre><code>using DecisionFn = bool(*)(); class Decide { public: Decide(DecisionFn dec) : _dec{dec} {} private: DecisionFn _dec; }; int main() { int x = 5; Decide greaterThanThree{ [x](){ return x &gt; 3; } }; return 0; } </code></pre> <p>When I <a href="http://cpp.sh/5x5r" rel="noreferrer">try to compile this</a>, I get the following compilation error:</p> <pre class="lang-none prettyprint-override"><code>In function 'int main()': 17:31: error: the value of 'x' is not usable in a constant expression 16:9: note: 'int x' is not const 17:53: error: no matching function for call to 'Decide::Decide(&lt;brace-enclosed initializer list&gt;)' 17:53: note: candidates are: 9:5: note: Decide::Decide(DecisionFn) 9:5: note: no known conversion for argument 1 from 'main()::&lt;lambda()&gt;' to 'DecisionFn {aka bool (*)()}' 6:7: note: constexpr Decide::Decide(const Decide&amp;) 6:7: note: no known conversion for argument 1 from 'main()::&lt;lambda()&gt;' to 'const Decide&amp;' 6:7: note: constexpr Decide::Decide(Decide&amp;&amp;) 6:7: note: no known conversion for argument 1 from 'main()::&lt;lambda()&gt;' to 'Decide&amp;&amp;' </code></pre> <p>That's one heck of an error message to digest, but I think what I'm getting out of it is that the lambda cannot be treated as a <code>constexpr</code> so therefore I cannot pass it as a function pointer? I've tried making <code>x</code> constexpr as well, but that doesn't seem to help.</p>
28,746,827
10
4
null
2015-02-26 15:45:23.263 UTC
86
2022-07-31 12:58:34.363 UTC
2021-12-28 18:12:36.537 UTC
null
2,296,458
null
2,296,458
null
1
301
c++|c++11|lambda|function-pointers
226,254
<p>A lambda can only be converted to a function pointer if it does not capture, from the <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf" rel="noreferrer">draft C++11 standard</a> section <code>5.1.2</code> <em>[expr.prim.lambda]</em> says (<em>emphasis mine</em>):</p> <blockquote> <p>The closure type for a lambda-expression <strong>with no lambda-capture</strong> has a public non-virtual non-explicit const <strong>conversion function to pointer to function</strong> having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator.</p> </blockquote> <p>Note, cppreference also covers this in their section on <a href="http://en.cppreference.com/w/cpp/language/lambda" rel="noreferrer">Lambda functions</a>.</p> <p>So the following alternatives would work:</p> <pre><code>typedef bool(*DecisionFn)(int); Decide greaterThanThree{ []( int x ){ return x &gt; 3; } }; </code></pre> <p>and so would this:</p> <pre><code>typedef bool(*DecisionFn)(); Decide greaterThanThree{ [](){ return true ; } }; </code></pre> <p>and as <a href="https://stackoverflow.com/a/28747100/1708801">5gon12eder</a> points out, you can also use <a href="http://en.cppreference.com/w/cpp/utility/functional/function" rel="noreferrer"><code>std::function</code></a>, but note that <a href="https://stackoverflow.com/a/9054802/1708801"><code>std::function</code> is heavy weight</a>, so it is not a cost-less trade-off.</p>
9,050,763
Format date in jQuery
<pre><code>var date = "Fri Jan 29 2012 06:12:00 GMT+0100"; </code></pre> <p>How can i show this in format <strong>2012-01-29 06:12</strong> ? In PHP is function ->format. In Javascript is also format, but if i try use this then i have error:</p> <p><strong>now.format is not a function</strong></p> <pre><code>var now = new Date(); console.log(now.format("isoDateTime")); </code></pre> <p><a href="http://jsfiddle.net/6v9hD/" rel="noreferrer">http://jsfiddle.net/6v9hD/</a></p> <p>I would like receive format: <strong>2012-01-29 06:12</strong></p>
9,050,848
6
2
null
2012-01-29 03:49:40.71 UTC
2
2017-04-14 20:41:23.577 UTC
null
null
null
null
1,118,206
null
1
10
javascript|jquery|datetime
89,335
<p>This question is a duplicate (see: <a href="https://stackoverflow.com/questions/8398897/how-to-get-current-date-in-jquery">How to get current date in jquery?</a>).</p> <p>By modifying <a href="https://stackoverflow.com/a/8398929/548696">my solution</a> from the other question, I got:</p> <pre><code>var d = new Date(); var month = d.getMonth()+1; var day = d.getDate(); var hour = d.getHours(); var minute = d.getMinutes(); var second = d.getSeconds(); var output = d.getFullYear() + '-' + ((''+month).length&lt;2 ? '0' : '') + month + '-' + ((''+day).length&lt;2 ? '0' : '') + day + ' ' + ((''+hour).length&lt;2 ? '0' :'') + hour + ':' + ((''+minute).length&lt;2 ? '0' :'') + minute + ':' + ((''+second).length&lt;2 ? '0' :'') + second; </code></pre> <p>See this jsfiddle for a proof: <a href="http://jsfiddle.net/nCE9u/3/" rel="nofollow noreferrer">http://jsfiddle.net/nCE9u/3/</a></p> <p>You can also enclose it within function (demo is here: <a href="http://jsfiddle.net/nCE9u/4/" rel="nofollow noreferrer">http://jsfiddle.net/nCE9u/4/</a>):</p> <pre><code>function getISODateTime(d){ // padding function var s = function(a,b){return(1e15+a+"").slice(-b)}; // default date parameter if (typeof d === 'undefined'){ d = new Date(); }; // return ISO datetime return d.getFullYear() + '-' + s(d.getMonth()+1,2) + '-' + s(d.getDate(),2) + ' ' + s(d.getHours(),2) + ':' + s(d.getMinutes(),2) + ':' + s(d.getSeconds(),2); } </code></pre> <p>and use it like that:</p> <pre><code>getISODateTime(new Date()); </code></pre> <p>or:</p> <pre><code>getISODateTime(some_other_date); </code></pre> <p><strong>EDIT:</strong> I have added some improvement to the function, as proposed by Ates Goral (also decreased its readability in favour of code comments).</p>
9,257,094
How to change a string into uppercase
<p>I have problem in changing a string into uppercase with Python. In my research, I got <code>string.ascii_uppercase</code> but it doesn't work.</p> <p>The following code:</p> <pre><code> &gt;&gt;s = 'sdsd' &gt;&gt;s.ascii_uppercase </code></pre> <p>Gives this error message:</p> <pre><code>Traceback (most recent call last): File "&lt;console&gt;", line 1, in &lt;module&gt; AttributeError: 'str' object has no attribute 'ascii_uppercase' </code></pre> <p>My question is: <strong>how can I convert a string into uppercase in Python?</strong></p>
9,257,122
7
2
null
2012-02-13 07:48:56.727 UTC
65
2022-02-28 10:26:39.257 UTC
2013-03-13 11:01:19.3 UTC
null
448,144
null
1,038,815
null
1
798
python|string|uppercase
1,284,709
<p>Use <a href="https://docs.python.org/3/library/stdtypes.html#str.upper" rel="noreferrer"><code>str.upper()</code></a>:</p> <pre><code>&gt;&gt;&gt; s = 'sdsd' &gt;&gt;&gt; s.upper() 'SDSD' </code></pre> <p>See <a href="https://docs.python.org/3/library/stdtypes.html#string-methods" rel="noreferrer">String Methods</a>.</p>
16,553,326
Dynamically load google fonts after page has loaded
<p>I would like to be able to have the user select which font they would like the page to be displayed in. <a href="https://developers.google.com/fonts/docs/webfont_loader" rel="noreferrer">Here</a> is the way that Google recommends you do it using JavaScript. </p> <pre><code>WebFontConfig = { google: { families: ['Tangerine', 'Cantarell'] } }; (function() { var wf = document.createElement('script'); wf.src = ('https:' == document.location.protocol ? 'https' : 'http') + '://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js'; wf.type = 'text/javascript'; wf.async = 'true'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(wf, s); })(); </code></pre> <p>How can I modify this so that I can re-get fonts after the page has loaded?</p>
16,553,688
3
0
null
2013-05-14 21:41:32.48 UTC
6
2022-03-21 04:10:26.087 UTC
2015-08-28 22:58:51.547 UTC
null
759,866
null
207,795
null
1
29
javascript|jquery|css|font-face|google-font-api
25,456
<p>Check out the WebFont.load command in this github repo:</p> <p><a href="https://github.com/typekit/webfontloader" rel="noreferrer">https://github.com/typekit/webfontloader</a></p> <p>You can load whatever font you want dynamically:</p> <pre><code> &lt;script src="http://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js"&gt;&lt;/script&gt; &lt;script&gt; WebFont.load({ google: { families: ['Droid Sans', 'Droid Serif'] } }); &lt;/script&gt; </code></pre>
16,465,313
How yield catches StopIteration exception?
<p>Why in the example function terminates:</p> <pre><code>def func(iterable): while True: val = next(iterable) yield val </code></pre> <p>but if I take off yield statement function will raise StopIteration exception?</p> <p><strong>EDIT:</strong> Sorry for misleading you guys. I know what generators are and how to use them. Of course when I said function terminates I didn't mean eager evaluation of function. I just implied that when I use function to produce generator:</p> <pre><code>gen = func(iterable) </code></pre> <p>in case of <em>func</em> it works and returns the same generator, but in case of func2:</p> <pre><code>def func2(iterable): while True: val = next(iterable) </code></pre> <p>it raises StopIteration instead of <em>None</em> return or infinite loop.</p> <p>Let me be more specific. There is a function <em><a href="http://docs.python.org/2/library/itertools.html#itertools.tee" rel="noreferrer">tee</a></em> in <strong>itertools</strong> which is equivalent to:</p> <pre><code>def tee(iterable, n=2): it = iter(iterable) deques = [collections.deque() for i in range(n)] def gen(mydeque): while True: if not mydeque: # when the local deque is empty newval = next(it) # fetch a new value and for d in deques: # load it to all the deques d.append(newval) yield mydeque.popleft() return tuple(gen(d) for d in deques) </code></pre> <p>There is, in fact, some magic, because nested function <em>gen</em> has infinite loop without break statements. <em>gen</em> function terminates due to <em>StopIteration</em> exception when there is no items in <em>it</em>. But it terminates correctly (without raising exceptions), i.e. just stops loop. <strong>So the question is</strong>: where is <em>StopIteration</em> is handled?</p>
16,473,009
5
1
null
2013-05-09 15:20:31.447 UTC
12
2021-09-30 04:41:15.54 UTC
2014-11-23 10:29:47.033 UTC
null
2,213,647
null
2,069,858
null
1
43
python|yield|stopiteration
74,474
<p><strong>Note: This question (and the original part of my answer to it) are only really meaningful for Python versions prior to 3.7. The behavior that was asked about no longer happens in 3.7 and later, thanks to changes described in <a href="https://www.python.org/dev/peps/pep-0479/" rel="nofollow noreferrer">PEP 479</a>. So this question and the original answer are only really useful as historical artifacts. After the PEP was accepted, I added an additional section at the bottom of the answer which is more relevant to modern versions of Python.</strong></p> <hr /> <p>To answer your question about where the <code>StopIteration</code> gets caught in the <code>gen</code> generator created inside of <code>itertools.tee</code>: it doesn't. It is up to the consumer of the <code>tee</code> results to catch the exception as they iterate.</p> <p>First off, it's important to note that a generator function (which is any function with a <code>yield</code> statement in it, anywhere) is fundamentally different than a normal function. Instead of running the function's code when it is called, instead, you'll just get a <code>generator</code> object when you call the function. Only when you iterate over the generator will you run the code.</p> <p>A generator function will never finish iterating without raising <code>StopIteration</code> (unless it raises some other exception instead). <code>StopIteration</code> is the signal from the generator that it is done, and it is not optional. If you reach a <code>return</code> statement or the end of the generator function's code without raising anything, Python will raise <code>StopIteration</code> for you!</p> <p>This is different from regular functions, which return <code>None</code> if they reach the end without returning anything else. It ties in with the different ways that generators work, as I described above.</p> <p>Here's an example generator function that will make it easy to see how <code>StopIteration</code> gets raised:</p> <pre><code>def simple_generator(): yield &quot;foo&quot; yield &quot;bar&quot; # StopIteration will be raised here automatically </code></pre> <p>Here's what happens when you consume it:</p> <pre><code>&gt;&gt;&gt; g = simple_generator() &gt;&gt;&gt; next(g) 'foo' &gt;&gt;&gt; next(g) 'bar' &gt;&gt;&gt; next(g) Traceback (most recent call last): File &quot;&lt;pyshell#6&gt;&quot;, line 1, in &lt;module&gt; next(g) StopIteration </code></pre> <p>Calling <code>simple_generator</code> always returns a <code>generator</code> object immediately (without running any of the code in the function). Each call of <code>next</code> on the generator object runs the code until the next <code>yield</code> statement, and returns the yielded value. If there is no more to get, <code>StopIteration</code> is raised.</p> <p>Now, normally you don't see <code>StopIteration</code> exceptions. The reason for this is that you usually consume generators inside <code>for</code> loops. A <code>for</code> statement will automatically call <code>next</code> over and over until <code>StopIteration</code> gets raised. It will catch and suppress the <code>StopIteration</code> exception for you, so you don't need to mess around with <code>try</code>/<code>except</code> blocks to deal with it.</p> <p>A <code>for</code> loop like <code>for item in iterable: do_suff(item)</code> is almost exactly equivalent to this <code>while</code> loop (the only difference being that a real <code>for</code> doesn't need a temporary variable to hold the iterator):</p> <pre><code>iterator = iter(iterable) try: while True: item = next(iterator) do_stuff(item) except StopIteration: pass finally: del iterator </code></pre> <p>The <code>gen</code> generator function you showed at the top is one exception. It uses the <code>StopIteration</code> exception produced by the iterator it is consuming as it's own signal that it is done being iterated on. That is, rather than catching the <code>StopIteration</code> and then breaking out of the loop, it simply lets the exception go uncaught (presumably to be caught by some higher level code).</p> <p>Unrelated to the main question, there is one other thing I want to point out. In your code, you're calling <code>next</code> on an variable called <code>iterable</code>. If you take that name as documentation for what type of object you will get, this is not necessarily safe.</p> <p><code>next</code> is part of the <code>iterator</code> protocol, not the <code>iterable</code> (or <code>container</code>) protocol. It may work for some kinds of iterables (such as files and generators, as those types are their own iterators), but it will fail for others iterables, such as tuples and lists. The more correct approach is to call <code>iter</code> on your <code>iterable</code> value, then call <code>next</code> on the iterator you receive. (Or just use <code>for</code> loops, which call both <code>iter</code> and <code>next</code> for you at appropriate times!)</p> <hr /> <p><strong>I just found my own answer in a Google search for a related question, and I feel I should update to point out that the answer above is not true in modern Python versions.</strong></p> <p><a href="https://www.python.org/dev/peps/pep-0479/" rel="nofollow noreferrer">PEP 479</a> has made it an error to allow a <code>StopIteration</code> to bubble up uncaught from a generator function. If that happens, Python will turn it into a <code>RuntimeError</code> exception instead. This means that code like the examples in older versions of <code>itertools</code> that used a <code>StopIteration</code> to break out of a generator function needs to be modified. Usually you'll need to catch the exception with a <code>try</code>/<code>except</code> and then <code>return</code>.</p> <p>Because this was a backwards incompatible change, it was phased in gradually. In Python 3.5, all code worked as before by default, but you could get the new behavior with <code>from __future__ import generator_stop</code>. In Python 3.6, unmodified code would still work, but it would give a warning. In Python 3.7 and later, the new behavior applies all the time.</p>
16,084,474
Convert time value to format “hh:mm Am/Pm” using Android
<p>I am getting date value from database like "2013-02-27 06:06:30" using StringTokenizer I will get time separately like below </p> <pre><code>String startTime = "2013-02-27 06:06:30"; StringTokenizer token = new StringTokenizer(startTime); String date1 = token.nextToken(); String time1 = token.nextToken(); </code></pre> <p>and in time1 I am getting the result 06:06:30,</p> <p>Can I re-store it in another variable of type String as follows?</p> <pre><code>String displayValue = "06:06 AM"; </code></pre> <p>And if time1 variable has the value of</p> <pre><code>String time = 16:00:00; </code></pre> <p>then it should be converted to:</p> <pre><code>String displayValue = "04:00 PM"; </code></pre>
16,099,240
10
0
null
2013-04-18 13:35:04.697 UTC
5
2019-09-05 19:48:17.957 UTC
2018-10-03 15:12:31.29 UTC
null
1,396,042
null
1,396,042
null
1
48
android|stringtokenizer|android-date
115,265
<p>I got answer just doing like this.</p> <pre><code>startTime = "2013-02-27 21:06:30"; StringTokenizer tk = new StringTokenizer(startTime); String date = tk.nextToken(); String time = tk.nextToken(); SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss"); SimpleDateFormat sdfs = new SimpleDateFormat("hh:mm a"); Date dt; try { dt = sdf.parse(time); System.out.println("Time Display: " + sdfs.format(dt)); // &lt;-- I got result here } catch (ParseException e) { e.printStackTrace(); } </code></pre>
16,186,474
Java casting in interfaces
<p>Can someone please explain to me how the compiler does not complain in the first casting, but does complain in the second?</p> <pre><code>interface I1 { } interface I2 { } class C1 implements I1 { } class C2 implements I2 { } public class Test{ public static void main(String[] args){ C1 o1 = new C1(); C2 o2 = new C2(); Integer o3 = new Integer(4); I2 x = (I2)o1; //compiler does not complain I2 y = (I2)o3; //compiler complains here !! } } </code></pre>
16,186,588
4
7
null
2013-04-24 07:54:54.847 UTC
16
2021-01-17 13:44:01.047 UTC
2021-01-17 13:44:01.047 UTC
null
7,873,018
null
711,189
null
1
80
java|interface|casting
33,127
<p>When you cast <code>o1</code> and <code>o3</code> with <code>(I2)</code>, you tell the compiler that the class of the object is actually a subclass of its declared type, and that this subclass implements <code>I2</code>.</p> <p>The <code>Integer</code> class is <strong>final</strong>, so <code>o3</code> cannot be an instance of a subclass of <code>Integer</code>: the compiler knows that you're lying. <code>C1</code> however is not final, so <code>o1</code> <em>could</em> be an instance of a subtype of <code>C1</code> that implements <code>I2</code>.</p> <p>If you make <code>C1</code> final, the compiler will complain too:</p> <pre><code>interface I1 { } interface I2 { } final class C1 implements I1 { } class C2 implements I2 { } public class Test{ public static void main(){ C1 o1 = new C1(); C2 o2 = new C2(); Integer o3 = new Integer(4); I2 y = (I2)o3; //compiler complains here !! I2 x = (I2)o1; //compiler complains too } } </code></pre>
13,158,387
ERROR New missing/unsatisfied dependencies: (Cannot configure datasource)
<p>I have a web app using JSF(Primefaces), JPA(Hibernate) and EJBs and have trouble to configure the data source on JBoss . I am getting the following error:</p> <pre><code>2012/10/31 07:20:17,948 INFO [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) JBAS010404: Deploying non-JDBC-compliant driver class com.mysql.jdbc.Driver (version 5.1) 2012/10/31 07:20:18,836 INFO [org.jboss.as.server] (DeploymentScanner-threads - 2) JBAS015870: Deploy of deployment "ROOT.war" was rolled back with failure message {"JBAS014771: Services with missing/unavailable dependencies" =&gt; ["jboss.persistenceunit.\"ROOT.war#test\"jboss.naming.context.java.jboss.datasources.MysqlDSMissing[jboss.persistenceunit.\"ROOT.war#test\"jboss.naming.context.java.jboss.datasources.MysqlDS]"]} 2012/10/31 07:20:19,252 INFO [org.jboss.as.server.deployment] (MSC service thread 1-2) JBAS015877: Stopped deployment ROOT.war in 413ms 2012/10/31 07:20:19,255 INFO [org.jboss.as.controller] (DeploymentScanner-threads - 2) JBAS014774: Service status report JBAS014775: New missing/unsatisfied dependencies: service jboss.naming.context.java.jboss.datasources.MysqlDS (missing) dependents: [service jboss.persistenceunit."ROOT.war#test"] 2012/10/31 07:20:19,334 ERROR [org.jboss.as.server.deployment.scanner] (DeploymentScanner-threads - 1) {"JBAS014653: Composite operation failed and was rolled back. Steps that failed:" =&gt; {"Operation step-2" =&gt; {"JBAS014771: Services with missing/unavailable dependencies" =&gt; ["jboss.persistenceunit.\"ROOT.war#test\"jboss.naming.context.java.jboss.datasources.MysqlDSMissing[jboss.persistenceunit.\"ROOT.war#test\"jboss.naming.context.java.jboss.datasources.MysqlDS]"]}}} </code></pre> <p>Below you can see my <code>persistence.xml</code>, <code>stanadlone.xml</code> and <code>pom.xml</code>. <strong>Am I missing some dependency in the pom.xml?</strong></p> <p>Persistence.xml</p> <p></p> <p></p> <pre><code> &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt; &lt;jta-data-source&gt;java:jboss/datasources/MysqlDS&lt;/jta-data-source&gt; &lt;properties&gt; &lt;property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/&gt; &lt;property name="hibernate.show_sql" value="true"/&gt; &lt;property name="hibernate.max_fetch_depth" value="3"/&gt; &lt;property name="hibernate.hbm2ddl.auto" value="update" /&gt; &lt;/properties&gt; </code></pre> <p></p> <p></p> <p>Standalone.xml</p> <pre><code>&lt;datasources&gt; &lt;datasource jndi-name="java:jboss/datasources/ExampleDS" enabled="true" use-java-context="true" pool-name="H2DS"&gt; &lt;connection-url&gt;jdbc:h2:${jboss.server.data.dir}/test;DB_CLOSE_DELAY=-1&lt;/connection-url&gt; &lt;driver&gt;h2&lt;/driver&gt; &lt;security&gt; &lt;user-name&gt;sa&lt;/user-name&gt; &lt;password&gt;sa&lt;/password&gt; &lt;/security&gt; &lt;/datasource&gt; &lt;datasource jndi-name="java:jboss/datasources/MysqlDS" enabled="${mysql.enabled}" use-java-context="true" pool-name="MysqlDS"&gt; &lt;connection-url&gt;jdbc:mysql://127.5.54.1:3306/researchprojects&lt;/connection-url&gt; &lt;driver&gt;mysql&lt;/driver&gt; &lt;security&gt; &lt;user-name&gt;admin&lt;/user-name&gt; &lt;password&gt;*******&lt;/password&gt; &lt;/security&gt; &lt;validation&gt; &lt;check-valid-connection-sql&gt;SELECT 1&lt;/check-valid-connection-sql&gt; &lt;/validation&gt; &lt;/datasource&gt; &lt;datasource jndi-name="java:jboss/datasources/PostgreSQLDS" enabled="${postgresql.enabled}" use-java-context="true" pool-name="PostgreSQLDS" use-ccm="true"&gt; &lt;connection-url&gt;jdbc:postgresql://${env.OPENSHIFT_DB_HOST}:${env.OPENSHIFT_DB_PORT}/${env.OPENSHIFT_APP_NAME}&lt;/connection-url&gt; &lt;driver&gt;postgresql&lt;/driver&gt; &lt;security&gt; &lt;user-name&gt;${env.OPENSHIFT_DB_USERNAME}&lt;/user-name&gt; &lt;password&gt;${env.OPENSHIFT_DB_PASSWORD}&lt;/password&gt; &lt;/security&gt; &lt;validation&gt; &lt;check-valid-connection-sql&gt;SELECT 1&lt;/check-valid-connection-sql&gt; &lt;/validation&gt; &lt;/datasource&gt; &lt;drivers&gt; &lt;driver name="h2" module="com.h2database.h2"&gt; &lt;xa-datasource-class&gt;org.h2.jdbcx.JdbcDataSource&lt;/xa-datasource-class&gt; &lt;/driver&gt; &lt;driver name="mysql" module="com.mysql.jdbc"&gt; &lt;xa-datasource-class&gt;com.mysql.jdbc.jdbc2.optional.MysqlXADataSource&lt;/xa-datasource-class&gt; &lt;/driver&gt; &lt;driver name="postgresql" module="org.postgresql.jdbc"&gt; &lt;xa-datasource-class&gt;org.postgresql.xa.PGXADataSource&lt;/xa-datasource-class&gt; &lt;/driver&gt; &lt;/drivers&gt; &lt;/datasources&gt; </code></pre> <p>Pom.xml</p> <pre><code> &lt;project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"&gt; &lt;modelVersion&gt;4.0.0&lt;/modelVersion&gt; &lt;groupId&gt;openshifttest&lt;/groupId&gt; &lt;artifactId&gt;openshifttest&lt;/artifactId&gt; &lt;packaging&gt;war&lt;/packaging&gt; &lt;version&gt;1.0&lt;/version&gt; &lt;name&gt;openshifttest&lt;/name&gt; &lt;repositories&gt; &lt;repository&gt; &lt;id&gt;scala&lt;/id&gt; &lt;name&gt;Scala Tools&lt;/name&gt; &lt;url&gt;http://scala-tools.org/repo-releases/&lt;/url&gt; &lt;releases&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;/releases&gt; &lt;snapshots&gt; &lt;enabled&gt;false&lt;/enabled&gt; &lt;/snapshots&gt; &lt;/repository&gt; &lt;repository&gt; &lt;id&gt;prime-repo&lt;/id&gt; &lt;name&gt;PrimeFaces Maven Repository&lt;/name&gt; &lt;url&gt;http://repository.primefaces.org&lt;/url&gt; &lt;layout&gt;default&lt;/layout&gt; &lt;/repository&gt; &lt;/repositories&gt; &lt;pluginRepositories&gt; &lt;pluginRepository&gt; &lt;id&gt;scala&lt;/id&gt; &lt;name&gt;Scala Tools&lt;/name&gt; &lt;url&gt;http://scala-tools.org/repo-releases/&lt;/url&gt; &lt;releases&gt; &lt;enabled&gt;true&lt;/enabled&gt; &lt;/releases&gt; &lt;snapshots&gt; &lt;enabled&gt;false&lt;/enabled&gt; &lt;/snapshots&gt; &lt;/pluginRepository&gt; &lt;/pluginRepositories&gt; &lt;properties&gt; &lt;project.build.sourceEncoding&gt;UTF-8&lt;/project.build.sourceEncoding&gt; &lt;maven.compiler.source&gt;1.6&lt;/maven.compiler.source&gt; &lt;maven.compiler.target&gt;1.6&lt;/maven.compiler.target&gt; &lt;/properties&gt; &lt;dependencies&gt; &lt;dependency&gt; &lt;groupId&gt;org.jboss.spec&lt;/groupId&gt; &lt;artifactId&gt;jboss-javaee-6.0&lt;/artifactId&gt; &lt;version&gt;1.0.0.Final&lt;/version&gt; &lt;type&gt;pom&lt;/type&gt; &lt;scope&gt;provided&lt;/scope&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.scala-lang&lt;/groupId&gt; &lt;artifactId&gt;scala-library&lt;/artifactId&gt; &lt;version&gt;2.7.2&lt;/version&gt; &lt;/dependency&gt; &lt;dependency&gt; &lt;groupId&gt;org.primefaces&lt;/groupId&gt; &lt;artifactId&gt;primefaces&lt;/artifactId&gt; &lt;version&gt;3.4.1&lt;/version&gt; &lt;/dependency&gt; &lt;/dependencies&gt; &lt;profiles&gt; &lt;profile&gt; &lt;!-- When built in OpenShift the 'openshift' profile will be used when invoking mvn. --&gt; &lt;!-- Use this profile for any OpenShift specific customization your app will need. --&gt; &lt;!-- By default that is to put the resulting archive into the 'deployments' folder. --&gt; &lt;!-- http://maven.apache.org/guides/mini/guide-building-for-different-environments.html --&gt; &lt;id&gt;openshift&lt;/id&gt; &lt;build&gt; &lt;finalName&gt;openshifttest&lt;/finalName&gt; &lt;plugins&gt; &lt;plugin&gt; &lt;artifactId&gt;maven-war-plugin&lt;/artifactId&gt; &lt;version&gt;2.1.1&lt;/version&gt; &lt;configuration&gt; &lt;outputDirectory&gt;deployments&lt;/outputDirectory&gt; &lt;warName&gt;ROOT&lt;/warName&gt; &lt;/configuration&gt; &lt;/plugin&gt; &lt;plugin&gt; &lt;groupId&gt;org.scala-tools&lt;/groupId&gt; &lt;artifactId&gt;maven-scala-plugin&lt;/artifactId&gt; &lt;executions&gt; &lt;execution&gt; &lt;id&gt;compile&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;compile&lt;/goal&gt; &lt;/goals&gt; &lt;phase&gt;compile&lt;/phase&gt; &lt;/execution&gt; &lt;execution&gt; &lt;id&gt;test-compile&lt;/id&gt; &lt;goals&gt; &lt;goal&gt;testCompile&lt;/goal&gt; &lt;/goals&gt; &lt;phase&gt;test-compile&lt;/phase&gt; &lt;/execution&gt; &lt;execution&gt; &lt;phase&gt;process-resources&lt;/phase&gt; &lt;goals&gt; &lt;goal&gt;compile&lt;/goal&gt; &lt;/goals&gt; &lt;/execution&gt; &lt;/executions&gt; &lt;/plugin&gt; &lt;/plugins&gt; &lt;/build&gt; &lt;/profile&gt; &lt;/profiles&gt; &lt;/project&gt; </code></pre> <p><strong>Could someone tell me what am I doing wrong ?</strong> </p>
13,187,657
8
0
null
2012-10-31 12:51:12.51 UTC
null
2016-12-20 07:48:11.293 UTC
2013-09-25 04:14:33.277 UTC
null
1,544,069
null
525,894
null
1
3
jpa|jboss|jboss7.x
54,850
<p>did you enable mysql datasource? as by default it is disabled.</p> <p>part of configuration </p> <pre><code>&lt;datasource jndi-name="java:jboss/datasources/MysqlDS" enabled="${mysql.enabled}" use-java-context="true" pool-name="MysqlDS"&gt; </code></pre> <p>has flag ${mysql.enabled} that is system property that enables the data source in case it is mysql is enabled.</p> <p>take a look at the guide <a href="http://jaitechwriteups.blogspot.com/2011/08/deploy-java-ee-application-on-openshift.html" rel="nofollow">http://jaitechwriteups.blogspot.com/2011/08/deploy-java-ee-application-on-openshift.html</a></p> <p>and search for "Using the MySQL database available in OpenShift Express" chapter</p> <p>that shows you what part of configuration you are missing.</p>
29,020,935
Using Toolbar with Fragments
<p>I am trying to create a viewpager that swipes through 3 different fragments each with a different toolbar. I have implemented the new toolbar in an activity before and got it to work however I am trying to get it to work with fragments</p> <p>Here is the fragment code</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout resource that'll be returned View rootView = inflater.inflate(R.layout.fragment_home, container, false); mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar_home); if (mToolbar != null) { setSupportActionBar(mToolbar); } mToolbar.setTitle(null); return rootView; } </code></pre> <p>I am extending my fragment with <code>Fragment</code>, however I am getting the error</p> <pre><code>Cannot resolve method setSupportActionBar </code></pre> <p>I am not sure how to resolve this, if I remove the <code>setSupportActionBar</code> code will it stop working with certain devices?</p>
29,021,287
6
4
null
2015-03-12 21:52:13.597 UTC
25
2021-07-06 11:13:07.243 UTC
2019-06-26 12:19:23.61 UTC
null
1,000,551
null
1,136,379
null
1
46
java|android|android-fragments|android-viewpager|android-toolbar
104,688
<p><a href="http://developer.android.com/reference/android/support/v4/app/Fragment.html" rel="noreferrer">Fragments</a> don't have such method <code>setSupportActionBar()</code>. ActionBar is a property of Activity, so to set your toolbar as the actionBar, your activity should extend from ActionBarActivity and then you can call in your Fragment:</p> <pre><code> ((ActionBarActivity)getActivity()).setSupportActionBar(mToolbar); </code></pre> <p><strong>UPDATE</strong></p> <p>If you're using <a href="https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html" rel="noreferrer">AppCompatActivity</a> :</p> <pre><code> ((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar); </code></pre>
29,307,370
How to transition smoothly from translucent to opaque UINavigationBar iOS?
<p>I'm running into problems reconfiguring the <code>UINavigationBar</code> on iOS 7 and 8 when transitioning between views.</p> <p>My application currently contains the following <code>UIViewController</code> flow:</p> <p>VC1 --> VC2 --> VC3</p> <p>In this flow</p> <ul> <li>VC1 is the home screen and has an <strong>opaque</strong> <code>UINavigationBar</code></li> <li>VC2 has a <strong>translucent</strong> <code>UINavigationBar</code></li> <li>VC3 goes back to having an <strong>opaque</strong> <code>UINavigationBar</code></li> </ul> <p>The problem I've been running into is that the transitions between these views are all very sloppy looking. To start with I tried the following:</p> <p>in VC2</p> <pre><code>- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // configure appearance [self.navigationController.navigationBar configureTranslucentAppearance]; } </code></pre> <p>And in VC1 and VC3</p> <pre><code>- (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // configure appearance [self.navigationController.navigationBar restoreDefaultAppearance]; } </code></pre> <p>Here are the implementations of the two helper functions listed above:</p> <pre><code>- (void)restoreDefaultAppearance { [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; [self setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor JTTextNavBar]}]; [self setTintColor:[UIColor JTTextNavBar]]; [self setBarTintColor:[UIColor JTBackgroundNavBarWithAlpha:1.0]]; [self setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault]; [self setBackgroundColor:[UIColor JTBackgroundNavBarWithAlpha:1.0]]; [self setShadowImage:[UIImage navigationBarShadowImage]]; [self setTranslucent:NO]; } - (void)configureTranslucentAppearance { [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; [self setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; [self setBackgroundColor:[UIColor clearColor]]; [self setShadowImage:[UIImage new]]; [self setTranslucent:YES]; } </code></pre> <p>This is the most basic way of handling this transition. It has the following visual artefacts:</p> <ul> <li>When going from VC1 --> VC2 the moment you begin the transition the navigation bar turns black. The animation completes normally <img src="https://i.stack.imgur.com/U5dla.png" alt="enter image description here"></li> <li>When going from VC2 --> VC1 the nav bar instantly changes to the application default colour before the segue has time to complete. <img src="https://i.stack.imgur.com/o9WDf.png" alt="enter image description here"></li> <li>When going from VC2 --> VC3 the navigation bar instantly goes from translucent to the app nav bar color and then menu items and VC body animate in. <img src="https://i.stack.imgur.com/OCeat.png" alt="enter image description here"></li> <li>When going from VC3 --> VC2 the nav bar instantly turns black and remains this way until the segue is complete. <img src="https://i.stack.imgur.com/QqgDN.png" alt="enter image description here"></li> </ul> <p>None of these transitions look good at all. Ideally I would like the views to transition smoothly along with their new <code>UINavigationBar</code> but the only way I've seen to do this successfully is to manually add a toolbar to each xib.</p> <p>Any suggestions? Apologies if this description is confusing :(</p> <p><strong>Edit:</strong> Added cropped images of the <code>UINavigationBar</code> and top portion of <code>UIViewController</code> for each of the listed transitions.</p>
30,244,238
11
5
null
2015-03-27 18:06:50.987 UTC
18
2020-12-29 21:13:54.79 UTC
2015-03-27 20:31:36.41 UTC
null
740,474
null
740,474
null
1
31
ios|objective-c|uinavigationbar
12,092
<p>I finally found a decent solution!</p> <p>There doesn't appear to be a proper way to smoothly transition from an opaque to transparent <code>UINavigationBar</code> BUT you can transition smoothly from a view controller with a visible status bar to one that has a hidden status bar.</p> <p>This opens up a possible workaround which is to add the following in the <code>viewWillAppear</code> of <strong>VC2</strong> from above:</p> <pre><code>[self.navigationController setNavigationBarHidden:YES animated:YES]; </code></pre> <p>Once you have that, manually add a <code>UINavigationBar</code> to your xib and configure it to be transparent (and add all necessary <code>UIBarButtonItem</code> and views).</p> <p>If everything is hooked up properly transitioning from <strong>VC1</strong> to <strong>VC2</strong> will hide the <code>UINavigationBar</code> at the same speed as the view transition and <strong>VC2</strong> will show up with it's embedded <code>UINavigationBar</code></p> <p><strong>Note:</strong> To make this work properly you'll have to make sure that in the <code>viewWillAppear</code> of View Controllers that can be accessed from <strong>VC2</strong> you reset the <code>UINavigationBar</code> to be visible (if necessary) via:</p> <pre><code>[self.navigationController setNavigationBarHidden:NO animated:YES]; </code></pre> <hr/> <p><strong>TL;DR</strong> - manually add a <code>UINavigationBar</code> to your transparent nav bar view controller and in its <code>viewWillAppear</code> hide the default one via <code>setNavigationBarHidden:animated:</code></p>
17,236,358
How is it possible to know what's spotify is playing from an external Android app?
<p>I just found out this settings option in Spotify for Android settings screen: </p> <blockquote> <p>"Device broadcast status - allow other apps on your device to see what you are listening to"</p> </blockquote> <p>I guess that means any other app can access what's being played via Spotify. How can this be implemented? Is there any documentation around?</p> <p>Thanks</p>
22,195,867
2
3
null
2013-06-21 13:22:22.6 UTC
11
2014-03-08 21:05:26.637 UTC
null
null
null
null
334,209
null
1
11
android|spotify
11,802
<p>Spotify has the following intent-actions:</p> <p>metadatachanged, playbackstatechanged, and queuechanged.</p> <p><strong>queuechanged</strong> contains no extra data. <br> <strong>playbackstatechanged</strong> has a boolean value for "playing", and a value for playbackPosition.<br> <strong>metadatachanged</strong> contains artist, album, track, length, and id values.<br></p> <p>You can get Artist, Track, and Album names when the track is changed (manually or automatically) by using <strong>com.spotify.mobile.android.metadatachanged</strong></p> <p>If Spotify is paused and started again, only playbackstatechanged is broadcast. </p>
17,209,975
Facebook open graph GraphMethodException error code 100
<p>I'm trying to work my way through the Facebook tutorial publish and open graph story for iOS, <a href="https://developers.facebook.com/docs/tutorials/ios-sdk-tutorial/publish-open-graph-story/">https://developers.facebook.com/docs/tutorials/ios-sdk-tutorial/publish-open-graph-story/</a></p> <p>Step 3 is failing for me. When I use the graph API explorer I get the error </p> <pre><code>{ "error": { "message": "Unsupported post request.", "type": "GraphMethodException", "code": 100 } } </code></pre> <p>I've looked through a bunch of answers on stack overflow relating to this error but none seem to be my problem. I have selected get access token and have publish permissions. The page is not alcohol related and the user page I'm using is not age restricted.</p> <p>I have selected my application from the top of the page. I have selected post and then entered my story object in the space provided me/gopiratestd:boss</p> <p>then I add a new field and use the key beat on the left and then the following url on the right. <a href="https://hidden-castle-7245.herokuapp.com/opengraphobject.php?fb:app_id=554329451276476&amp;og:type=gopiratestd:boss&amp;og:title=">https://hidden-castle-7245.herokuapp.com/opengraphobject.php?fb:app_id=554329451276476&amp;og:type=gopiratestd:boss&amp;og:title=</a> beataboss&amp;og:description=%22Beat%22&amp;og:image=<a href="http://images.all-free-download.com/images/graphicmedium/beautiful_cat_picture_6_168770.jpg&amp;body=Beat">http://images.all-free-download.com/images/graphicmedium/beautiful_cat_picture_6_168770.jpg&amp;body=Beat</a></p> <p>Then when I hit submit it returns that error.</p> <p>Is there anything obvious I'm doing wrong here?</p> <p>When I use that link in the object debugger it doesn't return any errors.</p>
17,211,685
5
0
null
2013-06-20 09:22:39.593 UTC
3
2017-10-13 09:20:08.123 UTC
null
null
null
null
385,816
null
1
15
facebook|facebook-graph-api
59,734
<p>Error 100 means that there is a plain syntax error in the URL you are posting to.</p> <p>I suspect you have a custom graph url set which doesn't match your action - see <a href="http://developers.facebook.com/docs/opengraph/creating-action-types" rel="nofollow">http://developers.facebook.com/docs/opengraph/creating-action-types</a> :</p> <blockquote> <p><strong>Graph API URL</strong> This customizes the exact endpoint used when publishing actions, which by default for custom action types is /me/{app-namespace}:{action-type-name}.</p> </blockquote>
24,590,256
MySQL - SELECT then UPDATE
<p>I have a script written in PHP which has this line which is working correctly for selecting the data i need;</p> <pre><code>$result = mysql_query("SELECT product_name, sku, qty FROM supplier_dropship_items WHERE supplier_id = '3' AND status = '2'", $db_beb); </code></pre> <p>What I'm struggling with is a way to update the records I have selected, once selected I need to change the <code>status = '1'</code> so that the next time my script runs it won't pull the same data in the select and will only pull new items in the table which have status 2.</p> <p>This is my working result thanks to the comments of the accepted answer below;</p> <pre><code>$result = mysql_query("SELECT id, product_name, sku, qty FROM supplier_dropship_items WHERE supplier_id = '3' AND status = '2' FOR UPDATE", $db_beb); while($row = mysql_fetch_assoc($result)) { $sql_table_data[] = $row; mysql_query("UPDATE supplier_dropship_items SET status=1 WHERE id='".$row['id']."'", $db_beb); } </code></pre>
24,590,344
2
4
null
2014-07-05 20:19:37.293 UTC
6
2021-11-11 07:49:11.857 UTC
2014-07-05 20:52:55.113 UTC
null
1,375,874
null
1,375,874
null
1
17
mysql|select|sql-update
55,765
<p>If <code>supplier_dropship_items</code> has a primary key (it should), then include those fields in the <strong><code>SELECT</code></strong>, then, when you cycle through the results, execute an <strong><code>UPDATE</code></strong> using the primary key to set the <code>status</code>, as in:</p> <pre><code>UPDATE supplier_dropship_items SET status=1 WHERE &lt;id_field&gt;=&lt;id_value&gt;; </code></pre> <p>This assumes you are not executing in an concurrent environment. If you are, then you should lock the records for update, by using <strong><code>SELECT... FOR UPDATE</code></strong>. You can read about it <a href="http://dev.mysql.com/doc/refman/5.1/en/innodb-locking-reads.html" rel="noreferrer">here</a>. As far as I know, this works under MySQL on InnoDB tables.</p>
39,750,906
PHP setcookie "SameSite=Strict"?
<p>I recently read &quot;RFC 6265&quot; on the attribute &quot;Same Site&quot;, I looked at some articles that talked about that in April 2016, &quot;same-site&quot; attribute has been implemented for Chrome 51 and Opera 39 ...</p> <p>I wonder if current PHP supports creating cookies with this attribute?</p> <p>Reference:</p> <ul> <li><a href="https://www.chromestatus.com/feature/4672634709082112" rel="noreferrer">Feature documentation on Chrome’s <code>chromestatus.com</code></a></li> <li><a href="https://datatracker.ietf.org/doc/html/draft-west-first-party-cookies-07" rel="noreferrer">HTTPbis draft first adopted by Chrome</a></li> <li><a href="https://datatracker.ietf.org/doc/draft-ietf-httpbis-rfc6265bis/?include_text=1" rel="noreferrer">Latest HTTPbis draft</a></li> </ul>
46,971,326
10
10
null
2016-09-28 14:48:15.88 UTC
27
2022-08-17 09:24:05.92 UTC
2021-10-07 07:24:50.413 UTC
null
-1
null
4,093,960
null
1
91
php|security|cookies
122,251
<p>[<strong>Important update:</strong> As @caw pointed out below, this hack <a href="https://github.com/php/php-src/commit/5cb825df7251aeb28b297f071c35b227a3949f01" rel="noreferrer">WILL BREAK in PHP 7.3</a>. Stop using it now to save yourself from unpleasant surprises! Or at least wrap it in a PHP version check like <code>if (PHP_VERSION_ID &lt; 70300) { ... } else { ... }</code>.]</p> <p>It seems like you can abuse the "path" or "domain" parameter of PHP's "setcookie" function to sneak in the SameSite attribute because PHP does not escape semicolons:</p> <pre><code>setcookie('samesite-test', '1', 0, '/; samesite=strict'); </code></pre> <p>Then PHP sends the following HTTP header:</p> <blockquote> <p>Set-Cookie: samesite-test=1; path=/; samesite=strict</p> </blockquote> <p>I've just discovered this a few minutes ago, so please do your own testing! I'm using PHP 7.1.11.</p>
30,331,282
WebdriverWait is showing TimeoutException, if I use sleep.time it works ok
<p>I want to use WebdriverWait for when clicking elements in Python Webdriver.</p> <p>I get the following TimeoutException error when using WebdriverWait:</p> <pre><code>Traceback (most recent call last): File &quot;C:\Users\riaz.ladhani\PycharmProjects\Selenium Webdriver\ClearCore\TestCases\AdministrationPage_TestCase.py&quot;, line 30, in test_add_Project administration_page = login_page.clickAdministration() File &quot;C:\Users\riaz.ladhani\PycharmProjects\Selenium Webdriver\ClearCore\Pages\login.py&quot;, line 46, in clickAdministration WebDriverWait (self.driver, 10).until(lambda d: self.driver.find_element(*MainPageLocators.AdministrationButton_xpath).click()) File &quot;C:\Python27\lib\site-packages\selenium\webdriver\support\wait.py&quot;, line 75, in until raise TimeoutException(message, screen, stacktrace) TimeoutException: Message: </code></pre> <p>If I use <code>time.sleep(10)</code> it works ok and clicks the elements. I have reverted all my links to time.sleep for now until I can get <code>WebdriverWait</code> to work properly.</p> <p>My code snippet for WebdriverWait is:</p> <pre><code>class LoginPage(BasePage): #Click Administration from top menu def clickAdministration(self): WebDriverWait (self.driver, 10).until(lambda d: self.driver.find_element(*MainPageLocators.AdministrationButton_xpath).click()) #time.sleep(10) return AdministrationPage(self.driver) </code></pre> <p>The imports are:</p> <pre><code>from selenium.webdriver.support.ui import WebDriverWait from selenium.common.exceptions import TimeoutException class LoginPage_TestCase(unittest.TestCase): def test_add_Project(self): login_page = login.LoginPage(self.driver) login_page.userLogin_valid() administration_page = login_page.clickAdministration() </code></pre> <p>Is my <code>WebdriverWait</code> syntax correct? Why the TimeoutException?</p> <p>If I use <code>time.sleep(secs)</code>, it works fine but not the best efficient way to do it.</p>
30,331,643
2
2
null
2015-05-19 16:32:47.397 UTC
5
2021-01-04 17:20:32.773 UTC
2021-01-04 17:20:32.773 UTC
null
1,783,163
null
358,378
null
1
4
python|selenium|selenium-webdriver|webdriver
56,818
<p>You are not using the Explicit Wait correctly - you need to make use of Expected Conditions - callables that would be called repeatedly until return <code>True</code>. You are returning the result of <code>click()</code> method which returns <code>None</code> which is falsy - the expected condition never returns <code>True</code> and, hence, you are getting <code>TimeoutException</code>.</p> <p>In this case, built-in <a href="http://selenium-python.readthedocs.io/waits.html#explicit-waits" rel="noreferrer"><code>element_to_be_clickable</code></a> fits nicely, example:</p> <pre><code>from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By wait = WebDriverWait(self.driver, 10) element = wait.until(EC.element_to_be_clickable((By.XPATH, '//div[@class="test"]'))) element.click() </code></pre>
36,802,354
Print binary tree in a pretty way using c++
<p>I am a "bit" lost trying to print a binary tree like below in c++:</p> <pre><code> 8 / \ / \ / \ 5 10 / \ / \ 2 6 9 11 </code></pre> <p>I know how to get the height of the tree and the number of nodes in each level, but I couldn't figure out how to set the right number of spaces between the root and the second level (there are 3 lines under the root for 3 levels but I believe it is not this everytime,I thought it could be 3 times the height for greater trees). </p> <p>I would like to have some help to print these spaces in the rows and the number of lines between the rows.Thank you.</p> <p>I am coding in c++</p> <pre><code>Get height int tree::getHeight(No *node) { if (node == NULL) return 0; return 1 + max(getHeight(node-&gt;esq), getHeight(node-&gt;dir)); } Get number of nodes per line void tree::getLine(const No *root, int depth, vector&lt;int&gt;&amp; vals){ int placeholder = 10; if (depth &lt;= 0 &amp;&amp; root != nullptr) { vals.push_back(root-&gt;chave); return; } if (root-&gt;esq != nullptr) getLine(root-&gt;esq, depth-1, vals); else if (depth-1 &lt;= 0) vals.push_back(placeholder); if (root-&gt;dir != nullptr) getLine(root-&gt;dir, depth-1, vals); else if (depth-1 &lt;= 0) vals.push_back(placeholder); } </code></pre>
36,810,117
5
4
null
2016-04-22 20:00:12.377 UTC
13
2022-07-06 07:16:07.71 UTC
null
null
null
null
5,425,522
null
1
19
c++|binary-tree
46,863
<p>Here is an example of code creating a text-based representation of a binary tree. This demonstration uses a minimally useful binary tree class (BinTree), with a small footprint, just to avoid bloating the example's size.</p> <p>Its text-rendering member functions are more serious, using iteration rather than recursion, as found in other parts of the class.</p> <p>This does its job in three steps, first a vector of rows of string values is put together.</p> <p>Then this is used to format lines of text strings representing the tree.</p> <p>Then the strings are cleaned up and dumped to cout.</p> <p>As an added bonus, the demo includes a &quot;random tree&quot; feature, for hours of nonstop entertainment.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &lt;algorithm&gt; #include &lt;random&gt; using std::vector; using std::string; using std::cout; template &lt;typename T&gt; class BinTree { struct Node { T value; Node *left,*right; Node() : left(nullptr),right(nullptr) {} Node(const T&amp; value) :value(value),left(nullptr),right(nullptr) {} // stack-abusing recursion everywhere, for small code ~Node() { delete left; delete right; } int max_depth() const { const int left_depth = left ? left-&gt;max_depth() : 0; const int right_depth = right ? right-&gt;max_depth() : 0; return (left_depth &gt; right_depth ? left_depth : right_depth) + 1; } }; Node *root; public: BinTree() : root(nullptr) {} ~BinTree() { delete root; } int get_max_depth() const { return root ? root-&gt;max_depth() : 0; } void clear() { delete root; root = nullptr; } void insert() {} template &lt;typename ...Args&gt; void insert(const T&amp; value, Args...more) { if(!root) { root = new Node(value); } else { Node* p = root; for(;;) { if(value == p-&gt;value) return; Node* &amp;pchild = value &lt; p-&gt;value ? p-&gt;left : p-&gt;right; if(!pchild) { pchild = new Node(value); break; } p = pchild; } } insert(more...); } struct cell_display { string valstr; bool present; cell_display() : present(false) {} cell_display(std::string valstr) : valstr(valstr), present(true) {} }; using display_rows = vector&lt; vector&lt; cell_display &gt; &gt;; // The text tree generation code below is all iterative, to avoid stack faults. // get_row_display builds a vector of vectors of cell_display structs // each vector of cell_display structs represents one row, starting at the root display_rows get_row_display() const { // start off by traversing the tree to // build a vector of vectors of Node pointers vector&lt;Node*&gt; traversal_stack; vector&lt; std::vector&lt;Node*&gt; &gt; rows; if(!root) return display_rows(); Node *p = root; const int max_depth = root-&gt;max_depth(); rows.resize(max_depth); int depth = 0; for(;;) { // Max-depth Nodes are always a leaf or null // This special case blocks deeper traversal if(depth == max_depth-1) { rows[depth].push_back(p); if(depth == 0) break; --depth; continue; } // First visit to node? Go to left child. if(traversal_stack.size() == depth) { rows[depth].push_back(p); traversal_stack.push_back(p); if(p) p = p-&gt;left; ++depth; continue; } // Odd child count? Go to right child. if(rows[depth+1].size() % 2) { p = traversal_stack.back(); if(p) p = p-&gt;right; ++depth; continue; } // Time to leave if we get here // Exit loop if this is the root if(depth == 0) break; traversal_stack.pop_back(); p = traversal_stack.back(); --depth; } // Use rows of Node pointers to populate rows of cell_display structs. // All possible slots in the tree get a cell_display struct, // so if there is no actual Node at a struct's location, // its boolean &quot;present&quot; field is set to false. // The struct also contains a string representation of // its Node's value, created using a std::stringstream object. display_rows rows_disp; std::stringstream ss; for(const auto&amp; row : rows) { rows_disp.emplace_back(); for(Node* pn : row) { if(pn) { ss &lt;&lt; pn-&gt;value; rows_disp.back().push_back(cell_display(ss.str())); ss = std::stringstream(); } else { rows_disp.back().push_back(cell_display()); } } } return rows_disp; } // row_formatter takes the vector of rows of cell_display structs // generated by get_row_display and formats it into a test representation // as a vector of strings vector&lt;string&gt; row_formatter(const display_rows&amp; rows_disp) const { using s_t = string::size_type; // First find the maximum value string length and put it in cell_width s_t cell_width = 0; for(const auto&amp; row_disp : rows_disp) { for(const auto&amp; cd : row_disp) { if(cd.present &amp;&amp; cd.valstr.length() &gt; cell_width) { cell_width = cd.valstr.length(); } } } // make sure the cell_width is an odd number if(cell_width % 2 == 0) ++cell_width; // allows leaf nodes to be connected when they are // all with size of a single character if(cell_width &lt; 3) cell_width = 3; // formatted_rows will hold the results vector&lt;string&gt; formatted_rows; // some of these counting variables are related, // so its should be possible to eliminate some of them. s_t row_count = rows_disp.size(); // this row's element count, a power of two s_t row_elem_count = 1 &lt;&lt; (row_count-1); // left_pad holds the number of space charactes at the beginning of the bottom row s_t left_pad = 0; // Work from the level of maximum depth, up to the root // (&quot;formatted_rows&quot; will need to be reversed when done) for(s_t r=0; r&lt;row_count; ++r) { const auto&amp; cd_row = rows_disp[row_count-r-1]; // r reverse-indexes the row // &quot;space&quot; will be the number of rows of slashes needed to get // from this row to the next. It is also used to determine other // text offsets. s_t space = (s_t(1) &lt;&lt; r) * (cell_width + 1) / 2 - 1; // &quot;row&quot; holds the line of text currently being assembled string row; // iterate over each element in this row for(s_t c=0; c&lt;row_elem_count; ++c) { // add padding, more when this is not the leftmost element row += string(c ? left_pad*2+1 : left_pad, ' '); if(cd_row[c].present) { // This position corresponds to an existing Node const string&amp; valstr = cd_row[c].valstr; // Try to pad the left and right sides of the value string // with the same number of spaces. If padding requires an // odd number of spaces, right-sided children get the longer // padding on the right side, while left-sided children // get it on the left side. s_t long_padding = cell_width - valstr.length(); s_t short_padding = long_padding / 2; long_padding -= short_padding; row += string(c%2 ? short_padding : long_padding, ' '); row += valstr; row += string(c%2 ? long_padding : short_padding, ' '); } else { // This position is empty, Nodeless... row += string(cell_width, ' '); } } // A row of spaced-apart value strings is ready, add it to the result vector formatted_rows.push_back(row); // The root has been added, so this loop is finsished if(row_elem_count == 1) break; // Add rows of forward- and back- slash characters, spaced apart // to &quot;connect&quot; two rows' Node value strings. // The &quot;space&quot; variable counts the number of rows needed here. s_t left_space = space + 1; s_t right_space = space - 1; for(s_t sr=0; sr&lt;space; ++sr) { string row; for(s_t c=0; c&lt;row_elem_count; ++c) { if(c % 2 == 0) { row += string(c ? left_space*2 + 1 : left_space, ' '); row += cd_row[c].present ? '/' : ' '; row += string(right_space + 1, ' '); } else { row += string(right_space, ' '); row += cd_row[c].present ? '\\' : ' '; } } formatted_rows.push_back(row); ++left_space; --right_space; } left_pad += space + 1; row_elem_count /= 2; } // Reverse the result, placing the root node at the beginning (top) std::reverse(formatted_rows.begin(), formatted_rows.end()); return formatted_rows; } // Trims an equal number of space characters from // the beginning of each string in the vector. // At least one string in the vector will end up beginning // with no space characters. static void trim_rows_left(vector&lt;string&gt;&amp; rows) { if(!rows.size()) return; auto min_space = rows.front().length(); for(const auto&amp; row : rows) { auto i = row.find_first_not_of(' '); if(i==string::npos) i = row.length(); if(i == 0) return; if(i &lt; min_space) min_space = i; } for(auto&amp; row : rows) { row.erase(0, min_space); } } // Dumps a representation of the tree to cout void Dump() const { const int d = get_max_depth(); // If this tree is empty, tell someone if(d == 0) { cout &lt;&lt; &quot; &lt;empty tree&gt;\n&quot;; return; } // This tree is not empty, so get a list of node values... const auto rows_disp = get_row_display(); // then format these into a text representation... auto formatted_rows = row_formatter(rows_disp); // then trim excess space characters from the left sides of the text... trim_rows_left(formatted_rows); // then dump the text to cout. for(const auto&amp; row : formatted_rows) { std::cout &lt;&lt; ' ' &lt;&lt; row &lt;&lt; '\n'; } } }; int main() { BinTree&lt;int&gt; bt; // Build OP's tree bt.insert(8,5,2,6,10,9,11); cout &lt;&lt; &quot;Tree from OP:\n\n&quot;; bt.Dump(); cout &lt;&lt; &quot;\n\n&quot;; bt.clear(); // Build a random tree // This toy tree can't balance, so random // trees often look more like linked lists. // Just keep trying until a nice one shows up. std::random_device rd; std::mt19937 rng(rd()); int MaxCount=20; int MaxDepth=5; const int Min=0, Max=1000; std::uniform_int_distribution&lt;int&gt; dist(Min,Max); while(MaxCount--) { bt.insert(dist(rng)); if(bt.get_max_depth() &gt;= MaxDepth) break; } cout &lt;&lt; &quot;Randomly generated tree:\n\n&quot;; bt.Dump(); } </code></pre> <p>An example of the output:</p> <pre class="lang-none prettyprint-override"><code>Tree from OP: 8 / \ / \ / \ 5 10 / \ / \ 2 6 9 11 Randomly generated tree: 703 / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ / \ 137 965 / \ / / \ / / \ / / \ / / \ / / \ / / \ / 41 387 786 \ / \ / \ \ / \ / \ \ / \ / \ 95 382 630 726 813 \ 841 </code></pre>
26,265,526
How to improve fragment loading speed?
<p><strong>Performance Enhancement:</strong></p> <p>Previously I saved <strong>ALL</strong> images in <code>drawable</code> folder, this might be the reason why the map first loads slow, when draw the markers on screen, the image may not fit the screen size. <strong>Now</strong> I saved images in <code>drawable-mdpi</code>, <code>drawable-hdpi</code> and so on, the app works smoother than before. Hope it helps</p> <p><strong>Original Question:</strong></p> <p>I created a map in a fragment, the source code can be found below.</p> <p>The map fragment is sluggish when <strong>the first time</strong> it loads. If I go any other fragment and click the map fragment again, it loads fast and no slug anymore.</p> <p>Can anyone tell me what is going on here? Thanks!</p> <p>fragment_map.xml, id is <code>map</code></p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;fragment xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; xmlns:map=&quot;http://schemas.android.com/apk/res-auto&quot; android:id=&quot;@+id/map&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:name=&quot;com.google.android.gms.maps.SupportMapFragment&quot; /&gt; </code></pre> <p>MyMapFragment.java (contains <code>onCreateView</code> and <code> setUpMapIfNeeded</code>)</p> <pre><code>@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { try { rootView = inflater.inflate(R.layout.fragment_map, container, false); } catch (InflateException e) { /* map is already there, just return view as it is */ Log.e(TAG, &quot;inflateException&quot;); } setUpMapIfNeeded(); return rootView; } public void setUpMapIfNeeded() { // Do a null check to confirm that we have not already instantiated the fragment_map. if (myMap == null) { // Try to obtain the fragment_map from the SupportMapFragment. myMap = ((SupportMapFragment) MainActivity.fragmentManager.findFragmentById(R.id.map)).getMap(); // Check if we were successful in obtaining the fragment_map. if (myMap != null) { setUpMap(); } } } </code></pre>
29,246,677
5
2
null
2014-10-08 20:09:19.323 UTC
17
2020-10-09 05:49:40.083 UTC
2020-10-08 15:10:58.13 UTC
null
12,286,396
null
1,735,756
null
1
31
android|android-maps-v2|android-maps
26,802
<p>I'm using a very hackish but effective way in my application, but it works good. My mapFragment is not displayed right after the app launches! Otherwise this would not make sense.</p> <p>Put this in your launcher activity's <strong>onCreate</strong>:</p> <pre><code> // Fixing Later Map loading Delay new Thread(new Runnable() { @Override public void run() { try { MapView mv = new MapView(getApplicationContext()); mv.onCreate(null); mv.onPause(); mv.onDestroy(); }catch (Exception ignored){ } } }).start(); </code></pre> <p>This will create a mapview in an background thread (far away from the ui) and with it, initializes all the google play services and map data.</p> <p>The loaded data is about 5MB extra.</p> <p>If someone has some ideas for improvements feel free to comment please !</p> <hr> <p>Java 8 Version:</p> <pre><code>// Fixing Later Map loading Delay new Thread(() -&gt; { try { MapView mv = new MapView(getApplicationContext()); mv.onCreate(null); mv.onPause(); mv.onDestroy(); }catch (Exception ignored){} }).start(); </code></pre>
5,346,890
what is the difference between const_iterator and iterator?
<p>What is difference between these two regarding implementation inside STL. what is the difference regarding performance? I guess when we are traversing the vector in "read only wise", we prefer <code>const_iterator</code>, right?</p> <p>Thank you.</p>
5,346,927
3
0
null
2011-03-18 00:45:11.993 UTC
33
2018-04-25 18:26:24.67 UTC
2018-04-25 18:26:24.67 UTC
null
1,971,003
null
658,266
null
1
148
c++|stl|iterator|const-iterator
137,972
<p>There is no performance difference.</p> <p>A <code>const_iterator</code> is an iterator that points to const value (like a <code>const T*</code> pointer); dereferencing it returns a reference to a constant value (<code>const T&amp;</code>) and prevents modification of the referenced value: it enforces <a href="http://en.wikipedia.org/wiki/Const-correctness" rel="noreferrer"><code>const</code>-correctness</a>.</p> <p>When you have a const reference to the container, you can only get a <code>const_iterator</code>.</p> <p><strong>Edited:</strong> I mentionned “The <code>const_iterator</code> returns constant pointers” which is not accurate, thanks to Brandon for pointing it out.</p> <p><strong>Edit:</strong> For COW objects, getting a non-const iterator (or dereferencing it) will probably trigger the copy. (Some obsolete and now disallowed implementations of <code>std::string</code> use COW.)</p>
18,442,328
how to finish all activities except the first activity?
<p>I google it but even if i run this code below it didnt finish the other activities.</p> <pre><code>ButtonClick.setOnClickListener(new OnClickListener() { @Override public void onClick(View view) { LoginManager.getInstance().ctrl = false; UserManager.getInstance().loginControl(); OrderManager.getInstance().orderCtrl = false; Intent intent = new Intent(OrderComplete.this, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(intent); finish(); } }); } </code></pre>
25,159,180
9
8
null
2013-08-26 10:49:19.75 UTC
2
2017-10-10 06:30:19.247 UTC
2013-08-26 11:00:41.3 UTC
null
1,537,443
null
2,598,194
null
1
32
android|android-intent
24,368
<p>To clear top activities from stack use below code</p> <pre><code>Intent intents = new Intent(A.this, B.class); intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | IntentCompat.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intents); finish(); </code></pre> <p>It will <strong>delete all activities from stack</strong> either asynctask run or not in the application.</p> <p>It works fine and also a good approach</p>
14,976,331
Use of ~ (tilde) in R programming Language
<p>I saw in a tutorial about regression modeling the following command:</p> <pre><code>myFormula &lt;- Species ~ Sepal.Length + Sepal.Width + Petal.Length + Petal.Width </code></pre> <p>What exactly does this command do, and what is the role of <code>~</code> (tilde) in the command?</p>
14,976,479
3
2
null
2013-02-20 09:27:57.883 UTC
72
2021-03-23 18:19:28 UTC
2021-01-14 08:10:13.36 UTC
null
1,953,718
null
2,090,489
null
1
225
r|r-faq|r-formula
167,566
<p>The thing on the right of <code>&lt;-</code> is a <a href="https://www.rdocumentation.org/packages/stats/topics/formula" rel="noreferrer"><code>formula</code></a> object. It is often used to denote a statistical model, where the thing on the left of the <code>~</code> is the response and the things on the right of the <code>~</code> are the explanatory variables. So in English you'd say something like <em>"Species depends on Sepal Length, Sepal Width, Petal Length and Petal Width"</em>.</p> <p>The <code>myFormula &lt;-</code> part of that line stores the formula in an object called <code>myFormula</code> so you can use it in other parts of your R code.</p> <hr> <p><strong>Other common uses of formula objects in R</strong></p> <p>The <code>lattice</code> package uses them to <a href="https://www.rdocumentation.org/packages/lattice/topics/B_00_xyplot" rel="noreferrer">specify the variables to plot</a>.<br> The <code>ggplot2</code> package uses them to <a href="https://www.rdocumentation.org/packages/ggplot2/topics/facet_wrap" rel="noreferrer">specify panels for plotting</a>.<br> The <code>dplyr</code> package uses them for <a href="https://cran.r-project.org/web/packages/lazyeval/vignettes/lazyeval.html" rel="noreferrer">non-standard evaulation</a>.</p>
38,090,989
Property 'toPromise' does not exist on type 'Observable<Response>'
<pre class="lang-js prettyprint-override"><code>import { Headers, Http } from '@angular/http'; @Injectable() export class PublisherService{ private publishersUrl = 'app/publisher'; constructor(private http: Http) { } getPublishers(): Promise&lt;Publisher[]&gt;{ return this.http.get(this.publishersUrl) .toPromise() .then(response =&gt; response.json().data) .catch(this.handleError); } } </code></pre> <p>I am getting this error:</p> <blockquote> <p>Property 'toPromise' does not exist on type 'Observable'.any</p> </blockquote>
38,091,759
3
2
null
2016-06-29 05:23:55.53 UTC
9
2019-05-22 07:41:14.563 UTC
2017-12-07 12:39:50.747 UTC
null
2,903,341
null
6,504,463
null
1
76
angular|typescript|rxjs|angular2-services
58,358
<p>You need to add the operator like this:</p> <pre><code>import 'rxjs/add/operator/toPromise'; </code></pre> <p>This is needed for every rxjs operator you want to use. </p>
38,175,020
Can't access localhost via IP address
<p>I'm viewing a locally hosted website (using <code>grunt serve</code>, if that matters). I can view it via <code>http://localhost:9000/</code> or <code>http://127.0.0.1:9000/</code>, but not via <code>http://10.0.0.16:9000/</code>.</p> <p>10.0.0.16 is my local IP address (from <code>ifconfig</code> or System Preferences), but I cannot access my locally hosted content at <code>http://10.0.0.16:9000/</code> from either the device that is hosting it or from other devices on the network.</p> <p>I haven't had trouble using my local IP address to access locally hosted sites when my computer is on other networks, only on my home network. Do you have any idea what needs to change?</p>
38,175,246
2
3
null
2016-07-03 22:52:24.193 UTC
6
2021-06-03 11:03:43.117 UTC
null
null
null
null
1,502,723
null
1
41
networking|localhost
75,399
<p>If you can access a server running on your own machine via <code>127.0.0.1</code> (or <code>localhost</code>) but not via the computer's ip address, this means that the server software is configured to listen on the localhost interface only. This is a configuration item and to avoid exposing a potentially unsecure server many server programs come preconfigured to listen on localhost only. That way you can safely test locally before exposing the server.</p> <p>Note that <code>0.0.0.0</code> means "listen on all interfaces present on this computer" which is convenient, but may cause security issues if the machine has multiple interfaces.</p>
8,239,969
Rounding of float values
<p>I have the <code>double</code> value like <code>12.256852651</code> and I want to display it as <code>12.257</code> as a float number without converting it in to a string type.</p> <p>How can I do it in C# ?</p>
8,240,013
2
3
null
2011-11-23 09:40:05.123 UTC
5
2014-02-18 21:17:30.78 UTC
2013-05-15 01:18:44.83 UTC
null
1,046,955
null
1,046,955
null
1
36
c#|floating-point
76,315
<p>I'd first convert to <code>Decimal</code> and then use <code>Math.Round</code> on the result. This conversion is not strictly necessary, but I always feel a bit uneasy if I round to decimal places while using binary floating points.</p> <pre><code>Math.Round((Decimal)f, 3, MidpointRounding.AwayFromZero) </code></pre> <p>You should also look into the choice of <a href="http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx" rel="noreferrer"><code>MidpointRounding</code></a>, since by default this uses Banker's round, which is not what you are used to from school.</p>
9,396,411
ie javascript form submit with file input
<p>I have a html form, with a custom file upload field. And by that I mean that I have moved the actual file field beyond the borders of the page with css, that I have a custom input field and button in place, and that I have a jquery click event attached to that custom button to trigger the file input dialog. It all works fine, in every browser.</p> <p>But I need to submit the form through javascript. And I got somewhere that IE remembers my actions with javascript as a malicious manipulation of the file input field and blocks my access with an error <code>"access denied"</code> when I invoke <code>document.formName.submit()</code>.</p> <p>Is there a way around this, because I have gone completely mad by trying to search for a solution. I seriously don't want to use the default file input field, as every browsers renders it differently and messes up my design..</p> <p>code:</p> <pre><code>&lt;form name="thisForm" onsubmit="return false;" enctype="multipart/form-data" method="post" action="index.cfm/somepage"&gt; &lt;input type="file" class="hidden" name="hidden" id="hidden" /&gt; &lt;input type="text" name="shown" id="shown" /&gt; &lt;button id="button"&gt;browse..&lt;/button&gt; &lt;input type="submit" id="submitForm" /&gt; &lt;/form&gt; &lt;script&gt; $('button').click(function(){ $('#shown').val($('#hidden').val()); }); $('submitForm').click(function(){ validateForm(); }); function validateForm() { //regular expression validation against all other input fields in the form //not the file input field validateVAT(); } function validateVAT() { //connect to external service to check VAT submitForm(); } function submitForm() { document.thisForm.submit(); } &lt;/script&gt; </code></pre> <p><strong>UPDATE:</strong> I just tried to first upload the file, before submitting the form, through ajax, but that also gave me the acces denied error.. >_></p>
9,411,060
8
7
null
2012-02-22 14:09:12.293 UTC
12
2014-07-30 14:52:29.497 UTC
2012-02-23 09:23:37.587 UTC
null
940,833
null
940,833
null
1
25
javascript|jquery|html|forms
49,937
<p>I found the answer myself, After 2 days of crazy trial&amp;error. I hope I can help somebody with this..</p> <p>I removed the hidden file input field from my coldfusion page and replaced it by an iframe tag. That iframe tag linked to another coldfusion page, containing another form with the removed file input field. Now when I use javascript to click the file input field, which is still hidden from view, it still gives the browse file dialog without a hitch. But when I use javascript to submit the form, through the iframe, miraculously, it submits the form in the iframe, making it possible to upload the file in some serverside scripting of your preference.</p> <p>iframe code:</p> <pre><code>&lt;form id="formFileUpload" class="formFileUpload" name="formFileUpload" method="post" action="../actions/act_upload_file.cfm" autocomplete="off" enctype="multipart/form-data"&gt; &lt;input type="file" class="buttonFileHidden" id="inputFile" name="partnersLogo" /&gt; &lt;/form&gt; </code></pre> <p>iframe itself:</p> <pre><code>&lt;iframe src="admin/dsp_file_upload.cfm" id="ifu" name="ifu" class="buttonFileHidden"&gt; &lt;/iframe&gt; </code></pre> <p>javascript click &amp; submit:</p> <pre><code>ifu.document.formFileUpload.partnersLogo.click(); ifu.document.formFileUpload.submit(); </code></pre>
14,793,585
IndexError: too many indices
<p>I am trying to use an algorithm in scikit-learn to predict the output based on a number of inputs. I seem to be getting the error 'too many indices' returned, but cannot figure out why. </p> <p>CSV File Training:</p> <pre><code> 1.1 0.2 0.1 0 0.12 0.1 1.4 0.2 0.1 0.1 0.14 0.1 0.1 0.1 0.1 0 0.26 0.1 24.5 0.1 0 0.1 0.14 0.1 0.1 0.1 0.1 0 0.25 0.1 </code></pre> <p>Code:</p> <pre><code> fileCSVTraining = genfromtxt('TrainingData.csv', delimiter=',', dtype=None) #Define first 6 rows of data as the features t = fileCSVTraining[:, 6:] #Define which column to put prediction in r = fileCSVTraining[:, 0-6:] #Create and train classifier x, y = r, t clf = LinearSVC() clf = clf.fit(x, y) #New data to predict X_new = [1.0, 2.1, 3.0, 2.4, 2.1] b = clf.predict(X_new) </code></pre> <p>Error:</p> <pre><code> t = fileCSVTraining[:, 6:] IndexError: too many indices </code></pre>
14,794,023
4
3
null
2013-02-10 01:18:13.683 UTC
1
2014-01-27 07:19:02.6 UTC
2013-02-13 08:28:05.347 UTC
null
72,882
null
1,987,845
null
1
2
python|numpy|scikit-learn
40,071
<p>Based on the comments, I think you want:</p> <pre><code>fileCSVTraining = genfromtxt('TrainingData.csv') </code></pre> <p>Then, to get the "first 6 rows", you would use</p> <pre><code>t = fileCSVTraining[:6, :] </code></pre> <p>(I'm assuming your actual data file is longer than you've shown. Your example has only 5 rows.)</p> <p>I suspect your use of array indexing to get <code>r</code> is also incorrect.</p>
23,876,782
How do I split a TypeScript class into multiple files?
<p>I found a lot of examples and also tried myself to split a module into several files. So I get that one, very handy. But it's also practical sometimes to split a class for the same reason. Say I have a couple of methods and I don't want to cram everything into one long file.</p> <p>I'm looking for something similar to the <strong>partial</strong> declaration in C#.</p>
23,876,952
12
7
null
2014-05-26 19:43:55.103 UTC
15
2022-05-23 05:44:42.823 UTC
null
null
null
null
2,147,704
null
1
86
javascript|typescript
39,241
<p>You can't.</p> <p>There was a feature request to implement partial classes, first on <a href="https://typescript.codeplex.com/workitem/1612" rel="noreferrer">CodePlex</a> and later on <a href="https://github.com/Microsoft/TypeScript/issues/563" rel="noreferrer">GitHub</a>, but <a href="https://github.com/Microsoft/TypeScript/issues/563#issuecomment-291300044" rel="noreferrer">on 2017-04-04</a> it was declared out-of-scope. A number of reasons are given, the main takeaway seems to be that they want to avoid deviating from ES6 as much as possible:</p> <blockquote> <p>TypeScript <em>already</em> has too many TS-specific class features [...] Adding yet another TS-specific class feature is another straw on the camel's back that we should avoid if we can. [...] So if there's some scenario that really knocks it out of the park for adding partial classes, then that scenario ought to be able to justify itself through the TC39 process.</p> </blockquote>
8,692,488
Jquery check two inputs for same value
<p>I've been trying to write Jquery code to check if two inputs have the same value on form submit without luck.</p> <p>If input with id "id1" has the same value as input with id "id2" alert "some text" and return false.</p> <p>Any help would be much appreciated.</p> <pre><code>$('#form').submit(function() { var id1 = $(#id1).text(); var id2 = $(#id2).text(); if (id1 == id2) { alert('Error, cant do that'); return false; } else { return true; } }); </code></pre>
8,692,507
3
3
null
2012-01-01 09:09:59.28 UTC
2
2012-01-01 09:57:30.237 UTC
2012-01-01 09:15:51.113 UTC
null
448,014
null
448,014
null
1
8
jquery
41,035
<p><a href="http://jsfiddle.net/NotInUse/g2kBm/2/" rel="noreferrer">DEMO HERE</a></p> <pre><code>&lt;input type="text" id="id1" /&gt; &lt;input type="text" id="id2" /&gt; $('input').blur(function() { if ($('#id1').attr('value') == $('#id2').attr('value')) { alert('Same Value'); return false; } else { return true; } }); </code></pre> <p>I simply used blur rather than a form submit.</p>
8,589,880
How can i change included xml layout to another layout on java code?
<p>I included second layout to first layout like this:</p> <pre><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; &gt; &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:layout_width=&quot;300dp&quot; android:layout_height=&quot;match_parent&quot; android:layout_gravity=&quot;clip_horizontal&quot; android:layout_alignParentLeft=&quot;true&quot; android:id=&quot;@+id/rlMenu&quot; &gt; &lt;Button android:id=&quot;@+id/bMusteriler&quot; android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot; android:text=&quot;Musteriler&quot; android:textSize=&quot;45dp&quot; android:layout_alignParentLeft=&quot;true&quot; /&gt; &lt;/RelativeLayout&gt; &lt;RelativeLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;match_parent&quot; android:layout_toRightOf=&quot;@id/rlEkranlar&quot; &gt; &lt;include android:id=&quot;@+id/include1&quot; android:layout_width=&quot;fill_parent&quot; android:layout_height=&quot;wrap_content&quot; layout=&quot;@layout/ikinci&quot; /&gt; &lt;/RelativeLayout&gt; &lt;/RelativeLayout&gt; </code></pre> <p>Problem is how can I change included layout when clicked a button(on java code)?</p>
8,612,347
3
3
null
2011-12-21 12:31:41.8 UTC
15
2021-07-21 05:08:32.77 UTC
2021-07-21 05:08:32.77 UTC
null
12,892,553
null
1,109,820
null
1
28
android|android-layout|xml-layout
40,839
<p>I suggest <code>ViewFlipper</code> inside <code>RelativeLayout</code> of your <code>include</code> statements. Try like this:</p> <pre><code>&lt;ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/vf" android:layout_width="fill_parent" android:layout_height="wrap_content" &gt; &lt;include android:id="@+id/include1" layout="@layout/ikinci" /&gt; &lt;include android:id="@+id/map" layout="@layout/third_layout" /&gt; &lt;/ViewFlipper&gt; </code></pre> <p>Access ViewFlipper as below. Initially first layout is output:</p> <pre><code>ViewFlipper vf = (ViewFlipper)findViewById(R.id.vf); </code></pre> <p>For Button onClickListener:</p> <pre><code>button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub vf.setDisplayedChild(1); } }); </code></pre>
9,008,299
Check if MySQL table exists or not
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1525784/mysql-check-if-a-table-exists-without-throwing-an-exception">MySQL check if a table exists without throwing an exception</a> </p> </blockquote> <p>I have a dynamic mysql query builder in my project that creates select queries from different tables.<br> I need to check if the current processing table exists or not.<br> Imagine that my tables are table1, table2, and table3. My code is something like this: </p> <pre><code>&lt;?php for($i = 1 ; $i &lt;= 3 ; $i++) { $this_table = 'table'.$i; $query = mysql_query("SELECT * FROM $this_table"); // ... } ?&gt; </code></pre> <p>How can I do this check (Please tell me the simplest way).</p>
9,008,326
7
3
null
2012-01-25 18:39:37.683 UTC
6
2017-11-04 23:06:02.8 UTC
2017-11-04 23:06:02.8 UTC
null
4,370,109
null
789,090
null
1
44
php|mysql|exists
146,493
<p>Updated mysqli version:</p> <pre><code>if ($result = $mysqli-&gt;query("SHOW TABLES LIKE '".$table."'")) { if($result-&gt;num_rows == 1) { echo "Table exists"; } } else { echo "Table does not exist"; } </code></pre> <p>Original mysql version:</p> <pre><code>if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) echo "Table exists"; else echo "Table does not exist"; </code></pre> <p>Referenced from the <a href="http://www.php.net/manual/en/function.mysql-tablename.php" rel="noreferrer">PHP docs</a>.</p>
8,682,622
Using setInterval() to do simplistic continuous polling
<p>For a simple web app that needs to refresh parts of data presented to the user in set intervals, are there any downsides to just using <code>setInterval()</code> to get a JSON from an endpoint instead of using a proper polling framework?</p> <p>For the sake of an example, let's say I'm refreshing the status of a processing job every 5 seconds.</p>
8,682,723
5
3
null
2011-12-30 18:21:13.19 UTC
18
2022-05-20 18:58:20.007 UTC
2022-01-06 12:29:21.87 UTC
null
10,158,227
null
276,328
null
1
67
javascript|ajax|setinterval|polling
67,966
<p>From my comment:</p> <p>I would use <a href="https://developer.mozilla.org/en/DOM/window.setTimeout"><code>setTimeout</code> <em><sup>[docs]</sup></em></a> and always call it when the previous response was received. This way you avoid possible congestion or function stacking or whatever you want to call it, in case a request/response takes longer than your interval.</p> <p>So something like this:</p> <pre><code>function refresh() { // make Ajax call here, inside the callback call: setTimeout(refresh, 5000); // ... } // initial call, or just call refresh directly setTimeout(refresh, 5000); </code></pre>
5,590,862
icd9 regex pattern
<p>I cannot find a definitive guide to icd9 code formats.</p> <p>Can anyone explain the format - especially the use of trailing and leading zeros?</p> <p>A C# regex for icd9 and icd10 codes would also be nice.</p> <p>Thanks!</p>
9,573,066
4
2
null
2011-04-08 05:35:28.77 UTC
11
2017-01-17 13:18:28.573 UTC
null
null
null
null
36,902
null
1
21
c#|regex
8,694
<p>I was looking for the same thing and found what I believe to be a more complete answer. Thought I'd help anyone else coming in the future.</p> <p><strong>ICD-9 Regex</strong></p> <p>The ICD 9 format has a bunch of ways it can be formatted. It can begin with V, E, or a number.</p> <ul> <li>If it begins with V, then it has 2 numbers, a decimal, then up to two numbers <ul> <li>Examples: <code>V10.12</code> and <code>V12</code></li> </ul></li> <li>If it begins when E, then it has 3 numbers, the decimal place, then up to two numbers <ul> <li>Examples: <code>E000.0</code> and <code>E002</code></li> </ul></li> <li>If it begins with a number, then it is up to 3 numbers, a decimal, then up to two numbers <ul> <li>Examples: <code>730.12</code> and <code>730</code></li> </ul></li> </ul> <p>A good regex that checks all these rules is (Credit goes to <a href="http://www.sascommunity.org/wiki/Validate_the_format_of_ICD-9_codes" rel="noreferrer">sascomunitt</a>)</p> <pre><code>^(V\d{2}(\.\d{1,2})?|\d{3}(\.\d{1,2})?|E\d{3}(\.\d)?)$ </code></pre> <p><strong>ICD-10 Regex</strong></p> <p>According to <a href="https://www.cms.gov/ICD10/Downloads/032310_ICD10_Slides.pdf" rel="noreferrer">www.cms.gov</a> ICD-10 has the following rules:</p> <ul> <li>3-7 Characters</li> <li>Character 1 is alpha (cannot be U)</li> <li>Character 2 is numeric</li> <li>Characters 3-7 are alphanumeric</li> <li>After 3 characters you use a decimal</li> <li>Use of dummy placeholder "x" (This is the only one I am not accounting for in my regex...)</li> <li>Alpha characters are not case sensitive</li> </ul> <p>Here is the regex I came up with:</p> <pre><code>^[A-TV-Z][0-9][A-Z0-9](\.[A-Z0-9]{1,4})?$ </code></pre> <p><strong>Note</strong> These regexes are for javascript and may need tweaked for C# (I'm too lazy to test it right now)</p>
5,525,854
How to convert the file last modified timestamp to a date?
<p>How do I convert <a href="http://download.oracle.com/javase/6/docs/api/java/io/File.html#lastModified%28%29"><code>File#lastModified()</code></a> to a real date? The format is not really important.</p>
5,525,871
4
1
null
2011-04-02 21:02:08.24 UTC
4
2020-04-16 17:35:15.573 UTC
2011-04-02 21:12:17.59 UTC
null
633,239
null
282,383
null
1
37
java|date
73,682
<pre><code>Date d = new Date(file.lastModified()); </code></pre> <p><code>lastModified()</code> returns the milliseconds since 1970-01-01, and the <code>Date</code> class stores its time also in the same way. The <code>Date(long)</code> constructor takes these milliseconds, and initializes the <code>Date</code> with it. </p>
5,207,503
How do I get the contents of a nicEdit form when submitting trough ajax?
<p>So what I want to do is to submit a form using jQuery's AJAX function. And the route I choose to go was to use $('#form').serialize(); and then pass that as a GET request. It works out all dandy and fine and dandy until I add the editor, NicEdit, that I'm going to use on the site.</p> <p>I've researched the issue and the situation is so that once NicEdit takes over a text-area for example, it hides the text-area to the user and instead has her write into a . This data will then be put back into the text-area triggered by the push of a normal submit button.</p> <p>Now the issue is: I don't have a normal submit button and hence don't trigger the event that puts the data back in the text-area. And I have tried my best to <strike> solve the issue</strike> google a solution but everything I've found has been worthless.</p> <p>Given the fallowing basic setup of my situation: <a href="http://jsfiddle.net/MMzhS/1/" rel="noreferrer">http://jsfiddle.net/MMzhS/1/</a> - How would you get the data from the NicEdit form to the text-area before alert(); is called?</p>
5,207,777
7
0
null
2011-03-05 23:27:23.397 UTC
9
2015-10-30 10:48:09.737 UTC
null
null
null
null
501,017
null
1
9
jquery|ajax|nicedit
31,728
<p>The following as provided by BinaryKitten from #jQuery does the same but a bit cleaner in my opinion: <a href="http://jsfiddle.net/MMzhS/5/">http://jsfiddle.net/MMzhS/5/</a> </p>
5,285,623
How do I install Eclipse Marketplace in Eclipse Classic?
<p>I'm running Eclipse 3.6.1 Classic, which does not come with the Eclipse Marketplace plugin by default. I've looked around the Eclipse website, but I don't see an available plugin for installing Eclipse Marketplace. Am I just not seeing it?</p>
5,285,816
9
3
null
2011-03-12 21:29:16.307 UTC
43
2017-01-28 01:29:21.597 UTC
null
null
null
null
572
null
1
248
eclipse|eclipse-plugin|eclipse-marketplace
150,291
<p>Help &rarr; Install new Software &rarr; Switch to the Kepler Repository &rarr; General Purpose Tools &rarr; Marketplace Client</p> <p>If you use Eclipse Luna SR 1, the released Marketplace contains a bug; you have to install it from the Marketplace update site. This is fixed again in Luna SR 2.</p> <p>Marketplace update site:</p> <ul> <li>Luna - <a href="http://download.eclipse.org/mpc/luna" rel="noreferrer">http://download.eclipse.org/mpc/luna</a></li> <li>Helios - <a href="http://download.eclipse.org/releases/helios" rel="noreferrer">http://download.eclipse.org/releases/helios</a></li> <li>Juno - <a href="http://download.eclipse.org/releases/juno" rel="noreferrer">http://download.eclipse.org/releases/juno</a></li> <li>Mars - <a href="http://download.eclipse.org/releases/mars" rel="noreferrer">http://download.eclipse.org/releases/mars</a></li> </ul>
5,337,828
Hide a DIV when it loses focus/blur
<p>I have a JavaScript that displays a DIV (sets its display css property from 'none' to 'normal'. Is there a way to give it focus as well so that when I click somewhere else on the page, the DIV loses focus and its display property is set to none (basically hiding it). I'm using JavaScript and jQuery</p>
14,194,155
11
5
null
2011-03-17 10:31:19.713 UTC
5
2018-08-28 09:33:16.093 UTC
2011-03-17 10:59:16.367 UTC
null
360,890
null
521,180
null
1
19
javascript|jquery|html
73,325
<p>For the hide the div when clicking any where on page except the selecteddiv</p> <pre><code>$(document).not("#selecteddiv").click(function() { $('#selecteddiv').hide(); }); </code></pre> <p>if you want to hide the div with lost focus or blur with animation then also</p> <pre><code>$("#selecteddiv").focusout(function() { $('#selecteddiv').hide(); }); </code></pre> <p>with animation</p> <pre><code>$("#selecteddiv").focusout(function() { $('#selecteddiv').animate({ display:"none" }); }); </code></pre> <p>May this will help you</p>
5,499,035
Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX
<p>I have a standard Rails3 environment, RVM 1.2.9, Rails 3.0.5, Ruby 1.9.2p180, MySQL2 Gem 0.2.7, mysql-5.5.10-osx10.6-x86_64</p> <p>Error I get when running <code>rake db:migrate</code> to create database is:</p> <pre><code>Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2) </code></pre> <p>config/database.yml has</p> <pre><code>development: adapter: mysql2 host: localhost username: root password: xxxx database: xxxx </code></pre> <p>sure it's something simple I'm missing.</p>
6,412,218
14
3
null
2011-03-31 11:24:53.643 UTC
50
2019-12-06 04:53:04.623 UTC
null
null
null
null
345,916
null
1
87
mysql|ruby-on-rails-3|macos
105,040
<p>First, to find your socket file:</p> <pre><code>mysqladmin variables | grep socket </code></pre> <p>For me, this gives:</p> <pre><code>| socket | /tmp/mysql.sock | </code></pre> <p>Then, add a line to your <code>config/database.yml</code>:</p> <pre><code>development: adapter: mysql2 host: localhost username: root password: xxxx database: xxxx socket: /tmp/mysql.sock </code></pre>
16,996,775
Horizontally center a DIV in page
<p>I'm trying to center a div, which is the Microsoft pubCenter AdControl for Windows 8 apps in HTML5/JavaScript.</p> <pre><code> &lt;div id="myAd" style="; top: 0%; width: 292px; height: 60px; z-index: 1" data-win-control="MicrosoftNSJS.Advertising.AdControl" data-win-options="{applicationId: 'exampleAdId', adUnitId: 'exampleAdUnit'}"&gt; &lt;/div&gt; </code></pre> <p>How would I center a div horizontally so it is always in the middle of a page?</p>
16,996,799
5
1
null
2013-06-08 06:30:01.827 UTC
1
2015-09-25 06:39:53.79 UTC
2013-06-08 07:30:48.787 UTC
null
1,982,850
null
1,480,886
null
1
12
html|windows-8|microsoft-metro|winjs
69,147
<p>you can use css only</p> <pre><code>left:50%;margin-left:-146px; </code></pre> <p>the point is to set margin left as half of the div width </p>
41,587,802
CSS Animation from Left to Right
<p>I am trying to make an animation in <code>CSS</code>. I read some examples of it online and I cannot figure out what I'm doing wrong... I want my potato image to go from left to right and then turn around and then go back to the left side again, but I probably messed up something in my code? Any suggestions what I'm doing wrong or how I should face this problem instead?</p> <p>Here is my code:</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-css lang-css prettyprint-override"><code>#pot { bottom: 15%; position: absolute; -webkit-animation: linear infinite alternate; -webkit-animation-name: run; -webkit-animation-duration: 5s; } @-webkit-keyframes run { 0% { left: 0; } 50% { right: 0; } 100% { left: 0; , webkit-transform: scaleX(-1); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="pot"&gt; &lt;img src="https://i.stack.imgur.com/qgNyF.png?s=328&amp;g=1" width=100px height=100px&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>(sorry mos, safari and opera users) <a href="https://jsfiddle.net/oxc12av7/" rel="noreferrer">https://jsfiddle.net/oxc12av7/</a></p>
64,712,239
6
3
null
2017-01-11 10:03:26.427 UTC
10
2022-09-23 11:48:49.41 UTC
2020-11-06 08:29:14.763 UTC
null
6,109,554
null
6,109,554
null
1
16
html|css|animation
178,186
<p>Since this question is still getting alot of attention and none of the soulotions yet provide the full answer that I was trying to achieve, I'll give an example how I solved it some years ago.</p> <blockquote> <p>First to make the animation go left to right, like many other questions have showed:</p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#pot { bottom: 15%; position: absolute; -webkit-animation: linear infinite; -webkit-animation-name: run; -webkit-animation-duration: 5s; } @-webkit-keyframes run { 0% { left: 0; } 50% { left: 100%; } 100% { left: 0; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="pot"&gt; &lt;img src="https://i.stack.imgur.com/qgNyF.png?s=328&amp;g=1" width=100px height=100px&gt; &lt;/div&gt; </code></pre> </div> </div> </p> <p>The problem with only this solution is that the potato goes too far to the right so it gets pushed out from the viewport before turning around. As the user Taig suggested we can use <code>transform: translate</code> solution, but we can also just set <code>50% { left: calc(100% - potatoWidth); }</code></p> <blockquote> <p>Second to make the animation go left to right, without getting pushed out from viewport:</p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#pot { bottom: 15%; position: absolute; -webkit-animation: linear infinite; -webkit-animation-name: run; -webkit-animation-duration: 5s; } @-webkit-keyframes run { 0% { left: 0; } 50% { left: calc(100% - 100px); } 100% { left: 0; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="pot"&gt; &lt;img src="https://i.stack.imgur.com/qgNyF.png?s=328&amp;g=1" width=100px height=100px&gt; &lt;/div&gt; </code></pre> </div> </div> </p> <p>And lastly to make potato turn around which I also asked for in the question. To do that we need to change the transform around it's y-axis.</p> <p>Note that if we make it turn around only at 50% it will slowly turn around at the same time it's moving. So we need to specify how long the potato should be at <code>-webkit-transform: rotateY(0deg);</code>. In this example the potato doesn't turn until it's 48% into the animation, then it's able to turn in the span of 48% to 50%.</p> <blockquote> <p>Third to make the potato turn around in each corner so it doesn't move backwards:</p> </blockquote> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#pot { bottom: 15%; position: absolute; -webkit-animation: linear infinite; -webkit-animation-name: run; -webkit-animation-duration: 5s; } @-webkit-keyframes run { 0% { left: 0; } 48% { -webkit-transform: rotateY(0deg); } 50% { left: calc(100% - 100px); -webkit-transform: rotateY(180deg); } 98% { -webkit-transform: rotateY(180deg); } 100% { left: 0; -webkit-transform: rotateY(0deg); } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="pot"&gt; &lt;img src="https://i.stack.imgur.com/qgNyF.png?s=328&amp;g=1" width=100px height=100px&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
41,552,973
CardView background color always white
<p>I am using RecyclerView with GridLayoutManager and I have each item as CardView.</p> <p>Unfortunately, the CardView here does not seem to change its background color. I tried in layout and programmatically as well but I have tried nothing seems to work.</p> <p>I Have been struggling for quite a while. I appreciate if someone could help me out with this issue.</p>
41,553,093
8
4
null
2017-01-09 16:53:46.637 UTC
23
2022-07-22 14:16:25.99 UTC
2017-06-22 08:33:36.31 UTC
null
2,608,346
null
3,024,565
null
1
185
android|android-recyclerview|android-cardview
141,390
<p>If you want to change the card background color, use: </p> <pre><code>app:cardBackgroundColor="@somecolor" </code></pre> <p>like this:</p> <pre><code>&lt;android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" app:cardBackgroundColor="@color/white"&gt; &lt;/android.support.v7.widget.CardView&gt; </code></pre> <p><strong>Edit:</strong> As pointed by @imposible, you need to include </p> <pre><code>xmlns:app="http://schemas.android.com/apk/res-auto" </code></pre> <p>in your root XML tag in order to make this snippet function</p>
12,340,688
Copying range and pasting into new workbook
<p>This should be really simple, but I've been trawling forums and SO answers for hours to find the answer with no luck, so am (reluctantly) creating a question of my own.</p> <p>What I'm trying to do is simply create a new workbook, and paste a range from another workbook into that workbook. Sounds simple..?</p> <p>My original workbook, let's call Book1. I'm trying to create a new workbook, Book2, which I will copy the <em>values</em> of cells A1:B10 to.</p> <p>Here's one version of my code (starting with Book1 open):</p> <pre><code>Range("A1:B10").Copy Set NewBook = Workbooks.Add With NewBook .SaveAs Filename:="Book2.xls" End With Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False </code></pre> <p>This gives a "PasteSpecial of Range class failed" error. I have tried the following fixes with no luck:</p> <ul> <li>added 'Workbooks("Book2.xls").Activate' to the code</li> <li>removed the extra arguments in the PasteSpecial line</li> <li>tried '.Paste' instead of '.PasteSpecial'</li> <li>changed 'Selection.PasteSpecial' to 'ActiveSheet.PasteSpecial'</li> <li>explicitly referencing the copy range, including the workbook and sheet reference</li> <li>creating the new workbook first, then performing the copy, before reactivating the new workbook and pasting</li> </ul> <p>None of the above solutions work... any wisdom at this stage would be gratefully received!</p>
12,340,929
2
0
null
2012-09-09 16:14:46.277 UTC
4
2016-02-26 09:55:27.803 UTC
2018-07-09 19:34:03.733 UTC
null
-1
null
741,739
null
1
6
excel|vba
101,178
<p>Is this what you are trying? I have commented the code so that you shouldn't have any problem understanding what the code does.</p> <pre><code>Option Explicit Sub Sample() Dim wbI As Workbook, wbO As Workbook Dim wsI As Worksheet, wsO As Worksheet '~~&gt; Source/Input Workbook Set wbI = ThisWorkbook '~~&gt; Set the relevant sheet from where you want to copy Set wsI = wbI.Sheets("Sheet1") '~~&gt; Destination/Output Workbook Set wbO = Workbooks.Add With wbO '~~&gt; Set the relevant sheet to where you want to paste Set wsO = wbO.Sheets("Sheet1") '~~&gt;. Save the file .SaveAs Filename:="C:\Book2.xls", FileFormat:=56 '~~&gt; Copy the range wsI.Range("A1:B10").Copy '~~&gt; Paste it in say Cell A1. Change as applicable wsO.Range("A1").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _ SkipBlanks:=False, Transpose:=False End With End Sub </code></pre>
12,339,083
Android call method from another app
<p>I have 2 android apps. Both are installed on the phone. Lets say the package name for the two are com.android.test1 and com.android.test2. How can i call the method <code>Main2method()</code> from the test1.Main class ?</p> <p>Class for test1:</p> <pre><code>package com.android.test1; import android.app.Activity; import android.os.Bundle; public class Main extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } } </code></pre> <p>Class for test2:</p> <pre><code>package com.android.test2; import android.app.Activity; import android.os.Bundle; public class Main2 extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public static void Main2method() { //do something.. } } </code></pre>
12,339,345
4
1
null
2012-09-09 12:30:50.287 UTC
8
2019-07-17 14:15:56.663 UTC
2015-07-10 08:27:10.037 UTC
null
3,422,488
null
1,449,761
null
1
15
android|methods|static|package
11,090
<p>Maybe you can broadcast an Intent to call it.</p> <pre><code>Intent it = new Intent("com.android.test2.Main2method"); context.sendBroadcast(it) </code></pre> <p>Make a <code>BroadcastReceiver</code> in <code>com.android.test2.Main2</code> to receive the broadcast:</p> <pre><code>public class ActionReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if ("com.android.test2.Main2method".equalsIgnoreCase(intent.getAction())) { Main2method(); } } } </code></pre> <p>Register the receiver in <code>onCreate</code> method of class <code>Main1</code>:</p> <pre><code>public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... receiver = new ActionReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("com.android.test2.Main2method"); registerReceiver(receiver, filter); ... } </code></pre>
12,290,165
Generating Hypermedia links in a Web API
<p>I'm curious to know how others have dealt with the issue of generating hypermedia links for their web APIs? Specifically, I'm using ASP.NET Web API, and am torn between having operations return hypermedia-related types, or returning the resource itself, and having the hypermedia stuff happen later in the pipeline. That is, do people tend to do things like:</p> <pre><code>public Resource&lt;Order&gt; GetOrder(int id) { return new Resource&lt;Order&gt;() { Content = new Order(), Links = new LinkCollection&lt;Order&gt;() { new AddOrderLink(), new UpdateOrderLink()} } </code></pre> <p>Or something more like</p> <pre><code>public Order GetOrder(int id) { return new Order(); } </code></pre> <p>And then add hypermedia links inside an HttpOperationHandler or custom formatter or something?</p> <p>If the approach is more like #2, how do you know what links to generate? Just have some standard set of links that get generated for all Order objects? Attributes decorating various operations in OrdersController?</p>
12,295,059
4
2
null
2012-09-05 21:37:43.403 UTC
8
2017-09-08 10:54:34.617 UTC
2016-06-02 04:58:36.467 UTC
null
41,956
null
125,831
null
1
22
c#|asp.net-web-api|hateoas|hypermedia
10,550
<p>I prefer option two (adding the hypermedia links later in the pipeline) and <a href="http://ben.onfabrik.com/posts/generating-hypermedia-links-in-aspnet-web-api" rel="noreferrer">blogged about doing this yesterday</a>.</p> <p>The solution was to "enrich" my resources with hypermedia links before they are returned to the client using a message handler.</p>
12,387,212
Openpyxl setting number format
<p>Could please someone show an example of applying the number format to the cell. For example, I need scientific format, form would be like '2.45E+05' but I couldn't figure a way how to do that in openpyxl.</p> <p>I tried in several ways but they are all reporting errors when saving the workbook.</p> <p>for example:</p> <pre><code> import openpyxl as oxl wb = oxl.Workbook() ws = wb.create_sheet(title='testSheet') _cell = ws.cell('A1') _cell.style.number_format = '0.00E+00' </code></pre> <p>or this (here I'm trying to use some of the predefined number formats, I have also seen there is engineering format in builtins but don't know how to access it:</p> <pre><code> nf = oxl.style.NumberFormat.FORMAT_NUMBER_00 _cell.style.number_format = nf </code></pre> <p>In both cases I get the same error:</p> <pre><code>C:\Python27\openpyxl\cell.pyc in is_date(self) 408 """ 409 return (self.has_style --&gt; 410 and self.style.number_format.is_date_format() 411 and isinstance(self._value, NUMERIC_TYPES)) AttributeError: 'str' object has no attribute 'is_date_format' </code></pre> <p>I have seen this question: <a href="https://stackoverflow.com/questions/8440284/setting-styles-in-openpyxl">Setting styles in Openpyxl</a> but it doesn't help because I don't have to change any other formatting settings.</p>
26,334,956
4
0
null
2012-09-12 11:32:30.713 UTC
7
2021-10-09 02:52:27.07 UTC
2018-10-03 09:09:27.947 UTC
null
119,775
null
1,349,418
null
1
35
python|openpyxl
76,471
<p>This answer works with openpyxl 2.0. (The <a href="https://stackoverflow.com/a/12401556/119775">previously accepted answer</a> does not.)</p> <p>The <code>number_format</code> can be changed directly.</p> <p>The given example becomes:</p> <pre><code>from openpyxl import Workbook wb = Workbook() ws = wb.create_sheet(title='testSheet') _cell = ws.cell('A1') _cell.number_format = '0.00E+00' </code></pre>
12,333,764
DataModel must implement org.primefaces.model.SelectableDataModel when selection is enabled.
<p>I'm trying to create a DataTable with Multiple Row Selection but i'm getting an error here's the link of the tutorial <a href="http://www.primefaces.org/showcase/ui/datatableRowSelectionMultiple.jsf" rel="noreferrer">http://www.primefaces.org/showcase/ui/datatableRowSelectionMultiple.jsf</a> :</p> <p>Here's my xhtml:</p> <pre><code> &lt;p:dataTable border="1" value="#{projectAdminisrationMB.projectNoUsersList}" var="userObj" selection="# {projectAdminisrationMB.selectedUsers}" selectionMode="multiple" rowIndexVar="rowIndex"binding="#{table2}"&gt; &lt;p:column id="column3"&gt; &lt;f:facet name="header"&gt; &lt;h:outputText value=" user "&gt;&lt;/h:outputText&gt; &lt;/f:facet&gt; &lt;h:outputText value="#{userObj.name}"/&gt; / &lt;h:outputText value="#{userObj.lastName}"&gt;&lt;/h:outputText&gt; &amp;nbsp; &lt;h:outputText value="#{userObj.firstName}"&gt;&lt;/h:outputText&gt; &lt;/p:column&gt; &lt;f:facet name="footer"&gt; &lt;p:commandButton id="addProjectUser" value=" Add " onclick="dlg1.show()" /&gt; &lt;p:commandButton id="deleteProjectUser" value=" Delete " /&gt; &lt;/f:facet&gt; &lt;/p:dataTable&gt; </code></pre> <p>Managed Bean :</p> <pre><code> @ManagedBean @SessionScoped public class ProjectAdminisrationMB implements Serializable { private static final long serialVersionUID = 1L; private String projectName; private List &lt;User&gt; projectUsersList; private List&lt;User&gt; projectNoUsersList; private List&lt;User&gt; selectedUsers; private String projectAdmin; public ProjectAdminisrationMB() { super(); AdministrationProjectFinal administrationProjectFinal =new AdministrationProjectFinal(); this.projectUsersList=administrationProjectFinal.getUserList(); this.projectNoUsersList=administrationProjectFinal.getNotUserList(); } public String getProjectName() { return projectName; } public void setProjectName(String projectName) { this.projectName = projectName; } public List&lt;User&gt; getProjectUsersList() { return projectUsersList; } public void setProjectUsersList(List&lt;User&gt; projectUsersList) { this.projectUsersList = projectUsersList; } public String getProjectAdmin() { return projectAdmin; } public void setProjectAdmin(String projectAdmin) { this.projectAdmin = projectAdmin; } public List&lt;User&gt; getProjectNoUsersList() { return projectNoUsersList; } public void setProjectNoUsersList(List&lt;User&gt; projectNoUsersList) { this.projectNoUsersList = projectNoUsersList; } public List&lt;User&gt; getSelectedUsers() { return selectedUsers; } public void setSelectedUsers(List&lt;User&gt; selectedUsers) { this.selectedUsers = selectedUsers; } } </code></pre> <p>i'm getting this error:</p> <pre><code> javax.faces.FacesException: DataModel must implement org.primefaces.model.SelectableDataModel when selection is enabled..... </code></pre>
12,333,887
4
2
null
2012-09-08 19:25:01.107 UTC
9
2019-01-06 15:10:13.953 UTC
null
null
null
null
1,657,164
null
1
37
jsf|primefaces|facelets
92,003
<p>just add this attribute rowKey to the datatable tag :</p> <pre><code>&lt;p:dataTable border="1" value="#{projectAdminisrationMB.projectNoUsersList}" var="userObj" rowKey="#{userObj.name}"selection="#{projectAdminisrationMB.selectedUsers}" selectionMode="multiple" rowIndexVar="rowIndex" binding="#{table2}"&gt; </code></pre>
12,417,197
What is "->" after function declaration?
<p>In one system header file, I see the expression like this:</p> <pre><code>auto create_task(_Ty _Param) -&gt; task&lt;typename details::_TaskTypeFromParam&lt;_Ty&gt;::_Type&gt; {…} </code></pre> <p>I don't know what &quot;-&gt;&quot; means, it isn't pointer expression or lambda expression, can anyone help me?</p>
12,417,204
1
1
null
2012-09-14 02:01:15.77 UTC
8
2021-11-04 00:26:38.557 UTC
2020-11-29 14:11:32.973 UTC
null
5,825,294
null
1,534,282
null
1
39
c++|c++11
4,973
<p>It's the new function declaration syntax from C++11, and it's called the "trailing return type". At the end of a function declaration, <code>-&gt;</code> means that the following is the return type of the function. It can only be used when the <code>auto</code> keyword is used instead of an actual return type where you would normally expect it.</p> <p>For instance, these two declarations are compatible:</p> <pre><code>int foo(); auto foo() -&gt; int; </code></pre> <p>Depending on your tastes, you may find it prettier than the old declaration syntax, especially when the return type is extremely long/complex:</p> <pre><code>task&lt;typename details::_TaskTypeFromParam&lt;_Ty&gt;::_Type&gt; create_task(_Ty _Param); auto create_task(_Ty _Param) -&gt; task&lt;typename details::_TaskTypeFromParam&lt;_Ty&gt;::_Type&gt;; </code></pre> <p>But sometimes it can be necessary with templates, when the return type of the function could vary with the arguments.</p> <p>Say you want a templated function to add variables:</p> <pre><code>template&lt;typename T&gt; T add(const T&amp; x, const T&amp; y) { return x + y; } </code></pre> <p>That's great, but you'll only be able to add variables of the same type. Suppose you would like to be able to add variables of any type (like <code>add((int)1, (double)2)</code>).</p> <pre><code>template&lt;typename T, typename U&gt; ??? add(const T&amp; x, const U&amp; y) { return x + y; } </code></pre> <hr> <p><strong>EDIT</strong>: note that in C++14 and onwards, it's legal to write <code>auto add(const T&amp; x, const U&amp; y)</code>, without a trailing return type, for function <strong>definitions</strong> (in other words, when you define the body of your function).</p> <hr> <p>The problem is that you can't tell in advance what the result type of <code>x + y</code> will be. As templates stand, they could even be non-integral types. (Wouldn't you like to be able to do <code>add(std::string("x"), "y")</code>?)</p> <p><code>Decltype</code>, along with the new function declaration syntax, lets you solve this problem.</p> <pre><code>template&lt;typename T, typename U&gt; auto add(const T&amp; x, const U&amp; y) -&gt; decltype(x + y) { return x + y; } </code></pre> <p><code>Decltype</code> "returns" the type of an expression. Since you need <code>x</code> and <code>y</code> to have been declared for <code>decltype(x + y)</code> to work, you need the new syntax.</p>
12,101,440
'+' (one or more occurrences) not working with 'sed' command
<p>I'm trying to refine my code by getting rid of unnecessary white spaces, empty lines, and having parentheses balanced with a space in between them, so:</p> <pre><code> int a = 4; if ((a==4) || (b==5)) a++ ; </code></pre> <p>should change to:</p> <pre><code> int a = 4; if ( (a==4) || (b==5) ) a++ ; </code></pre> <p>It does work for the brackets and empty lines. However, it forgets to reduce the multiple spaces to one space:</p> <pre><code> int a = 4; if ( (a==4) || (b==5) ) a++ ; </code></pre> <p>Here is my script:</p> <pre><code> #!/bin/bash # Script to refine code # filename=read.txt sed 's/((/( (/g' $filename &gt; new.txt mv new.txt $filename sed 's/))/) )/g' $filename &gt; new.txt mv new.txt $filename sed 's/ +/ /g' $filename &gt; new.txt mv new.txt $filename sed '/^$/d' $filename &gt; new.txt mv new.txt $filename </code></pre> <p>Also, is there a way to make this script more concise, e.g. removing or reducing the number of commands?</p>
12,101,471
6
4
null
2012-08-23 23:40:05.95 UTC
9
2018-10-17 15:11:04.98 UTC
2017-04-15 15:33:46.5 UTC
null
1,033,581
null
792,238
null
1
93
macos|bash|sed
42,308
<p>If you are using <strong>GNU sed</strong> then you need to use <code>sed -r</code> which forces <code>sed</code> to use extended regular expressions, including the wanted behavior of <code>+</code>. See <code>man sed</code>:</p> <pre><code>-r, --regexp-extended use extended regular expressions in the script. </code></pre> <p>The same holds if you are using <strong>OS X sed</strong>, but then you need to use <code>sed -E</code>:</p> <pre class="lang-none prettyprint-override"><code>-E Interpret regular expressions as extended (modern) regular expressions rather than basic regular regular expressions (BRE's). </code></pre>
24,090,637
Open new JFrame with JButton Click - Java Swing
<p>I am trying to open a new JFrame window with a button click event. There is lots of info on this site but nothing that helps me because I think it is not so much the code I have, but the order it is executed (however I am uncertain).</p> <p>This is the code for the frame holding the button that I want to initiate the event:</p> <pre><code>package messing with swing; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.border.EmptyBorder; public class ReportGUI extends JFrame{ //Fields private JButton viewAllReports = new JButton("View All Program Details"); private JButton viewPrograms = new JButton("View Programs and Majors Associated with this course"); private JButton viewTaughtCourses = new JButton("View Courses this Examiner Teaches"); private JLabel courseLabel = new JLabel("Select a Course: "); private JLabel examinerLabel = new JLabel("Select an Examiner: "); private JPanel panel = new JPanel(new GridLayout(6,2,4,4)); private ArrayList&lt;String&gt; list = new ArrayList&lt;String&gt;(); private ArrayList&lt;String&gt; courseList = new ArrayList&lt;String&gt;(); public ReportGUI(){ reportInterface(); allReportsBtn(); examinnerFileRead(); courseFileRead(); comboBoxes(); } private void examinnerFileRead(){ try{ Scanner scan = new Scanner(new File("Examiner.txt")); while(scan.hasNextLine()){ list.add(scan.nextLine()); } scan.close(); } catch (FileNotFoundException e){ e.printStackTrace(); } } private void courseFileRead(){ try{ Scanner scan = new Scanner(new File("Course.txt")); while(scan.hasNextLine()){ courseList.add(scan.nextLine()); } scan.close(); } catch (FileNotFoundException e){ e.printStackTrace(); } } private void reportInterface(){ setTitle("Choose Report Specifications"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); JPanel panel = new JPanel(new FlowLayout()); add(panel, BorderLayout.CENTER); setSize(650,200); setVisible(true); setResizable(false); setLocationRelativeTo(null); } private void allReportsBtn(){ JPanel panel = new JPanel(new GridLayout(1,1)); panel.setBorder(new EmptyBorder(70, 50, 70, 25)); panel.add(viewAllReports); viewAllReports.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e){ JFrame AllDataGUI = new JFrame(); new AllDataGUI(); } }); add(panel, BorderLayout.LINE_END); } private void comboBoxes(){ panel.setBorder(new EmptyBorder(0, 5, 5, 10)); String[] comboBox1Array = list.toArray(new String[list.size()]); JComboBox comboBox1 = new JComboBox(comboBox1Array); panel.add(examinerLabel); panel.add(comboBox1); panel.add(viewTaughtCourses); viewTaughtCourses.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame ViewCourseGUI = new JFrame(); new ViewCourseGUI(); } }); String[] comboBox2Array = courseList.toArray(new String[courseList.size()]); JComboBox comboBox2 = new JComboBox(comboBox2Array); panel.add(courseLabel); panel.add(comboBox2); panel.add(viewPrograms); add(panel, BorderLayout.LINE_START); } </code></pre> <p>If you don't want to delve into the above code, the button ActionListener is here:</p> <pre><code> panel.add(viewTaughtCourses); viewTaughtCourses.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JFrame ViewCourseGUI = new JFrame(); new ViewCourseGUI(); } }); </code></pre> <p>This is the code in the class holding the JFrame I want to open:</p> <pre><code>package messing with swing; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; public class ViewCourseGUI extends JFrame{ private JButton saveCloseBtn = new JButton("Save Changes and Close"); private JButton closeButton = new JButton("Exit Without Saving"); private JFrame frame=new JFrame("Courses taught by this examiner"); private JTextArea textArea = new JTextArea(); public void ViewCoursesGUI(){ panels(); } private void panels(){ JPanel panel = new JPanel(new GridLayout(1,1)); panel.setBorder(new EmptyBorder(5, 5, 5, 5)); JPanel rightPanel = new JPanel(new GridLayout(15,0,10,10)); rightPanel.setBorder(new EmptyBorder(15, 5, 5, 10)); JScrollPane scrollBarForTextArea=new JScrollPane(textArea,JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); panel.add(scrollBarForTextArea); frame.add(panel); frame.getContentPane().add(rightPanel,BorderLayout.EAST); rightPanel.add(saveCloseBtn); rightPanel.add(closeButton); frame.setSize(1000, 700); frame.setVisible(true); frame.setLocationRelativeTo(null); } } </code></pre> <p>Could someone please point me in the right direction?</p>
24,090,736
3
5
null
2014-06-06 21:07:41.11 UTC
1
2016-07-05 05:38:50.107 UTC
2014-06-07 02:09:44.277 UTC
null
418,556
null
2,723,546
null
1
3
java|swing|jframe
42,869
<p>As pointed out by PM 77-3</p> <p>I had:</p> <pre><code> public void ViewCoursesGUI(){ panels(); } </code></pre> <p>When I should have had:</p> <pre><code>public ViewCourseGUI(){ panels(); } </code></pre> <p>A Combination of syntax and spelling errors.</p>
24,422,831
Convert NSSet to Swift Array
<p>In CoreData I have defined an <em>unordered</em> to-many relationship. This relationship is defined in Swift like this:</p> <pre><code>@NSManaged var types : NSMutableSet </code></pre> <p>However, to use Swift at it's best, I want to use a normal Swift array like <code>Type[]</code>. However, CoreData forces me to use <code>NS(Mutable)Set</code>. How can I type-cast / convert the <code>NSSet</code> to <code>Array&lt;Type&gt;[]</code>?</p>
35,091,834
7
6
null
2014-06-26 05:13:58.443 UTC
12
2021-10-03 09:57:41.94 UTC
null
null
null
null
58,107
null
1
66
core-data|swift|ios8
62,460
<p><em>As of Xcode 7.2 with Swift 2.1.1</em></p> <p>Actually, I found out by trial that:</p> <pre><code>@NSManaged var types : Set&lt;Type&gt; </code></pre> <p>Works perfectly fine.</p> <p>The fact is that CoreData generates somethink like:</p> <pre><code>@NSManaged var types : NSSet </code></pre> <p>when creating a <code>NSManagedObject</code> subclass from the editor. So I was wondering if there was a not very verbose method to use the <code>filter</code> method without casting. But then Swift is supposed to bridge automatically between NSSet, NSArray and their counterparts. So I tried declaring it directly as a Set and it works.</p> <p>Answering the question, converting it to an Array becomes trivial:</p> <pre><code>Array(types) </code></pre>
3,946,558
C++: Read from text file and separate into variable
<p>I have this in a text file:</p> <pre><code>John 20 30 40 mike 30 20 10 </code></pre> <p>How do i read from the text file and separate them into variable name, var1, var2, var3. This is my attempt, seems it doesnt work. Help please.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;sstream&gt; using namespace std; int main () { string name,result; int number1; ifstream myfile ("marks.txt"); if (myfile.is_open()) { while ( !myfile.eof() ) { getline (myfile,name,'\t'); getline (myfile,var1,'\t'); getline (myfile,var2,'\t'); getline (myfile,var3,'\t'); cout &lt;&lt; name &lt;&lt; var1 &lt;&lt; var2 &lt;&lt; var3; } myfile.close(); } else cout &lt;&lt; "Unable to open file"; return 0; } </code></pre> <p>EDIT 1:</p> <p>Nocturne Suggestion:</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;sstream&gt; using namespace std; int main() { ifstream inputFile("marks.txt"); string line; while (getline(inputFile, line)) { istringstream ss(line); string name; int var1, var2, var3; ss &gt;&gt; name &gt;&gt; var1 &gt;&gt; var2 &gt;&gt; var3; cout &lt;&lt; name &lt;&lt; var1 &lt;&lt; var2 &lt;&lt; var3 &lt;&lt; endl &lt;&lt; endl; } } </code></pre> <p>output:</p> <pre><code>John203040 mike302010 302010 </code></pre> <p>Why another 302010???</p>
3,946,710
3
3
null
2010-10-15 22:19:58.107 UTC
4
2018-08-18 13:42:11.553 UTC
2010-10-15 23:02:32.87 UTC
null
459,885
null
459,885
null
1
11
c++|string
90,678
<p>Something like this should work (I don't have a compiler handy, so you may need to tweak this a little):</p> <pre><code>#include &lt;iostream&gt; #include &lt;sstream&gt; using namespace std; int main() { ifstream inputFile("marks.txt"); string line; while (getline(inputFile, line)) { istringstream ss(line); string name; int var1, var2, var3; ss &gt;&gt; name &gt;&gt; var1 &gt;&gt; var2 &gt;&gt; var3; } } </code></pre> <p>Edit: Just saw this again, I don’t know why I chose the get line approach earlier. Doesn’t the following (simpler solution) work?</p> <pre><code>#include &lt;fstream&gt; using namespace std; int main() { ifstream fin(“marks.txt”); string name; int var1; int var2; int var3; while (fin &gt;&gt; name &gt;&gt; var1 &gt;&gt; var2 &gt;&gt; var3) { /* do something with name, var1 etc. */ cout &lt;&lt; name &lt;&lt; var1 &lt;&lt; var2 &lt;&lt; var3 &lt;&lt; “\n”; } } </code></pre>
36,827,962
PEP8 – import not at top of file with sys.path
<h1>Problem</h1> <p>PEP8 has a rule about putting imports at the top of a file:</p> <blockquote> <p>Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.</p> </blockquote> <p>However, in certain cases, I might want to do something like:</p> <pre><code>import sys sys.path.insert("..", 0) import my_module </code></pre> <p>In this case, the <code>pep8</code> command line utility flags my code:</p> <blockquote> <p>E402 module level import not at top of file</p> </blockquote> <p>What is the best way to achieve PEP8 compliance with <code>sys.path</code> modifications?</p> <h1>Why</h1> <p>I have this code because I'm following <a href="https://github.com/kennethreitz/samplemod">the project structure</a> given in <a href="http://docs.python-guide.org/en/latest/writing/structure/#structure-of-the-repository">The Hitchhiker's Guide to Python</a>.</p> <p>That guide suggests that I have a <code>my_module</code> folder, separate from a <code>tests</code> folder, both of which are in the same directory. If I want to access <code>my_module</code> from <code>tests</code>, I think I need to add <code>..</code> to the <code>sys.path</code></p>
36,829,884
8
7
null
2016-04-24 19:35:39.46 UTC
26
2021-09-01 22:09:47.863 UTC
null
null
null
null
4,414,003
null
1
108
python|python-3.x|pep8
52,218
<p>Often I have multiple files with tests in a subdirectory <code>foo/tests</code> of my project, while the modules I'm testing are in <code>foo/src</code>. To run the tests from <code>foo/tests</code> without import errors I create a file <code>foo/tests/pathmagic.py</code> that looks like this;</p> <pre><code>"""Path hack to make tests work.""" import os import sys bp = os.path.dirname(os.path.realpath('.')).split(os.sep) modpath = os.sep.join(bp + ['src']) sys.path.insert(0, modpath) </code></pre> <p>In every test file, I then use</p> <pre><code>import pathmagic # noqa </code></pre> <p>as the first import. The "noqa" comment prevents <code>pycodestyle</code>/<code>pep8</code> from complaining about an unused import.</p>
8,850,497
switch / case request with boolean
<p>I'm trying to create a method which checks if the Login (username and password) has a minimum of 6 charakters.</p> <p>To realize that I created this method <code>public void checkLoginData(final String username, final String password)</code>. In that method, I create to booleans (user and pass), with those I can create 4 different boolean-chains:</p> <ul> <li>user: true pass: true</li> <li>user: false pass: true</li> <li>user: false pass: false</li> <li>user: true pass: false</li> </ul> <p>Now I'd like to do a switch/case request for each of them, but I don't get how to realize that...</p> <p>If you ask why I need the switch, I just think I need it, because I'd like to do for every of those 4 boolean-chains, that it does/show something diffrent. Also I'd like to do this in a sexy-java-way not with tousands of diffrent 'ifs' :P, Please help!</p> <p>Here's the code of the method:</p> <pre><code>public void checkLoginData(final String username, final String password){ boolean user, pass; if (username.length() &lt; 6){ user = false; }else { user = true; } if (password.length() &lt; 6){ pass = false; }else { pass = true; } boolean[] logindaten = {user, pass}; } </code></pre> <hr> <p>Thx for the help in Advance!</p> <p>Best Regards safari</p>
8,850,860
8
6
null
2012-01-13 12:21:26.337 UTC
2
2020-11-26 23:48:46.003 UTC
2012-01-13 12:39:12.03 UTC
null
909,003
null
909,003
null
1
14
java|android|boolean|switch-statement
95,665
<p>You can't switch over <code>boolean[]</code>, only over integral types. To convert the booleans to an int, you could use a bit mask for the 2 booleans, like for example this:</p> <pre><code>int val = 0; if (user) val |= 0x1; if (pass) val |= 0x2; switch (val) { case 0: // Both too short case 1: // User Ok, pass too short case 2: // User too short, pass ok case 3: // Both Ok } </code></pre>
26,091,390
PostgreSQL: how to install plpythonu extension
<p>I'm running PostgreSQL 9.3.1 on Ubuntu 12.04.4. I'd like to use the plpython language extension but I get an error when I try to use it I get:</p> <p><code>ERROR: language &quot;plpythonu&quot; does not exist</code></p> <p>When I try to create the extension:</p> <pre class="lang-sql prettyprint-override"><code>CREATE EXTENSION plpythonu </code></pre> <p>I get <code>ERROR: could not access file &quot;$libdir/plpython2&quot;: No such file or directory</code> After much searching and digging through blog posts, I've tried installing additional packages, and have copied all the plpython files from /usr/share/postgresql/9.1/extension to /opt/bitnami/postgresql/share/extension where PostgreSQL seems to be looking for them. That at least got me to a point at which PostgreSQL actually <em>sees</em> the available extensions. When I run:</p> <pre class="lang-sql prettyprint-override"><code>SELECT name, default_version, installed_version FROM pg_available_extensions WHERE name LIKE('plpy*') </code></pre> <p>I get :</p> <pre><code> name | default_version | installed_version ------------+-----------------+------------------- plpython2u | 1.0 | plpython3u | 1.0 | plpythonu | 1.0 | </code></pre> <p>There are still no plpython libraries that I can see in <code>/opt/bitnami/postgresql/lib</code>. Can anybody help me get through remaining steps to make the extension work? Thanks in advance!</p>
26,091,691
3
4
null
2014-09-29 01:31:52.89 UTC
5
2021-09-01 11:58:17.717 UTC
2021-09-01 11:58:17.717 UTC
null
11,154,841
null
1,373,196
null
1
24
python|linux|postgresql|ubuntu
41,722
<p>You're using a PostgreSQL package from Bitnami, in <code>/opt</code>. It's not clear if you installed this with <code>apt-get</code> or via an installer script/program, but in either case it's not the same PostgreSQL as what's in the Ubuntu <code>postgresql</code> package.</p> <p>Installing <code>postgresql-plpython</code> won't do you any good, because you're installing PL/Python support for a different PostgreSQL install than the one you're actually using.</p> <p>You'll need to use the same installation method you originally used to install the Bitnami PostgreSQL to add PL/Python support, if it's available. It might not be provided by Bitnami.</p> <p>Otherwise, if you're not too attached to using Bitnami's PostgreSQL, you could use the recommended packages from <a href="http://apt.postgresql.org/">http://apt.postgresql.org/</a> .</p>
21,999,016
jQuery .removeClass() not working
<p>I need to remove a CSS class from an text field since I want to change its background color. I need to change the color back later, so I have to add and remove classes to the field, depending on some data.</p> <p><code>.addClass</code> is working totally fine. The problem is that the original class is above the added, so the changes are not shown, but the class is added properly. I now try to remove the class which is above the added - but I cant remove any classes from my elements. Why is that? What am I doing wrong? Here's the code:</p> <pre><code>if(i.stadt=="T") { $("#stadtInput").removeClass("ui-input-text input"); $("#stadtInput").removeClass("ui-input-search input"); $("#stadtInput").addClass( 'textboxRight' ); } else { $("#stadtInput").addClass( 'textboxWrong' ); } </code></pre> <p>If I inspect the elements with Webdev-Tools of browser I can see that the <code>textboxRight</code>/<code>textboxWrong</code> class is added, but no class is removed. I already tried to remove all classes by <code>.removeClass()</code>, but that doesn't work either..</p>
21,999,412
6
6
null
2014-02-24 21:08:12.907 UTC
3
2020-12-29 04:44:29.687 UTC
2014-02-24 21:34:02.057 UTC
null
1,725,764
null
2,872,319
null
1
33
jquery|css
89,341
<p>I'm not sure if this will fit your specifications, but the jQuery attr() method will take two arguments and replace all of the classes with the class name your provide. This won't work if you have other classes that you want to keep on your element, but if not try:</p> <pre><code> $("#stadtInput").attr("class", "textboxRight"); </code></pre>
11,230,091
Why's My Root Certificate Not Trusted?
<p>I have issued myself a Code Signing certificate from a certificate server. I have also issued myself the root certificate from the same certificate server. <strong>The root certificate exists in both the Current User and Local Computer certificate stores within the Trusted Root Certification Authorities folder.</strong> I have <strong>successfully</strong> signed a DLL using the signtool.exe wizard:</p> <pre><code>"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\signtool.exe" signwizard &lt;MyDLLName&gt;.dll </code></pre> <p>However, when I try to verify my DLL, it fails verification with the following error:</p> <pre><code>"C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\signtool.exe" verify &lt;MyDLLName&gt;.dll SignTool Error: A certificate chain processed, but terminated in a root certificate which is not trusted by the trust provider. SignTool Error: File not valid: &lt;MyDLLName&gt;.dll </code></pre> <p>Why is this happening? I thought having the root certificate in the Trusted Root Certification Authorities folder would verify the DLL.</p>
11,232,469
1
0
null
2012-06-27 15:41:51.097 UTC
3
2017-01-19 17:12:56.567 UTC
null
null
null
null
982,639
null
1
30
c#|dll|certificate|code-signing|signtool
23,743
<p>On your verify command add in the /pa option to tell it to use the Default Authentication Verification Policy instead of the Windows Driver Verification Policy, meaning it will look at your certificate stores instead of the limited set of CAs Microsoft trusts with drivers.</p> <p>Look here for more options: <a href="http://msdn.microsoft.com/en-us/library/8s9b9yaz(v=vs.90).aspx">http://msdn.microsoft.com/en-us/library/8s9b9yaz(v=vs.90).aspx</a> </p>
11,027,996
success_url in UpdateView, based on passed value
<p>How can I set <code>success_url</code> based on a parameter?<br> I really want to go back to where I came from, not some static place. In pseudo code:</p> <pre><code>url(r'^entry/(?P&lt;pk&gt;\d+)/edit/(?P&lt;category&gt;\d+)', UpdateView.as_view(model=Entry, template_name='generic_form_popup.html', success_url='/category/%(category)')), </code></pre> <p>Which would mean: edit entry <code>pk</code> and then return to 'category'. Here an entry can be part of multiple categories.</p>
11,029,512
5
0
null
2012-06-14 06:44:26.73 UTC
13
2020-09-28 19:40:54.433 UTC
2017-04-07 14:31:13.173 UTC
null
72,350
null
311,364
null
1
39
django|django-class-based-views
43,577
<p>Create a class <code>MyUpdateView</code> inheritted from <code>UpdateView</code> and override <code>get_success_url</code> method:</p> <pre><code>class MyUpdateView(UpdateView): def get_success_url(self): pass #return the appropriate success url </code></pre> <p>Also i like to pass such parameters like template_name and model inside of inheritted class view, but not in <code>.as_view()</code> in urls.py</p>
11,409,075
Postgres error "invalid value for parameter "TimeZone": "UTC""
<pre><code>Jupitor$ bundle exec rake db:create db:migrate APP_development already exists rake aborted! PG::Error: ERROR: invalid value for parameter "TimeZone": "UTC" : SET time zone 'UTC' </code></pre> <p>I keep getting this error when trying to migrate to my postgres database. help would be much appreciated!</p>
12,002,810
16
5
null
2012-07-10 08:06:25.313 UTC
9
2022-08-29 10:49:21.777 UTC
null
null
null
null
1,394,977
null
1
94
ruby-on-rails-3|postgresql
43,538
<p>I had the same problem using the Postgres.app from Heroku. Rebooting my Mac solved it.</p>
12,659,953
Is there a foreground equivalent to background-image in css?
<p>I want to add some shine to an element on webpage. I would prefer if I don't have to add additional html to the page. I want the image to appear in front of the element rather than behind. What's the best way to do this?</p>
12,660,106
5
4
null
2012-09-30 08:50:08.623 UTC
9
2022-03-14 06:32:20.85 UTC
2012-09-30 09:23:07.487 UTC
null
938,089
null
350,080
null
1
61
html|css|foreground
83,160
<p>To achieve a &quot;foreground image&quot; (without extra HTML code), you can use a pseudo-element (<code>::before</code> / <code>:before</code>) <strong>plus the CSS <a href="https://developer.mozilla.org/en-US/docs/CSS/pointer-events" rel="nofollow noreferrer"><code>pointer-events</code></a></strong>. The last property is needed so that the user can actually click through the layer &quot;as if it did not exist&quot;.</p> <p>Here's an example (using a colour whose alpha channel is 50% so that you can see that the real elements can actually be focused). <a href="http://jsfiddle.net/JxNdT/" rel="nofollow noreferrer">http://jsfiddle.net/JxNdT/</a></p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>#cont { width: 200px; height: 200px; border: 1px solid #aaa; /*To show the boundaries of the element*/ } #cont:before { position: absolute; content: ''; background: rgba(0, 0, 0, 0.5); width: 200px; height: 200px; pointer-events: none; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="cont"&gt; Test&lt;br&gt; &lt;input type="text" placeholder="edit"&gt; &lt;/div&gt;</code></pre> </div> </div> </p> <p>​ PS. I picked the <code>::before</code> pseudo-element, because that naturally leads to the correct positioning. If I pick <code>::after</code>, then I have to add <code>position:relative;</code> to the real element (<code>#cont</code>), and <code>top:0;left:0;</code> to the pseudo-element (<code>::after</code>).</p> <hr /> <p>PPS. To get the <strong>foreground effect on elements without a fixed size</strong>, an additional element is needed. This wrapper element requires the <code>position:relative;display:inline-block;</code> styles. Set the <code>width</code> and <code>height</code> of the pseudo-element to <code>100%</code>, and the pseudo-element will stretch to the width and height of the wrapper element. Demo: <a href="http://jsfiddle.net/JxNdT/1/" rel="nofollow noreferrer">http://jsfiddle.net/JxNdT/1/</a>.</p>
16,840,554
Reading a Line From File Without Advancing [Pythonic Approach]
<p>What's a pythonic approach for reading a line from a file but not advancing where you are in the file?</p> <p>For example, if you have a file of </p> <pre><code>cat1 cat2 cat3 </code></pre> <p>and you do <code>file.readline()</code> you will get <code>cat1\n</code> . The next <code>file.readline()</code> will return <code>cat2\n</code> .</p> <p>Is there some functionality like <code>file.some_function_here_nextline()</code> to get <code>cat1\n</code> then you can later do <code>file.readline()</code> and get back <code>cat1\n</code>?</p>
16,840,747
5
0
null
2013-05-30 15:48:18.703 UTC
3
2020-07-13 09:53:31.637 UTC
2015-06-09 10:42:19.343 UTC
null
1,609,276
null
1,431,282
null
1
33
python
20,943
<p>As far as I know, there's no builtin functionality for this, but such a function is easy to write, since most Python <code>file</code> objects support <code>seek</code> and <code>tell</code> methods for jumping around within a file. So, the process is very simple: </p> <ul> <li>Find the current position within the file using <code>tell</code>.</li> <li>Perform a <code>read</code> (or <code>write</code>) operation of some kind.</li> <li><code>seek</code> back to the previous file pointer.</li> </ul> <p>This allows you to do nice things like read a chunk of data from the file, analyze it, and then potentially overwrite it with different data. A simple wrapper for the functionality might look like:</p> <pre><code>def peek_line(f): pos = f.tell() line = f.readline() f.seek(pos) return line print peek_line(f) # cat1 print peek_line(f) # cat1 </code></pre> <hr> <p>You could implement the same thing for other <code>read</code> methods just as easily. For instance, implementing the same thing for <code>file.read</code>:</p> <pre><code>def peek(f, length=1): pos = f.tell() data = f.read(length) # Might try/except this line, and finally: f.seek(pos) f.seek(pos) return data print peek(f, 4) # cat1 print peek(f, 4) # cat1 </code></pre>
16,890,582
Unix:merge multiple CSV files with same header by keeping the header of the first file
<p>I have to merge multiple CSV files with same headers. I have to keep the header of the first file and remove headers of all the other files and merge them and create one master file.</p> <p>file 1:</p> <pre><code>Id,city,name ,location 1,NA,JACK,CA </code></pre> <p>file 2:</p> <pre><code>ID,city,name,location 2,NY,JERRY,NY </code></pre> <p>output:</p> <pre><code>Id,city,name,location 1,NA,JACK,CA 2,NY,JERRY,NY </code></pre> <p>Currently I am using this code:</p> <pre><code>ls *.csv | xargs -n 1 tail -n+2 &gt; master.csv </code></pre> <p>This code will merge the files perfectly , but as I need the header of the first file, this will not give me the header.</p> <p>What should I do?</p>
16,890,695
4
1
null
2013-06-03 05:38:47.827 UTC
24
2020-10-29 19:32:56.037 UTC
2013-06-03 05:57:26.31 UTC
null
23,897
null
2,376,510
null
1
35
unix|csv
27,909
<pre><code>awk 'FNR==1 &amp;&amp; NR!=1{next;}{print}' *.csv </code></pre> <p>tested on solaris unix:</p> <pre><code>&gt; cat file1.csv Id,city,name ,location 1,NA,JACK,CA &gt; &gt; cat file2.csv ID,city,name,location 2,NY,JERRY,NY &gt; &gt; nawk 'FNR==1 &amp;&amp; NR!=1{next;}{print}' *.csv Id,city,name ,location 1,NA,JACK,CA 2,NY,JERRY,NY &gt; </code></pre> <p>Explanation given by <a href="https://stackoverflow.com/users/353308">kevin-d</a>:</p> <blockquote> <p>FNR is the number of lines (records) read so far in the current file. NR is the number of lines read overall. So the condition 'FNR==1 &amp;&amp; NR!=1{next;}' says, "Skip this line if it's the first line of the current file, and at least 1 line has been read overall." This has the effect of printing the CSV header of the first file while skipping it in the rest.</p> </blockquote> <p><a href="https://www.thegeekstuff.com/2011/06/awk-nawk-gawk/" rel="noreferrer">Link</a> for the difference between <a href="/questions/tagged/awk" class="post-tag" title="show questions tagged &#39;awk&#39;" rel="tag">awk</a> and <a href="/questions/tagged/nawk" class="post-tag" title="show questions tagged &#39;nawk&#39;" rel="tag">nawk</a></p>
16,976,904
Javascript counting number of objects in object
<p>I have an object something like:</p> <pre><code>Object {0=Object, 1=Object, 2=Object} // Output from console.log(obj.Data); </code></pre> <p>But there is no way that I can count the number of objects in object, then finally get the attribute value from the sub objects.</p> <p>I have tried</p> <pre><code>console.log(obj.Data[0].length); // It does not work console.log(obj.Data.length); // It does not work </code></pre> <p>This is a bit tricky for me. Hope you guys can help. </p>
16,976,927
3
3
null
2013-06-07 05:35:36.437 UTC
23
2013-06-07 07:37:15.71 UTC
null
null
null
null
2,365,196
null
1
103
javascript|object|count
224,362
<p>The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either <a href="http://lodash.com/" rel="noreferrer">Lo-Dash</a> or <a href="http://underscorejs.org/" rel="noreferrer">Underscore</a> in your page.</p> <p>Then you can use either <code>_.size(object)</code> or <code>_.keys(object).length</code></p> <p>For your <code>obj.Data</code>, you could test this with:</p> <pre><code>console.log( _.size(obj.Data) ); </code></pre> <p>or:</p> <pre><code>console.log( _.keys(obj.Data).length ); </code></pre> <p>Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)</p> <p>Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:</p> <pre><code>function ObjectLength( object ) { var length = 0; for( var key in object ) { if( object.hasOwnProperty(key) ) { ++length; } } return length; }; </code></pre> <p>You can test this with:</p> <pre><code>console.log( ObjectLength(obj.Data) ); </code></pre> <p>That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:</p> <pre><code>function ObjectLength_Modern( object ) { return Object.keys(object).length; } function ObjectLength_Legacy( object ) { var length = 0; for( var key in object ) { if( object.hasOwnProperty(key) ) { ++length; } } return length; } var ObjectLength = Object.keys ? ObjectLength_Modern : ObjectLength_Legacy; </code></pre> <p>and as before, test it with:</p> <pre><code>console.log( ObjectLength(obj.Data) ); </code></pre> <p>This code uses <code>Object.keys(object).length</code> in modern browsers and falls back to counting in a loop for old browsers.</p> <p>But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.</p> <p>I set up a <a href="http://jsperf.com/counting-object-properties" rel="noreferrer">jsPerf that compares the speed of these various approaches</a>. Please run it in any browsers you have handy to add to the tests.</p> <p>Thanks to <a href="https://stackoverflow.com/users/1491895/barmar">Barmar</a> for <a href="https://stackoverflow.com/a/16976940/1202830">suggesting <code>Object.keys</code> for newer browsers</a> in his answer.</p>
20,578,474
Permission Denial: this requires android.permission.INTERACT_ACROSS_USERS_FULL
<p>I am having an issue with sqlite db in Android. But as I made a quick research on the internet, I suspect that the problem is not related to sqlite but system user. My app is not recognized as authorized user to access db functionalities. I tried to apply possible suggested solutions in stack overflow but none of them made a difference. This is the LogCat I am facing every time I attempt to use db functionality. </p> <pre><code>12-14 02:35:17.721 2953-3355/? E/DatabaseUtils﹕ Writing exception to parcel java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL at com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:13082) at android.app.ActivityManager.handleIncomingUser(ActivityManager.java:2038) at com.android.providers.settings.SettingsProvider.callFromPackage(SettingsProvider.java:577) at android.content.ContentProvider$Transport.call(ContentProvider.java:279) at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:273) at android.os.Binder.execTransact(Binder.java:388) at dalvik.system.NativeStart.run(Native Method) </code></pre> <p>I tried to add permission</p> <pre><code>android.permission.INTERACT_ACROSS_USERS_FULL </code></pre> <p>but still no sound. The strange thing is when I try to add INTERNET permission Android Studio 0.3 (ide I use) suggests me possible permissions I can choose. But when it comes to INTERACT_ACROSS_USERS_FULL permission it behaves like it has no idea about this permission. My test device is Samsung S4 running on 4.3.</p> <p>I assume that I am not the only one who tries to use db on android. So there is a solution. </p> <p>How can I really add INTERACT_ACROSS_USERS_FULL permission to my application?</p>
21,825,156
5
8
null
2013-12-14 00:57:40.507 UTC
5
2019-01-15 10:44:47.89 UTC
null
null
null
null
2,160,546
null
1
36
android|sqlite|permissions|user-permissions
55,595
<p>According to this answer: <a href="https://stackoverflow.com/a/19756762/713354"><code>android.permission.INTERACT_ACROSS_USERS_FULL</code> is a signature level permission.</a> Your app will not be able to use it until and unless it has the same signature as the system.</p> <p>Which is not something you can achieve unless you either are the creator or the system build, or collaborating with them such that they are willing to sign your apk with their certificate. In other words, this is off limits for most developers.</p>
68,237,292
Xcode "Manage Version and Build Number" option
<p>I have just updated to Xcode 13 Beta and I am about to upload my first build to App Store using this version of Xcode. This version of Xcode shows a new App Store Connect distribution option which I previously haven't seen:</p> <blockquote> <p>Manage Version and Build Number</p> <p>This will change the version and build number of all content in your app to 1.2 (3).</p> </blockquote> <p><a href="https://i.stack.imgur.com/gkcfm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gkcfm.png" alt="enter image description here" /></a></p> <p>I have already increased my version and build number from Xcode before archiving. What should we do here? If it is an automated way of build increment, what are the benefits of using it?</p>
68,238,065
3
3
null
2021-07-03 14:48:06.147 UTC
7
2022-07-25 08:31:50.717 UTC
2022-04-14 20:40:23.63 UTC
null
1,265,393
null
3,009,341
null
1
60
ios|xcode|app-store|app-store-connect
12,403
<blockquote> <p>I have already increased my version and build number from Xcode before archiving. What should we do here?</p> </blockquote> <p>If you are sure that you have already updated your version/build number before archiving, then you can uncheck this and this will be ignored.</p> <blockquote> <p>If it is an automated way of build increment, what are the benefits of using it?</p> </blockquote> <ol> <li><p>It provides you a chance to change <code>version</code>/<code>build</code> just in case you forgot about it. There was no indication for this in previous Xcode versions.</p> </li> <li><p>It allows you to change <code>version</code>/<code>build</code> number before export/upload (<strong>after archiving</strong>), previously you had to create a new archive if you wanted to change the <code>version</code>/<code>build</code> number.</p> </li> </ol>
10,218,722
Why do you have to pass the event object as a parameter?
<p>I'm learning how to manipulate events in JavaScript and I'm wondering &quot;why do you have to pass the event object as a parameter (argument) into a function when using event handling?&quot;</p> <p>Here's an example of what I am talking about:</p> <pre><code>&lt;script type=&quot;text/javascript&quot;&gt; document.getElementById('button_1').onclick = (function (event) { alert(&quot;The event is: &quot; + &quot;on&quot; + event.type); }); &lt;/script&gt; </code></pre> <p>I wrote the code above and I pretty much understand what it does. I just don't understand the whole (event) passing. I thought of this as a way of assigning an anonymous function to the <code>button_1.onclick</code> event handler. Does the event handler try to pass in an event before it gets assigned or?... I'm having a difficult time understanding this. If someone could please clarify this for me I would be grateful.</p> <p><em>[I tried searching it on Google but found very complex explanations and examples. Only a simple-to-intermediate explanation would help.]</em> =)</p>
10,218,767
5
0
null
2012-04-18 22:02:05.353 UTC
9
2022-06-21 15:45:12.777 UTC
2022-06-21 15:45:12.777 UTC
null
4,370,109
null
1,140,038
null
1
10
javascript|events|event-handling|dom-events
8,026
<h3>The Ever-Present Event, Whether You Like it or Not</h3> <p>The event is always present, even when you don't provide a name:</p> <pre><code>$(".foo").on("click", function(){ alert( arguments[0].type ); }); </code></pre> <p>That is the same as saying this:</p> <pre><code>$(".foo").on("click", function(event){ alert( event.type ); }); </code></pre> <p><em>The event object is already being passed to your callback</em> (whether your provide a name for it or not), you can choose to not use it if you like. For instance, if we looked to a jQuery onClick method:</p> <pre><code>$(".foo").on("click", function(){ /* Do stuff */ }); </code></pre> <h3>Making Use of It</h3> <p>You'll note that I have no event object referenced in my callback. I'm not required to. However, if I want to use it, for whatever purpose, I should give it a name:</p> <pre><code>$(".foo").on("click", function(myEvent){ myEvent.preventDefault(); myEvent.stopPropagation(); }); </code></pre> <p>Now that I have granted myself access to the event details, I can prevent the default behavior that would result from the event, and I can also stop the event from bubbling up the DOM to other elements.</p> <h3>Practical Example</h3> <p>Suppose we wanted to listen for click events on an element:</p> <pre><code>$("#bigSquare").on("click", function(event){ /* Do something */ }); </code></pre> <p>Click events happen on an element when you click the element itself, or any of its children. Now suppose this element had two children:</p> <pre><code>&lt;div id="bigSquare"&gt; &lt;div id="redSquare"&gt;&lt;/div&gt; &lt;div id="blueSquare"&gt;&lt;/div&gt; &lt;/div&gt; </code></pre> <p>Clicking any of these, the big square, the red square, or the blue square will cause the "click" event on the big square - after it causes the click event on whichever element you clicked first (events bubble up the DOM).</p> <p>We could determine which element was the target in any click event via the event itself:</p> <pre><code>$("#bigSquare").on("click", function(event){ alert( event.target.id ); }); </code></pre> <p>Note here how we're accessing the ID of the target that raised the event. If you click on the red square, when that event bubbles up to the big square, we will see alerted "redSquare". The same goes for the blue square. If you click that, the event will bubble up to the big square and we will see alerted "blueSquare".</p> <p>You can test this online via the following demo: <a href="http://jsbin.com/ejekim/edit#javascript,live" rel="noreferrer">http://jsbin.com/ejekim/edit#javascript,live</a></p> <p>Try clicking the orange, red, or blue square to see what is alerted.</p>
10,055,913
set timeout for socket receive
<p>I want to send data to server, then wait for an answer for one minute and then close the socket.</p> <p>How to do it?</p> <pre><code> DatagramPacket sendpack = new ......; socket.send(pack); DatagramPacket recievepack = new .....; //wait 1 minute{ socket.recieve(buf); //wait 1 minute} socket.close(); </code></pre>
10,056,866
3
2
null
2012-04-07 15:54:54.73 UTC
5
2017-07-28 18:34:37.86 UTC
2012-05-25 15:41:46.603 UTC
null
67,097
null
964,645
null
1
12
java|sockets|timeout|udp
49,666
<p>You can try this. Change the timeout of the socket as required in your scenario! This code will send a message and then wait to receive messages until the timeout is reached!</p> <pre><code>DatagramSocket s; try { s = new DatagramSocket(); byte[] buf = new byte[1000]; DatagramPacket dp = new DatagramPacket(buf, buf.length); InetAddress hostAddress = InetAddress.getByName("localhost"); String outString = "Say hi"; // message to send buf = outString.getBytes(); DatagramPacket out = new DatagramPacket(buf, buf.length, hostAddress, 9999); s.send(out); // send to the server s.setSoTimeout(1000); // set the timeout in millisecounds. while(true){ // recieve data until timeout try { s.receive(dp); String rcvd = "rcvd from " + dp.getAddress() + ", " + dp.getPort() + ": "+ new String(dp.getData(), 0, dp.getLength()); System.out.println(rcvd); } catch (SocketTimeoutException e) { // timeout exception. System.out.println("Timeout reached!!! " + e); s.close(); } } } catch (SocketException e1) { // TODO Auto-generated catch block //e1.printStackTrace(); System.out.println("Socket closed " + e1); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } </code></pre>
10,113,097
Invalid Pointer Operation - Delphi XE
<p>I can't seem to figure this one out. My program compiles and runs successfully, but during debugging only it pops up a message box saying "Invalid Pointer Operation" when shutting the program down. I have painstakingly checked all the FormCloseQuery and FormDestory events for any syntax or logical error. I found none and they execute as expected without any error. </p> <p><img src="https://i.stack.imgur.com/3Es5T.png" alt="enter image description here"></p> <p>When I do tell the compiler to break at Invalid Pointer Operation error, it doesn't do anything but hangs up the program. At which point, I had to terminate or kill the process.</p> <p>How do you figure this one out?</p> <p>Thanks in advance,</p>
10,113,467
4
10
null
2012-04-11 20:04:27.95 UTC
4
2016-09-23 21:07:22.787 UTC
2015-01-13 10:37:00.353 UTC
null
2,932,052
null
639,464
null
1
13
delphi|debugging|exception|delphi-xe
38,150
<p>An Invalid Pointer exception is thrown by the memory manager when it tries to free invalid memory. There are three ways this can happen.</p> <p>The most common is because you're trying to free an object that you've already freed. If you turn on FastMM's FullDebugMode, it will detect this and point you directly to the problem. (But make sure to build a map file so it will have the information it needs to create useful stack traces from.)</p> <p>The second way is if you're trying to free memory that was allocated somewhere other than the memory manager. I've seen this a few times when passing a <strong>string</strong> from a Delphi EXE to a Delphi DLL that wasn't using the shared memory manager feature.</p> <p>And the third way involves messing around with pointers directly and probably doesn't apply to you. If you try to <code>FreeMem</code> or <code>Dispose</code> a bad pointer that doesn't refer to an actual block of memory allocated by FastMM, you'll get this error.</p> <p>It's most likely the first one. Use FullDebugMode and you'll find the source of the problem easily.</p>
10,255,790
Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied
<p>I just installed IIS on Windows XP.</p> <p>When I try to execute an app, I get an error:</p> <blockquote> <p>Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.</p> <p>Exception Details: System.UnauthorizedAccessException: Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied.</p> <p>ASP.NET is not authorized to access the requested resource. Consider granting access rights to the resource to the ASP.NET request identity. ASP.NET has a base process identity (typically {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6) that is used if the application is not impersonating. If the application is impersonating via , the identity will be the anonymous user (typically IUSR_MACHINENAME) or the authenticated request user.</p> <p>To grant ASP.NET access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.</p> <p>Source Error:</p> <p>Line 70: Protected Sub cmbSettingFiles_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles cmbSettingFiles.SelectedIndexChanged<br> Line 71: Dim doc As XmlDocument = New XmlDocument()<br> Line 72: doc.Load(Path.Combine(basePath, cmbSettingFiles.SelectedValue)) Line 74: Dim settingsNode As XmlNode = doc.SelectSingleNode("/settings")</p> <p>Source File: C:\myapp\install\install.aspx.vb Line: 72 </p> </blockquote> <p>I have tried grating permission by doing this:</p> <blockquote> <p>To grant ASP.NET access to a file, right-click the file in Explorer, choose "Properties" and select the Security tab. Click "Add" to add the appropriate user or group. Highlight the ASP.NET account, and check the boxes for the desired access.</p> </blockquote> <p>But the error persists.</p> <p>Does this have anything to do with my code?</p> <p>How can I resolve this?</p> <p><strong>EDIT</strong></p> <p>I have solved the problem on my dev machine, but I am still getting the error on my web server.</p> <p>Thanks.</p>
10,257,235
13
1
null
2012-04-21 02:56:52.533 UTC
11
2021-09-17 04:31:48.84 UTC
2017-07-10 21:30:17.457 UTC
null
8,166,701
null
362,461
null
1
23
asp.net|iis|access-denied
125,964
<blockquote> <p>Try to go to App_Data folder property and add ASPNET user with read and write privileges</p> </blockquote> <p>Ref:<br> <a href="http://www.afterlogic.com/kb/articles/how-to-assign-correct-permissions-to-appdata-folder-of-webmail-pro-aspnet" rel="noreferrer">How to assign correct permissions to App_Data folder of WebMail Pro ASP.NET</a><br> <a href="http://forums.asp.net/t/920414.aspx/1" rel="noreferrer">Permissions on APP_DATA Folder</a><br> <a href="https://serverfault.com/questions/14655/asp-asp-net-best-way-to-handle-write-permissions">ASP/ASP.NET Best way to handle write permissions?</a></p> <p>If it does not solve your problem then check whether your XML files are not open by another thread using these configuration files.. and provide some more details if still persists.</p>
9,780,038
Is it possible to block Tor users?
<p>Would it be possible to block Tor users? (<a href="https://www.torproject.org/" rel="noreferrer">https://www.torproject.org/</a>)</p> <p>Due to the nature of the site I run I should do all I can to stop multiple accounts and block certain locations. Tor is worse than proxies - a total nightmare...</p>
9,861,102
15
0
null
2012-03-20 00:51:32.48 UTC
21
2021-09-27 16:35:23.367 UTC
2016-11-28 13:03:52.613 UTC
null
63,550
null
997,407
null
1
42
tor
84,290
<p>Tor is much easier to block than other open proxies since the list of exit IP addresses is known and published. Read the answer at <a href="https://www.torproject.org/docs/faq-abuse.html.en#Bans" rel="noreferrer">https://www.torproject.org/docs/faq-abuse.html.en#Bans</a> and if you still want to block users from accessing your site you could use <a href="https://www.torproject.org/projects/tordnsel.html.en" rel="noreferrer">https://www.torproject.org/projects/tordnsel.html.en</a> or the Bulk Exit List exporting tool. </p> <p>If you use the Bulk Exit List exporting tool be sure to get a fresh list often and expire the old blocks since the list of IP addresses change. </p>
27,928,372
React-router URLs don't work when refreshing or writing manually
<p>I'm using React-router and it works fine while I'm clicking on link buttons, but when I refresh my webpage it does not load what I want.</p> <p>For instance, I am in <code>localhost/joblist</code> and everything is fine because I arrived here pressing a link. But <em>if</em> I refresh the webpage I get:</p> <pre class="lang-none prettyprint-override"><code>Cannot GET /joblist </code></pre> <p>By default, it didn't work like this. Initially I had my URL as <code>localhost/#/</code> and <code>localhost/#/joblist</code> and they worked perfectly fine. But I don't like this kind of URL, so trying to erase that <code>#</code>, I wrote:</p> <pre><code>Router.run(routes, Router.HistoryLocation, function (Handler) { React.render(&lt;Handler/&gt;, document.body); }); </code></pre> <p>This problem does not happen with <code>localhost/</code>, this one always returns what I want.</p> <p>This app is single-page, so <code>/joblist</code> doesn't need to ask anything to any server.</p> <p>My entire router.</p> <pre><code>var routes = ( &lt;Route name=&quot;app&quot; path=&quot;/&quot; handler={App}&gt; &lt;Route name=&quot;joblist&quot; path=&quot;/joblist&quot; handler={JobList}/&gt; &lt;DefaultRoute handler={Dashboard}/&gt; &lt;NotFoundRoute handler={NotFound}/&gt; &lt;/Route&gt; ); Router.run(routes, Router.HistoryLocation, function (Handler) { React.render(&lt;Handler/&gt;, document.body); }); </code></pre>
36,623,117
54
5
null
2015-01-13 17:51:54.14 UTC
629
2022-07-18 07:05:50.727 UTC
2022-05-06 13:49:05.883 UTC
null
63,550
null
4,377,851
null
1
1,112
javascript|reactjs|url|react-router
683,828
<h3>Server-side vs Client-side</h3> <p>The first big thing to understand about this is that there are now 2 places where the URL is interpreted, whereas there used to be only 1 in 'the old days'. In the past, when life was simple, some user sent a request for <code>http://example.com/about</code> to the server, which inspected the path part of the URL, determined the user was requesting the about page, and then sent back that page.</p> <p>With client-side routing, which is what React Router provides, things are less simple. At first, the client does not have any JavaScript code loaded yet. So the very first request will always be to the server. That will then return a page that contains the needed script tags to load React and React Router, etc. Only when those scripts have loaded does phase 2 start. In phase 2, when the user clicks on the 'About us' navigation link, for example, the URL is changed <em>locally only</em> to <code>http://example.com/about</code> (made possible by the <a href="https://developer.mozilla.org/en-US/docs/Web/API/History_API" rel="noreferrer">History API</a>), but <strong>no request to the server is made</strong>. Instead, React Router does its thing on the client-side, determines which React view to render, and renders it. Assuming your about page does not need to make any <a href="https://en.wikipedia.org/wiki/Representational_state_transfer" rel="noreferrer">REST</a> calls, it's done already. You have transitioned from <em>Home</em> to <em>About Us</em> without any server request having fired.</p> <p>So basically when you click a link, some JavaScript runs that manipulates the URL in the address bar, <em>without causing a page refresh</em>, which in turn causes React Router to perform a page transition <strong>on the client-side</strong>.</p> <p>But now consider what happens if you copy-paste the URL in the address bar and e-mail it to a friend. Your friend has not loaded your website yet. In other words, she is still in <em>phase 1</em>. No React Router is running on her machine yet. So her browser will make a <strong>server request</strong> to <code>http://example.com/about</code>.</p> <p>And this is where your trouble starts. Until now, you could get away with just placing a static HTML at the webroot of your server. But that would give <em>404</em> errors for all other URLs <em>when requested from the server</em>. Those same URLs work fine <em>on the client-side</em>, because there React Router is doing the routing for you, but they fail <em>on the server-side</em> unless you make your server understand them.</p> <h3>Combining server- and client-side routing</h3> <p>If you want the <code>http://example.com/about</code> URL to work on both the server- and the client-side, you need to set up routes for it on both the server- and the client-side. It makes sense, right?</p> <p>And this is where your choices begin. Solutions range from bypassing the problem altogether, via a catch-all route that returns the bootstrap HTML, to the full-on isomorphic approach where both the server and the client run the same JavaScript code.</p> <h2>Bypassing the problem altogether: Hash History</h2> <p>With <a href="https://github.com/jintoppy/react-training/blob/master/basic/node_modules/react-router/docs/guides/Histories.md#hashhistory" rel="noreferrer">Hash History</a>, instead of <a href="https://github.com/jintoppy/react-training/blob/master/basic/node_modules/react-router/docs/guides/Histories.md#browserhistory" rel="noreferrer">Browser History</a>, your URL for the about page would look something like this: <code>http://example.com/#/about</code></p> <p>The part after the hash (<code>#</code>) symbol is not sent to the server. So the server only sees <code>http://example.com/</code> and sends the index page as expected. React Router will pick up the <code>#/about</code> part and show the correct page.</p> <p><strong>Downsides</strong>:</p> <ul> <li>'ugly' URLs</li> <li>Server-side rendering is not possible with this approach. As far as <a href="https://en.wikipedia.org/wiki/Search_engine_optimization" rel="noreferrer">search engine optimization</a> (SEO) is concerned, your website consists of a single page with hardly any content on it.</li> </ul> <h2>Catch-all</h2> <p>With this approach, you do use the Browser History, but just set up a catch-all on the server that sends <code>/*</code> to <code>index.html</code>, effectively giving you much the same situation as with Hash History. You do have clean URLs however and you could improve upon this scheme later without having to invalidate all your user's favorites.</p> <p><strong>Downsides</strong>:</p> <ul> <li>More complex to set up</li> <li>Still no good SEO</li> </ul> <h2>Hybrid</h2> <p>In the hybrid approach, you expand upon the catch-all scenario by adding specific scripts for specific routes. You could make some simple PHP scripts to return the most important pages of your site with content included, so Googlebot can at least see what's on your page.</p> <p><strong>Downsides</strong>:</p> <ul> <li>Even more complex to set up</li> <li>Only good SEO for those routes you give the special treatment</li> <li>Duplicating code for rendering content on server and client</li> </ul> <h2>Isomorphic</h2> <p>What if we use <a href="https://en.wikipedia.org/wiki/Node.js" rel="noreferrer">Node.js</a> as our server so we can run <em>the same</em> JavaScript code on both ends? Now, we have all our routes defined in a single react-router configuration and we don't need to duplicate our rendering code. This is 'the holy grail' so to speak. The server sends the exact same markup as we would end up with if the page transition had happened on the client. This solution is optimal in terms of SEO.</p> <p><strong>Downsides</strong>:</p> <ul> <li>Server <em>must</em> (be able to) run JavaScript. I've experimented with Java in conjunction with <a href="https://en.wikipedia.org/wiki/Nashorn_(JavaScript_engine)" rel="noreferrer">Nashorn</a>, but it's not working for me. In practice, it mostly means you must use a Node.js based server.</li> <li>Many tricky environmental issues (using <code>window</code> on server-side, etc.)</li> <li>Steep learning curve</li> </ul> <h3>Which should I use?</h3> <p>Choose the one that you can get away with. Personally, I think the catch-all is simple enough to set up, so that would be my minimum. This setup allows you to improve on things over time. If you are already using Node.js as your server platform, I'd definitely investigate doing an isomorphic app. Yes, it's tough at first, but once you get the hang of it it's actually a very elegant solution to the problem.</p> <p>So basically, for me, that would be the deciding factor. If my server runs on Node.js, I'd go isomorphic; otherwise, I would go for the Catch-all solution and just expand on it (Hybrid solution) as time progresses and SEO requirements demand it.</p> <p>If you'd like to learn more about isomorphic (also called 'universal') rendering with React, there are some good tutorials on the subject:</p> <ul> <li><a href="https://www.smashingmagazine.com/2015/04/react-to-the-future-with-isomorphic-apps/" rel="noreferrer">React to the future with isomorphic apps</a></li> <li><a href="https://reactjsnews.com/isomorphic-react-in-real-life" rel="noreferrer">The Pain and the Joy of creating isomorphic apps in ReactJS</a></li> <li><a href="https://strongloop.com/strongblog/node-js-react-isomorphic-javascript-why-it-matters/" rel="noreferrer">How to Implement Node + React Isomorphic JavaScript &amp; Why it Matters</a></li> </ul> <p>Also, to get you started, I recommend looking at some starter kits. Pick one that matches your choices for the technology stack (remember, React is just the V in <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller" rel="noreferrer">MVC</a>, you need more stuff to build a full app). Start with looking at the one published by Facebook itself:</p> <ul> <li><a href="https://github.com/facebookincubator/create-react-app" rel="noreferrer">Create React App</a></li> </ul> <p>Or pick one of the many by the community. There is a nice site now that tries to index all of them:</p> <ul> <li><a href="http://andrewhfarmer.com/starter-project/" rel="noreferrer">Pick your perfect React starter project</a></li> </ul> <p>I started with these:</p> <ul> <li><a href="https://github.com/RickWong/react-isomorphic-starterkit" rel="noreferrer">React Isomorphic Starterkit</a></li> <li><a href="https://github.com/erikras/react-redux-universal-hot-example" rel="noreferrer">React Redux Universal Hot Example</a></li> </ul> <p>Currently, I am using a homebrewed version of universal rendering that was inspired by the two starter kits above, but they are out of date now.</p> <p>Good luck with your quest!</p>
9,705,982
pythonw.exe or python.exe?
<p>Long story short: <code>pythonw.exe</code> does nothing, <code>python.exe</code> accepts nothing (which one should I use?)</p> <p>test.py:</p> <pre><code>print "a" </code></pre> <p>CMD window:</p> <pre><code>C:\path&gt;pythonw.exe test.py &lt;BLANK LINE&gt; C:\path&gt; C:\path&gt;python.exe test.py File "C:\path\test.py", line 7 print "a" ^ SyntaxError: invalid syntax C:\path&gt; </code></pre> <p>Please tell me what I'm doing terrible wrong.</p>
9,706,045
6
1
null
2012-03-14 16:30:07.957 UTC
72
2021-07-04 02:30:41.557 UTC
2013-03-12 20:53:36.8 UTC
null
42,346
null
945,873
null
1
191
python|python-3.x
252,713
<p>If you don't want a terminal window to pop up when you run your program, use <code>pythonw.exe</code>;<br> Otherwise, use <code>python.exe</code></p> <p>Regarding the syntax error: <code>print</code> <a href="http://www.python.org/dev/peps/pep-3105/" rel="noreferrer">is now a function in 3.x</a><br> So use instead: </p> <pre><code>print("a") </code></pre>
7,872,578
How to properly use qRegisterMetaType on a class derived from QObject?
<p>I've been searching far and wide for an answer to this but to no avail. My lament is as follows:</p> <p>I have a <code>ClassA</code> that roughly looks like this:</p> <pre><code>class ClassA : public QObject { Q_OBJECT public: ClassA() { mName = "lol"; } ~ClassA(); void ShowName() { std::cout &lt;&lt; mName &lt;&lt; std::endl; } std::string mName; }; </code></pre> <p>Of course, since I use moc, this class is actually split into cpp and hpp in my project but that part is not the issue here.</p> <p>Please note that I do not use <code>Q_DECLARE_METATYPE</code> on purpose because I don't actually need its features (QVariant expansion) right now. I only care about runtime instantiation.</p> <p>The issue here is that <code>Q_OBJECT</code> forbids the copy and assignment constructors. Due to that, I have to apply <code>qRegisterMetaType</code> not to <code>ClassA</code> itself but to <code>ClassA*</code> which seems to work fine at first glance.</p> <p>Now, I want to create this class dynamically at runtime from a string and run the method <code>ShowName()</code>. I'm doing that like this:</p> <pre><code>int main() { qRegisterMetaType&lt;ClassA*&gt;("ClassA*"); int id = QMetaType::type("ClassA*"); std::cout &lt;&lt; "meta id: " &lt;&lt; id &lt;&lt; std::endl; // Outputs correct generated user id (not 0) ClassA* myclass = static_cast&lt;ClassA*&gt;(QMetaType::construct(id)); myclass-&gt;ShowName(); // Segfaults, oh dear return 0; } </code></pre> <p>Now, there is my issue. I don't seem to actually have a correctly constructed object there.</p> <p>If we change the class to look like this:</p> <pre><code>class ClassA : public QObject { Q_OBJECT public: ClassA() { mName = "lol"; } ClassA(const ClassA&amp; other) { assert(false &amp;&amp; "DONT EVER USE THIS"); } ~ClassA(); void ShowName() { std::cout &lt;&lt; mName &lt;&lt; std::endl; } std::string mName; }; </code></pre> <p>then we can change our program accordingly to:</p> <pre><code>int main() { qRegisterMetaType&lt;ClassA&gt;("ClassA"); int id = QMetaType::type("ClassA"); std::cout &lt;&lt; "meta id: " &lt;&lt; id &lt;&lt; std::endl; // Outputs correct generated user id (not 0) ClassA* myclass = static_cast&lt;ClassA*&gt;(QMetaType::construct(id)); myclass-&gt;ShowName(); // "lol", yay return 0; } </code></pre> <p>Obviously I could just use my fake overwritten copy constructor but it doesn't feel right and Qt suggests against that and instead suggests the use of pointers to QObjects only.</p> <p>Does anyone see what's wrong here? Also, I am aware there are similar questions on SO but none of them tackle this exact problem.</p>
7,877,659
3
1
null
2011-10-24 07:45:27.63 UTC
8
2016-12-08 10:41:18.687 UTC
null
null
null
null
161,775
null
1
25
c++|qt|reflection
41,206
<p>A few things:</p> <ul> <li><p>The reason that registering ClassA* isn't working is because your call to construct() is constructing a pointer to a ClassA object, but not an actual object.</p></li> <li><p>It is worthy of noting the following quote from the QMetaType documentation:</p></li> </ul> <blockquote> <p>Any class or struct that has a public default constructor, a public copy constructor, and a public destructor can be registered.</p> </blockquote> <ul> <li><p>Take a look at Qt's implementation of qMetaTypeConstructHelper:</p> <pre><code>template &lt;typename T&gt; void *qMetaTypeConstructHelper(const T *t) { if (!t) return new T(); return new T(*static_cast&lt;const T*&gt;(t)); } </code></pre></li> </ul> <p>and note their usage of the copy constructor. This being the case, you have two ways around the problem:</p> <p>1) Provide a copy constructor (which you have done)</p> <p>2) Provide a specialization of qMetaTypeConstructHelper that doesn't use the copy constructor:</p> <pre><code>template &lt;&gt; void *qMetaTypeConstructHelper&lt;ClassA&gt;(const ClassA *) { return new ClassA(); } </code></pre>
11,748,234
Check whether the JSON (object property exists) & print it as unicode decoded
<p>I get the following data from the <a href="http://instagram.com/developer/endpoints/users/">Instagram API</a>, I m trying to get the text <code>property</code> from the <code>caption</code> using the following code: </p> <pre><code>data = simplejson.load(info) # info is retrieved using the urllib2 for post in data['data']: if post['caption'] is not "null": try: post['caption']['text'] except NameError: post['caption']['text'] = 0 if post['caption']['text'] is not 0: print post['caption']['text'] </code></pre> <p>But I keep getting the <code>TypeError: 'NoneType' object has no attribute '__getitem__'</code> error + <code>UnicodeEncodeError: 'charmap' codec can't encode characters in position 0-5: cha racter maps to &lt;undefined&gt;</code> error while printing the unicode strings</p> <p>Here is the JSON data that is retrieved and stored in <code>info</code></p> <pre><code>{ "pagination":{ "next_url":"https:\/\/api.instagram.com\/v1\/users\/self\/feed?access_token=184046392.f59def8.c5726b469ad2462f85c7cea5f72083c0&amp;count=3&amp;max_id=247821697921944007_6064449", "next_max_id":"247821697921944007_6064449" }, "meta":{ "code":200 }, "data":[ { "attribution":null, "tags":[ "usausausa", "olympics" ], "type":"image", "location":{ "latitude":37.785929, "name":"Aquatech Swim School", "longitude":-122.278718, "id":16343815 }, "comments":{ "count":0, "data":[ ] }, "filter":"Valencia", "created_time":"1343765260", "link":"http:\/\/instagr.am\/p\/NwhEktJvEp\/", "likes":{ "count":0, "data":[ ] }, "images":{ "low_resolution":{ "url":"http:\/\/distilleryimage1.s3.amazonaws.com\/61d9cbeedb4b11e1b8e822000a1e8b8e_6.jpg", "width":306, "height":306 }, "thumbnail":{ "url":"http:\/\/distilleryimage1.s3.amazonaws.com\/61d9cbeedb4b11e1b8e822000a1e8b8e_5.jpg", "width":150, "height":150 }, "standard_resolution":{ "url":"http:\/\/distilleryimage1.s3.amazonaws.com\/61d9cbeedb4b11e1b8e822000a1e8b8e_7.jpg", "width":612, "height":612 } }, "caption":{ "created_time":"1343765325", "text":"Part of my job to watch swimming. #olympics #USAUSAUSA", "from":{ "username":"kissinkatkelly", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_4672491_75sq_1341713095.jpg", "id":"4672491", "full_name":"kissinkatkelly" }, "id":"247843973390332239" }, "user_has_liked":false, "id":"247843429330383145_4672491", "user":{ "username":"kissinkatkelly", "website":"", "bio":"I sing the body electric\r\n\r\nBay Area, CA", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_4672491_75sq_1341713095.jpg", "full_name":"kissinkatkelly", "id":"4672491" } }, { "attribution":null, "tags":[ ], "type":"image", "location":{ "latitude":36.020832061, "longitude":-121.548835754 }, "comments":{ "count":4, "data":[ { "created_time":"1343763343", "text":"I wanna cut your mustache off. \ue313\ue313\ue313\ue004", "from":{ "username":"glorias_noodles", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_24432017_75sq_1343633079.jpg", "id":"24432017", "full_name":"\ue340MeGusta Gloria\ue340" }, "id":"247827343962686703" }, { "created_time":"1343763844", "text":"Ahaha^", "from":{ "username":"chloe_carter", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_44766575_75sq_1343509145.jpg", "id":"44766575", "full_name":"Chloe Carter" }, "id":"247831551235474746" }, { "created_time":"1343763958", "text":"Amazingg thoo", "from":{ "username":"saulyp", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_18051263_75sq_1335648741.jpg", "id":"18051263", "full_name":"Saul Perez" }, "id":"247832506790200642" }, { "created_time":"1343764298", "text":"@popesaintvictor where is that? :o", "from":{ "username":"youknow_jameson", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_194001394_75sq_1343613135.jpg", "id":"194001394", "full_name":"Jameson Medina" }, "id":"247835358103225704" } ] }, "filter":"Normal", "created_time":"1343763202", "link":"http:\/\/instagr.am\/p\/NwdJRpBkfX\/", "likes":{ "count":611, "data":[ { "username":"jakyvedder", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_18148021_75sq_1336938690.jpg", "id":"18148021", "full_name":"Janycken" }, { "username":"nadjasinbruker", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_174576513_75sq_1343582260.jpg", "id":"174576513", "full_name":"Nadja" }, { "username":"vivi11", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_1193390_75sq_1338169730.jpg", "id":"1193390", "full_name":"Viviana Rodriguez" }, { "username":"me_4_eva", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_181498114_75sq_1343506811.jpg", "id":"181498114", "full_name":"Kelly" }, { "username":"roxczajkowski", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_9367244_75sq_1343696914.jpg", "id":"9367244", "full_name":"Czajkowski \u041a\u043e\u0440\u0448\u0443\u043d\u043e\u0432\u0430" }, { "username":"arsi1989", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_201586134_75sq_1343761866.jpg", "id":"201586134", "full_name":"Arsalan MemOn" }, { "username":"puppyluva", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_201579504_75sq_1343760137.jpg", "id":"201579504", "full_name":"puppyluva" }, { "username":"paulinamurr", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_49364097_75sq_1343428499.jpg", "id":"49364097", "full_name":"Paulina Murray" }, { "username":"_mcquadeface_", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_20679753_75sq_1327617901.jpg", "id":"20679753", "full_name":"Emily McQuade" } ] }, "images":{ "low_resolution":{ "url":"http:\/\/distilleryimage11.s3.amazonaws.com\/96cd5b90db4611e1827612313814176c_6.jpg", "width":306, "height":306 }, "thumbnail":{ "url":"http:\/\/distilleryimage11.s3.amazonaws.com\/96cd5b90db4611e1827612313814176c_5.jpg", "width":150, "height":150 }, "standard_resolution":{ "url":"http:\/\/distilleryimage11.s3.amazonaws.com\/96cd5b90db4611e1827612313814176c_7.jpg", "width":612, "height":612 } }, "caption":null, "user_has_liked":false, "id":"247826160271378391_605400", "user":{ "username":"popesaintvictor", "website":"http:\/\/popesaintvictor.com", "bio":"artist, friend, and brand designer for blood:water mission in nashville, tennessee. \r\n\r\nhusband to @ohsoamy\r\n\r\nbe inspired. be awesome.\r\n", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_605400_75sq_1342893414.jpg", "full_name":"pope saint victor", "id":"605400" } }, { "attribution":null, "tags":[ ], "type":"image", "location":{ "latitude":40.738834381, "longitude":-73.994163513 }, "comments":{ "count":6, "data":[ { "created_time":"1343762733", "text":"Nice :)", "from":{ "username":"belieberpernille99", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_186196238_75sq_1341347304.jpg", "id":"186196238", "full_name":"official belieber" }, "id":"247822232418879860" }, { "created_time":"1343762748", "text":"Those pants \ud83d\ude0d", "from":{ "username":"morganmarzulli", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_29155556_75sq_1337653621.jpg", "id":"29155556", "full_name":"morganmarzulli" }, "id":"247822351461615990" }, { "created_time":"1343762777", "text":"That outfit is to die for. I love her pants! They're so fun. \ud83d\udc4d", "from":{ "username":"ninavnegron", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_18421926_75sq_1343356820.jpg", "id":"18421926", "full_name":"Nina V" }, "id":"247822600452278654" }, { "created_time":"1343762782", "text":"YEAH THEIR COOL", "from":{ "username":"belieberpernille99", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_186196238_75sq_1341347304.jpg", "id":"186196238", "full_name":"official belieber" }, "id":"247822639375419775" }, { "created_time":"1343762782", "text":"Another day another shoot! Look out for me and my chicest staff on @racked!", "from":{ "username":"rebeccaminkoff", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_6064449_75sq_1332274636.jpg", "id":"6064449", "full_name":"Rebecca Minkoff" }, "id":"247822641497737600" }, { "created_time":"1343764430", "text":"Hot mama! Miss you!", "from":{ "username":"ashleekoston", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_12925089_75sq_1340081366.jpg", "id":"12925089", "full_name":"ashleekoston" }, "id":"247836463642020446" } ] }, "filter":"Walden", "created_time":"1343762670", "link":"http:\/\/instagr.am\/p\/NwcIVwRYnH\/", "likes":{ "count":528, "data":[ { "username":"claireyoung48", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_40091175_75sq_1338778945.jpg", "id":"40091175", "full_name":"claireyoung48" }, { "username":"l_christine_k", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_14871166_75sq_1341962995.jpg", "id":"14871166", "full_name":"Lauren Kawano" }, { "username":"grcdaly", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_41426567_75sq_1335023058.jpg", "id":"41426567", "full_name":"\u24bc\u24c7\u24b6\u24b8\u24ba \u24b9\u24b6\u24c1\u24e8" }, { "username":"vanessaalcalaa", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_18115905_75sq_1342828120.jpg", "id":"18115905", "full_name":"Vanessa Alcala" }, { "username":"makennalenover", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_6464394_75sq_1343268613.jpg", "id":"6464394", "full_name":"Makenna Lenover" }, { "username":"heyitsmaryanne", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_623979_75sq_1340838647.jpg", "id":"623979", "full_name":"Maryanne L" }, { "username":"sarabeen", "profile_picture":"http:\/\/images.instagram.com\/profiles\/anonymousUser.jpg", "id":"6463387", "full_name":"sarabeen" }, { "username":"boldincrimson", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_191122242_75sq_1341889110.jpg", "id":"191122242", "full_name":"Pilar Chapa" }, { "username":"elizzabethhope", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_6761399_75sq_1342553102.jpg", "id":"6761399", "full_name":"Lizz\u270c" } ] }, "images":{ "low_resolution":{ "url":"http:\/\/distilleryimage7.s3.amazonaws.com\/59bc708edb4511e1b7ea22000a1cbb16_6.jpg", "width":306, "height":306 }, "thumbnail":{ "url":"http:\/\/distilleryimage7.s3.amazonaws.com\/59bc708edb4511e1b7ea22000a1cbb16_5.jpg", "width":150, "height":150 }, "standard_resolution":{ "url":"http:\/\/distilleryimage7.s3.amazonaws.com\/59bc708edb4511e1b7ea22000a1cbb16_7.jpg", "width":612, "height":612 } }, "caption":null, "user_has_liked":false, "id":"247821697921944007_6064449", "user":{ "username":"rebeccaminkoff", "website":"http:\/\/www.rebeccaminkoff.com", "bio":"The Downtown Romantic. My life, my work, my world.", "profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_6064449_75sq_1332274636.jpg", "full_name":"Rebecca Minkoff", "id":"6064449" } } ] } </code></pre>
11,748,645
2
5
null
2012-07-31 20:13:30.887 UTC
7
2012-07-31 20:39:49.393 UTC
2012-07-31 20:32:47.76 UTC
null
997,562
null
997,562
null
1
17
python|json|unicode|simplejson
77,868
<p>You don't need the intricate tests on wether 'text' is present for the post caption. This code works well with the JSON string you posted:</p> <pre><code>for post in data['data']: if post.get('caption'): print post['caption'].get('text', 0) </code></pre> <p>Furthermore, you could be more defensive and refer to <code>data.get('data', [])</code> when starting the loop in case Instagram sends you empty JSON.</p>
11,891,984
Count the number of occurrences of 0's in integers from 1 to N
<p>How will you efficiently count number of occurrences of 0's in the decimal representation of integers from 1 to N?</p> <pre><code>e.g. The number of 0's from 1 to 105 is 16. How? 10,20,30,40,50,60,70,80,90,100,101,102,103,104,105 </code></pre> <p>Count the number of 0's &amp; you will find it 16.</p> <p>Obviously, a brute force approach won't be appreciated. You have to come up with an approach which doesn't depend on "How many numbers fall between 1 to N". Can we just do by seeing some kind of pattern?</p> <p>Cannot we extend the <a href="http://www.geeksforgeeks.org/archives/22180" rel="noreferrer">logic compiled here</a> to work for this problem?</p>
11,892,024
7
10
null
2012-08-09 21:08:07.43 UTC
16
2022-09-20 11:21:37.48 UTC
2012-08-09 21:29:50.223 UTC
null
1,347,366
null
1,347,366
null
1
17
c|algorithm|math
29,297
<p><strong>Updated Answer</strong></p> <p>My original answer was simple to understand but tricky to code. Here's something that is simpler to code. It's a straight-forward <strong>non-recursive</strong> solution that works by counting the number of ways zeros can appear in each position.</p> <p>For example:</p> <blockquote> <p>x &lt;= 1234. How many numbers are there of the following form?</p> <p>x = ??0? </p> </blockquote> <p>There are 12 possibilities for the "hundreds or more" (1,2, ..., 12). Then there must be a zero. Then there are 10 possibilities for the last digit. This gives <code>12 * 10 = 120</code> numbers containing a 0 at the third digit.</p> <p>The solution for the range (1 to 1234) is therefore:</p> <ul> <li>?0??: 1 * 100 = 100</li> <li>??0?: 12 * 10 = 120</li> <li>???0: 123</li> <li>Total = 343</li> </ul> <p>But an exception is if <code>n</code> contains a zero digit. Consider the following case:</p> <blockquote> <p>x &lt;= 12034. How many numbers are there of the following form?</p> <p>x = ??0?? </p> </blockquote> <p>We have 12 ways to pick the "thousands or more". For 1, 2, ... 11 we can choose any two last digits (giving 11 * 100 possibilities). But if we start with 12 we can only choose a number between <code>00</code> and <code>34</code> for the last two digits. So we get <code>11 * 100 + 35</code> possibilities altogether.</p> <hr> <p>Here's an implementation of this algorithm (written in Python, but in a way that should be easy to port to C):</p> <pre><code>def countZeros(n): result = 0 i = 1 while True: b, c = divmod(n, i) a, b = divmod(b, 10) if a == 0: return result if b == 0: result += (a - 1) * i + c + 1 else: result += a * i i *= 10 </code></pre>
11,842,332
Google Analytics Content Experiments: Possible to setup Variations for Multiple Pages at once?
<p>I've recently learned about the new Google Analytics Content Experiments which looks interesting. ( <a href="http://analytics.blogspot.nl/2012/06/helping-to-create-better-websites.html" rel="noreferrer">http://analytics.blogspot.nl/2012/06/helping-to-create-better-websites.html</a> ) </p> <p>The standard usecase seems to be that for a certain page, say a product detail page, you supply variations (different urls) and select a percentage of users that are included in the test. Such a user will be presented a variation of the product-detail page (and will continue to be presented the same variation over and over for continuation/ux reasons, based on cookies presumably) . </p> <p>All fine and good. </p> <p>However, say I have 100 products on my site. Just testing a variation on 1 of those products has imho the following disadvantages: </p> <ul> <li>slow progressing tests because of lower nr of visitors. </li> <li>the test isn't isolated. I.e: since other product detail pages aren't included in the test, displaying a variation-page for 1 product-detail page while all other product-detail pages show the original can (will) lead to a confusing experience (and thus skewed conversion statistics) for the user that browses multiple products, which most of them do.</li> </ul> <p>To me it seems far better to be able to dynamically include all products of a certain type into the same test (e.g: all TV's) , for example by enabling to set some regular expression or other filter on urls to include in the test. </p> <p>Is such a thing possible currently, scheduled, useful, or completely missing the point? </p> <p><strong>EDIT</strong></p> <p>Part of the solution seems to be "relative urls" <a href="https://support.google.com/analytics/bin/answer.py?hl=en&amp;answer=2664470" rel="noreferrer">https://support.google.com/analytics/bin/answer.py?hl=en&amp;answer=2664470</a></p> <blockquote> <p>Taking the previous example one step further, we can see how the use of relative URLs lets you easily run an experiment on a set of different original pages, and test visual alternatives across that group of pages (e.g., the product pages in an e-commerce site).</p> </blockquote> <p>Remaining question: How to dynamically tag which pages belong to the experiment (e.g: based on regex) </p> <p>Thanks. </p>
14,465,029
5
4
null
2012-08-07 08:49:58.523 UTC
11
2021-12-01 15:18:09.857 UTC
2014-02-17 10:53:07.927 UTC
null
1,053,103
null
209,591
null
1
23
google-analytics|ab-testing|google-experiments
8,426
<p>The solution is to use relative url for the variation page.</p> <p>E.g. you have a number of product pages:</p> <pre><code>www.mysite.com/products/eggs.html www.mysite.com/products/cheese.html www.mysite.com/products/bread.html etc. </code></pre> <p>For each page you have a matching variation page:</p> <pre><code>www.mysite.com/products/eggs.html?var=bigpicture www.mysite.com/products/cheese.html?var=bigpicture www.mysite.com/products/bread.html?var=bigpicture etc. </code></pre> <p>You want to use all the product pages in 1 experiment.</p> <p>Go To google Analytics Content Experiments: For the orginal page choose ONE of the many product pages (e.g. www.mysite.com/products/eggs.html) (This is just to get the experiment code and provide GA with an example page)</p> <p>For the variation page choose relative url and put ?var=bigpicture</p> <p>Then place the javascript required for the experiment on ALL the original product pages you want in the experiment</p> <p><img src="https://i.stack.imgur.com/9tBfs.png" alt="Google Content experiments Dynamic URL product pages"></p> <p>For more information see: <a href="http://support.google.com/analytics/bin/answer.py?hl=en&amp;answer=2664470&amp;topic=1745208&amp;ctx=topic" rel="noreferrer">http://support.google.com/analytics/bin/answer.py?hl=en&amp;answer=2664470&amp;topic=1745208&amp;ctx=topic</a></p>
11,854,470
What does "Unexpected precompiled header error" mean?
<p>I was trying to build a simple solution involving a Windows and a Console application. After using the wizard to generate the code skeleton for the projects, I didn't add any code and just built the generated code. In both cases I got the same error:</p> <p><code>1&gt;c:\c\winpr\winpr\winpr.cpp(4) : fatal error C1859: 'Debug\winpr.pch' unexpected precompiled header error, simply rerunning the compiler might fix this problem</code></p> <p>What is wrong, any thoughts? </p>
11,854,569
6
2
null
2012-08-07 21:34:43.44 UTC
5
2017-07-18 23:34:52.02 UTC
2013-03-25 08:22:54.547 UTC
null
132,735
null
1,501,700
null
1
37
c++|visual-studio-2008|compiler-errors
26,498
<p>There is a fix for Visual C++ 2008 SP1 compiler error C1859. You may download it <a href="http://connect.microsoft.com/VisualStudio/Downloads/DownloadDetails.aspx?DownloadID=25785" rel="noreferrer">here</a>.</p> <p>For details see <a href="http://blogs.msdn.com/b/vcblog/archive/2009/11/12/visual-c-precompiled-header-errors-on-windows-7.aspx" rel="noreferrer">this</a>.</p>
12,035,316
Reading entire html file to String?
<p>Are there better ways to read an entire html file to a single string variable than:</p> <pre><code> String content = ""; try { BufferedReader in = new BufferedReader(new FileReader("mypage.html")); String str; while ((str = in.readLine()) != null) { content +=str; } in.close(); } catch (IOException e) { } </code></pre>
12,035,351
8
0
null
2012-08-20 09:37:19.833 UTC
8
2021-05-25 13:40:02.17 UTC
null
null
null
null
1,194,415
null
1
37
java|file-io
129,972
<p>There's the <a href="http://commons.apache.org/io/apidocs/org/apache/commons/io/IOUtils.html#toString(java.io.InputStream)" rel="noreferrer"><code>IOUtils.toString(..)</code></a> utility from Apache Commons. </p> <p>If you're using <code>Guava</code> there's also <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html" rel="noreferrer"><code>Files.readLines(..)</code></a> and <a href="http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/io/Files.html" rel="noreferrer"><code>Files.toString(..)</code></a>. </p>
11,467,424
someString.IndexOf(someString) returns 1 instead of 0 under .NET 4
<p>We have recently upgraded all our projects from .NET 3.5 to .NET 4. I have come across a rather strange issue with respect to <code>string.IndexOf()</code>.</p> <p>My code obviously does something slightly different, but in the process of investigating the issue, I found that calling <code>IndexOf()</code> on a string with itself returned 1 instead of 0. In other words:</p> <pre><code>string text = "\xAD\x2D"; // problem happens with "­-dely N.China", too; int index = text.IndexOf(text); // see update note below. </code></pre> <p>Gave me an index of 1, instead of 0. A couple of things to note about this problem:</p> <ul> <li><p>The problems seems related to these hyphens (the first character is the Unicode soft hyphen, the second is a regular hyphen).</p></li> <li><p>I have double checked, this does not happen in .NET 3.5 but does in .NET 4.</p></li> <li><p>Changing the <code>IndexOf()</code> to do an ordinal compare fixes the issue, so for some reason that first character is ignored with the default <code>IndexOf</code>.</p></li> </ul> <p>Does anyone know why this happens?</p> <p><strong>EDIT</strong></p> <p>Sorry guys, made a bit of a stuff up on the original post and got the hidden dash in there twice. I have updated the string, this should return index of 1 instead of 2, as long as you paste it in the correct editor.</p> <p><strong>Update:</strong></p> <p>Changed the original problem string to one where every actual character is clearly visible (using escaping). This simplifies the question a bit.</p>
11,467,605
3
3
null
2012-07-13 09:08:51.68 UTC
13
2012-07-14 02:49:44.18 UTC
2012-07-13 11:20:29.27 UTC
null
240,733
null
1,228,513
null
1
55
c#|string|.net-4.0|.net-3.5
2,666
<p>Your string exists of two characters: a <a href="http://www.fileformat.info/info/unicode/char/ad/index.htm" rel="nofollow noreferrer">soft hyphen</a> (Unicode code point 173) and a <a href="http://www.fileformat.info/info/unicode/char/2d/index.htm" rel="nofollow noreferrer">hyphen</a> (Unicode code point 45). </p> <blockquote> <p><a href="http://en.wikipedia.org/wiki/Soft_hyphen" rel="nofollow noreferrer">Wiki</a>: According to the Unicode standard, a soft hyphen is not displayed if the line is not broken at that point.</p> </blockquote> <p>When using <code>"\xAD\x2D".IndexOf("\xAD\x2D")</code> in .NET 4, it seems to ignore that you're looking for the soft hyphen, returning a starting index of 1 (the index of <code>\x2D</code>). In .NET 3.5, this returns 0.</p> <p>More fun, if you run this code (so when <em>only</em> looking for the soft hyphen):</p> <pre><code>string text = "\xAD\x2D"; string shy = "\xAD"; int i1 = text.IndexOf(shy); </code></pre> <p>then <code>i1</code> becomes 0, regardless of the .NET version used. The result of <code>text.IndexOf(text);</code> varies indeed, which at a glance looks like a bug to me. </p> <p>As far as I can track back through the framework, older .NET versions use an <a href="https://stackoverflow.com/questions/1211462/c-sharp-internal-static-extern-with-internalcall-attribute-internal-or-externa">InternalCall</a> to <code>IndexOfString()</code> (I can't figure out to which API call that goes), while from .NET 4 a <a href="https://stackoverflow.com/questions/9491337/what-is-dllimportqcall">QCall</a> to <code>InternalFindNLSStringEx()</code> is made, which in turn calls <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd318059(v=vs.85).aspx" rel="nofollow noreferrer"><code>FindNLSStringEx()</code></a>.</p> <p>The issue (I really can't figure out if this is intended behaviour) indeed occurs when calling <code>FindNLSStringEx</code>:</p> <pre><code>LPCWSTR lpStringSource = L"\xAD\x2D"; LPCWSTR lpStringValue = L"\xAD"; int length; int i = FindNLSStringEx( LOCALE_NAME_SYSTEM_DEFAULT, FIND_FROMSTART, lpStringSource, -1, lpStringValue, -1, &amp;length, NULL, NULL, 1); Console::WriteLine(i); i = FindNLSStringEx( LOCALE_NAME_SYSTEM_DEFAULT, FIND_FROMSTART, lpStringSource, -1, lpStringSource, -1, &amp;length, NULL, NULL, 1); Console::WriteLine(i); Console::ReadLine(); </code></pre> <p>Prints 0 and then 1. Note that <code>length</code>, an out parameter indicating the length of the found string, is 0 after the first call and 1 after the second; the soft hyphen is counted as having a length of 0.</p> <p>The workaround is to use <code>text.IndexOf(text, StringComparison.OrdinalIgnoreCase);</code>, as you've noted. This makes a QCall to <code>InternalCompareStringOrdinalIgnoreCase()</code> which in turn calls <a href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd318061(v=vs.85).aspx" rel="nofollow noreferrer"><code>FindStringOrdinal()</code></a>, which returns 0 for both cases.</p>
12,019,684
How to verify if $_GET exists?
<p>So, I have some PHP code that looks a bit like this:</p> <pre><code>&lt;body&gt; The ID is &lt;?php echo $_GET["id"] . "!"; ?&gt; &lt;/body&gt; </code></pre> <p>Now, when I pass an ID like <code>http://localhost/myphp.php?id=26</code> it works alright, but if there is no ID like just <code>http://localhost/myphp.php</code> then it outputs:</p> <pre><code>The ID is Notice: Undefined index: id in C:\xampp\htdocs\myphp.php on line 9 ! </code></pre> <p>I have searched for a way to fix this but I cannot find any way to check if a URL variable exists. I know there must be a way though.</p>
12,019,694
7
2
null
2012-08-18 15:14:06.347 UTC
10
2021-03-01 16:38:15.533 UTC
null
null
null
null
1,223,693
null
1
70
php|html|urlvariables
176,963
<p>You can use <code>isset</code> function:</p> <pre><code>if(isset($_GET['id'])) { // id index exists } </code></pre> <p>You can create a handy function to return default value if index doesn't exist:</p> <pre><code>function Get($index, $defaultValue) { return isset($_GET[$index]) ? $_GET[$index] : $defaultValue; } // prints &quot;invalid id&quot; if $_GET['id'] is not set echo Get('id', 'invalid id'); </code></pre> <p>You can also try to validate it at the same time:</p> <pre><code>function GetInt($index, $defaultValue) { return isset($_GET[$index]) &amp;&amp; ctype_digit($_GET[$index]) ? (int)$_GET[$index] : $defaultValue; } // prints 0 if $_GET['id'] is not set or is not numeric echo GetInt('id', 0); </code></pre>
11,595,757
What is the equivalent of "!=" in Excel VBA?
<p>The problem is that <code>!=</code> does not work as a function in excel vba.</p> <p>I want to be able to use </p> <p><code>If strTest != "" Then</code> instead of <code>If strTest = "" Then</code></p> <p>Is there another approach to do this besides <code>!=</code>?</p> <p>My function to mimic <code>!=</code> is </p> <pre><code>Sub test() Dim intTest As Integer Dim strTest As String intTest = 5 strTest = CStr(intTest) ' convert Range("A" + strTest) = "5" For i = 1 To 10 Cells(i, 1) = i If strTest = "" Then Cells(i, 1) = i End If Next i End Sub </code></pre>
11,595,780
4
3
null
2012-07-21 20:53:36.96 UTC
6
2019-07-11 15:36:20.447 UTC
2019-07-11 15:36:20.447 UTC
null
11,615,632
null
484,390
null
1
102
excel|vba|function|syntax|inequality
415,007
<p>Because the inequality operator in VBA is <code>&lt;&gt;</code></p> <pre><code>If strTest &lt;&gt; "" Then ..... </code></pre> <p>the operator <code>!=</code> is used in C#, C++.</p>
12,013,334
How do you create a transparent demo screen for an Android app?
<p>I'm trying to create a semi-transparent demo screen that is launched only when a user first installs my application. Here's an example from the Pulse News app:</p> <p><strong>Galaxy Nexus</strong></p> <p><img src="https://i.stack.imgur.com/P3kzh.png" alt="Example screenshot from Pulse News on Galaxy Nexus"></p> <p><strong>Nexus One</strong></p> <p><img src="https://i.stack.imgur.com/Jji5T.png" alt="enter image description here"></p> <p>Instead of a 'tap-to-dismiss' feature, I want the user to be able to swipe through a couple of such transparent demo pages. </p> <p>For my first attempt, I modified a sample from the <a href="http://viewpagerindicator.com/" rel="noreferrer">ViewPagerIndicator</a> library. I used semi-transparent PNGs in ImageViews inside each of the view pager's fragments. I then launched this as a 'demo activity' in the onCreate method of my 'main activity'. </p> <p>Problem: The 'main activity' could not be seen in the background - instead it was just black. I tried the solutions <a href="https://stackoverflow.com/questions/2176922/how-to-create-transparent-activity-in-android">here</a>, but that didn't fix the problem.</p> <p>Is there a better approach to creating something like this, or am I on the right track? </p> <p>I also had another related question which depends on how this is implemented. I'm trying to overlay text and arrows such that they point at particular UI components in the background. By using a PNG that has the text and arrows, it's likely that it will not scale properly on different devices. I.e., the arrows may not necessarily point to the correct UI component in the background. Is there a way to tackle this problem as well?</p> <p>Thanks!</p> <p>Here's my code for the first attempt:</p> <p><strong>DemoActivity.java</strong></p> <pre><code>public class DemoActivity extends FragmentActivity { DemoFragmentAdapter mAdapter; ViewPager mPager; PageIndicator mIndicator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.demo_activity); mAdapter = new DemoFragmentAdapter(getSupportFragmentManager()); mPager = (ViewPager)findViewById(R.id.pager); mPager.setAdapter(mAdapter); //mPager.setAlpha(0); UnderlinePageIndicator indicator = (UnderlinePageIndicator)findViewById(R.id.indicator); indicator.setViewPager(mPager); indicator.setFades(false); mIndicator = indicator; } } </code></pre> <p><strong>DemoFragmentAdapter.java</strong></p> <pre><code>class DemoFragmentAdapter extends FragmentPagerAdapter { protected static final int[] CONTENT = new int[] { R.drawable.demo1, R.drawable.demo2, R.drawable.demo3, R.drawable.demo4}; private int mCount = CONTENT.length; public DemoFragmentAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int position) { return DemoFragment.newInstance(CONTENT[position % CONTENT.length]); } @Override public int getCount() { return mCount; } public void setCount(int count) { if (count &gt; 0 &amp;&amp; count &lt;= 10) { mCount = count; notifyDataSetChanged(); } } } </code></pre> <p><strong>DemoFragment.java</strong></p> <pre><code>public final class DemoFragment extends Fragment { private static final String KEY_CONTENT = "TestFragment:Content"; public static DemoFragment newInstance(int content) { DemoFragment fragment = new DemoFragment(); fragment.mContent = content; return fragment; } private int mContent; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if ((savedInstanceState != null) &amp;&amp; savedInstanceState.containsKey(KEY_CONTENT)) { mContent = savedInstanceState.getInt(KEY_CONTENT); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { ImageView image = new ImageView(getActivity()); image.setBackgroundResource(mContent); LinearLayout layout = new LinearLayout(getActivity()); layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); layout.setGravity(Gravity.CENTER); layout.addView(image); return layout; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putInt(KEY_CONTENT, mContent); } } </code></pre>
12,192,314
8
2
null
2012-08-17 21:20:49.02 UTC
84
2015-10-28 03:35:26.333 UTC
2017-05-23 12:26:06.95 UTC
null
-1
null
886,468
null
1
106
android|android-viewpager|transparent|demo|showcaseview
72,957
<p>Put your demo info in a different activity and give it the following theme.</p> <pre><code>&lt;style name="Transparent" parent="@android:style/Theme.NoTitleBar"&gt; &lt;item name="android:windowContentOverlay"&gt;@null&lt;/item&gt; &lt;item name="android:windowIsTranslucent"&gt;true&lt;/item&gt; &lt;item name="android:windowBackground"&gt;@android:color/transparent&lt;/item&gt; &lt;item name="android:windowNoTitle"&gt;true&lt;/item&gt; &lt;item name="android:backgroundDimEnabled"&gt;false&lt;/item&gt; &lt;/style&gt; </code></pre> <p>If you're using ActionBarSherlock change <code>parent</code> to <code>@style/Theme.Sherlock</code>.</p> <p>This will give you a transparent activity, so you will be able to see the activity below it.</p> <p>Now I'm guessing you want a translucent background too.</p> <p>In the xml layout (of your transparent activity) add: </p> <pre><code>android:background="#aa000000" </code></pre> <p>The last 6 digits define the color: 000000 is black.</p> <p>The first 2 define the opacity: 00 is 100% transparent, ff is 100% opaque. So choose something in between.</p>
20,139,050
What really is a declarative environment record and how does it differ from an activation object?
<p>Okay, so I lately have been reading about ES-5 lexical environment scope and I am not sure if I really understand what is going on with how variables are stored in EcmaScript. I did some research but it didn't clarified my information, only brought me up to two questions. So there they are:</p> <ol> <li><p>The first one is about ES-3 <code>activations objects</code>/<code>variable objects</code>. After reading ES-3 Specification and some sources on the Internet I can assume that they are just normal object, for example like those created by <code>new Object</code>, but none of the sources says "yes, this is just a plain object" directly. Moreover, Dmitry Soshnikov wrote on his blog (the emphasis is mine):</p> <blockquote> <p><strong>Schematically and for examples</strong>, it is possible to present variable object as a normal ECMAScript object</p> </blockquote> <p>and that quotation doesn't let me be sure about what really an activation object is. So this is the first question: is an activation object a regular EcmaScript object? If not, then what is it otherwise?</p></li> <li><p>In ES-5 we now have <code>object environment records</code>, which seem to be more or less the same that ES-3 activation objects, and <code>declarative environment records</code>, which replaced activation objects in functions and try-catch statement. So, assuming that object environment records <strong>are</strong> just plain EcmaScript objects, then what is a declarative environment record? The specification doesn't clarify this, furthermore, from what I've read there I cannot imagine that this is not implemented as an object. So, again, if declarative environment records are not ES objects, then what are they and how are they implemented and represented during the code execution?</p></li> </ol> <p>Thank you very much in advance for brightening that topic for me.</p> <p><strong>EDIT</strong>: I think I need to clarify what is this question about. The main thing that I want to know is what is the exact difference between activation objects/object environment records and declarative environment records. That's what I'm interested in most.</p>
20,140,626
1
9
null
2013-11-22 07:07:09.94 UTC
15
2013-11-22 09:31:54.103 UTC
2013-11-22 09:05:06.08 UTC
null
218,196
null
2,148,667
null
1
17
javascript|ecmascript-5
4,024
<p>First of all you have to be aware that all of these terms just describe <em>concepts</em>. They don't dictate any kind of implementation. But because this can be hard to imagine/visualize it can be <strong>helpful</strong> to think about these concepts as instantiations of something you know, like maps or tables.</p> <p><em>Declarative environment records</em> (DER) and <em>object environment records</em> (OER) have one thing in common: They are both <em>environment records</em> (ER), which are defined <a href="http://es5.github.io/#x10.2.1">in the specification</a> as:</p> <blockquote> <p>An Environment Record records the identifier bindings that are created within the scope of its associated Lexical Environment.</p> </blockquote> <p>This basically means that an ER keeps track of variable and function names and their associated values.</p> <p>Consider this example:</p> <pre><code>var foo = 42; function bar() { }; </code></pre> <p>The corresponding ER would have two entries, one for <code>foo</code> and one for <code>bar</code>. If you imagine an ER to be a table, then it would look like</p> <pre><code> name value ---------------------- foo 42 bar &lt;function object&gt; </code></pre> <p>Now on to the difference between DER and OER. A DER might be the easiest to understand. </p> <p><a href="http://es5.github.io/#x10.2.1.1"><strong>Declarative Environment Record</strong></a></p> <p>The term <em>declarative</em> should sound familiar since we are often talking of <em>variable declarations</em> and <em>function declarations</em>. The specification says:</p> <blockquote> <p>Each declarative environment record is associated with an ECMAScript program scope containing variable and/or function declarations. A declarative environment record binds the set of identifiers defined by the declarations contained within its scope.</p> </blockquote> <p>So, when you see</p> <pre><code>var foo = 42; </code></pre> <p>or </p> <pre><code>function bar() { } </code></pre> <p>then you can assume that their names and values are stored in a DER.</p> <p><a href="http://es5.github.io/#x10.2.1.2"><strong>Object Environment Record</strong></a></p> <p>OERs are less common, but in each JS application there exist at least one OER. The specification describes it as </p> <blockquote> <p>Each object environment record is associated with an object called its binding object. An object environment record binds the set of identifier names that directly correspond to the property names of its binding object. </p> </blockquote> <p>Have you ever wondered why the properties of the <code>window</code> object are global variables? That's because the ER of the global scope is an OER: <code>window</code> is the <em>binding object</em> and for each of its properties a corresponding entry is created in the OER. This is also in the specification: </p> <blockquote> <p>The global environment’s Environment Record is an object environment record whose binding object is the global object.</p> </blockquote> <p>Here is an example: Lets assume out binding object is</p> <pre><code>var obj = { answer: 42 }; </code></pre> <p>then the OER would be </p> <pre><code> name value ------------------------ answer 42 </code></pre> <p>Note that in this case, the binding object (<code>obj</code>) is really a JavaScript object. You are in the same situation when you are using the <code>with</code> statement:</p> <pre><code>var obj = { foo: 42; }; with (obj) { foo = foo / 2; } console.log(obj); </code></pre> <p><code>with</code> creates a OER and populates it with the property names and values from the passed object. That's why you can access them without explicitly referring to them via <code>obj.*</code>. The OER also makes sure to update the binding object with the new value if one was assigned to one of the identifiers.</p> <hr> <p><strong>Activation Object</strong></p> <p>It looks like that in ES3, activation objects (AO) where automatically created when a function was executed and it was holding a reference to the special <code>arguments</code> object. This seems to be related to DERs, but still to be something independent.<br> The concept of AOs doesn't seem to exist anymore in ES5 and I assume that it was unnecessary, since <code>arguments</code> can be added directly to the DER of the execution context.</p> <p><strong>Execution Context</strong></p> <p>A new <em>execution context</em> (EC) is established whenever a function is executed and is used to keep track of the state of the execution:</p> <blockquote> <p>An execution context contains whatever state is necessary to track the execution progress of its associated code. </p> </blockquote> <p>This means the engine can add whatever information it needs to track the execution progress. But the specification also defines components that an EC <em>must</em> have, one of which is the <em>VariableEnvironment</em>, which is an ER (probably always a DER, but I don't know for sure). That means an ER is a <em>part</em> of an EC.</p>
3,559,337
How to generate a random list of fixed length of values from given range?
<p>How to generate a random (but unique and sorted) list of a fixed given length out of numbers of a given range in Python?</p> <p>Something like that:</p> <pre><code>&gt;&gt;&gt; list_length = 4 &gt;&gt;&gt; values_range = [1, 30] &gt;&gt;&gt; random_list(list_length, values_range) [1, 6, 17, 29] &gt;&gt;&gt; random_list(list_length, values_range) [5, 6, 22, 24] &gt;&gt;&gt; random_list(3, [0, 11]) [0, 7, 10] </code></pre>
3,559,364
4
1
null
2010-08-24 17:43:10.647 UTC
8
2022-01-07 01:09:25.057 UTC
2017-05-11 19:26:42.91 UTC
null
3,924,118
null
63,503
null
1
31
python|random|list|sample
73,841
<p>A random sample like this returns list of unique items of sequence. Don't confuse this with random integers in the range.</p> <pre><code>&gt;&gt;&gt; import random &gt;&gt;&gt; random.sample(range(30), 4) [3, 1, 21, 19] </code></pre>
3,607,352
struct with 2 cells vs std::pair?
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/2236182/what-is-the-difference-between-using-a-struct-with-two-fields-and-a-pair">What is the difference between using a struct with two fields and a pair?</a> </p> </blockquote> <p>Dear all,</p> <p>I have a little question about pairs and struct. Is there any advantage to use a std::pair instead of a struct with two cells ? I have used pairs for a while but the main problem is readability : If you want to represent for example a duple (int "label", double "value") you can use either a :</p> <pre><code>typedef std::pair&lt;int,double&gt; myElem; </code></pre> <p>or a </p> <pre><code>typedef struct { int label; double value; } myElem; </code></pre> <p>The code becomes more readable if your statements have a "semantic" sense (you will always know what x.label is. that's not the case with x.first).</p> <p>However, I guess there is an advantage using pair. Is it more performant or something else?</p>
3,607,404
5
1
null
2010-08-31 08:36:15.097 UTC
7
2015-12-08 23:28:37.543 UTC
2017-05-23 11:47:31.443 UTC
null
-1
null
378,917
null
1
35
c++|struct|std-pair
21,708
<p>A <code>pair</code> is implemented as a templated <code>struct</code>. It provides you with a shorthand for creating a (typically heterogenous) pair. Also, there are some constraints on the types that you can use with a <code>pair</code>:</p> <blockquote> <p><strong>Type requirements</strong></p> <p>T1 and T2 must both be models of Assignable. Additional operations have additional requirements. Pair's default constructor may only be used if both T1 and T2 are DefaultConstructible, operator== may only be used if both T1 and T2 are EqualityComparable, and operator&lt; may only be used if both T1 and T2 are LessThanComparable.</p> </blockquote> <p>(from SGI STL <a href="http://www.sgi.com/tech/stl/pair.html" rel="noreferrer"><code>std::pair</code></a> documentation)</p> <p>Defining your own POD may make sense if the types do not follow any of these constraints or if you do not care about them.</p> <p>Finally, I guess it is a matter of personal choice/coding style.</p>
3,647,518
PEP8 and PyQt, how to reconcile function capitalization?
<p>I'm starting to use PyQt in some projects and I'm running into a stylistic dilemma. PyQt's functions use camel case, but PEP8, which I prefer to follow, says to use underscores and all lowercase for function names.</p> <p>So on the one hand, I can continue to follow PEP8, meaning that my code will have mixed functions calls to camel case and underscore functions, and even my classes will have mixed function names, since I'll need to be overloading functions like mousePressEvent. Or, I can break PEP8 and adopt camel case for all my function names in the name of consistency.</p> <p>I realize this is subjective and it's really just what I personally prefer, but I like to hear from others about what they do and why they chose to do it that way.</p>
67,340,477
6
2
null
2010-09-05 19:46:57.897 UTC
3
2021-04-30 21:08:54.997 UTC
2018-03-15 22:47:59.667 UTC
null
3,357,935
null
251,276
null
1
35
python|coding-style|pyqt|pyqt4|pep8
3,554
<p>In december 2020, with the release of Qt 6.0, the <a href="https://www.qt.io/blog/qt-for-python-6-released" rel="noreferrer">Qt for Python 6 / PySide6</a> (the official Python bindings for Qt) was also released, introducing a new option called <code>__feature__</code>. With this option you can have Qt objects with PEP8-compliant snake case methods and true properties.</p> <p>Old style:</p> <pre class="lang-py prettyprint-override"><code>table = QTableWidget() table.setColumnCount(2) button = QPushButton(&quot;Add&quot;) button.setEnabled(False) layout = QVBoxLayout() layout.addWidget(table) layout.addWidget(button) </code></pre> <p>New PySide6 style:</p> <pre class="lang-py prettyprint-override"><code>from __feature__ import snake_case, true_property table = QTableWidget() table.column_count = 2 button = QPushButton(&quot;Add&quot;) button.enabled = False layout = QVBoxLayout() layout.add_widget(table) layout.add_widget(button) </code></pre>
3,337,825
Language to learn to move out of manual testing towards automated/programming
<p>I have been working as a manual tester and documentation (Test plans etc.) personnel in a company's software/IT division. I do not have a big programming background but I want learn programming language(s) and tool(s). Hence, I am looking for automated testing tools and programming language(s) to learn which also give me industrial advantage.</p> <p>Some points to note are:</p> <ol> <li>I need to know which tools are the most common in the industry and languages associated with those tools.</li> <li>I do not have a lot of time to learn loads of stuff. Hence, I am looking for tools which use languages that are beneficial to learn in case I want to do more programming.</li> <li>I'd prefer Web based app testing but that is not a constraint.</li> <li>You can give 2-3 languages as I understand there cannot be one winner.</li> <li>I have done some QTP which uses VBScript but VBScript is not broadly used. I want to learn a language that had broader base.</li> <li>Please still give your inputs and ideas even if this question seems really difficult to answer.</li> </ol> <p>Thanks in advance.</p> <hr> <p><strong>EDIT:</strong> I think so far I have decided that I will go for: </p> <ol> <li>QTP </li> <li>Selenium</li> <li>Test Driven Development Methodologies</li> </ol> <p>I just need to figure out a good programming language that gives me a programmer's edge and is suitable for multiple testing tools (including Selenium). Maybe Python, Ruby or Java?</p>
3,337,932
7
3
null
2010-07-26 18:31:45.24 UTC
11
2013-11-11 05:41:20.047 UTC
2010-07-27 15:23:46.223 UTC
null
402,595
null
402,595
null
1
15
testing|programming-languages|automated-tests|manual-testing
28,070
<p>Wow this is quite a widesweeping question. I'd say you were in a good position as the industry moves towards a <a href="http://www.agiledata.org/essays/tdd.html" rel="noreferrer">Test Driven Development</a> (or write your tests before your code) model.</p> <p>First of all you'll want to know about <a href="http://en.wikipedia.org/wiki/Unit_testing" rel="noreferrer">Unit Testing</a>, <a href="http://martinfowler.com/articles/continuousIntegration.html" rel="noreferrer">Continuous Integration</a> and Web Automation.</p> <p>I'm going to focus on the areas I know (.NET, Java, Javascript, Build automation, Selenium)</p> <ol> <li><p>In .NET <a href="http://www.nunit.org/" rel="noreferrer">NUnit</a> is probably the most widely used unit testing framework. It is a port (copy of) <a href="http://www.junit.org/" rel="noreferrer">JUnit</a> in the java world. Most unit testing frameworks are very similar to these in terms of the concepts. So learn one and it won't take you long to pick up the others.</p> </li> <li><p>I think reading the above links and having an idea about these concepts will get you on your way. It's probably worth experimenting with Python or Ruby as these have low barriers to entry to mess around with some simple tests.</p> </li> <li><p>For web based testing the most well known are probably <a href="http://www.selenium.org" rel="noreferrer">Selenium</a> and <a href="http://watin.sourceforge.net/" rel="noreferrer">Watin</a>. These allow you to script browsers to perform actions automatically. However, I have come across very few good usage of these and they are very fiddly (you're talking days/weeks of effort) to get set up and useful. Again the concepts behind these are similar whatever framework you use.</p> <p>Think I answered 4,5,6 in 1,2,3 :-)</p> </li> </ol> <p>HTH</p>
4,039,229
Checking if two cubic Bézier curves intersect
<p>For a personal project, I'd need to find out if two cubic Bézier curves intersect. I don't need to know where: I just need to know if they do. However, I'd need to do it fast.</p> <p>I've been scavenging the place and I found several resources. Mostly, there's <a href="https://stackoverflow.com/questions/109364/bezier-clipping">this question here</a> that had a promising answer.</p> <p>So after I figured what is a <a href="http://en.wikipedia.org/wiki/Sylvester_matrix" rel="noreferrer">Sylvester matrix</a>, what is a <a href="http://mathworld.wolfram.com/Determinant.html" rel="noreferrer">determinant</a>, what is a <a href="http://mathworld.wolfram.com/Resultant.html" rel="noreferrer">resultant</a> and <a href="https://stackoverflow.com/questions/109364/bezier-clipping#comment-4332265">why it's useful</a>, I thought I figured how the solution works. However, reality begs to differ, and it doesn't work so well.</p> <hr /> <h1>Messing Around</h1> <p>I've used my graphing calculator to draw two Bézier splines (that we'll call B<sub>0</sub> and B<sub>1</sub>) that intersect. Their coordinates are as follow (P<sub>0</sub>, P<sub>1</sub>, P<sub>2</sub>, P<sub>3</sub>):</p> <pre><code>(1, 1) (2, 4) (3, 4) (4, 3) (3, 5) (3, 6) (0, 1) (3, 1) </code></pre> <p>The result is the following, B<sub>0</sub> being the &quot;horizontal&quot; curve and B<sub>1</sub> the other one:</p> <p><img src="https://i.stack.imgur.com/ZYVaW.png" alt="Two cubic Bézier curves that intersect" /></p> <p>Following directions from the aforementioned question's top-voted answer, I've subtracted B<sub>0</sub> to B<sub>1</sub>. It left me with two equations (the X and the Y axes) that, according to my calculator, are:</p> <pre><code>x = 9t^3 - 9t^2 - 3t + 2 y = 9t^3 - 9t^2 - 6t + 4 </code></pre> <hr /> <h1>The Sylvester Matrix</h1> <p>And from that I've built the following Sylvester matrix:</p> <pre><code>9 -9 -3 2 0 0 0 9 -9 -3 2 0 0 0 9 -9 -3 2 9 -9 -6 4 0 0 0 9 -9 -6 4 0 0 0 9 -9 -6 4 </code></pre> <p>After that, I've made a C++ function to calculate determinants of matrices using <a href="http://en.wikipedia.org/wiki/Laplace_expansion" rel="noreferrer">Laplace expansion</a>:</p> <pre><code>template&lt;int size&gt; float determinant(float* matrix) { float total = 0; float sign = 1; float temporaryMatrix[(size - 1) * (size - 1)]; for (int i = 0; i &lt; size; i++) { if (matrix[i] != 0) { for (int j = 1; j &lt; size; j++) { float* targetOffset = temporaryMatrix + (j - 1) * (size - 1); float* sourceOffset = matrix + j * size; int firstCopySize = i * sizeof *matrix; int secondCopySize = (size - i - 1) * sizeof *matrix; memcpy(targetOffset, sourceOffset, firstCopySize); memcpy(targetOffset + i, sourceOffset + i + 1, secondCopySize); } float subdeterminant = determinant&lt;size - 1&gt;(temporaryMatrix); total += matrix[i] * subdeterminant * sign; } sign *= -1; } return total; } template&lt;&gt; float determinant&lt;1&gt;(float* matrix) { return matrix[0]; } </code></pre> <p>It seems to work pretty well on relatively small matrices (2x2, 3x3 and 4x4), so I'd expect it to work on 6x6 matrices too. I didn't conduct extensive tests however, and there's a possibility that it's broken.</p> <hr /> <h1>The Problem</h1> <p>If I understood correctly the answer from the other question, the determinant should be 0 since the curves intersect. However, feeding my program the Sylvester matrix I made above, it's -2916.</p> <p>Is it a mistake on my end or on their end? What's the correct way to find out if two cubic Bézier curves intersect?</p>
4,041,286
8
7
null
2010-10-28 02:19:03.487 UTC
17
2021-09-18 14:03:49.987 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
251,153
null
1
39
c++|intersection|bezier
16,725
<p>Intersection of Bezier curves is done by the (very cool) <a href="http://asymptote.sourceforge.net/" rel="noreferrer">Asymptote</a> vector graphics language: look for <code>intersect()</code> <a href="http://asymptote.sourceforge.net/doc/Paths-and-guides.html" rel="noreferrer">here</a>.</p> <p>Although they don't explain the algorithm they actually use there, except to say that it's from p. 137 of "The Metafont Book", it appears that the key to it is two important properties of Bezier curves (which are explained elsewhere on that site though I can't find the page right now):</p> <ul> <li>A Bezier curve is always contained within the bounding box defined by its 4 control points</li> <li>A Bezier curve can always be subdivided at an arbitrary <em>t</em> value into 2 sub-Bezier curves</li> </ul> <p>With these two properties and an algorithm for intersecting polygons, you can recurse to arbitrary precision:</p> <h2>bezInt(B<sub>1</sub>, B<sub>2</sub>):</h2> <ol start="2"> <li>Does bbox(B<sub>1</sub>) intersect bbox(B<sub>2</sub>)? <ul> <li>No: Return false.</li> <li>Yes: Continue.</li> </ul></li> <li>Is area(bbox(B<sub>1</sub>)) + area(bbox(B<sub>2</sub>)) &lt; threshold? <ul> <li>Yes: Return true.</li> <li>No: Continue.</li> </ul></li> <li>Split B<sub>1</sub> into B<sub>1a</sub> and B<sub>1b</sub> at <em>t</em> = 0.5</li> <li>Split B<sub>2</sub> into B<sub>2a</sub> and B<sub>2b</sub> at <em>t</em> = 0.5</li> <li>Return bezInt(B<sub>1a</sub>, B<sub>2a</sub>) || bezInt(B<sub>1a</sub>, B<sub>2b</sub>) || bezInt(B<sub>1b</sub>, B<sub>2a</sub>) || bezInt(B<sub>1b</sub>, B<sub>2b</sub>).</li> </ol> <p>This will be fast if the curves don't intersect -- is that the usual case?</p> <p><strong>[EDIT]</strong> It looks like the algorithm for splitting a Bezier curve in two is called <a href="http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm" rel="noreferrer">de Casteljau's algorithm</a>.</p>
3,235,131
Set TextView text from html-formatted string resource in XML
<p>I have some fixed strings inside my <code>strings.xml</code>, something like:</p> <pre><code>&lt;resources&gt; &lt;string name="somestring"&gt; &lt;B&gt;Title&lt;/B&gt;&lt;BR/&gt; Content &lt;/string&gt; &lt;/resources&gt; </code></pre> <p>and in my layout I've got a <code>TextView</code> which I'd like to fill with the html-formatted string.</p> <pre><code>&lt;TextView android:id="@+id/formattedtext" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/htmlstring"/&gt; </code></pre> <p>if I do this, the content of <code>formattedtext</code> is just the content of <code>somestring</code> stripped of any html tags and thus unformatted.</p> <p>I know that it is possible to set the formatted text programmatically with </p> <p><code>.setText(Html.fromHtml(somestring));</code> </p> <p>because I use this in other parts of my program where it is working as expected.</p> <p>To call this function I need an <code>Activity</code>, but at the moment my layout is just a simple more or less static view in plain XML and I'd prefer to leave it that way, to save me from the overhead of creating an <code>Activity</code> just to set some text.</p> <p>Am I overlooking something obvious? Is it not possible at all? Any help or workarounds welcome!</p> <p>Edit: Just tried some things and it seems that HTML formatting in xml has some restraints: </p> <ul> <li><p>tags must be written lowercase </p></li> <li><p>some tags which are mentioned <a href="https://stackoverflow.com/questions/3207769/android-textview-with-html-seperator">here</a> do not work, e.g. <code>&lt;br/&gt;</code> (it's possible to use <code>\n</code> instead)</p></li> </ul>
6,159,538
8
3
null
2010-07-13 07:51:10.633 UTC
91
2022-03-09 06:45:59.477 UTC
2017-05-23 11:47:08.953 UTC
null
-1
null
323,715
null
1
205
html|android|formatting|textview
226,696
<p>Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You <em><strong>CAN</strong></em> include raw HTML in strings.xml, as long as you wrap it in</p> <pre><code>&lt;![CDATA[ ...raw html... ]]&gt; </code></pre> <h3>Edge Cases:</h3> <ul> <li>Characters like apostrophe ('), double-quote (&quot;), and ampersand (&amp;) only need to be escaped if you want them to appear in the rendered text AS themselves, but they COULD be plausibly interpreted as HTML. <ul> <li><code>'</code> and <code>&quot;</code> can be represented as<code>\'</code> and <code>\&quot;</code>, or <code>&amp;apos;</code> and <code>&amp;quot;</code>.</li> <li><code>&lt;</code> and <code>&gt;</code> <em>always</em> need to be escaped as <code>&amp;lt;</code> and <code>&amp;gt;</code> if you literally want them to render as '&lt;' and '&gt;' in the text.</li> <li>Ampersand (&amp;) is a little more complicated. <ul> <li>Ampersand followed by whitespace renders as ampersand.</li> <li>Ampersand followed by one or more characters that don't form a valid HTML entity code render as Ampersand followed by those characters. So... <code>&amp;qqq;</code> renders as <code>&amp;qqq;</code>, but <code>&amp;lt;1</code> renders as <code>&lt;1</code>.</li> </ul> </li> </ul> </li> </ul> <p>Example:</p> <pre><code>&lt;string name=&quot;nice_html&quot;&gt; &lt;![CDATA[ &lt;p&gt;This is a html-formatted \&quot;string\&quot; with &lt;b&gt;bold&lt;/b&gt; and &lt;i&gt;italic&lt;/i&gt; text&lt;/p&gt; &lt;p&gt;This is another paragraph from the same \'string\'.&lt;/p&gt; &lt;p&gt;To be clear, 0 &amp;lt; 1, &amp; 10 &amp;gt; 1&lt;p&gt; ]]&gt; &lt;/string&gt; </code></pre> <p>Then, in your code:</p> <pre><code>TextView foo = (TextView)findViewById(R.id.foo); foo.setText(Html.fromHtml(getString(R.string.nice_html), FROM_HTML_MODE_LEGACY)); </code></pre> <p>IMHO, this is several orders of magnitude nicer to work with :-)</p> <hr /> <p><strong>August 2021 update:</strong> My original answer used Html.fromHtml(String), which was deprecated in API 24. The alternative <a href="https://developer.android.com/reference/android/text/Html#fromHtml(java.lang.String,%20int)" rel="noreferrer">fromHtml(String,int)</a> form is suggested as its replacement.</p> <p>FROM_HTML_MODE_LEGACY is likely to work... but one of the other flags might be a better choice for what you want to do.</p> <p>On a final note, if you'd prefer to render Android Spanned text suitable for use in a TextView using <strong>Markdown</strong> syntax instead of HTML, there are now multiple thirdparty libraries to make it easy including <a href="https://noties.io/Markwon" rel="noreferrer">https://noties.io/Markwon</a>.</p>
3,442,296
Empty or Null value display in SSRS text boxes
<p>Using SSRS (2008) what is the best way you have found to handle null or empty values and replace them with something else to display. The quite obvious solutions is</p> <pre><code>=IIF(IsNothing(Fields!MyField.Value),"NA",Fields!MyFields.Value) </code></pre> <p>That works though it is tedious, my hope was to find something like an EmptyText property on the textbox but alas nothing. Any ideas? Should I make a custom report item from the TextBox base that creates this property?</p>
3,444,062
9
0
null
2010-08-09 16:56:22.923 UTC
1
2019-12-15 21:44:50.06 UTC
null
null
null
null
40,714
null
1
19
ssrs-2008|reporting-services
147,093
<p>Call a custom function?</p> <p><a href="http://msdn.microsoft.com/en-us/library/ms155798.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms155798.aspx</a></p> <p>You could always put a case statement in there to handle different types of 'blank' data.</p>