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
5,411,355
How do I get an entire column in used range?
<p>I am trying to get a column, but limiting it to used range...</p> <pre><code>public static Excel.Application App = new Excel.Application(); public static Excel.Workbook WB; WB = App.Workbooks.Open("xxx.xls", ReadOnly: true); var sheet = (WB.Sheets[1] as Excel.Worksheet); // returns 65536 rows, I want only 82 (used range) sheet.get_Range("F:F"); sheet.UsedRange.get_Range("F:F").Rows.Count; // 65536 </code></pre> <p>How can I get it?</p>
5,411,554
3
0
null
2011-03-23 20:41:38.827 UTC
1
2015-12-12 12:47:54.13 UTC
2011-03-23 20:50:33.967 UTC
null
340,760
null
340,760
null
1
15
c#|excel|interop
46,539
<p>You can use</p> <pre><code>sheet.UsedRange.Columns[6, Type.Missing].Rows.Count </code></pre> <p>or this</p> <pre><code>sheet.UsedRange.Columns["F:F", Type.Missing].Rows.Count </code></pre>
18,402,853
Must the int main() function return a value in all compilers?
<p>Why is it not necessary to include the return statement while using int main() in some compilers for C++? What about Turbo C++?</p>
18,402,896
7
3
null
2013-08-23 12:27:10.447 UTC
8
2013-08-24 03:25:49.8 UTC
2013-08-23 17:24:18.1 UTC
null
1,203,129
null
2,565,398
null
1
21
c++|turbo-c++
14,559
<p>In C++, and in C99 and C11, it is a special rule of the language that if the control flow reaches the end of the <code>main</code> function, then the function impliclty returns <code>0</code>.</p>
15,011,508
Check if a string contains nothing but an URL in PHP
<p>I am wondering if this is a proper way to check, if a string contains nothing but an URL:</p> <pre><code>if (stripos($string, 'http') == 0 &amp;&amp; !preg_match('/\s/',$string)) { do_something(); } </code></pre> <p>stripos() checks if the string starts with "http"<br> preg_match() checks if the string contains spaces</p> <p>If not so, I assume that the string is nothing but an URL - but is that assumption valid? Are there better ways to achieve this?</p>
15,011,528
3
1
null
2013-02-21 20:23:07.28 UTC
10
2022-04-09 02:49:05.743 UTC
2013-02-21 20:25:16.177 UTC
null
250,259
null
381,821
null
1
53
php|url|validation
52,035
<p>Use <a href="http://www.php.net/manual/en/function.filter-var.php"><code>filter_var()</code></a></p> <pre><code>if (filter_var($string, FILTER_VALIDATE_URL)) { // you're good } </code></pre> <p>The filters can be even more refined. <a href="http://www.php.net/manual/en/filter.filters.validate.php">See the manual</a> for more on this.</p>
38,168,108
Spring Data Join with Specifications
<p>I'm trying to convert this raw sql query:</p> <pre><code>select product.* from following_relationship join product on following_relationship.following=product.owner_id where following_relationship.owner=input </code></pre> <p>Into Spring Data specifications, i think that my issue so far is on joining those tables.</p> <p>Here is my current conversion in Specification:</p> <pre><code>protected Specification&lt;Product&gt; test(final User user){ return new Specification&lt;Product&gt;() { @Override public Predicate toPredicate(Root&lt;Product&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb) { Join&lt;FollowingRelationship,Product&gt; pfJoin = query.from(FollowingRelationship.class).join("following"); pfJoin.on(cb.equal(pfJoin.get("following"),"owner")); return query.where(cb.equal(pfJoin.get("following"),user)).getGroupRestriction(); } }; } </code></pre> <p>And I'm getting this exception :</p> <pre><code>Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessA piUsageException: org.hibernate.hql.internal.ast.InvalidWithClauseException: with clause can only reference columns in the driving table </code></pre> <p>I will like to add that I'm new at Spring framework for instance this is my first application on spring, so my apologies for the newbie question ;)</p> <p>Edit: added entities Product, FollowingRelationShip</p> <pre><code>Entity @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "json_id_prop") public class FollowingRelationship extends BaseEntity { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "OWNER", referencedColumnName = "uuid") private User owner; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "FOLLOWING", referencedColumnName = "uuid") private User following; public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } public User getFollowing() { return following; } public void setFollowing(User following) { this.following = following; } } @Entity @Table(name = "product") @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "json_id_prop") public class Product extends BaseEntity { @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "OWNER_ID", referencedColumnName = "uuid") private User owner; @NotNull private String name; @NotNull private String description; @NotNull private String price; @NotNull private String brand; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getPrice() { return price; } public void setPrice(String price) { this.price = price; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public User getOwner() { return owner; } public void setOwner(User owner) { this.owner = owner; } } </code></pre> <p>Product and FollowingRelationShip entities do no have any explicit relationship, hence the join on my implementation about.What i want to achieve is to get all products from all users which another user follow in Spring data Specifications. </p>
38,244,217
1
4
null
2016-07-03 08:27:10.003 UTC
11
2020-11-21 04:31:58.587 UTC
2016-07-07 16:53:03.433 UTC
null
3,262,804
null
3,262,804
null
1
28
java|mysql|spring|spring-data
68,446
<p>EDIT: Ok, I did quite a mess here, but I hope this time I'm closer to the right answer.</p> <p>Consider (id's are auto-generated like 1 for John etc.):</p> <pre><code>INSERT INTO some_user (name) VALUES ('John'); INSERT INTO some_user (name) VALUES ('Ariel'); INSERT INTO some_user (name) VALUES ('Brian'); INSERT INTO some_user (name) VALUES ('Kelly'); INSERT INTO some_user (name) VALUES ('Tom'); INSERT INTO some_user (name) VALUES ('Sonya'); INSERT INTO product (owner_id,name) VALUES (1,'Nokia 3310'); INSERT INTO product (owner_id,name) VALUES (2,'Sony Xperia Aqua'); INSERT INTO product (owner_id,name) VALUES (3,'IPhone 4S'); INSERT INTO product (owner_id,name) VALUES (1,'Xiaomi MI5'); INSERT INTO product (owner_id,name) VALUES (3,'Samsung Galaxy S7'); INSERT INTO product (owner_id,name) VALUES (3,'Sony Xperia Z3'); INSERT INTO following_relationship (follower_id, owner_id) VALUES (4,1); INSERT INTO following_relationship (follower_id, owner_id) VALUES (5,1); INSERT INTO following_relationship (follower_id, owner_id) VALUES (4,2); INSERT INTO following_relationship (follower_id, owner_id) VALUES (6,2); INSERT INTO following_relationship (follower_id, owner_id) VALUES (6,3); INSERT INTO following_relationship (follower_id, owner_id) VALUES (1,3); </code></pre> <p>Based on simplified version of entities that You provided, and SomeUser Entity like:</p> <pre><code>@Entity public class FollowingRelationship { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinColumn(name = &quot;owner_id&quot;) SomeUser owner; @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinColumn(name = &quot;follower_id&quot;) SomeUser follower; ... @Entity public class Product { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @ManyToOne() @JoinColumn(name = &quot;owner_id&quot;) private SomeUser owner; @Column private String name; ... @Entity public class SomeUser { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id; @Column private String name; @OneToMany(mappedBy = &quot;owner&quot;) private Set&lt;Product&gt; products = new HashSet&lt;Product&gt;(); @OneToMany(mappedBy = &quot;owner&quot;) private Set&lt;FollowingRelationship&gt; ownedRelationships = new HashSet&lt;FollowingRelationship&gt;(); @OneToMany(mappedBy = &quot;follower&quot;) private Set&lt;FollowingRelationship&gt; followedRelationships = new HashSet&lt;FollowingRelationship&gt;(); </code></pre> <p>I have created Specification like:</p> <pre><code>public static Specification&lt;Product&gt; joinTest(SomeUser input) { return new Specification&lt;Product&gt;() { public Predicate toPredicate(Root&lt;Product&gt; root, CriteriaQuery&lt;?&gt; query, CriteriaBuilder cb) { Join&lt;Product,SomeUser&gt; userProd = root.join(&quot;owner&quot;); Join&lt;FollowingRelationship,Product&gt; prodRelation = userProd.join(&quot;ownedRelationships&quot;); return cb.equal(prodRelation.get(&quot;follower&quot;), input); } }; } </code></pre> <p>And now, we can execute the query with:</p> <pre><code>SomeUser someUser = someUserRepository.findOne(Specification.where(ProductSpecifications.userHasName(&quot;Kelly&quot;))); List&lt;Product&gt; thatProducts = productRepository.findAll(Specification.where(ProductSpecifications.joinTest(someUser))); System.out.println(thatProducts.toString()); </code></pre> <p>We get:</p> <pre><code>[Product [id=1, name=Nokia 3310], Product [id=4, name=Xiaomi MI5], Product [id=2, name=Sony Xperia Aqua]] </code></pre> <p>And this in My opinion is equivalent of: &quot;get all products from all users which another user follow&quot; - get products of all users that Kelly is following.</p>
8,231,060
jQuery Mobile Grid with auto-resizing images
<p>I have this grid:</p> <pre class="lang-html prettyprint-override"><code>&lt;div class="ui-grid-b"&gt; &lt;div class="ui-block-a"&gt; &lt;div class="ui-bar"&gt; &lt;a href="xxx.htm"&gt; &lt;img alt="alt..." src="image.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-block-b"&gt; &lt;div class="ui-bar"&gt; &lt;a href="xxx.htm"&gt; &lt;img alt="alt..." src="image.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-block-c"&gt; &lt;div class="ui-bar"&gt; &lt;a href="xxx.htm"&gt; &lt;img alt="alt..." src="image.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-block-a"&gt; &lt;div class="ui-bar"&gt; &lt;a href="xxx.htm"&gt; &lt;img alt="alt..." src="image.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-block-b"&gt; &lt;div class="ui-bar"&gt; &lt;a href="xxx.htm"&gt; &lt;img alt="alt..." src="image.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="ui-block-c"&gt; &lt;div class="ui-bar"&gt; &lt;a href="xxx.htm"&gt; &lt;img alt="alt..." src="image.jpg" /&gt; &lt;/a&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>But my images (180X80px) display "<em>cropped</em>" on the iPhone screen (320px width).</p> <p><strong>How can I auto resize them?</strong></p>
8,232,142
2
0
null
2011-11-22 17:30:25.383 UTC
6
2013-05-24 22:45:06.627 UTC
2013-05-24 22:45:06.627 UTC
null
1,887,779
null
494,826
null
1
10
image|jquery-mobile|grid|resize
41,022
<p>You can set the CSS of your images to automatically take-up all the horizontal space available on the screen:</p> <pre><code>&lt;style&gt; .ui-grid-b img { width : 100%; height : auto; } &lt;/style&gt; </code></pre> <p>This will set each image to completely fill its parent element (<code>&lt;div class="ui-bar"&gt;</code>) horizontally while maintaining its aspect ratio.</p>
7,857,323
iOS5 What does "Discarding message for event 0 because of too many unprocessed messages" mean?
<p>I'm doing some performance testing of my app and noticed that it takes exceedingly long to run some integrations. After a while, I got a whole bunch of </p> <pre><code>Discarding message for event 0 because of too many unprocessed messages </code></pre> <p>in the xcode console. What does this mean precisely? </p>
8,108,274
2
2
null
2011-10-22 04:05:37.663 UTC
16
2018-03-06 09:35:23.657 UTC
null
null
null
null
967,484
null
1
56
ios|xcode|performance|debugging
17,780
<p>This what Apple Technical Support says about this (after paying $49 for a Developer Tech Support Incident):</p> <p>These messages are coming from Core Location framework. The most likely cause of these messages is that there isn't a run loop running on the thread on which the CLLocationManager was created. (This implies that the CLLocationManager wasn't created on the main thread.) The messages that are being discarded are location messages: event 0 is a location and event 24 is an authorization status update, for example. Because the messages being discarded, you won't see the appropriate delegate callbacks being invoked. Did you set up a geofence or some other callback and isn't servicing it quickly enough? The queue limit appears to be 10 before it starts dumping events and logging this message. This information isn't publicly documented yet. I'm working with the Core Location team to improve the reported messages and see if this can be better documented.</p>
8,985,080
SSH connection to Amazon EC2 in Linux
<p>I am trying to ssh to amazon ec2 instance from shell using the following command</p> <pre><code>ssh -vi sec.ppk [email protected] </code></pre> <p>but failed to connect </p> <p>Here is the debug output generated by the above command</p> <pre><code>OpenSSH_5.3p1 Debian-3ubuntu7, OpenSSL 0.9.8k 25 Mar 2009 debug1: Reading configuration data /etc/ssh/ssh_config debug1: Applying options for * debug1: Connecting to ec2-xx.compute-1.amazonaws.com port 22. debug1: Connection established. debug1: identity file security1.ppk type -1 debug1: Remote protocol version 2.0, remote software version OpenSSH_5.5p1 Debian-4ubuntu5 debug1: match: OpenSSH_5.5p1 Debian-4ubuntu5 pat OpenSSH* debug1: Enabling compatibility mode for protocol 2.0 debug1: Local version string SSH-2.0-OpenSSH_5.3p1 Debian-3ubuntu7 debug1: SSH2_MSG_KEXINIT sent debug1: SSH2_MSG_KEXINIT received debug1: kex: server-&gt;client aes128-ctr hmac-md5 none debug1: kex: client-&gt;server aes128-ctr hmac-md5 none debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024&lt;1024&lt;8192) sent debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP debug1: SSH2_MSG_KEX_DH_GEX_INIT sent debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY debug1: Host 'ec2-xx.compute-1.amazonaws.com' is known and matches the RSA host key. debug1: Found key in /home/ma/.ssh/known_hosts:9 debug1: ssh_rsa_verify: signature correct debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received debug1: Authentications that can continue: publickey debug1: Next authentication method: publickey debug1: Trying private key: sec.ppk debug1: PEM_read_PrivateKey failed debug1: read PEM private key done: type &lt;unknown&gt; Enter passphrase for key 'sec.ppk': </code></pre> <p>Why it is asking passphrase for sec.ppk</p> <p>What is the issue? Can anyone help?</p> <p>Forgot to mention that i successfully made a connection using FileZilla with same above credentials</p>
8,988,184
3
5
null
2012-01-24 10:15:52.88 UTC
16
2015-12-03 07:11:33.5 UTC
2012-01-24 10:27:15.907 UTC
null
216,514
null
216,514
null
1
24
ubuntu|amazon-ec2|openssh
40,009
<p>Try with</p> <pre><code>ssh -i /directory/keyname.pem [email protected] </code></pre> <p>Where .pem is the key pair file you've created while you setup your instance.</p>
5,014,617
Why does HTML5 ignore line-height smaller than font-size?
<p><br> i'm switching some pages over to HTML5 which contains headlines that need to be set with a really small line height. Now since <code>&lt;!DOCTYPE html&gt;</code> any line-height below the font-size is ignored. I can space them out all I want, but no chance bringing them closer together. Anyone know why that is and if it's cureable?<br> Thanks, thomas</p> <p>Edit: Found it. My old markup was <code>&lt;a style="line-height:12px;" href="#"&gt;something&lt;/a&gt;</code> which worked in XHTML 1.0 transitional but not in HTML5.<br> I changed it to <code>&lt;div style="line-height:12px;"&gt;&lt;a href="#"&gt;something&lt;/a&gt;</code> an that works!<br> Thanks!</p>
9,814,390
4
4
null
2011-02-16 09:22:56.04 UTC
5
2017-09-07 07:16:48.847 UTC
2011-02-16 15:42:08.883 UTC
null
523,247
null
523,247
null
1
30
html|css
31,430
<p>Your <code>&lt;a&gt;</code> tag is an inline element and it appears in HTML5 inline elements defer to its parent 'block' element's line-height ( or all the way up to the <code>&lt;body&gt;</code> style if that is the immediate parent ).</p> <p>Example:</p> <pre><code>body { line-height:20px; } a { line-height:12px; } </code></pre> <p>and this markup:</p> <pre><code>&lt;body&gt; &lt;a href="#"&gt;test&lt;/a&gt; &lt;/body&gt; </code></pre> <p>The <code>&lt;a&gt;</code> tag will have a line-height of 20px not 12px.</p> <p>So your 'inline' <code>&lt;a style="line-height:12px;" href="#"&gt;something&lt;/a&gt;</code> didn't work but did when you wrapped it in the 'block'-level <code>&lt;div&gt;</code> element because block elements can dictate line-height.</p> <p>A better way than bloating your markup by wrapping your inline element in a block element, just use CSS to make the tag display 'inline-block'.</p> <p><code>&lt;a style="display:inline-block; line-height:12px;" href="#"&gt;something&lt;/a&gt;</code></p> <p>Even better, give your <code>&lt;a&gt;</code> a class (change 'xx' below to something semantic):</p> <pre><code>&lt;a class="xx" href="#"&gt;something&lt;/a&gt; </code></pre> <p>Then in your CSS file set that class to 'inline-block':</p> <pre><code>.xx { display:inline-block; line-height:12px; } </code></pre> <p>Hope that helps.</p>
5,394,799
Check select box has certain options with Capybara
<p>How do I use Capybara to check that a select box has certain values listed as options? It has to be compatible with Selenium...</p> <p>This is the HTML that I have:</p> <pre><code>&lt;select id="cars"&gt; &lt;option&gt;&lt;/option&gt; &lt;option value="volvo"&gt;Volvo&lt;/option&gt; &lt;option value="saab"&gt;Saab&lt;/option&gt; &lt;option value="mercedes"&gt;Mercedes&lt;/option&gt; &lt;option value="audi"&gt;Audi&lt;/option&gt; &lt;/select&gt; </code></pre> <p>This is what I want to do:</p> <pre><code>Then the "cars" field should contain the option "audi" </code></pre>
8,229,536
5
1
null
2011-03-22 16:46:43.79 UTC
8
2016-03-16 19:05:38.487 UTC
2012-09-24 21:58:20.02 UTC
null
525,478
null
1,421,542
null
1
56
ruby-on-rails|selenium|cucumber|capybara
31,296
<p>Try using the capybara rspec matcher <a href="http://www.rubydoc.info/github/jnicklas/capybara/master/Capybara%2FRSpecMatchers%3Ahave_select" rel="noreferrer">have_select(locator, options = {})</a> instead:</p> <pre><code>#Find a select box by (label) name or id and assert the given text is selected Then /^"([^"]*)" should be selected for "([^"]*)"$/ do |selected_text, dropdown| expect(page).to have_select(dropdown, :selected =&gt; selected_text) end #Find a select box by (label) name or id and assert the expected option is present Then /^"([^"]*)" should contain "([^"]*)"$/ do |dropdown, text| expect(page).to have_select(dropdown, :options =&gt; [text]) end </code></pre>
5,017,009
Confusion about vim folding - how to disable?
<ol> <li>When I open the file it looks like this: <img src="https://i.stack.imgur.com/fbmqn.png" alt="enter image description here"> or even this <img src="https://i.stack.imgur.com/6DpUG.png" alt="enter image description here"></li> <li>When I open all folds, they are closed again when I navigated to another buffer and came back. </li> <li>To be able to work with it, I have to apply <code>zR</code> each time when opening a buffer.</li> </ol> <p>I have these set up in <code>.vimrc</code>:</p> <pre><code>set foldlevelstart=99 set foldlevel=99 </code></pre> <p>Please point me on how to disable the folding, or at least making the navigation to another buffer not to close the opened ones.</p>
5,017,035
9
1
null
2011-02-16 13:27:18.133 UTC
29
2017-02-20 11:25:22.147 UTC
2015-03-26 20:29:56.063 UTC
null
2,498,729
null
350,789
null
1
131
vim|vi|folding
48,993
<p>You're not alone.</p> <pre><code>set nofoldenable " disable folding </code></pre>
5,573,096
Detecting WebP support
<p>How can I detect support for WebP via Javascript? I'd like to use feature detection rather than browser detection if possible, but I can't find a way to do so. Modernizr (<a href="http://www.modernizr.com" rel="noreferrer">www.modernizr.com</a>) doesn't check for it.</p>
27,232,658
21
10
null
2011-04-06 21:20:21.193 UTC
52
2021-10-23 10:49:41.44 UTC
2011-05-21 05:42:07.74 UTC
null
12,460
null
287,750
null
1
123
javascript|html|image|webp
80,308
<p>This is my solution - is taking around 6ms and I'm considering WebP is only a feature for a modern browser. Uses a different approach using canvas.toDataUrl() function instead of image as the way to detect the feature:</p> <pre><code>function support_format_webp() { var elem = document.createElement('canvas'); if (!!(elem.getContext &amp;&amp; elem.getContext('2d'))) { // was able or not to get WebP representation return elem.toDataURL('image/webp').indexOf('data:image/webp') == 0; } else { // very old browser like IE 8, canvas not supported return false; } } </code></pre>
12,123,661
Android, Change Image size in ImageView
<p>For Android, How can I change the image size in an ImageView in a layout?</p> <p>My image is <code>jpeg</code> format.</p>
12,123,781
4
0
null
2012-08-25 16:22:34.14 UTC
3
2014-04-15 13:23:31.547 UTC
2013-08-28 07:32:22.557 UTC
null
445,131
null
1,652,954
null
1
8
android|android-layout|imageview
45,387
<pre><code>&lt;ImageView android:id="@+id/imageView1" android:layout_margin="20dp" android:src="@drawable/stop" android:layout_width="50dp" android:layout_height="50dp"/&gt; </code></pre> <p>Just change width and height attribute.</p>
12,518,597
Check if variable returns true
<p>I want to echo 'success' if the variable is true. (I originally wrote "returns true" which only applies to functions.</p> <pre><code>$add_visits = add_post_meta($id, 'piwik_visits', $nb_visits, true); if($add_visits == true){ echo 'success'; } </code></pre> <p>Is this the equivalent of</p> <pre><code>$add_visits = add_post_meta($id, 'piwik_visits', $nb_visits, true); if($add_visits){ echo 'success'; } </code></pre> <p>Or does $add_visits exist whether it is 'true' or 'false';</p>
12,518,636
8
0
null
2012-09-20 18:24:14.823 UTC
null
2022-01-18 02:13:36.923 UTC
2012-09-20 18:36:09.547 UTC
null
719,689
null
719,689
null
1
9
php
75,938
<p>Testing <code>$var == true</code> is the same than just testing <code>$var</code>.</p> <p>You can read <a href="https://stackoverflow.com/questions/80646/how-do-the-equality-double-equals-and-identity-triple-equals-comparis">this SO question</a> on comparison operator. You can also read <a href="http://php.net/manual/en/language.operators.comparison.php" rel="noreferrer">PHP manual</a> on this topic.</p> <p>Note: a variable does not <em>return</em> <code>true</code>. It <strong>is</strong> <code>true</code>, or it <strong>evaluates</strong> to <code>true</code>. However, a function <strong>returns</strong> <code>true</code>.</p>
12,161,654
Restrict NSTextField to only allow numbers
<p>How do I restrict a <code>NSTextField</code> to allow only numbers/integers? I've found questions like this one, but they didn't help!</p>
12,190,317
9
4
null
2012-08-28 14:35:10.657 UTC
13
2021-11-28 18:01:00.057 UTC
2021-11-28 18:01:00.057 UTC
null
277,952
null
1,588,369
null
1
28
cocoa|nstextfield
20,004
<p>Try to make your own <code>NSNumberFormatter</code> subclass and check the input value in <code>-isPartialStringValid:newEditingString:errorDescription:</code> method.</p> <pre><code>@interface OnlyIntegerValueFormatter : NSNumberFormatter @end @implementation OnlyIntegerValueFormatter - (BOOL)isPartialStringValid:(NSString*)partialString newEditingString:(NSString**)newString errorDescription:(NSString**)error { if([partialString length] == 0) { return YES; } NSScanner* scanner = [NSScanner scannerWithString:partialString]; if(!([scanner scanInt:0] &amp;&amp; [scanner isAtEnd])) { NSBeep(); return NO; } return YES; } @end </code></pre> <p>And then set this formatter to your <code>NSTextField</code>:</p> <pre><code>OnlyIntegerValueFormatter *formatter = [[[OnlyIntegerValueFormatter alloc] init] autorelease]; [textField setFormatter:formatter]; </code></pre>
12,570,807
Format string to a 3 digit number
<p>Instead of doing this, I want to make use of <code>string.format()</code> to accomplish the same result:</p> <pre><code>if (myString.Length &lt; 3) { myString = "00" + 3; } </code></pre>
12,570,898
9
2
null
2012-09-24 18:34:20.537 UTC
7
2019-03-27 14:45:10.193 UTC
2019-03-27 14:45:10.193 UTC
null
306,028
null
41,508
null
1
83
c#|string|numbers|format
175,330
<p>If you're just formatting a number, you can just provide the proper <a href="http://msdn.microsoft.com/en-us/library/0c899ak8.aspx">custom numeric format</a> to make it a 3 digit string directly:</p> <pre><code>myString = 3.ToString("000"); </code></pre> <p>Or, alternatively, use the <a href="http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx">standard D format string</a>:</p> <pre><code>myString = 3.ToString("D3"); </code></pre>
19,166,599
ASP.NET Identity Cookie across subdomains
<p>For forms authentication I used this in web.config (note the domain attribute):</p> <pre><code>&lt;authentication mode="Forms"&gt; &lt;forms loginUrl="~/Account/Login" timeout="2880" name=".ASPXAUTH" protection="Validation" path="/" domain=".myserver.dev" /&gt; &lt;/authentication&gt; </code></pre> <p>How is a single sign-on across subdomains configured for the new ASP.NET Identity Framework in Mvc 5?</p> <p>More Info:</p> <p>I am creating a multitenant application. Each client will be on a subdomain:</p> <p>client1.myapp.com</p> <p>client2.myapp.com</p> <p>I want a user to be able to sign on to <code>client1.myapp.com</code> and then go to <code>client2.myapp.com</code> and still be signed in. This was easy with forms authentication. I'm trying to figure out how to do it with the new Identity Framework.</p> <p>EDIT</p> <p>Here is the code that eventually worked for me:</p> <pre><code>app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Application", LoginPath = "/Account/Login", CookieDomain = ".myapp.com" }); </code></pre>
19,230,348
4
3
null
2013-10-03 18:32:47.047 UTC
23
2015-09-28 10:18:23.97 UTC
2013-10-14 21:19:59.69 UTC
null
836,186
null
836,186
null
1
44
c#|authentication|forms-authentication|asp.net-identity
27,616
<p>In Startup.Auth.cs, you will see something like:</p> <p>for RC:</p> <pre><code>app.UseSignInCookies(); </code></pre> <p>This was removed in RTM and replaced with the explicit configuration of the cookie auth:</p> <pre><code> app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); </code></pre> <p>The CookieAuthenticationOptions class has a CookieDomain property which is what you are looking for I believe.</p>
19,300,020
Python match a string with regex
<p>I need a python regular expression to check if a word is present in a string. The string is separated by commas, potentially.</p> <p>So for example,</p> <pre><code>line = 'This,is,a,sample,string' </code></pre> <p>I want to search based on "sample", this would return true. I am crappy with reg ex, so when I looked at the python docs, I saw something like</p> <pre><code>import re re.match(r'sample', line) </code></pre> <p>But I don't know why there was an 'r' before the text to be matched. Can someone help me with the regular expression?</p>
19,300,157
6
5
null
2013-10-10 15:28:10.74 UTC
5
2022-08-08 02:40:44.417 UTC
2014-01-11 15:26:52.06 UTC
null
1,400,768
null
1,108,761
null
1
47
python|regex
175,760
<p>Are you sure you need a regex? It seems that you only need to know if a word is present in a string, so you can do:</p> <pre><code>&gt;&gt;&gt; line = 'This,is,a,sample,string' &gt;&gt;&gt; "sample" in line True </code></pre>
3,328,495
How to read whole file in Ruby?
<p>Is there an in-built function in Ruby to read the whole file without using any loop? So far, I have only come across methods that read in chunks (line or character).</p>
3,328,510
3
3
null
2010-07-25 08:06:20.283 UTC
4
2017-02-27 17:56:47.55 UTC
2016-06-03 07:02:05.167 UTC
null
388,350
null
388,350
null
1
68
ruby|file
46,189
<pre><code>IO.read("filename") </code></pre> <p>or</p> <pre><code>File.read("filename") </code></pre>
36,762,248
Why is std::queue not thread-safe?
<p>The topic says it. I don't understand why the std::queue (or in general: any queue) is not thread-safe by its nature, when there is no iterator involved as with other datastructures.</p> <p>According to the common rule that</p> <ul> <li>at least one thread is writing to ...</li> <li>and another thread is reading from a shared resource </li> </ul> <p>I should have gotten a conflict in the following example code:</p> <pre><code>#include "stdafx.h" #include &lt;queue&gt; #include &lt;thread&gt; #include &lt;iostream&gt; struct response { static int &amp; getCount() { static int theCount = 0; return theCount; } int id; }; std::queue&lt;response&gt; queue; // generate 100 response objects and push them into the queue void produce() { for (int i = 0; i &lt; 100; i++) { response r; r.id = response::getCount()++; queue.push(r); std::cout &lt;&lt; "produced: " &lt;&lt; r.id &lt;&lt; std::endl; } } // get the 100 first responses from the queue void consume() { int consumedCounter = 0; for (;;) { if (!queue.empty()) { std::cout &lt;&lt; "consumed: " &lt;&lt; queue.front().id &lt;&lt; std::endl; queue.pop(); consumedCounter++; } if (consumedCounter == 100) break; } } int _tmain(int argc, _TCHAR* argv[]) { std::thread t1(produce); std::thread t2(consume); t1.join(); t2.join(); return 0; } </code></pre> <p>Everything seems to be working fine: - No integrity violated / data corrupted - The order of the elements in which the consumer gets them are correct (0&lt;1&lt;2&lt;3&lt;4...), of course the order in which the prod. and cons. are printing is random as there is no signaling involved.</p>
36,763,257
1
12
null
2016-04-21 07:11:44.133 UTC
10
2018-06-22 08:37:21.237 UTC
null
null
null
null
2,755,279
null
1
15
c++|multithreading|queue
36,127
<p>Imagine you check for <code>!queue.empty()</code>, enter the next block and before getting to access <code>queue.first()</code>, another thread would remove (pop) the one and only element, so you query an empty queue.</p> <p>Using a synchronized queue like the following</p> <pre><code>#pragma once #include &lt;queue&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; template &lt;typename T&gt; class SharedQueue { public: SharedQueue(); ~SharedQueue(); T&amp; front(); void pop_front(); void push_back(const T&amp; item); void push_back(T&amp;&amp; item); int size(); bool empty(); private: std::deque&lt;T&gt; queue_; std::mutex mutex_; std::condition_variable cond_; }; template &lt;typename T&gt; SharedQueue&lt;T&gt;::SharedQueue(){} template &lt;typename T&gt; SharedQueue&lt;T&gt;::~SharedQueue(){} template &lt;typename T&gt; T&amp; SharedQueue&lt;T&gt;::front() { std::unique_lock&lt;std::mutex&gt; mlock(mutex_); while (queue_.empty()) { cond_.wait(mlock); } return queue_.front(); } template &lt;typename T&gt; void SharedQueue&lt;T&gt;::pop_front() { std::unique_lock&lt;std::mutex&gt; mlock(mutex_); while (queue_.empty()) { cond_.wait(mlock); } queue_.pop_front(); } template &lt;typename T&gt; void SharedQueue&lt;T&gt;::push_back(const T&amp; item) { std::unique_lock&lt;std::mutex&gt; mlock(mutex_); queue_.push_back(item); mlock.unlock(); // unlock before notificiation to minimize mutex con cond_.notify_one(); // notify one waiting thread } template &lt;typename T&gt; void SharedQueue&lt;T&gt;::push_back(T&amp;&amp; item) { std::unique_lock&lt;std::mutex&gt; mlock(mutex_); queue_.push_back(std::move(item)); mlock.unlock(); // unlock before notificiation to minimize mutex con cond_.notify_one(); // notify one waiting thread } template &lt;typename T&gt; int SharedQueue&lt;T&gt;::size() { std::unique_lock&lt;std::mutex&gt; mlock(mutex_); int size = queue_.size(); mlock.unlock(); return size; } </code></pre> <p>The call to <code>front()</code> waits until it has an element and locks the underlying queue so only one thread may access it at a time.</p>
38,228,962
HTML title attribute style
<p>How do I change the styling of the title attribute in the following tag without using javascript or CSS, since I am inserting the HTML into a specific spot in an otherwise uneditable doc.</p> <pre><code> &lt;span title = "This is information"&gt; This is a test &lt;/span&gt; </code></pre>
38,232,206
1
8
null
2016-07-06 16:23:04.977 UTC
2
2019-07-30 07:04:13.35 UTC
2016-07-06 16:32:43.1 UTC
null
6,556,957
null
6,556,957
null
1
8
html
42,684
<p><a href="https://jsfiddle.net/LvjaxLfn/153/" rel="noreferrer">https://jsfiddle.net/LvjaxLfn/153/</a></p> <pre><code>&lt;span aria-label="This is information"&gt;This is a test&lt;/span&gt; span:hover { position: relative; } span[aria-label]:hover:after { content: attr(aria-label); padding: 4px 8px; position: absolute; left: 0; top: 100%; white-space: nowrap; z-index: 20; background:red; } </code></pre> <p>Using an aria label to keep accessibility </p> <p>You could also add a transition delay to make it show up after a delay like a native html title</p> <p><a href="https://jsfiddle.net/f9zna6k2/10/" rel="noreferrer">https://jsfiddle.net/f9zna6k2/10/</a></p> <pre><code>span { position: relative; cursor: pointer; } span[aria-label]:after { opacity:0; content: attr(aria-label); padding: 4px 8px; position: absolute; left: 0; top: 100%; white-space: nowrap; z-index: 20; background:red; transition: opacity 0.5s; pointer-events:none; } span[aria-label]:hover:after { opacity:1; transition-delay:1.5s; } </code></pre>
11,265,039
Set UITableView Delegate and DataSource
<p>This is my problem: I have this small <code>UITableView</code> in my storyboard:<img src="https://i.stack.imgur.com/msfw2.png" alt="enter image description here"></p> <p>And this is my code:</p> <p><strong>SmallTableViewController.h</strong></p> <pre><code>#import &lt;UIKit/UIKit.h&gt; #import "SmallTable.h" @interface SmallViewController : UIViewController @property (weak, nonatomic) IBOutlet UITableView *myTable; @end </code></pre> <p><strong>SmallTableViewController.m</strong></p> <pre><code>#import "SmallViewController.h" @interface SmallViewController () @end @implementation SmallViewController @synthesize myTable = _myTable; - (void)viewDidLoad { SmallTable *myTableDelegate = [[SmallTable alloc] init]; [super viewDidLoad]; [self.myTable setDelegate:myTableDelegate]; [self.myTable setDataSource:myTableDelegate]; // Do any additional setup after loading the view, typically from a nib. } - (void)viewDidUnload { [super viewDidUnload]; // Release any retained subviews of the main view. } - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } @end </code></pre> <p>Now as you can see, I want to set an instance called myTableDelegate as Delegate and DataSource of myTable.</p> <p>This is the Source of SmallTable class.</p> <p><strong>SmallTable.h</strong></p> <pre><code>#import &lt;Foundation/Foundation.h&gt; @interface SmallTable : NSObject &lt;UITableViewDelegate , UITableViewDataSource&gt; @end </code></pre> <p><strong>SmallTable.m</strong></p> <pre><code>@implementation SmallTable - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 0; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return 5; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; // Configure the cell... cell.textLabel.text = @"Hello there!"; return cell; } #pragma mark - Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { NSLog(@"Row pressed!!"); } @end </code></pre> <p>I implemented all the <code>UITableViewDelegate</code> and <code>UITableViewDataSource</code> method that the app need. Why it just crash before the view appear??</p> <p>Thanks!!</p>
11,265,562
5
3
null
2012-06-29 15:53:36.097 UTC
4
2016-04-27 05:16:41.733 UTC
2016-04-27 05:16:41.733 UTC
null
5,020,932
null
1,417,901
null
1
15
iphone|objective-c|uitableview|delegates
39,592
<p>rickster is right. But I guess you need to use a <code>strong</code> qualifier for your property since at the end of your <code>viewDidLoad</code> method the object will be deallocated anyway.</p> <pre><code>@property (strong,nonatomic) SmallTable *delegate; // inside viewDidload [super viewDidLoad]; self.delegate = [[SmallTable alloc] init]; [self.myTable setDelegate:myTableDelegate]; [self.myTable setDataSource:myTableDelegate]; </code></pre> <p>But is there any reason to use a separated object (data source and delegate) for your table? Why don't you set <code>SmallViewController</code> as both the source and the delegate for your table?</p> <p>In addition you are not creating the cell in the correct way. These lines do nothing:</p> <pre><code>static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; // Configure the cell... cell.textLabel.text = @"Hello there!"; </code></pre> <p><code>dequeueReusableCellWithIdentifier</code> simply retrieves from the table "cache" a cell that has already created and that can be reused (this to avoid memory consumption) but you haven't created any.</p> <p>Where are you doing <code>alloc-init</code>? Do this instead:</p> <pre><code>static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(!cell) { cell = // alloc-init here } // Configure the cell... cell.textLabel.text = @"Hello there!"; </code></pre> <p>Furthermore say to <code>numberOfSectionsInTableView</code> to return 1 instead of 0:</p> <pre><code>- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } </code></pre>
12,928,062
Efficient methods for Incrementing and Decrementing in the same Loop
<p>Suppose some situations exist where you would like to increment and decrement values in the same for loop. In this set of situations, there are some cases where you can "cheat" this by taking advantage of the nature of the situation -- for example, reversing a string. </p> <p>Because of the nature of building strings, we don't really have to manipulate the iterate or add an additional counter:</p> <pre><code>public static void stringReversal(){ String str = "Banana"; String forwardStr = new String(); String backwardStr = new String(); for(int i = str.length()-1; i &gt;= 0; i--){ forwardStr = str.charAt(i)+forwardStr; backwardStr = backwardStr+str.charAt(i); } System.out.println("Forward String: "+forwardStr); System.out.println("Backward String: "+backwardStr); } </code></pre> <p>However, suppose a different case exists where we just want to print a decremented value, from the initial value to 0, and an incremented value, from 0 to the initial value.</p> <pre><code>public static void incrementAndDecrement(){ int counter = 0; for(int i = 10; i &gt;= 0; i--){ System.out.println(i); System.out.println(counter); counter++; } } </code></pre> <p>This works well enough, but having to create a second counter to increment seems messy. Are there any mathematical tricks or tricks involving the for loop that could be used that would make <code>counter</code> redundant?</p>
12,928,084
2
2
null
2012-10-17 06:01:49.207 UTC
1
2016-03-03 07:56:39.89 UTC
null
null
null
null
775,544
null
1
9
java|for-loop|increment|decrement
39,449
<p>Well it <em>looks</em> like you just want:</p> <pre><code>for(int i = 10; i &gt;= 0; i--){ System.out.println(i); System.out.println(10 - i); } </code></pre> <p>Is that the case? Personally I'd normally write this as an <em>increasing</em> loop, as I find it easier to think about that:</p> <pre><code>for (int i = 0; i &lt;= 10; i++) { System.out.println(10 - i); System.out.println(i); } </code></pre> <p>Note that your string example is <em>really</em> inefficient, by the way - far more so than introducing an extra variable. Given that you know the lengths involved to start with, you can just start with two <code>char[]</code> of the right size, and populate the right index each time. Then create a string from each afterwards. Again, I'd do this with an <em>increasing</em> loop:</p> <pre><code>char[] forwardChars = new char[str.length()]; char[] reverseChars = new char[str.length()]; for (int i = 0; i &lt; str.length(); i++) { forwardChars[i] = str.charAt(i); reverseChars[reverseChars.length - i - 1] = str.charAt(i); } String forwardString = new String(forwardChars); String reverseString = new String(reverseChars); </code></pre> <p>(Of course <code>forwardString</code> will just be equal to <code>str</code> in this case anyway...)</p>
13,075,822
Split an array in ruby based on some condition
<p>I have an array named <code>@level1</code> which has a value like this:</p> <pre><code>[ [3.1, 4], [3.0, 7], [2.1, 5], [2.0, 6], [1.9, 3] ] </code></pre> <p>I want to split this into two arrays such that the first array (<code>@arr1</code>) contains the values till <code>2.1</code> and the second array (<code>@arr2</code>) contains values after it.</p> <p>After doing that, I would reverse-sort my second array by doing something like this:</p> <pre><code>@arr2 = @arr2.sort_by { |x, _| x }.reverse </code></pre> <p>I would then like to merge this array to <code>@arr1</code>. Can someone help me how to split the array and then merge them together?</p>
13,076,075
2
3
null
2012-10-25 19:28:59.01 UTC
3
2021-07-01 10:16:22.723 UTC
2012-10-25 20:57:53.347 UTC
null
314,166
null
1,450,521
null
1
30
ruby|arrays|multidimensional-array
19,609
<p>Try the <a href="https://ruby-doc.org/core-3.0.1/Enumerable.html#method-i-partition" rel="noreferrer">partition</a> method</p> <pre><code>@arr1, @arr2 = @level1.partition { |x| x[0] &gt; 2.1 } </code></pre> <p>The condition there may need to be adjusted, since that wasn't very well specified in the question, but that should provide a good starting point.</p>
13,056,683
HTML attribute with/without quotes
<p>Is there any difference between the following code blocks?</p> <pre class="lang-html prettyprint-override"><code>&lt;iframe src=&quot;http://example.com&quot; width=100%&gt;&lt;/iframe&gt; </code></pre> <pre class="lang-html prettyprint-override"><code>&lt;iframe src=http://example.com width=&quot;100%&quot;&gt;&lt;/iframe&gt; </code></pre> <p>I've tried both and both seem to work, but I'm asking just in case there's something I need to be careful with?</p>
13,056,720
6
2
null
2012-10-24 19:53:57.347 UTC
4
2020-11-27 08:51:03.433 UTC
2020-11-27 08:51:03.433 UTC
null
12,860,895
null
1,736,691
null
1
34
html|quotes
16,007
<p>It is all about the true validity of HTML markup. It's for what W3C (WWW Consortium) work for. Many things might work in HTML but they have to be validated in order to be more carefully recognized by the web browser. You can even omit the <code>&lt;html&gt;</code> and <code>&lt;/html&gt;</code> tags at the start and end, but it is not recommended at all, nobody does it and it is considered as a 'bad code'.</p> <p>Therefore, it is more valid to put them in quotes.</p>
37,335,383
Can a C++ default argument be initialized with another argument?
<p>For a default argument in C++, does the value need to be a constant or will another argument do?</p> <p>That is, can the following work?</p> <pre><code>RateLimiter(unsigned double rateInPermitsPerSecond, unsigned int maxAccumulatedPermits = rateInPermitsPerSecond); </code></pre> <p>Currently I am getting an error:</p> <blockquote> <p>RateLimiter.h:13: error: ‘rateInPermitsPerSecond’ was not declared in this scope</p> </blockquote>
37,335,422
5
8
null
2016-05-19 22:59:40.513 UTC
1
2016-05-25 05:21:23.497 UTC
2016-05-21 10:09:31.307 UTC
null
63,550
null
1,918,858
null
1
61
c++
6,171
<p>Another argument cannot be used as the default value. The standard states:</p> <blockquote> <p><strong>8.3.6 Default arguments</strong><br>...<br> <sup>9</sup> A default argument is evaluated each time the function is called with no argument for the corresponding parameter. The order of evaluation of function arguments is unspecified. Consequently, parameters of a function shall not be used in a default argument, even if they are not evaluated.</p> </blockquote> <p>and illustrates it with the following sample:</p> <pre><code>int f(int a, int b = a); // error: parameter a // used as default argument </code></pre>
17,062,065
How to select data items of a certain length?
<p>How do I select the row of a column such that the row size is &lt;= 5 ? Is there a query for this which will work on most/all databases ?</p> <p>eg. id, first_name</p> <p>Select only those people whose firstname is more than 10 characters. Their name is too long ?</p>
17,064,762
4
4
null
2013-06-12 09:30:48.497 UTC
2
2020-04-29 12:43:21.443 UTC
null
null
null
null
2,442,667
null
1
14
sql
93,584
<p>If you are bound to use a specific RDBMS then the solution is easy.</p> <pre><code>Use the LENGTH function. </code></pre> <p>Depending upon your database the length function can be LEN, Length, CarLength. Just search google for it.</p> <p>According to your question </p> <blockquote> <p>How do I select the row of a column such that the row size is <strong>&lt;= 5</strong> ? Is there a query for this which will work on most/all databases ?</p> </blockquote> <p>solution can be</p> <pre><code>SELECT * FROM TableName WHERE LENGTH(name) &lt;= 5 </code></pre> <p>If you want something that can work with almost all the database and I assume that the length of your string that you want to fetch is of a significant small length. Example 5 or 8 characters then you can use something like this</p> <pre><code> SELECT * FROM tab WHERE colName LIKE '' OR colName LIKE '_' OR colName LIKE '__' OR colName LIKE '___' OR colName LIKE '____' OR colName LIKE '_____' </code></pre> <p>This works with almost all major DBMS.</p> <p>see example:</p> <p><a href="http://sqlfiddle.com/#!6/dc25e/1" rel="noreferrer">SQL Server</a></p> <p><a href="http://sqlfiddle.com/#!2/13843/2" rel="noreferrer">MySQL</a></p> <p><a href="http://sqlfiddle.com/#!4/76d01/1" rel="noreferrer">Oracle</a></p> <p><a href="http://sqlfiddle.com/#!1/3020b/1" rel="noreferrer">Postgre SQL</a></p> <p><a href="http://sqlfiddle.com/#!7/e17b2/1" rel="noreferrer">SQLite</a></p>
16,997,141
Writing Structs to a file in c
<p>Is it possible to write an entire struct to a file</p> <p>example:</p> <pre><code>struct date { char day[80]; int month; int year; }; </code></pre>
16,997,175
1
2
null
2013-06-08 07:21:46.51 UTC
10
2015-11-06 10:48:37.023 UTC
2015-11-06 10:48:37.023 UTC
null
322,537
null
1,726,847
null
1
34
c|file-io|structure
80,078
<blockquote> <p>Is it possible to write an entire struct to a file</p> </blockquote> <p>Your question is actually writing struct instances into file.</p> <ol> <li>You can use <code>fwrite</code> function to achieve this.</li> <li>You need to pass the reference in first argument.</li> <li><code>sizeof</code> each object in the second argument</li> <li>Number of such objects to write in 3rd argument.</li> <li>File pointer in 4th argument. </li> <li>Don't forget to open the file in <code>binary mode</code>.</li> <li>You can read objects from file using fread.</li> <li><p>Careful with endianness when you are writing/reading in little endian systems and reading/writing in big endian systems and viceversa. Read <a href="https://stackoverflow.com/questions/13994674/how-to-write-endian-agnostic-c-c-code">how-to-write-endian-agnostic-c-c-code</a></p> <pre><code>struct date *object=malloc(sizeof(struct date)); strcpy(object-&gt;day,"Good day"); object-&gt;month=6; object-&gt;year=2013; FILE * file= fopen("output", "wb"); if (file != NULL) { fwrite(object, sizeof(struct date), 1, file); fclose(file); } </code></pre></li> </ol> <p>You can read them in the same way....using <code>fread</code></p> <pre><code> struct date *object2=malloc(sizeof(struct date)); FILE * file= fopen("output", "rb"); if (file != NULL) { fread(object2, sizeof(struct date), 1, file); fclose(file); } printf("%s/%d/%d\n",object2-&gt;day,object2-&gt;month,object2-&gt;year); </code></pre>
57,903,061
forEach loop through two arrays at the same time in javascript
<p>I want to build a <code>for</code> loop that iterates through two variables at the same time. <code>n</code> is an array and <code>j</code> goes from 0 to 16.</p> <pre><code>var n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]; var m = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16]; m.forEach(k =&gt; { n.forEach(i =&gt; { console.log(i, k) }); }; </code></pre> <p>The final result should output:</p> <pre><code>1,0 2,1 3,2 5,3 (...) </code></pre> <p>Unfortunately this loop doesn't do that for some reason as it repeats every number 17 times.</p> <p>What am I missing here?</p>
57,903,085
1
4
null
2019-09-12 08:49:35.86 UTC
7
2022-08-29 23:51:21.857 UTC
2019-09-12 08:56:55.403 UTC
null
7,571,176
null
7,571,176
null
1
35
javascript|for-loop|vue.js|foreach
66,167
<p>Use the second parameter <code>forEach</code> accepts instead, which will be the current index you're iterating over:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>n = [1,2,3,5,7,8,9,11,12,13,14,16,17,18,20,21,22]; n.forEach((element, index) =&gt; { console.log(element, index); });</code></pre> </div> </div> </p> <p>If you have two separate arrays to begin with, in each iteration, access the <code>[index]</code> property of the other array:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var n = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 20, 21, 22]; var m = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; n.forEach((num1, index) =&gt; { const num2 = m[index]; console.log(num1, num2); });</code></pre> </div> </div> </p>
9,798,008
Connection between mmap user call to mmap kernel call
<p>I am trying to understand how mmap works. User level call of mmap looks like below. </p> <pre><code>void *mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t off); </code></pre> <p>but kernel level mmap for a particular device driver looks like: </p> <pre><code>int &lt;device_name&gt;_mmap(struct file*fp, struct vm_area_struct *vma) </code></pre> <p>I also looked at the source code but I am not able to find the connection in between.</p> <p>How does mmap for particular device gets its arguments "struct vm_area_struct *vma" ? Can you please help me understand that ? Appreciate your help.</p>
9,798,514
1
3
null
2012-03-21 02:53:13.863 UTC
9
2012-03-21 04:15:52.417 UTC
2012-03-21 03:06:06.25 UTC
null
134,633
null
802,199
null
1
9
c|linux-kernel|device-driver|linux-device-driver
5,669
<p>The <code>mmap()</code> library call is implemented by libc, which converts the offset in bytes to an offset in pages, then calls the <code>mmap_pgoff()</code> system call.</p> <p>The <a href="http://lxr.linux.no/#linux+v3.3/mm/mmap.c#L1080"><code>mmap_pgoff()</code></a> system call fetches the <code>struct file *</code> corresponding to the file descriptor argument, and calls <code>do_mmap_pgoff()</code>.</p> <p><a href="http://lxr.linux.no/#linux+v3.3/mm/mmap.c#L942"><code>do_mmap_pgoff()</code></a> calculates the actual address and length that will be used based on the hint and the available address space, converts the provided flags into VM flags, and tests for permission to perform the mapping. It then calls <code>mmap_region()</code>.</p> <p><a href="http://lxr.linux.no/#linux+v3.3/mm/mmap.c#L1193"><code>mmap_region()</code></a> removes any prior mappings in the area being replaced by the new mapping, performs memory accounting and creates the new <code>struct vm_area_struct</code> describing the region of the address space being mapped (this encapsulates the address, length, offset and VM flags of the mapping). It then calls the file's <code>-&gt;mmap()</code> implementation, passing the <code>struct file *</code> and <code>struct vm_area_struct *</code>. For device files this will be a call to the device's mmap implementation function.</p>
9,877,744
Request-URI Too Large
<p>Got this error on a big <code>$_GET</code> query in size ~9 000 symbols (they are divided into ~10 variables).</p> <pre><code>Request-URI Too Large The requested URL's length exceeds the capacity limit for this server. </code></pre> <p>What is a workaround for this problem?</p>
9,878,210
3
9
null
2012-03-26 18:36:14.84 UTC
2
2013-09-15 12:22:07.37 UTC
2012-06-23 11:49:47.367 UTC
null
367,456
null
723,627
null
1
10
php|get|request|capacity
64,851
<p>There is no workaround if you want pass all these info with GET without change server configuration.</p> <p>Other solutions:</p> <ul> <li>Use POST with a form (or an hidden form and add onclick event at your link that submit it)</li> <li>Use Session. When the server generates the link, store it in $_SESSION with an unique id (or RID, it can be md5 of complete URI) and pass it via GET.</li> <li>Use Database or file storage (with the same procedure of session)</li> </ul>
10,131,908
Only include files that match a given pattern in a recursive diff
<p>How can you perform a recursive diff of the files in two directories (a and b):</p> <pre><code>$ diff -r a b </code></pre> <p>but only look at files whose name matches a given pattern. For example, using the same syntax available in the find command, this would look like:</p> <pre><code>$ diff -r a b -name "*crazy*" </code></pre> <p>which would show diffs between files with the same name and path in a and b, which have "crazy" in their name.</p> <p>Effectively, I'm looking for the opposite of the --exclude option which is available in diff.</p>
10,132,592
2
1
null
2012-04-12 21:10:52.497 UTC
8
2018-11-09 12:49:25.07 UTC
2013-08-26 21:28:03.717 UTC
null
182,677
null
182,677
null
1
27
shell|unix|diff
9,894
<p>Perhaps this is a bit indirect, but it ought to work. You can use <code>find</code> to get a list of files that <em>don't</em> match the pattern, and then "exclude" all those files:</p> <pre><code>find a b -type f ! -name 'crazy' -printf '%f\n' | diff -r a b -X - </code></pre> <p>The <code>-X -</code> will make <code>diff</code> read the patterns from stdin and exclude anything that matches. This should work provided your files don't have funny chars like <code>*</code> or <code>?</code> in their names. The only downside is that your diff won't include the <code>find</code> command, so the listed <code>diff</code> command is not that useful.</p> <p>(I've only tested it with GNU <code>find</code> and <code>diff</code>).</p> <p><strong>EDIT</strong>:</p> <p>Since only non-GNU <code>find</code> doesn't have <code>-printf</code>, <code>sed</code> could be used as an alternative:</p> <pre><code>find a b -type f ! -name '*crazy*' -print | sed -e 's|.*/||' | diff -X - -r a b </code></pre> <p>That's also assuming that non-GNU <code>diff</code> has <code>-X</code> which I don't know.</p>
10,191,139
Doctrine2 $em->persist($entity) on foreach loop
<p>I'm currently in a spot, where I need to create or update entities in a foreach loop.</p> <p>So I'm doing the following (short code):</p> <pre><code>foreach ($dataset as $data) { $entity = new Entity(); // ---- Some setting operations on the entity $em-&gt;persist($entity); } $em-&gt;flush(); </code></pre> <p>The thing I was expecting is that Doctrine manages the entities and then with one statement inserts the entities into the table.</p> <p>But it occurs, that Doctrine makes one statement for each created entity. Since the $dataset array can be pretty big (a lot of entities created), I would like to have it packed into one statement.</p> <p>How can I achieve this?</p>
10,193,058
3
11
null
2012-04-17 12:20:28.127 UTC
7
2019-08-02 10:03:55.107 UTC
2012-04-17 12:21:38.83 UTC
null
353,612
null
735,226
null
1
31
symfony|doctrine-orm
41,488
<p>As suggested by <a href="https://stackoverflow.com/users/353612/greg0ire">greg0ire</a>, this link describes how Doctrine optimizes INSERT statements : <a href="https://www.slideshare.net/jwage/doctrine-2-not-the-same-old-php-orm/47-sflive2010_Insert_Performance_Inserting_20" rel="noreferrer">https://www.slideshare.net/jwage/doctrine-2-not-the-same-old-php-orm/47-sflive2010_Insert_Performance_Inserting_20</a> (have a look from slide #47). It uses transactions but doesn't group INSERT of same objects in a unique statement.</p> <p>If you really need to divide the amount of data you pass to your DB server at once, I suggest you process EntityManager::flush() every x statement.</p>
9,815,208
CodeIgniter: "The filetype you are attempting to upload is not allowed."
<p>I'm experiencing a very odd upload problem. Here's the relevant view file:</p> <pre><code>&lt;form action="http://localhost/index.php/temp/upload/" method="post" enctype="multipart/form-data"&gt; &lt;fieldset&gt; &lt;input type="file" name="userfile"/&gt; &lt;input type="submit" value="Upload"/&gt; &lt;/fieldset&gt; &lt;/form&gt; </code></pre> <p>And here's my <code>temp</code> controller's <code>upload()</code> method:</p> <pre><code>public function upload() { $config['upload_path'] = FCPATH . 'uploads' . DIRECTORY_SEPARATOR; assert(file_exists($config['upload_path']) === TRUE); $config['allowed_types'] = 'avi|mpg|mpeg|wmv|jpg'; $config['max_size'] = '0'; $this-&gt;load-&gt;library('upload', $config); if ($this-&gt;upload-&gt;do_upload('userfile') === FALSE) { // Some error occured var_dump($this-&gt;upload-&gt;display_errors('', '')); var_dump($_FILES); } else { // Upload successful var_dump($this-&gt;upload-&gt;data()); } } </code></pre> <p>When I upload an AVI video, everything works fine. When I upload, say, a WMV video, I get the following var dumps:</p> <pre><code>string 'The filetype you are attempting to upload is not allowed.' (length=57) array 'userfile' =&gt; array 'name' =&gt; string 'wmv.wmv' (length=7) 'type' =&gt; string 'video/x-ms-wmv' (length=14) 'tmp_name' =&gt; string 'C:\wamp\tmp\php2333.tmp' (length=23) 'error' =&gt; int 0 'size' =&gt; int 83914 </code></pre> <p>The "wmv" extension is being interpreted as the MIME type: <code>video/x-ms-wmv</code>. This should be fine since my config/mimes.php has the following:</p> <pre><code>'wmv' =&gt; array('video/x-ms-wmv', 'audio/x-ms-wmv') </code></pre> <p>It's a similar situation when I try uploading other files. So far, the only one that seems to work is my test AVI video.</p> <p>Any ideas what might be wrong?</p> <p><strong>UPDATE 1:</strong></p> <p>One my machine, only AVI uploads. On another developer's machine, no files upload. On yet another developer's machine, all supported files upload. Are these browser or server issues?</p>
10,850,763
11
2
null
2012-03-22 01:22:18.87 UTC
3
2021-05-14 15:15:31.013 UTC
2012-06-07 12:53:50.087 UTC
null
253,976
null
253,976
null
1
33
php|codeigniter|mime-types|codeigniter-2
76,262
<p>You are using Firefox, aren't you?</p> <p>You could try looking at <code>system/libraries/Upload.php</code> line 199:</p> <pre><code>$this-&gt;_file_mime_type($_FILES[$field]); </code></pre> <p>Change that line to:</p> <pre><code>$this-&gt;_file_mime_type($_FILES[$field]); var_dump($this-&gt;file_type); die(); </code></pre> <p>Then do upload your <code>.wmv</code> file. It would show something like <code>application/octet-stream</code> or whatever. Add that to your <code>mimes.php</code>. Hope this help =)</p> <p>Similar answer <a href="https://stackoverflow.com/a/10762488/700643">here</a></p> <p>Some links:</p> <ul> <li><a href="http://codeigniter.com/forums/viewthread/146338/" rel="noreferrer">CodeIgniter forum's thread</a></li> <li><a href="http://techblog.procurios.nl/k/news/view/15872/14863/Mimetype-corruption-in-Firefox.html" rel="noreferrer">Mimetype corruption in Firefox</a></li> <li><a href="http://weblog.philringnalda.com/2004/04/06/getting-around-ies-mime-type-mangling" rel="noreferrer">Getting around IE’s MIME type mangling</a></li> </ul>
44,085,886
How to set up telnet in AWS instance?
<p>I got SSH working fine. But I am facing an issue with connecting via telnet.</p> <p><a href="https://i.stack.imgur.com/6RyUh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6RyUh.png" alt="Outbound"></a></p> <p><a href="https://i.stack.imgur.com/iZs3c.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iZs3c.png" alt="Inbound"></a></p> <p><a href="https://i.stack.imgur.com/KXFpk.png" rel="noreferrer"><img src="https://i.stack.imgur.com/KXFpk.png" alt="Putty"></a></p>
44,088,746
2
12
null
2017-05-20 12:28:16.847 UTC
7
2020-06-08 08:06:01.8 UTC
2017-05-21 02:00:06.81 UTC
null
13,317
null
5,751,745
null
1
17
amazon-ec2|linux-kernel|telnet|putty
59,622
<p><strong>ssh</strong> is recommended over <strong>telnet</strong>, as <strong>telnet</strong> is not encrypted and is by default not installed in amazon instance. </p> <p>However if needed, steps involved for Linux : Amazon Instance or Centos</p> <ol> <li><p><strong>Install telnet daemon in the instance:</strong> Install telnet-server using <code>sudo yum install telnet-server</code> . Package <code>telnet</code> is for the client program in case one want to connect using telnet client from the instance, not needed for the exercise.</p></li> <li><p><strong>Enable the telnet daemon service:</strong> - By default the service is disabled in <code>/etc/xinetd.d/telnet</code>, The <code>disable</code> flag needs to be set to <code>no</code>.</p> <p><code>service telnet { flags = REUSE socket_type = stream wait = no user = root server = /usr/sbin/in.telnetd log_on_failure += USERID disable = yes }</code></p> <p>Post change it should look like below <code>service telnet { flags = REUSE socket_type = stream wait = no user = root server = /usr/sbin/in.telnetd log_on_failure += USERID disable = no }</code></p> <p>Verify the configuration in case of any edit related errors. <code>sudo chkconfig xinetd on</code></p></li> <li><p><strong>Bring up the telnet service:</strong></p> <p>Bring up the telnet daemon as root using <code>sudo service xinetd restart</code> command</p></li> <li><p><strong>Enable inbound telnet default port (23) on AWS Console:</strong> In AWS Console <code>EC2/Security Groups/&lt;Your Security Group&gt;/Inbound</code>, set a rule </p> <p><code>Type:Custom-TCP Rule</code></p> <p><code>Protocol: TCP Range</code></p> <p><code>Port Range: 23</code></p> <p><code>Source: &lt;As per your business requirement&gt;</code> </p></li> <li><p><strong>Test the telnet connection:</strong> Test the telnet connection from any client enabled in the firewall.</p> <p><code>&gt;telnet ec2-XX-XX-XXX-XXX.region.compute.amazonaws.com. Connected to ec2-XX-XX-XXX-XXX.region.compute.amazonaws.com. Escape character is '^]'. Password:</code> </p></li> </ol> <p>The steps(tools) will vary slightly for other linux variants. </p> <p>PS: Referred <a href="http://aws-certification.blogspot.in/2016/01/install-and-setup-telnet-on-ec2-amazon.html" rel="noreferrer">http://aws-certification.blogspot.in/2016/01/install-and-setup-telnet-on-ec2-amazon.html</a>, fixed few issues in the commands.</p>
10,155,344
Auto height div with overflow and scroll when needed
<p>I'm trying to make a website with no vertical scrolling for a page, but i need that one of the DIVs i have to expand vertically to the bottom of the page (at most), and that when it has content that does not fit, the div should create a vertical scroller.</p> <p>i already have the css for the <em>inside</em> of the div figured out in <a href="http://jsfiddle.net/CdN7L/92/">this fiddle</a>, creating the scroller when needed. i also have figured out <a href="http://jsfiddle.net/CcKnJ/">how to make</a> the container div grow to occupy exactly the vertical space it has in the page. i just can't make them work out together!</p> <p>please have in mind that in jsfiddle you won't be able to view the content of the whole website and in that sense what you get for the 2nd fiddle doesn't really show what's being done, but it works as i intended though.</p> <p>just another note: as they are different fiddles, the id#container div in the 1st fiddle is he id#dcontent div of the 2nd example.</p> <p>there is one other thing: for a type of content, this div will scroll vertically, but for other type of content, i want it to scroll horizontally, as it will have a product "slider" displaying elements horizontally inside this DIV.</p> <p>please also look at this photo because it might be easier to understand what i'm trying to say: <a href="http://i39.tinypic.com/cu5u9.jpg">PICTURE</a></p> <p>i tried looking to other questions regarding these topics, but none seemed to cover all of the aspects i'm trying to solve... :S</p> <p>if there is something else i can provide to help you/me :) figuring it out, pls let me know!</p> <p>thanks!</p> <p>EDIT1: fixed typos</p> <p>EDIT2: added picture for explanation</p>
10,164,076
10
0
null
2012-04-14 16:38:14.737 UTC
12
2021-10-01 09:21:49.673 UTC
2012-04-14 17:07:33.777 UTC
null
24,098
null
24,098
null
1
64
html|css|scroll|overflow
237,144
<p>Well, after long research, i found a workaround that does what i need: <a href="http://jsfiddle.net/CqB3d/25/" rel="nofollow noreferrer">http://jsfiddle.net/CqB3d/25/</a></p> <p>CSS:</p> <pre><code>body{ margin: 0; padding: 0; border: 0; overflow: hidden; height: 100%; max-height: 100%; } #caixa{ width: 800px; margin-left: auto; margin-right: auto; } #framecontentTop, #framecontentBottom{ position: absolute; top: 0; width: 800px; height: 100px; /*Height of top frame div*/ overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/ background-color: navy; color: white; } #framecontentBottom{ top: auto; bottom: 0; height: 110px; /*Height of bottom frame div*/ overflow: hidden; /*Disable scrollbars. Set to "scroll" to enable*/ background-color: navy; color: white; } #maincontent{ position: fixed; top: 100px; /*Set top value to HeightOfTopFrameDiv*/ margin-left:auto; margin-right: auto; bottom: 110px; /*Set bottom value to HeightOfBottomFrameDiv*/ overflow: auto; background: #fff; width: 800px; } .innertube{ margin: 15px; /*Margins for inner DIV inside each DIV (to provide padding)*/ } * html body{ /*IE6 hack*/ padding: 130px 0 110px 0; /*Set value to (HeightOfTopFrameDiv 0 HeightOfBottomFrameDiv 0)*/ } * html #maincontent{ /*IE6 hack*/ height: 100%; width: 800px; } </code></pre> <p>HTML:</p> <pre><code>&lt;div id="framecontentBottom"&gt; &lt;div class="innertube"&gt; &lt;h3&gt;Sample text here&lt;/h3&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="maincontent"&gt; &lt;div class="innertube"&gt; Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed scelerisque, ligula hendrerit euismod auctor, diam nunc sollicitudin nibh, id luctus eros nibh porta tellus. Phasellus sed suscipit dolor. Quisque at mi dolor, eu fermentum turpis. Nunc posuere venenatis est, in sagittis nulla consectetur eget... //much longer text... &lt;/div&gt; &lt;/div&gt; </code></pre> <p>might not work with the horizontal thingy yet, but, it's a work in progress!</p> <p>I basically dropped the "inception" boxes-inside-boxes-inside-boxes model and used fixed positioning with dynamic height and overflow properties.</p> <p>Hope this might help whoever finds the question later!</p> <p>EDIT: This is the final answer.</p>
7,841,167
Table Header Views in StoryBoards
<p>Is there a way to insert a Table Header View (tableHeaderView) in StoryBoard (like we used to do in Interface Builder)?</p>
8,053,361
3
0
null
2011-10-20 19:28:52.69 UTC
38
2020-05-20 19:01:17.9 UTC
2012-04-24 02:10:31.35 UTC
null
1,508
null
716,082
null
1
192
ios|uitableview|xcode4|storyboard
96,489
<p>It looks like one simply drags a control to the top of the table view. I didn't expect it to be that easy.</p> <p>Before Drop</p> <p><img src="https://i.stack.imgur.com/T2Rv0.png" alt="Before Drop"></p> <p>After Drop</p> <p><img src="https://i.stack.imgur.com/FQYYU.png" alt="After Drop"></p>
11,493,978
How to retrieve the comment of a PostgreSQL database?
<p>I recently discovered you can <a href="http://www.postgresql.org/docs/current/static/sql-comment.html">attach a comment</a> to all sort of objects in PostgreSQL. In particular, I'm interested on playing with the comment of a database. For example, to <strong>set</strong> the comment of a database:</p> <pre><code>COMMENT ON DATABASE mydatabase IS 'DB Comment'; </code></pre> <p>However, what is the opposite statement, to <strong>get</strong> the comment of <code>mydatabase</code>?</p> <p>From the <code>psql</code> command line, I can see the comment along with other information as a result of the <code>\l+</code> command; which I could use with the aid of awk in order to achieve my goal. But I'd rather use an SQL statement, if possible.</p>
11,494,353
6
0
null
2012-07-15 17:16:23.13 UTC
12
2022-04-24 15:52:20.333 UTC
null
null
null
null
1,100,958
null
1
25
postgresql
20,149
<p>To get the comment on the database, use the following query:</p> <pre><code>select description from pg_shdescription join pg_database on objoid = pg_database.oid where datname = '&lt;database name&gt;' </code></pre> <p>This query will get you table comment for the given table name:</p> <pre><code>select description from pg_description join pg_class on pg_description.objoid = pg_class.oid where relname = '&lt;your table name&gt;' </code></pre> <p>If you use the same table name in different schemas, you need to modify it a bit:</p> <pre><code>select description from pg_description join pg_class on pg_description.objoid = pg_class.oid join pg_namespace on pg_class.relnamespace = pg_namespace.oid where relname = '&lt;table name&gt;' and nspname='&lt;schema name&gt;' </code></pre>
12,025,374
Learning d3.js for data visualisation
<p>I want to start learning to make data visualisations (as side project in my PhD) preferably with the <code>D3.js</code> package. I do not have <code>java</code>-experience but i do have a background in OOP as i mostly work in <code>python</code>. As such, I was wondering what's the best way to learn working with d3 and which environment one could recommend me.</p>
15,127,091
6
8
null
2012-08-19 08:58:35.627 UTC
35
2015-07-28 22:37:28.98 UTC
2012-08-19 09:02:07.947 UTC
null
1,105,514
null
698,207
null
1
47
javascript|d3.js
35,653
<p>Since I recently found it, I'd recommend working with <a href="http://phrogz.net/js/d3-playground/" rel="noreferrer">http://phrogz.net/js/d3-playground/</a> as well for a sandbox in which to trial out and learn how the pieces can work together.</p>
11,552,248
When to use @QueryParam vs @PathParam
<p>I am not asking the question that is already asked here: <a href="https://stackoverflow.com/questions/5579744/what-is-the-difference-between-pathparam-and-queryparam">What is the difference between @PathParam and @QueryParam</a></p> <p>This is a "best practices" or convention question.</p> <p>When would you use <code>@PathParam</code> vs <code>@QueryParam</code>.</p> <p>What I can think of that the decision might be using the two to differentiate the information pattern. Let me illustrate below my LTPO - less than perfect observation.</p> <p>PathParam use could be reserved for information category, which would fall nicely into a branch of an information tree. PathParam could be used to drill down to entity class hierarchy.</p> <p>Whereas, QueryParam could be reserved for specifying attributes to locate the instance of a class.</p> <p>For example,</p> <ul> <li><code>/Vehicle/Car?registration=123</code></li> <li><code>/House/Colonial?region=newengland</code></li> </ul> <p><code>/category?instance</code></p> <pre><code>@GET @Path("/employee/{dept}") Patient getEmployee(@PathParam("dept")Long dept, @QueryParam("id")Long id) ; </code></pre> <p>vs <code>/category/instance</code></p> <pre><code>@GET @Path("/employee/{dept}/{id}") Patient getEmployee(@PathParam("dept")Long dept, @PathParam("id")Long id) ; </code></pre> <p>vs <code>?category+instance</code></p> <pre><code>@GET @Path("/employee") Patient getEmployee(@QueryParam("dept")Long dept, @QueryParam("id")Long id) ; </code></pre> <p>I don't think there is a standard convention of doing it. Is there? However, I would like to hear of how people use PathParam vs QueryParam to differentiate their information like I exemplified above. I would also love to hear the reason behind the practice.</p>
11,569,077
18
1
null
2012-07-19 00:18:57.29 UTC
132
2022-06-02 10:16:17.447 UTC
2017-05-23 12:34:37.587 UTC
null
-1
null
140,803
null
1
332
java|rest|jax-rs
502,474
<p>REST may not be a standard as such, but reading up on general REST documentation and blog posts should give you some guidelines for a good way to structure API URLs. Most rest APIs tend to only have resource names and resource IDs in the path. Such as:</p> <pre><code>/departments/{dept}/employees/{id} </code></pre> <p>Some REST APIs use query strings for filtering, pagination and sorting, but Since REST isn't a strict standard I'd recommend checking some REST APIs out there such as <a href="http://developer.github.com/v3/repos/" rel="noreferrer">github</a> and <a href="https://api.stackexchange.com/docs">stackoverflow</a> and see what could work well for your use case. </p> <p>I'd recommend putting any required parameters in the path, and any optional parameters should certainly be query string parameters. Putting optional parameters in the path will end up getting really messy when trying to write URL handlers that match different combinations. </p>
11,687,302
PyCharm not recognizing Python files
<p>PyCharm is no longer recognizing Python files. The interpreter path is correctly set.</p> <p><img src="https://i.stack.imgur.com/sml3Y.jpg" alt="Screen shot" /></p>
11,687,851
16
1
null
2012-07-27 11:56:48.017 UTC
16
2022-05-17 11:02:59.433 UTC
2020-12-29 13:49:30.447 UTC
null
433,717
null
433,717
null
1
101
python|pycharm
63,524
<p>Please check <code>File</code> | <code>Settings</code> (<code>Preferences</code> on macOS) | <code>Editor</code> | <code>File Types</code>, ensure that file name or extension is not listed in <strong>Text</strong> files.</p> <p>To fix the problem remove it from the <strong>Text</strong> files and double check that <code>.py</code> extension is associated with <strong>Python</strong> files.</p> <p><a href="https://i.stack.imgur.com/jooFr.png" rel="noreferrer"><img src="https://i.stack.imgur.com/jooFr.png" alt="Text"></a></p>
11,581,697
Is there a way to force ASP.NET Web API to return plain text?
<p>I need to get a response back in plain text from a ASP.NET Web API controller.</p> <p>I have tried do a request with <code>Accept: text/plain</code> but it doesn't seem to do the trick. Besides, the request is external and out of my control. What I would accomplish is to mimic the old ASP.NET way:</p> <pre><code>context.Response.ContentType = "text/plain"; context.Response.Write("some text); </code></pre> <p>Any ideas?</p> <p><em>EDIT, solution</em>: Based on Aliostad's answer, I added the <a href="http://nuget.org/packages/WebAPIContrib">WebAPIContrib</a> text formatter, initialized it in the Application_Start:</p> <pre><code> config.Formatters.Add(new PlainTextFormatter()); </code></pre> <p>and my controller ended up something like:</p> <pre><code>[HttpGet, HttpPost] public HttpResponseMessage GetPlainText() { return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, "Test data", "text/plain"); } </code></pre>
13,028,027
6
0
null
2012-07-20 14:49:01.79 UTC
29
2018-01-04 22:11:33.483 UTC
2012-07-20 15:39:45.617 UTC
null
3,584
null
3,584
null
1
133
asp.net|asp.net-web-api
82,327
<p>Hmmm... I don't think you need to create a custom formatter to make this work. Instead return the content like this:</p> <pre><code> [HttpGet] public HttpResponseMessage HelloWorld() { string result = "Hello world! Time is: " + DateTime.Now; var resp = new HttpResponseMessage(HttpStatusCode.OK); resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain"); return resp; } </code></pre> <p>This works for me without using a custom formatter.</p> <p>If you explicitly want to create output and override the default content negotiation based on Accept headers you won't want to use <code>Request.CreateResponse()</code> because it forces the mime type. </p> <p>Instead explicitly create a new <code>HttpResponseMessage</code> and assign the content manually. The example above uses <code>StringContent</code> but there are quite a few other content classes available to return data from various .NET data types/structures.</p>
11,887,934
How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?
<p>This is a bit of my JS code for which this is needed:</p> <pre><code>var secDiff = Math.abs(Math.round((utc_date-this.premiere_date)/1000)); this.years = this.calculateUnit(secDiff,(86400*365)); this.days = this.calculateUnit(secDiff-(this.years*(86400*365)),86400); this.hours = this.calculateUnit((secDiff-(this.years*(86400*365))-(this.days*86400)),3600); this.minutes = this.calculateUnit((secDiff-(this.years*(86400*365))-(this.days*86400)-(this.hours*3600)),60); this.seconds = this.calculateUnit((secDiff-(this.years*(86400*365))-(this.days*86400)-(this.hours*3600)-(this.minutes*60)),1); </code></pre> <p>I want to get the datetime in "ago", but if the DST is in use then the dates are off by 1 hour. I don't know how to check if the DST is in effect or not.</p> <p>How can I know when the daylight saving starts and ends?</p>
11,888,430
15
0
null
2012-08-09 16:33:34.197 UTC
83
2022-05-09 06:22:31.973 UTC
2020-06-19 06:59:15.887 UTC
null
8,112,776
null
1,286,942
null
1
197
javascript|datetime|dst|timezone-offset|datetime-conversion
242,860
<p>This code uses the fact that <code>getTimezoneOffset</code> returns a <em>greater</em> value during Standard Time versus Daylight Saving Time (DST). Thus it determines the expected output during Standard Time, and it compares whether the output of the given date the same (Standard) or less (DST). </p> <p>Note that <code>getTimezoneOffset</code> returns <em>positive</em> numbers of minutes for zones <em>west</em> of UTC, which are usually stated as <em>negative</em> hours (since they're "behind" UTC). For example, Los Angeles is <strong>UTC–8h</strong> Standard, <strong>UTC-7h</strong> DST. <code>getTimezoneOffset</code> returns <code>480</code> (positive 480 minutes) in December (winter, Standard Time), rather than <code>-480</code>. It returns <em>negative</em> numbers for the Eastern Hemisphere (such <code>-600</code> for Sydney in winter, despite this being "ahead" (<strong>UTC+10h</strong>). </p> <pre><code>Date.prototype.stdTimezoneOffset = function () { var jan = new Date(this.getFullYear(), 0, 1); var jul = new Date(this.getFullYear(), 6, 1); return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset()); } Date.prototype.isDstObserved = function () { return this.getTimezoneOffset() &lt; this.stdTimezoneOffset(); } var today = new Date(); if (today.isDstObserved()) { alert ("Daylight saving time!"); } </code></pre>
3,657,181
Very large collection in .Net causes out-of-memory exception
<p>I am testing how big a collection could be in .Net. Technically, any collection object could grows to the size of the physical memory. </p> <p>Then I tested the following code in a sever, which has 16GB memory, running Windows 2003 server and Visual Studio 2008. I tested both F# and C# code, and looked at the Task Manager while running. I can see that after about growing 2GB memory, the program crashed with out-of-memory exception. I did set the target platform to x64 in the property page. </p> <pre><code>open System.Collections.Generic let d = new Dictionary&lt;int, int&gt;() for i=1 to 1000000000 do d.Add(i,i) </code></pre> <p>I did a same test to the <a href="http://www.itu.dk/research/c5/" rel="noreferrer">C5</a> collection library. The result is that the dictionary in C5 could use up the whole memory. The code uses C5:</p> <pre><code>let d = C5.HashDictionary&lt;int, int&gt; () for i=1 to 1000000000 do d.Add(i,i) </code></pre> <p>Anyone knows why? </p>
3,657,189
4
2
null
2010-09-07 08:52:37.31 UTC
8
2017-07-15 22:58:30.153 UTC
2016-06-06 22:01:22.84 UTC
null
1,243,762
null
183,828
null
1
32
c#|.net|f#|gcallowverylargeobjects
26,188
<p>The Microsoft CLR has a 2GB maximum object size limit, even the 64 bit version. (I'm not sure whether this limit is also present in other implementations such as Mono.)</p> <p>The limitation applies to each <em>single</em> object -- not the total size of all objects -- which means that it's relatively easy to workaround using a composite collection of some sort.</p> <p>There's a discussion and some example code here...</p> <ul> <li><a href="http://blogs.msdn.com/b/joshwil/archive/2005/08/10/450202.aspx" rel="noreferrer">BigArray&lt;T&gt;, getting around the 2GB array size limit</a></li> </ul> <p>There seems to be very little official documentation that refers to this limit. It is, after all, just an implementation detail of the current CLR. The only mention that I'm aware of is <a href="http://msdn.microsoft.com/en-us/library/ms241064.aspx" rel="noreferrer">on this page</a>:</p> <blockquote> <p>When you run a 64-bit managed application on a 64-bit Windows operating system, you can create an object of no more than 2 gigabytes (GB).</p> </blockquote>
3,450,965
Determine if Oracle date is on a weekend?
<p>Is this the best way to determine if an Oracle date is on a weekend?</p> <pre><code>select * from mytable where TO_CHAR (my_date, 'DY', 'NLS_DATE_LANGUAGE=ENGLISH') IN ('SAT', 'SUN'); </code></pre>
3,451,090
5
1
null
2010-08-10 16:02:48.343 UTC
9
2014-03-28 09:05:46.323 UTC
null
null
null
null
47,281
null
1
19
oracle|date|plsql|weekend
63,835
<p>As of Oracle 11g, yes. The only viable region agnostic alternative that I've seen is as follows:</p> <pre><code>SELECT * FROM mytable WHERE MOD(TO_CHAR(my_date, 'J'), 7) + 1 IN (6, 7); </code></pre>
3,423,540
Zip latest committed changes only
<p>Git has the very handy <code>archive</code> command which allows me to make a copy of a particular commit in a .zip archive like so:</p> <pre><code>git archive -o ../latest.zip some-commit</code></pre> <p>This will contain the entire working tree for that commit. Usually I just need the changed files since a previous release. Currently I use this to get those files into a zip:</p> <pre><code>git diff --name-only previous-commit latest-commit | zip ../changes.zip -@</code></pre> <p>This will however zip files from my working copy, which may have uncommitted changes. Is there some way to get only the changed files as they were committed directly into a zip?</p>
3,424,408
6
0
null
2010-08-06 12:02:11.763 UTC
13
2022-07-06 08:41:22 UTC
null
null
null
null
64,096
null
1
23
git|bash
14,362
<p><code>git archive</code> will accept paths as arguments. All you should need to do is:</p> <pre><code>git archive -o ../latest.zip some-commit $(git diff --name-only earlier-commit some-commit) </code></pre> <p>or if you have files with spaces (or other special characters) in them, use xargs:</p> <pre><code>git diff --name-only earlier-commit some-commit | xargs -d'\n' git archive -o ../latest.zip some-commit </code></pre> <p>If you don't have xargs properly installed, you could cook up an alternative:</p> <pre><code>#!/bin/bash IFS=$'\n' files=($(git diff --name-only earlier-commit some-commit)) git archive -o ../latest.zip some-commit "${files[@]}" </code></pre> <p>Written as a shell script, but should work as a one-liner too. Alternatively, change <code>earlier-commit</code>, <code>some-commit</code>, and <code>../latest.zip</code> to <code>$1</code> <code>$2</code> and <code>$3</code> and you've got yourself a reusable script.</p>
3,506,706
Is == in PHP a case-sensitive string comparison?
<p>I was unable to find this on php.net. Is the double equal sign (<code>==</code>) case sensitive when used to compare strings in PHP?</p>
3,506,722
7
0
null
2010-08-17 20:33:54.557 UTC
10
2020-01-16 20:08:56.023 UTC
2010-08-17 20:38:41.66 UTC
null
309,308
user374343
null
null
1
91
php|string-comparison
68,331
<p>Yes, <code>==</code> is case sensitive.</p> <p>You can use <a href="https://secure.php.net/manual/en/function.strcasecmp.php" rel="noreferrer"><code>strcasecmp</code></a> for case insensitive comparison</p>
3,740,128
PSCustomObject to Hashtable
<p>What is the easiest way to convert a <code>PSCustomObject</code> to a <code>Hashtable</code>? It displays just like one with the splat operator, curly braces and what appear to be key value pairs. When I try to cast it to <code>[Hashtable]</code> it doesn't work. I also tried <code>.toString()</code> and the assigned variable says its a string but displays nothing - any ideas?</p>
3,740,403
8
2
null
2010-09-18 02:22:50.543 UTC
14
2022-05-28 08:51:24.99 UTC
2018-02-06 19:41:00.69 UTC
null
2,067,941
null
444,896
null
1
86
powershell|hashtable|pscustomobject
87,889
<p>Shouldn't be too hard. Something like this should do the trick:</p> <pre><code># Create a PSCustomObject (ironically using a hashtable) $ht1 = @{ A = 'a'; B = 'b'; DateTime = Get-Date } $theObject = new-object psobject -Property $ht1 # Convert the PSCustomObject back to a hashtable $ht2 = @{} $theObject.psobject.properties | Foreach { $ht2[$_.Name] = $_.Value } </code></pre>
3,772,867
Lambda capture as const reference?
<p>Is it possible to capture by <code>const</code> reference in a lambda expression?</p> <p>I want the assignment marked below to fail, for example:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;string&gt; using namespace std; int main() { string strings[] = { &quot;hello&quot;, &quot;world&quot; }; static const size_t num_strings = sizeof(strings)/sizeof(strings[0]); string best_string = &quot;foo&quot;; for_each( &amp;strings[0], &amp;strings[num_strings], [&amp;best_string](const string&amp; s) { best_string = s; // this should fail } ); return 0; } </code></pre> <p><em>Update:</em> As this is an old question, it might be good to update it if there are facilities in C++14 to help with this. Do the extensions in C++14 allow us to capture a non-const object by const reference? (<em>August 2015</em>)</p>
3,772,980
8
4
null
2010-09-22 19:23:36.567 UTC
36
2021-12-09 15:53:30.307 UTC
2021-09-04 19:59:22.813 UTC
Roger Pate
10,871,073
null
241,536
null
1
213
c++|c++11|lambda|c++14
87,811
<p><code>const</code> isn't in the grammar for captures as of n3092:</p> <pre><code>capture: identifier &amp; identifier this </code></pre> <p>The text only mention capture-by-copy and capture-by-reference and doesn't mention any sort of const-ness.</p> <p>Feels like an oversight to me, but I haven't followed the standardization process very closely.</p>
3,241,422
Include PHP inside JavaScript (.js) files
<p>I have a JavaScript file (extension <code>.js</code>, not <code>.html</code>) containing several JavaScript functions.</p> <p>I want to call one of the PHP functions in a PHP file containing only several PHP functions from within one of the JavaScript functions.</p> <ul> <li>Is that possible?</li> <li>Would I need to "include" the <code>.php</code> file containing the PHP function in the <code>.js</code> file?</li> <li>How would I do that? <br /> For example, say I had a file called myLib.php containing a function called <code>myFunc</code> that takes two parameters (<code>param1</code> and <code>param2</code>). Then I have a <code>.js</code> file containing a function called <code>myJsFunc</code>. How would a call the <code>myFunc</code> (PHP) from within the <code>myJsFunc</code> (JavaScript function)? Wouldn't I need to include the PHP file somehow in the <code>.js</code> file?</li> </ul>
3,241,877
11
4
null
2010-07-13 20:51:23.527 UTC
22
2021-05-26 15:55:55.33 UTC
2014-05-02 15:50:38.537 UTC
null
2,373,138
null
222,279
null
1
49
php|javascript
248,878
<h2>7 years later update: This is terrible advice. Please don't do this.</h2> <p>If you just need to pass variables from PHP to the javascript, you can have a tag in the php/html file using the javascript to begin with.</p> <pre><code>&lt;script type=&quot;text/javascript&quot;&gt; var phpVars = &lt;?php echo json_encode($vars) ?&gt;; &lt;/script&gt; &lt;script type=&quot;text/javascript&quot; src=&quot;yourScriptThatUsesPHPVars.js&quot;&gt;&lt;/script&gt; </code></pre> <p>If you're trying to call functions, then you can do this like this</p> <pre><code>&lt;script type=&quot;text/javascript&quot; src=&quot;YourFunctions.js&quot;&gt;&lt;/script&gt; &lt;script type=&quot;text/javascript&quot;&gt; // assume each element of $arrayWithVars has already been json_encoded functionOne(&lt;?php echo implode(', ', $arrayWithVars); ?&gt;); functionTwo(&lt;?php echo json_encode($moreVars) ?&gt;, &lt;?php echo json_encode($evenMoreVars) ?&gt;); &lt;/script&gt; </code></pre>
4,039,879
Best way to find the months between two dates
<p>I have the need to be able to accurately find the months between two dates in python. I have a solution that works but its not very good (as in elegant) or fast. </p> <pre><code>dateRange = [datetime.strptime(dateRanges[0], "%Y-%m-%d"), datetime.strptime(dateRanges[1], "%Y-%m-%d")] months = [] tmpTime = dateRange[0] oneWeek = timedelta(weeks=1) tmpTime = tmpTime.replace(day=1) dateRange[0] = tmpTime dateRange[1] = dateRange[1].replace(day=1) lastMonth = tmpTime.month months.append(tmpTime) while tmpTime &lt; dateRange[1]: if lastMonth != 12: while tmpTime.month &lt;= lastMonth: tmpTime += oneWeek tmpTime = tmpTime.replace(day=1) months.append(tmpTime) lastMonth = tmpTime.month else: while tmpTime.month &gt;= lastMonth: tmpTime += oneWeek tmpTime = tmpTime.replace(day=1) months.append(tmpTime) lastMonth = tmpTime.month </code></pre> <p>So just to explain, what I'm doing here is taking the two dates and converting them from iso format into python datetime objects. Then I loop through adding a week to the start datetime object and check if the numerical value of the month is greater (unless the month is December then it checks if the date is less), If the value is greater I append it to the list of months and keep looping through until I get to my end date.</p> <p>It works perfectly it just doesn't seem like a good way of doing it...</p>
4,039,971
40
3
null
2010-10-28 04:55:29.54 UTC
31
2022-07-18 06:48:03.493 UTC
2014-06-23 15:13:08.387 UTC
null
1,565,828
null
188,792
null
1
127
python|datetime|monthcalendar|date-math
225,693
<p><strong>Update 2018-04-20:</strong> it seems that OP @Joshkunz was asking for finding <em>which months</em> are between two dates, instead of "how many months" are between two dates. So I am not sure why @JohnLaRooy is upvoted for more than 100 times. @Joshkunz indicated in the comment under the original question he wanted the actual dates [or the months], instead of finding the <em>total number of months</em>.</p> <p>So it appeared the question wanted, for between two dates <code>2018-04-11</code> to <code>2018-06-01</code></p> <pre><code>Apr 2018, May 2018, June 2018 </code></pre> <p>And what if it is between <code>2014-04-11</code> to <code>2018-06-01</code>? Then the answer would be </p> <pre><code>Apr 2014, May 2014, ..., Dec 2014, Jan 2015, ..., Jan 2018, ..., June 2018 </code></pre> <p>So that's why I had the following pseudo code many years ago. It merely suggested using the two months as end points and loop through them, incrementing by one month at a time. @Joshkunz mentioned he wanted the "months" and he also mentioned he wanted the "dates", without knowing exactly, it was difficult to write the exact code, but the idea is to use one simple loop to loop through the end points, and incrementing one month at a time.</p> <p>The answer 8 years ago in 2010:</p> <p>If adding by a week, then it will approximately do work 4.35 times the work as needed. Why not just:</p> <pre><code>1. get start date in array of integer, set it to i: [2008, 3, 12], and change it to [2008, 3, 1] 2. get end date in array: [2010, 10, 26] 3. add the date to your result by parsing i increment the month in i if month is &gt;= 13, then set it to 1, and increment the year by 1 until either the year in i is &gt; year in end_date, or (year in i == year in end_date and month in i &gt; month in end_date) </code></pre> <p>just pseduo code for now, haven't tested, but i think the idea along the same line will work.</p>
7,934,802
Android Fragment does not respect match_parent as height
<p>Sorry for the huge code dump, but I'm truly lost.</p> <p><strong>MyActivity.java onCreate</strong>:</p> <pre><code>super.onCreate(savedInstanceState); setContentView(R.layout.activity_singlepane_empty); mFragment = new PlacesFragment(); getSupportFragmentManager().beginTransaction() .add(R.id.root_container, mFragment) .commit(); </code></pre> <p><strong>PlacesFragment.java onCreateView</strong>:</p> <pre><code>mRootView = (ViewGroup) inflater.inflate(R.layout.list_content, null); return mRootView; </code></pre> <p><strong>Notes</strong>: <code>mRootView</code> is a <code>ViewGroup</code> global, no problem about it, I believe. <code>PlacesFragment</code> is a <code>ListFragment</code>.</p> <p>Layouts:</p> <p><strong>activity_singlepane_empty.xml</strong>:</p> <pre><code>&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:id=&quot;@+id/root_container&quot; android:orientation=&quot;vertical&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:background=&quot;#00f&quot;&gt; &lt;include layout=&quot;@layout/actionbar&quot;/&gt; &lt;!-- FRAGMENTS COME HERE! See match_parent above --&gt; &lt;/LinearLayout&gt; </code></pre> <p><strong>list_content.xml</strong>:</p> <pre><code>&lt;FrameLayout 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; android:id=&quot;@+id/listContainer&quot; android:background=&quot;#990&quot; &gt; &lt;ListView android:id=&quot;@android:id/list&quot; android:layout_width=&quot;match_parent&quot; android:layout_height=&quot;match_parent&quot; android:drawSelectorOnTop=&quot;false&quot; /&gt; &lt;TextView android:id=&quot;@id/android:empty&quot; android:layout_width=&quot;wrap_content&quot; android:layout_height=&quot;wrap_content&quot; android:layout_gravity=&quot;center&quot; android:gravity=&quot;center&quot; android:textAppearance=&quot;?android:attr/textAppearanceMedium&quot; android:text=&quot;@string/no_data_suggest_connection&quot;/&gt; &lt;/FrameLayout&gt; </code></pre> <p><strong>Problem:</strong> as you can see, the expected behavior would be to have the empty <code>TextView</code> above to appear centered on the screen. On the design preview in Eclipse, it is OK. Only when added to <code>root_view</code> as a fragment the <code>FrameLayout</code> won't fill the whole screen.</p> <p><code>root_container</code> is blue, and <code>FrameLayout</code> is yellowish, see below for debug purposes. <em><strong>Shouldn't the yellow pane fill the whole screen?!?!?!?</strong></em></p> <p><img src="https://i.stack.imgur.com/W14iF.png" alt="enter image description here" /></p>
9,668,933
6
1
null
2011-10-28 20:52:57.947 UTC
8
2021-05-11 11:37:55.45 UTC
2020-09-18 10:59:15.997 UTC
null
11,199,298
null
489,607
null
1
50
android|center|android-linearlayout|fragment|android-framelayout
35,332
<p>I had the same problem and think it happens when you inflate the layout in the Fragment's onCreateView with null, like you did here:</p> <pre><code>mRootView = (ViewGroup) inflater.inflate(R.layout.list_content, null); </code></pre> <p>Instead you have to do this:</p> <pre><code>mRootView = (ViewGroup) inflater.inflate(R.layout.list_content,container, false); </code></pre> <p>Where container is the Viewgroup. At least, that solved the problem for me.</p>
8,328,983
Check whether an array is empty
<p>I have the following code</p> <pre><code>&lt;?php $error = array(); $error['something'] = false; $error['somethingelse'] = false; if (!empty($error)) { echo 'Error'; } else { echo 'No errors'; } ?&gt; </code></pre> <p>However, <code>empty($error)</code> still returns <code>true</code>, even though nothing is set.</p> <p>What's not right?</p>
8,329,005
12
5
null
2011-11-30 16:03:00.577 UTC
51
2017-06-07 12:09:33.763 UTC
2014-07-09 11:34:09.64 UTC
null
2,487,549
null
333,733
null
1
247
php|arrays
564,681
<p>There are two elements in array and this definitely doesn't mean that array is empty. As a quick workaround you can do following:</p> <pre><code>$errors = array_filter($errors); if (!empty($errors)) { } </code></pre> <p><code>array_filter()</code> function's default behavior will remove all values from array which are equal to <code>null</code>, <code>0</code>, <code>''</code> or <code>false</code>.</p> <p>Otherwise in your particular case <code>empty()</code> construct will always return <code>true</code> if there is at least one element even with "empty" value.</p>
4,221,735
Rails and caching, is it easy to switch between memcache and redis?
<p>Is there a common api such that if I switch between Redis or Memcached I don't have to change my code, just a config setting?</p>
4,223,466
3
0
null
2010-11-19 03:03:09.753 UTC
15
2013-09-22 22:13:53.837 UTC
2010-11-19 09:07:12.647 UTC
null
123,527
null
39,677
null
1
26
ruby-on-rails|caching|memcached|redis
15,818
<p>As long as you don't initialize the Memcached client yourself but you rely on <code>Rails.cache</code> common API, switching from Memcached to Redis is just a matter of installing <a href="https://github.com/jodosha/redis-store">redis-store</a> and changing the configuration from</p> <pre><code>config.cache_store = :memcached_store </code></pre> <p>to</p> <pre><code>config.cache_store = :redis_store </code></pre> <p>More <a href="http://guides.rubyonrails.org/caching_with_rails.html">info about Rails.cache</a>.</p>
4,486,609
When can compiling c++ without RTTI cause problems?
<p>I'm using gcc's <code>-fno-rtti</code> flag to compile my C++ without runtime type information.</p> <p>Assuming I'm not using <code>dynamic_cast&lt;&gt;</code> or <code>typeid()</code>, is there anything that could lead me to later problems?</p>
4,486,715
3
4
null
2010-12-20 03:15:08.27 UTC
12
2021-08-27 15:18:59.457 UTC
2010-12-20 07:39:45.373 UTC
null
540,312
null
119,046
null
1
65
c++|gcc|rtti
39,618
<p>Since your question is specific to GCC you should consult carefully the documentation for the version you are using. The documentation for GCC 4.5.2 says the following. Which from my reading would indicate that if you avoid dynamic_cast and typeid, you should be ok. That said, I have no personal experience with -fno-rtti. Perhaps you might like to elaborate on why you are using -fno-rtti.</p> <blockquote> <p>-fno-rtti<br> Disable generation of information about every class with virtual functions for use by the C++ runtime type identification features (<code>dynamic_cast</code> and <code>typeid</code>). If you don't use those parts of the language, you can save some space by using this flag. Note that exception handling uses the same information, but it will generate it as needed. The <code>dynamic_cast</code> operator can still be used for casts that do not require runtime type information, i.e. casts to <code>void *</code> or to unambiguous base classes.</p> </blockquote> <p>There is discussion about the relationship between virtual functions and RTTI available at <a href="https://stackoverflow.com/questions/34353751/no-rtti-but-still-virtual-methods">No RTTI but still virtual methods</a>. The short version is that virtual functions should be fine without RTTI.</p>
4,408,158
XSD Element Not Null or Empty Constraint For Xml?
<p>This is my sample XML Code:</p> <pre><code>&lt;bestContact&gt; &lt;firstName&gt;&lt;![CDATA[12345]]&gt;&lt;/firstName&gt; &lt;lastName /&gt; &lt;/bestContact&gt; </code></pre> <p>I am using:</p> <pre><code>&lt;xs:element name="lastName" type="xs:string" minOccurs="1" nillable="false"/&gt; </code></pre> <p>The XSD Should be validate <code>lastName</code> as not null or empty.</p>
4,408,763
5
0
null
2010-12-10 11:02:55.12 UTC
7
2019-07-09 20:54:31.413 UTC
2015-04-29 00:58:33.87 UTC
null
597,755
null
346,953
null
1
27
xml|xsd
67,879
<p>Try</p> <pre><code>&lt;xs:element name="lastName" minOccurs="1" nillable="false"&gt; &lt;xs:simpleType&gt; &lt;xs:restriction base="xs:string"&gt; &lt;xs:minLength value="1"/&gt; &lt;/xs:restriction&gt; &lt;/xs:simpleType&gt; &lt;/xs:element&gt; </code></pre>
4,213,882
How to sync chrome extension options
<p>I've made a Chrome extension with an options page. The data is saved in localstorage and works just fine.</p> <p>Chrome doesn't sync the localstorage to the cloud, just the extensions. This means that any user data will not sync to other computers of the same google account.</p> <p>I can not find an API at <a href="http://developer.chrome.com/extensions/docs.html" rel="noreferrer">http://developer.chrome.com/extensions/docs.html</a> which allows me to sync the user-chosen preferences.</p> <p>What methods do you suggest?</p>
9,391,545
5
5
null
2010-11-18 10:41:20.08 UTC
13
2021-06-16 22:25:15.147 UTC
2014-06-02 15:20:45.503 UTC
null
3,486,353
null
61,521
null
1
32
javascript|google-chrome-extension|sync|local-storage
8,573
<p><del>In the (hopefully near) future, you'll be</del> You are now able to store stuff in <a href="https://developer.chrome.com/docs/extensions/reference/storage/#usage" rel="nofollow noreferrer"><code>chrome.storage.sync</code></a>, and it will be synced automagically.</p> <p>Unless you need something <em>right now</em>, do consider putting all your configurations in an single object, sometime later you'll be able to just sync it!</p> <p><strong>Edit:</strong> now this is <a href="https://developer.chrome.com/docs/extensions/reference/storage/#usage" rel="nofollow noreferrer">available in stable Chrome</a>!</p>
4,811,172
Is it possible to track hash links like pages with google analytics?
<p>Is it possible to track hash links like pages with google analytics?</p> <p>For example, I want index.php/#1, index.php/#2, and index.php/#3 to all show up as individual page hits with individual time spent on page. </p> <p>If there is no simple way of doing this, how can I add a track event to an onclick event with jquery? Can I still receive accurate time on "page" information this way?</p>
4,813,223
5
3
null
2011-01-26 23:07:26.947 UTC
20
2021-12-28 01:33:13.543 UTC
2011-01-27 06:01:44.203 UTC
null
172,322
null
466,290
null
1
57
javascript|jquery|google-analytics
40,127
<p>Generically, your code could look like this</p> <pre><code>_gaq.push(['_trackPageview',location.pathname + location.search + location.hash]); </code></pre> <p>You could either bind that code to every time you have a hash change within your application, or you could use a <a href="http://benalman.com/projects/jquery-hashchange-plugin/" rel="nofollow noreferrer">generic hashchange plugin</a>, that uses the HTML5 onhashchange, and some backwards compatible hacks for older browsers, and bind this code to that event, so that it fires every time your hash changes.</p> <p>Using that plugin, your code could look like:</p> <pre><code>$(window).hashchange( function(){ _gaq.push(['_trackPageview',location.pathname + location.search + location.hash]); }) </code></pre> <hr> **UPDATE 2014:** <p>This is how you'd do this in the new <a href="https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications" rel="nofollow noreferrer">Universal Analytics</a>:</p> <pre><code>ga('set', 'page', location.pathname + location.search + location.hash); ga('send', 'pageview'); </code></pre> <p>Note from Google Analytics documentation:</p> <blockquote> <p>While technically the <code>send</code> command for pageview hits accepts an optional <code>page</code> field as the third parameter, passing the <code>page</code> field that way is not recommended when measuring single page applications.</p> </blockquote> <p>This is how you'd do it if you're using Google Analytics within Google Tag Manager:</p> <ul> <li>Go to your macros</li> <li>Updated the URL Macro to &quot;Fragment&quot;</li> </ul>
4,671,836
How get a WPF Datagrid with cells that wrap text instead of truncating it?
<p>What must be done to get a WPF DataGrid with cells that wrap text instead of truncating it?</p> <p>Right now when a text is bigger and don't fit in a column the text is truncated and users can't see it value cos the DataGrid's IsReadOnly property is true. What I want is that the text in cells be wrapped and the cell height (NO CELL WIDTH) increased the amount needed to show all the text.</p>
4,671,974
5
0
null
2011-01-12 17:24:20.98 UTC
13
2021-03-10 06:07:53.683 UTC
2017-05-31 10:58:47.75 UTC
null
271,200
user1785721
null
null
1
65
wpf|datagrid|word-wrap
68,438
<p>You could try to template the cells with a <code>TextBlock</code> which has text-wrapping enabled.</p>
4,649,699
Is it possible to get element's numerical index in its parent node without looping?
<p>Normally I'm doing it this way:</p> <pre><code>for(i=0;i&lt;elem.parentNode.length;i++) { if (elem.parentNode[i] == elem) //.... etc.. etc... } </code></pre>
4,649,936
7
0
null
2011-01-10 17:42:52.14 UTC
8
2021-02-22 13:48:16.717 UTC
2011-01-10 17:48:24.803 UTC
null
224,671
null
393,087
null
1
47
javascript|dom
32,461
<p>You could count siblings... The childNodes list includes text <strong>and</strong> element nodes-</p> <pre><code>function whichChild(elem){ var i= 0; while((elem=elem.previousSibling)!=null) ++i; return i; } </code></pre>
4,258,466
Can I add arbitrary properties to DOM objects?
<p>Can I add arbitrary properties to JavaScript DOM objects, such as <code>&lt;INPUT&gt;</code> or <code>&lt;SELECT&gt;</code> elements? Or, if I cannot do that, is there a way to associate my own objects with page elements via a reference property?</p>
4,258,487
7
0
null
2010-11-23 16:41:10.957 UTC
13
2021-10-26 11:22:57.887 UTC
2010-11-23 17:54:34.807 UTC
null
45,433
null
67,063
null
1
63
javascript|dom
26,677
<p>Sure, people have been doing it for ages. It's not recommended as it's messy and you may mess with existing properties.</p> <p>If you are looping code with <code>for..in</code> your code may break because you will now be enumerating through these newly attached properties.</p> <p>I suggest using something like jQuery's <code>.data</code> which keeps metadata attached to objects. If you don't want to use a library, re-implement <code>jQuery.data</code></p>
4,603,349
Python design mistakes
<p>A while ago, when I was learning Javascript, I studied <a href="https://rads.stackoverflow.com/amzn/click/com/0596517742" rel="noreferrer" rel="nofollow noreferrer">Javascript: the good parts</a>, and I particularly enjoyed the chapters on the bad and the ugly parts. Of course, I did not agree with everything, as summing up the design defects of a programming language is to a certain extent subjective - although, for instance, I guess everyone would agree that the keyword <code>with</code> was a mistake in Javascript. Nevertheless, I find it useful to read such reviews: even if one does not agree, there is a lot to learn.</p> <p>Is there a blog entry or some book describing design mistakes for Python? For instance I guess some people would count the lack of tail call optimization a mistake; there may be other issues (or non-issues) which are worth learning about.</p>
4,604,048
13
15
null
2011-01-05 11:05:10.75 UTC
18
2019-06-09 06:42:30.41 UTC
2011-01-05 11:13:20.063 UTC
null
180,239
null
249,001
null
1
42
python
12,451
<p>You asked for a link or other source, but there really isn't one. The information is spread over many different places. What really constitutes a design mistake, and do you count just syntactic and semantic issues in the language definition, or do you include pragmatic things like platform and standard library issues and specific implementation issues? You could say that Python's dynamism is a design mistake from a performance perspective, because it makes it hard to make a straightforward efficient implementation, and it makes it hard (I didn't say completely impossible) to make an IDE with code completion, refactoring, and other nice things. At the same time, you could argue for the pros of dynamic languages.</p> <p>Maybe one approach to start thinking about this is to look at <a href="https://docs.python.org/3/whatsnew/index.html" rel="nofollow noreferrer" title="What&#39;s New in Python">the language changes from Python 2.x to 3.x</a>. Some people would of course argue that <code>print</code> being a function is inconvenient, while others think it's an improvement. Overall, there are not that many changes, and most of them are quite small and subtle. For example, <code>map()</code> and <code>filter()</code> return iterators instead of lists, <code>range()</code> behaves like <code>xrange()</code> used to, and <code>dict</code> methods like <code>dict.keys()</code> return views instead of lists. Then there are some changes related to integers, and one of the big changes is binary/string data handling. It's now <em>text</em> and <em>data</em>, and text is always Unicode. There are several syntactic changes, but they are more about consistency than revamping the whole language.</p> <p>From this perspective, it appears that Python has been pretty well designed on the language (syntax and sematics) level since at least 2.x. You can always argue about indentation-based block syntax, but we all know that doesn't lead anywhere... ;-)</p> <p>Another approach is to look at what alternative Python implementations are trying to address. Most of them address performance in some way, some address platform issues, and some add or make changes to the language itself to more efficiently solve certain kinds of tasks. <a href="https://code.google.com/archive/p/unladen-swallow/" rel="nofollow noreferrer" title="Unladen Swallow">Unladen swallow</a> wants to make Python significantly faster by optimizing the runtime byte-compilation and execution stages. <a href="https://github.com/stackless-dev/stackless/wiki" rel="nofollow noreferrer" title="Stackless Python">Stackless</a> adds functionality for efficient, heavily threaded applications by adding constructs like microthreads and tasklets, channels to allow bidirectional tasklet communication, scheduling to run tasklets cooperatively or preemptively, and serialisation to suspend and resume tasklet execution. <a href="https://www.jython.org/" rel="nofollow noreferrer" title="Jython">Jython</a> allows using Python on the Java platform and <a href="https://ironpython.net/" rel="nofollow noreferrer" title="IronPython">IronPython</a> on the .Net platform. <a href="https://cython.org/" rel="nofollow noreferrer" title="Cython">Cython</a> is a Python dialect which allows calling C functions and declaring C types, allowing the compiler to generate efficient C code from Cython code. <a href="https://code.google.com/archive/p/shedskin/" rel="nofollow noreferrer" title="Shed Skin">Shed Skin</a> brings implicit static typing into Python and generates C++ for standalone programs or extension modules. <a href="http://codespeak.net/pypy/" rel="nofollow noreferrer" title="PyPy">PyPy</a> implements Python in a subset of Python, and changes some implementation details like adding garbage collection instead of reference counting. The purpose is to allow Python language and implementation development to become more efficient due to the higher-level language. <a href="https://code.google.com/archive/p/pyv8/" rel="nofollow noreferrer" title="Py V8">Py V8</a> bridges Python and JavaScript through the V8 JavaScript engine – you could say it's solving a platform issue. <a href="http://psyco.sourceforge.net/" rel="nofollow noreferrer" title="Psyco">Psyco</a> is a special kind of JIT that dynamically generates special versions of the running code for the data that is currently being handled, which can give speedups for your Python code without having to write optimised C modules.</p> <p>Of these, something can be said about the current state of Python by looking at <a href="https://www.python.org/dev/peps/pep-3146/" rel="nofollow noreferrer" title="Merging Unladen Swallow into CPython">PEP-3146</a> which outlines how Unladen Swallow would be merged into CPython. This PEP is accepted and is thus the Python developers' judgement of what is the most feasible direction to take at the moment. Note it addresses performance, not the language per se.</p> <p>So really I would say that Python's main design <em>problems</em> are in the performance domain – but these are basically the same challenges that any dynamic language has to face, and the Python family of languages and implementations are trying to address the issues. As for outright design <em>mistakes</em> like the ones listed in <a href="https://rads.stackoverflow.com/amzn/click/0596517742" rel="nofollow noreferrer" title="Javascript: the good parts">Javascript: the good parts</a>, I think the meaning of "mistake" needs to be more explicitly defined, but you may want to check out the following for thoughts and opinions:</p> <ul> <li><a href="https://twit.tv/shows/floss-weekly/episodes/11" rel="nofollow noreferrer" title="FLOSS Weekly 11">FLOSS Weekly 11: Guido van Rossum</a> (podcast August 4th, 2006)</li> <li><a href="https://python-history.blogspot.com/" rel="nofollow noreferrer" title="The History of Python blog">The History of Python blog</a></li> </ul>
14,489,112
How do I dynamically bind and statically add MenuItems?
<p>I'm binding the ItemsSource of my MenuItem to an ObservableCollection in my ViewModel. Here is my xaml:</p> <pre><code>&lt;MenuItem Header="_View" ItemsSource="{Binding Windows}"&gt; &lt;MenuItem.ItemContainerStyle&gt; &lt;Style&gt; &lt;Setter Property="MenuItem.Header" Value="{Binding Title}" /&gt; &lt;/Style&gt; &lt;/MenuItem.ItemContainerStyle&gt; &lt;/MenuItem&gt; </code></pre> <p>This part works great, but now I also want to add some static MenuItems to the same View MenuItem, separated with a separator. Something like this, even though I know this won't work because I can't set the items twice. </p> <pre><code>&lt;MenuItem Header="_View" ItemsSource="{Binding Windows}"&gt; &lt;MenuItem.ItemContainerStyle&gt; &lt;Style&gt; &lt;Setter Property="MenuItem.Header" Value="{Binding Title}" /&gt; &lt;/Style&gt; &lt;/MenuItem.ItemContainerStyle&gt; &lt;Separator /&gt; &lt;MenuItem Header="item 1" /&gt; &lt;MenuItem Header="item 2" /&gt; &lt;/MenuItem&gt; </code></pre> <p>For now I have created a work around by adding another level to the MenuItem like this:</p> <pre><code>&lt;MenuItem Header="_View"&gt; &lt;MenuItem Header="Windows" ItemsSource="{Binding Windows}"&gt; &lt;MenuItem.ItemContainerStyle&gt; &lt;Style&gt; &lt;Setter Property="MenuItem.Header" Value="{Binding Title}" /&gt; &lt;/Style&gt; &lt;/MenuItem.ItemContainerStyle&gt; &lt;/MenuItem&gt; &lt;MenuItem Header="Load Layout" /&gt; &lt;MenuItem Header="Save Layout" /&gt; &lt;/MenuItem&gt; </code></pre> <p>This works fine, but I'd rather not have a sub menu if at all possible. Oh, and I'd also prefer to do this in xaml instead of code behind. Any ideas?</p>
14,489,482
1
1
null
2013-01-23 20:49:59.693 UTC
12
2022-04-12 20:05:36.863 UTC
2013-07-23 14:40:21.37 UTC
null
84,873
null
598,859
null
1
26
wpf|xaml|styles|datatemplate|menuitem
18,753
<p>You can use a <code>CompositeCollection</code> to do this, you can combine different Collections and add static items in the xaml.</p> <p>Example:</p> <p>Xaml:</p> <pre><code>&lt;Window x:Class=&quot;WpfApplication8.MainWindow&quot; xmlns=&quot;http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot; xmlns:x=&quot;http://schemas.microsoft.com/winfx/2006/xaml&quot; Title=&quot;MainWindow&quot; Height=&quot;233&quot; Width=&quot;143&quot; Name=&quot;UI&quot;&gt; &lt;Window.Resources&gt; &lt;CollectionViewSource Source=&quot;{Binding ElementName=UI, Path=Windows}&quot; x:Key=&quot;YourMenuItems&quot;/&gt; &lt;/Window.Resources&gt; &lt;Grid DataContext=&quot;{Binding ElementName=UI}&quot;&gt; &lt;Menu Height=&quot;24&quot; VerticalAlignment=&quot;Top&quot;&gt; &lt;MenuItem Header=&quot;_View&quot; &gt; &lt;MenuItem Header=&quot;Windows&quot;&gt; &lt;MenuItem.ItemsSource&gt; &lt;CompositeCollection&gt; &lt;CollectionContainer Collection=&quot;{Binding Source={StaticResource YourMenuItems}}&quot; /&gt; &lt;MenuItem Header=&quot;Menu Item 1&quot; /&gt; &lt;MenuItem Header=&quot;Menu Item 2&quot; /&gt; &lt;MenuItem Header=&quot;Menu Item 3&quot; /&gt; &lt;/CompositeCollection&gt; &lt;/MenuItem.ItemsSource&gt; &lt;MenuItem.ItemContainerStyle&gt; &lt;Style&gt; &lt;Setter Property=&quot;MenuItem.Header&quot; Value=&quot;{Binding Title}&quot;/&gt; &lt;/Style&gt; &lt;/MenuItem.ItemContainerStyle&gt; &lt;/MenuItem&gt; &lt;/MenuItem&gt; &lt;/Menu&gt; &lt;/Grid&gt; &lt;/Window&gt; </code></pre> <p>Code</p> <pre><code>public partial class MainWindow : Window { private ObservableCollection&lt;MyObject&gt; _windows = new ObservableCollection&lt;MyObject&gt;(); public MainWindow() { InitializeComponent(); Windows.Add(new MyObject { Title = &quot;Collection Item 1&quot; }); Windows.Add(new MyObject { Title = &quot;Collection Item 2&quot; }); } public ObservableCollection&lt;MyObject&gt; Windows { get { return _windows; } set { _windows = value; } } } public class MyObject { public string Title { get; set; } } </code></pre> <p>Result:</p> <p><img src="https://i.stack.imgur.com/giGYv.png" alt="enter image description here" /></p>
14,805,225
What's the difference between 'mouseup' and 'click' events?
<p>Using jQuery, I often like to use <code>mousedown</code> and <code>mouseup</code> events in conjunction for pushable buttons.</p> <p>However, in every case I've used the <code>mouseup</code> event, binding the <code>click</code> event instead seemed to produce identical results.</p> <p>Is there any substantial difference between the two methods below?</p> <pre><code>// Method 1 $('.myButton').bind('click', callback); // Method 2 $('.myButton').bind('mouseup', callback); </code></pre> <p><em>Please note I'm seeking a technical explanation on the differences between using both methods. This has no relation to the question that has been flagged as a dupe: <a href="https://stackoverflow.com/questions/12572644/differentiate-click-vs-mousedown-mouseup">Differentiate click vs mousedown/mouseup</a></em></p>
14,805,233
5
3
null
2013-02-11 02:51:24.037 UTC
4
2020-09-13 15:48:26.433 UTC
2017-05-23 10:31:30.213 UTC
null
-1
null
1,608,072
null
1
43
javascript|jquery
35,883
<p>With a mouseup event, you can click somewhere else on the screen, hold down the click button, and move the pointer to your mouseup element, and then release the mouse pointer. </p> <p>A click event requires the mousedown and mouseup event to happen on that element.</p> <p>The normal expectation is that a click requires both the mousedown and mouseup event, so I'd recommend the click event.</p> <p>From the possible duplicate, it appears that mouseup and mousedown events can also be caused by mouse buttons other than the left click button. Which is very different from what a generic user would expect.</p>
14,532,959
How do you save values into a YAML file?
<p>Inside my persist.yml file. I have the following key-value pair...</p> <pre><code>session = 0 </code></pre> <p>How do I update the YAML file such that:</p> <pre><code>session = 2 </code></pre>
14,533,229
1
3
null
2013-01-26 01:44:43.833 UTC
14
2017-05-10 23:39:37.763 UTC
2017-05-10 23:39:37.763 UTC
null
128,421
null
1,967,873
null
1
51
ruby|ruby-on-rails-3|yaml
56,656
<p>Using ruby-1.9.3 (Approach may not work in older versions).</p> <p>I'm assuming the file looks like this (adjust code accordingly):</p> <pre><code>--- content: session: 0 </code></pre> <p>and is called /tmp/test.yml</p> <p>Then the code is just:</p> <pre><code>require 'yaml' # Built in, no gem required d = YAML::load_file('/tmp/test.yml') #Load d['content']['session'] = 2 #Modify File.open('/tmp/test.yml', 'w') {|f| f.write d.to_yaml } #Store </code></pre>
14,907,104
AlertDialog with custom view: Resize to wrap the view's content
<p>I have been having this problem in an application I am building. Please ignore all of the design shortcomings and lack of best practice approaches, this is purely to show an example of what I cannot solve.</p> <p>I have <code>DialogFragment</code> which returns a basic <code>AlertDialog</code> with a custom <code>View</code> set using <code>AlertDialog.Builder.setView()</code>. If this <code>View</code> has a specific size requirement, how do I get the <code>Dialog</code> to correctly resize itself to display all of the content in the custom <code>View</code>?</p> <p>This is the example code I have been using:</p> <pre><code>package com.test.test; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Use a button for launching Button b = new Button(this); b.setText("Launch"); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Launch the dialog myDialog d = new myDialog(); d.show(getFragmentManager(), null); } }); setContentView(b); } public static class myDialog extends DialogFragment { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Create the dialog AlertDialog.Builder db = new AlertDialog.Builder(getActivity()); db.setTitle("Test Alert Dialog:"); db.setView(new myView(getActivity())); return db.create(); } protected class myView extends View { Paint p = null; public myView(Context ct) { super(ct); // Setup paint for the drawing p = new Paint(); p.setColor(Color.MAGENTA); p.setStyle(Style.STROKE); p.setStrokeWidth(10); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(800, 300); } @Override protected void onDraw(Canvas canvas) { // Draw a rectangle showing the bounds of the view canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), p); } } } } </code></pre> <p>A <code>Button</code> is created, which opens the <code>DialogFragment</code> on a click. The custom <code>View</code> (<code>myView</code>) is required to have a width of 800 and height of 300 which is correctly set in an override of <code>onMeasure()</code>. This <code>View</code>, draws its measured bounds in magenta for debugging purposes.</p> <p>The 800 width is wider than the default <code>Dialog</code> size on my device, but is clipped rather than stretching correctly.</p> <p>I have looked through the following solutions:</p> <ul> <li><a href="https://stackoverflow.com/questions/8456143/dialogfragment-getdialog-returns-null">DialogFragment.getDialog returns null</a></li> <li><a href="https://stackoverflow.com/questions/4406804/how-to-control-the-width-and-height-of-default-alert-dialog-in-android">How to control the width and height of the default Alert Dialog in Android?</a></li> <li><a href="https://stackoverflow.com/questions/8835931/size-of-alert-dialog-or-custom-alert-dialog">Size of Alert Dialog or Custom Alert Dialog</a></li> </ul> <p>I have deduced the following two coding approaches:</p> <ol> <li>Get the <code>WindowManager.LayoutParams</code> of the <code>Dialog</code> and override them using <code>myDialog.getDialog().getWindow().get/setAttributes()</code></li> <li>Using the <code>setLayout(w, h)</code> method through <code>myDialog.getDialog().getWindow().setLayout()</code></li> </ol> <p>I have tried them everywhere I can think of (overriding <code>onStart()</code>, in a <code>onShowListener</code>, after the <code>Dialog</code> is created and shown, etc) and can generally get both methods to work correctly if the <code>LayoutParams</code> are supplied a <strong>specific value</strong>. But whenever <code>WRAP_CONTENT</code> is supplied, nothing happens.</p> <p>Any suggestions?</p> <p><strong>EDIT:</strong></p> <p>Screenshot of the situation: <img src="https://i.stack.imgur.com/7161w.png" alt="enter image description here"></p> <p>Screenshot of a specific value (note 900 is entered here, 850 doesn't cover the entire width of the View, which makes sense given the entire window is being adjusted. So that provides - if another was needed - reason why <code>WRAP_CONTENT</code> is essential / fixed values are not appropriate): <img src="https://i.stack.imgur.com/F4Qnc.png" alt="enter image description here"></p>
14,918,253
8
1
null
2013-02-16 04:54:59.383 UTC
21
2018-11-22 20:12:15.797 UTC
2017-05-23 11:47:20.577 UTC
null
-1
null
1,386,784
null
1
60
java|android|android-layout|android-alertdialog|android-dialogfragment
55,781
<p>I have a working solution that to be honest, I think digs way too deep to obtain such a simple result. But here it is:</p> <p><strong>What exactly is happening:</strong> </p> <p>By opening the <code>Dialog</code> layout with the <a href="http://developer.android.com/tools/debugging/debugging-ui.html" rel="noreferrer">Hierarchy Viewer</a>, I was able to examine the entire layout of the <code>AlertDialog</code> and what exactly what was going on: <img src="https://i.stack.imgur.com/AqyqJ.png" alt="enter image description here"></p> <p>The <strong>blue</strong> highlight is all of the high level parts (<code>Window</code>, frames for the <code>Dialog</code> visual style, etc) and from the end of the <strong>blue</strong> down is where the components for the <code>AlertDialog</code> are (<strong>red</strong> = title, <strong>yellow</strong> = a scrollview stub, maybe for list <code>AlertDialog</code>s, <strong>green</strong> = <code>Dialog</code> content i.e. custom view, <strong>orange</strong> = buttons).</p> <p>From here it was clear that the 7-view path (from the start of the <strong>blue</strong> to the end of the <strong>green</strong>) was what was failing to correctly <code>WRAP_CONTENT</code>. Looking at the <code>LayoutParams.width</code> of each <code>View</code> revealed that all are given <code>LayoutParams.width = MATCH_PARENT</code> and somewhere (I guess at the top) a size is set. So if you follow that tree, it is clear that your custom <code>View</code> at the bottom of the tree, will <strong>never</strong> be able to affect the size of the <code>Dialog</code>.</p> <p>So what were the existing solutions doing?</p> <ul> <li>Both of the <em>coding approaches</em> mentioned in my question were simply getting the top <code>View</code> and modifying its <code>LayoutParams</code>. Obviously, with all <code>View</code> objects in the tree matching the parent, if the top level is set a static size, the whole <code>Dialog</code> will change size. But if the top level is set to <code>WRAP_CONTENT</code>, all the rest of the <code>View</code> objects in the tree are still <em>looking up the tree</em> to "MATCH their PARENT", as opposed to <em>looking down the tree</em> to "WRAP their CONTENT".</li> </ul> <p><strong>How to solve the problem:</strong></p> <p>Bluntly, change the <code>LayoutParams.width</code> of all <code>View</code> objects in the affecting path to be <code>WRAP_CONTENT</code>.</p> <p>I found that this could only be done AFTER <code>onStart</code> lifecycle step of the <code>DialogFragment</code> is called. So the <code>onStart</code> is implemented like:</p> <pre><code>@Override public void onStart() { // This MUST be called first! Otherwise the view tweaking will not be present in the displayed Dialog (most likely overriden) super.onStart(); forceWrapContent(myCustomView); } </code></pre> <p>Then the function to appropriately modify the <code>View</code> hierarchy <code>LayoutParams</code>:</p> <pre><code>protected void forceWrapContent(View v) { // Start with the provided view View current = v; // Travel up the tree until fail, modifying the LayoutParams do { // Get the parent ViewParent parent = current.getParent(); // Check if the parent exists if (parent != null) { // Get the view try { current = (View) parent; } catch (ClassCastException e) { // This will happen when at the top view, it cannot be cast to a View break; } // Modify the layout current.getLayoutParams().width = LayoutParams.WRAP_CONTENT; } } while (current.getParent() != null); // Request a layout to be re-done current.requestLayout(); } </code></pre> <p>And here is the working result: <img src="https://i.stack.imgur.com/pSCmZ.png" alt="enter image description here"></p> <p>It confuses me why the entire <code>Dialog</code> would not want to be <code>WRAP_CONTENT</code> with an explicit <code>minWidth</code> set to handle all cases that fit inside the default size, but I'm sure there is a good reason for it the way it is (would be interested to hear it).</p>
2,613,063
remove duplicate from string in PHP
<p>I am looking for the fastest way to remove duplicate values in a string separated by commas.</p> <p>So my string looks like this;</p> <pre><code>$str = 'one,two,one,five,seven,bag,tea'; </code></pre> <p>I can do it be exploding the string to values and then compare, but I think it will be slow. what about preg_replace() will it be faster? Any one did it using this function?</p>
2,613,069
2
1
null
2010-04-10 10:39:51.317 UTC
15
2018-02-01 02:46:34.463 UTC
null
null
null
null
222,159
null
1
40
php|string|duplicates
69,979
<p>The shortest code would be:</p> <pre><code>$str = implode(',',array_unique(explode(',', $str))); </code></pre> <p>If it is the fastest... I don't know, it is probably faster then looping explicitly.</p> <p>Reference: <a href="http://php.net/manual/en/function.implode.php" rel="noreferrer"><code>implode</code></a>, <a href="http://php.net/manual/en/function.array-unique.php" rel="noreferrer"><code>array_unique</code></a>, <a href="http://www.php.net/manual/en/function.explode.php" rel="noreferrer"><code>explode</code></a></p>
17,883,971
Which provider should be used for the Java Persistence API (JPA) implemenation
<p>I want to use the Java Persistence API (JPA) for my web application.</p> <p>There are popular JPA implementations like <em>Hibernate</em>, <em>Toplink</em> and <em>EclipseLink</em>. What implementation is a good choise and why?</p>
17,883,972
1
1
null
2013-07-26 14:24:56.76 UTC
20
2022-02-10 18:19:24.437 UTC
2022-02-10 18:19:24.437 UTC
null
4,294,399
null
2,614,299
null
1
31
java|jpa|persistence|implementation
39,509
<p>When the <strong>Java Persistence API (API)</strong> was developed, it became popular very fast. JPA describes the management of relational data in applications using Java.</p> <p><em>JPA (Java Persistence API) is an interface for persistence providers to implement.</em></p> <p>Hibernate is one such implementation of JPA. When you use Hibernate with JPA you are actually using the Hibernate JPA implementation.</p> <p>JPA typically defines the metadata via annotations in the Java class. Alternatively via XML or a combination of both. A XML configuration overwrites the annotations.</p> <p><strong><em>JPA implementations:</em></strong></p> <ul> <li><strong>Hibernate</strong>: The most advanced and widely used. Pay attention for the classpath because a lot of libraries are used, especially when using JBoss. Supports JPA 2.1.</li> <li><strong>Toplink</strong>: Only supports the basic JPA specs. (This was oracle’s free version of the JPA implementation)</li> <li><strong>EclipseLink</strong>: Is based on TopLink, and is the intended path forward for persistence for Oracle and TopLink. Supports JPA 2.1</li> <li><strong>Apache OpenJPA</strong>: Best documentation but seems very buggy. Open source implementation for JPA. Supports JPA 2.0</li> <li><strong>DataNucleus</strong>: Well documented, open source (Apache 2 license), is also a JDO provider. Supports JPA 2.1</li> <li><strong>ObjectDB</strong>: well documented</li> <li><strong>CMobileCom JPA</strong>: light-weight JPA 2.1 implementation for both Java and Android.</li> </ul> <p><strong><em>Other approaches are:</em></strong></p> <ul> <li>Plain JDBC</li> <li>ORM with Hibernate: Hibernate is now also very supportive for JPA</li> <li>iBatis: The project moved to MyBatis (<a href="http://mybatis.org" rel="noreferrer">link</a>)</li> <li>JDO</li> </ul> <p><em>Motivation for Hibernate as my JPA choice:</em></p> <ul> <li>Mature project: <ul> <li>Most advanced</li> <li>Well documented</li> </ul></li> <li>Useful Hibernate sub projects <ul> <li>Hibernate tools: automatic generation of code and database generation</li> <li>Hibernate validation: bean specification capabilities. Integrates with JPA2</li> <li>Hibernate search: powerful full-text search on domain objects</li> </ul></li> <li>Active community <ul> <li>Big development community</li> <li>Widely used</li> </ul></li> </ul> <p>Hibernate became an open source implementation of JPA very fast after the final specification was published. It has a rich feature set and generates new features fast, because an open-source development process tend to be faster then a Java community process.</p>
7,083,095
Is there a better way of detecting if a Spring DB transaction is active than using TransactionSynchronizationManager.isActualTransactionActive()?
<p>I have some legacy code that I am now trying to re-use under Spring. This code is deeply nested in other code so it's not practical to redesign and is called in many situations, only some of which are through Spring. What I'd like to do is to use the Spring transaction if one has been started; otherwise, continue to use the existing (legacy) db connection mechanism. Our first thought was to make our legacy class a bean and use an injected <code>TransactionPlatformManager</code>, but that does not seem to have any methods germane to our situation. Some research showed that Spring has a class called <code>TransactionSynchronizationManager</code> which has a static method <code>isActualTransactionActive()</code>. My testing indicates this method is a reliable way of detecting if a Spring transaction is active:</p> <ul> <li>When called via Spring service without the <code>@Transactional</code> annotation, it returns false</li> <li>When called via Spring service with <code>@Transactional</code>, it returns true</li> <li>In my legacy method called the existing way, it returns false</li> </ul> <p>My question: Is there a better way of detecting if a transaction is active?</p>
7,083,131
1
0
null
2011-08-16 18:24:37.79 UTC
13
2011-08-18 04:13:19.373 UTC
2011-08-18 04:13:19.373 UTC
null
269,361
null
269,361
null
1
46
spring|transactions
17,581
<p>No better way than the <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/transaction/support/TransactionSynchronizationManager.html#isActualTransactionActive%28%29" rel="noreferrer"><code>TransactionSynchronizationManager.isActualTransactionActive()</code></a>. It is the utility method used by spring to handle the transactions. Although it is not advisable to use it within your code, for some specific cases you should - that's why it's public.</p> <p>Another way might be to use the entity manager / session / connection and check there if there's an existing transaction, but I'd prefer the synchronization manager.</p>
24,769,257
Custom Listview Adapter with filter Android
<p>Please am trying to implement a filter on my listview. But whenever the text change, the list disappears.Please Help Here are my codes. The adapter class.</p> <pre><code>package com.talagbe.schymn; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; public class HymnsAdapter extends ArrayAdapter&lt;Hymns&gt; { ArrayList&lt;Hymns&gt; hymnarray; Context context; LayoutInflater inflater; int Resource; public HymnsAdapter(Context context, int resource, ArrayList&lt;Hymns&gt; objects) { super(context, resource, objects); // TODO Auto-generated constructor stub hymnarray=objects; Resource= resource; this.context=context; inflater= (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; if(convertView==null){ convertView= inflater.inflate(Resource,null); holder= new ViewHolder(); holder.hymntitle= (TextView) convertView.findViewById(R.id.Hymn_title); // holder.hymntext= (TextView) convertView.findViewById(R.id.Channel_name); convertView.setTag(holder); }else{ holder=(ViewHolder)convertView.getTag(); } holder.hymntitle.setText(hymnarray.get(position).getTitle()); //holder.hymntext.setText(hymnarray.get(position).getText()); return convertView; } static class ViewHolder{ public TextView hymntitle; public TextView hymntext; } } </code></pre> <p>Here is the other class where am trying to implement the filter. I have an edittext,where i implement on textChangeListener</p> <pre><code>package com.talagbe.schymn; import java.util.ArrayList; import database.DatabaseHelper; import android.os.Bundle; import android.support.v4.app.Fragment; import android.text.Editable; import android.text.TextWatcher; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.widget.AdapterView.OnItemClickListener; public class Home extends Fragment { private static final String DB_NAME = "schymn.sqlite"; private static final String TABLE_NAME = "Hymns"; private static final String Hymn_ID = "_id"; private static final String Hymn_Title = "Title"; private static final String Hymn_Text = "Text"; private SQLiteDatabase database; ListView list; EditText search; HymnsAdapter vadapter; ArrayList&lt;Hymns&gt; HymnsList; String url; Context context=null; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub return inflater.inflate(R.layout.index, container,false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onCreate(savedInstanceState); list = (ListView)getActivity().findViewById(R.id.hymn_list); search = (EditText) getActivity().findViewById(R.id.search); HymnsList = new ArrayList&lt;Hymns&gt;(); DatabaseHelper dbOpenHelper = new DatabaseHelper(getActivity(), DB_NAME); database = dbOpenHelper.openDataBase(); fillHymns(); //setUpList(); } private void fillHymns() { Cursor hymnCursor = database.query(TABLE_NAME, new String[] {Hymn_ID, Hymn_Title,Hymn_Text}, null, null, null, null , Hymn_Title); hymnCursor.moveToFirst(); if(!hymnCursor.isAfterLast()) { do { Hymns hy = new Hymns(); hy.setTitle(hymnCursor.getString(1)); hy.setText(hymnCursor.getString(2)); HymnsList.add(hy); } while (hymnCursor.moveToNext()); } hymnCursor.close(); vadapter = new HymnsAdapter(getActivity().getApplicationContext(),R.layout.hymns,HymnsList); list.setAdapter(vadapter); list.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) { Intent intent = new Intent(getActivity().getApplicationContext(), Hymn_Text.class); intent.putExtra("Title",HymnsList.get(position).getTitle()); intent.putExtra("Text",HymnsList.get(position).getText()); startActivity(intent); //Log.i("Text",HymnsList.get(position).getText()); } }); search.addTextChangedListener( new TextWatcher() { @Override public void onTextChanged(CharSequence cs, int start, int before, int count) { // TODO Auto-generated method stub if(count&gt;0){ } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub Home.this.vadapter.getFilter().filter(s); Log.i("Changed",s.toString()); } }); } } </code></pre> <p>The log,logs whatever input i type in,but doesn't show the listview. Thank you </p>
24,771,174
10
0
null
2014-07-15 22:29:32.247 UTC
39
2020-09-18 08:23:34.14 UTC
null
null
null
null
3,119,931
null
1
78
android|android-listview|custom-adapter
155,122
<p>You can use the <code>Filterable</code> interface on your Adapter, have a look at the example below:</p> <pre><code>public class SearchableAdapter extends BaseAdapter implements Filterable { private List&lt;String&gt;originalData = null; private List&lt;String&gt;filteredData = null; private LayoutInflater mInflater; private ItemFilter mFilter = new ItemFilter(); public SearchableAdapter(Context context, List&lt;String&gt; data) { this.filteredData = data ; this.originalData = data ; mInflater = LayoutInflater.from(context); } public int getCount() { return filteredData.size(); } public Object getItem(int position) { return filteredData.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary calls // to findViewById() on each row. ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no need // to reinflate it. We only inflate a new View when the convertView supplied // by ListView is null. if (convertView == null) { convertView = mInflater.inflate(R.layout.list_item, null); // Creates a ViewHolder and store references to the two children views // we want to bind data to. holder = new ViewHolder(); holder.text = (TextView) convertView.findViewById(R.id.list_view); // Bind the data efficiently with the holder. convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder) convertView.getTag(); } // If weren't re-ordering this you could rely on what you set last time holder.text.setText(filteredData.get(position)); return convertView; } static class ViewHolder { TextView text; } public Filter getFilter() { return mFilter; } private class ItemFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { String filterString = constraint.toString().toLowerCase(); FilterResults results = new FilterResults(); final List&lt;String&gt; list = originalData; int count = list.size(); final ArrayList&lt;String&gt; nlist = new ArrayList&lt;String&gt;(count); String filterableString ; for (int i = 0; i &lt; count; i++) { filterableString = list.get(i); if (filterableString.toLowerCase().contains(filterString)) { nlist.add(filterableString); } } results.values = nlist; results.count = nlist.size(); return results; } @SuppressWarnings(&quot;unchecked&quot;) @Override protected void publishResults(CharSequence constraint, FilterResults results) { filteredData = (ArrayList&lt;String&gt;) results.values; notifyDataSetChanged(); } } } </code></pre> <p>In your Activity or Fragment where of Adapter is instantiated :</p> <pre><code>editTxt.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { System.out.println(&quot;Text [&quot;+s+&quot;]&quot;); mSearchableAdapter.getFilter().filter(s.toString()); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void afterTextChanged(Editable s) { } }); </code></pre> <p>Here are the links for the <a href="https://gist.github.com/fjfish/3024308" rel="noreferrer">original source</a> and <a href="http://software-workshop.eu/content/android-development-creating-custom-filter-listview" rel="noreferrer">another example</a></p>
22,217,176
split() function for '$' not working
<p>I'm doing a simple code </p> <pre><code>String splitString = "122$23$56$rt"; for(int i=0;i&lt;splitString.split("$").length;i++){ System.out.println("I GOT IS :: "+splitString.split("$")[i]); } </code></pre> <p>When I split like </p> <pre><code>splitString.split("$") </code></pre> <p>It is giving me output <code>[122$23$56$rt]</code></p> <p>Why this is not splinting on '$'?</p>
22,217,214
8
0
null
2014-03-06 06:50:05.77 UTC
3
2014-03-06 08:41:41.2 UTC
2014-03-06 07:03:55.29 UTC
null
1,735,406
null
3,243,855
null
1
29
java
4,438
<p><code>String.split()</code> takes in <strong>regex</strong> as argument and <code>$</code> is a metacharacter in <code>Java regex API</code>. Therefore, you need to escape it:</p> <pre><code>String splitString = "122$23$56$rt"; for(int i=0;i&lt;splitString.split("\\$").length;i++){ System.out.println("I GOT IS :: "+splitString.split("\\$")[i]); } </code></pre> <p>Other metacharacters supported by the <code>Java regex API</code> are: <code>&lt;([{\^-=!|]})?*+.&gt;</code></p>
2,504,923
How to redirect [Authorize] to loginUrl only when Roles are not used?
<p>I'd like <code>[Authorize]</code> to redirect to <em>loginUrl</em> unless I'm also using a role, such as <code>[Authorize (Roles="Admin")]</code>. In that case, I want to simply display a page saying the user isn't authorized.</p> <p>What should I do?</p>
2,510,150
3
3
null
2010-03-24 02:11:16.55 UTC
15
2014-09-10 21:21:20.363 UTC
null
null
null
null
58,634
null
1
26
asp.net-mvc
42,250
<p>Here is the code from my modified implementation of <code>AuthorizeAttribute</code>; I named it <code>SecurityAttribute</code>. The only thing that I have changed is the <code>OnAuthorization</code> method, and I added an additional string property for the Url to redirect to an Unauthorized page:</p> <pre><code>// Set default Unauthorized Page Url here private string _notifyUrl = "/Error/Unauthorized"; public string NotifyUrl { get { return _notifyUrl; } set { _notifyUrl = value; } } public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (AuthorizeCore(filterContext.HttpContext)) { HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; cachePolicy.SetProxyMaxAge(new TimeSpan(0)); cachePolicy.AddValidationCallback(CacheValidateHandler, null); } /// This code added to support custom Unauthorized pages. else if (filterContext.HttpContext.User.Identity.IsAuthenticated) { if (NotifyUrl != null) filterContext.Result = new RedirectResult(NotifyUrl); else // Redirect to Login page. HandleUnauthorizedRequest(filterContext); } /// End of additional code else { // Redirect to Login page. HandleUnauthorizedRequest(filterContext); } } </code></pre> <p>You call it the same way as the original <code>AuthorizeAttribute</code>, except that there is an additional property to override the Unauthorized Page Url:</p> <pre><code>// Use custom Unauthorized page: [Security (Roles="Admin, User", NotifyUrl="/UnauthorizedPage")] // Use default Unauthorized page: [Security (Roles="Admin, User")] </code></pre>
2,764,615
WPF StringFormat={0:C} showing as dollars
<p>Why does this line of code</p> <pre><code>&lt;TextBlock Text="{Binding Net, StringFormat=c}"/&gt; </code></pre> <p>Output the result as $xx.xx when all my regional settings are set to UK. I expect it to output it as £xx.xx. Any ideas? I have tried different variations of the stringformat including StringFormat={}{0:C} but still get the same result.</p> <p>Thanks for looking.</p>
2,764,668
3
0
null
2010-05-04 10:52:28.017 UTC
17
2013-09-23 16:29:26.853 UTC
null
null
null
null
280,302
null
1
48
wpf|binding|currency|regional|string-formatting
40,359
<p>I'm not sure if this has been fixed in .NET 4, but WPF has never picked up the current culture when rendering things like currency or dates. It's something I consider a massive oversight, but thankfully is easily corrected.</p> <p>In your App class:</p> <pre><code>protected override void OnStartup(StartupEventArgs e) { FrameworkElement.LanguageProperty.OverrideMetadata( typeof(FrameworkElement), new FrameworkPropertyMetadata( XmlLanguage.GetLanguage( CultureInfo.CurrentCulture.IetfLanguageTag))); base.OnStartup(e); } </code></pre> <p>See <a href="http://www.nbdtech.com/Blog/archive/2009/03/18/getting-a-wpf-application-to-pick-up-the-correct-regional.aspx" rel="noreferrer">this excellent post</a> for more information.</p>
2,790,383
How to asynchronously read to std::string using Boost::asio?
<p>I'm learning Boost::asio and all that async stuff. How can I asynchronously read to variable <code>user_</code> of type std::string? <code>Boost::asio::buffer(user_)</code> works only with <code>async_write()</code>, but not with <code>async_read()</code>. It works with vector, so what is the reason for it not to work with string? Is there another way to do that besides declaring <code>char user_[max_len]</code> and using <code>Boost::asio::buffer(user_, max_len)</code>?</p> <p>Also, what's the point of inheriting from <code>boost::enable_shared_from_this&lt;Connection&gt;</code> and using <code>shared_from_this()</code> instead of <code>this</code> in <code>async_read()</code> and <code>async_write()</code>? I've seen that a lot in the examples.</p> <p>Here is a part of my code:</p> <pre><code>class Connection { public: Connection(tcp::acceptor &amp;acceptor) : acceptor_(acceptor), socket_(acceptor.get_io_service(), tcp::v4()) { } void start() { acceptor_.get_io_service().post( boost::bind(&amp;Connection::start_accept, this)); } private: void start_accept() { acceptor_.async_accept(socket_, boost::bind(&amp;Connection::handle_accept, this, placeholders::error)); } void handle_accept(const boost::system::error_code&amp; err) { if (err) { disconnect(); } else { async_read(socket_, boost::asio::buffer(user_), boost::bind(&amp;Connection::handle_user_read, this, placeholders::error, placeholders::bytes_transferred)); } } void handle_user_read(const boost::system::error_code&amp; err, std::size_t bytes_transferred) { if (err) { disconnect(); } else { ... } } ... void disconnect() { socket_.shutdown(tcp::socket::shutdown_both); socket_.close(); socket_.open(tcp::v4()); start_accept(); } tcp::acceptor &amp;acceptor_; tcp::socket socket_; std::string user_; std::string pass_; ... }; </code></pre>
2,795,371
4
0
null
2010-05-07 17:23:00.997 UTC
9
2021-04-27 00:01:58.973 UTC
2014-01-10 20:44:12.607 UTC
null
2,228,070
null
69,265
null
1
18
string|boost|asynchronous|boost-asio
29,784
<p>The Boost.Asio documentation states:</p> <blockquote> <p>A buffer object represents a contiguous region of memory as a 2-tuple consisting of a pointer and size in bytes. A tuple of the form {void*, size_t} specifies a mutable (modifiable) region of memory.</p> </blockquote> <p>This means that in order for a call to <code>async_read</code> to write data to a buffer, it must be (in the underlying buffer object) a contiguous block of memory. Additionally, the buffer object must be able to write to that block of memory. </p> <p><code>std::string</code> does not allow arbitrary writes into its buffer, so <code>async_read</code> cannot write chunks of memory into a string's buffer (note that <code>std::string</code> <em>does</em> give the caller read-only access to the underlying buffer via the <code>data()</code> method, which guarantees that the returned pointer will be valid until the next call to a non-const member function. For this reason, Asio can easily create a <code>const_buffer</code> wrapping an <code>std::string</code>, and you can use it with <code>async_write</code>).</p> <p>The Asio documentation has example code for a simple "chat" program (see <a href="http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/examples.html#boost_asio.examples.chat" rel="noreferrer">http://www.boost.org/doc/libs/1_43_0/doc/html/boost_asio/examples.html#boost_asio.examples.chat</a>) that has a good method of overcoming this problem. Basically, you need to have the sending TCP send along the size of a message first, in a "header" of sorts, and your read handler must interpret the header to allocate a buffer of a fixed size suitable for reading the actual data.</p> <p>As far as the need for using <code>shared_from_this()</code> in <code>async_read</code> and <code>async_write</code>, the reason is that it guarantees that the method wrapped by <code>boost::bind</code> will always refer to a live object. Consider the following situation:</p> <ol> <li>Your <code>handle_accept</code> method calls <code>async_read</code> and sends a handler "into the reactor" - basically you've asked the <code>io_service</code> to invoke <code>Connection::handle_user_read</code> when it finishes reading data from the socket. The <code>io_service</code> stores this functor and continues its loop, waiting for the asynchronous read operation to complete.</li> <li>After your call to <code>async_read</code>, the <code>Connection</code> object is deallocated for some reason (program termination, an error condition, etc.)</li> <li>Suppose the <code>io_service</code> now determines that the asynchronous read is complete, <em>after</em> the <code>Connection</code> object has been deallocated but <em>before</em> the <code>io_service</code> is destroyed (this can occur, for example, if <code>io_service::run</code> is running in a separate thread, as is typical). Now, the <code>io_service</code> attempts to invoke the handler, and it has an invalid reference to a <code>Connection</code> object.</li> </ol> <p>The solution is to allocate <code>Connection</code> via a <code>shared_ptr</code> and use <code>shared_from_this()</code> instead of <code>this</code> when sending a handler "into the reactor" - this allows <code>io_service</code> to store a shared reference to the object, and <code>shared_ptr</code> guarantees that it won't be deallocated until the last reference expires.</p> <p>So, your code should probably look something like:</p> <pre><code>class Connection : public boost::enable_shared_from_this&lt;Connection&gt; { public: Connection(tcp::acceptor &amp;acceptor) : acceptor_(acceptor), socket_(acceptor.get_io_service(), tcp::v4()) { } void start() { acceptor_.get_io_service().post( boost::bind(&amp;Connection::start_accept, shared_from_this())); } private: void start_accept() { acceptor_.async_accept(socket_, boost::bind(&amp;Connection::handle_accept, shared_from_this(), placeholders::error)); } void handle_accept(const boost::system::error_code&amp; err) { if (err) { disconnect(); } else { async_read(socket_, boost::asio::buffer(user_), boost::bind(&amp;Connection::handle_user_read, shared_from_this(), placeholders::error, placeholders::bytes_transferred)); } } //... }; </code></pre> <p>Note that you now must make sure that each <code>Connection</code> object is allocated via a <code>shared_ptr</code>, e.g.:</p> <pre><code>boost::shared_ptr&lt;Connection&gt; new_conn(new Connection(...)); </code></pre> <p>Hope this helps!</p>
2,709,361
Monad equivalent in Ruby
<p>What would an equivalent construct of a monad be in Ruby?</p>
2,709,454
4
2
null
2010-04-25 18:25:01.107 UTC
21
2012-05-03 21:07:38.837 UTC
null
null
null
user65663
null
null
1
39
ruby|functional-programming|monads
6,993
<p><strong>The precise technical definition</strong>: A monad, in Ruby, would be any class with <code>bind</code> and <code>self.unit</code> methods defined such that for all instances m:</p> <pre><code>m.class.unit[a].bind[f] == f[a] m.bind[m.class.unit] == m m.bind[f].bind[g] == m.bind[lambda {|x| f[x].bind[g]}] </code></pre> <p><strong>Some practical examples</strong></p> <p>A very simple example of a monad is the lazy Identity monad, which emulates lazy semantics in Ruby (a strict language):</p> <pre><code>class Id def initialize(lam) @v = lam end def force @v[] end def self.unit lambda {|x| Id.new(lambda { x })} end def bind x = self lambda {|f| Id.new(lambda { f[x.force] })} end end </code></pre> <p>Using this, you can chain procs together in a lazy manner. For example, in the following, <code>x</code> is a container "containing" <code>40</code>, but the computation is not performed until the second line, evidenced by the fact that the <code>puts</code> statement doesn't output anything until <code>force</code> is called:</p> <pre><code>x = Id.new(lambda {20}).bind[lambda {|x| puts x; Id.unit[x * 2]}] x.force </code></pre> <p>A somewhat similar, less abstract example would be a monad for getting values out of a database. Let's presume that we have a class <code>Query</code> with a <code>run(c)</code> method that takes a database connection <code>c</code>, and a constructor of <code>Query</code> objects that takes, say, an SQL string. So <code>DatabaseValue</code> represents a value that's coming from the database. DatabaseValue is a monad:</p> <pre><code>class DatabaseValue def initialize(lam) @cont = lam end def self.fromQuery(q) DatabaseValue.new(lambda {|c| q.run(c) }) end def run(c) @cont[c] end def self.unit lambda {|x| DatabaseValue.new(lambda {|c| x })} end def bind x = self lambda {|f| DatabaseValue.new(lambda {|c| f[x.run(c)].run(c) })} end end </code></pre> <p>This would let you chain database calls through a single connection, like so:</p> <pre><code>q = unit["John"].bind[lambda {|n| fromQuery(Query.new("select dep_id from emp where name = #{n}")). bind[lambda {|id| fromQuery(Query.new("select name from dep where id = #{id}"))}]. bind[lambda { |name| unit[doSomethingWithDeptName(name)] }] begin c = openDbConnection someResult = q.run(c) rescue puts "Error #{$!}" ensure c.close end </code></pre> <p>OK, so why on earth would you do that? Because there are extremely useful functions that can be written once <em>for all monads</em>. So code that you would normally write over and over can be reused for any monad once you simply implement <code>unit</code> and <code>bind</code>. For example, we can define a Monad mixin that endows all such classes with some useful methods:</p> <pre><code>module Monad I = lambda {|x| x } # Structure-preserving transform that applies the given function # across the monad environment. def map lambda {|f| bind[lambda {|x| self.class.unit[f[x]] }]} end # Joins a monad environment containing another into one environment. def flatten bind[I] end # Applies a function internally in the monad. def ap lambda {|x| liftM2[I,x] } end # Binds a binary function across two environments. def liftM2 lambda {|f, m| bind[lambda {|x1| m.bind[lambda {|x2| self.class.unit[f[x1,x2]] }] }] } end end </code></pre> <p>And this in turn lets us do even more useful things, like define this function:</p> <pre><code># An internal array iterator [m a] =&gt; m [a] def sequence(m) snoc = lambda {|xs, x| xs + [x]} lambda {|ms| ms.inject(m.unit[[]], &amp;(lambda {|x, xs| x.liftM2[snoc, xs] }))} end </code></pre> <p>The <code>sequence</code> method takes a class that mixes in Monad, and returns a function that takes an array of monadic values and turns it into a monadic value containing an array. They could be <code>Id</code> values (turning an array of Identities into an Identity containing an array), or <code>DatabaseValue</code> objects (turning an array of queries into a query that returns an array), or functions (turning an array of functions into a function that returns an array), or arrays (turning an array of arrays inside-out), or parsers, continuations, state machines, or anything else that could possibly mix in the <code>Monad</code> module (which, as it turns out, is true for almost all data structures).</p>
2,723,052
How to get the list of the authenticated users?
<p>I would like to display the list of the authenticated users. </p> <p>On the documentation: <a href="http://docs.djangoproject.com/en/dev/topics/auth/" rel="noreferrer">http://docs.djangoproject.com/en/dev/topics/auth/</a></p> <blockquote> <p>class models.User<br> is_authenticated()¶<br> Always returns True. This is a way to tell if the user has been authenticated. ...</p> </blockquote> <p>You can know on the template side is the <strong>current</strong> User is authenticated or not: </p> <blockquote> <p>{% if user.is_authenticated %} {% endif %}</p> </blockquote> <p>But I didn't found the way the get the list of the authenticated users.</p> <p>Any idea?</p>
2,723,706
4
0
null
2010-04-27 16:33:44.72 UTC
31
2022-04-11 07:27:39.923 UTC
2011-11-04 11:35:40.907 UTC
null
1,288
null
327,036
null
1
39
django|authentication
29,361
<p>Going along with rz's answer, you could query the <code>Session</code> model for non-expired sessions, then turn the session data into users. Once you've got that you could turn it into a template tag which could render the list on any given page.</p> <p>(This is all untested, but hopefully will be close to working).</p> <p>Fetch all the logged in users...</p> <pre><code>from django.contrib.auth.models import User from django.contrib.sessions.models import Session from django.utils import timezone def get_all_logged_in_users(): # Query all non-expired sessions # use timezone.now() instead of datetime.now() in latest versions of Django sessions = Session.objects.filter(expire_date__gte=timezone.now()) uid_list = [] # Build a list of user ids from that query for session in sessions: data = session.get_decoded() uid_list.append(data.get('_auth_user_id', None)) # Query all logged in users based on id list return User.objects.filter(id__in=uid_list) </code></pre> <p>Using this, you can make a simple inclusion template tag...</p> <pre><code>from django import template from wherever import get_all_logged_in_users register = template.Library() @register.inclusion_tag('templatetags/logged_in_user_list.html') def render_logged_in_user_list(): return { 'users': get_all_logged_in_users() } </code></pre> <p><strong>logged_in_user_list.html</strong></p> <pre><code>{% if users %} &lt;ul class="user-list"&gt; {% for user in users %} &lt;li&gt;{{ user }}&lt;/li&gt; {% endfor %} &lt;/ul&gt; {% endif %} </code></pre> <p>Then in your main page you can simply use it where you like...</p> <pre><code>{% load your_library_name %} {% render_logged_in_user_list %} </code></pre> <p><strong>EDIT</strong></p> <p>For those talking about the 2-week persistent issue, I'm assuming that anyone wanting to have an "active users" type of listing will be making use of the <a href="http://docs.djangoproject.com/en/dev/topics/http/sessions/#browser-length-sessions-vs-persistent-sessions" rel="noreferrer"><code>SESSION_EXPIRE_AT_BROWSER_CLOSE</code></a> setting, though I recognize this isn't always the case.</p>
38,769,888
Check if a user/guest has purchased specific products in WooCommerce
<p>I need to check if a customer has purchased a specific product earlier in WooCommerce. </p> <p>The case is this: The customer shall not be able to purchase product "c", "d", "e" unless they have purchased product "a" or "b" at an earlier time.</p> <p>If the customer has purchased product "a" or "b" earlier, then the purchase button of product "c", "d" and "e" is activated and they are allowed to buy them. </p> <p>If they haven´t purchased "a" or "b" earlier, they will not be allowed to purchase "c", "d", "e" and the purchase button is deactivated.</p> <p>How can I achieve this? </p> <p>Thanks.</p>
38,772,202
4
0
null
2016-08-04 14:15:11.827 UTC
9
2022-04-07 17:08:52.79 UTC
2022-04-07 17:08:52.79 UTC
null
11,987,538
null
6,678,418
null
1
13
php|wordpress|woocommerce|product|orders
33,100
<blockquote> <h3>Lighter and improved code version <a href="https://stackoverflow.com/a/46217461/3730754">in HERE</a> that handle multiple product IDs</h3> </blockquote> <p><strong>Updated</strong> <em>(compatibility for Woocommerce 3+)</em></p> <p>Yes it's possible, writing a conditional function that returns "true" if current customer has already bought specifics defined products IDs. <em>This code goes on function.php file of your active child theme or theme</em>. </p> <p>Here is the conditional function:</p> <pre><code>function has_bought_items() { $bought = false; // Set HERE ine the array your specific target product IDs $prod_arr = array( '21', '67' ); // Get all customer orders $customer_orders = get_posts( array( 'numberposts' =&gt; -1, 'meta_key' =&gt; '_customer_user', 'meta_value' =&gt; get_current_user_id(), 'post_type' =&gt; 'shop_order', // WC orders post type 'post_status' =&gt; 'wc-completed' // Only orders with status "completed" ) ); foreach ( $customer_orders as $customer_order ) { // Updated compatibility with WooCommerce 3+ $order_id = method_exists( $order, 'get_id' ) ? $order-&gt;get_id() : $order-&gt;id; $order = wc_get_order( $customer_order ); // Iterating through each current customer products bought in the order foreach ($order-&gt;get_items() as $item) { // WC 3+ compatibility if ( version_compare( WC_VERSION, '3.0', '&lt;' ) ) $product_id = $item['product_id']; else $product_id = $item-&gt;get_product_id(); // Your condition related to your 2 specific products Ids if ( in_array( $product_id, $prod_arr ) ) $bought = true; } } // return "true" if one the specifics products have been bought before by customer return $bought; } </code></pre> <p><strong>This code is tested and works.</strong></p> <hr> <p><strong>USAGE:</strong><br> For example, you can use it in some <strong><a href="https://docs.woocommerce.com/document/template-structure/" rel="noreferrer">WooCommerce templates</a></strong> that you will have previously copied to your active child theme or theme: </p> <ul> <li>The template for <strong>Shop page</strong> concerning <strong><code>add-to-cart</code></strong> button is <a href="https://docs.woocommerce.com/document/template-structure/" rel="noreferrer"><code>loop/add-to-cart.php</code></a>. </li> <li>The templates for <strong>Product pages</strong> concerning <strong><code>add-to-cart</code></strong> button are in <a href="https://docs.woocommerce.com/document/template-structure/" rel="noreferrer"><code>single-product/add-to-cart</code> folder</a> depending on your product types.</li> </ul> <p>Here is an example that you could use in those templates <em>(above)</em>:</p> <pre><code>// Replace the numbers by your special restricted products IDs $restricted_products = array( '20', '32', '75' ); // compatibility with WC +3 $product_id = method_exists( $product, 'get_id' ) ? $product-&gt;get_id() : $product-&gt;id; // customer has NOT already bought a specific product for this restricted products if ( !has_bought_items() &amp;&amp; in_array( $product_id, $restricted_products ) ) { // Displaying an INACTIVE add-to-cart button (With a custom text, style and without the link). // (AND optionally) an explicit message for example. // ALL OTHER PRODUCTS OR RESTRICTED PRODUCTS IF COSTUMER HAS ALREADY BOUGHT SPECIAL PRODUCTS } else { // place for normal Add-To-Cart button code here } </code></pre> <p>And here <strong>the complete applied example</strong> to <strong><code>add-to-cart</code></strong> button template on <strong>Shop page</strong>: </p> <pre><code>&lt;?php /** * Loop Add to Cart * * This template can be overridden by copying it to yourtheme/woocommerce/loop/add-to-cart.php. * * HOWEVER, on occasion WooCommerce will need to update template files and you * (the theme developer) will need to copy the new files to your theme to * maintain compatibility. We try to do this as little as possible, but it does * happen. When this occurs the version of the template file will be bumped and * the readme will list any important changes. * * @see https://docs.woocommerce.com/document/template-structure/ * @author WooThemes * @package WooCommerce/Templates * @version 2.5.0 */ if ( ! defined( 'ABSPATH' ) ) { exit; } global $product; // Replace the numbers by your special restricted products IDs $restricted_products = array( '37', '53', '70' ); // compatibility with WC +3 $product_id = method_exists( $product, 'get_id' ) ? $product-&gt;get_id() : $product-&gt;id; if ( !has_bought_items() &amp;&amp; in_array( $product_id, $restricted_products ) ) { echo '&lt;a class="button greyed_button"&gt;' . __("Disabled", "your_theme_slug") . '&lt;/a&gt;'; echo '&lt;br&gt;&lt;span class="greyed_button-message"&gt;' . __("Your message goes here…", "your_theme_slug") . '&lt;/span&gt;'; } else { echo apply_filters( 'woocommerce_loop_add_to_cart_link', sprintf( '&lt;a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s"&gt;%s&lt;/a&gt;', esc_url( $product-&gt;add_to_cart_url() ), esc_attr( isset( $quantity ) ? $quantity : 1 ), esc_attr( $product_id ), esc_attr( $product-&gt;get_sku() ), esc_attr( isset( $class ) ? $class : 'button' ), esc_html( $product-&gt;add_to_cart_text() ) ), $product ); } </code></pre> <p><em>You will style the inactive button with <strong><code>greyed_button</code></strong> class in the <strong><code>style.css</code></strong> file of your active child theme or theme. Same thing for the message with <strong><code>greyed_button-message</code></strong> class.</em></p>
36,188,356
Enable select2 multi-select search box
<p>I need to be able to add a search box to my multi-select fields using select2.</p> <p>For whatever reason, while search boxes appear as expected in single-select fields, the same select2() call on a multi-select field does not add a search box.</p> <pre><code>var data = []; // Programatically-generated options array with &gt; 5 options var placeholder = "select"; $(".mySelect").select2({ data: data, placeholder: placeholder, allowClear: false, minimumResultsForSearch: 5}); </code></pre> <p>Does select2 not support search boxes with multi-selects? Does anyone have a good similarly-functioning alternative?</p>
36,201,207
4
0
null
2016-03-23 20:44:42.353 UTC
4
2020-10-08 10:28:44.937 UTC
null
null
null
null
2,444,020
null
1
20
javascript|jquery|jquery-select2
114,440
<p>The answer is that the select2 input element <em>becomes</em> the search box for multiple selects without back end data</p> <p>if you start typing , your results will start filtering the options</p> <p>if you have it set to load remote ajax data, it actually does retain a search box, but for multiple selects without a data source, the input is the search bar, which is fairly intuitive</p> <p><a href="https://select2.github.io/examples.html" rel="noreferrer">https://select2.github.io/examples.html</a></p>
45,839,316
Pandas : balancing data
<p><strong>Note: This question is not the same as an answer here: "Pandas: sample each group after groupby"</strong></p> <p>Trying to figure out how to use <code>pandas.DataFrame.sample</code> or any other function to balance this data:</p> <pre><code>df[class].value_counts() c1 9170 c2 5266 c3 4523 c4 2193 c5 1956 c6 1896 c7 1580 c8 1407 c9 1324 </code></pre> <p>I need to get a random sample of each class (c1, c2, .. c9) where sample size is equal to the size of a class with min number of instances. In this example sample size should be the size of class c9 = 1324.</p> <p>Any simple way to do this with Pandas?</p> <p><strong>Update</strong></p> <p>To clarify my question, in the table above :</p> <pre><code>c1 9170 c2 5266 c3 4523 ... </code></pre> <p>Numbers are counts of instances of c1,c2,c3,... classes, so actual data looks like this:</p> <pre><code>c1 'foo' c2 'bar' c1 'foo-2' c1 'foo-145' c1 'xxx-07' c2 'zzz' ... </code></pre> <p>etc.</p> <p><strong>Update 2</strong></p> <p>To clarify more:</p> <pre><code>d = {'class':['c1','c2','c1','c1','c2','c1','c1','c2','c3','c3'], 'val': [1,2,1,1,2,1,1,2,3,3] } df = pd.DataFrame(d) class val 0 c1 1 1 c2 2 2 c1 1 3 c1 1 4 c2 2 5 c1 1 6 c1 1 7 c2 2 8 c3 3 9 c3 3 df['class'].value_counts() c1 5 c2 3 c3 2 Name: class, dtype: int64 g = df.groupby('class') g.apply(lambda x: x.sample(g.size().min())) class val class c1 6 c1 1 5 c1 1 c2 4 c2 2 1 c2 2 c3 9 c3 3 8 c3 3 </code></pre> <p>Looks like this works. Main questions:</p> <p>How <code>g.apply(lambda x: x.sample(g.size().min()))</code> works? I know what 'lambda` is, but: </p> <ul> <li>What is passed to <code>lambda</code> in <code>x</code> in this case? </li> <li>What is <code>g</code> in <code>g.size()</code>? </li> <li>Why output contains 6,5,4, 1,8,9 numbers? What do they mean?</li> </ul>
45,839,920
5
0
null
2017-08-23 12:08:58.263 UTC
13
2021-10-29 02:12:51.327 UTC
2017-08-23 13:51:06.377 UTC
null
1,226,649
null
1,226,649
null
1
29
python|pandas
32,835
<pre><code>g = df.groupby('class') g.apply(lambda x: x.sample(g.size().min()).reset_index(drop=True)) class val 0 c1 1 1 c1 1 2 c2 2 3 c2 2 4 c3 3 5 c3 3 </code></pre> <hr> <p><strong>Answers to your follow-up questions</strong> </p> <ol> <li>The <code>x</code> in the <code>lambda</code> ends up being a dataframe that is the subset of <code>df</code> represented by the group. Each of these dataframes, one for each group, gets passed through this <code>lambda</code>.</li> <li><code>g</code> is the <code>groupby</code> object. I placed it in a named variable because I planned on using it twice. <code>df.groupby('class').size()</code> is an alternative way to do <code>df['class'].value_counts()</code> but since I was going to <code>groupby</code> anyway, I might as well reuse the same <code>groupby</code>, use a <code>size</code> to get the value counts... saves time.</li> <li>Those numbers are the the index values from <code>df</code> that go with the sampling. I added <code>reset_index(drop=True)</code> to get rid of it.</li> </ol>
29,740,488
Parameter type may not live long enough?
<p>The following code segment gives me an error:</p> <pre><code>use std::rc::Rc; // Definition of Cat, Dog, and Animal (see the last code block) // ... type RcAnimal = Rc&lt;Box&lt;Animal&gt;&gt;; fn new_rc_animal&lt;T&gt;(animal: T) -&gt; RcAnimal where T: Animal /* + 'static */ // works fine if uncommented { Rc::new(Box::new(animal) as Box&lt;Animal&gt;) } fn main() { let dog: RcAnimal = new_rc_animal(Dog); let cat: RcAnimal = new_rc_animal(Cat); let mut v: Vec&lt;RcAnimal&gt; = Vec::new(); v.push(cat.clone()); v.push(dog.clone()); for animal in v.iter() { println!("{}", (**animal).make_sound()); } } </code></pre> <pre class="lang-none prettyprint-override"><code>error[E0310]: the parameter type `T` may not live long enough --&gt; src/main.rs:8:13 | 4 | fn new_rc_animal&lt;T&gt;(animal: T) -&gt; RcAnimal | - help: consider adding an explicit lifetime bound `T: 'static`... ... 8 | Rc::new(Box::new(animal) as Box&lt;Animal&gt;) | ^^^^^^^^^^^^^^^^ | note: ...so that the type `T` will meet its required lifetime bounds --&gt; src/main.rs:8:13 | 8 | Rc::new(Box::new(animal) as Box&lt;Animal&gt;) | ^^^^^^^^^^^^^^^^ </code></pre> <p>but this compiles fine:</p> <pre><code>use std::rc::Rc; // Definition of Cat, Dog, and Animal (see the last code block) // ... fn new_rc_animal&lt;T&gt;(animal: T) -&gt; Rc&lt;Box&lt;T&gt;&gt; where T: Animal, { Rc::new(Box::new(animal)) } fn main() { let dog = new_rc_animal(Dog); let cat = new_rc_animal(Cat); } </code></pre> <p>What is the cause of the error? The only real difference seems to be the use of operator <code>as</code>. How can a <em>type</em> not live long enough? (<a href="https://play.rust-lang.org/?gist=ed3b70d7b845c9ee13982ae6de01577d&amp;version=beta" rel="noreferrer">playground</a>)</p> <pre><code>// Definition of Cat, Dog, and Animal trait Animal { fn make_sound(&amp;self) -&gt; String; } struct Cat; impl Animal for Cat { fn make_sound(&amp;self) -&gt; String { "meow".to_string() } } struct Dog; impl Animal for Dog { fn make_sound(&amp;self) -&gt; String { "woof".to_string() } } </code></pre> <hr> <p><strong>Addendum</strong></p> <p>Just to clarify, I had two questions:</p> <ol> <li>Why doesn't this work? ... which is addressed in the accepted answer.</li> <li>How can a <em>type</em>, as opposed to a value or reference, be shortlived? ... which was addressed in the comments. Spoiler: a <em>type</em> simply exists since it's a compile-time concept.</li> </ol>
29,740,792
1
0
null
2015-04-20 06:16:57.883 UTC
2
2020-04-30 09:58:40.787 UTC
2020-04-30 09:58:40.787 UTC
null
2,849,934
null
2,849,934
null
1
35
rust
19,218
<p>There are actually plenty of types that can "not live long enough": all the ones that have a lifetime parameter.</p> <p>If I were to introduce this type:</p> <pre class="lang-rust prettyprint-override"><code>struct ShortLivedBee&lt;'a&gt;; impl&lt;'a&gt; Animal for ShortLivedBee&lt;'a&gt; {} </code></pre> <p><code>ShortLivedBee</code> is not valid for any lifetime, but only the ones that are valid for <code>'a</code> as well.</p> <p>So in your case with the bound</p> <pre class="lang-rust prettyprint-override"><code>where T: Animal + 'static </code></pre> <p>the only <code>ShortLivedBee</code> I could feed into your function is <code>ShortLivedBee&lt;'static&gt;</code>.</p> <p>What causes this is that when creating a <code>Box&lt;Animal&gt;</code>, you are creating a trait object, which need to have an associated lifetime. If you do not specify it, it defaults to <code>'static</code>. So the type you defined is actually:</p> <pre class="lang-rust prettyprint-override"><code>type RcAnimal = Rc&lt;Box&lt;Animal + 'static&gt;&gt;; </code></pre> <p>That's why your function require that a <code>'static</code> bound is added to <code>T</code>: <strong>It is not possible to store a <code>ShortLivedBee&lt;'a&gt;</code> in a <code>Box&lt;Animal + 'static&gt;</code> unless <code>'a = 'static</code>.</strong></p> <hr> <p>An other approach would be to add a lifetime annotation to your <code>RcAnimal</code>, like this:</p> <pre class="lang-rust prettyprint-override"><code>type RcAnimal&lt;'a&gt; = Rc&lt;Box&lt;Animal + 'a&gt;&gt;; </code></pre> <p>And change your function to explicit the lifetime relations:</p> <pre class="lang-rust prettyprint-override"><code>fn new_rc_animal&lt;'a, T&gt;(animal: T) -&gt; RcAnimal&lt;'a&gt; where T: Animal + 'a { Rc::new(Box::new(animal) as Box&lt;Animal&gt;) } </code></pre>
29,688,982
Derived account balance vs stored account balance for a simple bank account?
<p>So, its like our normal bank accounts where we have a lot of transactions which result in inflow or outflow of money. The account balance can always be derived by simply summing up the transaction values. What would be better in this case, storing the updated account balance in the database or re-calculating it whenever needed?</p> <p>Expected transaction volume per account: &lt;5 daily</p> <p>Expected retrieval of account balance: Whenever a transaction happens and once a day on an average otherwise. </p> <p>How would you suggest to take a decision on this? Thanks a lot!</p>
29,713,230
2
0
null
2015-04-17 02:04:37.993 UTC
87
2019-12-29 17:13:22.73 UTC
null
null
null
null
4,389,984
null
1
64
database|database-design|derived-table
19,809
<blockquote> <h3>Preface</h3> <p>There is an objective truth: Audit requirements. Additionally, when dealing with public funds, there is Legislature that must be complied with.</p> <p>You don't have to implement the full accounting requirement, you can implement just the parts that you need.</p> <p>Conversely, it would be ill-advised to implement something <em>other than</em> the standard accounting requirement (the parts thereof) because that guarantees that when the number of bugs or the load exceeds some threshold, or the system expands,you will have to re-implement. A cost that can, and therefore should, be avoided.</p> <p>It also needs to be stated: do not hire an unqualified, un-accredited "auditor". There will be consequences, the same as if you hired an unqualified developer. It might be worse, if the Tax Office fines you. </p> </blockquote> <h1>Method</h1> <p>The Standard Accounting method in not-so-primitive countries is this. The "best practice", if you will, in others.</p> <p>This method applies to any system that has similar operations; needs; historic monthly figures vs current-month requirements, such as Inventory Control, etc.</p> <h3>Consideration</h3> <p>First, the considerations.</p> <ol> <li><p>Never duplicate data.<br> If the Current Balance can be derived (and here it is simple), do not duplicate it with a summary column. Such a column is a duplication of data. It breaks Normalisation rules. Further, it <em>creates</em> an Update Anomaly, which otherwise does not exist.</p></li> <li><p>If you do use a summary column, whenever the Transactions are updated (as in changed, not as in when a new Transaction is inserted), the summary column <em>value</em> becomes obsolete, so it must be updated all the time anyway. That is the consequence of the Update Anomaly. Which eliminates the value of having it.</p></li> <li><p>External publication.<br> Separate point. If the balance is published, as in a monthly Bank Statement, such documents usually have legal restrictions and implications, thus that published Current Balance value must not change after publication.</p> <ul> <li><p>Any change, after the publication date, in the database, of a figure that is published externally, is evidence of dishonest conduct, fraud, etc. </p> <ul> <li>Such an act, attempting to change published history, is the hallmark of a novice. Novices and mental patients will insist that history can be changed. But as everyone should know, ignorance of the law does not constitute a valid defence.</li> </ul></li> <li><p>You wouldn't want your bank, in Apr 2015, to change your Current Balance that they published in their Bank Statement to you of Dec 2014. </p></li> <li><p>That figure has to be viewed as an Audit figure, published and unchangeable. </p></li> </ul></li> <li><p>To correct an error that was made in the past, that is being corrected in the present, the correction or adjustment that is necessary, is made as new Transactions in the current month (even though it applies to some previous month or duration). </p> <p>This is because that applicable-to month is closed; Audited; and published, because one cannot change history after it has happened and it has been recorded. The only <strong>effective</strong> month is the current one.</p> <ul> <li><p>For interest-bearing systems, etc, in not-so-primitive countries, when an error is found, and it has an historic effect (eg. you find out in Apr 2015 that the interest calculated on a security has been incorrect, since Dec 2014), the value of the corrected interest payment/deduction is calculated today, for the number of days that were in error, and the sum is inserted as a Transaction in the current month. Again, the only effective month is the current one.</p> <p>And of course, the interest rate for the security has to be corrected as well, so that that error does not repeat.</p></li> <li><p>If you find an error in your bank's calculation of the interest on your Savings (interest-bearing) Account, and you have it corrected, you get a single deposit, that constitutes the whole adjustment value, in the current month. That is a Transaction in the current month.</p> <p>The bank does not: change history; apply interest for each of the historic months; recall the historic Bank Statements; re-publish the historic Bank Statements. No. Except maybe in third world countries.</p></li> <li><p>The same principles apply to Inventory control systems. It maintains sanity.</p></li> </ul></li> <li><p>All real accounting systems (ie. those that are accredited by the Audit Authority in the applicable country, as opposed to the Mickey Mouse "packages" that abound) use a Double Entry system for Transactions, precisely because it prevents a raft of errors, the most important of which is, funds do not get "lost". That requires a General Ledger and Double-Entry Accounting.</p> <ul> <li>You have not asked for that, you do not need that, therefore I am not describing it here. But do remember it, in case money goes "missing", because that is what you will have to implement, not some band-aid solution; not yet another unaccredited "package".</li> </ul> <blockquote> <p>This Answer services the Question that is asked, which is <strong>not</strong> Double-Entry Accounting.<br> For a full treatment of that subject (detailed data model; examples of accounting Transactions; rows affected; and SQL code examples), refer to this Q&amp;A:<br> <strong><a href="https://stackoverflow.com/a/59465148/484814">Relational Data Model for Double-Entry Accounting</a></strong>.</p> </blockquote></li> <li><p>The major issues that affect performance are outside the scope of this question, they are in the area of whether you implement a genuine Relational Database or not (eg. a 1960's Record Filing System, which is characterised by <code>Record IDs</code>, deployed in an SQL database container for convenience). </p> <ul> <li><p>The use of genuine Relational Keys, etc will maintain high performance, regardless of the population of the tables. </p></li> <li><p>Conversely, an RFS will perform badly, they simply cannot perform. "Scale" when used in the context of an RFS, is a fraudulent term: it hides the cause and seeks to address everything but the cause. Most important, such systems have none of the Relational Integrity; the Relational Power; or the Relational Speed, of a Relational system.</p></li> </ul></li> </ol> <h2>Implementation</h2> <h3>Relational Data Model • Account Balance</h3> <p><img src="https://www.softwaregems.com.au/Documents/Student%20Resolutions/Anmol%20Gupta%20TA%20Account.png" alt="Acct" title="Relational data model/Account Balance, for Anmol Gupta"></p> <h3>Relational Data Model • Inventory</h3> <p><img src="https://www.softwaregems.com.au/Documents/Student%20Resolutions/Anmol%20Gupta%20TA%20Inventory.png" alt="Inv" title="Relational data model/Inventory, for Anmol Gupta"></p> <h3>Notation</h3> <ul> <li><p>All my data models are rendered in <strong><a href="https://www.idef.com/idef1x-data-modeling-method/" rel="noreferrer">IDEF1X</a></strong>, the Standard for modelling Relational databases since 1993.</p></li> <li><p>My <strong><a href="https://www.softwaregems.com.au/Documents/Documentary%20Examples/IDEF1X%20Introduction.pdf" rel="noreferrer">IDEF1X Introduction</a></strong> is essential reading for those who are new to the <em>Relational Model</em>, or its modelling method. Note that IDEF1X models are rich in detail and precision, showing all required details, whereas home-grown models have far less than that. Which means, the notation has to be understood.</p></li> </ul> <h3>Content</h3> <ol> <li><p>For each Account, there will be a <code>ClosingBalance</code>, in a <code>AccountStatement</code> table (one row per <code>AccountNo</code> per month), along with Statement Date (usually the first day of the month) and other Statement details. </p> <ul> <li><p>This is not a duplicate because it is demanded for Audit and sanity purposes. </p> <p>For Inventory, it is a <code>QtyOnHand</code> column, in the <code>PartAudit</code> table (one row per <code>PartCode</code> per month)</p></li> <li><p>It has an additional value, in that it constrains the scope of the Transaction rows required to be queried <strong>to</strong> the current month</p> <ul> <li><p>Again, if your table is Relational, the Primary Key for <code>AccountTransaction</code> will be (<code>AccountNo</code>, Transaction <code>DateTime</code>) which will retrieve the Transactions at millisecond speeds.</p></li> <li><p>Whereas for a Record Filing System, the "primary key" will be <code>TransactionID</code>, and you will be retrieving the current month by Transaction Date, which may or may not be indexed correctly, and the rows required will be spread across the file. In any case at far less than ClusteredIndex speeds, and due to the spread, it will incur a tablescan.</p></li> </ul></li> </ul></li> <li><p>The <code>AccountTransaction</code> table remains simple (the real world notion of a bank account Transaction is simple). It has a single positive <code>Amount</code> column.</p></li> <li><p>For each <code>Account</code>, the <code>CurrentBalance</code> is:</p> <ul> <li><p>the <code>AccountStatement.ClosingBalance</code> of the previous month, dated the first of the next month for convenience</p> <p>(for inventory, the <code>PartAudit.QtyOnHand</code>)</p></li> <li><p>plus the SUM of the <code>AccountTransaction.Amounts</code> in the current month, where the <code>TransactionType</code> indicates a deposit</p> <p>(for inventory, the <code>PartMovement.Quantity</code>) </p></li> <li><p>minus the SUM of the <code>AccountTransaction.Amounts</code> in the current month, where the `MovementType indicates a withdrawal.</p></li> </ul></li> <li><p>In this Method, the <code>AccountTransactions</code> in the current month, only, are in a state of flux, thus they <strong>must be derived</strong>. All previous months are published and closed, thus the Audit figure <strong>must be used</strong>.</p></li> <li><p>The older rows in the <code>AccountTransaction</code> table can be purged. Older than ten years for public money, five years otherwise, one year for hobby club systems.</p></li> <li><p>Of course, it is essential that any code relating to accounting systems uses genuine OLTP Standards and genuine SQL ACID Transactions.</p></li> <li><p>This design incorporates all scope-level performance considerations (if this is not obvious, please ask for expansion). Scaling inside the database is a non-issue, any scaling issues that remain are honestly outside database.</p></li> </ol> <hr> <h1>Corrective Advice</h1> <p>These items need to be stated only because incorrect advice has been provided in many SO Answers (and up-voted by the masses, democratically, of course), and the internet is chock-full of incorrect advice (amateurs love to publish their subjective "truths"):</p> <ol> <li><p>Evidently, some people do not understand that I have given a Method in technical terms, to operate against a clear data model. As such, it is not pseudo-code for a specific application in a specific country. The Method is for capable developers, it is not detailed enough for those who need to be lead by the hand.</p> <ul> <li><p>They also do not understand that the cut-off period of a month is an <strong>example</strong>: if your cut-off for Tax Office purposes is quarterly, then by all means, use a quarterly cut-off; if the only legal requirement you have is annual, use annual. </p></li> <li><p>Even if your cut-off is quarterly for external or compliance purposes, the company may well choose a monthly cut-off, for internal Audit and sanity purposes (ie. to keep the length of the period of the state of flux to a minimum).</p> <p>Eg. in Australia, the Tax Office cut-off for businesses is quarterly, but larger companies cut-off their inventory control monthly (this saves having to chase errors over a long period). </p> <p>Eg. banks have legal compliance requirements monthly, therefore they perform an internal Audit on the figures, and close the books, monthly.</p></li> <li><p>In primitive countries and rogue states, banks keep their state-of-flux period at the maximum, for obvious nefarious purposes. Some of them only make their compliance reports annually. That is one reason why the banks in Australia do not fail.</p></li> </ul></li> <li><p>In the <code>AccountTransaction</code> table, do not use negative/positive in the Amount column. Money always has a positive value, there is no such thing as negative twenty dollars (or that <em>you owe me minus fifty dollars</em>), and then working out that the double negatives mean something else. </p></li> <li><p>The movement direction, or what you are going to do with the funds, is a separate and discrete fact (to the <code>AccountTransaction.Amount</code>). Which requires a separate column (two facts in one datum breaks Normalisation rules, with the consequence that it introduces complexity into the code). </p> <ul> <li><p>Implement a <code>TransactionType</code> reference table, the Primary Key of which is (<code>D, W</code> ) for Deposit/Withdrawal as your starting point. As the system grows, simply add ( <code>A, a, F, w</code> ) for Adjustment Credit; Adjustment Debit; Bank Fee; ATM_Withdrawal; etc. </p></li> <li><p>No code changes required.</p></li> </ul></li> <li><p>In some primitive countries, litigation requirements state that in any report that lists Transactions, a running total must be shown on every line. (Note, this is not an Audit requirement because those are superior [(refer Method above) to the court requirement; Auditors are somewhat less stupid than lawyers; etc.) </p> <p>Obviously, I would not argue with a court requirement. The problem is that primitive coders translate that into: <em>oh, oh, we must implement a</em> <code>AccountTransaction.CurrentBalance</code> <em>column</em>. They fail to understand that:</p> <ul> <li><p>the requirement to print a column on a report is not a dictate to store a value in the database</p></li> <li><p>a running total of any kind is a derived value, and it is easily coded (post a question if it isn't easy for you). Just implement the required code in the report.</p></li> <li><p>implementing the running total eg. <code>AccountTransaction.CurrentBalance</code> as a column causes horrendous problems:</p> <ul> <li><p>introduces a duplicated column, because it is derivable. Breaks Normalisation. Introduces an Update Anomaly.</p></li> <li><p>the Update Anomaly: whenever a Transaction is inserted historically, or a <code>AccountTransaction.Amount</code> is changed, all the <code>AccountTransaction.CurrentBalances</code> <strong>from that date to the present</strong> have to be re-computed and updated.</p></li> </ul></li> <li><p>in the above case, the report that was filed for court use, is now obsolete (every report of online data is obsolete the moment it is printed). Ie. print; review; change the Transaction; re-print; re-review, until you are happy. It is meaningless in any case.</p></li> <li><p>which is why, in less-primitive countries, the courts do not accept any old printed paper, they accept only published figures, eg. Bank Statements, which are already subject to Audit requirements (refer the Method above), and which cannot be recalled or changed and re-printed.</p></li> </ul></li> </ol> <hr> <h1>Comments</h1> <blockquote> <p>Alex:<br> yes code would be nice to look at, thank you. Even maybe a sample "bucket shop" so people could see the starting schema once and forever, would make world much better. </p> </blockquote> <p>For the data model above.</p> <h3>Code • Report Current Balance</h3> <pre class="lang-sql prettyprint-override"><code>SELECT AccountNo, ClosingDate = DATEADD( DD, -1 Date ), -- show last day of previous ClosingBalance, CurrentBalance = ClosingBalance + ( SELECT SUM( Amount ) FROM AccountTransaction WHERE AccountNo = @AccountNo AND TransactionTypeCode IN ( "A", "D" ) AND DateTime &gt;= CONVERT( CHAR(6), GETDATE(), 2 ) + "01" ) - ( SELECT SUM( Amount ) FROM AccountTransaction WHERE AccountNo = @AccountNo AND TransactionTypeCode NOT IN ( "A", "D" ) AND DateTime &gt;= CONVERT( CHAR(6), GETDATE(), 2 ) + "01" ) FROM AccountStatement WHERE AccountNo = @AccountNo AND Date = CONVERT( CHAR(6), GETDATE(), 2 ) + "01" </code></pre> <blockquote> <p>By denormalising that transactions log I trade normal form for more convenient queries and less changes in views/materialised views when I add more tx types</p> </blockquote> <p>God help me.</p> <ol> <li><p>When you go against Standards, you place yourself in a third-world position, where things that are not supposed to break, that never break in first-world countries, break. </p> <p>It is probably not a good idea to seek the right answer from an authority, and then argue against it, or argue for your sub-standard method.</p></li> <li><p>Denormalising (here) causes an Update Anomaly, the duplicated column, that can be derived from TransactionTypeCode. You want ease of coding, but you are willing to code it in two places, rather than one. That is exactly the kind of code that is prone to errors. </p> <p>A database that is fully Normalised according to Dr E F Codd's <em>Relational Model</em> provides for the easiest, the most logical, straight-forward code. (In my work, I contractually guarantee every report can be serviced by a single <code>SELECT</code>.)</p></li> <li><p><code>ENUM</code> is not SQL. (The freeware NONsql suites have no SQL compliance, but they do have extras which are not required in SQL.) If ever your app graduates to a commercial SQL platform, you will have to re-write all those <code>ENUMs</code> as ordinary LookUp tables. With a <code>CHAR(1)</code> or a <code>INT</code> as the PK. Then you will appreciate that it is actually a table with a PK.</p></li> <li><p>An error has a value of zero (it also has negative consequences). A truth has a value of one. I would not trade a one for a zero. Therefore it is not a trade-off. It is just your development decision.</p></li> </ol>
31,976,236
What's the difference between EnableEurekaClient and EnableDiscoveryClient?
<p>In some applications, I saw people are using EnableEurekaClient. And some other example applications are using EnableDiscoveryClient.</p> <p>Is there any difference between these two?</p>
31,993,406
5
0
null
2015-08-12 22:08:13.783 UTC
26
2022-01-05 14:52:39.45 UTC
2017-04-19 21:18:33.723 UTC
null
3,423,236
null
953,991
null
1
134
spring-cloud|netflix-eureka
58,707
<p>There are multiple implementations of "Discovery Service" (eureka, <a href="https://github.com/spring-cloud/spring-cloud-consul">consul</a>, <a href="https://github.com/spring-cloud/spring-cloud-zookeeper">zookeeper</a>). <code>@EnableDiscoveryClient</code> lives in <a href="https://github.com/spring-cloud/spring-cloud-commons">spring-cloud-commons</a> and picks the implementation on the classpath. <code>@EnableEurekaClient</code> lives in <a href="https://github.com/spring-cloud/spring-cloud-netflix/">spring-cloud-netflix</a> and only works for eureka. If eureka is on your classpath, they are effectively the same.</p>
56,916,798
React/RCTBridgeDelegate.h' file not found
<p>I have created a new project called auth using react-native init auth at terminal.When i tried to run the project using react-native run-ios. The build failed and gave a error 'React/RCTBridgeDelegate.h' file not found.</p> <p>Tried to update the react native version</p> <p>react-native run-ios at terminal in mac</p> <p>I expect the build to be successful and see the ios simulator The actual result which i got is build failed and hence cant see the simulator</p>
56,919,645
11
0
null
2019-07-06 18:49:13.257 UTC
5
2022-09-20 23:02:31.667 UTC
null
null
null
null
8,046,243
null
1
32
react-native|build|project|new-operator
67,441
<p>The issue is related to <code>cocoapods</code> dependency manager. Do the following to fix this:</p> <ol> <li>Open the terminal and go to your project <code>ios</code> directory</li> <li>Type in <code>pod init</code> (If it doesn't exist) and then <code>pod install</code></li> <li>Open the workspace project and delete the build from ios folder</li> <li>Run <code>react-native run-ios</code> from terminal.</li> </ol> <p>It should work now.</p>
50,684,231
What is an exclamation point in GraphQL?
<p>In a schema file that I have I noticed there are exclamation marks after some types, like</p> <pre><code># Information on an account relationship type AccountEdge { cursor: String! node: Account! } </code></pre> <p>What do these mean? I can't find anything about it in the documentation or through googling </p>
50,684,271
3
0
null
2018-06-04 15:39:46.617 UTC
11
2022-09-15 23:22:33.28 UTC
2020-04-24 07:44:46.323 UTC
null
1,480,391
null
3,117,409
null
1
119
graphql
36,643
<p>That means that the field is non-nullable.</p> <p>See more info in <a href="https://graphql.org/learn/schema/#:%7E:text=means%20that%20the%20field%20is,those%20with%20an%20exclamation%20mark" rel="noreferrer">Graphql - Schemas and Types</a></p>
51,079,849
Kubernetes - wait for other pod to be ready
<p>I have two applications - <strong>app1</strong> and <strong>app2</strong>, where <strong>app1</strong> is a <code>config server</code> that holds configs for <strong>app2</strong>. I have defined <code>/readiness</code> endpoint in <strong>app1</strong> and need to wait till it returns <code>OK</code> status to start up pods of <strong>app2</strong>. </p> <p>It's crucial that deployment of <strong>app2</strong> wait till <code>kubernetes</code> receives <code>Http Status OK</code> from <strong>/readiness</strong> endpoint in <strong>app1</strong> as it's a configuration server and holds crucial configs for app2.</p> <p>Is it possible to do this kind of deployment dependency?</p>
51,080,978
6
0
null
2018-06-28 09:53:33.507 UTC
10
2022-05-23 09:02:35.463 UTC
2018-06-28 10:05:49.227 UTC
null
7,227,475
null
7,227,475
null
1
46
kubernetes
55,897
<p>Yes, it's possible using <a href="https://kubernetes.io/docs/concepts/workloads/pods/init-containers/#what-can-init-containers-be-used-for" rel="noreferrer">Init Containers</a> (also, see this <a href="https://blog.openshift.com/kubernetes-pods-life/" rel="noreferrer">blog post</a> for some background re timing) but a better, more Kubernetes-native pattern is to use retries and timeouts rather than hard-coding dependencies in this way.</p>
47,809,437
How to access current HttpContext in ASP.NET Core 2 Custom Policy-Based Authorization with AuthorizationHandlerContext
<p>How can I access current HttpContext to check for route and parameters inside AuthorizationHandlerContext of Custom Policy-Based Authorization inside ASP.NET Core 2?</p> <p>Ref example: <a href="http://jakeydocs.readthedocs.io/en/latest/security/authorization/policies.html" rel="noreferrer">Custom Policy-Based Authorization</a></p>
47,809,981
5
0
null
2017-12-14 09:00:59.563 UTC
7
2022-07-28 04:20:06.26 UTC
2018-09-19 23:28:23.39 UTC
null
41,956
null
884,649
null
1
33
c#|asp.net-core|.net-core|asp.net-core-2.0
18,971
<p>You should inject an instance of an <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.ihttpcontextaccessor?view=aspnetcore-2.0" rel="noreferrer">IHttpContextAccessor</a> into your <code>AuthorizationHandler</code>.</p> <p>In the context of your <a href="http://jakeydocs.readthedocs.io/en/latest/security/authorization/policies.html" rel="noreferrer">example</a>, this may look like the following:</p> <pre class="lang-cs prettyprint-override"><code>public class BadgeEntryHandler : AuthorizationHandler&lt;EnterBuildingRequirement&gt; { IHttpContextAccessor _httpContextAccessor = null; public BadgeEntryHandler(IHttpContextAccessor httpContextAccessor) { _httpContextAccessor = httpContextAccessor; } protected override Task HandleRequirementAsync( AuthorizationContext context, EnterBuildingRequirement requirement) { HttpContext httpContext = _httpContextAccessor.HttpContext; // Access context here if (context.User.HasClaim(c =&gt; c.Type == ClaimTypes.BadgeId &amp;&amp; c.Issuer == "http://microsoftsecurity")) { context.Succeed(requirement); return Task.FromResult(0); } } } </code></pre> <p>You may need to register this in your DI setup (if one of your dependencies has not already), as follows:</p> <pre class="lang-cs prettyprint-override"><code>services.AddHttpContextAccessor(); </code></pre>
38,908,243
Cannot read property 'forEach' of undefined
<pre><code>var funcs = [] [1, 2].forEach( (i) =&gt; funcs.push( () =&gt; i ) ) </code></pre> <p>Why does it produce the error below?</p> <pre><code>TypeError: Cannot read property 'forEach' of undefined at Object.&lt;anonymous&gt; </code></pre> <p>However, the error goes away if the semicolon <code>;</code> is added to the end of the first line.</p>
38,908,271
6
2
null
2016-08-12 00:53:22.607 UTC
4
2022-08-18 06:06:28.82 UTC
2016-08-12 01:14:23.55 UTC
null
363,663
null
363,663
null
1
37
javascript
174,425
<p>There is no semicolon at the end of the first line. So the two lines run together, and it is interpreted as setting the value of <code>funcs</code> to</p> <pre><code>[][1, 2].forEach( (i) =&gt; funcs.push( () =&gt; i ) ) </code></pre> <p>The expression <code>1, 2</code> becomes just <code>2</code> (<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comma_Operator" rel="noreferrer">comma operator</a>), so you're trying to access index 2 of an empty array:</p> <pre><code>[][2] // undefined </code></pre> <p>And <code>undefined</code> has no <code>forEach</code> method. To fix this, always make sure you put a semicolon at the end of your lines (or if you don't, make sure you know what you're doing).</p>
32,345,923
How to control ordering of stacked bar chart using identity on ggplot2
<p>Using this dummy <code>data.frame</code></p> <pre><code>ts &lt;- data.frame(x=1:3, y=c("blue", "white", "white"), z=c("one", "one", "two")) </code></pre> <p>I try and plot with category "blue" on top.</p> <pre><code>ggplot(ts, aes(z, x, fill=factor(y, levels=c("blue","white" )))) + geom_bar(stat = "identity") </code></pre> <p><a href="https://i.stack.imgur.com/CnWfE.png" rel="noreferrer"><img src="https://i.stack.imgur.com/CnWfE.png" alt="enter image description here"></a></p> <p>gives me "white" on top. and</p> <pre><code>ggplot(ts, aes(z, x, fill=factor(y, levels=c("white", "blue")))) + geom_bar(stat = "identity") </code></pre> <p><a href="https://i.stack.imgur.com/qtnym.png" rel="noreferrer"><img src="https://i.stack.imgur.com/qtnym.png" alt="enter image description here"></a></p> <p>reverses the colors, but still gives me "white" on top. How can I get "blue" on top?</p>
32,346,701
6
0
null
2015-09-02 06:22:20.45 UTC
19
2020-10-26 09:00:55.31 UTC
null
null
null
null
378,085
null
1
54
r|ggplot2
119,651
<p>I've struggled with the same issue before. It appears that ggplot stacks the bars based on their appearance in the dataframe. So the solution to your problem is to sort your data by the fill factor in the reverse order you want it to appear in the legend: bottom item on top of the dataframe, and top item on bottom:</p> <pre><code>ggplot(ts[order(ts$y, decreasing = T),], aes(z, x, fill=factor(y, levels=c(&quot;blue&quot;,&quot;white&quot; )))) + geom_bar(stat = &quot;identity&quot;) </code></pre> <p><a href="https://i.stack.imgur.com/zrpWT.png" rel="noreferrer"><img src="https://i.stack.imgur.com/zrpWT.png" alt="enter image description here" /></a></p> <h1>Edit: More illustration</h1> <p>Using sample data, I created three plots with different orderings of the dataframe, I thought that more fill-variables would make things a bit clearer.</p> <pre><code>set.seed(123) library(gridExtra) df &lt;- data.frame(x=rep(c(1,2),each=5), fill_var=rep(LETTERS[1:5], 2), y=1) #original order p1 &lt;- ggplot(df, aes(x=x,y=y,fill=fill_var))+ geom_bar(stat=&quot;identity&quot;) + labs(title=&quot;Original dataframe&quot;) #random order p2 &lt;- ggplot(df[sample(1:10),],aes(x=x,y=y,fill=fill_var))+ geom_bar(stat=&quot;identity&quot;) + labs(title=&quot;Random order&quot;) #legend checks out, sequence wird #reverse order p3 &lt;- ggplot(df[order(df$fill_var,decreasing=T),], aes(x=x,y=y,fill=fill_var))+ geom_bar(stat=&quot;identity&quot;) + labs(title=&quot;Reverse sort by fill&quot;) plots &lt;- list(p1,p2,p3) do.call(grid.arrange,plots) </code></pre> <p><a href="https://i.stack.imgur.com/gaFId.png" rel="noreferrer"><img src="https://i.stack.imgur.com/gaFId.png" alt="enter image description here" /></a></p>
32,256,834
Swift: guard let vs if let
<p>I have been reading about Optionals in Swift, and I have seen examples where <code>if let</code> is used to check if an Optional holds a value, and in case it does – do something with the unwrapped value.</p> <p>However, I have seen that in Swift 2.0 the keyword <code>guard let</code> is used mostly. I wonder whether <code>if let</code> has been removed from Swift 2.0 or if it still possible to be used.</p> <p>Should I change my programs that contain <code>if let</code> to <code>guard let</code>?</p>
32,256,911
9
0
null
2015-08-27 18:23:49.413 UTC
70
2022-09-20 01:42:54.633 UTC
2020-03-12 14:27:47.72 UTC
null
5,175,709
null
3,705,840
null
1
189
swift|swift2|option-type|conventions|control-flow
107,370
<p><code>if let</code> and <code>guard let</code> serve similar, but distinct purposes.</p> <p>The "else" case of <code>guard</code> must exit the current scope. Generally that means it must call <code>return</code> or abort the program. <code>guard</code> is used to provide early return without requiring nesting of the rest of the function.</p> <p><code>if let</code> nests its scope, and does not require anything special of it. It can <code>return</code> or not.</p> <p>In general, if the <code>if-let</code> block was going to be the rest of the function, or its <code>else</code> clause would have a <code>return</code> or abort in it, then you should be using <code>guard</code> instead. This often means (at least in my experience), when in doubt, <code>guard</code> is usually the better answer. But there are plenty of situations where <code>if let</code> still is appropriate.</p>
54,500,483
How can I display image encoded in base64 format in Angular 6?
<p>I struggle with a problem associated with Angular 6 and displaying image encoded in base64 format. Any ideas why code shown below doesn't display image?</p> <p>html:</p> <pre><code>&lt;tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows"&gt; &lt;img src="{{this.hello}}" /&gt; </code></pre> <p>ts:</p> <pre><code>this.hello = "data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..." </code></pre> <p>While code shown below works properly and displays picture?</p> <p>html:</p> <pre><code>&lt;tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows"&gt; &lt;!--&lt;img src="data:image/png;base64, /9j/4AAQSkZJRgABAQAAA..."/&gt; </code></pre> <p><code>this.hello</code> is assigned in the constructor just for test purpose. I create it in this way <code>this.hello = 'data:image/png;base64, ' + this.UploaderService.imageRecognitionRowsData[0].toString()</code> My main goal is to display <code>imageRecognitionRowsData</code> in this loop <code>&lt;tr *ngFor="let row of this.UploaderService.tableImageRecognition.dataRows"&gt;</code>. So for first iteration I would display image <code>imageRecognitionRowsData[0]</code> then during next iteration image <code>imageRecognitionRowsData[1]</code> etc. The length of <code>this.UploaderService.tableImageRecognition.dataRows</code> is always the same as <code>this.UploaderService.imageRecognitionRowsData</code> When I add <code>&lt;p&gt;{{this.hello}}&lt;/p&gt;</code> I get the same string in html. I have no idea what is wrong. I tried also with <code>this.hello2 = this.sanitizer.bypassSecurityTrustResourceUrl(this.hello);</code>, <code>this.hello2 = this.sanitizer.bypassSecurityTrustUrl(this.hello);</code>, <code>&lt;img [src]="this.hello" /&gt;</code> etc. but nothing works. Any ideas how to solve this?</p>
54,500,815
3
0
null
2019-02-03 06:20:58.247 UTC
2
2019-08-23 20:41:21.257 UTC
null
null
null
null
8,499,517
null
1
5
html|angular|typescript|base64|angular6
38,242
<p>You don't use "this" to refer the variables defined in the component "ts" file. Remove "this" may solve your problem.</p> <p>Please Review this stackbliz Fiddle. Look inside the app component to see the implementation.</p> <p><a href="https://stackblitz.com/edit/angular-g9n9np" rel="noreferrer">StackBlitz</a></p>
25,829,856
How to set a spinner into the middle of the screen with CSS?
<p>i need some CSS help, i have a spinner for the loading page, centered totally, it is centered vertically, but now how can i center that spinner for all possible screen widths?</p> <p>This is my markup:</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; ... &lt;body&gt; &lt;div class="loading"&gt; &lt;div class="loader"&gt;&lt;/div&gt; &lt;/div&gt; ... &lt;/body&gt; &lt;/html&gt; </code></pre> <p>and this is my stylesheet:</p> <pre><code>.loading { position: fixed; left: 0px; top: 0px; width: 100%; height: 100%; z-index: 9999999999; overflow: hidden; background: #fff; } .loader { font-size: 10px; border-top: .8em solid rgba(218, 219, 223, 1); border-right: .8em solid rgba(218, 219, 223, 1); border-bottom: .8em solid rgba(218, 219, 223, 1); border-left: .8em solid rgba(58, 166, 165, 1); -webkit-animation: load8 1.1s infinite linear; animation: load8 1.1s infinite linear; } .loader, .loader:after { border-radius: 50%; width: 8em; height: 8em; display: block; position: absolute; top: 50%; margin-top: -4.05em; } </code></pre>
25,829,868
1
0
null
2014-09-14 03:41:44.843 UTC
7
2017-01-25 18:11:15.03 UTC
null
null
null
user3697569
null
null
1
21
html|css
70,478
<p>Since the element has a fixed width of <code>8em</code>, you could add <code>left: 50%</code> and then displace half of the element's width using <code>margin-left: -4px</code>:</p> <p><a href="http://jsfiddle.net/kz2nm800/" rel="noreferrer"><strong>Updated Example</strong></a></p> <pre><code>.loader { left: 50%; margin-left: -4em; } </code></pre> <p>If the dimensions of the element aren't fixed and known in advance, <a href="https://stackoverflow.com/questions/19461521/how-to-center-an-element-horizontally-and-vertically/19461564#19461564">see my other answer for alternative options</a>.</p>
43,156,023
What is HTTP "Host" header?
<p>Given that the TCP connection is already established when the HTTP request is sent, the IP address and port are implicitly known -- a TCP connection is an IP + Port.</p> <p>So, why do we need the <code>Host</code> header? Is this only needed for the case where there are multiple hosts mapped to the IP address implied in the TCP connection?</p>
43,156,094
2
0
null
2017-04-01 11:04:57.783 UTC
41
2021-12-25 23:49:26.233 UTC
2020-11-09 13:36:49.017 UTC
null
814,702
null
1,616,677
null
1
199
http|http-headers
224,293
<p>The <a href="https://www.rfc-editor.org/rfc/rfc7230#section-5.4" rel="noreferrer"><code>Host</code></a> Header tells the webserver which <em>virtual host</em> to use (if set up). You can even have the same virtual host using several <em>aliases</em> (= domains and wildcard-domains). In this case, you still have the possibility to read that header manually in your web app if you want to provide different behavior based on different domains addressed. This is possible because in your webserver you can (and if I'm not mistaken you must) set up <em>one</em> vhost to be the default host. This default vhost is used whenever the <code>host</code> header does not match any of the configured virtual hosts.</p> <p>That means: You get it right, although saying &quot;multiple hosts&quot; may be somewhat misleading: The host (the addressed machine) is the same, what really gets resolved to the IP address are different <em>domain names</em> (including subdomains) that are also referred to as <em>hostnames</em> (but not hosts!). <br><br></p> <hr /> <p>Although not part of the question, a fun fact: This specification led to problems with SSL in the early days because the web server has to deliver the certificate that corresponds to the domain the client has addressed. However, in order to know what certificate to use, the webserver should have known the addressed hostname in advance. But because the client sends that information only over the encrypted channel (which means: after the certificate has already been sent), the server had to assume you browsed the default host. That meant one SSL-secured domain per IP address / port-combination.</p> <p>This has been overcome with <a href="https://en.wikipedia.org/wiki/Server_Name_Indication" rel="noreferrer">Server Name Indication</a>; however, that again breaks some privacy, as the server name is now transferred in plain text again, so every man-in-the-middle would see <em>which hostname</em> you are trying to connect to.</p> <p>Although the webserver would know the hostname from Server Name Indication, the <code>Host</code> header is not obsolete, because the Server Name Indication information is only used within the TLS handshake. With an unsecured connection, there is no Server Name Indication at all, so the <code>Host</code> header is still valid (and necessary).</p> <p>Another fun fact: Most webservers (if not all) reject your HTTP request if it does not contain exactly one <code>Host</code> header, even if it could be omitted because there is only the default vhost configured. That means the minimum required information in an http-(get-)request is the first line containing <code>METHOD</code> <code>RESOURCE</code> and <code>PROTOCOL VERSION</code> and at least the <code>Host</code> header, like this:</p> <pre><code>GET /someresource.html HTTP/1.1 Host: www.example.com </code></pre> <p>In the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Host" rel="noreferrer">MDN Documentation on the &quot;Host&quot; header</a> they actually phrase it like this:</p> <blockquote> <p>A Host header field must be sent in all HTTP/1.1 request messages. A 400 (Bad Request) status code will be sent to any HTTP/1.1 request message that lacks a Host header field or contains more than one.</p> </blockquote> <p>As mentioned by Darrel Miller, the complete specs can be found in <a href="https://www.rfc-editor.org/rfc/rfc7230#section-5.4" rel="noreferrer">RFC7230</a>.</p>
51,607,400
How to extract first 8 characters from a string in pandas
<p>I have column in a dataframe and i am trying to extract 8 digits from a string. How can I do it</p> <pre><code> Input Shipment ID 20180504-S-20000 20180514-S-20537 20180514-S-20541 20180514-S-20644 20180514-S-20644 20180516-S-20009 20180516-S-20009 20180516-S-20009 20180516-S-20009 </code></pre> <p><strong>Expected Output</strong></p> <pre><code>Order_Date 20180504 20180514 20180514 20180514 20180514 20180516 20180516 20180516 20180516 </code></pre> <p>I tried below code and it didnt work.</p> <pre><code>data['Order_Date'] = data['Shipment ID'][:8] </code></pre>
51,607,410
3
0
null
2018-07-31 07:09:13.243 UTC
2
2022-08-21 12:03:33.9 UTC
2021-10-17 06:42:50.907 UTC
null
3,163,618
null
9,161,067
null
1
28
python-3.x|pandas|substring
58,120
<p>You are close, need indexing with <code>str</code> which is apply for each value of <code>Serie</code>s:</p> <pre><code>data['Order_Date'] = data['Shipment ID'].str[:8] </code></pre> <p>For better performance if no <code>NaN</code>s values:</p> <pre><code>data['Order_Date'] = [x[:8] for x in data['Shipment ID']] </code></pre> <hr> <pre><code>print (data) Shipment ID Order_Date 0 20180504-S-20000 20180504 1 20180514-S-20537 20180514 2 20180514-S-20541 20180514 3 20180514-S-20644 20180514 4 20180514-S-20644 20180514 5 20180516-S-20009 20180516 6 20180516-S-20009 20180516 7 20180516-S-20009 20180516 8 20180516-S-20009 20180516 </code></pre> <p>If omit <code>str</code> code filter column by position, first N values like:</p> <pre><code>print (data['Shipment ID'][:2]) 0 20180504-S-20000 1 20180514-S-20537 Name: Shipment ID, dtype: object </code></pre>
48,915,003
Get the bounding box coordinates in the TensorFlow object detection API tutorial
<p>I am new to both Python and Tensorflow. I am trying to run the object detection tutorial file from the <a href="https://github.com/tensorflow/models/tree/master/research/object_detection" rel="nofollow noreferrer">Tensorflow Object Detection API</a>, but I cannot find where I can get the coordinates of the bounding boxes when objects are detected.</p> <p>Relevant code:</p> <pre><code> # The following processing is only for single image detection_boxes = tf.squeeze(tensor_dict['detection_boxes'], [0]) detection_masks = tf.squeeze(tensor_dict['detection_masks'], [0]) </code></pre> <p>The place where I assume bounding boxes are drawn is like this:</p> <pre><code> # Visualization of the results of detection. vis_util.visualize_boxes_and_labels_on_image_array( image_np, output_dict['detection_boxes'], output_dict['detection_classes'], output_dict['detection_scores'], category_index, instance_masks=output_dict.get('detection_masks'), use_normalized_coordinates=True, line_thickness=8) plt.figure(figsize=IMAGE_SIZE) plt.imshow(image_np) </code></pre> <p>I tried printing <code>output_dict['detection_boxes']</code> but I am not sure what the numbers mean. There are a lot.</p> <pre><code>array([[ 0.56213236, 0.2780568 , 0.91445708, 0.69120586], [ 0.56261235, 0.86368728, 0.59286624, 0.8893863 ], [ 0.57073039, 0.87096912, 0.61292225, 0.90354401], [ 0.51422435, 0.78449738, 0.53994244, 0.79437423], ...... [ 0.32784131, 0.5461576 , 0.36972913, 0.56903434], [ 0.03005961, 0.02714229, 0.47211722, 0.44683522], [ 0.43143299, 0.09211366, 0.58121657, 0.3509962 ]], dtype=float32) </code></pre> <p>I found answers for similar questions, but I don't have a variable called boxes as they do. How can I get the coordinates?</p>
48,915,493
3
0
null
2018-02-21 20:36:23.787 UTC
12
2021-11-30 09:12:25.333 UTC
2021-11-30 09:12:25.333 UTC
null
2,423,278
null
9,393,009
null
1
29
python|tensorflow|bounding-box|object-detection-api
47,547
<blockquote> <p>I tried printing output_dict['detection_boxes'] but I am not sure what the numbers mean</p> </blockquote> <p>You can check out the code for yourself. <code>visualize_boxes_and_labels_on_image_array</code> is defined <a href="https://github.com/tensorflow/models/blob/master/research/object_detection/utils/visualization_utils.py" rel="noreferrer">here</a>.</p> <p>Note that you are passing <code>use_normalized_coordinates=True</code>. If you trace the function calls, you will see your numbers <code>[ 0.56213236, 0.2780568 , 0.91445708, 0.69120586]</code> etc. are the values <code>[ymin, xmin, ymax, xmax]</code> where the image coordinates: </p> <pre><code>(left, right, top, bottom) = (xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height) </code></pre> <p>are computed by the function:</p> <pre><code>def draw_bounding_box_on_image(image, ymin, xmin, ymax, xmax, color='red', thickness=4, display_str_list=(), use_normalized_coordinates=True): """Adds a bounding box to an image. Bounding box coordinates can be specified in either absolute (pixel) or normalized coordinates by setting the use_normalized_coordinates argument. Each string in display_str_list is displayed on a separate line above the bounding box in black text on a rectangle filled with the input 'color'. If the top of the bounding box extends to the edge of the image, the strings are displayed below the bounding box. Args: image: a PIL.Image object. ymin: ymin of bounding box. xmin: xmin of bounding box. ymax: ymax of bounding box. xmax: xmax of bounding box. color: color to draw bounding box. Default is red. thickness: line thickness. Default value is 4. display_str_list: list of strings to display in box (each to be shown on its own line). use_normalized_coordinates: If True (default), treat coordinates ymin, xmin, ymax, xmax as relative to the image. Otherwise treat coordinates as absolute. """ draw = ImageDraw.Draw(image) im_width, im_height = image.size if use_normalized_coordinates: (left, right, top, bottom) = (xmin * im_width, xmax * im_width, ymin * im_height, ymax * im_height) </code></pre>
38,419,325
Catching FULL exception message
<p>Consider:</p> <pre><code>Invoke-WebRequest $sumoApiURL -Headers @{"Content-Type"= "application/json"} -Credential $cred -WebSession $webRequestSession -Method post -Body $sumojson -ErrorAction Stop </code></pre> <p>This throws the following exception:</p> <p><a href="https://i.stack.imgur.com/Lg7aA.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Lg7aA.png" alt="Enter image description here"></a></p> <p>How can I catch it entirely or at least filter out the "A resource with the same name already exist."?</p> <p>Using <code>$_.Exception.GetType().FullName</code> yields</p> <blockquote> <p>System.Net.WebException</p> </blockquote> <p>and <code>$_.Exception.Message</code> gives</p> <blockquote> <p>The remote server returned an error: (400) Bad Request.</p> </blockquote>
38,421,525
6
0
null
2016-07-17 08:31:26.703 UTC
33
2021-03-25 18:03:09.5 UTC
2018-11-06 20:02:59.29 UTC
null
63,550
null
1,571,299
null
1
87
powershell|exception|exception-handling
164,838
<p>Errors and exceptions in PowerShell are structured objects. The error message you see printed on the console is actually a formatted message with information from several elements of the error/exception object. You can (re-)construct it yourself like this:</p> <pre><code>$formatstring = "{0} : {1}`n{2}`n" + " + CategoryInfo : {3}`n" + " + FullyQualifiedErrorId : {4}`n" $fields = $_.InvocationInfo.MyCommand.Name, $_.ErrorDetails.Message, $_.InvocationInfo.PositionMessage, $_.CategoryInfo.ToString(), $_.FullyQualifiedErrorId $formatstring -f $fields </code></pre> <p>If you just want the error message displayed in your <code>catch</code> block you can simply echo the current object variable (which holds the error at that point):</p> <pre><code>try { ... } catch { $_ } </code></pre> <p>If you need colored output use <code>Write-Host</code> with a formatted string as described above:</p> <pre><code>try { ... } catch { ... Write-Host -Foreground Red -Background Black ($formatstring -f $fields) } </code></pre> <p>With that said, usually you don't want to just display the error message as-is in an exception handler (otherwise the <code>-ErrorAction Stop</code> would be pointless). The structured error/exception objects provide you with additional information that you can use for better error control. For instance you have <code>$_.Exception.HResult</code> with the actual error number. <code>$_.ScriptStackTrace</code> and <code>$_.Exception.StackTrace</code>, so you can display stacktraces when debugging. <code>$_.Exception.InnerException</code> gives you access to nested exceptions that often contain additional information about the error (top level PowerShell errors can be somewhat generic). You can unroll these nested exceptions with something like this:</p> <pre><code>$e = $_.Exception $msg = $e.Message while ($e.InnerException) { $e = $e.InnerException $msg += "`n" + $e.Message } $msg </code></pre> <p>In your case the information you want to extract seems to be in <code>$_.ErrorDetails.Message</code>. It's not quite clear to me if you have an object or a JSON string there, but you should be able to get information about the types and values of the members of <code>$_.ErrorDetails</code> by running</p> <pre><code>$_.ErrorDetails | Get-Member $_.ErrorDetails | Format-List * </code></pre> <p>If <code>$_.ErrorDetails.Message</code> is an object you should be able to obtain the message string like this:</p> <pre><code>$_.ErrorDetails.Message.message </code></pre> <p>otherwise you need to convert the JSON string to an object first:</p> <pre><code>$_.ErrorDetails.Message | ConvertFrom-Json | Select-Object -Expand message </code></pre> <p>Depending what kind of error you're handling, exceptions of particular types might also include more specific information about the problem at hand. In your case for instance you have a <code>WebException</code> which in addition to the error message (<code>$_.Exception.Message</code>) contains the actual response from the server:</p> <pre>PS C:\> <b>$e.Exception | Get-Member</b> TypeName: System.Net.WebException Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj), bool _Exception.E... GetBaseException Method System.Exception GetBaseException(), System.Excep... GetHashCode Method int GetHashCode(), int _Exception.GetHashCode() GetObjectData Method void GetObjectData(System.Runtime.Serialization.S... GetType Method type GetType(), type _Exception.GetType() ToString Method string ToString(), string _Exception.ToString() Data Property System.Collections.IDictionary Data {get;} HelpLink Property string HelpLink {get;set;} HResult Property int HResult {get;} InnerException Property System.Exception InnerException {get;} Message Property string Message {get;} <b><i>Response Property System.Net.WebResponse Response {get;}</i></b> Source Property string Source {get;set;} StackTrace Property string StackTrace {get;} Status Property System.Net.WebExceptionStatus Status {get;} TargetSite Property System.Reflection.MethodBase TargetSite {get;}</pre> <p>which provides you with information like this:</p> <pre>PS C:\> <b>$e.Exception.Response</b> IsMutuallyAuthenticated : False Cookies : {} Headers : {Keep-Alive, Connection, Content-Length, Content-T...} SupportsHeaders : True ContentLength : 198 ContentEncoding : ContentType : text/html; charset=iso-8859-1 CharacterSet : iso-8859-1 Server : Apache/2.4.10 LastModified : 17.07.2016 14:39:29 StatusCode : NotFound StatusDescription : Not Found ProtocolVersion : 1.1 ResponseUri : http://www.example.com/ Method : POST IsFromCache : False</pre> <p>Since not all exceptions have the exact same set of properties you may want to use specific handlers for particular exceptions:</p> <pre><code>try { ... } catch [System.ArgumentException] { # handle argument exceptions } catch [System.Net.WebException] { # handle web exceptions } catch { # handle all other exceptions } </code></pre> <p>If you have operations that need to be done regardless of whether an error occured or not (cleanup tasks like closing a socket or a database connection) you can put them in a <code>finally</code> block after the exception handling:</p> <pre><code>try { ... } catch { ... } finally { # cleanup operations go here } </code></pre>
1,316,251
WPF Listbox auto scroll while dragging
<p>I have a WPF app that has a <code>ListBox</code>. The drag mechanism is already implemented, but when the list is too long and I want to move an item to a position not visible, I can't.</p> <p>For example, the screen shows 10 items. And I have 20 items. If I want to drag the last item to the first position I must drag to the top and drop. Scroll up and drag again.</p> <p>How can I make the <code>ListBox</code> auto scroll?</p>
1,316,377
2
0
null
2009-08-22 15:47:38.193 UTC
6
2022-05-17 15:30:41.067 UTC
2022-05-17 15:30:41.067 UTC
null
45,382
null
1,013
null
1
28
c#|.net|wpf|scroll|listbox
13,203
<p>Got it. Used the event <code>DragOver</code> of the <code>ListBox</code>, used the function found <a href="https://stackoverflow.com/questions/665719/wpf-animate-listbox-scrollviewer-horizontaloffset">here</a> to get the <code>scrollviewer</code> of the listbox and after that its just a bit of juggling with the Position.</p> <pre><code>private void ItemsList_DragOver(object sender, System.Windows.DragEventArgs e) { ListBox li = sender as ListBox; ScrollViewer sv = FindVisualChild&lt;ScrollViewer&gt;(ItemsList); double tolerance = 10; double verticalPos = e.GetPosition(li).Y; double offset = 3; if (verticalPos &lt; tolerance) // Top of visible list? { sv.ScrollToVerticalOffset(sv.VerticalOffset - offset); //Scroll up. } else if (verticalPos &gt; li.ActualHeight - tolerance) //Bottom of visible list? { sv.ScrollToVerticalOffset(sv.VerticalOffset + offset); //Scroll down. } } public static childItem FindVisualChild&lt;childItem&gt;(DependencyObject obj) where childItem : DependencyObject { // Search immediate children first (breadth-first) for (int i = 0; i &lt; VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null &amp;&amp; child is childItem) return (childItem)child; else { childItem childOfChild = FindVisualChild&lt;childItem&gt;(child); if (childOfChild != null) return childOfChild; } } return null; } </code></pre>
518,192
How do you explicitly animate a CALayer's backgroundColor?
<p>I'm trying to construct a CABasicAnimation to animate the backgroundColor property of a Core Animation CALayer, but I can't figure out how to properly wrap a CGColorRef value to pass to the animation. For example: </p> <pre><code>CGColorSpaceRef rgbColorspace = CGColorSpaceCreateDeviceRGB(); CGFloat values[4] = {1.0, 0.0, 0.0, 1.0}; CGColorRef red = CGColorCreate(rgbColorspace, values); CGColorSpaceRelease(rgbColorspace); CABasicAnimation *selectionAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"]; [selectionAnimation setDuration:0.5f]; [selectionAnimation setToValue:[NSValue valueWithPointer:red]]; [layer addAnimation:selectionAnimation forKey:@"selectionAnimation"]; </code></pre> <p>seems to do nothing to the backgroundColor property, I assume because handing it off as a pointer wrapped in an NSValue is not the way to pass it along. </p> <p>backgroundColor is an animatable property of CALayer, so my question is: how do you set the From or To values for this particular property (preferably in a Mac / iPhone platform-independent way)?</p>
518,719
2
0
null
2009-02-05 22:08:22.003 UTC
26
2018-06-21 14:04:30.237 UTC
2018-06-21 14:04:30.237 UTC
null
19,679
Brad Larson
19,679
null
1
34
iphone|cocoa|macos|core-animation
25,568
<p>You don't need to wrap <code>CGColorRef</code>s when setting the <code>toValue</code> or <code>fromValue</code> properties of a <code>CABasicAnimation</code>. Simply use the <code>CGColorRef</code>. To avoid the compiler warning, you can cast the <code>CGColorRef</code> to an <code>id</code>.</p> <p>In my sample app, the following code animated the background to red.</p> <pre><code>CABasicAnimation* selectionAnimation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"]; selectionAnimation.toValue = (id)[UIColor redColor].CGColor; [self.view.layer addAnimation:selectionAnimation forKey:@"selectionAnimation"]; </code></pre> <p>However, when the animation is over, the background returns to the original color. This is because the <code>CABasicAnimation</code> only effects the presentation layer of the target layer while the animation is running. After the animation finishes, the value set in the model layer returns. So you are going to have to set the layers <code>backgroundColor</code> property to red as well. Perhaps turn off the implicit animations using a <code>CATransaction</code>.</p> <p>You could save yourself this trouble by using an implicit animation in the first place.</p>
2,495,290
Writing Strings to files in python
<p>I'm getting the following error when trying to write a string to a file in pythion:</p> <pre><code>Traceback (most recent call last): File "export_off.py", line 264, in execute save_off(self.properties.path, context) File "export_off.py", line 244, in save_off primary.write(file) File "export_off.py", line 181, in write variable.write(file) File "export_off.py", line 118, in write file.write(self.value) TypeError: must be bytes or buffer, not str </code></pre> <p>I basically have a string class, which contains a string:</p> <pre><code>class _off_str(object): __slots__ = 'value' def __init__(self, val=""): self.value=val def get_size(self): return SZ_SHORT def write(self,file): file.write(self.value) def __str__(self): return str(self.value) </code></pre> <p>Furthermore, I'm calling that class like this (where variable is an array of _off_str objects:</p> <pre><code>def write(self, file): for variable in self.variables: variable.write(file) </code></pre> <p>I have no idea what is going on. I've seen other python programs writing strings to files, so why can't this one?</p> <p>Thank you very much for your help.</p> <p>Edit: It looks like I needed to state how I opened the file, here is how:</p> <pre><code>file = open(filename, 'wb') primary.write(file) file.close() </code></pre>
2,495,347
5
5
null
2010-03-22 19:58:51.677 UTC
2
2010-03-22 21:51:24.07 UTC
2010-03-22 21:51:24.07 UTC
null
192,839
null
288,439
null
1
12
python|string|file|io|python-3.x
40,582
<p>I suspect you are using Python 3 and have opened the file in binary mode, which will only accept bytes or buffers to be written into it.</p> <p>Any chance we could see the code that opens up the file for writing?</p> <hr> <p><strong>edit:</strong> Looks like that is indeed the culprit.</p>
2,796,219
Set width of Button in Android
<p>How can I set a fixed width for an Android button? Everytime I try to set a fixed width it fills the current parent (the RelativeView). Here is my XML:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;RelativeLayout android:id="@+id/relativelayout" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;EditText android:layout_height="wrap_content" android:editable="false" android:layout_width="fill_parent" android:id="@+id/output"&gt;&lt;/EditText&gt; &lt;Button android:layout_height="wrap_content" android:id="@+id/Button01" android:layout_below="@id/output" android:text="7" android:layout_width="wrap_content"&gt;&lt;/Button&gt; &lt;Button android:layout_below="@id/output" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button02" android:layout_toRightOf="@+id/Button01" android:text="8"&gt;&lt;/Button&gt; &lt;Button android:layout_below="@id/output" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/Button03" android:layout_toRightOf="@+id/Button02" android:text="9"&gt;&lt;/Button&gt; &lt;/RelativeLayout&gt; </code></pre> <p>How would I give it a FIXED width?<br> <b>UPDATE</b><br> Say I have several buttons that I want the same size as each other and 1/3 of the entire view (Portrait), then I want a button with double the width. Then a button with double the height. How could I accomplish this other that manually sizing them?</p>
2,796,363
5
0
null
2010-05-09 00:54:16.5 UTC
3
2016-04-30 05:25:08.367 UTC
2010-05-09 01:03:49.163 UTC
null
200,477
null
200,477
null
1
18
java|xml|android|size
95,651
<p>To accomplish what you want, you can use a LinearLayout with a weightsum. For example, you can put a WeightSum of 9. If you put the weight of three button inside to 1 each. They will take 1/3 of the place, and you can put 2 for another object. This object will be twice as big as the other.</p> <p><a href="http://developer.android.com/reference/android/widget/LinearLayout.html#setWeightSum(float)" rel="noreferrer">http://developer.android.com/reference/android/widget/LinearLayout.html#setWeightSum(float)</a></p> <p>Edit: I would like to add that for this to work correctly, you have to set the width or height to 0px (depending on if it's an horizontal or a vertical layout).</p>
3,179,106
Python: Select subset from list based on index set
<p>I have several lists having all the same number of entries (each specifying an object property):</p> <pre><code>property_a = [545., 656., 5.4, 33.] property_b = [ 1.2, 1.3, 2.3, 0.3] ... </code></pre> <p>and list with flags of the same length</p> <pre><code>good_objects = [True, False, False, True] </code></pre> <p>(which could easily be substituted with an equivalent index list:</p> <pre><code>good_indices = [0, 3] </code></pre> <p>What is the easiest way to generate new lists <code>property_asel</code>, <code>property_bsel</code>, ... which contain only the values indicated either by the <code>True</code> entries or the indices?</p> <pre><code>property_asel = [545., 33.] property_bsel = [ 1.2, 0.3] </code></pre>
3,179,119
5
0
null
2010-07-05 11:30:33.963 UTC
28
2022-09-06 10:12:39.683 UTC
2010-07-05 13:30:22.437 UTC
null
12,855
null
143,931
null
1
129
python|list
250,602
<p>You could just use <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="noreferrer">list comprehension</a>:</p> <pre><code>property_asel = [val for is_good, val in zip(good_objects, property_a) if is_good] </code></pre> <p>or</p> <pre><code>property_asel = [property_a[i] for i in good_indices] </code></pre> <p>The latter one is faster because there are fewer <code>good_indices</code> than the length of <code>property_a</code>, assuming <code>good_indices</code> are precomputed instead of generated on-the-fly.</p> <hr> <p><strong>Edit</strong>: The first option is equivalent to <code>itertools.compress</code> available since Python 2.7/3.1. See <a href="https://stackoverflow.com/a/3179138/224671">@Gary Kerr</a>'s answer.</p> <pre><code>property_asel = list(itertools.compress(property_a, good_objects)) </code></pre>
2,395,438
Convert System.Drawing.Color to RGB and Hex Value
<p>Using C# I was trying to develop the following two. The way I am doing it may have some problem and need your kind advice. In addition, I dont know whether there is any existing method to do the same.</p> <pre><code>private static String HexConverter(System.Drawing.Color c) { String rtn = String.Empty; try { rtn = "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"); } catch (Exception ex) { //doing nothing } return rtn; } private static String RGBConverter(System.Drawing.Color c) { String rtn = String.Empty; try { rtn = "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")"; } catch (Exception ex) { //doing nothing } return rtn; } </code></pre> <p>Thanks.</p>
2,395,708
6
1
null
2010-03-07 06:54:11.8 UTC
27
2022-04-14 08:21:31.573 UTC
null
null
null
null
218,565
null
1
151
c#|asp.net|rgb|system.drawing.color
194,636
<p>I'm failing to see the problem here. The code looks good to me.</p> <p>The only thing I can think of is that the try/catch blocks are redundant -- Color is a struct and R, G, and B are bytes, so c can't be null and <code>c.R.ToString()</code>, <code>c.G.ToString()</code>, and <code>c.B.ToString()</code> can't actually fail (the only way I can see them failing is with a <code>NullReferenceException</code>, and none of them can actually be null).</p> <p>You could clean the whole thing up using the following:</p> <pre><code>private static String HexConverter(System.Drawing.Color c) { return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2"); } private static String RGBConverter(System.Drawing.Color c) { return "RGB(" + c.R.ToString() + "," + c.G.ToString() + "," + c.B.ToString() + ")"; } </code></pre>