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
2,720,396
how to remove attribute of a etree Element?
<p>I've Element of etree having some attributes - how can we delete the attribute of perticular etree Element.</p>
2,720,418
3
0
null
2010-04-27 10:31:30.583 UTC
6
2017-08-31 11:28:11.187 UTC
2015-02-10 22:38:19.347 UTC
null
3,204,551
null
144,408
null
1
46
python|xml|lxml|elementtree
38,708
<p>The <a href="http://effbot.org/zone/element.htm#attributes" rel="noreferrer"><code>.attrib</code> member of the element object</a> contains the dict of attributes - you can use <code>.pop("key")</code> or <code>del</code> <a href="http://docs.python.org/library/stdtypes.html#mapping-types-dict" rel="noreferrer">like you would on any other dict</a> to remove a key-val pair.</p>
2,492,730
How do I introspect things in Ruby?
<p>For instance, in Python, I can do things like this if I want to get all attributes on an object:</p> <pre><code>&gt;&gt;&gt; import sys &gt;&gt;&gt; dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__package__', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache', '_current_frames', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'getcheckinterval', 'getdefaultencoding', 'getdlopenflags', 'getfilesystemencoding', 'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'hexversion', 'maxint', 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'py3kwarning', 'pydebug', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', 'version_info', 'warnoptions'] </code></pre> <p>Or if I want to view the documentation of something, I can use the help function:</p> <pre><code>&gt;&gt;&gt; help(str) </code></pre> <p>Is there any way to do similar things in Ruby?</p>
2,492,776
4
2
null
2010-03-22 13:57:29.713 UTC
10
2010-03-22 16:11:48.323 UTC
null
null
null
null
2,147
null
1
24
ruby|introspection|irb
10,802
<p>Sure, it's even simpler than in Python. Depending on what information you're looking for, try:</p> <pre><code>obj.methods </code></pre> <p>and if you want just the methods defined for obj (as opposed to getting methods on <code>Object</code> as well)</p> <pre><code>obj.methods - Object.methods </code></pre> <p>Also interesting is doing stuff like:</p> <pre><code>obj.methods.grep /to_/ </code></pre> <p>To get instance variables, do this:</p> <pre><code>obj.instance_variables </code></pre> <p>and for class variables:</p> <pre><code>obj.class_variables </code></pre>
2,901,470
How to make JTable column contain checkboxes?
<p>Preface: I am horrible with java, and worse with java ui components.</p> <p>I have found several different tutorials on how to add buttons to tables, however I am struggling with adding checkboxes. I need to have a column that draws a text box ticked on default (cell renderer i think handles that), then on click of tickbox, unticks the box, redraws said box, and fires off an event somewhere I can track.</p> <p>currently I have a custom cellrenderer:</p> <pre><code>public class GraphButtonCellRenderer extends JCheckBox implements TableCellRenderer { public GraphButtonCellRenderer() { } public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { if(isSelected) setSelected(true); else setSelected(false); setMargin(new Insets(0, 16, 0, 0)); setIconTextGap(0); setBackground(new Color(255,255,255,0)); return this; }} </code></pre> <p>Which currently handles drawing the tick box, but only ticks and unticks the box if that row is selected. But I don't know how to handle the events. Really what I am asking is possibly a link to a good tutorial on how to add checkboxes cleanly to a JTable. Any assist is greatly appreciated :)</p>
2,901,500
5
0
null
2010-05-25 01:40:32.653 UTC
null
2012-11-11 05:54:32.12 UTC
2012-08-17 16:00:51.777 UTC
null
203,657
null
179,914
null
1
8
java|swing|jtable|jcheckbox|tablecellrenderer
51,330
<p>There's no need to create your own table renderer. <a href="http://www.java2s.com/Tutorial/Java/0240__Swing/UsingdefaultBooleanvaluecelleditorandrenderer.htm" rel="noreferrer">Here's a simpler example</a>. Just create a custom table model and for a given column return the class Boolean for:</p> <pre><code>public Class getColumnClass(int column) </code></pre> <p>If you want the column to be editable, return true for</p> <pre><code>public boolean isCellEditable(int row, int column) </code></pre> <p>JTable takes care of the rendering for you.</p> <p><a href="http://java.sun.com/docs/books/tutorial/uiswing/components/table.html#data" rel="noreferrer">Another example is here.</a></p>
46,401,830
Amazon RDS Aurora vs RDS MySQL vs MySQL on EC2?
<p>I've been looking around for best practices when setting up your database on the cloud but it still isn't clear to me which of the following solutions should we be going for?</p> <ul> <li>Amazon RDS Aurora</li> <li>Amazon RDS MySQL</li> <li>MySQL on EC2 instances</li> </ul> <p>I see Amazon Aurora being marketed as the better alternative however after some research it doesn't seem like people are using it. Is there a problem with it? </p>
46,409,772
3
1
null
2017-09-25 09:27:31.417 UTC
11
2018-01-12 17:18:56.783 UTC
2017-09-25 15:33:34.963 UTC
null
13,070
null
4,096,056
null
1
48
mysql|amazon-web-services|amazon-ec2|amazon-rds|amazon-aurora
22,047
<p>You should benchmark Aurora carefully before you consider it. Launch an instance and set up a test instance of your application and your database. Generate as high of load as you can. I did at my last company, and I found that despite Amazon's claims of high performance, Aurora failed spectacularly. Two orders of magnitude slower than RDS. Our app had a high rate of write traffic.</p> <p>Our conclusion: if you have secondary indexes and have high write traffic, Aurora is not suitable. I bet it's good for read-only traffic though.</p> <p>(Edit: the testing I'm describing was done in Q1 of 2017. As with most AWS services, I expect Aurora to improve over time. Amazon has an explicit strategy of "<a href="http://www.businessinsider.com/3-lessons-we-can-learn-from-jeff-bezos-about-making-decisions-2017-11" rel="noreferrer">Release ideas at 70% and then iterate.</a>" From this, we should conclude that a new product from AWS is worth testing, but probably not production-ready for at least a few years after it's introduced).</p> <p>At that company, I recommended RDS. They had no dedicated DBA staff, and the automation that RDS gives you for DB operations like upgrades and backups was very helpful. You sacrifice a little bit of flexibility on tuning options, but that shouldn't be a problem.</p> <p>The worst inconvenience of RDS is that you can't have a MySQL user with SUPER privilege, but RDS provides stored procs for most common tasks you would need SUPER privilege for.</p> <p>I compared a multi-AZ RDS instance versus a replica set of EC2 instances, managed by Orchestrator. Because Orchestrator requires three nodes so you can have quorum, RDS was the clear winner on cost here, as well as ease of setup and operations.</p>
36,490,579
Rails - check if record exists in has_many association
<p>I'm not sure if my question is worded correctly.</p> <p>I have three models: <code>User</code>, <code>Item</code>, and <code>UserItem</code>.</p> <pre><code>user has_many :user_items user has_many :items, through :user_items item has_many :user_items item has_many :users -&gt; {uniq}, through :user_items item belongs_to :user user_item belongs_to :user user_item belongs_to :item </code></pre> <p>I need a way to see if a user has an item to make <code>if</code> statements in my item views But here's the catch, user_items have <code>enum status: [ :pending, approved]</code>. So I need to see if a <code>current_user</code> has a certain <code>:pending</code> item.</p> <p>For example when a user visits item1's view page I have the item_controller's show action declare <code>@item = Item.find_by_id(params[:id])</code>. But then what can I do with this <code>@item</code> to see if a user has this item?</p>
36,490,722
4
0
null
2016-04-08 02:36:28.907 UTC
3
2019-07-10 02:12:23.25 UTC
null
null
null
null
4,584,963
null
1
29
ruby-on-rails|activerecord|associations|has-many
27,558
<p>Try:</p> <pre><code>current_user.items.exists?(params[:id]) </code></pre> <p>Or </p> <pre><code>current_user.items.exists?(@item.id) </code></pre>
529,045
Dated reminders in sharepoint calendars
<p>I have a departmental maintenance that needs to be done roughly every 3 months. The maintenance itself can't be automated (it involves physically swapping a primary and spare piece of networking hardware to verify the spare is still working correctly).</p> <p>I could put this as a recurring event in Outlook and give it a two week reminder window, but I don't want it to be tied to an individual's account (if I or one of my coworkers leaves the company, I still want the reminder to go to the department).</p> <p>We're working on implementing Sharepoint and my group has a maintenance calendar, which seems like a lovely place to put this. However, there don't seem to be dated notifications for the events. You can set up notifications if the event <strong>changes</strong>, and you can subscribe to the calendar and set up a notification via Outlook, but that notification is still a per-user notification.</p> <p>At this point I'm probably just going to write a cronjob on a linux server that emails a reminder, but I thought I'd ask if there's a way to do it using all these expensive collab tools we're putting in place.</p> <p>So, any idea how to get notifications of a dated event that is not tied to individual users? I also welcome being told that my entire take on the problem is false as long as it involves some good alternatives. Thanks!</p>
529,295
2
0
null
2009-02-09 17:16:58.053 UTC
11
2021-01-07 06:12:46.26 UTC
null
null
null
jj33
430
null
1
17
sharepoint|calendar
56,862
<p>Expanding on Andy's answer (<a href="http://www.andrewconnell.com/blog/articles/CreatingCustomSharePointTimerJobs.aspx" rel="nofollow noreferrer">http://www.andrewconnell.com/blog/articles/CreatingCustomSharePointTimerJobs.aspx</a>) if you just put code to send an email in the Execute method of the timer job this doesn't give you anything more than cron.</p> <p>What you could do is to write code to iterate through the Calendar (actually an Event List) finding any events due soon and sending email to whomever is in the Assigned To field. This could then be called from the Timer Jobs Execute method or using a normal scheduled task. This will be easier to administer changes than cron and could be used for other types of tasks.</p> <p>A link to get you started - <a href="https://web.archive.org/web/20160327144827/http://stevepietrek.com/2007/09/21/iterate-through-items-in-a-list/" rel="nofollow noreferrer">Iterate through Items in a List</a></p> <p>Another option would be to use <a href="http://sharepointmagazine.net/technical/development/the-dog-ate-my-task-use-sharepoint-designer-to-email-daily-task-reminders" rel="nofollow noreferrer">Workflow to send out emails from the calendar</a></p> <p>EDIT - Since SharePoint SP2 this no longer works as is as workflows can no longer start themselves (loop) - <a href="https://docs.microsoft.com/en-us/archive/blogs/sharepointdesigner/service-pack-2-prevents-an-on-change-workflow-from-starting-itself" rel="nofollow noreferrer">explanation and workaround</a></p> <p>This CodeProject article shows how to develop a <a href="https://www.codeproject.com/Articles/32753/Send-scheduled-Reminder-Alerts-by-email-in-SharePo" rel="nofollow noreferrer">feature to send scheduled reminders</a></p> <p>Yet another option would be to use one of the 3rd party tools that do this <em>(disclaimer - I work for the first company)</em></p> <ul> <li><a href="http://www.pentalogic.net/sharepoint-products/reminder" rel="nofollow noreferrer">Pentalogic - SharePoint Reminder</a></li> <li><a href="https://web.archive.org/web/20200925192643/http://store.bamboosolutions.com/ps-34-5-alert-plus-web-part-available-early-oct-06.aspx" rel="nofollow noreferrer">Bamboo - Alert Plus</a></li> <li><a href="http://www.boostsolutions.com/sharepoint-alert-reminder.html" rel="nofollow noreferrer">BoostSolutions - Alert Reminder Boost</a></li> </ul> <p>Finally - whichever method you choose (custom code/workflow/3rd party) you will likely run into trouble with recurring events as SharePoint doesn't provide a way to get an 'expanded' list of all occurrences.</p>
502,389
Binding in a WPF data grid text column
<p>I'm trying to build a data grid where one of the columns is a font name displayed in that font. Previously, I was working with a list box where I had defined the following template:</p> <pre><code>&lt;TextBlock Text="{Binding Path=Name}" FontFamily="{Binding Path=Name}"/&gt; </code></pre> <p>This worked just fine. So, I tweaked the data structure (Name became Font.Name) and moved onto a data grid to try this:</p> <pre><code>&lt;dg:DataGridTextColumn Binding="{Binding Font.Name}" FontFamily="{Binding Font.Name}" IsReadOnly="True" Header="Font"/&gt; </code></pre> <p>Now the font names are all displayed in the default font, and I get this error:</p> <pre><code>System.Windows.Data Error: 2 : Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:Path=Font.Name; DataItem=null; target element is 'DataGridTextColumn' (HashCode=56915998); target property is 'FontFamily' (type 'FontFamily') </code></pre> <p>A few Google results dealing with custom controls suggest changing the property from DependencyObject to FrameworkElement, but I'd have to inherit DataGridTextColumn and define my own property to do so - there must be a better way.</p> <p>I've tried several different approaches to the binding, including attempting to change just the font size with a distinct property in my data class (i.e., <code>FontSize="{Binding FontSize}"</code>). They've all resulted in the same error as above.</p> <p>Anyone know what I'm doing wrong here?</p> <p><strong>Edit:</strong></p> <p>Thanks to Jared's reply, I found the following:</p> <p><a href="https://docs.microsoft.com/en-us/archive/blogs/jaimer/forwarding-the-datagrids-datacontext-to-its-columns" rel="nofollow noreferrer">https://docs.microsoft.com/en-us/archive/blogs/jaimer/forwarding-the-datagrids-datacontext-to-its-columns</a></p> <p>The method looks sound, but I need to make a binding that references the correct element in the DataContext for each row, as opposed to sharing a single value for the entire column.</p> <p>Code behind:</p> <pre><code>fontDataGrid.DataContext = from font in new InstalledFontCollection().Families; </code></pre> <p>XAML:</p> <pre><code>Binding="{Binding Font.Name}" FontFamily="{Binding (FrameworkElement.DataContext).Font.Name, RelativeSource={x:Static RelativeSource.Self}}" </code></pre> <p>Using the above XAML clearly isn't correct, because DataContext is the entire collection of fonts. But I can't index the collection, since I don't know what the row number is (or do I?). Is there some approach I can use to achieve this?</p> <p>And a secondary question - why does the Binding attribute seem to work just fine, even without the DataContext? Is it looking at ItemsSource instead?</p>
505,605
2
1
null
2009-02-02 06:50:14.45 UTC
7
2020-02-28 04:25:51.363 UTC
2020-02-28 04:25:51.363 UTC
Matthew Maravillas
119,418
Matthew Maravillas
2,186
null
1
27
.net|wpf|data-binding|xaml|datagrid
66,845
<p>Jared's answer is correct, but I've found a concrete solution that's solved my problem.</p> <p><a href="http://blogs.msdn.com/vinsibal/archive/2008/12/17/wpf-datagrid-dynamically-updating-datagridcomboboxcolumn.aspx" rel="noreferrer">http://blogs.msdn.com/vinsibal/archive/2008/12/17/wpf-datagrid-dynamically-updating-datagridcomboboxcolumn.aspx</a></p> <p>Following this example, I changed my DataGridTextColumn definition to:</p> <pre><code>&lt;dg:DataGridTextColumn Binding="{Binding Font.Name}" IsReadOnly="True" Header="Font"&gt; &lt;dg:DataGridTextColumn.ElementStyle&gt; &lt;Style TargetType="TextBlock"&gt; &lt;Setter Property="FontFamily" Value="{Binding Font.Name}" /&gt; &lt;/Style&gt; &lt;/dg:DataGridTextColumn.ElementStyle&gt; &lt;/dg:DataGridTextColumn&gt; </code></pre> <p>And I don't need to worry about the column inheriting the DataContext. This gives me the result I want.</p>
781,472
How to get all arguments passed to function (vs. optional only $args)
<p>$args returns only optional arguments. How can I get all function parameters?</p>
782,876
2
1
null
2009-04-23 12:22:00.47 UTC
7
2009-05-03 22:01:35.52 UTC
null
null
null
null
62,192
null
1
32
powershell|arguments
28,185
<p>$args returns any <em>undeclared</em> parameters, not optional parameters. So just don't declare parameters.</p> <p>In PowerShell v2, you can use $PSBoundParameters to get all parameters in a structured way.</p>
2,819,522
JQuery - Get the number of rows in a table body
<p>I have an HTML table that is defined as follows:</p> <pre><code>&lt;table id="myTable" cellpadding="0" cellspacing="0"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;First Name&lt;/th&gt; &lt;th&gt;Last Name&lt;/th&gt; &lt;th&gt;Birth Date&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;John&lt;/td&gt; &lt;td&gt;Smith&lt;/td&gt; &lt;td&gt;03-11-1980&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; </code></pre> <p>I want to understand how to determine <strong>how many rows are in the</strong> <code>tbody</code> <strong>portion of my table</strong>, instead of the table in general. How do I use JQuery to determine how many rows are in the tbody portion of a table?</p> <p>Thank you!</p>
2,819,544
5
0
null
2010-05-12 14:06:18.82 UTC
2
2017-05-17 12:42:14.78 UTC
2016-08-23 09:04:37.173 UTC
null
6,359,835
null
336,786
null
1
27
jquery
59,881
<p>Like this:</p> <pre><code>$("#myTable &gt; tbody &gt; tr").length </code></pre> <p>The <a href="http://api.jquery.com/child-selector/" rel="noreferrer" title="Child Selector"><code>a &gt; b</code></a> selector selects all <code>b</code> elements that are <em>direct</em> children of an <code>a</code> element. Therefore, this selector will not match rows in nested tables.</p>
2,636,086
Code example with annotation in JavaDoc
<p>my JavaDoc doesn't work when I have a code example with an annotation.</p> <p>Any suggestions?</p> <pre><code>/** * &lt;pre&gt; * public class Demo { * @DemoAnnotation * public void demoMethod() { * } * } * &lt;/pre&gt; */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD}) public @interface DemoAnnotation { </code></pre>
2,636,111
5
0
null
2010-04-14 08:59:40.41 UTC
3
2018-08-29 00:04:58.837 UTC
null
null
null
null
316,335
null
1
36
java|javadoc
14,403
<p>You must replace <code>@</code> with <code>&amp;#064;</code> in your JavaDoc.</p>
3,106,912
Why does Android prefer static classes
<p>I see a lot of java code where android prefers to have developers use static inner classes. Particularly for patterns like the <a href="http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html" rel="noreferrer" title="ViewHolder Pattern">ViewHolder Pattern</a> in custom ListAdapters.</p> <p>I'm not sure what the differences are between static and non-static classes. I've read about it but it doesn't seem to make sense when concerned with performance or memory-footprint.</p>
3,107,626
5
0
null
2010-06-24 02:42:29.977 UTC
28
2010-06-29 02:32:10.78 UTC
null
null
null
null
42,005
null
1
40
java|android|performance|static-classes
28,132
<p>It's not just Android developers...</p> <p>A non-static inner class always keeps an implicit reference to the enclosing object. If you don't need that reference, all it does is cost memory. Consider this:</p> <pre><code>class Outer { class NonStaticInner {} static class StaticInner {} public List&lt;Object&gt; foo(){ return Arrays.asList( new NonStaticInner(), new StaticInner()); } } </code></pre> <p>When you compile it, what you get will be something like this:</p> <pre><code>class Outer { Outer(){} public List&lt;Object&gt; foo(){ return Arrays.asList( new Outer$NonStaticInner(this), new StaticInner()); } } class Outer$NonStaticInner { private final Outer this$0; Outer$NonStaticInner(Outer enclosing) { this$0 = enclosing; } } class Outer$StaticInner { Outer$StaticInner(){} } </code></pre>
2,359,014
Scala @ operator
<p>What does Scala's @ operator do?</p> <p>For example, in the blog post <em><a href="http://szeiger.de/blog/2008/08/02/formal-language-processing-in-scala-part-2/" rel="noreferrer">Formal Language Processing in Scala, Part 2</a></em> there is a something like this</p> <pre><code>case x @ Some(Nil) =&gt; x </code></pre>
2,359,365
5
0
null
2010-03-01 20:55:41.087 UTC
55
2013-05-10 08:13:49.623 UTC
2013-05-10 08:13:49.623 UTC
null
63,550
null
283,910
null
1
142
scala|operators
29,764
<p>It enables one to bind a matched pattern to a variable. Consider the following, for instance:</p> <pre><code>val o: Option[Int] = Some(2) </code></pre> <p>You can easily extract the content:</p> <pre><code>o match { case Some(x) =&gt; println(x) case None =&gt; } </code></pre> <p>But what if you wanted not the <em>content</em> of <code>Some</code>, but the option itself? That would be accomplished with this:</p> <pre><code>o match { case x @ Some(_) =&gt; println(x) case None =&gt; } </code></pre> <p>Note that <code>@</code> can be used at <em>any</em> level, not just at the top level of the matching.</p>
2,708,160
Recursive LINQ calls
<p>I'm trying to build an XML tree of some data with a parent child relationship, but in the same table.</p> <p>The two fields of importance are</p> <p>CompetitionID ParentCompetitionID</p> <p>Some data might be</p> <p>CompetitionID=1, ParentCompetitionID=null</p> <p>CompetitionID=2, ParentCompetitionID=1</p> <p>CompetitionID=3, ParentCompetitionID=1</p> <p>The broken query I have simply displays results in a flat format. Seeing that I'm working with XML, some sort of recursive functionality is required. I can do this using normal for loop recursion, but would like to see the linq version. Any help appreciated.</p> <pre><code>var results = from c1 in comps select new { c.CompetitionID, SubComps= from sc in comps.Where (c2 =&gt; c2.CompetitionID == c1.CompetitionID) select sc }; </code></pre> <h2>Update</h2> <p>I found an interesting article by Chris Eargle <a href="http://www.kodefuguru.com/post/2011/04/19/How-to-Write-a-Recursive-Func.aspx" rel="nofollow noreferrer">here</a> that shows you how to call lambda delegates recursively. Here is the code. Thanks Chris!</p> <pre><code>Func&lt;int, int&gt; factoral = x =&gt; x &lt;= 1 ? 1 : x + factoral(--x); Func&lt;int, int&gt; factoral = null; factoral = x =&gt; x &lt;= 1 ? 1 : x + factoral(--x); </code></pre> <p>^ added code formatting to show the lamba funcs The trick is to assign null to the Func delegate first.</p>
2,711,873
6
1
null
2010-04-25 12:18:51.23 UTC
10
2013-08-29 02:51:27.747 UTC
2013-08-29 02:51:27.747 UTC
null
38,461
null
17,211
null
1
15
c#|linq
6,398
<p>Don't know how to write a recursive LINQ. But I think no recursion is actually required here. A tree may be built in just two steps:</p> <pre><code>Dictionary&lt;int, Competition&gt; dic = comps.ToDictionary(e =&gt; e.CompetitionID); foreach (var c in comps) if (dic.ContainsKey(c.ParentCompetitionID)) dic[c.ParentCompetitionID].Children.Add(c); var root = dic[1]; </code></pre> <p>The root variable now contains the complete tree.</p> <p>Here's a complete sample to test:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication2 { class Competition { public int CompetitionID; public int ParentCompetitionID; public List&lt;Competition&gt; Children=new List&lt;Competition&gt;(); public Competition(int id, int parent_id) { CompetitionID = id; ParentCompetitionID = parent_id; } } class Program { static void Main(string[] args) { List&lt;Competition&gt; comps = new List&lt;Competition&gt;() { new Competition(1, 0), new Competition(2,1), new Competition(3,1), new Competition(4,2), new Competition(5,3) }; Dictionary&lt;int, Competition&gt; dic = comps.ToDictionary(e =&gt; e.CompetitionID); foreach (var c in comps) if (dic.ContainsKey(c.ParentCompetitionID)) dic[c.ParentCompetitionID].Children.Add(c); var root = dic[1]; } } } </code></pre>
2,563,498
Making LaTeX tables smaller?
<p>I have a LaTeX table that looks like this:</p> <pre><code>\begin{table}[!ht] \centering \small \caption{ \bf{Caption}} \begin{tabular}{l|c|c|l|c|c|c|c|c} field1 &amp; field 2 &amp; ... \\ \hline ... </code></pre> <p>the problem is that even with "\small" the table is too big, since I use:</p> <pre><code>\usepackage{setspace} \doublespacing </code></pre> <p>in the header. How can I:</p> <ol> <li>Make the table single spaced? and </li> <li>Make the table smaller? </li> </ol> <p>I'd like it to fit on an entire page.</p>
2,565,470
6
0
null
2010-04-01 20:35:44.547 UTC
22
2022-06-23 08:31:55.533 UTC
2017-01-14 20:40:39.9 UTC
null
4,370,109
user248237
null
null
1
67
latex
236,871
<p>As well as <code>\singlespacing</code> mentioned previously to reduce the height of the table, a useful way to reduce the width of the table is to add <code>\tabcolsep=0.11cm</code> before the <code>\begin{tabular}</code> command and take out all the vertical lines between columns. It's amazing how much space is used up between the columns of text. You could reduce the font size to something smaller than <code>\small</code> but I normally wouldn't use anything smaller than <code>\footnotesize</code>.</p>
2,575,429
interface as a method parameter in Java
<p>I had an interview days ago and was thrown a question like this.</p> <p>Q: Reverse a linked list. Following code is given:</p> <pre><code>public class ReverseList { interface NodeList { int getItem(); NodeList nextNode(); } void reverse(NodeList node) { } public static void main(String[] args) { } } </code></pre> <p>I was confused because I did not know an interface object could be used as a method parameter. The interviewer explained a little bit but I am still not sure about this. Could somebody enlighten me?</p>
2,575,454
8
1
null
2010-04-04 18:21:43.137 UTC
30
2018-08-05 09:13:03.677 UTC
2017-09-26 01:14:43.09 UTC
null
1,057,230
null
179,385
null
1
67
java|oop|interface
100,983
<p>This is in fact one of the most common and useful ways to use an interface. The interface defines a contract, and your code can work with any class that implements the interface, without having to know the concrete class - it can even work with classes that didn't exist yet when the code was written.</p> <p>There are many examples in the Java standard API, especially in the collections framework. For example, <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List)" rel="noreferrer">Collections.sort()</a> can sort anything that implements the <code>List</code> interface (not just <code>ArrayList</code> or <code>LinkedList</code>, though implementing your own <code>List</code> is uncommon) and whose contents implement the <code>Comparable</code> interface (not just <code>String</code> or the numerical wrapper classes - and having your own class implement <code>Comparable</code> for that purpose is <em>quite</em> common).</p>
3,202,136
Using G++ to compile multiple .cpp and .h files
<p>I've just inherited some C++ code that was written poorly with one cpp file which contained the main and a bunch of other functions. There are also <code>.h</code> files that contain classes and their function definitions.</p> <p>Until now the program was compiled using the command <code>g++ main.cpp</code>. Now that I've separated the classes to <code>.h</code> and <code>.cpp</code> files do I need to use a makefile or can I still use the <code>g++ main.cpp</code> command?</p>
3,202,161
13
1
null
2010-07-08 09:18:58.267 UTC
90
2022-03-19 12:28:33.913 UTC
2020-08-19 11:04:01.053 UTC
null
11,277,894
null
99,213
null
1
223
c++|compilation|header|makefile
421,118
<p>list all the other cpp files after main.cpp.</p> <p>ie </p> <pre><code>g++ main.cpp other.cpp etc.cpp </code></pre> <p>and so on.</p> <p>Or you can compile them all individually. You then link all the resulting ".o" files together.</p>
2,543,670
Finding the direction of scrolling in a UIScrollView?
<p>I have a <code>UIScrollView</code> with only horizontal scrolling allowed, and I would like to know which direction (left, right) the user scrolls. What I did was to subclass the <code>UIScrollView</code> and override the <code>touchesMoved</code> method:</p> <pre><code>- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event { [super touchesMoved:touches withEvent:event]; UITouch *touch = [touches anyObject]; float now = [touch locationInView:self].x; float before = [touch previousLocationInView:self].x; NSLog(@"%f %f", before, now); if (now &gt; before){ right = NO; NSLog(@"LEFT"); } else{ right = YES; NSLog(@"RIGHT"); } } </code></pre> <p>But this method sometimes doesn't get called at all when I move. What do you think?</p>
4,073,028
24
2
null
2010-03-30 08:11:23.333 UTC
87
2021-06-30 09:40:49.387 UTC
2014-04-23 06:09:13.107 UTC
null
1,929,123
null
171,911
null
1
194
iphone|ios|cocoa-touch|uiscrollview
163,125
<p>Determining the direction is fairly straightforward, but keep in mind that the direction can change several times over the course of a gesture. For example, if you have a scroll view with paging turned on and the user swipes to go to the next page, the initial direction could be rightward, but if you have bounce turned on, it will briefly be going in no direction at all and then briefly be going leftward.</p> <p>To determine the direction, you'll need to use the <code>UIScrollView scrollViewDidScroll</code> delegate. In this sample, I created a variable named <code>lastContentOffset</code> which I use to compare the current content offset with the previous one. If it's greater, then the scrollView is scrolling right. If it's less then the scrollView is scrolling left:</p> <pre><code>// somewhere in the private class extension @property (nonatomic, assign) CGFloat lastContentOffset; // somewhere in the class implementation - (void)scrollViewDidScroll:(UIScrollView *)scrollView { ScrollDirection scrollDirection; if (self.lastContentOffset &gt; scrollView.contentOffset.x) { scrollDirection = ScrollDirectionRight; } else if (self.lastContentOffset &lt; scrollView.contentOffset.x) { scrollDirection = ScrollDirectionLeft; } self.lastContentOffset = scrollView.contentOffset.x; // do whatever you need to with scrollDirection here. } </code></pre> <p>I'm using the following enum to define direction. Setting the first value to ScrollDirectionNone has the added benefit of making that direction the default when initializing variables:</p> <pre><code>typedef NS_ENUM(NSInteger, ScrollDirection) { ScrollDirectionNone, ScrollDirectionRight, ScrollDirectionLeft, ScrollDirectionUp, ScrollDirectionDown, ScrollDirectionCrazy, }; </code></pre>
2,812,770
Add centered text to the middle of a horizontal rule
<p>I'm wondering what options one has in xhtml 1.0 strict to create a line on both sides of text like-so:</p> <pre> Section one ----------------------- Next section ----------------------- Section two </pre> <p>I've thought of doing some fancy things like this:</p> <pre><code>&lt;div style="float:left; width: 44%;"&gt;&lt;hr/&gt;&lt;/div&gt; &lt;div style="float:right; width: 44%;"&gt;&lt;hr/&gt;&lt;/div&gt; Next section </code></pre> <p>Or alternatively, because the above has problems with alignment (both vertical and horizontal):</p> <pre><code>&lt;table&gt;&lt;tr&gt; &lt;td style="width:47%"&gt;&lt;hr/&gt;&lt;/td&gt; &lt;td style="vertical-align:middle; text-align: center"&gt;Next section&lt;/td&gt; &lt;td style="width:47%"&gt;&lt;hr/&gt;&lt;/td&gt; &lt;/tr&gt;&lt;/table&gt; </code></pre> <p>This also has alignment problems, which I solve with this mess:</p> <pre><code>&lt;table&gt;&lt;tr&gt; &lt;td style="border-bottom: 1px solid gray; width: 47%"&gt;&amp;nbsp;&lt;/td&gt; &lt;td style="vertical-align:middle;text-align:center" rowspan="2"&gt;Next section&lt;/td&gt; &lt;td style="border-bottom: 1px solid gray; width: 47%"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt;&lt;tr&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt;&lt;/table&gt; </code></pre> <p>In addition to the alignment problems, both options feel 'fudgy', and I'd be much obliged if you happened to have seen this before and know of an elegant solution.</p>
26,634,224
33
5
null
2010-05-11 17:00:12.48 UTC
91
2021-07-15 21:19:44.97 UTC
2021-07-15 21:19:44.97 UTC
null
1,264,804
null
19,212
null
1
278
html|css|xhtml|line|vertical-alignment
353,369
<p>Flexbox is the solution:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-css lang-css prettyprint-override"><code>.separator { display: flex; align-items: center; text-align: center; } .separator::before, .separator::after { content: ''; flex: 1; border-bottom: 1px solid #000; } .separator:not(:empty)::before { margin-right: .25em; } .separator:not(:empty)::after { margin-left: .25em; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="separator"&gt;Next section&lt;/div&gt;</code></pre> </div> </div> </p> <p>Nowadays <a href="https://caniuse.com/flexbox" rel="noreferrer">every browser supports it</a>, and you can ensure compatibility with decade-old browsers by adding respective vendor prefixes if needed. It would degrade gracefully anyways.</p>
40,317,106
Failed to start redis.service: Unit redis-server.service is masked
<p>I Installed Redis Server on ubuntu 16.04. but when I try to start the redis service using</p> <pre><code>$ sudo systemctl start redis </code></pre> <p>I receive message:</p> <pre><code>Failed to start redis.service: Unit redis-server.service is masked. </code></pre> <p>I don't have any idea about this error.</p>
40,317,748
4
0
null
2016-10-29 07:44:04.693 UTC
11
2021-10-26 11:10:07.053 UTC
2021-06-25 20:56:34.963 UTC
null
213,269
null
3,597,679
null
1
36
redis|ubuntu-16.04|servicestack.redis
58,037
<p>I found the solution. I think it will help for others | <strong>systemctl unmask servicename</strong> </p> <pre><code>$ sudo systemctl unmask redis-server.service </code></pre>
10,269,221
How can I expand a vector into the arguments of a function in r?
<p>If I have the function with three individual arguments</p> <pre><code>fun &lt;- function(a,b,c){ a+b^2*c } </code></pre> <p>How can I call it using a single vector</p> <pre><code>my_vector &lt;- c(1,2,3) fun(my_vector) </code></pre>
10,269,233
2
0
null
2012-04-22 15:25:42.267 UTC
1
2022-04-30 23:25:13.513 UTC
null
null
null
null
355,567
null
1
31
r
4,089
<p>try this:</p> <pre><code>&gt; do.call("fun", as.list(my_vector)) [1] 13 </code></pre>
5,867,647
Getting a list of magento stores
<p>How can I get a list of store groups under a website in Magento and then a list of stores from that store group?</p>
5,867,890
2
0
null
2011-05-03 09:36:00.453 UTC
6
2017-12-20 13:50:24.15 UTC
2014-09-20 12:32:54.903 UTC
null
759,866
null
735,852
null
1
28
magento
44,568
<p>Try this to get the objects directly </p> <pre><code>Mage::app()-&gt;getWebsites(); &lt; in file &gt; app/code/core/Mage/Core/Model/App.php:920 Mage::app()-&gt;getStores(); &lt; in file &gt; app/code/core/Mage/Core/Model/App.php:834 </code></pre> <p>iterate over to get the needed scope of one specific website or store</p> <pre><code>foreach (Mage::app()-&gt;getWebsites() as $website) { foreach ($website-&gt;getGroups() as $group) { $stores = $group-&gt;getStores(); foreach ($stores as $store) { //$store is a store object } } } </code></pre> <p>For the future if you have similar questions here's how i discovered those answers within 60 seconds. First i grep for method names or similar method names with space before method name to see where the methods are defined</p> <pre><code>grep ' getStores' app/code -rsn grep ' getWebsites' app/code -rsn </code></pre> <p>Second step is grep for usage samples to see how they are meant to use by core developers. For that i add >methodName to grep and this gives me list of files where this method is called and this will give us place to look for examples:</p> <pre><code>grep '&gt;getWebsites' app/code -rsn </code></pre>
6,191,412
How to URL encode periods?
<p>I need to URL encode some periods since I have to pass some document path along and it is like this</p> <pre><code>http://example.com/test.aspx?document=test.docx </code></pre> <p>So test.docx is causing me an error of an illegal character. So I need to change it to </p> <pre><code>. --&gt; %2E </code></pre> <p>I tried to use Server.UrlEncode</p> <pre><code> string b = Server.UrlEncode("http://example.com/test.aspx?document=test.docx"); </code></pre> <p>but I get</p> <pre><code>"http%3a%2f%2fexample.com%2ftest.aspx%3fdocument%3dtest.docx" </code></pre> <p>So do I have to use like a string replace and do it manually and replace all periods with that code?</p>
6,191,428
2
1
null
2011-05-31 17:45:35.597 UTC
3
2018-09-18 07:21:00.783 UTC
2018-09-18 07:21:00.783 UTC
null
608,639
null
130,015
null
1
34
c#|urlencode|url-encoding
62,879
<p>The period there isn't he problem (given that %2E doesn't solve the problem). A period is a perfectly valid URL character whatever the problem is it's not the period. Check the stack trace of the error being throw or post the complete error details.</p> <p>And you shouldn't be URL encoding the entire path. Only the query string parameter <em>value</em>.</p> <pre><code>string b = "http://example.com/test.aspx?document=" + Server.UrlEncode("test.docx"); </code></pre> <p>Are you still getting the error if you try it that way?</p> <p>I wouldn't touch SharePoint with a ten foot pole. However, escaping the period wouldn't necessarily stop SharePoint from doing it's shenanigans. But I guess you should at least try it.</p> <pre><code>Server.UrlEncode("test.docx").Replace(".", "%2E"); </code></pre>
33,357,821
Export a DynamoDB table as CSV through AWS CLI (without using pipeline)
<p>I am new to AWS CLI and I am trying to export my DynamoDB table in CSV format so that I can import it directly into PostgreSQL. Is there a way to do that using AWS CLI?</p> <p>I came across this command: <code>aws dynamodb scan --table-name &lt;table-name&gt;</code> - but this does not provide an option of a CSV export.</p> <p>With this command, I can see the output in my terminal but I am not sure how to write it into a file.</p>
33,358,747
5
0
null
2015-10-27 00:12:38.193 UTC
18
2022-04-09 14:31:12.31 UTC
2022-04-09 14:31:12.31 UTC
null
992,887
null
5,249,746
null
1
45
amazon-web-services|csv|amazon-dynamodb|aws-cli
58,497
<p>If all items have the same attributes, e.g. <code>id</code> and <code>name</code> both of which are strings, then run:</p> <pre><code>aws dynamodb scan \ --table-name mytable \ --query &quot;Items[*].[id.S,name.S]&quot; \ --output text </code></pre> <p>That would give tab-separated output. You can redirect this to file using <code>&gt; output.txt</code>, and you could then easily convert tabs into commas for csv.</p> <p>Note that you may need to paginate per the <a href="https://docs.aws.amazon.com/cli/latest/reference/dynamodb/scan.html" rel="noreferrer">scan documentation</a>:</p> <blockquote> <p>If the total number of scanned items exceeds the maximum dataset size limit of 1 MB, the scan stops and results are returned to the user as a LastEvaluatedKey value to continue the scan in a subsequent operation. The results also include the number of items exceeding the limit. A scan can result in no table data meeting the filter criteria.</p> </blockquote> <p>Another option is the <a href="https://github.com/edasque/DynamoDBtoCSV" rel="noreferrer">DynamoDBtoCSV</a> project at github.</p>
33,180,058
Coerce multiple columns to factors at once
<p>I have a sample data frame like below:</p> <pre><code>data &lt;- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10]))) </code></pre> <p>I want to know how can I select multiple columns and convert them together to factors. I usually do it in the way like <code>data$A = as.factor(data$A)</code>. But when the data frame is very large and contains lots of columns, this way will be very time consuming. Does anyone know of a better way to do it? </p>
33,180,265
11
1
null
2015-10-16 21:47:09.833 UTC
36
2021-12-02 23:55:32.767 UTC
2018-11-29 04:04:19.743 UTC
null
3,063,910
null
5,421,308
null
1
93
r|dataframe|r-factor
145,717
<p>Choose some columns to coerce to factors:</p> <pre><code>cols &lt;- c("A", "C", "D", "H") </code></pre> <p>Use <code>lapply()</code> to coerce and replace the chosen columns:</p> <pre><code>data[cols] &lt;- lapply(data[cols], factor) ## as.factor() could also be used </code></pre> <p>Check the result:</p> <pre><code>sapply(data, class) # A B C D E F G # "factor" "integer" "factor" "factor" "integer" "integer" "integer" # H I J # "factor" "integer" "integer" </code></pre>
31,111,771
can you catch all errors of a React.js app with a try/catch block?
<p>I've made a react application which is not running live, and the people that use it note that very occasionally some strange error occurs. I don't know why or what happens, and can't reproduce it.</p> <p>So I'm wondering if there is a way to wrap the entire app, or parts of it, in a try/catch block so that I can send the errors to an error log on the server?</p> <p>All I've read so far is that you could wrap the entire render function in a try/catch, but that would not catch any errors due to user interation right?</p>
50,897,227
5
1
null
2015-06-29 09:08:36.28 UTC
11
2021-09-26 04:40:18.253 UTC
null
null
null
null
977,206
null
1
55
try-catch|reactjs
64,805
<p>React 16 introduced <a href="https://reactjs.org/docs/error-boundaries.html" rel="noreferrer">Error Boundaries</a> and the <a href="https://reactjs.org/docs/react-component.html#componentdidcatch" rel="noreferrer">componentDidCatch lifecycle method</a>:</p> <pre><code>class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false }; } componentDidCatch(error, info) { // Display fallback UI this.setState({ hasError: true }); // You can also log the error to an error reporting service logErrorToMyService(error, info); } render() { if (this.state.hasError) { // You can render any custom fallback UI return &lt;h1&gt;Something went wrong.&lt;/h1&gt;; } return this.props.children; } } </code></pre> <p>Then you can use it as a regular component:</p> <pre><code>&lt;ErrorBoundary&gt; &lt;MyWidget /&gt; &lt;/ErrorBoundary&gt; </code></pre> <p>Or you can wrap your root component with the npm package <a href="https://github.com/bvaughn/react-error-boundary" rel="noreferrer">react-error-boundary</a>, and set a fallback component and behavior.</p> <pre><code>import {ErrorBoundary} from 'react-error-boundary'; const myErrorHandler = (error: Error, componentStack: string) =&gt; { // ... }; &lt;ErrorBoundary onError={myErrorHandler}&gt; &lt;ComponentThatMayError /&gt; &lt;/ErrorBoundary&gt; </code></pre>
31,508,603
How to retrieve build_id of latest successful build in Jenkins?
<p>Generally, to get the artifact of the latest successful build, I do a <code>wget</code> on the below URL:</p> <p><a href="http://jenkins.com/job/job_name/lastSuccessfulBuild/artifact/artifact1/jenkins.txt" rel="noreferrer">http://jenkins.com/job/job_name/lastSuccessfulBuild/artifact/artifact1/jenkins.txt</a></p> <p>Is there a way, I can do a <code>wget</code> on <code>lastSuccessfulBuild</code> and get a <code>build_id</code> like below?</p> <pre><code>build_id=`wget http://jenkins.p2pcredit.local/job/job_name/lastSuccessfulBuild` </code></pre>
31,511,619
7
1
null
2015-07-20 03:52:57.41 UTC
4
2021-08-30 12:12:51.79 UTC
2015-12-29 18:12:23.73 UTC
null
2,675,154
null
2,194,137
null
1
20
maven|jenkins|build
43,953
<p>Yes, there is a way and it is pretty straightforward:</p> <pre><code>$ build_id=`wget -qO- jenkins_url/job/job_name/lastSuccessfulBuild/buildNumber` $ echo $build_id 131 # that's my build number </code></pre>
35,405,374
Angular2 ngFor skip first index
<p>How can I skip the first index from the array?</p> <pre><code>&lt;li *ngFor="#user of users"&gt; {{ user.name }} is {{ user.age }} years old. &lt;/li&gt; </code></pre>
35,405,426
2
0
null
2016-02-15 09:16:04.59 UTC
6
2017-09-13 15:27:23.053 UTC
2016-02-15 17:32:23.107 UTC
null
215,945
null
75,799
null
1
49
angular|angular2-directives
32,488
<p>You could use the <a href="https://angular.io/docs/ts/latest/api/common/index/SlicePipe-pipe.html" rel="noreferrer">slice pipe</a>.</p> <pre><code>&lt;li *ngFor="#user of users | slice:1"&gt; {{ user.name }} is {{ user.age }} years old. &lt;/li&gt; </code></pre> <p>The first parameter corresponds to a positive integer representing the start index.</p>
19,015,282
How do I enable https support in libcurl?
<p>When I try to <code>$ brew update</code> I'm getting the error:</p> <pre><code>error: Protocol https not supported or disabled in libcurl while accessing https://github.com/mxcl/homebrew/info/refs?service=git-upload-pack </code></pre> <p>However, when I <code>$ curl --version</code>, I see:</p> <pre><code>curl 7.21.4 (x86_64-apple-darwin12.2.0) libcurl/7.21.4 OpenSSL/0.9.8y zlib/1.2.5 libidn/1.20 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp Features: IDN IPv6 Largefile NTLM SSL libz </code></pre> <p>Unless I'm missing something, that looks good to me. Notice that <code>https</code> is listed in the protocols list.</p> <p><code>$ which curl</code> yields a suspicious response:</p> <pre><code>/usr/local/php5/bin/curl </code></pre> <p>Hmmmmm...maybe <code>brew</code> is using a different <code>curl</code> (like the one at <code>/usr/bin/curl</code>). Let's see:</p> <p><code>$ /usr/bin/curl --version</code></p> <pre><code>curl 7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8y zlib/1.2.5 Protocols: dict file ftp ftps gopher http https imap imaps ldap ldaps pop3 pop3s rtsp smtp smtps telnet tftp Features: AsynchDNS GSS-Negotiate IPv6 Largefile NTLM NTLM_WB SSL libz </code></pre> <p>Okay, it's obviously a different install of <code>curl</code>, but it's also listing <code>https</code> in the protocols list, and has the OpenSSL info there too.</p> <p>BTW: I get the same error if I try to use an <code>https</code> URL with any <code>git</code> repo on my machine.</p> <p>Questions:</p> <ol> <li><del>How can I determine the path to the <code>curl</code> that <code>brew</code> is using?</del></li> <li>How do I enable support for <code>https</code> in <code>libcurl</code>?</li> </ol> <p><strong>UPDATE:</strong> I was able to determine the path to <code>libcurl.4.dylib</code> that <code>git</code> (and <code>brew</code>) are using by following deltheil's method below. The path is:</p> <pre><code>/usr/lib/libcurl.4.dylib (compatibility version 6.0.0, current version 6.1.0) </code></pre> <p>So I tried this:</p> <pre><code>$ brew install curl --with-libssh2 </code></pre> <p>Luckily curl is available at a non-SSL URI, so it actually did insstall. It didn't symlink into <code>/usr/local</code>, but that's fine with me (I think). So I did this:</p> <pre><code>$ cd /usr/lib $ mv libcurl.4.dylib libcurl.4.dylib.bk $ ln -s /usr/local/Cellar/curl/7.30.0/lib/libcurl.4.dylib libcurl.4.dylib $ brew update </code></pre> <p>But it's still throwing me this error:</p> <pre><code>error: Protocol https not supported or disabled in libcurl while accessing https://github.com/mxcl/homebrew/info/refs?service=git-upload-pack </code></pre> <p>So now the question exclusively becomes: How do I enable support for <code>https</code> in <code>libcurl</code>?</p>
19,046,003
3
0
null
2013-09-25 21:11:26.637 UTC
4
2020-12-21 12:11:43.7 UTC
2013-09-27 22:34:16.283 UTC
null
1,023,812
null
1,023,812
null
1
21
git|libcurl|homebrew
57,209
<blockquote> <p>How can I determine the path to the curl that brew is using?</p> </blockquote> <p>Homebrew uses <code>/usr/bin/curl</code>, i.e the version that ships with Mac OS X, as you can see <a href="https://github.com/mxcl/homebrew/blob/e9749ff2b0880a51877599a05ac58db6f12d3d8f/Library/Homebrew/utils.rb#L135" rel="noreferrer">here</a>.</p> <p>That being said, and as you precise, your problem is probably related to the version of libcurl that is linked with <code>git</code> and used for <code>http://</code> and <code>https://</code>.</p> <p>Perform a <code>which git</code> to determine which is the version you are being used (mine is installed under <code>/usr/local</code>).</p> <p>Then scan the shared libraries used as follow:</p> <pre><code>$ otool -L /usr/local/git/libexec/git-core/git-http-push | grep curl /usr/lib/libcurl.4.dylib </code></pre> <p><em>Replace <code>/usr/local/</code> with the install directory that corresponds to your <code>git</code>.</em></p> <p>Since the libcurl version used by your <code>git</code> exec lacks of HTTPS support, this will tell you what is this version and where it is installed.</p>
19,144,246
Grails get child domain objects
<p>I have two domain classes one is parent and other one is child and i have a hasMany relationship between them. Parent class has many childs and child class belongs to parent class. And here is coding example.</p> <pre><code>class Parent{ String name static hasMany = [childs:Child] static constraints = { } } class Child{ String name static belongsTo = [parent:Parent] static constraints={} } </code></pre> <p>Problem is as soon as I get the parent object the child objects associated with parent class were also fetched. But when I convert the object to JSON I don't see the child object completely I can only able to see the ID's of child objects. I want to see all columns of child object instead of only Id.</p> <p>Converted JSON response:</p> <pre><code>[{"class":"project.Parent","id":1, "name":"name1","childs":[{"class":"Child","id":1},{"class":"Review","id":2}]}] </code></pre> <p>But I want the response which contains name of child object too, as follows</p> <pre><code>[{"class":"project.Parent","id":1,"name":"name1", "childs":[{"class":"Child","id":1,"name":"childname1"}, {"class":"Review","id":2,"name":"childname2"} ] }] </code></pre> <p>Any help greatly appreciated. Thanks in advance.</p>
19,144,350
4
0
null
2013-10-02 18:35:40.763 UTC
12
2018-07-25 13:47:43.65 UTC
2013-10-02 18:50:23.127 UTC
null
2,051,952
null
2,823,355
null
1
29
json|grails|grails-domain-class
12,702
<p>The issue is with the use of default JSON converter. Here are your options:</p> <pre><code> 1. Default - all fields, shallow associations a. render blah as JSON 2. Global deep converter - change all JSON converters to use deep association traversal a. grails.converters.json.default.deep = true 3. Named config marshaller using provided or custom converters a. JSON.createNamedConfig('deep'){ it.registerObjectMarshaller( new DeepDomainClassMarshaller(...) ) } b. JSON.use('deep'){ render blah as JSON } 4. Custom Class specific closure marshaller a. JSON.registerObjectMarshaller(MyClass){ return map of properties} b. render myClassInstance as JSON 5. Custom controller based closure to generate a map of properties a. convert(object){ return map of properties } b. render convert(blah) as JSON </code></pre> <p>You are currently using Option 1, which is default. </p> <p>The simplest you can do is use Option 2 to set global deep converter, but be aware this effects ALL domain classes in your app. Which means that if you have a large tree of associations culminating in a top level object and you try to convert a list of those top level objects the deep converter will execute all of the queries to fetch all of the associated objects and their associated objects in turn. - <strong>You could load an entire database in one shot</strong> :) Be careful.</p>
51,869,261
Save json to CoreData as String and use the String to create array of objects
<p>I am creating an app for a radio station and I want to store "show" objects into an array. I use a webserver to supply json data to populate the array, but I want to store this json data into CoreData as a string so that access to the array doesn't depend on internet connection. Therefore, I want to update the string in CoreData on app launch, but create an array based off of the string stored in CoreData not on the json data from the webserver.</p> <p>Here's my function to download the json data from the webserver and store it into a string: </p> <pre><code>func downloadShows() { let urlPath = "http://dogradioappdatabase.com/shows.php" guard let url = URL(string: urlPath) else {return} let task = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let dataResponse = data, error == nil else { print(error?.localizedDescription ?? "Response Error") return } let jsonAsString = self.jsonToString(json: dataResponse) DispatchQueue.main.async { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let task2 = WebServer(context: context) // Link Task &amp; Context task2.showsArray = jsonAsString print(jsonAsString) (UIApplication.shared.delegate as! AppDelegate).saveContext() } } task.resume() } func jsonToString(json: Data) -&gt; String { let convertedString: String convertedString = String(data: json, encoding: String.Encoding.utf8)! // the data will be converted to the string return convertedString } </code></pre> <p>Here's the function to create the shows array from the fetched json from CoreData:</p> <pre><code> func createShowsArray () -&gt; Array&lt;ShowModel&gt; { var array: Array&lt;ShowModel&gt; = Array() var tasks: [WebServer] = [] let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext do { tasks = try context.fetch(WebServer.fetchRequest()) } catch { print("Fetching Failed") } let arrayAsString: String = tasks[0].showsArray! print(arrayAsString) do { let data1 = arrayAsString.data(using: .utf8)! let decoder = JSONDecoder() array = try decoder.decode([ShowModel].self, from: data1) } catch let parsingError { print("Error", parsingError) } return array } </code></pre> <p>However, this does not correctly load the data into an array. I printed the value I saved to CoreData in the downloadShows() function (jsonAsString) and got this as a response: </p> <blockquote> <p>[{"Name":"Example Show 2","ID":"2","Description":"This ...</p> </blockquote> <p>But when I fetched the string from CoreData in the createShowsArray() function (arrayAsString), it had added "DOG_Radio.ShowModel"</p> <blockquote> <p>[DOG_Radio.ShowModel(Name: "Example Show 2", ID: "2", Description: "This ...</p> </blockquote> <p>The JSON Decoder does not decode arrayAsString into an actual array. It throws this back:</p> <blockquote> <p>Error dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 1." UserInfo={NSDebugDescription=Invalid value around character 1.})))</p> </blockquote> <p>Sorry for the long question, I just don't know how to use CoreData to save json as String then convert that String into an array later</p>
51,873,317
2
0
null
2018-08-16 03:36:39.223 UTC
11
2018-08-16 17:00:37.91 UTC
null
null
null
null
10,192,689
null
1
7
ios|arrays|json|swift|core-data
9,684
<p>It's a bad practice to store json data or 'whole raw data' into CoreData. Instead Store the <code>Show</code> itself as a <code>NSManagedObject</code>. You can do this by converting the JSON data to an Object (which it looks like you are already doing), then creating CoreData NSManagedObjects from them.</p> <p>Realistically if you have no trouble converting the data from JSON there is no need to convert it to a string before saving to CoreData. You can simply store the <code>Data</code> as <code>NSData</code>, i.e. <code>transformable</code> or <code>binary data</code> and reconvert it later if your fetch to the server fails.</p> <p>However, thats not that reliable and much harder to work with in the long run. The data could be corrupt and/or malformed.</p> <p>In short, you need a Data Model and a JSON readable Data Structure you can Convert to your Data Model to for CoreData to manage. This will become important later when you want to allow the user to update, remove, save or filter individual <code>Show</code>'s.</p> <p><code>Codable</code> will allow you to covert from JSON to a Struct with <code>JSONDecoder().decode(_:from:)</code>.</p> <p><strong>ShowModelCodeable.swift</strong></p> <pre><code>import Foundation struct ShowModelCodeable: Codable { var name: String? var description: String? var producer: String? var thumb: String? var live: String? var banner: String? var id: String? enum CodingKeys: String, CodingKey { case name = "Name" case id = "ID" case description = "Description" case producer = "Producer" case thumb = "Thumb" case live = "Live" case banner = "Banner" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) name = try values.decode(String.self, forKey: .name) description = try values.decode(String.self, forKey: .description) producer = try values.decode(String.self, forKey: .producer) thumb = try values.decode(String.self, forKey: .thumb) live = try values.decode(String.self, forKey: .live) banner = try values.decode(String.self, forKey: .banner) id = try values.decode(String.self, forKey: .id) } func encode(to encoder: Encoder) throws { } } </code></pre> <p>Next, We'll need a Core Data Stack and a CoreData Entity. Its very common to create a Core Data Stack as a Class Singleton that can be accessed anywhere in your app. I've included one with basic operations:</p> <p><a href="https://i.stack.imgur.com/bO6Dm.png" rel="noreferrer"><img src="https://i.stack.imgur.com/bO6Dm.png" alt="Image of Core Data Model"></a></p> <p><strong>DatabaseController.Swift</strong></p> <pre><code>import Foundation import CoreData class DatabaseController { private init() {} //Returns the current Persistent Container for CoreData class func getContext () -&gt; NSManagedObjectContext { return DatabaseController.persistentContainer.viewContext } static var persistentContainer: NSPersistentContainer = { //The container that holds both data model entities let container = NSPersistentContainer(name: "StackOverflow") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ //TODO: - Add Error Handling for Core Data fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support class func saveContext() { let context = self.getContext() if context.hasChanges { do { try context.save() print("Data Saved to Context") } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. //You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } /* Support for GRUD Operations */ // GET / Fetch / Requests class func getAllShows() -&gt; Array&lt;ShowModel&gt; { let all = NSFetchRequest&lt;ShowModel&gt;(entityName: "ShowModel") var allShows = [ShowModel]() do { let fetched = try DatabaseController.getContext().fetch(all) allShows = fetched } catch { let nserror = error as NSError //TODO: Handle Error print(nserror.description) } return allShows } // Get Show by uuid class func getShowWith(uuid: String) -&gt; ShowModel? { let requested = NSFetchRequest&lt;ShowModel&gt;(entityName: "ShowModel") requested.predicate = NSPredicate(format: "uuid == %@", uuid) do { let fetched = try DatabaseController.getContext().fetch(requested) //fetched is an array we need to convert it to a single object if (fetched.count &gt; 1) { //TODO: handle duplicate records } else { return fetched.first //only use the first object.. } } catch { let nserror = error as NSError //TODO: Handle error print(nserror.description) } return nil } // REMOVE / Delete class func deleteShow(with uuid: String) -&gt; Bool { let success: Bool = true let requested = NSFetchRequest&lt;ShowModel&gt;(entityName: "ShowModel") requested.predicate = NSPredicate(format: "uuid == %@", uuid) do { let fetched = try DatabaseController.getContext().fetch(requested) for show in fetched { DatabaseController.getContext().delete(show) } return success } catch { let nserror = error as NSError //TODO: Handle Error print(nserror.description) } return !success } } // Delete ALL SHOWS From CoreData class func deleteAllShows() { do { let deleteFetch = NSFetchRequest&lt;NSFetchRequestResult&gt;(entityName: "ShowModel") let deleteALL = NSBatchDeleteRequest(fetchRequest: deleteFetch) try DatabaseController.getContext().execute(deleteALL) DatabaseController.saveContext() } catch { print ("There is an error in deleting records") } } </code></pre> <p>Finally, we need a way to get the JSON data and convert it to our Objects, then Display it. Note that when the update button is pressed, it fires <code>getDataFromServer()</code>. The most important line here is</p> <pre><code>self.newShows = try JSONDecoder().decode([ShowModelCodeable].self, from: dataResponse) </code></pre> <p>The Shows are being pulled down from your Server, and converted to <code>ShowModelCodeable</code> Objects. Once <code>newShows</code> is set it will run the code in <code>didSet</code>, here you can delete all the Objects in the context, then run <code>addNewShowsToCoreData(_:)</code> to create new NSManagedObjects to be saved in the context.</p> <p>I've created a basic view controller and programmatically added a tableView to manage the data. Here, <code>Shows</code> is your NSManagedObject array from CoreData, and <code>newShows</code> are new objects encoded from json that we got from the server request.</p> <p><strong>ViewController.swift</strong></p> <pre><code>import Foundation import UIKit import CoreData class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // Properties var Shows:[ShowModel]? var newShows:[ShowModelCodeable]? { didSet { // Remove all Previous Records DatabaseController.deleteAllShows() // Add the new spots to Core Data Context self.addNewShowsToCoreData(self.newShows!) // Save them to Core Data DatabaseController.saveContext() // Reload the tableView self.reloadTableView() } } // Views var tableView: UITableView = { let v = UITableView() v.translatesAutoresizingMaskIntoConstraints = false return v }() lazy var updateButton: UIButton = { let b = UIButton() b.translatesAutoresizingMaskIntoConstraints = false b.setTitle("Update", for: .normal) b.setTitleColor(.black, for: .normal) b.isEnabled = true b.addTarget(self, action: #selector(getDataFromServer), for: .touchUpInside) return b }() override func viewWillAppear(_ animated: Bool) { self.Shows = DatabaseController.getAllShows() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.tableView.delegate = self self.tableView.dataSource = self self.tableView.register(ShowCell.self, forCellReuseIdentifier: ShowCell.identifier) self.layoutSubViews() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //TableView - func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int { return DatabaseController.getAllShows().count } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -&gt; CGFloat { // 100 return ShowCell.height() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell { let cell = self.tableView.dequeueReusableCell(withIdentifier: ShowCell.identifier) as! ShowCell self.Shows = DatabaseController.getAllShows() if Shows?.count != 0 { if let name = Shows?[indexPath.row].name { cell.nameLabel.text = name } if let descriptionInfo = Shows?[indexPath.row].info { cell.descriptionLabel.text = descriptionInfo } } else { print("No shows bros") } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Show the contents print(Shows?[indexPath.row] ?? "No Data For this Row.") } func reloadTableView() { DispatchQueue.main.async { self.tableView.reloadData() } } func layoutSubViews() { let guide = self.view.safeAreaLayoutGuide let spacing: CGFloat = 8 self.view.addSubview(tableView) self.view.addSubview(updateButton) updateButton.topAnchor.constraint(equalTo: guide.topAnchor, constant: spacing).isActive = true updateButton.leftAnchor.constraint(equalTo: guide.leftAnchor, constant: spacing * 4).isActive = true updateButton.rightAnchor.constraint(equalTo: guide.rightAnchor, constant: spacing * -4).isActive = true updateButton.heightAnchor.constraint(equalToConstant: 55.0).isActive = true tableView.topAnchor.constraint(equalTo: updateButton.bottomAnchor, constant: spacing).isActive = true tableView.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true tableView.rightAnchor.constraint(equalTo: self.view.rightAnchor).isActive = true tableView.bottomAnchor.constraint(equalTo: guide.bottomAnchor, constant: spacing).isActive = true } @objc func getDataFromServer() { print("Updating...") let urlPath = "http://dogradioappdatabase.com/shows.php" guard let url = URL(string: urlPath) else {return} let task = URLSession.shared.dataTask(with: url) { (data, response, error) in guard let dataResponse = data, error == nil else { print(error?.localizedDescription ?? "Response Error") return } do { self.newShows = try JSONDecoder().decode([ShowModelCodeable].self, from: dataResponse) } catch { print(error) } } task.resume() } func addNewShowsToCoreData(_ shows: [ShowModelCodeable]) { for show in shows { let entity = NSEntityDescription.entity(forEntityName: "ShowModel", in: DatabaseController.getContext()) let newShow = NSManagedObject(entity: entity!, insertInto: DatabaseController.getContext()) // Create a unique ID for the Show. let uuid = UUID() // Set the data to the entity newShow.setValue(show.name, forKey: "name") newShow.setValue(show.description, forKey: "info") newShow.setValue(show.producer, forKey: "producer") newShow.setValue(show.thumb, forKey: "thumb") newShow.setValue(show.live, forKey: "live") newShow.setValue(show.banner, forKey: "banner") newShow.setValue(show.id, forKey: "id") newShow.setValue(uuid.uuidString, forKey: "uuid") } } } </code></pre> <p><a href="https://i.stack.imgur.com/iaHYU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/iaHYU.png" alt="View Hierarchy"></a></p>
8,380,797
Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user
<p>MySQL 5.1.31 running on Windows XP.</p> <p>From the <strong>local</strong> MySQL server (192.168.233.142) I can connect as root as follows:</p> <pre><code>&gt;mysql --host=192.168.233.142 --user=root --password=redacted </code></pre> <p>From a <strong>remote</strong> machine (192.168.233.163), I can see that the mysql port is open:</p> <pre><code># telnet 192.168.233.142 3306 Trying 192.168.233.142... Connected to 192.168.233.142 (192.168.233.142). </code></pre> <p>But when trying to connect to mysql from the <strong>remote</strong> machine, I receive:</p> <pre><code># mysql --host=192.168.233.142 --user=root --password=redacted ERROR 1045 (28000): Access denied for user 'root'@'192.168.233.163' (using password: YES) </code></pre> <p>I have only 2 entries in mysql.user:</p> <pre><code>Host User Password -------------------------------------- localhost root *blahblahblah % root [same as above] </code></pre> <p>What more do I need to do to enable remote access?</p> <p><strong>EDIT</strong></p> <p>As suggested by Paulo below, I tried replacing the mysql.user entry for % with an IP specific entry, so my user table now looks like this:</p> <pre><code>Host User Password ------------------------------------------ localhost root *blahblahblah 192.168.233.163 root [same as above] </code></pre> <p>I then restarted the machine, but the problem persists.</p>
8,381,403
13
0
null
2011-12-05 03:50:12.757 UTC
72
2020-12-24 00:34:04.303 UTC
2016-01-16 02:00:50.78 UTC
null
289,319
null
289,319
null
1
146
mysql
326,018
<p>Paulo's help lead me to the solution. It was a combination of the following:</p> <ul> <li>the password contained a dollar sign</li> <li>I was trying to connect from a Linux shell</li> </ul> <p>The bash shell treats the dollar sign as a special character for <a href="http://www.gnu.org/software/bash/manual/bashref.html#Shell-Parameter-Expansion" rel="noreferrer">expansion</a> to an environment variable, so we need to escape it with a backslash. Incidentally, we <strong>don't</strong> have to do this in the case where the dollar sign is the final character of the password.</p> <p>As an example, if your password is "pas$word", from Linux bash we must connect as follows:</p> <pre><code># mysql --host=192.168.233.142 --user=root --password=pas\$word </code></pre>
30,717,347
docker-machine create node without tls verification
<p>When I create a node with <strong>docker-machine</strong></p> <pre><code>docker-machine create -d virtualbox node1 </code></pre> <p>it is created with tls verification enabled for docker deamon which made things a bit more of a hassle than normal for swarm.</p> <p>I want to create a node with <strong>docker-machine</strong> without tls verification for testing purpose.</p> <p>I tried with:</p> <pre><code>docker-machine create -d virtualbox --engine-tls false node1 </code></pre> <p>and</p> <pre><code>docker-machine create -d virtualbox --engine-tls-verify false node1 </code></pre> <p>and</p> <pre><code>docker-machine create -d virtualbox --engine-opt-tls false node1 </code></pre>
31,122,414
3
0
null
2015-06-08 19:19:07.637 UTC
10
2016-02-11 23:42:17.917 UTC
null
null
null
null
818,094
null
1
14
docker|docker-machine
8,698
<p>try:</p> <pre><code>docker-machine create -d virtualbox --engine-opt tlsverify=false node1 </code></pre> <p>and after running:</p> <pre><code>eval "$(docker-machine env node1)" </code></pre> <p>run:</p> <pre><code>unset DOCKER_TLS_VERIFY </code></pre>
43,724,426
'this' is undefined inside the foreach loop
<p>I am writing some typescript code and iterating an array. Inside the loop, I am trying to access 'this' object to do some processing as:</p> <pre><code>console.log('before iterate, this = ' +this); myarray.days.forEach(function(obj, index) { console.log('before transform, this : ' + this); this.datePipe.transform... }); </code></pre> <p>but this fails, as it complains that 'this' is undefined 'this' object prints correctly as [object object] before/outside the loop, but inside the loop, it is undefined. Why is that? And what is the fix for that?</p>
43,724,448
3
0
null
2017-05-01 18:34:43.293 UTC
8
2019-04-22 15:57:00.41 UTC
null
null
null
null
1,892,775
null
1
48
typescript|typescript2.0|typescript1.8
32,399
<p>You need to either use an <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions" rel="noreferrer">arrow function</a>:</p> <pre><code>myarray.days.forEach((obj, index) =&gt; { console.log('before transform, this : ' + this); this.datePipe.transform... }); </code></pre> <p>Or use the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind" rel="noreferrer">bind method</a>:</p> <pre><code>myarray.days.forEach(function(obj, index) { console.log('before transform, this : ' + this); this.datePipe.transform... }.bind(this)); </code></pre> <p>The reason is that when passing a regular function as a callback, when it is invoked the <code>this</code> is not actually preserved.<br> The two ways which I mentioned above will make sure that the right <code>this</code> scope is preserved for the future execution of the function.</p>
846,257
How can I remove the last seven characters of a hash value in Perl?
<p>I need to cut off the last seven characters of a string (a string that is stored in a hash). What is the easiest way to do that in perl? Many thanks in advance!</p>
846,265
3
1
null
2009-05-10 22:45:37.31 UTC
5
2014-11-16 22:50:58.583 UTC
2010-02-25 01:16:42.943 UTC
null
2,766,176
null
101,289
null
1
22
perl|string
49,785
<p>With <a href="http://perldoc.perl.org/functions/substr.html" rel="noreferrer"><code>substr()</code></a>:</p> <pre><code>substr($string, 0, -7); </code></pre> <p>I suggest you read the Perldoc page on <code>substr()</code> (which I linked to above) before just copying and pasting this into your code. It does what you asked, but <code>substr()</code> is a very useful and versatile function, and I suggest you understand everything you can use it for (by reading the documentation).</p> <p>Also, in the future, please consider Googling your question (or, in the case of Perl, looking it up on Perldoc) before asking it here. You can find great resources on things like this without having to ask questions here. Not to put down your question, but it's pretty simple, and I think if you tried, you could find the answer on your own.</p>
1,309,524
Find parent directory of a path
<p>Is there any way to find the parent directory of a path using <code>NSFileManager</code> or something?</p> <p>e.g. Take this:</p> <blockquote> <p>/path/to/something</p> </blockquote> <p>And turn it into</p> <blockquote> <p>/path/to/</p> </blockquote>
1,309,658
3
0
null
2009-08-21 00:27:45.593 UTC
8
2017-01-08 10:43:52.013 UTC
2017-01-08 10:40:45.793 UTC
null
691,409
null
153,112
null
1
35
objective-c|cocoa|path|nsfilemanager
18,229
<p>The <code>NSString</code> method <code>-stringByDeletingLastPathComponent</code> does just that.</p> <p>You can use it like this:</p> <pre><code>NSLog(@"%@", [@"/tmp/afolder" stringByDeletingLastPathComponent]); </code></pre> <p>And it will log <code>/tmp</code>.</p>
770,013
How to clear previous expectations on an object?
<p>I would like to set up a return value</p> <pre><code>_stubRepository.Stub(Contains(null)).IgnoreArguments().Return(true); </code></pre> <p>but then in a specific test, override that expectation to return false. </p> <p>Something like:</p> <pre><code>_stubRepository.ClearExpectations(); //&lt;- this does not exist, I'm just making something up _stubRepository.Stub(Contains(null)).IgnoreArguments().Return(false); </code></pre> <p>Notice, I do not want the expectation to return false on the second call, I want to override the first expectation.</p> <p>This would help simplify my testing scenario greatly.</p>
770,083
3
0
null
2009-04-20 20:44:10.1 UTC
13
2017-03-07 10:08:48.957 UTC
2017-03-07 10:08:48.957 UTC
null
2,642,204
null
5,056
null
1
63
.net|rhino-mocks
15,607
<p>There are three ways:</p> <p><strong>You can reset the expectations by using BackToRecord</strong></p> <p>I have to admit that I never really used it because it is awkward.</p> <pre><code>// clear expectations, an enum defines which _stubRepository.BackToRecord(BackToRecordOptions.All); // go to replay again. _stubRepository.Replay(); </code></pre> <p><strong>Edit:</strong> Now I use it sometimes, it is actually the cleanest way. There should be an extension method (like Stub) which does it - I think it just got forgotten. I would suggest to write your own.</p> <p><strong>You can use Repeat.Any()</strong></p> <p>It 'breaks' the order of the stubbed definition and "overrides" previous definitions. But it's somehow implicit. I use it sometimes because it is easy to write.</p> <pre><code>_stubRepository.Stub(x =&gt; x.Contains(null)) .IgnoreArguments() .Return(false) .Repeat.Any(); </code></pre> <p><strong>You can create a new mock</strong></p> <p>Trivial, but explicit and easy to understand. It is only a problem if you want to keep plenty of definitions and only change one call.</p> <pre><code>_stubRepository = MockRepository.GenerateMock&lt;IRepository&gt;(); _stubRepository.Stub(x =&gt; x.Contains(null)) .IgnoreArguments() .Return(false); </code></pre>
1,077,347
Hello World in Python
<p>I tried running a python script:</p> <pre><code>print "Hello, World!" </code></pre> <p>And I get this error:</p> <pre><code> File "hello.py", line 1 print "Hello, World!" ^ SyntaxError: invalid syntax </code></pre> <p>What is going on?</p>
1,077,349
3
7
null
2009-07-03 00:27:53.687 UTC
17
2015-02-21 15:19:43.47 UTC
2014-05-10 20:59:50.203 UTC
null
1,398,425
null
100,835
null
1
136
python|python-3.x
160,084
<pre><code>print("Hello, World!") </code></pre> <p>You are probably using Python 3.0, where <code>print</code> is <a href="http://docs.python.org/release/3.0.1/whatsnew/3.0.html#print-is-a-function" rel="noreferrer">now a function</a> (hence the parenthesis) instead of a statement.</p>
36,309,314
Set Firefox profile to download files automatically using Selenium and Java
<p>I want to verify file download using Selenium WebDriver and Java. The file to download is of PDF format. When WebDriver clicks on "Download" link in the AUT, Firefox opens up the following download confirmation window:</p> <p><a href="https://i.stack.imgur.com/TqnYi.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/TqnYi.jpg" alt="Download Confirmation Window"></a></p> <p>I want Firefox to download the file automatically without showing above confirmation window, so I used the below code:</p> <pre><code>FirefoxProfile firefoxProfile=new FirefoxProfile(); firefoxProfile.setPreference("browser.download.folderList",2); firefoxProfile.setPreference("browser.download.manager.showWhenStarting",false); firefoxProfile.setPreference("browser.download.dir",downloadPath); firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk","application/pdf"); WebDriver driver=new FirefoxDriver(firefoxProfile); </code></pre> <p>but still Firefox shows the same window. How can I set Firefox profile so that PDF files are downloaded automatically without showing the confirmation dialogue?</p>
36,309,735
8
2
null
2016-03-30 12:46:05.553 UTC
13
2021-09-24 02:27:38.06 UTC
2019-01-23 10:16:13.757 UTC
null
7,901,720
null
5,912,043
null
1
34
java|selenium-webdriver
55,868
<p>Just like @Jason suggested, it's most probably another mime type. To get the mime type:</p> <ul> <li>Open Developer Tools</li> <li>Go to Network</li> <li>Click on the link to download the pdf</li> <li>In the network panel, select the first request</li> <li>The mime type is the Content-Type from the response header:</li> </ul> <p><a href="https://i.stack.imgur.com/mKd9p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/mKd9p.png" alt="enter image description here" /></a></p> <p>Then to download a PDF with Firefox:</p> <pre><code>FirefoxOptions options = new FirefoxOptions(); options.setPreference(&quot;browser.download.folderList&quot;, 2); options.setPreference(&quot;browser.download.dir&quot;, &quot;C:\\Windows\\temp&quot;); options.setPreference(&quot;browser.download.useDownloadDir&quot;, true); options.setPreference(&quot;browser.download.viewableInternally.enabledTypes&quot;, &quot;&quot;); options.setPreference(&quot;browser.helperApps.neverAsk.saveToDisk&quot;, &quot;application/pdf;text/plain;application/text;text/xml;application/xml&quot;); options.setPreference(&quot;pdfjs.disabled&quot;, true); // disable the built-in PDF viewer WebDriver driver = new FirefoxDriver(options); driver.get(&quot;https://www.mozilla.org/en-US/foundation/documents&quot;); driver.findElement(By.linkText(&quot;IRS Form 872-C&quot;)).click(); </code></pre>
35,262,686
Genymotion virtualization engine not found/plugin loading aborted on Mac
<p>I downloaded Genymotion but cannot get it to work. I keep on getting "virtualization engine not found, plugin loading aborted". I have uninstalled and reinstalled it, force quit and restarted it, and looked at other solutions to no avail. It seems to hit a snag <a href="https://i.stack.imgur.com/whAtk.png" rel="noreferrer">here</a>.</p> <p>I am running on a Mac, OSX Yosemite version 10.10.5.</p>
35,262,743
10
2
null
2016-02-08 05:09:47.12 UTC
5
2019-11-04 03:40:58.99 UTC
null
null
null
null
5,376,626
null
1
75
android|macos|virtual-machine|genymotion
59,856
<p>You have to install Virtualbox to get genymotion to work.</p> <p>Here is the link to download it <a href="https://www.virtualbox.org/wiki/Downloads" rel="noreferrer">https://www.virtualbox.org/wiki/Downloads</a></p>
20,540,877
Correct use for angular-translate in controllers
<p>I'm using <a href="http://angular-translate.github.io/" rel="noreferrer">angular-translate</a> for i18n in an AngularJS application.</p> <p>For every application view, there is a dedicated controller. In the controllers below, I set the value to be shown as the page title.</p> <h2>Code</h2> <h3>HTML</h3> <pre><code>&lt;h1&gt;{{ pageTitle }}&lt;/h1&gt; </code></pre> <h3>JavaScript</h3> <pre><code>.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) { $scope.pageTitle = $filter('translate')('HELLO_WORLD'); }]) .controller('SecondPageCtrl', ['$scope', '$filter', function ($scope, $filter) { $scope.pageTitle = 'Second page title'; }]) </code></pre> <p>I'm loading the translation files using the <a href="https://github.com/PascalPrecht/angular-translate/wiki/Asynchronous-loading" rel="noreferrer">angular-translate-loader-url</a> extension.</p> <h2>Problem</h2> <p>On the initial page load, the translation key is shown instead of the translation for that key. The translation is <code>Hello, World!</code>, but I'm seeing <code>HELLO_WORLD</code>.</p> <p>The second time I go to the page, all is well and the translated version is shown.</p> <p>I assume the issue has to do with the fact that maybe the translation file is not yet loaded when the controller is assigning the value to <code>$scope.pageTitle</code>.</p> <h2>Remark</h2> <p>When using <code>&lt;h1&gt;{{ pageTitle | translate }}&lt;/h1&gt;</code> and <code>$scope.pageTitle = 'HELLO_WORLD';</code>, the translation works perfect from the first time. The problem with this is that I don't always want to use translations (eg. for the second controller I just want to pass a raw string).</p> <h2>Question</h2> <p>Is this a known issue / limitation? How can this be solved?</p>
20,542,535
5
0
null
2013-12-12 10:26:06.863 UTC
53
2018-04-10 21:22:54.33 UTC
2015-04-23 16:42:03.413 UTC
null
1,343,917
null
363,448
null
1
126
javascript|angularjs|angular-translate
178,119
<p><strong>EDIT</strong>: Please see the answer from PascalPrecht (the author of angular-translate) for a better solution.</p> <hr> <p>The asynchronous nature of the loading causes the problem. You see, with <code>{{ pageTitle | translate }}</code>, Angular will watch the expression; when the localization data is loaded, the value of the expression changes and the screen is updated.</p> <p>So, you can do that yourself:</p> <pre><code>.controller('FirstPageCtrl', ['$scope', '$filter', function ($scope, $filter) { $scope.$watch( function() { return $filter('translate')('HELLO_WORLD'); }, function(newval) { $scope.pageTitle = newval; } ); }); </code></pre> <p>However, this will run the watched expression on every digest cycle. This is suboptimal and may or may not cause a visible performance degradation. Anyway it is what Angular does, so it cant be that bad...</p>
24,110,520
Xcode 6 Beta: No such module 'Cocoa'
<p>I'm trying to use the standard Cocoa library in a swift file in Xcode 6 Beta. I followed <a href="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/buildingcocoaapps/index.html#//apple_ref/doc/uid/TP40014216-CH2-XID_0">this instructions</a> but when I import the library</p> <pre><code>import Cocoa </code></pre> <p>XCode complains with the error</p> <pre><code>No such module 'Cocoa' </code></pre> <p>I also tried with the REPL and I have no problems at all. I suppose it's a bug, cause I started different projects and only sometimes I get this error. Any suggestions? I'm using Mavericks (10.9.3)</p>
24,110,545
7
0
null
2014-06-08 20:29:23.553 UTC
1
2016-06-20 15:47:14.07 UTC
2014-06-08 20:32:40.937 UTC
null
509,005
null
960,734
null
1
45
xcode|swift
34,228
<p>You can't <code>import Cocoa</code> from an iOS playground or application. Make sure your code is running in a Cocoa playground (select <strong>OS X > Source</strong> in the new file dialog).</p>
24,190,085
Markdown multiline code blocks in tables when rows have to be specified with one-liners
<p>I have a table:</p> <pre><code>| YAY! | TABLE | \^^/ | 1-liner JSON column! | | ---- | ----- | ---- | -------------------- | | That | has | JSON | `{a: 1, b: 2, c: 3}` | | Here | is | more | `{d: 4, e: 5, f: 6}` | </code></pre> <p>Is there any way for me to insert in multiline code blocks into a generated table cell?</p>
24,190,674
2
0
null
2014-06-12 17:04:56.593 UTC
4
2021-10-21 07:43:27.933 UTC
null
null
null
null
1,708,136
null
1
42
markdown|github-flavored-markdown|apiary.io
38,862
<p>Replace <code>`</code> with <code>&lt;code&gt;</code> tags and use <code>&amp;nbsp;</code> and <code>&lt;br&gt;</code>for indentation.</p> <p>Similarly you can use <code>&lt;pre&gt;</code> tags instead of <code>```</code>.</p>
42,695,917
Laravel 5.4 Disable Register Route
<p>I am trying to disable the register route on my application which is running in Laravel 5.4.</p> <p>In my routes file, I have only the</p> <pre><code>Auth::routes(); </code></pre> <p>Is there any way to disable the register routes?</p>
42,700,000
13
2
null
2017-03-09 12:52:38.89 UTC
15
2020-05-04 07:51:47.083 UTC
2019-01-29 09:45:56.36 UTC
null
1,872,647
null
3,938,343
null
1
47
php|laravel|laravel-5.4
50,181
<p>The <code>code</code>:</p> <pre class="lang-php prettyprint-override"><code>Auth::routes(); </code></pre> <p>its a shorcut for this collection of routes:</p> <pre class="lang-php prettyprint-override"><code>// Authentication Routes... Route::get('login', 'Auth\LoginController@showLoginForm')-&gt;name('login'); Route::post('login', 'Auth\LoginController@login'); Route::post('logout', 'Auth\LoginController@logout')-&gt;name('logout'); // Registration Routes... Route::get('register', 'Auth\RegisterController@showRegistrationForm')-&gt;name('register'); Route::post('register', 'Auth\RegisterController@register'); // Password Reset Routes... Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')-&gt;name('password.request'); Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')-&gt;name('password.email'); Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')-&gt;name('password.reset'); Route::post('password/reset', 'Auth\ResetPasswordController@reset'); </code></pre> <p>So you can substitute the first with the list of routes and comment out any route you don't want in your application.</p> <p><strong>Edit for <code>laravel version =&gt; 5.7</code></strong> </p> <p>In newer versions you can add a parameter to the <code>Auth::routes()</code> function call to disable the register routes:</p> <pre class="lang-php prettyprint-override"><code>Auth::routes(['register' =&gt; false]); </code></pre> <p>The email verification routes were added:</p> <pre class="lang-php prettyprint-override"><code>Route::get('email/verify', 'Auth\VerificationController@show')-&gt;name('verification.notice'); Route::get('email/verify/{id}', 'Auth\VerificationController@verify')-&gt;name('verification.verify'); Route::get('email/resend', 'Auth\VerificationController@resend')-&gt;name('verification.resend'); </code></pre> <p>BTW you can also disable <code>Password Reset</code> and <code>Email Verification</code> routes:</p> <pre class="lang-php prettyprint-override"><code>Auth::routes(['reset' =&gt; false, 'verify' =&gt; false]); </code></pre>
41,527,058
Many to Many relationship in Firebase
<p>I have a Firebase database. I have Companies and Contractors. A Contractor can work for more than one Company and a Company can have multiple Contractors. This is a straightforward many to many relationship. I want to be able to answer the questions about Companies and Contractors: </p> <ol> <li>Given a Company, who are the current Contractors. </li> <li>Given a Contractor what Companies are they working for. </li> </ol> <p>What are the alternatives for structuring the data within firebase?</p>
41,528,908
2
0
null
2017-01-07 22:01:23.877 UTC
20
2017-08-05 10:45:44.64 UTC
2017-09-22 18:01:22.247 UTC
null
-1
null
2,824,087
null
1
42
firebase|firebase-realtime-database|angularfire2|nosql
22,934
<p>The self-answer is indeed one way of modeling this. It's probably the most direct equivalent of how you'd model this in a relational database:</p> <ul> <li>contractors</li> <li>companies</li> <li>companyAndContractorsAssignment (the many-to-many connector table)</li> </ul> <p>An alternative would be to use 4 top-level nodes:</p> <ul> <li>contractors</li> <li>companies</li> <li>companyContractors</li> <li>contractorCompanies</li> </ul> <p>The last two nodes would look like:</p> <pre><code>companyContractors companyKey1 contractorKey1: true contractorKey3: true companyKey2 contractorKey2: true contractorCompanies contractorKey1 companyKey1: true contractorKey2 companyKey2: true contractorKey3 companyKey1: true </code></pre> <p>This bidirectional structure allows you to both look up "contractors for a company" and "companies for a contractor", without either of these needing to be a query. This is bound to be faster, especially as you add contractors and companies.</p> <p>Whether this is necessary for your app, depends on the use-cases you need, the data sizes you expect and much more.</p> <p>Recommended reading <a href="https://highlyscalable.wordpress.com/2012/03/01/nosql-data-modeling-techniques/" rel="noreferrer">NoSQL data modeling</a> and viewing <a href="https://www.youtube.com/playlist?list=PLl-K7zZEsYLlP-k-RKFa7RyNPa9_wCH2s" rel="noreferrer">Firebase for SQL developers</a>. This question was also featured in an <a href="https://youtu.be/HjlQH3RsGcU?t=2m45s" rel="noreferrer">episode of the #AskFirebase youtube series</a>.</p> <h3>Update (2017016)</h3> <p>Somebody posted a <a href="https://stackoverflow.com/questions/41862017/how-to-get-data-within-firebase-when-we-have-many-to-many-relationship/41862505?noredirect=1#comment70933355_41862505">follow-up question that links here</a> about retrieving the actual items from the "contractors" and "companies" nodes. You will need to retrieve those one at a time, since Firebase doesn't have an equivalent to <code>SELECT * FROM table WHERE id IN (1,2,3)</code>. But this operation is not as slow as you may think, because the requests are pipelined over a single connection. Read more about that here: <a href="https://stackoverflow.com/questions/35931526/speed-up-fetching-posts-for-my-social-network-app-by-using-query-instead-of-obse/35932786#35932786">Speed up fetching posts for my social network app by using query instead of observing a single event repeatedly</a>.</p>
6,300,613
Whats the difference between bundle install --deployment and bundle pack
<p>I know they both put the gems in your app in different locations but it seems as if <strong>bundle install --deployment</strong> does a more thorough job. Can I just add the vendor/bundle directory it creates to version control and be done?</p>
6,300,737
3
0
null
2011-06-10 00:00:13.687 UTC
9
2017-10-17 13:37:09.477 UTC
null
null
null
null
141,822
null
1
21
ruby-on-rails|ruby-on-rails-3|gem|bundle|bundler
22,378
<p>Have a look at the description of the two on Bundler's site.</p> <p>Running <code>bundle install --deployment</code> is to be run in the production environment, but will grab the gems from rubygems when run. Read more <a href="http://bundler.io/guides/deploying.html#deploying-your-application" rel="noreferrer">here</a> under the 'Deploying Your Application' heading for the purpose of the <code>--deployment</code> flag.</p> <p><code>bundle package</code> is similar to the old <code>rake rails:gems:freeze</code> command from Rails 2.3. It grabs the gems and packages them in vendor/cache. From the bundler site <a href="http://bundler.io/man/bundle-package.1.html" rel="noreferrer">here</a>: </p> <blockquote> <p>You can use this to avoid a dependency on rubygems.org at deploy time, or if you have private gems that are not in a public repository</p> </blockquote>
5,710,391
Converting Python dict to kwargs?
<p>I want to build a query for sunburnt(solr interface) using class inheritance and therefore adding key - value pairs together. The sunburnt interface takes keyword arguments. How can I transform a dict <code>({'type':'Event'})</code> into keyword arguments <code>(type='Event')</code>?</p>
5,710,402
3
0
null
2011-04-19 00:46:46.273 UTC
82
2019-05-18 22:30:17.313 UTC
2012-09-26 08:01:19.133 UTC
null
157,176
null
714,357
null
1
434
python|dictionary|keyword-argument
201,606
<p>Use the <a href="http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists" rel="noreferrer">double-star</a> (aka <a href="https://stackoverflow.com/questions/2322355/proper-name-for-python-operator/2322384#2322384">double-splat?</a>) operator:</p> <pre><code>func(**{'type':'Event'}) </code></pre> <p>is equivalent to</p> <pre><code>func(type='Event') </code></pre>
6,274,457
set isolation level for postgresql stored procedures
<p>Hopefully a simple question, but one for which I haven't readily found a decent answer. I'm reliably informed that stored procedures (user-defined DB functions) in PostgreSQL (specifically, version 9.0.4) are inherently transactional, inasmuch as they are called through a SELECT statement which itself is a transaction. So how does one choose the isolation level of the stored procedure? I believe in other DBMSs the desired transactional block would be wrapped in a START TRANSACTION block for which the desired isolation level is an optional parameter.</p> <p>As a specific made-up example, say I want to do this:</p> <pre><code>CREATE FUNCTION add_new_row(rowtext TEXT) RETURNS VOID AS $$ BEGIN INSERT INTO data_table VALUES (rowtext); UPDATE row_counts_table SET count=count+1; END; $$ LANGUAGE plpgsql SECURITY DEFINER; </code></pre> <p>And imagine I want to make sure this function is always performed as a serializable transaction (yes, yes, PostgreSQL SERIALIZABLE isn't proper serializable, but that's not the point). I don't want to require it to be called as</p> <pre><code>START TRANSACTION ISOLATION LEVEL SERIALIZABLE; SELECT add_new_row('foo'); COMMIT; </code></pre> <p>So how do I push the required isolation level down into the function? I believe I cannot just put the isolation level in the <code>BEGIN</code> statement, as <a href="http://www.postgresql.org/docs/current/static/plpgsql-structure.html" rel="noreferrer">the manual says</a></p> <blockquote> <p>It is important not to confuse the use of BEGIN/END for grouping statements in PL/pgSQL with the similarly-named SQL commands for transaction control. PL/pgSQL's BEGIN/END are only for grouping; they do not start or end a transaction. Functions and trigger procedures are always executed within a transaction established by an outer query — they cannot start or commit that transaction, since there would be no context for them to execute in.</p> </blockquote> <p>The most obvious approach to me would be to use <code>SET TRANSACTION</code> somewhere in the function definition, e.g.,:</p> <pre><code>CREATE FUNCTION add_new_row(rowtext TEXT) RETURNS VOID AS $$ BEGIN SET TRANSACTION ISOLATION LEVEL SERIALIZABLE; INSERT INTO data_table VALUES (rowtext); UPDATE row_counts_table SET count=count+1; END; $$ LANGUAGE plpgsql SECURITY DEFINER; </code></pre> <p>While this would be accepted, it's not clear than I can rely on this to work. The <a href="http://www.postgresql.org/docs/current/static/sql-set-transaction.html" rel="noreferrer">documentation</a> for <code>SET TRANSACTION</code> says</p> <blockquote> <p>If SET TRANSACTION is executed without a prior START TRANSACTION or BEGIN, it will appear to have no effect, since the transaction will immediately end.</p> </blockquote> <p>Which leaves me puzzled, since if I call a solitary <code>SELECT add_new_row('foo');</code> statement I would expect (provided I haven't disabled autocommit) the SELECT to be running as a single-line transaction with the session default isolation level.</p> <p>The <a href="http://www.postgresql.org/docs/current/static/sql-set-transaction.html" rel="noreferrer">manual</a> also says:</p> <blockquote> <p>The transaction isolation level cannot be changed after the first query or data-modification statement (SELECT, INSERT, DELETE, UPDATE, FETCH, or COPY) of a transaction has been executed.</p> </blockquote> <p>So what happens if the function is called from within a transaction with a lower isolation level, e.g.,:</p> <pre><code>START TRANSACTION ISOLATION LEVEL READ COMMITTED; UPDATE row_counts_table SET count=0; SELECT add_new_row('foo'); COMMIT; </code></pre> <p>For a bonus question: does the language of the function make any difference? Would one set the isolation level differently in PL/pgSQL than in plain SQL? </p> <p>I'm a fan of standards and documented best practices, so any decent references would be appreciated.</p>
6,283,190
4
5
null
2011-06-08 05:11:14.173 UTC
6
2012-02-02 17:14:42.91 UTC
2011-06-08 11:50:56.357 UTC
null
290,182
null
290,182
null
1
28
postgresql|stored-procedures|isolation-level
21,579
<p>You can't do that.</p> <p>What you could do is have your function check what the current transaction isolation level is and abort if it's not the one you want. You can do this by running <code>SELECT current_setting('transaction_isolation')</code> and then checking the result.</p>
5,911,267
What are "sums-and-products" data structures?
<p>A <a href="http://wcook.blogspot.com/" rel="noreferrer">recent blog post on William Cook's Fusings</a> mentions:</p> <blockquote> <p>The key point is that structures in Ensō are viewed holistically as graphs, not as individual values or traditional sums-and-products data structures.</p> </blockquote> <p>What are the traditional sums-and-products data structures he is referring to?</p>
5,914,867
4
1
null
2011-05-06 12:15:48.67 UTC
34
2020-11-17 09:10:37.9 UTC
2011-05-06 17:32:23.18 UTC
null
19,750
null
244,526
null
1
52
data-structures|programming-languages|types|type-systems|algebraic-data-types
7,856
<blockquote> <p>What are the traditional sums-and-products data structures he is referring to?</p> </blockquote> <p>In type theory, regular data structures can be described in terms of sums, products and recursive types. This leads to an <em>algebra</em> for describing data structures (and so-called <em>algebraic data types</em>). Such data types are common in statically typed functional languages, such as ML or Haskell.</p> <p><strong>Products</strong></p> <p>Products can be thought of as the type-theoretic view of &quot;structs&quot; or &quot;tuples&quot;.</p> <p>Formally, PFPL, Ch 14:</p> <blockquote> <p>The binary <strong>product</strong> of two types consists of ordered pairs of values, one from each type in the order specified. The associated eliminatory forms are projections, which select the first and second component of a pair. The nullary product, or unit, type consists solely of the unique “null tuple” of no values, and has no associated eliminatory form.</p> </blockquote> <p><strong>Sums</strong></p> <p>Sum types express choice between variants of a data structure. Sometimes they are called &quot;union types&quot; (as in C). Many languages have no notion of sum types.</p> <p>PFPL, ch 15:</p> <blockquote> <p>Most data structures involve alternatives such as the distinction between a leaf and an interior node in a tree, or a choice in the outermost form of a piece of abstract syntax. Importantly, the choice determines the structure of the value. For example, nodes have children, but leaves do not, and so forth. These concepts are expressed by sum types, specifically the binary sum, which offers a choice of two things, and the nullary sum, which offers a choice of no things.</p> </blockquote> <p><strong>Recursive types</strong></p> <p>Along with products and sums, we can introduce recursion, so a type may be defined (partially) in terms of itself. Nice examples include trees and lists.</p> <pre><code> data List a = Empty | a : List a data Tree a = Nil | Node a (Tree a) (Tree a) </code></pre> <p><strong>Algebra of sums, products and recursion</strong></p> <p>Give a type, say <code>Int</code>, we can start building up a notation for algebraic expressions that describe data structures:</p> <p>A lone variable:</p> <p><code>Int</code></p> <p>A product of two types (denoting a pair):</p> <p><code>Int * Bool</code></p> <p>A sum of two types (denoting a choice between two types):</p> <p><code>Int + Bool</code></p> <p>And some constants:</p> <p><code>1 + Int</code></p> <p>where <code>1</code> is the unit type, <code>()</code>.</p> <p>Once you can describe types this way, you get some cool power for free. Firstly, a very concise notation for describing data types, secondly, some results transfer from other algebras (e.g. <a href="http://www.cs.nott.ac.uk/%7Etxa/publ/jpartial.pdf" rel="noreferrer">differentiation works on data structures</a>).</p> <p><strong>Examples</strong></p> <p>The unit type, <code>data () = ()</code></p> <p><img src="https://i.stack.imgur.com/G3qVe.png" alt="enter image description here" /></p> <p>A tuple, the simplest <strong>product type</strong>: <code>data (a,b) = (a,b)</code></p> <p><img src="https://i.stack.imgur.com/Nyihb.png" alt="enter image description here" /></p> <p>A simple <strong>sum type</strong>, <code>data Maybe a = Nothing | Just a</code></p> <p><img src="https://i.stack.imgur.com/fla7R.png" alt="enter image description here" /></p> <p>and its alternative,</p> <p><img src="https://i.stack.imgur.com/om6zJ.png" alt="enter image description here" /></p> <p>and a <strong>recursive type</strong>, the type of linked lists: <code>data [a] = [] | a : [a]</code></p> <p><img src="https://i.stack.imgur.com/ayo1S.png" alt="enter image description here" /></p> <p>Given these, you can build quite complicated structures by combining sums, products and recursive types. E.g. the simple notation for a list of products of sums of products: <code>[(Maybe ([Char], Double), Integer)]</code> gives rise to some quite complicated trees:</p> <p><img src="https://i.stack.imgur.com/LQK2j.png" alt="enter image description here" /></p> <hr /> <p><em>References</em></p> <ul> <li>Practical Foundations for Programming Language, Robert Harper, 2011, <a href="http://www.cs.cmu.edu/%7Erwh/plbook/book.pdf" rel="noreferrer">http://www.cs.cmu.edu/~rwh/plbook/book.pdf</a></li> <li>Quick intro to the algebra of data types, <a href="http://blog.lab49.com/archives/3011" rel="noreferrer">http://blog.lab49.com/archives/3011</a> <em><strong>(Link appears to be dead. Internet Archive link: <a href="http://web-old.archive.org/web/20120321033340/http://blog.lab49.com/archives/3011" rel="noreferrer">http://web-old.archive.org/web/20120321033340/http://blog.lab49.com/archives/3011</a>)</strong></em></li> <li>Species and Functors and Types, Oh My!, Brent Yorgey, <a href="http://www.cis.upenn.edu/%7Ebyorgey/papers/species-pearl.pdf" rel="noreferrer">http://www.cis.upenn.edu/~byorgey/papers/species-pearl.pdf</a> -- has a very good overview of the algebra, Haskell data types, and the connection with <em>combinatorial species</em> from mathematics.</li> </ul>
1,535,576
Google Chart HtmlHelper for Asp.net Mvc
<p>Are there any HtmlHelper Extensions for <a href="http://code.google.com/apis/chart/" rel="noreferrer">Google Chart Api</a>? (I like to use for some basic charts, e.g. Pie Chart, Bar Chart)</p> <p>Soe Moe</p>
1,535,636
2
0
null
2009-10-08 04:07:57.38 UTC
9
2009-10-08 14:37:07.953 UTC
2009-10-08 12:32:57.96 UTC
null
40,015
null
102,940
null
1
10
c#|asp.net-mvc|google-visualization
8,540
<p>Google says that you insert a chart like this:</p> <pre><code>&lt;img src="http://chart.apis.google.com/chart? chs=250x100 &amp;amp;chd=t:60,40 &amp;amp;cht=p3 &amp;amp;chl=Hello|World" alt="Sample chart" /&gt; </code></pre> <p>So it should be easy enough to write an HtmlHelper like this (untested):</p> <pre><code>namespace System.Web.Mvc.Html { public static class GoogleChartHelpers { public static string GoogleChart (string cht, string chd, string chs, string chl) { return "&lt;img source='http://chart.apis.google.com/chart?cht=" + cht + "&amp;amp;chd=" + chd + "&amp;amp;chs=" + chs + "&amp;amp;chl=" + chl + "' /&gt;; } } } </code></pre> <p>and call it like this:</p> <pre><code>&lt;%= Html.GoogleChart("P3","t:60,40","250x100","Hello|World") %&gt; </code></pre> <p>which should insert this into your page:</p> <p><img src="https://chart.apis.google.com/chart?cht=p3&amp;chd=t:60,40&amp;chs=250x100&amp;chl=Hello|World" alt="alt text"></p>
2,053,214
How to create a case insensitive copy of a string field in SOLR?
<p>How can I create a copy of a string field in case insensitive form? I want to use the typical "string" type and a case insensitive type. The types are defined like so:</p> <pre><code> &lt;fieldType name="string" class="solr.StrField" sortMissingLast="true" omitNorms="true" /&gt; &lt;!-- A Case insensitive version of string type --&gt; &lt;fieldType name="string_ci" class="solr.StrField" sortMissingLast="true" omitNorms="true"&gt; &lt;analyzer type="index"&gt; &lt;tokenizer class="solr.KeywordTokenizerFactory"/&gt; &lt;filter class="solr.LowerCaseFilterFactory" /&gt; &lt;/analyzer&gt; &lt;analyzer type="query"&gt; &lt;tokenizer class="solr.KeywordTokenizerFactory"/&gt; &lt;filter class="solr.LowerCaseFilterFactory" /&gt; &lt;/analyzer&gt; &lt;/fieldType&gt; </code></pre> <p>And an example of the field like so:</p> <pre><code>&lt;field name="destANYStr" type="string" indexed="true" stored="true" multiValued="true" /&gt; &lt;!-- Case insensitive version --&gt; &lt;field name="destANYStrCI" type="string_ci" indexed="true" stored="false" multiValued="true" /&gt; </code></pre> <p>I tried using CopyField like so:</p> <pre><code>&lt;copyField source="destANYStr" dest="destANYStrCI" /&gt; </code></pre> <p>But, apparently CopyField is called on source and dest before any analyzers are invoked, so even though I've specified that dest is case-insensitive through anaylyzers the case of the values copied from source field are preserved.</p> <p>I'm hoping to avoid re-transmitting the value in the field from the client, at record creation time.</p>
2,060,960
2
0
null
2010-01-12 23:20:57.037 UTC
14
2017-02-07 17:31:37.07 UTC
2017-02-07 17:31:37.07 UTC
null
154,461
null
154,461
null
1
28
solr|case-insensitive
36,529
<p>With no answers from SO, I followed up on the SOLR users list. I found that my string_ci field was not working as expected before even considering the effects of copyField. Ahmet Arslan explains why the "string_ci" field should be using solr.TextField and not solr.StrField:</p> <blockquote> <p>From apache-solr-1.4.0\example\solr\conf\schema.xml :</p> <p>"The StrField type is not analyzed, but indexed/stored verbatim." </p> <p>"solr.TextField allows the specification of custom text analyzers specified as a tokenizer and a list of token filters."</p> </blockquote> <p>With an example he provdied and a slight tweak by myself, the following field definition seems to do the trick, and now the CopyField works as expected as well.</p> <pre><code> &lt;fieldType name="string_ci" class="solr.TextField" sortMissingLast="true" omitNorms="true"&gt; &lt;analyzer&gt; &lt;tokenizer class="solr.KeywordTokenizerFactory"/&gt; &lt;filter class="solr.LowerCaseFilterFactory" /&gt; &lt;/analyzer&gt; &lt;/fieldType&gt; </code></pre> <p>The destANYStrCI field will have a case preserved value stored but will provide a case insensitive field to search on. CAVEAT: case insensitive wildcard searching cannot be done since wild card phrases bypass the query analyzer and will not be lowercased before matching against the index. This means that the characters in wildcard phrases must be lowercase in order to match.</p>
59,785,124
VS Code Regex find and replace with lowercase, use \l or \L if possible
<p>Is there a way to do a find and replace (regex) all uppercase characters in the matching strings with lowercase ones? Preferably in VS Code or IntelliJ I already have my regex ready.</p> <p>Edit: To be clear I already know who to find the matches. But looking for that function to replace all uppercase matches with lowercase ones</p>
59,793,139
2
0
null
2020-01-17 10:04:22.107 UTC
5
2021-07-25 09:53:42.763 UTC
2020-07-01 22:44:56.257 UTC
null
836,330
null
2,291,704
null
1
45
visual-studio-code|intellij-15
20,197
<ul> <li>Press <kbd>Ctrl</kbd> + <kbd>F</kbd></li> <li>Select <code>.*</code> button and enter your RegEx</li> <li>Press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> (Windows) or <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> (Mac) to select all matched results</li> <li>Press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> (Windows) or <kbd>Cmd</kbd> + <kbd>Shift</kbd> + <kbd>P</kbd> (Mac)</li> <li>Choose <code>Transform to Lowercase</code></li> </ul> <p>If you want to modify only part of the matching text you have to do 1 step extra.</p> <p>If you press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> in the Find dialog it selects the full matching text but you can't move the (multi) cursors and make a partial selection.</p> <p>After entering the regex, VSC will show you which parts will match the find.</p> <ul> <li><strong>Click somewhere in the file</strong></li> <li>Press <kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>L</kbd> (Select All)</li> </ul> <p>or</p> <ul> <li>Press <kbd>Alt</kbd> + <kbd>Enter</kbd> (<strong>in</strong> the Find dialog)</li> </ul> <p>Now you can move the (multi) cursors and make a partial selection and apply the needed transform.</p>
29,132,891
Vagrant/VirtualBox VM provisioning: rbenv installs successfully but subsequent uses in script fail
<p>I am using Vagrant + VirtualBox to set up a virtual machine for my Rails app. I am working on cleaning up a <code>.sh</code> provisioning script that is referenced in <code>Vagrantfile</code> like so:</p> <pre><code>config.vm.provision "shell", path: "script/provision-script.sh" </code></pre> <p>The provision script does a number of things, but towards the end it is supposed to install rbenv Ruby versioning and then use rbenv to install Ruby 2.2.1. That part of the provision script looks like this:</p> <pre><code>echo "setting up rbenv" # execute the remaining commands as vagrant user, instead of root sudo -H -u vagrant bash -c "git clone https://github.com/sstephenson/rbenv.git ~vagrant/.rbenv" sudo -H -u vagrant bash -c "git clone https://github.com/sstephenson/ruby-build.git ~vagrant/.rbenv/plugins/ruby-build" sudo -H -u vagrant bash -c "git clone https://github.com/sstephenson/rbenv-gem-rehash.git ~vagrant/.rbenv/plugins/rbenv-gem-rehash" echo "setting up rbenv environment in bash" echo 'export PATH="$HOME/.rbenv/bin:$PATH"' &gt;&gt; ~vagrant/.bashrc echo 'eval "$(rbenv init -)"' &gt;&gt; ~vagrant/.bashrc # start new vagrant shell so rbenv will work echo "building ruby" su vagrant rbenv install 2.2.1 &amp;&amp; rbenv global 2.2.1 &amp;&amp; rbenv rehash &amp;&amp; cd /path/to/my/app &amp;&amp; gem install bundler rake &amp;&amp; rbenv rehash &amp;&amp; bundle &amp;&amp; rbenv rehash </code></pre> <p>Everything up to the <code>rbenv install...</code> part works correctly. Installing ruby fails with the following error:</p> <pre><code>==&gt; default: setting up rbenv ==&gt; default: Cloning into '/home/vagrant/.rbenv'... ==&gt; default: Cloning into '/home/vagrant/.rbenv/plugins/ruby-build'... ==&gt; default: Cloning into '/home/vagrant/.rbenv/plugins/rbenv-gem-rehash'... ==&gt; default: setting up rbenv environment in bash ==&gt; default: building ruby ==&gt; default: /tmp/vagrant-shell: line 73: rbenv: command not found </code></pre> <p>The script then finishes. I can open the vm with <code>vagrant ssh</code> and then successfully run <code>rbenv install 2.2.1</code>, so I'm guessing that during provisioning a new vagrant shell is not actually being started. I was under the impression that this should happen with <code>su vagrant</code> right before <code>rbenv install 2.2.1</code>. </p> <p>What can I do to make sure that a new shell is initialized during this provisioning and that the <code>rbenv</code> command will work?</p>
30,106,828
3
1
null
2015-03-18 21:18:49.857 UTC
9
2020-03-11 09:59:40.81 UTC
null
null
null
null
1,066,615
null
1
13
ruby-on-rails|ruby|ubuntu|vagrant|virtualbox
3,256
<p>I had a similar problem because I was trying to <strong>install rbenv</strong> and the vagrant provisioning was giving me the error:</p> <pre><code>==&gt; default: /tmp/vagrant-shell: line 10: rbenv: command not found </code></pre> <p><strong>First of all, it is very important to understand that vagrant provisioning script is running in sudo mode</strong>. So, when in the script we refer to ~/ path, we are referring to /root/ path and not to /home/vagrant/ path. The problem is that I was installing rbenv for the root user and after trying to call rbenv command from a vagrant user and, of course, it didn't work!</p> <p>So, what I did is specify the vagrant to run the provisioner NOT in sudo user, adding <strong>privileged: false</strong>:</p> <pre><code>config.vm.provision :shell, privileged: false, inline: $script </code></pre> <p>Then in my script I considered everything as being called from the vagrant user. <strong>Here @Casper answer helped me a lot, because it works only specifying: sudo -H -u vagrant bash -i -c '......'</strong></p> <blockquote> <p>Since you just updated .bashrc with a new path and other settings, you will want to run "sudo bash" with the -i option. This will force bash to simulate an interactive login shell, and therefore read .bashrc and load the correct path for rbenv.</p> </blockquote> <p><strong>Below is my final Vagrantfile.</strong></p> <pre><code># -*- mode: ruby -*- # vi: set ft=ruby : $script = &lt;&lt;SCRIPT sudo apt-get -y update sudo apt-get -y install curl git-core python-software-properties ruby-dev libpq-dev build-essential nginx libsqlite3-0 libsqlite3-dev libxml2 libxml2-dev libxslt1-dev nodejs postgresql postgresql-contrib imagemagick git clone https://github.com/sstephenson/rbenv.git ~/.rbenv echo 'export PATH="$HOME/.rbenv/bin:$PATH"' &gt;&gt; ~/.bashrc echo 'eval "$(rbenv init -)"' &gt;&gt; ~/.bashrc source ~/.bashrc git clone https://github.com/sstephenson/ruby-build.git ~/.rbenv/plugins/ruby-build sudo -H -u vagrant bash -i -c 'rbenv install 2.1.3' sudo -H -u vagrant bash -i -c 'rbenv rehash' sudo -H -u vagrant bash -i -c 'rbenv global 2.1.3' sudo -H -u vagrant bash -i -c 'gem install bundler --no-ri --no-rdoc' sudo -H -u vagrant bash -i -c 'rbenv rehash' sudo -u postgres createdb --locale en_US.utf8 --encoding UTF8 --template template0 development echo "ALTER USER postgres WITH PASSWORD \'develop\';" | sudo -u postgres psql SCRIPT VAGRANTFILE_API_VERSION = "2" Vagrant.configure(VAGRANTFILE_API_VERSION) do |config| config.vm.box = "hashicorp/precise64" config.vm.network "forwarded_port", guest: 3000, host: 3000 # config.vm.provider :virtualbox do |vb| # vb.customize ["modifyvm", :id, "--memory", "1024"] # end config.vm.provision :shell, privileged: false, inline: $script end </code></pre> <p>Hope it will be helpful to someone else.</p>
5,666,445
jquery how to get form element types, names and values
<p>I know I can get the name/value relationship by using </p> <pre><code>$(#form).serializeArray(); </code></pre> <p>But is there a way to get the whole enchilada, type, name and value with one call?</p>
5,666,635
5
0
null
2011-04-14 16:29:44.66 UTC
5
2017-12-11 15:48:00.65 UTC
2017-12-11 15:48:00.65 UTC
null
479,156
null
468,455
null
1
12
jquery|forms|elements
44,532
<p>Use <code>$("form :input")</code></p> <p>Per the <a href="http://api.jquery.com/input-selector/" rel="noreferrer">docs</a>:</p> <blockquote> <p>Description: Selects all input, textarea, select and button elements. </p> </blockquote> <p>Now to your question,</p> <blockquote> <p>there a way to get the whole enchilada, type, name and value with one call?</p> </blockquote> <p>If you simply want to loop through the items, </p> <pre><code>$("form :input").each(function(index, elm){ //Do something amazing... }); </code></pre> <p>But if you want to return some sort of structure, you can use <code>.map()</code></p> <pre><code>var items = $("form :input").map(function(index, elm) { return {name: elm.name, type:elm.type, value: $(elm).val()}; }); </code></pre> <p>Or if you simply want to get the elements</p> <pre><code>$("form :input").get() </code></pre> <p><br/> <strong><a href="http://jsfiddle.net/markcoleman/kkKb8/" rel="noreferrer">Example of this on jsfiddle</a></strong></p>
5,953,169
Avoid having subversion modify Linux file permissions.
<p>All of my code base is being stored in a subversion repository that I disperse amongst my load balanced Apache web servers, making it easy to check out code, run updates, and seamlessly get my code in development onto production.</p> <p>One of the inconveniences that I'm sure there is a easy work around for (other than executing a script upon every checkout), is getting the Linux permissions set (back) on files that are updated or checked out with subversion. Our security team has it set that the <code>Owner</code> and <code>Group</code> set in the <em>httpd.conf</em> files, and all directories within the <code>documentRoot</code> receive permissions of 700, all non-executable files (e.g. *.php, *.smarty, *.png) receive Linux permissions of 600, all executable files receive 700 (e.g. *.sh, *.pl, *.py). All files must have owner and group set to <code>apache:apache</code> in order to be read by the httpd service since only the file owner is set to have access via the permissions.</p> <p>Every time I run an <code>svn update</code>, or <code>svn co</code>, even though the files may not be created (i.e. <code>svn update</code>), I'm finding that the ownership of the files is getting set to the account that is running the svn commands, and often times, the file permissions are getting set to something other than what they were originally (i.e. a .htm file before an update is 600, but after and <code>svn update</code>, it gets set to 755, or even 777).</p> <p>What is the easiest way to bypass subversion's attempts at updating the file permissions and ownership? Is there something that can be done within the svn client, or on the Linux server to retain the original file permissions? I'm running RHEL5 (and now 6 on a few select instances).</p>
5,953,417
6
0
null
2011-05-10 16:20:12.347 UTC
5
2017-03-15 02:59:39.243 UTC
2014-03-31 22:18:34.307 UTC
null
1,288,306
null
740,318
null
1
32
linux|svn|file-permissions
24,151
<p>the owner of the files will be set to the user that is running the svn command because of how it implements the underlying up command - it removes and replaces files that are updated, which will cause the ownership to 'change' to the relevant user. The only way to prevent this is to actually perform the svn up as the user that the files are supposed to be owned as. If you want to ensure that they're owned by a particular user, then run the command as that user.</p> <p>With regards to the permissions, svn is only obeying the umask settings of the account - it's probably something like 066 - in order to ensure that the file is inaccessible to group and other accounts, you need to issue 'umask 077' before performing the svn up, this ensures that the files are only accessible to the user account issuing the command.</p> <p>I'd pay attention to the security issue of deploying the subversion data into the web server unless the .svn directories are secured.</p>
6,084,089
(Re)named std::pair members
<p>Instead of writing <code>town-&gt;first</code> I would like to write <code>town-&gt;name</code>. Inline named accessors (<a href="https://stackoverflow.com/q/1500064/341970">Renaming first and second of a map iterator</a> and <a href="http://compgroups.net/comp.lang.c++.moderated/Named-std-pair-members" rel="noreferrer">Named std::pair members</a>) are the best solutions I have found so far. My problem with named accessors is the loss of type safety: <code>pair&lt;int,double&gt;</code> may refer to <code>struct { int index; double value; }</code> or to <code>struct { int population; double avg_temp; }</code>. Can anyone propose a simple approach, perhaps something similar to traits?</p> <p>I often want to return a pair or a tuple from a function and it is quite tiring to introduce a new type like <code>struct city { string name; int zipcode; }</code> and its ctor every time. I am thrilled to learn about boost and C++0x but I need a pure C++03 solution without boost.</p> <p><strong>Update</strong></p> <p>Re andrewdski's question: yes, a (hypothetical) syntax like <code>pair&lt;int=index, double=value&gt;</code> which would create a distinct type from <code>pair&lt;int=population, double=avg_temp&gt;</code> would meet your requirement. I do not even mind having to implement a custom pair/tuple template class ONCE and just passing a 'name traits' template argument to it approprietly when I need a new type. I have no idea how that 'name traits' would look like. Maybe it's impossible.</p>
6,084,866
10
19
null
2011-05-21 19:54:59.473 UTC
7
2022-07-14 05:06:43.79 UTC
2017-05-23 10:31:16.803 UTC
null
-1
null
341,970
null
1
36
c++|templates|stl|typedef|traits
15,421
<p>I don't see how you can possibly do better than</p> <pre><code>struct city { string name; int zipcode; }; </code></pre> <p>There's nothing non-essential there. You need the types of the two members, your whole question is predicated around giving names to the two members, and you want it to be a unique type.</p> <p>You do know about aggregate initialization syntax, right? You don't need a constructor or destructor, the compiler-provided ones are just fine.</p> <p>Example: <strike><a href="http://ideone.com/IPCuw">http://ideone.com/IPCuw</a></strike></p> <hr> <p>Type safety requires that you introduce new types, otherwise <code>pair&lt;string, int&gt;</code> is ambiguous between (name, zipcode) and (population, temp).</p> <p>In C++03, returning a new tuple requires either:</p> <pre><code>city retval = { "name", zipcode }; return retval; </code></pre> <p>or writing a convenience constructor:</p> <pre><code>city::city( std::string newName, int newZip ) : name(newName), zipcode(newZip) {} </code></pre> <p>to get</p> <pre><code>return city("name", zipcode); </code></pre> <p>With C++0x, however, you will be allowed to write</p> <pre><code>return { "name", zipcode }; </code></pre> <p>and no user-defined constructor is necessary.</p>
5,777,483
Drop all databases from server
<p>I have a server (SQL Server 2005) with more than 300 databases. I don't want to right-click one by one and select <code>Delete</code>.</p> <p>How can I delete all databases easily?</p>
5,777,545
10
4
null
2011-04-25 10:31:01.99 UTC
10
2022-02-16 04:23:40.08 UTC
2011-12-05 04:55:31.937 UTC
null
674,039
null
539,693
null
1
50
sql|sql-server|sql-server-2005
71,625
<p>You can do this through the SSMS GUI. Select the <code>Databases</code> node then <kbd>F7</kbd> to bring up Object Explorer Details, Select all databases that you want to delete, Hit "Delete" and select the "Close Existing Connections" and "Continue after error" options.</p> <p>Alternatively through TSQL you can do</p> <pre><code>EXEC sp_MSforeachdb ' IF DB_ID(''?'') &gt; 4 BEGIN EXEC('' ALTER DATABASE [?] SET SINGLE_USER WITH ROLLBACK IMMEDIATE DROP DATABASE [?] '') END' </code></pre>
5,648,420
How to get all columns' names for all the tables in MySQL?
<p>Is there a fast way of getting all column names from all tables in <code>MySQL</code>, without having to list all the tables?</p>
5,648,713
11
1
null
2011-04-13 11:27:50.52 UTC
52
2022-07-04 18:54:30.707 UTC
2019-06-12 22:02:05.59 UTC
null
42,223
null
704,164
null
1
233
mysql|database-schema|database-metadata
231,225
<pre><code>select column_name from information_schema.columns where table_schema = 'your_db' order by table_name,ordinal_position </code></pre>
5,844,672
Delete an element from a dictionary
<p>How do I delete an item from a dictionary in Python?</p> <p>Without modifying the original dictionary, how do I obtain another dict with the item removed?</p>
5,844,692
18
5
null
2011-04-30 21:20:57.93 UTC
197
2022-06-06 05:13:07.33 UTC
2022-06-06 05:13:07.33 UTC
null
365,102
null
301,032
null
1
2,007
python|dictionary|del
2,424,077
<p>The <a href="http://docs.python.org/reference/simple_stmts.html#the-del-statement" rel="noreferrer"><code>del</code> statement</a> removes an element:</p> <pre><code>del d[key] </code></pre> <p>Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a <em>new</em> dictionary, make a copy of the dictionary:</p> <pre><code>def removekey(d, key): r = dict(d) del r[key] return r </code></pre> <p>The <code>dict()</code> constructor makes a <em>shallow copy</em>. To make a deep copy, see the <a href="https://docs.python.org/library/copy.html" rel="noreferrer"><code>copy</code> module</a>.</p> <hr /> <p>Note that making a copy for every dict <code>del</code>/assignment/etc. means you're going from constant time to linear time, and also using linear space. For small dicts, this is not a problem. But if you're planning to make lots of copies of large dicts, you probably want a different data structure, like a HAMT (as described in <a href="https://stackoverflow.com/a/50341031/908494">this answer</a>).</p>
5,745,814
How to change ProgressBar's progress indicator color in Android
<p>I have set Horizontal <code>ProgressBar</code>.</p> <p>I would like to change the progress color to yellow.</p> <pre><code>&lt;ProgressBar android:id="@+id/progressbar" android:layout_width="80dip" android:layout_height="20dip" android:focusable="false" style="?android:attr/progressBarStyleHorizontal" /&gt; </code></pre> <p>The problem is, the progress color is different in different devices. So, I want it to fix the progress color.</p>
5,745,923
19
1
null
2011-04-21 14:54:23.597 UTC
69
2022-03-28 08:38:14.347 UTC
2019-09-06 11:42:58.713 UTC
null
10,553,536
null
385,343
null
1
200
android|android-progressbar
237,893
<p>I copied this from one of my apps, so there's prob a few extra attributes, but should give you the idea. This is from the layout that has the progress bar:</p> <pre><code>&lt;ProgressBar android:id="@+id/ProgressBar" style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent" android:layout_height="wrap_content" android:indeterminate="false" android:maxHeight="10dip" android:minHeight="10dip" android:progress="50" android:progressDrawable="@drawable/greenprogress" /&gt; </code></pre> <p>Then create a new drawable with something similar to the following (In this case <code>greenprogress.xml</code>):</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;layer-list xmlns:android="http://schemas.android.com/apk/res/android"&gt; &lt;item android:id="@android:id/background"&gt; &lt;shape&gt; &lt;corners android:radius="5dip" /&gt; &lt;gradient android:angle="270" android:centerColor="#ff5a5d5a" android:centerY="0.75" android:endColor="#ff747674" android:startColor="#ff9d9e9d" /&gt; &lt;/shape&gt; &lt;/item&gt; &lt;item android:id="@android:id/secondaryProgress"&gt; &lt;clip&gt; &lt;shape&gt; &lt;corners android:radius="5dip" /&gt; &lt;gradient android:angle="270" android:centerColor="#80ffb600" android:centerY="0.75" android:endColor="#a0ffcb00" android:startColor="#80ffd300" /&gt; &lt;/shape&gt; &lt;/clip&gt; &lt;/item&gt; &lt;item android:id="@android:id/progress"&gt; &lt;clip&gt; &lt;shape&gt; &lt;corners android:radius="5dip" /&gt; &lt;gradient android:angle="270" android:endColor="#008000" android:startColor="#33FF33" /&gt; &lt;/shape&gt; &lt;/clip&gt; &lt;/item&gt; &lt;/layer-list&gt; </code></pre> <p>You can change up the colors as needed, this will give you a green progress bar. </p>
6,222,731
Should css class names like 'floatleft' that directly describe the attached style be avoided?
<p>Lots of websites use class names like <code>floatleft</code>, <code>clearfloat</code>, <code>alignright</code>, <code>small</code>, <code>center</code> etc that describe the style that is attached to the class. This seems to make sense so when writing new content you can easily wrap (for example) <code>&lt;div class="clearfloat"&gt;...&lt;/div&gt;</code> around your element to make it behave the way you want.</p> <p>My question is, doesn't this style of naming classes go against the idea of separating content from presentation? Putting <code>class="floatleft"</code> on an element is clearly putting presentation information into the HTML document.</p> <p>Should class names like this that directly describe the attached style be avoided, and if so what alternative is there?</p> <hr> <p>To clarify, this isn't just a question of what to name classes. For example a semantically accurate document might look something like:</p> <pre><code>&lt;div class="foo"&gt;Some info about foo&lt;/div&gt; ... &lt;div class="bar"&gt;Info about unrelated topic bar&lt;/div&gt; ... &lt;div class="foobar"&gt;Another unrelated topic&lt;/div&gt; </code></pre> <p>Say all these divs need to clear floats, the css would look something like:</p> <pre><code>div.foo, div.bar, div.foobar { clear:both; } </code></pre> <p>This starts to get ugly as the number of these clearing elements increases - whereas a single <code>class="clearfloat"</code> would serve the same purpose. Is it recommended to group elements based on the attached styles to avoid repetition in the CSS, even if this means presentational information creeps into the HTML?</p> <hr> <p><strong>Update</strong>: Thanks for all the answers. The general consensus seems to be to avoid these class names in favour of semantic names, or at least use them sparingly provided they don't hinder maintenance. I think the important thing is that changes in the layout should not require excessive changes to the markup (although a few people said minor changes are okay if it makes overall maintenance easier). Thanks to those who suggested other methods to keep CSS code smaller as well.</p>
6,222,812
20
4
null
2011-06-03 03:40:22.9 UTC
11
2019-11-17 02:00:54.947 UTC
2014-05-13 12:59:40.8 UTC
null
769,220
null
692,456
null
1
51
html|css|presentation
6,665
<p>It's great until you re-design, and <code>narrow</code> is highlighted yellow, <code>center</code> converts better left-justified, and the image you called <code>floatleft</code> now belongs on the right.</p> <p>I'll admit to the sin of using <code>floatleft</code> and <code>clear</code> as CSS class names, but it is much easier to maintain your CSS if you choose names that relate to the semantic meaning of the content, like <code>feedback</code> and <code>heroimage</code>.</p>
18,061,981
The class does not have property
<p>In my entity:</p> <pre><code>@Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(unique=true, nullable=false) private int tId; .... public int getTId() { return this.tId; } public void setTId(int tId) { this.tId = tId; } </code></pre> <p>And code in my JSF page:</p> <pre><code>&lt;ui:repeat value="#{techCat.techsOfCat}" var="post"&gt; &lt;h:outputText value="#{post.getTId()}"/&gt; ... &lt;/ui:repeat&gt; </code></pre> <p>The result is good. But if i code:</p> <pre><code>&lt;ui:repeat value="#{techCat.techsOfCat}" var="post"&gt; &lt;h:outputText value="#{post.tId}"/&gt; ... &lt;/ui:repeat&gt; </code></pre> <p>I faced an error:</p> <pre><code>value="#{post.tId}": The class 'model.Technology' does not have the property 'tId'. </code></pre> <p>I really don't understand that error. Can you explain to me? Thanks</p>
18,062,103
1
0
null
2013-08-05 15:30:12.037 UTC
null
2013-08-05 16:19:49.29 UTC
2013-08-05 16:19:49.29 UTC
null
157,882
null
2,376,270
null
1
9
jsf|properties|javabeans|el
38,120
<p>The error means that correct getters and setters could not be located for your property. The correct syntax for your getter and setter should be:</p> <pre><code>public int gettId() { return tId; } public void settId(int tId) { this.tId = tId; } </code></pre> <p>If you are not sure- always use code generation for your getters and setters.</p> <p>If you are interested in the <a href="https://stackoverflow.com/a/8969525/1611957">specific convention</a>, your getter and setter will relate to <code>TId</code> not <code>tId</code>.</p>
18,044,712
Best Way to store configuration setting inside my asp.net mvc application
<p>I am working on a asp.net mvc web application that perform some API calls to other web applications. but currently I am storing the API username, API password and API URL inside my code. As follow:-</p> <pre><code>using (var client = new WebClient()) { // client.Headers[HttpRequestHeader.Accept] = "AddAsset"; var query = HttpUtility.ParseQueryString(string.Empty); foreach (string key in formValues) { query[key] = this.Request.Form[key]; } query["username"] = "testuser"; query["password"] = "……"; query["assetType"] = "Rack"; query["operation"] = "AddAsset"; var url = new UriBuilder("http://win-spdev:8400/servlets/AssetServlet"); url.Query = query.ToString(); try { </code></pre> <p>But storing these setting inside my code will not be flexible in case I need to change the API call settings, and it is not secure. So what is the best way to store these setting . I was thinking to create two database tables one for storing the URL(and there might be multiple URLs sin the future). And another table to store the username and password. So is creating database tables the right way to store these settings.</p>
18,044,748
1
1
null
2013-08-04 15:47:43.2 UTC
8
2022-08-04 14:00:27.5 UTC
null
null
null
null
1,146,775
null
1
20
asp.net-mvc
18,933
<p><strong>2022 UPDATE:</strong> Now in .NET Core you should use the new Configuration API (<code>appSettings.json</code> or other providers / <code>IConfiguration</code> class injected into your classes/controllers), but the same principles apply. Read more about .NET Core configuration <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0" rel="nofollow noreferrer">here</a>.</p> <hr /> <p>You should use the Web.Config file (<a href="http://msdn.microsoft.com/en-us/library/ms228060%28v=vs.100%29.aspx" rel="nofollow noreferrer">Configuration API</a>) to store these settings. This way you will be able to update settings without having to recompile your entire application every time. That's the most standard way to store settings in a Web (MVC or WebForms) application, and gives you the possibility to <a href="http://msdn.microsoft.com/en-us/library/zhhddkxy%28v=vs.100%29.aspx" rel="nofollow noreferrer">encrypt sensitive settings</a> transparently to your application.</p> <p>You can access stored settings using the <a href="http://msdn.microsoft.com/en-us/library/system.web.configuration.webconfigurationmanager%28v=vs.100%29.aspx" rel="nofollow noreferrer">WebConfigurationManager</a> class. <a href="http://www.dotnetperls.com/appsettings" rel="nofollow noreferrer">Here</a> you can find some examples of how to use it.</p> <p><strong>Code sample:</strong></p> <p>Web.config appSettings:</p> <pre><code>&lt;appSettings&gt; &lt;add key=&quot;ApiUserName&quot; value=&quot;MySampleUsername&quot; /&gt; &lt;/appSettings&gt; </code></pre> <p>C# Code:</p> <pre><code>string userName = System.Web.Configuration.WebConfigurationManager.AppSettings[&quot;ApiUserName&quot;]; </code></pre>
39,227,100
Updating Python using 'PIP'
<p>just like we install packages like Matplotlib, using pip command in the cmd (pip install matplotlib) can we also update to newer version of python by some pip command?</p> <p><img src="https://i.stack.imgur.com/r108C.png" alt="screenshot"></p>
39,227,632
1
1
null
2016-08-30 12:08:14.953 UTC
1
2020-06-19 16:25:53.26 UTC
2020-06-19 16:25:53.26 UTC
null
3,890,673
null
6,365,011
null
1
17
python|pip
45,546
<p>Pip is designed for managing python packages and <strong>not python versions</strong> to update Python you must download the version you wish from their <a href="https://www.python.org/downloads/" rel="noreferrer">site in the download selection.</a></p> <h1>Simple Answer</h1> <p>No you cannot</p>
39,036,457
React create constants file
<p>How to create constants file like: key - value in ReactJs,</p> <pre><code>ACTION_INVALID = "This action is invalid!" </code></pre> <p>and to use that in other components</p> <pre><code>errorMsg = myConstClass.ACTION_INVALID; </code></pre>
39,036,632
5
2
null
2016-08-19 10:14:36.033 UTC
12
2022-03-10 21:52:04.587 UTC
null
null
null
null
5,490,549
null
1
82
javascript|reactjs|constants
115,043
<p>I'm not entirely sure I got your question but if I did it should be quite simple:</p> <p>From my understanding you just want to create a file with constants and use it in another file.</p> <p>fileWithConstants.js:</p> <pre><code>export const ACTION_INVALID = "This action is invalid!" export const CONSTANT_NUMBER_1 = 'hello I am a constant'; export const CONSTANT_NUMBER_2 = 'hello I am also a constant'; </code></pre> <p>fileThatUsesConstants.js:</p> <pre><code>import * as myConstClass from 'path/to/fileWithConstants'; const errorMsg = myConstClass.ACTION_INVALID; </code></pre> <p>If you are using react you should have either webpack or packager (for react-native) so you should have babel which can translate your use of export and import to older js.</p>
44,300,989
Get max value from row of a dataframe in python
<p>This is my dataframe df</p> <pre><code>a b c 1.2 2 0.1 2.1 1.1 3.2 0.2 1.9 8.8 3.3 7.8 0.12 </code></pre> <p>I'm trying to get max value from each row of a dataframe, I m expecting output like this</p> <pre><code>max_value 2 3.2 8.8 7.8 </code></pre> <p>This is what I have tried</p> <pre><code>df[len(df.columns)].argmax() </code></pre> <p>I'm not getting proper output, any help would be much appreciated. Thanks</p>
44,301,022
2
0
null
2017-06-01 07:19:16.53 UTC
8
2017-06-01 08:22:29.42 UTC
null
null
null
null
6,123,057
null
1
28
python|pandas|dataframe|max
98,733
<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.max.html" rel="noreferrer"><code>max</code></a> with <code>axis=1</code>:</p> <pre><code>df = df.max(axis=1) print (df) 0 2.0 1 3.2 2 8.8 3 7.8 dtype: float64 </code></pre> <p>And if need new column:</p> <pre><code>df['max_value'] = df.max(axis=1) print (df) a b c max_value 0 1.2 2.0 0.10 2.0 1 2.1 1.1 3.20 3.2 2 0.2 1.9 8.80 8.8 3 3.3 7.8 0.12 7.8 </code></pre>
5,474,316
Why JSF saves the state of UI components on server?
<ol> <li><p><strong>Until what point in time does JSF save the state of UI components on the server side &amp; when exactly is the UI component's state information removed</strong> from the server memory? As a logged-in user on the application navigates though pages, will the state of components keep on accumulating on the server?</p> </li> <li><p>I don't understand <strong>what is the benefit of keeping UI components state on server !?</strong> Isn't directly passing the validated/converted data to managed beans enough? Can I or should I try to avoid it?</p> </li> <li><p>Doesn't that consume <em>too much</em> memory on the server side, if there are thousands of concurrent user sessions? I have an application where users can post blogs on certain topics. This blogs are quite large in size. When there will be post back or request for viewing the blogs, <strong>will this big page data be saved as a part of the state of components?</strong> This would eat up too much memory. Isn't this a concern ?</p> </li> </ol> <hr /> <h1>Update 1:</h1> <p>Now, it is no longer necessary to save state while using JSF. A high performance Stateless JSF implementation is available for use. See this <a href="http://industrieit.com/blog/2011/11/stateless-jsf-high-performance-zero-per-request-memory-overhead/" rel="noreferrer">blog</a> &amp; <a href="https://stackoverflow.com/questions/10385340/jsf-state-saving-initially-to-server-on-session-timeout-transfer-to-client">this question</a> for relevant details &amp; discussion. Also, there is an open <a href="http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1055" rel="noreferrer">issue</a> to include in JSF specs, an option to provide stateless mode for JSF. (P.S. Consider voting for the issues <a href="http://java.net/jira/browse/JAVASERVERFACES_SPEC_PUBLIC-1055" rel="noreferrer">this</a> &amp; <a href="https://issues.apache.org/jira/browse/MYFACES-3465" rel="noreferrer">this</a> if this is a useful feature for you.)</p> <br/> <h1>Update 2 (24-02-2013):</h1> <p>A great news that <strong>Mojarra 2.1.19</strong> is out with <strong>stateless mode</strong>!</p> <p>See here:</p> <p><a href="http://weblogs.java.net/blog/mriem/archive/2013/02/08/jsf-going-stateless?force=255" rel="noreferrer">http://weblogs.java.net/blog/mriem/archive/2013/02/08/jsf-going-stateless?force=255</a></p> <p><a href="http://java.net/jira/browse/JAVASERVERFACES-2731" rel="noreferrer">http://java.net/jira/browse/JAVASERVERFACES-2731</a></p> <p><a href="http://balusc.blogspot.de/2013/02/stateless-jsf.html" rel="noreferrer">http://balusc.blogspot.de/2013/02/stateless-jsf.html</a></p>
5,475,564
1
0
null
2011-03-29 14:39:21.73 UTC
100
2020-09-10 16:36:56.263 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
530,153
null
1
111
java|jsf|jakarta-ee|state-saving
54,040
<blockquote> <p><em>Why does JSF need to save the state of UI components on the server side ?</em></p> </blockquote> <p>Because HTTP is stateless and JSF is stateful. The JSF component tree is subject to dynamic (programmatic) changes. JSF simply needs to know the exact state as it was when the form had been displayed to the enduser, so that it can successfully process the whole JSF lifecycle based on the information provided by the original JSF component tree when the form has been submitted back to the server. The component tree provides information about the request parameter names, the necessary converters/validators, the bound managed bean properties and action methods.</p> <hr /> <blockquote> <p><em>Until what point in time does JSF save the state of UI components on the server side and when exactly is the UI component's state information removed from the server memory?</em></p> </blockquote> <p>Those two questions seem to boil down to the same. Anyway, this is implementation specific and also dependent on whether the state is saved on server or client. A bit decent implementation will remove it when it has been expired or when the queue is full. Mojarra for example has a default limit of 15 logical views when state saving is set to session. This is configureable with the following context param in <code>web.xml</code>:</p> <pre class="lang-xml prettyprint-override"><code>&lt;context-param&gt; &lt;param-name&gt;com.sun.faces.numberOfLogicalViews&lt;/param-name&gt; &lt;param-value&gt;15&lt;/param-value&gt; &lt;/context-param&gt; </code></pre> <p>See also <a href="https://wikis.oracle.com/display/GlassFish/JavaServerFacesRI#JavaServerFacesRI-Whatcontextparametersareavailableandwhatdotheydo%3F" rel="noreferrer">Mojarra FAQ</a> for other Mojarra-specific params and this related answer <a href="https://stackoverflow.com/questions/4105439/jsf-numberofviewsinsession-vs-numberoflogicalviews-and-viewexpiredexception/16050424#16050424">com.sun.faces.numberOfViewsInSession vs com.sun.faces.numberOfLogicalViews</a></p> <hr /> <blockquote> <p><em>As a logged-in user on the application navigates though pages, will the state of components keep on accumulating on the server?</em></p> </blockquote> <p>Technically, that depends on the implementation. If you're talking about page-to-page navigation (just GET requests) then Mojarra won't save anything in session. If they are however POST requests (forms with commandlinks/buttons), then Mojarra will save state of each form in session until the max limit. This enables the enduser to open multiple forms in different browser tabs in the same session.</p> <p>Or, when the state saving is set to client, then JSF won't store anything in session. You can do that by the following context param in <code>web.xml</code>:</p> <pre class="lang-xml prettyprint-override"><code>&lt;context-param&gt; &lt;param-name&gt;javax.faces.STATE_SAVING_METHOD&lt;/param-name&gt; &lt;param-value&gt;client&lt;/param-value&gt; &lt;/context-param&gt; </code></pre> <p>It will then be serialized to an encrypted string in a hidden input field with the name <code>javax.faces.ViewState</code> of the form.</p> <hr /> <blockquote> <p><em>I dont understand what the benefit of keeping the UI component's state on the server side is. Isn't directly passing the validated/converted data to managed beans enough? Can/should I try to avoid it?</em></p> </blockquote> <p>That's not enough to ensure the integrity and robustness of JSF. JSF is a dynamic framework with a single entry point of control. Without a state management, one would be able spoof/hack HTTP requests in a certain way (e.g. manipulating <code>disabled</code>, <code>readonly</code> and <code>rendered</code> attributes), to let JSF do different -and potentially hazardful- things. It would even be prone to CSRF attacks and phishing.</p> <hr /> <blockquote> <p><em>And won't that consume too much memory on the server side, if there are thousands of concurrent user sessions? I have an application where users can post blogs on certain topics. This blogs are quite large in size. When there will be post back or request for viewing the blogs, the large blogs will be saved as a part of the state of components. This would consume too much memory. Isn't this a concern?</em></p> </blockquote> <p>Memory is particularly cheap. Just give the appserver enough memory. Or if network bandwidth is cheaper to you, just switch state saving to client side. To find the best match, just stresstest and profile your webapp with expected max amount of concurrent users and then give the appserver 125% ~ 150% of maximum measured memory.</p> <p>Note that JSF 2.0 has improved a lot in state management. It's possible to save partial state (e.g. <em>only</em> the <code>&lt;h:form&gt;</code> will be saved instead of the whole stuff from <code>&lt;html&gt;</code> all the way to the end). Mojarra for example does that. An average form with 10 input fields (each with a label and message) and 2 buttons would take no more than 1KB. With 15 views in session, that should be no more than 15KB per session. With ~1000 concurrent user sessions, that should be no more than 15MB.</p> <p>Your concern should be more focused on the real objects (managed beans and/or even DB entities) in session or application scope. I've seen lot of codes and projects which unnecessarily duplicates the entire database table into Java's memory in flavor of a session scoped bean where Java is been used instead of SQL to filter/group/arrange the records. With ~1000 records, that would easily go over 10MB <em>per user session</em>.</p>
14,282,322
jQuery validate, validation not working
<p>I have got a simple signup form that uses jQuery validate to validate the contents of the form. but it doesnt seem to be working. My servlet fires and the form is submitted with invalid data regardless of the jQuery at the top of my page. Below is my code. Can anyone please help?</p> <p>Script code:</p> <pre><code>&lt;head&gt; &lt;title&gt;Sign Up&lt;/title&gt; &lt;meta charset="iso-8859-1"&gt; &lt;link rel="stylesheet" href="style/style.css" type="text/css"&gt; &lt;!--[if lt IE 9]&gt;&lt;script src="scripts/html5shiv.js"&gt;&lt;/script&gt;&lt;![endif]--&gt; &lt;script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.js" type="text/javascript"&gt; &lt;/script&gt; &lt;script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"&gt; &lt;/script&gt; &lt;script type="text/javascript"&gt; $().ready(function() { // validate the comment form when it is submitted $("#signup").validate(); // validate signup form on keyup and submit $("#signup").validate({ rules: { firstname: "required", lastname: "required", address1: "required", city: "required", county: "required", postcode: "required", password_s: { required: true, minlength: 5 }, password_s_con: { required: true, minlength: 5, equalTo: "#password_s" }, email: { required: true, email: true }, agree: "required" }, messages: { firstname: "Please enter your first name", lastname: "Please enter your last name", address1: "Please enter your addres", city: "Please enter your city/town", county: "Please enter your county", postcode: "Please enter your postcode", password: { required: "Please provide a password", minlength: "Your password must be at least 5 characters long" }, confirm_password: { required: "Please provide a password", minlength: "Your password must be at least 5 characters long", equalTo: "Please enter the same password as above" }, email: "Please enter a valid email address", agree: "Please accept our policy" } }); }); &lt;/script&gt; &lt;/head&gt; </code></pre> <p>The Form:</p> <pre><code>&lt;table align="left"&gt; &lt;tr&gt;&lt;td align="left"&gt; &lt;form name="signup" id="signup" action="SignUpServlet" method="post"&gt; &lt;table width="400px" align="right" class=""&gt; &lt;fieldset&gt; &lt;legend&gt;Sign Up:&lt;/legend&gt; &lt;tr&gt; &lt;td&gt;First Name:&lt;/td&gt; &lt;td&gt;&lt;input type="text" id="firstname" name="firstname" required="required"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Last Name:&lt;/td&gt;&lt;td&gt;&lt;input type="text" id="lastname" name="lastname" required="required"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Address Line 1:&lt;/td&gt;&lt;td&gt; &lt;input type="text" id="address1" name="address1" required="required"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Address Line 2:&lt;/td&gt;&lt;td&gt; &lt;input type="text" id="address2" name="address2"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;City:&lt;/td&gt;&lt;td&gt; &lt;input type="text" id="city" name="city" required="required"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;County:&lt;/td&gt;&lt;td&gt;&lt;input type="text" id="county" name="county" required="required"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Postcode:&lt;/td&gt; &lt;td&gt;&lt;input type="text" id="postcode" name="postcode" required="required"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Phone:&lt;/td&gt;&lt;td&gt; &lt;input type="text" id="phone" name="phone"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Email Address:&lt;/td&gt;&lt;td&gt; &lt;input type="text" id="email_s" name="email_s" required="required"&gt;*&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Password:&lt;/td&gt;&lt;td&gt; &lt;input type="password" id="password_s" name="password_s" required="required"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Confirm Password:&lt;/td&gt;&lt;td&gt; &lt;input type="password" id="password_s_con" name="password_s_con" required="required"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Privacy Policy:&lt;/td&gt;&lt;td&gt; &lt;input type="checkbox" class="checkbox" id="agree" name="agree" required="required"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt;&lt;td&gt; &lt;input type="submit" id="lf_submit" value="submit"&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/fieldset&gt; &lt;/table&gt; &lt;/form&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td align="left"&gt; &lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; </code></pre>
14,282,660
1
0
null
2013-01-11 16:23:13.767 UTC
1
2015-03-04 19:14:57.913 UTC
2013-01-11 16:49:19.097 UTC
null
594,235
null
1,851,487
null
1
2
jquery|jquery-validate
61,046
<p>Firstly, you do not need to call <code>.validate()</code> twice. It's redundant and superfluous, so remove the first one, and naturally keep the one that contains the options.</p> <pre><code>$().ready(function() { // validate the comment form when it is submitted $("#signup").validate(); // &lt;-- REMOVE THIS // validate signup form on keyup and submit $("#signup").validate({ </code></pre> <p><code>.validate()</code> is called once within <code>DOM Ready</code> to initialize the form. All of the validation events such as <code>submit</code>, <code>keyup</code>, etc. are automatic unless you over-ride them in the plugin options.</p> <p>Secondly, you are <em>incorrectly</em> including jQuery <em>after</em> the plugin.</p> <p>No matter which jQuery plugins you use, <strong>jQuery ALWAYS needs to be included FIRST...</strong></p> <pre><code>&lt;script src="http://code.jquery.com/jquery-1.8.3.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.10.0/jquery.validate.js" type="text/javascript"&gt;&lt;/script&gt; </code></pre> <p><strong>Working Demo of Your Code:</strong> <a href="http://jsfiddle.net/qUYvS/"><strong>http://jsfiddle.net/qUYvS/</strong></a></p> <p><strong>Documentation:</strong> <a href="http://jqueryvalidation.org/">http://jqueryvalidation.org/</a></p>
49,073,043
Get Github Pages Site found in Google Search Results
<p>I have a site built with Jekyll Now on GitHub and I want it to appear in a google search. If I just google my GitHub username followed by 'GitHub' and 'io', it does not find my site. How do I get google to find my site in a google search?</p>
49,073,325
3
1
null
2018-03-02 16:12:28.487 UTC
18
2022-07-26 04:27:04.133 UTC
2019-03-18 21:53:16.383 UTC
null
2,171,044
null
9,244,664
null
1
35
github-pages|google-search
33,704
<p>You have to create a Google Search Console account and add your page, then typically you just drop a "marker" file in the root (Search Console generates this) so that Google can confirm you really own the page.</p> <p><a href="https://www.google.com/webmasters/tools/home" rel="noreferrer">Google Search Console</a></p> <p><a href="https://support.google.com/webmasters/answer/6332964?hl=en&amp;ref_topic=4564315" rel="noreferrer">Instructions</a></p> <p>(Since the instructions are long and have many links to sub-steps, I'm only providing the link.)</p> <p>Also, if you're going to use a registered domain name, set that up <em>before</em> you register the site for search.</p> <p>(Edit: Technically you don't <em>have</em> to do this, sooner or later Google will find you... but this will give your content a much higher-quality score.)</p>
42,451,189
How to calculate the counts of each distinct value in a pyspark dataframe?
<p>I have a column filled with a bunch of states' initials as strings. My goal is to how the count of each state in such list.</p> <p>For example: <code>(("TX":3),("NJ":2))</code> should be the output when there are two occurrences of <code>"TX"</code> and <code>"NJ"</code>.</p> <p>I'm fairly new to pyspark so I'm stumped with this problem. Any help would be much appreciated.</p>
42,452,414
2
1
null
2017-02-25 02:11:33.88 UTC
4
2020-01-02 10:35:12.87 UTC
2017-02-25 02:16:57.21 UTC
null
5,606,836
null
7,148,245
null
1
45
python|dataframe|pyspark
84,624
<p>I think you're looking to use the DataFrame idiom of <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.groupBy" rel="noreferrer">groupBy</a> and <a href="https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame.count" rel="noreferrer">count</a>.</p> <p>For example, given the following dataframe, one state per row:</p> <pre><code>df = sqlContext.createDataFrame([('TX',), ('NJ',), ('TX',), ('CA',), ('NJ',)], ('state',)) df.show() +-----+ |state| +-----+ | TX| | NJ| | TX| | CA| | NJ| +-----+ </code></pre> <p>The following yields:</p> <pre><code>df.groupBy('state').count().show() +-----+-----+ |state|count| +-----+-----+ | TX| 2| | NJ| 2| | CA| 1| +-----+-----+ </code></pre>
42,308,291
Resize images on the fly in CloudFront and get them in the same URL instantly: AWS CloudFront -> S3 -> Lambda -> CloudFront
<p><strong>TLDR:</strong> We have to trick CloudFront 307 redirect caching by creating new cache behavior for responses coming from our Lambda function.</p> <p>You will not believe how close we are to achieve this. We have stucked so badly in the last step.</p> <p>Business case:</p> <p>Our application stores images in S3 and serves them with CloudFront in order to avoid any geographic slow downs around the globe. Now, we want to be really flexible with the design and to be able to request new image dimentions directly in the CouldFront URL! Each new image size will be created on demand and then stored in S3, so the second time it is requested it will be served really quickly as it will exist in S3 and also will be cached in CloudFront.</p> <p>Lets say the user had uploaded the image chucknorris.jpg. Only the original image will be stored in S3 and wil be served on our page like this:</p> <p>//xxxxx.cloudfront.net/chucknorris.jpg</p> <p>We have calculated that we now need to display a thumbnail of 200x200 pixels. Therefore we put the image src to be in our template:</p> <p>//xxxxx.cloudfront.net/chucknorris-200x200.jpg</p> <p>When this new size is requested, the amazon web services have to provide it on the fly in the same bucket and with the requested key. This way the image will be directly loaded in the same URL of CloudFront.</p> <p>I made an ugly drawing with the architecture overview and the workflow on how we are doing this in AWS:</p> <p><a href="https://i.stack.imgur.com/rJuh1.png" rel="noreferrer"><img src="https://i.stack.imgur.com/rJuh1.png" alt="enter image description here" /></a></p> <p>Here is how Python Lambda ends:</p> <pre><code>return { 'statusCode': '301', 'headers': {'location': redirect_url}, 'body': '' } </code></pre> <p>The problem:</p> <p>If we make the Lambda function redirect to S3, it works like a charm. If we redirect to CloudFront, it goes into redirect loop because CloudFront caches 307 (as well as 301, 302 and 303). As soon as our Lambda function redirects to CloudFront, CloudFront calls the API Getaway URL instead of fetching the image from S3:</p> <p><a href="https://i.stack.imgur.com/4ofTY.png" rel="noreferrer"><img src="https://i.stack.imgur.com/4ofTY.png" alt="enter image description here" /></a></p> <p>I would like to create new cache behavior in CloudFront's <code>Behaviors</code> settings tab. This behavior should not cache responses from Lambda or S3 (don't know what exactly is happening internally there), but should still cache any followed requests to this very same resized image. I am trying to set path pattern <code>-\d+x\d+\..+$</code>, add the ARN of the Lambda function in add &quot;Lambda Function Association&quot; and set Event Type <code>Origin Response</code>. Next to that, I am setting the &quot;Default TTL&quot; to <code>0</code>.</p> <p>But I cannot save the behavior due to some error:</p> <p><a href="https://i.stack.imgur.com/vs89F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/vs89F.png" alt="enter image description here" /></a></p> <p>Are we on the right way, or is the idea of this &quot;Lambda Function Association&quot; totally different?</p>
42,332,204
2
1
null
2017-02-17 22:13:52.337 UTC
15
2017-03-02 13:01:05.433 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
3,865,171
null
1
25
amazon-web-services|caching|amazon-s3|aws-lambda|amazon-cloudfront
11,750
<p>Finally I was able to solve it. Although this is not really a structural solution, it does what we need.</p> <p>First, thanks to the answer of Michael, I have used path patterns to match all media types. Second, the Cache Behavior page was a bit misleading to me: indeed the Lambda association is for Lambda@Edge, although I did not see this anywhere in all the tooltips of the cache behavior: all you see is just Lambda. This feature cannot help us as we do not want to extend our AWS service scope with Lambda@Edge just because of that particular problem.</p> <p>Here is the solution approach:<br> I have defined multiple cache behaviors, one per media type that we support:</p> <p><a href="https://i.stack.imgur.com/GaKOi.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GaKOi.png" alt="enter image description here"></a></p> <p>For each cache behavior I set the <code>Default TTL</code> to be <code>0</code>.</p> <p>And the most important part: In the Lambda function, I have added a <code>Cache-Control</code> header to the resized images when putting them in S3:</p> <pre><code>s3_resource.Bucket(BUCKET).put_object(Key=new_key, Body=edited_image_obj, CacheControl='max-age=12312312', ContentType=content_type) </code></pre> <p>To validate that everything works, I see now that the new image dimention is served with the cache header in CloudFront:</p> <p><a href="https://i.stack.imgur.com/3lp9U.png" rel="noreferrer"><img src="https://i.stack.imgur.com/3lp9U.png" alt="enter image description here"></a></p>
51,308,613
Angular 6 material - how to get date and time from matDatepicker?
<p>I have this piece of code in my html:</p> <pre><code>&lt;mat-form-field&gt; &lt;input matInput [matDatepicker]="myDatepicker" placeholder="Choose a date" [(ngModel)]="model.value" name="value"&gt; &lt;mat-datepicker-toggle matSuffix [for]="myDatepicker"&gt;&lt;/mat-datepicker-toggle&gt; &lt;mat-datepicker #myDatepicker&gt;&lt;/mat-datepicker&gt; &lt;/mat-form-field&gt; </code></pre> <p>With this i'm able to get date with this format: <code>YYY-MM-DDThh:mm:ss:millisZ</code>. <br>Using matDatepicker i'm able to select the date but i need after the date selection to select the time too.<br> Is possible to achieve this result using matDatepicker <strong>ONLY</strong>?<br> Thanks</p>
51,309,204
3
1
null
2018-07-12 14:45:53.767 UTC
4
2022-03-18 21:02:26.367 UTC
2019-12-22 02:52:09.367 UTC
null
9,935,369
null
9,935,369
null
1
7
angular
48,805
<p>No, as of now, it is not possible to choose <code>time</code> from <code>matDatePicker</code>. There is still an open issue on <a href="https://github.com/angular/material2/issues/5648" rel="noreferrer">github</a> regarding this feature.</p> <p>Summary of the issue thread :</p> <p>Alternatively you can use one of the following to have <code>dateTimePicker</code> for your project.</p> <ol> <li><p><a href="https://github.com/SteveDunlap13/MaterialTimeControl" rel="noreferrer">MaterialTimeControl</a> - Material Design with Angular Material, CDK, and Flex Layouts</p></li> <li><p><a href="https://github.com/casni14/amazing-time-picker" rel="noreferrer">amazing-time-picker</a> - Not built with Angular Material, but built to be compatible with it</p></li> <li><p><a href="https://danielykpan.github.io/date-time-picker/" rel="noreferrer">date-time-picker</a> - Not fully Material Design, but built with the CDK</p></li> </ol>
32,989,426
How to insert into db in spring-data?
<p>I want to make a request that inserts data into my database. The table has 4 columns: ID_DOCUMENT (PK), ID_TASK, DESCRIPTION, FILEPATH</p> <p><strong>Entity</strong></p> <pre><code>... @Column(name = "ID_TASK") private Long idTask; @Column(name = "DESCRIPTION") private String description; @Column(name = "FILEPATH") private String filepath; ... </code></pre> <p><strong>Repository</strong></p> <pre><code>@Modifying @Query("insert into TaskDocumentEntity c (c.idTask, c.description, c.filepath) values (:id,:description,:filepath)") public void insertDocumentByTaskId(@Param("id") Long id,@Param("description") String description,@Param("filepath") String filepath); </code></pre> <p><strong>Controller</strong></p> <pre><code>@RequestMapping(value = "/services/tasks/addDocument", method = RequestMethod.POST) @ResponseBody public void set(@RequestParam("idTask") Long idTask,@RequestParam("description") String description,@RequestParam("filepath") String filepath){ //TaskDocumentEntity document = new TaskDocumentEntity(); taskDocumentRepository.insertDocumentByTaskId(idTask,descriere,filepath); } </code></pre> <p>When I run my test, I get this error: <em>Caused by: org.hibernate.hql.ast.QuerySyntaxException: expecting OPEN, found 'c' near line 1, column 32 [insert into TaskDocumentEntity c (c.idTask, c.descriere, c.filepath) values (:id,:descriere,:filepath)]</em> I tried to remove the alias c, and still doesn`t work.</p>
32,990,359
2
2
null
2015-10-07 10:04:55.76 UTC
1
2017-08-17 22:42:22.897 UTC
null
null
null
null
1,521,976
null
1
6
spring|spring-data
52,753
<p>Spring data provides out of the box <code>save</code> method used for insertion to database - no need to use <code>@Query</code>. Take a look at core concepts of springData (<a href="http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.core-concepts" rel="noreferrer">http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#repositories.core-concepts</a>)</p> <p>thus in your controller just create object <code>TaskDocumentEntity</code> and pass it to repository</p> <pre><code>@RequestMapping(value = "/services/tasks/addDocument", method = RequestMethod.POST) @ResponseBody public void set(@RequestParam("idTask") Long idTask,@RequestParam("description") String description,@RequestParam("filepath") String filepath){ // assign parameters to taskDocumentEntity by constructor args or setters TaskDocumentEntity document = new TaskDocumentEntity(idTask,descriere,filepath); taskDocumentRepository.save(document); } </code></pre>
9,644,786
How to translate timezone full names to tz abbreviations?
<p>In a Rails 3.x app I need to display time zone abbreviations (EST, PST, CST, etc.) rather than the full time zone name. I've seen a number of discussions that seem to address the issue, but in overly verbose manners.</p> <p><strong>Is there a gem or a very concise method to handle this that could be used to map them properly?</strong></p>
13,052,441
5
0
null
2012-03-10 07:37:58.507 UTC
2
2020-12-10 14:40:21.713 UTC
2012-03-20 19:19:41.797 UTC
null
320,681
null
320,681
null
1
28
ruby-on-rails|ruby|ruby-on-rails-3
16,816
<p>For the current time zone:</p> <pre><code>Time.zone.now.strftime('%Z') </code></pre> <p>Or for a list of time zones:</p> <pre><code>ActiveSupport::TimeZone.us_zones.map do |zone| Time.now.in_time_zone(zone).strftime('%Z') end </code></pre> <p>It works, but it still seems like there should be a better way...</p>
9,266,822
Pattern matching vs if-else
<p>I'm novice in Scala. Recently I was writing a hobby app and caught myself trying to use pattern matching instead of if-else in many cases.</p> <pre><code>user.password == enteredPassword match { case true =&gt; println("User is authenticated") case false =&gt; println("Entered password is invalid") } </code></pre> <p>instead of</p> <pre><code>if(user.password == enteredPassword) println("User is authenticated") else println("Entered password is invalid") </code></pre> <p>Are these approaches equal? Is one of them more preferrable than another for some reason?</p>
9,267,277
9
0
null
2012-02-13 19:36:53.537 UTC
17
2020-09-29 05:30:22.04 UTC
null
null
null
null
831,614
null
1
86
scala
57,926
<pre><code>class MatchVsIf { def i(b: Boolean) = if (b) 5 else 4 def m(b: Boolean) = b match { case true =&gt; 5; case false =&gt; 4 } } </code></pre> <p>I'm not sure why you'd want to use the longer and clunkier second version.</p> <pre><code>scala&gt; :javap -cp MatchVsIf Compiled from "&lt;console&gt;" public class MatchVsIf extends java.lang.Object implements scala.ScalaObject{ public int i(boolean); Code: 0: iload_1 1: ifeq 8 4: iconst_5 5: goto 9 8: iconst_4 9: ireturn public int m(boolean); Code: 0: iload_1 1: istore_2 2: iload_2 3: iconst_1 4: if_icmpne 11 7: iconst_5 8: goto 17 11: iload_2 12: iconst_0 13: if_icmpne 18 16: iconst_4 17: ireturn 18: new #14; //class scala/MatchError 21: dup 22: iload_2 23: invokestatic #20; //Method scala/runtime/BoxesRunTime.boxToBoolean:(Z)Ljava/lang/Boolean; 26: invokespecial #24; //Method scala/MatchError."&lt;init&gt;":(Ljava/lang/Object;)V 29: athrow </code></pre> <p>And that's a lot more bytecode for the match also. It's <em>fairly</em> efficient even so (there's no boxing unless the match throws an error, which can't happen here), but for compactness and performance one should favor <code>if</code>/<code>else</code>. If the clarity of your code is greatly improved by using match, however, go ahead (except in those rare cases where you know performance is critical, and then you might want to compare the difference).</p>
52,358,496
setContentView is using non-SDK interface
<p>When I run my application in an emulator with the API 28, the console gives me the following warning: </p> <blockquote> <p>W/oaristachimene: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (light greylist, reflection) W/oaristachimene: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (light greylist, reflection)</p> </blockquote> <p>I have been debugging it and I found out that it comes from the call: <code>setContentView(R.layout.activity_main)</code>, so is there another way to set the layout of an activity or is this method going to be updated so that it doesn't throws that warning when running on a device with android API 28?.</p>
53,736,775
6
2
null
2018-09-16 21:24:01.597 UTC
9
2021-05-28 02:18:28.11 UTC
null
null
null
null
6,401,791
null
1
37
android|sdk|android-emulator
24,910
<p>For the warnings in the question, <code>computeFitSystemWindows</code> and <code>makeOptionalFitsSystemWindows</code> are actually used by the support library or androidx library through reflection. You can verify it by simply searching those two methods in the <code>AppCompatDelegateImpl</code>.</p> <p>Hopefully this can be fixed later.</p> <p><strong>Update 1</strong></p> <p>Recently when I test app in Firebase Test Lab, these 2 APIs and some other APIs are marked</p> <blockquote> <p>One possible root cause for this warning is Google-owned library UI Toolkit. No action need be taken at this time.</p> </blockquote> <p>Or</p> <blockquote> <p>One possible root cause for this warning is Google-owned library Android WebView. No action need be taken at this time.</p> </blockquote>
34,156,996
Firebase Data Desc Sorting in Android
<p>I am storing data in Firebase storage.</p> <p>Object <code>Comment</code> with attribute <code>timestamp</code>. When I push data from device to Firebase I'm populating <code>timestamp</code> with currentTime and store in <code>long</code> data type.</p> <p>When I do retrieving the data with <code>firebaseRef.orderByChild("timestamp").limitToLast(15)</code> result is not sorting how I expected.</p> <p>I even played around with rules and no result:</p> <pre><code>{ "rules": { ".read": true, ".write": true, ".indexOn": "streetrate", "streetrate": { ".indexOn": ".value" } } } </code></pre> <p>I tried store <code>timestamp</code> in <code>String</code> data type, same issue.</p>
34,158,197
18
1
null
2015-12-08 13:20:52.787 UTC
11
2021-04-20 06:14:10.697 UTC
2019-11-11 18:12:29.377 UTC
null
3,399,890
null
4,959,097
null
1
36
android|firebase|sorting|firebase-realtime-database
43,117
<p>Firebase can order the items in ascending order by a given property and then returns either the first N items (<code>limitToFirst()</code>) or the last N items (<code>limitToLast()</code>). There is no way to indicate that you want the items in descending order. </p> <p>There are two options to get the behavior you want:</p> <ol> <li><p>Use a Firebase query to get the correct data, then re-order it client-side</p></li> <li><p>Add a field that has a descending value to the data</p></li> </ol> <p>For the latter approach, it is common to have a inverted timestamp.</p> <pre><code>-1 * new Date().getTime(); </code></pre>
10,381,412
Nginx config for WSS
<p>I am having a problem in connecting through WSS to my server. I followed the following article to setup nginx with websockets: <a href="http://www.letseehere.com/reverse-proxy-web-sockets" rel="noreferrer">http://www.letseehere.com/reverse-proxy-web-sockets</a></p> <p>The following is my nginx config which serves a Play! application:</p> <pre><code>#user nobody; worker_processes 1; error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } tcp { upstream websockets { ## Play! WS location server 127.0.0.1:9000; } server { listen 80; listen 8000; server_name socket.domain.com; tcp_nodelay on; proxy_pass websockets; proxy_send_timeout 300; } # virtual hosting #include /usr/local/nginx/vhosts/*; } http { server { listen 443 ssl; server_name socket.artoo.in; ssl_certificate /usr/local/nginx/key/socket.domain.com.crt; ssl_certificate_key /usr/local/nginx/key/socket.domain.com.key; ssl_session_timeout 5m; ssl_protocols SSLv2 SSLv3 TLSv1; ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; ssl_prefer_server_ciphers on; location / { proxy_pass http://127.0.0.1:9000; } } } </code></pre> <p>While the server is accessible on <a href="http://socket.domain.com" rel="noreferrer">http://socket.domain.com</a>, <a href="https://socket.domain.com" rel="noreferrer">https://socket.domain.com</a>, ws://socket.domain.com but not wss://socket.domain.com</p>
10,394,473
2
1
null
2012-04-30 09:34:14.183 UTC
6
2012-08-29 23:38:01.703 UTC
2012-05-01 06:45:40.873 UTC
null
356,580
null
356,580
null
1
15
ssl|nginx|websocket
51,047
<p>I have at least solved it for the short term by using stunnel (referring to this article: <a href="http://www.darkcoding.net/software/proxy-socket-io-and-nginx-on-the-same-port-over-ssl/" rel="nofollow">http://www.darkcoding.net/software/proxy-socket-io-and-nginx-on-the-same-port-over-ssl/</a>). </p> <p>Stunnel can convert HTTPS to HTTP and by that token WSS to WS. Nginx served the socket application running on 9000 port as usual:</p> <p>/etc/stunnel/stunnel.conf</p> <pre><code>[https] accept = 443 connect = 80 TIMEOUTclose = 0 </code></pre> <p>/usr/local/nginx/conf/nginx.conf</p> <pre><code>#user nobody; worker_processes 1; error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } tcp { upstream websockets { ## Play! WS location server 127.0.0.1:9000; check interval=3000 rise=2 fall=5 timeout=1000; } server { listen 80; listen 8000; server_name socket.artoo.in; tcp_nodelay on; proxy_pass websockets; proxy_send_timeout 300; } # virtual hosting #include /usr/local/nginx/vhosts/*; } #http { # # server { # listen 443 ssl; # server_name socket.artoo.in; # # ssl_certificate /usr/local/nginx/key/socket.domain.com.crt; # ssl_certificate_key /usr/local/nginx/key/socket.domain.com.key; # # ssl_session_timeout 5m; # # ssl_protocols SSLv2 SSLv3 TLSv1; # ssl_ciphers ALL:!ADH:!EXPORT56:RC4+RSA:+HIGH:+MEDIUM:+LOW:+SSLv2:+EXP; # ssl_prefer_server_ciphers on; # # location / { # proxy_pass http://127.0.0.1:9000; # } # } #} </code></pre> <p>Now the only thing I need to worry about is how to increase the timeout for websockets on nginx, the connection seems to be breaking every 75 secs (default for nginx).</p>
10,490,307
Retry a task multiple times based on user input in case of an exception in task
<p>All the service calls in my application are implemented as tasks.When ever a task is faulted ,I need to present the user with a dialog box to retry the last operation failed.If the user chooses retry the program should retry the task ,else the execution of the program should continue after logging the exception.Any one has got a high level idea on how to implement this functionality ?</p>
10,494,424
3
1
null
2012-05-07 23:04:26.113 UTC
10
2017-05-08 16:34:32.1 UTC
null
null
null
null
524,321
null
1
15
c#|wpf|exception-handling|task-parallel-library|task
16,155
<p><strong>UPDATE 5/2017</strong></p> <p><strong>C# 6</strong> exception filters make the <code>catch</code> clause a lot simpler :</p> <pre><code> private static async Task&lt;T&gt; Retry&lt;T&gt;(Func&lt;T&gt; func, int retryCount) { while (true) { try { var result = await Task.Run(func); return result; } catch when (retryCount-- &gt; 0){} } } </code></pre> <p>and a recursive version:</p> <pre><code> private static async Task&lt;T&gt; Retry&lt;T&gt;(Func&lt;T&gt; func, int retryCount) { try { var result = await Task.Run(func); return result; } catch when (retryCount-- &gt; 0){} return await Retry(func, retryCount); } </code></pre> <p><strong>ORIGINAL</strong></p> <p>There are many ways to code a Retry function: you can use recursion or task iteration. There was a <a href="http://www.dotnetzone.gr/cs/forums/thread/67309.aspx" rel="noreferrer">discussion</a> in the Greek .NET User group a while back on the different ways to do exactly this.<br> If you are using F# you can also use Async constructs. Unfortunately, you can't use the async/await constructs at least in the Async CTP, because the code generated by the compiler doesn't like multiple awaits or possible rethrows in catch blocks. </p> <p>The recursive version is perhaps the simplest way to build a Retry in C#. The following version doesn't use Unwrap and adds an optional delay before retries :</p> <pre><code>private static Task&lt;T&gt; Retry&lt;T&gt;(Func&lt;T&gt; func, int retryCount, int delay, TaskCompletionSource&lt;T&gt; tcs = null) { if (tcs == null) tcs = new TaskCompletionSource&lt;T&gt;(); Task.Factory.StartNew(func).ContinueWith(_original =&gt; { if (_original.IsFaulted) { if (retryCount == 0) tcs.SetException(_original.Exception.InnerExceptions); else Task.Factory.StartNewDelayed(delay).ContinueWith(t =&gt; { Retry(func, retryCount - 1, delay,tcs); }); } else tcs.SetResult(_original.Result); }); return tcs.Task; } </code></pre> <p>The <a href="http://blogs.msdn.com/b/pfxteam/archive/2009/06/03/9691796.aspx" rel="noreferrer">StartNewDelayed</a> function comes from the <a href="http://blogs.msdn.com/b/pfxteam/archive/2010/04/04/9990342.aspx" rel="noreferrer">ParallelExtensionsExtras</a> samples and uses a timer to trigger a TaskCompletionSource when the timeout occurs.</p> <p>The F# version is a lot simpler:</p> <pre><code>let retry (asyncComputation : Async&lt;'T&gt;) (retryCount : int) : Async&lt;'T&gt; = let rec retry' retryCount = async { try let! result = asyncComputation return result with exn -&gt; if retryCount = 0 then return raise exn else return! retry' (retryCount - 1) } retry' retryCount </code></pre> <p>Unfortunatley, it isn't possible to write something similar in C# using async/await from the Async CTP because the compiler doesn't like await statements inside a catch block. The following attempt also fails silenty, because the runtime doesn't like encountering an await after an exception:</p> <pre><code>private static async Task&lt;T&gt; Retry&lt;T&gt;(Func&lt;T&gt; func, int retryCount) { while (true) { try { var result = await TaskEx.Run(func); return result; } catch { if (retryCount == 0) throw; retryCount--; } } } </code></pre> <p>As for asking the user, you can modify Retry to call a function that asks the user and returns a task through a TaskCompletionSource to trigger the next step when the user answers, eg:</p> <pre><code> private static Task&lt;bool&gt; AskUser() { var tcs = new TaskCompletionSource&lt;bool&gt;(); Task.Factory.StartNew(() =&gt; { Console.WriteLine(@"Error Occured, continue? Y\N"); var response = Console.ReadKey(); tcs.SetResult(response.KeyChar=='y'); }); return tcs.Task; } private static Task&lt;T&gt; RetryAsk&lt;T&gt;(Func&lt;T&gt; func, int retryCount, TaskCompletionSource&lt;T&gt; tcs = null) { if (tcs == null) tcs = new TaskCompletionSource&lt;T&gt;(); Task.Factory.StartNew(func).ContinueWith(_original =&gt; { if (_original.IsFaulted) { if (retryCount == 0) tcs.SetException(_original.Exception.InnerExceptions); else AskUser().ContinueWith(t =&gt; { if (t.Result) RetryAsk(func, retryCount - 1, tcs); }); } else tcs.SetResult(_original.Result); }); return tcs.Task; } </code></pre> <p>With all the continuations, you can see why an async version of Retry is so desirable.</p> <p><strong>UPDATE:</strong></p> <p>In Visual Studio 2012 Beta the following two versions work:</p> <p>A version with a while loop:</p> <pre><code> private static async Task&lt;T&gt; Retry&lt;T&gt;(Func&lt;T&gt; func, int retryCount) { while (true) { try { var result = await Task.Run(func); return result; } catch { if (retryCount == 0) throw; retryCount--; } } } </code></pre> <p>and a recursive version:</p> <pre><code> private static async Task&lt;T&gt; Retry&lt;T&gt;(Func&lt;T&gt; func, int retryCount) { try { var result = await Task.Run(func); return result; } catch { if (retryCount == 0) throw; } return await Retry(func, --retryCount); } </code></pre>
10,728,420
Editing the git commit message in GitHub
<p>Is there any way of online editing the commit message in <code>GitHub.com</code>, after submission?</p> <p>From the command line, one can do</p> <pre><code>git commit --amend -m "New commit message" </code></pre> <p>as correctly suggested in <a href="https://stackoverflow.com/questions/179123/how-do-i-edit-an-incorrect-commit-message-in-git">another question</a>.</p> <p>Trying <code>git pull</code> and then <code>git push</code> has worked (without any other commit having interfered in the mean time).</p> <p>But can it be done via the <code>GitHub</code> website?</p>
10,728,453
9
1
null
2012-05-23 21:52:48.767 UTC
41
2022-05-13 19:10:43.517 UTC
2017-05-23 12:03:01.573 UTC
null
-1
null
834,316
null
1
211
git|github|commit|post-commit
190,351
<p>No, this is not directly possible. The hash for every Git commit is also calculated based on the commit message. When you change the commit message, you change the commit hash. If you want to push that commit, you have to force that push (git push -f). But if already someone pulled your old commit and started a work based on that commit, they would have to rebase their work onto your new commit.</p>
35,609,731
Remove duplicate in a string - javascript
<p>I have a string in javascript where there are a lot of duplicates. For example I have:</p> <pre><code>var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double" </code></pre> <p>What can I do to delete duplicates and to get for example <code>x="Int32,Double"</code>?</p>
35,609,777
12
2
null
2016-02-24 18:07:08.903 UTC
4
2022-05-02 07:13:18.957 UTC
null
null
null
null
4,592,796
null
1
10
javascript
50,823
<p>With <code>Set</code> and <code>Array.from</code> this is pretty easy:</p> <pre><code>Array.from(new Set(x.split(','))).toString() </code></pre> <p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double" x = Array.from(new Set(x.split(','))).toString(); document.write(x);</code></pre> </div> </div> </p>
21,182,535
Animate.css in hover
<p>Today I tried to implement in my site <a href="https://github.com/daneden/animate.css">animate.css</a> </p> <p>But I wanted to make sure that the 'effect is activated in the: hover So I used jquery for this </p> <p>The code is :</p> <pre><code> $(".questo").hover( function (e) { $(this).toggleClass('animated shake', e.type === 'mouseenter'); }); </code></pre> <p>The problem is that once you remove the mouse, the 'effect is interrupted. It could land the 'effect even without hover effect once it has begun?</p> <p><strong>Thank you all in advance</strong></p>
21,185,274
7
2
null
2014-01-17 09:41:24.553 UTC
5
2019-12-22 11:07:23.647 UTC
null
null
null
null
3,198,605
null
1
19
javascript|jquery|html|css|animate.css
42,837
<p>See this variant (more interactive):</p> <pre><code>$(".myDiv").hover(function(){ $(this).addClass('animated ' + $(this).data('action')); }); $(".myDiv").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd",function(){ $(this).removeClass('animated ' + $(this).data('action')); }); </code></pre> <p><a href="http://jsfiddle.net/DopustimVladimir/Vc2ug/">http://jsfiddle.net/DopustimVladimir/Vc2ug/</a></p>
18,541,476
Inserting datetime value into sql server table column
<p>I'm attempting to insert a <code>datetime('2013-08-30 19:05:00')</code> value into a SQL server database table column(smalldatetime) and the value stays "NULL" after the insert. </p> <p>I'm doing this to 6 other columns that are the exact same type. What is this only occuring on one column? I've triple checked that the names of the columns are correct. Any ideas?</p>
18,541,793
1
4
null
2013-08-30 21:07:38.7 UTC
3
2016-11-04 21:58:52.537 UTC
2016-11-04 21:58:52.537 UTC
null
178,163
null
1,911,030
null
1
2
sql-server-2008
88,063
<p>Assuming the situation is as you describe</p> <pre><code>CREATE TABLE T ( S SMALLDATETIME NULL ) INSERT INTO T VALUES('2013-08-30 19:05:00') SELECT * FROM T /*Returns NULL*/ </code></pre> <p>There are only two ways I can think of that this can happen.</p> <p>1) That is an ambiguous datetime format. Under the wrong session options this won't cast correctly and if you have some additional options <code>OFF</code> it will return <code>NULL</code> rather than raise an error (e.g.)</p> <pre><code>SET LANGUAGE Italian; SET ansi_warnings OFF; SET arithabort OFF; INSERT INTO T VALUES('2013-08-30 19:05:00') SELECT * FROM T /*NULL inserted*/ </code></pre> <p>2) You may have missed the column out in an <code>INSTEAD OF</code> trigger, or have an <code>AFTER</code> trigger that actually sets the value back to <code>NULL</code>.</p>
28,278,072
Force iOS view to not rotate, while still allowing child to rotate
<p>I have a view controller with a child view controller.</p> <pre><code>tab bar controller | | nav controller | | UIPageViewController (should rotate) | | A (Video Player) (shouldn't rotate) | | B (Controls overlay) (should rotate) </code></pre> <p>A should be forced to stay portrait at all times, but B should be allowed to rotate freely.</p> <p>I know <code>shouldAutorotate</code> applies to any view controllers and its children, but is there any way to get around this? It seems like I could use <code>shouldAutorotateToInterfaceOrientation</code>, but this is blocked in iOS 8.</p> <p>I'd like to keep a video player static (so horizontal videos are always horizontal regardless of device orientation), while the controls layer subview overlay is allowed to freely rotate.</p> <p>I'm using Swift.</p>
28,796,685
6
2
null
2015-02-02 12:44:40.253 UTC
9
2015-11-24 00:51:09.297 UTC
2015-02-03 01:26:06.243 UTC
null
240,569
null
240,569
null
1
9
ios|swift|uiviewcontroller|autorotate
5,151
<p>I had this exact problem, and found out quickly there's a lot of bad advice floating around about autorotation, especially because iOS 8 handles it differently than previous versions.</p> <p>First of all, you <strong>don't</strong> want to apply a counterrotation manually or subscribe to <code>UIDevice</code> orientation changes. Doing a counterrotation will still result in an unsightly animation, and <em>device</em> orientation isn't always the same as <em>interface</em> orientation. Ideally you want the camera preview to stay truly frozen, and your app UI to match the status bar orientation and size as they change, exactly like the native Camera app.</p> <p>During an orientation change in iOS 8, the window itself rotates rather than the view(s) it contains. You can add the views of multiple view controllers to a single <code>UIWindow</code>, but only the <code>rootViewController</code> will get an opportunity to respond via <code>shouldAutorotate()</code>. Even though you make the rotation decision at the view controller level, it's the parent window that actually rotates, thus rotating all of its subviews (including ones from other view controllers).</p> <p>The solution is two <code>UIWindow</code> stacked on top of each other, each rotating (or not) with its own root view controller. Most apps only have one, but there's no reason you can't have two and overlay them just like any other <code>UIView</code> subclass.</p> <p>Here's a working proof-of-concept, <a href="https://github.com/jstn/IndependentRotation">which I've also put on GitHub here</a>. Your particular case is a little more complicated because you have a stack of containing view controllers, but the basic idea is the same. I'll touch on some specific points below.</p> <pre><code>@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var cameraWindow: UIWindow! var interfaceWindow: UIWindow! func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -&gt; Bool { let screenBounds = UIScreen.mainScreen().bounds let inset: CGFloat = fabs(screenBounds.width - screenBounds.height) cameraWindow = UIWindow(frame: screenBounds) cameraWindow.rootViewController = CameraViewController() cameraWindow.backgroundColor = UIColor.blackColor() cameraWindow.hidden = false interfaceWindow = UIWindow(frame: CGRectInset(screenBounds, -inset, -inset)) interfaceWindow.rootViewController = InterfaceViewController() interfaceWindow.backgroundColor = UIColor.clearColor() interfaceWindow.opaque = false interfaceWindow.makeKeyAndVisible() return true } } </code></pre> <p>Setting a negative inset on <code>interfaceWindow</code> makes it slightly larger than the screen bounds, effectively hiding the black rectangular mask you'd see otherwise. Normally you wouldn't notice because the mask rotates with the window, but since the camera window is fixed the mask becomes visible in the corners during rotation.</p> <pre><code>class CameraViewController: UIViewController { override func shouldAutorotate() -&gt; Bool { return false } } </code></pre> <p>Exactly what you'd expect here, just add your own setup for <code>AVCapturePreviewLayer</code>.</p> <pre><code>class InterfaceViewController: UIViewController { var contentView: UIView! override func viewDidLoad() { super.viewDidLoad() contentView = UIView(frame: CGRectZero) contentView.backgroundColor = UIColor.clearColor() contentView.opaque = false view.backgroundColor = UIColor.clearColor() view.opaque = false view.addSubview(contentView) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() let screenBounds = UIScreen.mainScreen().bounds let offset: CGFloat = fabs(screenBounds.width - screenBounds.height) view.frame = CGRectOffset(view.bounds, offset, offset) contentView.frame = view.bounds } override func supportedInterfaceOrientations() -&gt; Int { return Int(UIInterfaceOrientationMask.All.rawValue) } override func shouldAutorotate() -&gt; Bool { return true } } </code></pre> <p>The last trick is undoing the negative inset we applied to the window, which we achieve by offsetting <code>view</code> the same amount and treating <code>contentView</code> as the main view.</p> <p>For your app, <code>interfaceWindow.rootViewController</code> would be your tab bar controller, which in turn contains a navigation controller, etc. All of these views need to be transparent when your camera controller appears so the camera window can show through beneath it. For performance reasons you might consider leaving them opaque and only setting everything to transparent when the camera is actually in use, and set the camera window to <code>hidden</code> when it's not (while also shutting down the capture session).</p> <p>Sorry to post a novel; I haven't seen this addressed anywhere else and it took me a while to figure out, hopefully it helps you and anyone else who's trying to get the same behavior. Even Apple's <code>AVCam</code> sample app doesn't handle it quite right.</p> <p><a href="https://github.com/jstn/IndependentRotation">The example repo I posted</a> also includes a version with the camera already set up. Good luck!</p>
2,050,973
What encoding are filenames in NTFS stored as?
<p>I'm just getting started on some programming to handle filenames with non-english names on a WinXP system. I've done some recommended reading on unicode and I think I get the basic idea, but some parts are still not very clear to me.</p> <p>Specifically, what encoding (UTF-8, UTF-16LE/BE) are the file <strong>names</strong> (not the content, but the actual name of the file) stored in NTFS? Is it possible to open any file using fopen(), which takes a char*, or do I have no choice but to use wfopen(), which uses a wchar_t*, and presumably takes a UTF-16 string?</p> <p>I tried manually feeding in a UTF-8 encoded string to fopen(), eg.</p> <pre class="lang-c prettyprint-override"><code>unsigned char filename[] = {0xEA, 0xB0, 0x80, 0x2E, 0x74, 0x78, 0x74, 0x0}; // 가.txt FILE* f = fopen((char*)filename, "wb+"); </code></pre> <p>but this came out as 'ê°€.txt'.</p> <p>I was under the impression (which may be wrong) that a UTF8-encoded string would suffice in opening any filename under Windows, because I seem to vaguely remember some Windows application passing around (char*), not (wchar_t*), and having no problems.</p> <p>Can anyone shed some light on this?</p>
2,051,018
3
2
null
2010-01-12 17:33:31.093 UTC
12
2019-08-31 15:46:54.97 UTC
2017-04-03 15:07:44.837 UTC
null
2,020,723
null
248,667
null
1
49
windows|unicode|ntfs
51,723
<p>NTFS stores filenames in UTF-16, however <code>fopen</code> is using ANSI (not UTF-8).</p> <p>In order to use an UTF16-encoded file name you will need to use the Unicode versions of the file open calls. Do this by defining <code>UNICODE</code> and <code>_UNICODE</code> in your project. Then use the <code>CreateFile</code> call or the <code>wfopen</code> call.</p>
1,361,307
Which Haskell XML library to use?
<p>I see that there is a few of XML processing libraries in Haskell.</p> <ul> <li><a href="http://www.haskell.org/HaXml/" rel="noreferrer">HaXml</a> seems to be the most popular (according to <a href="http://donsbot.wordpress.com/2009/08/29/haskell-popularity-rankings-september-2009/" rel="noreferrer">dons</a>)</li> <li><a href="http://www.fh-wedel.de/~si/HXmlToolbox/" rel="noreferrer">HXT</a> seems to be the most advanced (but also the most difficult to learn thanks to arrows)</li> <li><a href="http://hackage.haskell.org/package/xml" rel="noreferrer">xml</a> which seems to be just the basic parser</li> <li><a href="http://www.flightlab.com/~joe/hxml/" rel="noreferrer">HXML</a> seems to be abandoned</li> <li>tagsoup and tagchup</li> <li>libXML and libXML SAX bindings</li> </ul> <p>So, which library to choose if I want it</p> <ul> <li>to be reasonably powerful (to extract data from XML and to modify XML)</li> <li>likely to be supported long time in the future</li> <li>to be a “community choice” (default choice)</li> </ul> <p>And while most of the above seem to be sufficient for my current needs, what are the reason to choose one of them over the others?</p> <p><strong>UPD 20091222</strong>:</p> <p>Some notes about licenses:</p> <ul> <li>BSD or MIT: <a href="http://hackage.haskell.org/package/hexpat" rel="noreferrer">hexpat</a>, <a href="http://hackage.haskell.org/package/hxt" rel="noreferrer">hxt</a>, <a href="http://hackage.haskell.org/package/libxml" rel="noreferrer">libxml</a>, <a href="http://hackage.haskell.org/package/tagsoup" rel="noreferrer">tagsoup</a>, <a href="http://hackage.haskell.org/package/xml" rel="noreferrer">xml</a></li> <li>LGPL: <a href="http://hackage.haskell.org/package/HaXml" rel="noreferrer">HaXml</a></li> <li>GPLv2:</li> <li>GPLv3: <a href="http://hackage.haskell.org/package/libxml-sax" rel="noreferrer">libxml-sax</a>, <a href="http://hackage.haskell.org/package/tagchup" rel="noreferrer">tagchup</a>, <a href="http://hackage.haskell.org/package/tagsoup-ht" rel="noreferrer">tagsoup-ht</a></li> </ul>
1,364,982
3
0
null
2009-09-01 08:48:28.603 UTC
23
2013-05-27 17:48:41.77 UTC
2011-04-16 20:27:54.567 UTC
null
83,805
null
25,450
null
1
63
xml|haskell|comparison
11,715
<p>I would recommend:</p> <ol> <li><a href="http://hackage.haskell.org/package/xml" rel="noreferrer">xml</a>, if your task is simple</li> <li><a href="http://hackage.haskell.org/package/HaXml" rel="noreferrer">haxml</a>, if your task is complex</li> <li><a href="http://hackage.haskell.org/package/hxt" rel="noreferrer">hxt</a>, if you like arrows</li> <li><a href="http://hackage.haskell.org/package/hexpat" rel="noreferrer">hexpat</a> if you need high performance</li> </ol>
2,304,203
How to use boost bind with a member function
<p>The following code causes cl.exe to crash (MS VS2005).<br> I am trying to use boost bind to create a function to a calls a method of myclass: </p> <pre><code>#include "stdafx.h" #include &lt;boost/function.hpp&gt; #include &lt;boost/bind.hpp&gt; #include &lt;functional&gt; class myclass { public: void fun1() { printf("fun1()\n"); } void fun2(int i) { printf("fun2(%d)\n", i); } void testit() { boost::function&lt;void ()&gt; f1( boost::bind( &amp;myclass::fun1, this ) ); boost::function&lt;void (int)&gt; f2( boost::bind( &amp;myclass::fun2, this ) ); //fails f1(); f2(111); } }; int main(int argc, char* argv[]) { myclass mc; mc.testit(); return 0; } </code></pre> <p>What am I doing wrong?</p>
2,304,211
3
0
null
2010-02-20 23:37:19.133 UTC
22
2022-01-29 11:28:09.813 UTC
null
null
null
null
3,590
null
1
81
c++|boost|boost-bind|boost-function
127,194
<p>Use the following instead:</p> <pre><code>boost::function&lt;void (int)&gt; f2( boost::bind( &amp;myclass::fun2, this, _1 ) ); </code></pre> <p>This forwards the first parameter passed to the function object to the function using place-holders - you have to tell <em>Boost.Bind</em> how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.<br> See e.g. <a href="http://www.boost.org/doc/libs/1_42_0/libs/bind/bind.html#with_functions" rel="noreferrer">here</a> or <a href="http://www.boost.org/doc/libs/1_42_0/libs/bind/bind.html#with_member_pointers" rel="noreferrer">here</a> for common usage patterns.</p> <p>Note that VC8s cl.exe regularly crashes on <em>Boost.Bind</em> misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters <em>Bind</em>-internals were instantiated with if you read through the output.</p>
8,719,214
How can I update IntelliJ IDEA?
<p>I am running IntelliJ IDEA 11.0 on Mac OS X. I know it has an update 11.0.1. But when I used <kbd>Check for update</kbd>, it said I am already running the latest version.</p> <p>Please tell me how can I upgrade to version 11.0.1?</p> <p>Thank you.</p>
8,719,974
2
1
null
2012-01-03 21:59:24.297 UTC
1
2022-07-30 13:20:48.767 UTC
2015-11-03 08:29:46.353 UTC
null
814,702
null
286,802
null
1
13
intellij-idea
43,707
<p>Probably you have a connection problem or your proxy/firewall blocks IDEA access to the site where it checks for updates.</p> <p>I've tried it on my Mac and Windows machines and it works fine: <img src="https://i.stack.imgur.com/Ek7Bx.png" alt="Mac Update"></p> <p>In any case, you can just <a href="http://www.jetbrains.com/idea/download/index.html" rel="noreferrer">download and install</a> the complete version from .dmg file. Your license, settings and plugins will be preserved and the old version can be moved to Trash.</p>
8,567,070
Elegantly minify dynamically generated javascript in a .NET environment?
<p>I'm programmatically creating javascript files from a .NET web app and would like to minify it before passing it to the client. Is there an efficient technique for doing this?</p>
8,573,261
6
1
null
2011-12-19 20:24:14.753 UTC
8
2020-08-13 14:14:17.66 UTC
2020-08-13 14:14:17.66 UTC
null
1,294,283
null
803,631
null
1
32
javascript|.net|minify
24,191
<p>If you simply want to be able to minify a javascript string in C# before saving it to a file, I would use either the <a href="http://ajaxmin.codeplex.com/">MS Ajax Minifier</a> or the <a href="http://yuicompressor.codeplex.com/">YUI compressor for .net</a>. Both of these expose an API that allows you to do this. Here is a sample using the ajax minifier:</p> <pre><code>var minifier = new Microsoft.Ajax.Utilities.Minifier(); var minifiedString = minifier.MinifyJavaScript(unMinifiedString); </code></pre> <p>Using the YUI Compressor for .net:</p> <pre><code>var minifiedString = JavaScriptCompressor.Compress(unMinifiedString); </code></pre> <p>Both the ajax minifier and and YUI Compressor libraries are available via Nuget.</p>
8,834,031
Objective-C NSMutableArray mutated while being enumerated?
<p>I kinda stumbled into the error where you try to remove objects from an NSMutableArray while other objects is being added to it elsewhere. To keep it simple, i have no clue on how to fix it. Here is what i'm doing:</p> <p>I have 4 timers calling 4 different methods that adds an object to the same array. Now, when i press a certain button, i need to remove all objects in the array (or at least some). So i tried to first invalidate all the 4 timers, and then do the work i want with the array, and then fire up the timers. I thought this would've worked since i am not using the timers anymore to enumerate through the array, but seemingly it doesn't work.</p> <p>Any suggestions here?</p>
8,834,079
6
1
null
2012-01-12 11:05:00.023 UTC
14
2017-10-18 00:45:17.193 UTC
2012-01-12 11:56:57.493 UTC
null
137,317
null
1,012,558
null
1
38
iphone|objective-c|xcode
28,202
<p>It's nothing to do with your timers. Because (I assume) your timers are all working on the same thread as your modifying method you don't need to stop and start them. iOS doesn't use an interrupt model for timer callbacks, they have to wait their turn just like any other event :)</p> <p>You're probably doing something like</p> <pre><code>for (id object in myArray) if (someCondition) [myArray removeObject:object]; </code></pre> <p>You can't edit a mutable array while you're going through it so you need to make a temporary array to hold the things you want to remove</p> <pre><code>// Find the things to remove NSMutableArray *toDelete = [NSMutableArray array]; for (id object in myArray) if (someCondition) [toDelete addObject:object]; // Remove them [myArray removeObjectsInArray:toDelete]; </code></pre>
54,200
Encrypting appSettings in web.config
<p>I am developing a web app which requires a username and password to be stored in the web.Config, it also refers to some URLs which will be requested by the web app itself and never the client.</p> <p>I know the .Net framework will not allow a web.config file to be served, however I still think its bad practice to leave this sort of information in plain text. </p> <p>Everything I have read so far requires me to use a command line switch or to store values in the registry of the server. I have access to neither of these as the host is online and I have only FTP and Control Panel (helm) access.</p> <p>Can anyone recommend any good, free encryption DLL's or methods which I can use? I'd rather not develop my own!</p> <p>Thanks for the feedback so far guys but I am not able to issue commands and and not able to edit the registry. Its going to have to be an encryption util/helper but just wondering which one!</p>
54,213
4
0
null
2008-09-10 14:31:04.657 UTC
9
2020-04-02 18:43:52.06 UTC
2018-11-30 11:42:30.69 UTC
Mauro
1,016,343
Mauro
2,208
null
1
15
.net|security|encryption|web-applications|appsettings
36,707
<ul> <li><a href="http://msdn.microsoft.com/en-us/library/zhhddkxy.aspx" rel="noreferrer">Encrypting and Decrypting Configuration Sections</a> (ASP.NET) on MSDN</li> <li><a href="http://weblogs.asp.net/scottgu/archive/2006/01/09/434893.aspx" rel="noreferrer">Encrypting Web.Config Values in ASP.NET 2.0</a> on ScottGu's <a href="http://weblogs.asp.net/scottgu/default.aspx" rel="noreferrer">blog</a></li> <li><a href="http://odetocode.com/Blogs/scott/archive/2006/01/08/2707.aspx" rel="noreferrer">Encrypting Custom Configuration Sections</a> on K. Scott Allen's <a href="http://odetocode.com/Blogs/scott/default.aspx" rel="noreferrer">blog</a></li> </ul> <p><strong>EDIT:</strong><br> If you can't use asp utility, you can encrypt config file using <a href="http://msdn.microsoft.com/en-us/library/system.configuration.sectioninformation.protectsection.aspx" rel="noreferrer">SectionInformation.ProtectSection</a> method.</p> <p>Sample on codeproject:</p> <p><a href="https://secure.codeproject.com/KB/aspnet/webconfig.aspx" rel="noreferrer">Encryption of Connection Strings inside the Web.config in ASP.Net 2.0</a> </p>
19,333,598
In Python, what does '<function at ...>' mean?
<p>What does <code>&lt;function at 'somewhere'&gt;</code> mean? Example:</p> <pre><code>&gt;&gt;&gt; def main(): ... pass ... &gt;&gt;&gt; main &lt;function main at 0x7f95cf42f320&gt; </code></pre> <p>And maybe there is a way to somehow access it using <strong><code>0x7f95cf42f320</code></strong>?</p>
19,333,628
4
0
null
2013-10-12 11:23:06.8 UTC
8
2013-10-12 21:32:33.31 UTC
2013-10-12 13:42:06.56 UTC
null
551,449
null
2,433,073
null
1
9
python|function|memory-address|repr
16,899
<p>You are looking at the default representation of a function object. It provides you with a name and a unique id, which in CPython <em>happens</em> to be a memory address.</p> <p>You cannot access it using the address; the memory address is only used to help you distinguish between function objects.</p> <p>In other words, if you have <em>two</em> function objects which were originally named <code>main</code>, you can still see that they are different:</p> <pre><code>&gt;&gt;&gt; def main(): pass ... &gt;&gt;&gt; foo = main &gt;&gt;&gt; def main(): pass ... &gt;&gt;&gt; foo is main False &gt;&gt;&gt; foo &lt;function main at 0x1004ca500&gt; &gt;&gt;&gt; main &lt;function main at 0x1005778c0&gt; </code></pre>
33,338,726
Reload tableview section without scroll or animation
<p>I am reloading a tableView section using this code -</p> <pre><code>self.tableView.beginUpdates() self.tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.None) self.tableView.endUpdates() </code></pre> <p>Still the rows replacement is animated and the table view scrolls to the top.</p> <p>How can I make sure that no animation will be applied to the section reload + prevent the table view from scrolling.</p>
33,338,752
8
0
null
2015-10-26 04:57:10.273 UTC
13
2020-07-24 17:19:49.533 UTC
2018-11-14 19:25:01.85 UTC
null
5,175,709
null
358,480
null
1
41
ios|uitableview
53,604
<p>Try this:</p> <pre><code>UIView.setAnimationsEnabled(false) self.tableView.beginUpdates() self.tableView.reloadSections(NSIndexSet(index: 1) as IndexSet, with: UITableViewRowAnimation.none) self.tableView.endUpdates() </code></pre>
23,236,898
Add text on image at specific point using imagemagick
<p>I want to add text on an image at specific point and want it be centre aligned. How can I specify to margin from top? I want to specify margin in pixels/inches from top.</p> <p>Currently I am using this command: </p> <pre><code> convert temp.jpg -gravity Center -pointsize 30 -annotate 0 'Love you mom' temp1.jpg </code></pre> <p>it is writing text in centre of image. I want text to move to top.</p> <p>This is what I am getting: <img src="https://i.stack.imgur.com/Nw9sU.jpg" alt="enter image description here"></p> <p>This is what i want: <img src="https://i.stack.imgur.com/HOzNP.jpg" alt="enter image description here"></p>
23,238,369
3
0
null
2014-04-23 06:50:50.577 UTC
17
2020-06-25 10:52:25.817 UTC
2014-04-23 07:00:22.393 UTC
null
649,388
null
649,388
null
1
51
imagemagick
47,165
<p>Try using <code>-gravity North</code> (this will move your text to the top of the image) and then adding an offset (<code>-annotate +0+100</code>) to move down your text:</p> <pre><code>convert temp.jpg -gravity North -pointsize 30 -annotate +0+100 'Love you mom' temp1.jpg </code></pre>
47,521,730
How to convert String into Hex nodejs
<p>I was looking for some standard function like hex to string but inverse, I want to convert String to Hex, but I only found this <a href="https://snipplr.com/view/52975" rel="noreferrer">function</a>...</p> <pre><code>// Example of convert hex to String hex.toString('utf-8') </code></pre>
47,522,901
4
0
null
2017-11-27 23:51:43.203 UTC
5
2022-04-28 09:28:54.897 UTC
2020-02-12 19:05:25.893 UTC
null
5,287,072
null
5,287,072
null
1
15
node.js|string|hex
48,210
<p>In NodeJS, use <a href="https://nodejs.org/dist/latest-v8.x/docs/api/buffer.html#buffer_buffers_and_character_encodings" rel="noreferrer">Buffer</a> to convert string to hex.</p> <pre><code>Buffer.from('hello world', 'utf8').toString('hex'); </code></pre> <p>Simple example about how it works:</p> <pre><code>const bufferText = Buffer.from('hello world', 'utf8'); // or Buffer.from('hello world') console.log(bufferText); // &lt;Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64&gt; const text = bufferText.toString('hex'); // To get hex console.log(text); // 68656c6c6f20776f726c64 console.log(bufferText.toString()); // or toString('utf8') // hello world //one single line Buffer.from('hello world').toString('hex') </code></pre>
18,813,476
Is it possible to hide the address bar in iOS 7 Safari?
<p>Is it possible to hide the address bar in iOS 7?</p> <p>I am currently using the below to do this in iOS 6 but I just updated xCode and tested in iPhone Sim and iOS 7 Safari is not responding to this.</p> <p>js:</p> <pre><code>window.addEventListener("load",function() { // Set a timeout... setTimeout(function(){ // Hide the address bar! window.scrollTo(0, 1); }, 0); }); </code></pre>
18,891,963
1
0
null
2013-09-15 14:27:22.393 UTC
11
2013-09-22 11:24:49.973 UTC
2013-09-18 19:10:58.783 UTC
null
1,243,160
null
1,031,184
null
1
26
javascript|iphone|ios|safari|mobile-safari
60,702
<p>It does not work anymore. Here is a very detailed article around the <a href="http://www.mobilexweb.com/blog/safari-ios7-html5-problems-apis-review" rel="noreferrer">changes in IOS7</a></p>
50,404,109
Unable to locate Xcode. Please make sure to have Xcode installed on your machine
<p>I'm new to Fastlane. Does anyone know how to fix this error from running</p> <p><code>fastlane ios myLane</code>.</p> <p>The output:</p> <blockquote> <p>[12:50:11]: fastlane finished with errors</p> <p>[!] Unable to locate Xcode. Please make sure to have Xcode installed on your machine</p> </blockquote> <p>But I have the newest Xcode (9.3.1) installed from Mac App Store.</p> <h3>Environment info:</h3> <p><code>fastlane --version</code></p> <blockquote> <p>fastlane 2.95.0</p> </blockquote> <p>which is the newest version.</p> <p><code>ruby -v</code></p> <blockquote> <p>ruby 2.3.3p222 (2016-11-21 revision 56859) [universal.x86_64-darwin17]</p> </blockquote>
51,246,596
2
0
null
2018-05-18 05:05:08.873 UTC
5
2020-08-03 09:02:39.37 UTC
2020-06-20 09:12:55.06 UTC
null
-1
null
5,492,956
null
1
52
ios|xcode|fastlane
15,270
<p>Try check Preferences in Xcode under Locations and be sure you have selected your Xcode version in the Command Line Tools dropdown: <a href="https://i.stack.imgur.com/huX3J.png" rel="noreferrer"><img src="https://i.stack.imgur.com/huX3J.png" alt="Select Xcode version"></a></p>
51,937,363
.env vs config.json
<p>I just started learning <code>JavaScript</code> / <code>node.js</code> (a gentle introduction to back-end webdev), and thus I am completely green in the subject.</p> <p>A few days ago I was reading a tutorial from which I learned to keep my confidential data (like passwords) in a <code>config.json</code> file.</p> <p>Today I have discovered (by a chance) <code>.env</code> file, and the more I learn about it, it seems, the more people are using it to actually store passwords.</p> <p>So when should I use <code>.env</code> and when should I use <code>config.json</code>?</p>
51,937,555
7
0
null
2018-08-20 19:31:09.277 UTC
9
2022-04-26 17:06:02.12 UTC
2018-08-22 12:10:02.563 UTC
null
5,098,833
null
5,098,833
null
1
43
javascript|node.js
25,990
<h1>The Question</h1> <p>When should <code>.env</code> be used over <code>config.json</code> and for what?</p> <h1>The answer</h1> <p>This is a rather difficult answer. On the one hand, you should only really ever use either of these tools while in development. This means that when in a production or prod-like environment, you would add these variables directly to the environment:</p> <pre><code>NODE_ENV=development node ./sample.js --mongodb:host "dharma.mongohq.com" --mongodb:port 10065 </code></pre> <p>There is no real clear winner over the other per se as they are both helpful in different ways. You can have nested data with <code>config.json</code>, but on the other hand, you can also have a cleaner data structure with <code>.env</code></p> <p>Some thing also to note is that you never want to commit these files to source control (git, svc etc).</p> <p>On the other hand, these tools make it very easy for beginners to get started quickly without having to worry about how to set the environment variables and the differences between a windows environment and a linux one.</p> <p>All in all, I'd say its really up to the developer. </p>
29,637,974
What's the difference between "as?", "as!", and "as"?
<p>Before I upgraded to Swift 1.2, I could write the following line:</p> <pre><code>if let width = imageDetails["width"] as Int? </code></pre> <p>Now it forces me to write this line:</p> <pre><code>if let width = imageDetails["width"] as! Int? </code></pre> <p>My question is, if I'm forced to write it as above, couldn't I just write the code below and it would do the same thing? Would it give me the same result in all values of imageDetails?</p> <pre><code>if let width = imageDetails["width"] as Int </code></pre>
29,638,106
3
0
null
2015-04-14 21:47:56.083 UTC
29
2018-02-09 12:14:23.4 UTC
2018-02-09 12:14:23.4 UTC
null
8,300,359
null
1,004,129
null
1
57
swift|casting
20,357
<p>The as keyword used to do both upcasts and downcasts:</p> <pre><code>// Before Swift 1.2 var aView: UIView = someView() var object = aView as NSObject // upcast var specificView = aView as UITableView // downcast </code></pre> <p>The upcast, going from a derived class to a base class, can be checked at compile time and will never fail.</p> <p>However, downcasts can fail since you can’t always be sure about the specific class. If you have a UIView, it’s possible it’s a UITableView or maybe a UIButton. If your downcast goes to the correct type – great! But if you happen to specify the wrong type, you’ll get a runtime error and the app will crash.</p> <p>In Swift 1.2, downcasts must be either optional with as? or “forced failable” with as!. If you’re sure about the type, then you can force the cast with as! similar to how you would use an implicitly-unwrapped optional:</p> <pre><code>// After Swift 1.2 var aView: UIView = someView() var tableView = aView as! UITableView </code></pre> <p>The exclamation point makes it absolutely clear that you know what you’re doing and that there’s a chance things will go terribly wrong if you’ve accidentally mixed up your types!</p> <p>As always, as? with optional binding is the safest way to go:</p> <pre><code>// This isn't new to Swift 1.2, but is still the safest way var aView: UIView = someView() if let tableView = aView as? UITableView { // do something with tableView } </code></pre> <p>Got this from a site: <a href="http://www.raywenderlich.com/95181/whats-new-in-swift-1-2">SOURCE</a></p>
45,301,203
No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0
<p>I've got this issue while updating to the latest Support Library version 26.0.0 (<a href="https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0" rel="noreferrer">https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-0</a>): </p> <blockquote> <p>Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.</p> </blockquote> <pre><code>/.../app/build/intermediates/res/merged/beta/debug/values-v26/values-v26.xml Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. Error:(15, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. Error:(18, 21) No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. Error:Execution failed for task ':app:processBetaDebugResources'. </code></pre> <blockquote> <p>com.android.ide.common.process.ProcessException: Failed to execute aapt</p> </blockquote> <p>The file is from the support library:</p> <pre><code>&lt;style name="Base.V26.Widget.AppCompat.Toolbar" parent="Base.V7.Widget.AppCompat.Toolbar"&gt; &lt;item name="android:touchscreenBlocksFocus"&gt;true&lt;/item&gt; &lt;item name="android:keyboardNavigationCluster"&gt;true&lt;/item&gt; &lt;/style&gt; </code></pre> <p>We're using the following versions:</p> <pre><code>ext.COMPILE_SDK_VERSION = 26 ext.BUILD_TOOLS_VERSION = "26.0.1" ext.MIN_SDK_VERSION = 17 ext.TARGET_SDK_VERSION = 26 ext.ANDROID_SUPPORT_LIBRARY_VERSION = "26.0.0" ext.GOOGLE_PLAY_SERVICES_LIBRARY_VERSION = "11.0.2" </code></pre> <hr> <pre><code>compile 'com.android.support:appcompat-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION compile 'com.android.support:design:' + ANDROID_SUPPORT_LIBRARY_VERSION compile 'com.android.support:recyclerview-v7:' + ANDROID_SUPPORT_LIBRARY_VERSION </code></pre> <p>Any ideas?</p>
45,310,170
26
1
null
2017-07-25 10:53:04.237 UTC
19
2020-05-20 16:39:58.947 UTC
2017-07-31 09:32:21.18 UTC
null
1,392,423
null
684,582
null
1
215
android|android-gradle-plugin|android-support-library|android-appcompat
144,071
<p>I was able to resolve it by updating sdk version and tools in gradle <code>compileSdkVersion 26</code> <code>buildToolsVersion "26.0.1"</code> </p> <p>and <code>support library 26.0.1</code> <a href="https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-1" rel="noreferrer">https://developer.android.com/topic/libraries/support-library/revisions.html#26-0-1</a></p>
22,156,664
What does the dot after dollar sign mean in jQuery when declaring variables?
<p>I see variables declared as:</p> <pre><code>$.root = $("body"); </code></pre> <p>and</p> <pre><code>$root = $("body"); </code></pre> <p>What is the difference between the two?</p>
22,156,705
3
1
null
2014-03-03 20:25:24.427 UTC
10
2014-03-03 20:40:12.927 UTC
null
null
null
user1718673
null
null
1
33
jquery
12,158
<p>Functions in JavaScript are objects. And like most objects in JavaScript, you can arbitrarily add properties to them. The <code>$</code> function is just that, a function. So if you want to pop a property onto it and reference a jQuery collection, or reference, you can.</p> <p>By adding the collection as a property on the <code>$</code> function, it is one less variable in the current scope. You can examine the keys of the jQuery function before and after if you'd like to see how it affects the function's topography and (enumerable) property list:</p> <pre class="lang-js prettyprint-override"><code>Object.keys($); // ["fn", "extend", "expando"..."parseHTML", "offset", "noConflict"] $.root = $("body"); // [&lt;body&gt;] Object.keys($); // ["fn", "extend", "expando"..."parseHTML", "offset", "noConflict", "root"] </code></pre>