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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
38,003,836 | Pyspark: groupby and then count true values | <p>My data structure is in JSON format:</p>
<pre><code>"header"{"studentId":"1234","time":"2016-06-23","homeworkSubmitted":True}
"header"{"studentId":"1234","time":"2016-06-24","homeworkSubmitted":True}
"header"{"studentId":"1234","time":"2016-06-25","homeworkSubmitted":True}
"header"{"studentId":"1236","time":"2016-06-23","homeworkSubmitted":False}
"header"{"studentId":"1236","time":"2016-06-24","homeworkSubmitted":True}
....
</code></pre>
<p>I need to plot a histogram that shows number of homeworkSubmitted: True over all stidentIds. I wrote code that flattens the data structure, so my keys are header.studentId, header.time and header.homeworkSubmitted.</p>
<p>I used keyBy to group by studentId:</p>
<pre><code> initialRDD.keyBy(lambda row: row['header.studentId'])
.map(lambda (k,v): (k,v['header.homeworkSubmitted']))
.map(mapTF).groupByKey().mapValues(lambda x: Counter(x)).collect()
</code></pre>
<p>This gives me result like this:</p>
<pre><code>("1234", Counter({0:0, 1:3}),
("1236", Counter(0:1, 1:1))
</code></pre>
<p>I need only number of counts of 1, possibly mapped to a list so that I can plot a histogram using matplotlib. I am not sure how to proceed and filter everything.</p>
<p>Edit: at the end I iterated through the dictionary and added counts to a list and then plotted histogram of the list. I am wondering if there is a more elegant way to do the whole process I outlined in my code.</p> | 38,014,672 | 3 | 1 | null | 2016-06-24 00:14:13.3 UTC | 1 | 2016-06-24 14:51:18.963 UTC | 2016-06-24 04:38:41.643 UTC | null | 2,952,335 | null | 2,952,335 | null | 1 | 10 | apache-spark|pyspark | 66,299 | <pre><code>df = sqlContext.read.json('/path/to/your/dataset/')
df.filter(df.homeworkSubmitted == True).groupby(df.studentId).count()
</code></pre>
<p>Note it is not valid JSON if there is a <code>"header"</code> or <code>True</code> instead of <code>true</code></p> |
37,073,774 | Using lodash push to an array only if value doesn't exist? | <p>I'm trying to make an array that if a value doesn't exist then it is added but however if the value is there I would like to remove that value from the array as well. </p>
<p>Feels like Lodash should be able to do something like this. </p>
<p>I'm interested in your best practises suggestions. </p>
<p>Also it is worth pointing out that I am using Angular.js</p>
<p><strong>* Update *</strong> </p>
<pre><code>if (!_.includes(scope.index, val)) {
scope.index.push(val);
} else {
_.remove(scope.index, val);
}
</code></pre> | 37,073,878 | 9 | 2 | null | 2016-05-06 13:33:20.79 UTC | 6 | 2022-04-21 23:17:38.05 UTC | 2017-08-15 12:36:43.75 UTC | null | 1,093,582 | null | 5,070,590 | null | 1 | 70 | javascript|arrays|angularjs|lodash | 117,587 | <p>The <code>Set</code> feature introduced by ES6 would do exactly that.</p>
<pre><code>var s = new Set();
// Adding alues
s.add('hello');
s.add('world');
s.add('hello'); // already exists
// Removing values
s.delete('world');
var array = Array.from(s);
</code></pre>
<p>Or if you want to keep using regular Arrays</p>
<pre><code>function add(array, value) {
if (array.indexOf(value) === -1) {
array.push(value);
}
}
function remove(array, value) {
var index = array.indexOf(value);
if (index !== -1) {
array.splice(index, 1);
}
}
</code></pre>
<p>Using vanilla JS over Lodash is a good practice. It removes a dependency, forces you to understand your code, and often is more performant.</p> |
17,970,313 | using knockout to set css class with an if condition | <p>I want to set a bootstrap css class to a span with if condition (up to the binded value).
I have <code>isApproved</code> field in a list, I want to see the field with 'label-success' class when its active and 'label-important' class when its inactive</p>
<p>I added this line, but all the time it's taking the first class</p>
<pre><code>data-bind="
text: isApproved,
css: isApproved = 'true' ? 'label label-important' : 'label label-important'"
</code></pre>
<p>Is it possible in the html or I should add a computed field on my VM?</p> | 17,970,610 | 2 | 1 | null | 2013-07-31 12:22:58.833 UTC | 4 | 2021-07-20 09:31:26.143 UTC | 2021-07-20 09:31:26.143 UTC | null | 3,687,463 | null | 171,082 | null | 1 | 40 | knockout.js | 36,754 | <p>If I understood you right, this is the binding you are looking for.</p>
<pre><code> data-bind="text: isApproved, css: {
'label' : true,
'label-success' : isApproved(),
'label-important': !isApproved()
}"
</code></pre>
<p>I hope it helps.</p> |
17,758,401 | How to create Categories in Rails | <p>i'm trying to Add Categories to my Rails app, but don't quite know how to do this.</p>
<p>I have many Pins(Images) and want the user to be able to assign a category on those Pins.
<strong>ASSIGN</strong> not create, edit, or delete a Category, just selecting one for their Pin.
Meaning that, When a user uploads a pin, he can choose from a dropdown list a Category.</p>
<p>Then, another user can choose from the Menu a Category, and ONLY the Pins in this Category will be listed.</p>
<p>How do i do this? Where to start ?</p>
<p>Thank you</p> | 17,758,936 | 2 | 0 | null | 2013-07-20 03:39:44.953 UTC | 15 | 2016-03-26 16:53:15.583 UTC | 2013-07-20 07:29:18.39 UTC | null | 1,609,496 | null | 1,609,496 | null | 1 | 8 | ruby-on-rails|model-view-controller|controller|categories | 12,982 | <p>First If you don't want to manage categories in your application, then you can simply add a category field in your table and category select in your application :</p>
<pre><code><%= f.select :category, [ 'Box', 'Cover', 'Poster' ], :prompt => 'Select One' %>
</code></pre>
<p>Second, If you want to manage categories in your application, than you have to maintain a separate model and table for it. So you can start with generating your model:</p>
<pre><code>rails g model category
</code></pre>
<p>it will add model and migration in your application directory. Add stuff to your migration:</p>
<pre><code>class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.text :description
## you can add more stuff as per your requirements
t.timestamps
end
end
end
</code></pre>
<p>Define associations in category & Pin model add validation for this :-</p>
<pre><code>In Category Model:
has_many :pins
In Pin Model :
belongs_to :category
validates :category, presence: true
</code></pre>
<p>Create some categories by categories controller and form (I don't think, I need to tell you that stuff, you are able to do it yourself)</p>
<p>In your pin uploading form add this select :-</p>
<pre><code><%= f.select :category, Category.all, :prompt => "Select One" %>
</code></pre>
<p>Hope, It will help.</p> |
3,895,692 | What does `unsigned` in MySQL mean and when to use it? | <p>What does "unsigned" mean in MySQL and when should I use it?</p> | 3,895,705 | 1 | 0 | null | 2010-10-09 04:20:58.18 UTC | 72 | 2019-08-21 14:47:32.277 UTC | 2019-01-18 13:48:53.307 UTC | null | 1,480,391 | null | 697,684 | null | 1 | 304 | mysql|types | 216,585 | <p><a href="http://dev.mysql.com/doc/refman/5.7/en/numeric-type-attributes.html" rel="noreferrer">MySQL</a> says:</p>
<blockquote>
<p>All integer types can have an optional
(nonstandard) attribute UNSIGNED.
Unsigned type can be used to <strong>permit
only nonnegative numbers in a column</strong>
or <strong>when you need a larger upper
numeric range</strong> for the column. For
example, if an INT column is UNSIGNED,
the size of the column's range is the
same but its endpoints shift from
-2147483648 and 2147483647 up to 0 and 4294967295.</p>
</blockquote>
<p><strong>When do I use it ?</strong></p>
<p>Ask yourself this question: <em>Will this field ever contain a negative value</em>?<br>
If the answer is no, then you want an <code>UNSIGNED</code> data type.</p>
<p>A common mistake is to use a primary key that is an auto-increment <code>INT</code> starting at <strong>zero</strong>, yet the type is <code>SIGNED</code>, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.</p> |
3,224,312 | How can variables be set to NULL under the strict pragma? | <pre><code>use strict;
my $var = NULL;
</code></pre>
<p>will raise an error of <code>Bareword "NULL" not allowed while "strict subs" in use</code></p> | 3,224,318 | 1 | 0 | null | 2010-07-11 19:13:42.833 UTC | 6 | 2015-09-22 19:33:15.77 UTC | 2010-07-12 06:34:04.537 UTC | null | 133,939 | null | 312,483 | null | 1 | 50 | perl | 63,456 | <p>There's no NULL in Perl. However, variables can be <a href="http://perldoc.perl.org/functions/undef.html" rel="noreferrer"><code>undef</code></a>ined, which means that they have no value set.<br>
Here're some examples of how you can get an undefined variable in Perl:</p>
<pre><code>my $var; # variables are undefined by default
undef $var; # undef() undefines the value of a variable
$var = undef; # same, using an alternative syntax
</code></pre>
<p>To check for definedness of a variable, use <a href="http://perldoc.perl.org/functions/defined.html" rel="noreferrer"><code>defined()</code></a>, i.e. </p>
<pre><code>print "\$var is undefined\n" unless defined $var;
</code></pre> |
20,936,901 | Combining Spannable with String.format() | <p>Suppose you have the following string:</p>
<pre><code>String s = "The cold hand reaches for the %1$s %2$s Ellesse's";
String old = "old";
String tan = "tan";
String formatted = String.format(s,old,tan); //"The cold hand reaches for the old tan Ellesse's"
</code></pre>
<p>Suppose you want to end up with this string, but also have a particular <a href="https://developer.android.com/reference/android/text/Spannable.html" rel="noreferrer"><code>Span</code></a> set for any word replaced by <code>String.format</code>. </p>
<p>For instance, we also want to do the following:</p>
<pre><code>Spannable spannable = new SpannableString(formatted);
spannable.setSpan(new StrikethroughSpan(), oldStart, oldStart+old.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannable.setSpan(new ForegroundColorSpan(Color.BLUE), tanStart, tanStart+tan.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code></pre>
<p>Is there a robust way of getting to know the start indices of <code>old</code> and <code>tan</code>? </p>
<p>Note that just searching for 'old' returns the 'old' in 'cold', so that won't work.</p>
<p>What <em>will</em> work, I guess, is searching for <code>%[0-9]$s</code> beforehand, and calculating the offsets to account for the replacements in <code>String.format</code>. This seems like a headache though, I suspect there might be a method like <code>String.format</code> that is more informative about the specifics of its formatting. Well, is there?</p> | 20,937,501 | 5 | 2 | null | 2014-01-05 17:41:29.553 UTC | 11 | 2020-04-28 06:56:09.42 UTC | 2014-01-05 18:34:32.787 UTC | null | 2,556,111 | null | 673,206 | null | 1 | 31 | android|spannablestring|spannable | 12,012 | <p>Using Spannables like that is a headache -- this is probably the most straightforward way around:</p>
<pre><code>String s = "The cold hand reaches for the %1$s %2$s Ellesse's";
String old = "<font color=\"blue\">old</font>";
String tan = "<strike>tan</strike>";
String formatted = String.format(s,old,tan); //The cold hand reaches for the <font color="blue">old</font> <strike>tan</strike> Ellesse's
Spannable spannable = Html.fromHtml(formatted);
</code></pre>
<p>Problem: this does not put in a <code>StrikethroughSpan</code>. To make the <code>StrikethroughSpan</code>, we borrow a custom <code>TagHandler</code> from <a href="https://stackoverflow.com/questions/4044509/android-how-to-use-the-html-taghandler">this question</a>.</p>
<pre><code>Spannable spannable = Html.fromHtml(text,null,new MyHtmlTagHandler());
</code></pre>
<hr>
<p>MyTagHandler:</p>
<pre><code>public class MyHtmlTagHandler implements Html.TagHandler {
public void handleTag(boolean opening, String tag, Editable output,
XMLReader xmlReader) {
if (tag.equalsIgnoreCase("strike") || tag.equals("s")) {
processStrike(opening, output);
}
}
private void processStrike(boolean opening, Editable output) {
int len = output.length();
if (opening) {
output.setSpan(new StrikethroughSpan(), len, len, Spannable.SPAN_MARK_MARK);
} else {
Object obj = getLast(output, StrikethroughSpan.class);
int where = output.getSpanStart(obj);
output.removeSpan(obj);
if (where != len) {
output.setSpan(new StrikethroughSpan(), where, len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
private Object getLast(Editable text, Class kind) {
Object[] objs = text.getSpans(0, text.length(), kind);
if (objs.length == 0) {
return null;
} else {
for (int i = objs.length; i > 0; i--) {
if (text.getSpanFlags(objs[i - 1]) == Spannable.SPAN_MARK_MARK) {
return objs[i - 1];
}
}
return null;
}
}
}
</code></pre> |
21,264,359 | how to make hint disappear when edittext is touched? | <p>In my application in android are many EditText fields. And I ran into a problem with hint.
It is not disappearing when EditText is focused, but it disappears when I start to write something.
How can this problem be fixed? Because I need the hint to disappear when the EditText field is touched.</p>
<p>It is for example:</p>
<pre><code><EditText
android:layout_width="260dp"
android:layout_height="30dp"
android:ems="10"
android:inputType="text"
android:id="@+id/driv_lic_num_reg"
android:hint="@string/driver_license_numb"
android:textColor="@color/black"
android:textColorHint="@color/grey_hint"
android:background="@drawable/input_field_background"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_margin="2dp"
android:textCursorDrawable="@color/black"
android:textSize="15dp"
android:paddingLeft="10dp"
android:nextFocusDown="@+id/pass_reg"
android:imeOptions="actionNext"
android:maxLines="1"
android:maxLength="50"
android:focusableInTouchMode="true"/>
</code></pre> | 21,264,550 | 12 | 3 | null | 2014-01-21 16:55:35.943 UTC | 9 | 2020-04-05 21:42:41.273 UTC | 2018-10-21 06:31:48.087 UTC | null | 6,877,321 | null | 3,132,940 | null | 1 | 48 | android|android-edittext|hint | 47,275 | <p>Hint only disappears when you type in any text, not on focus. I don't think that there is any automatic way to do it, may be I am wrong. However, as a workaround I use the following code to remove hint on focus in EditText</p>
<pre><code>myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus)
myEditText.setHint("");
else
myEditText.setHint("Your hint");
}
});
</code></pre> |
20,906,305 | Import error cannot import name execute_manager in windows environment | <p>I'll get you up to speed. I'm trying to setup a windows dev environment. I've successfully installed python, django, and virtualenv + virtualenwrapper(<a href="http://virtualenvwrapper.readthedocs.org/en/latest/install.html">windows-cmd installer</a>)</p>
<pre><code>workon env
Python 2.7.6 (default, Nov 10 2013, 19:24:24) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> django.VERSION
(1,6,1, 'final',0)
>>> quit()
</code></pre>
<p>But when I run: <code>python manage.py runserver</code> from my cloned repository I get this error:</p>
<pre><code>Traceback (most recent call last)"
File "manage.py", line 2, in (module)
from django.core.management import execute_manager
ImportError: cannot import name execute_manager
</code></pre>
<p>Both python and django are added to my system variable PATH:</p>
<pre><code>...C:\Python27\;C:\Python27\Scripts\;C:\PYTHON27\DLLs\;C:\PYTHON27\LIB\;C:\Python27\Lib\site-packages\;
</code></pre>
<p>I've also tried this with bash and powershell and I still get the same error.</p>
<p>Is this a virtualenv related issue? Django dependence issue? Yikes. How do I fix this problem? Help me Stackoverflow-kenobi your my only hope. </p> | 20,906,461 | 3 | 3 | null | 2014-01-03 14:51:03.557 UTC | 6 | 2018-03-22 15:29:04.487 UTC | null | null | null | null | 908,392 | null | 1 | 38 | python|django|virtualenv|virtualenvwrapper | 57,791 | <p><code>execute_manager</code> deprecated in Django 1.4 as part of the project layout refactor and was removed in 1.6 per the deprecation timeline: <a href="https://docs.djangoproject.com/en/1.4/internals/deprecation/#id3" rel="noreferrer">https://docs.djangoproject.com/en/1.4/internals/deprecation/#id3</a></p>
<p>To fix this error you should either install a compatible version of Django for the project or update the <code>manage.py</code> to new style which does not use <code>execute_manager</code>: <a href="https://docs.djangoproject.com/en/stable/releases/1.4/#updated-default-project-layout-and-manage-py" rel="noreferrer">https://docs.djangoproject.com/en/stable/releases/1.4/#updated-default-project-layout-and-manage-py</a> Most likely if your <code>manage.py</code> is not compatible with 1.6 then neither is the rest of the project. You should find the appropriate Django version for the project.</p> |
28,353,725 | Java subtract LocalTime | <p>I have two <code>LocalTime</code> objects:</p>
<pre><code>LocalTime l1 = LocalTime.parse("02:53:40");
LocalTime l2 = LocalTime.parse("02:54:27");
</code></pre>
<p>How can I found different in minutes between them?</p> | 28,353,857 | 4 | 1 | null | 2015-02-05 20:49:41.937 UTC | 2 | 2016-03-02 12:35:55.883 UTC | null | null | null | null | 465,137 | null | 1 | 48 | java|localtime | 38,842 | <p>Use <code>until</code> or <code>between</code>, as described by the <a href="http://docs.oracle.com/javase/8/docs/api/java/time/LocalTime.html#until-java.time.temporal.Temporal-java.time.temporal.TemporalUnit-">api</a></p>
<pre><code>import java.time.LocalTime;
import static java.time.temporal.ChronoUnit.MINUTES;
public class SO {
public static void main(String[] args) {
LocalTime l1 = LocalTime.parse("02:53:40");
LocalTime l2 = LocalTime.parse("02:54:27");
System.out.println(l1.until(l2, MINUTES));
System.out.println(MINUTES.between(l1, l2));
}
}
</code></pre>
<blockquote>
<p>0
<br>
0</p>
</blockquote> |
8,916,532 | java.lang.NoSuchMethodError: android.os.Bundle.getString | <pre><code>game.multiplayer = bundle.getString("multiplayer" ,null);
</code></pre>
<p>is giving the error:</p>
<pre><code>java.lang.NoSuchMethodError: android.os.Bundle.getString
</code></pre>
<p>Other methods like </p>
<pre><code> game.word.word = bundle.getStringArray("word");
</code></pre>
<p>work fine.</p>
<p>Anyone any idea?</p> | 8,916,617 | 5 | 1 | null | 2012-01-18 19:56:31.603 UTC | 4 | 2015-06-19 06:23:28.063 UTC | null | null | null | null | 1,104,939 | null | 1 | 28 | android | 9,615 | <p>getString(key, defValue) was added in API 12. Use getString(key), as this will return null if the key doesn't exist.</p> |
19,737,436 | Looping through each row in a datagridview | <p>How do I loop through each row of a <code>DataGridView</code> that I read in? In my code, the rows won't bind to the next row because of the same productID, so the <code>DataGridView</code> won't move to a new row. It stays on the same row and overwrites the price (for some products, I have two prices). How do I loop through each row to show the same productID but have a different price?</p>
<p>EX : 1 Hamburger has 2 prices -- $1 and $2. After looping through the data, the result should have 2 rows with the same product but different pricing. How do I do this? Below is my code:</p>
<pre><code>productID = odr["product_id"].ToString();
quantity = Double.Parse(odr["quantity"].ToString());
//processing data...
key = productID.ToString();
if (key != key_tmp)
{
//update index...
i++;
//updating variable(s)...
key_tmp = key;
}
if (datagridviews.Rows[i].Cells["qty"].Value != null) //already has value...
{
currJlh = Double.Parse(ddatagridviews.Rows[i].Cells["qty"].Value.ToString());
}
else //not yet has value...
{
currQty = 0;
}
currQty += qty;
//show data...
datagridviews.Rows[i].Cells["price"].Value = cv.toAccountingCurrency_en(Double.Parse(odr["item_price"].ToString()));
MessageBoxes.Show(i.ToString());
MessageBoxes.Show(datagridviews.Rows[i].Cells["price"].Value.ToString()); // in here there is two price that looped but won't showed in datagridviews
</code></pre> | 19,737,522 | 3 | 1 | null | 2013-11-02 00:10:39.137 UTC | 5 | 2022-03-28 14:30:56.93 UTC | 2022-03-28 14:30:56.93 UTC | null | 2,666,368 | null | 2,666,368 | null | 1 | 29 | c#|loops|datagridview | 193,707 | <p>You could loop through <code>DataGridView</code> using <code>Rows</code> property, like:</p>
<pre><code>foreach (DataGridViewRow row in datagridviews.Rows)
{
currQty += row.Cells["qty"].Value;
//More code here
}
</code></pre> |
1,195,111 | C# MailTo with Attachment? | <p>Currently I am using the below method to open the users outlook email account and populate an email with the relevant content for sending:</p>
<pre><code>public void SendSupportEmail(string emailAddress, string subject, string body)
{
Process.Start("mailto:" + emailAddress + "?subject=" + subject + "&body="
+ body);
}
</code></pre>
<p>I want to however, be able to populate the email with an attached file.</p>
<p>something like:</p>
<pre><code>public void SendSupportEmail(string emailAddress, string subject, string body)
{
Process.Start("mailto:" + emailAddress + "?subject=" + subject + "&body="
+ body + "&Attach="
+ @"C:\Documents and Settings\Administrator\Desktop\stuff.txt");
}
</code></pre>
<p>However this does not seem to work.
Does anyone know of a way which will allow this to work!?</p>
<p>Help greatly appreciate.</p>
<p>Regards.</p> | 1,195,153 | 4 | 1 | null | 2009-07-28 16:03:46.14 UTC | 15 | 2017-04-15 17:52:29.803 UTC | 2012-12-21 21:24:05.587 UTC | null | 621,316 | null | 99,900 | null | 1 | 31 | c#|attachment|mailto | 82,397 | <p>mailto: doesn't officially support attachments. I've heard Outlook 2003 will work with this syntax:</p>
<pre><code><a href='mailto:[email protected]?Subject=SubjTxt&Body=Bod_Txt&Attachment=""C:\file.txt"" '>
</code></pre>
<p>A better way to handle this is to send the mail on the server using <a href="http://msdn.microsoft.com/en-us/library/system.net.mail.attachment.aspx" rel="nofollow noreferrer">System.Net.Mail.Attachment</a>.</p>
<pre><code> public static void CreateMessageWithAttachment(string server)
{
// Specify the file to be attached and sent.
// This example assumes that a file named Data.xls exists in the
// current working directory.
string file = "data.xls";
// Create a message and set up the recipients.
MailMessage message = new MailMessage(
"[email protected]",
"[email protected]",
"Quarterly data report.",
"See the attached spreadsheet.");
// Create the file attachment for this e-mail message.
Attachment data = new Attachment(file, MediaTypeNames.Application.Octet);
// Add time stamp information for the file.
ContentDisposition disposition = data.ContentDisposition;
disposition.CreationDate = System.IO.File.GetCreationTime(file);
disposition.ModificationDate = System.IO.File.GetLastWriteTime(file);
disposition.ReadDate = System.IO.File.GetLastAccessTime(file);
// Add the file attachment to this e-mail message.
message.Attachments.Add(data);
//Send the message.
SmtpClient client = new SmtpClient(server);
// Add credentials if the SMTP server requires them.
client.Credentials = CredentialCache.DefaultNetworkCredentials;
try {
client.Send(message);
}
catch (Exception ex) {
Console.WriteLine("Exception caught in CreateMessageWithAttachment(): {0}",
ex.ToString() );
}
data.Dispose();
}
</code></pre> |
437,958 | How can I exclude $(this) from a jQuery selector? | <p>I have something like this:</p>
<pre><code><div class="content">
<a href="#">A</a>
</div>
<div class="content">
<a href="#">B</a>
</div>
<div class="content">
<a href="#">C</a>
</div>
</code></pre>
<p>When one of these links is clicked, I want to perform the .hide() function on the links that are not clicked. I understand jQuery has the :not selector, but I can't figure out how to use it in this case because <strong>it is necessary that I select the links using <code>$(".content a")</code></strong></p>
<p>I want to do something like</p>
<pre><code>$(".content a").click(function()
{
$(".content a:not(this)").hide("slow");
});
</code></pre>
<p>but I can't figure out how to use the :not selector properly in this case.</p> | 437,979 | 4 | 1 | null | 2009-01-13 04:30:16.263 UTC | 42 | 2018-09-20 14:59:18.333 UTC | 2018-09-20 14:59:18.333 UTC | null | 1,264,804 | Logan Serman | 29,595 | null | 1 | 222 | jquery|jquery-selectors|this | 186,073 | <p>Try using the <a href="http://docs.jquery.com/Traversing/not" rel="noreferrer"><code>not()</code> <strong>method</strong></a> instead of the <a href="http://docs.jquery.com/Selectors/not" rel="noreferrer"><code>:not()</code> selector</a>.</p>
<pre><code>$(".content a").click(function() {
$(".content a").not(this).hide("slow");
});
</code></pre> |
303,725 | ASP.NET Application state vs a Static object | <p>if i have a standard ASP.NET application, is there any difference between making an object static as opposed to putting the object instance in the Application state?</p>
<p>from my understanding, both objects exist ONCE for the app domain.</p>
<p>Secondly, what happens if you have a static object in a referenced dll, for an ASP.NET site. It's also part of the app domain, so it will always exist once?</p> | 303,787 | 1 | 1 | null | 2008-11-19 23:00:14.667 UTC | 16 | 2008-11-19 23:23:46.79 UTC | null | null | null | Pure.Krome | 30,674 | null | 1 | 41 | asp.net|static-members|application-state | 9,528 | <p>From: <a href="http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312607" rel="noreferrer">http://support.microsoft.com/default.aspx?scid=kb;en-us;Q312607</a></p>
<blockquote>
<p>ASP.NET includes application state
primarily for compatibility with
classic ASP so that it is easier to
migrate existing applications to
ASP.NET. It is recommended that you
store data in static members of the
application class instead of in the
Application object. This increases
performance because you can access a
static variable faster than you can
access an item in the Application
dictionary.</p>
</blockquote>
<p>Also, yes, static variables behave the same way regardless of where they are loaded from, and exist exactly once per app domain (unless you're talking about those labeled [ThreadStatic])</p> |
42,230,304 | Checking if a request array is empty in Laravel | <p>I have a dynamically generated form that gives me an array of inputs. However the array might be empty, then the foreach will fail.</p>
<pre><code> public function myfunction(Request $request)
{
if(isset($request))
{
#do something
}
}
</code></pre>
<p>This obviously doesn't work since it is a $request object and is always set. I have no idea however how to check if there is any input at all.</p>
<p>Any ideas?</p> | 42,231,131 | 5 | 0 | null | 2017-02-14 15:41:02.347 UTC | 0 | 2022-01-03 12:22:10.37 UTC | null | null | null | null | 4,485,955 | null | 1 | 7 | php|arrays|laravel | 39,250 | <p>I always do this with my installations by adding a function to the <code>Controller</code> in the <code>App\Http\Controllers</code> directory.</p>
<pre><code>use Illuminate\Http\Request;
public function hasInput(Request $request)
{
if($request->has('_token')) {
return count($request->all()) > 1;
} else {
return count($request->all()) > 0;
}
}
</code></pre>
<p>Rather self explanatory, return true if other input variables outside of the <code>_token</code>, or return true if no <code>token</code> and contains other variables.</p> |
20,555,234 | How does one stub promise with sinon? | <p>I have a data service with following function</p>
<pre><code>function getInsureds(searchCriteria) {
var deferred = $q.defer();
insuredsSearch.get(searchCriteria,
function (insureds) {
deferred.resolve(insureds);
},
function (response) {
deferred.reject(response);
});
return deferred.promise;
}
</code></pre>
<p>I want to test following function:</p>
<pre><code>function search ()
{
dataService
.getInsureds(vm.searchCriteria)
.then(function (response) {
vm.searchCompleted = true;
if (response.insureds.length > 100) {
vm.searchResults = response.insureds.slice(0, 99);
} else {
vm.searchResults = response.insureds;
}
});
}
</code></pre>
<p>How would I stub the promise so that when I call getInsureds it would resolve the promise and return me the results immediately. I started like this (jasmine test), but I am stuck, as I don't know how to resolve the promise and pass in arguments needed.</p>
<pre><code>it("search returns over 100 results searchResults should contain only 100 records ", function () {
var results103 = new Array();
for (var i = 0; i < 103; i++) {
results103.push(i);
}
var fakeSearchForm = { $valid: true };
var isSearchValidStub = sinon.stub(sut, "isSearchCriteriaValid").returns(true);
var deferred = $q.defer();
var promise = deferred.promise;
var dsStub = sinon.stub(inSearchDataSvc, "getInsureds").returns(promise);
var resolveStub = sinon.stub(deferred, "resolve");
//how do i call resolve and pass in results103
sut.performSearch(fakeSearchForm);
sinon.assert.calledOnce(isSearchValidStub);
sinon.assert.calledOnce(dsStub);
sinon.assert.called(resolveStub);
expect(sut.searchResults.length).toBe(100);
});
</code></pre> | 20,614,500 | 5 | 0 | null | 2013-12-12 22:06:21.487 UTC | 14 | 2018-07-31 10:51:31.46 UTC | 2015-12-29 20:01:18.407 UTC | null | 690,413 | null | 103,682 | null | 1 | 64 | javascript|jasmine|sinon | 94,783 | <p>You just have to resolve the promise before you call the search function. This way your stub will return a resolved promise and <code>then</code> will be called immediately. So instead of </p>
<pre><code>var resolveStub = sinon.stub(deferred, "resolve");
</code></pre>
<p>you will resolve the deferred with your fake response data </p>
<pre><code>deferred.resolve({insureds: results103})
</code></pre> |
43,638,979 | Understanding Gitlab CI tags | <p>I've read documentation, some articles and you might call me dumb, but this is my first time working with a concept like this.</p>
<ul>
<li>I've registered runner with tag "testing"</li>
<li>created tag "testing" in gitlab</li>
<li>binded this runner, with particular project </li>
<li>I've also added the same tag e.g. "testing"in my local repo. </li>
</ul>
<p><strong>BUT how exactly is running my jobs dependent on those tags? Are all these operations necessary?</strong> If I push new code to repo, *.yml file is executed anyway as far as I tested.</p>
<p><strong>So what if I want to run build only when I define a version in a commit?</strong></p>
<p>IDK...</p>
<pre><code> git commit --tags "v. 2.0" -m "this is version 2.0" (probably not right)
</code></pre>
<p>But of course it should be universal, so I don't have to always tell, which tag to use to trigger the runner, but for example let him recognize numeric values.</p>
<p><strong>As you can see, I'm fairly confused... If you could elaborate how exactly tags work, so I would be able to understand the concept, I would be really grateful.</strong></p> | 43,745,896 | 3 | 0 | null | 2017-04-24 19:10:13.517 UTC | 10 | 2021-09-09 15:38:18.92 UTC | null | null | null | RiddleMeThis | 4,325,793 | null | 1 | 57 | tagging|gitlab|yaml | 102,722 | <p>Tags for GitLab CI and tags for Git are two different concepts.</p>
<p>When you write your <code>.gitlab-ci.yml</code>, you can specify some jobs with the tag <code>testing</code>. If a runner with this tag associated is available, it will pickup the job.</p>
<p>In Git, within your repository, tags are used to mark a specific commit. It is often used to <em>tag</em> a version.</p>
<p>The two concepts can be mixed up when you use tags (in Git) to start your pipeline in GitLab CI. In your <code>.gitlab-ci.yml</code>, you can specify the section <code>only</code> with <code>tags</code>.</p>
<p>Refer to <a href="https://docs.gitlab.com/ee/ci/yaml/#tags" rel="noreferrer">GitLab documentation for tags</a> and <a href="https://docs.gitlab.com/ee/ci/yaml/#only--except" rel="noreferrer">only</a>.</p>
<p>An example is when you push a tag with git:</p>
<pre><code>$ git tag -a 1.0.0 -m "1.0.0"
$ git push origin 1.0.0
</code></pre>
<p>And a job in <code>.gitlab-ci.yml</code> like this:</p>
<pre><code>compile:
stage: build
only: [tags]
script:
- echo Working...
tags: [testing]
</code></pre>
<p>would start using a runner with the <code>testing</code> tag.</p>
<p>By my understanding, what is missing in your steps is to specify the tag <code>testing</code> to your runner. To do this, go in GitLab into your project. Next to
<strong>Wiki</strong>, click on <strong>Settings</strong>. Go to <strong>CI/CD Pipelines</strong> and there you have your runner(s). Next to its Guid, click on the pen icon. On next page the tags can be modified.</p> |
44,936,028 | Progress Bar with axios | <p>I have to display the upload status of the file using a Progress Bar. I am using <code>axios</code> to make http requests. I followed the example from their github page <a href="https://github.com/mzabriskie/axios/blob/master/examples/upload/index.html" rel="noreferrer">https://github.com/mzabriskie/axios/blob/master/examples/upload/index.html</a></p>
<p>My code looks like this:</p>
<pre><code>this.store().then(() => {
var form = new FormData();
form.append('video', this.file);
form.append('uid', this.uid);
axios.post('/upload', form, {
progress: (progressEvent) => {
if (progressEvent.lengthComputable) {
console.log(progressEvent.loaded + ' ' + progressEvent.total);
this.updateProgressBarValue(progressEvent);
}
}
})
});
</code></pre>
<p>However, it is not executing the <code>console.log(progressEvent.loaded + ' ' + progressEvent.total);</code> at all nor is it calling <code>this.updateProgressBarValue(progressEvent);</code></p>
<p>How can I solve this??</p> | 44,937,301 | 4 | 0 | null | 2017-07-05 21:09:42.557 UTC | 5 | 2021-04-30 23:46:15.657 UTC | 2020-02-18 16:24:22.73 UTC | null | 6,778,849 | null | 5,924,007 | null | 1 | 43 | javascript|progress-bar|vuejs2|axios | 78,274 | <p>I found the answer. The name of the event is <code>onUploadProgress</code> and I was using <code>progress</code></p> |
29,018,842 | RStudio enters debug mode for every function error - how can I stop it? | <p>I've been using RStudio for years, and this has never happened to me before. For some reason, every time a function throws an error, RStudio goes into debug mode (I don't want it to). Even after using undebug() on a single function.</p>
<pre><code>> undebug(http.get)
Warning message:
In undebug(fun) : argument is not being debugged
> x = http.get(country = 'KE')
http --timeout=60 get "http://[email protected]/observation?country=KE" > freshobs.json </dev/null
Error in fromJSON(file = "freshobs.json") : unexpected character 'O'
Error in el[["product_name"]] : subscript out of bounds
Called from: grepl(el[["product_name"]], pattern = "json:", fixed = T)
Browse[1]> Q
</code></pre>
<p>Any function I use that breaks causes debug mode to start - which is pretty annoying because it opens up a source viewer and takes you away from your code. Anybody know how to stop this functionality?
This happens when the 'Use debug mode only when my code contains errors' check box in Preferences is and is not checked.</p>
<p>Thanks!</p> | 32,330,588 | 5 | 0 | null | 2015-03-12 19:40:56.343 UTC | 3 | 2020-04-23 14:43:25.29 UTC | null | null | null | null | 2,521,469 | null | 1 | 38 | r|debugging|rstudio | 8,622 | <p>I tried fixing this issue by putting <code>options(error = NULL)</code> in my <code>.Rprofile</code>, but this did not work.</p>
<p>What did work was to go to the <a href="https://support.rstudio.com/hc/en-us/articles/205612627-Debugging-with-RStudio#stopping-when-an-error-occurs">"Debug" -> "On Error" menu and select "Message only"</a>. This effectively is the same as setting <code>options(error = NULL)</code>, but it is persistent across restarts.</p>
<p><img src="https://support.rstudio.com/hc/en-us/article_attachments/201608428/break-in-code.png" alt="RStudio menu"></p> |
40,411,283 | Laravel how to test if a checkbox is checked in a controller | <p>I tried to get if checkbox is checked with:</p>
<p>In my view:</p>
<pre class="lang-php prettyprint-override"><code><form data-toggle="validator" data-disable="false" role="form" action="/admin/role/add" method="post">
<div class="checkbox checkbox-success">
<input name="test" id="test" type="checkbox" value="test">
<label for="test" style="padding-left: 15px!important;">test</label>
</div>
</form>
<form data-toggle="validator" data-disable="false" role="form" action="/admin/role/add" method="post">
{{ csrf_field() }}
<div class="form-group pull-right">
<button type="submit" class="btn btn-danger">Submit</button>
</div>
</form>
</code></pre>
<p>In my controller :</p>
<pre class="lang-php prettyprint-override"><code>public function createRole(Request $request)
{
if($request->has('test')) {
new \App\Debug\Firephp('test', ['test' => true]);
}
}
</code></pre>
<p>In my <code>web.php</code>:</p>
<pre class="lang-php prettyprint-override"><code>Route::post('/admin/role/add', 'AdminController@createRole')
</code></pre>
<p>but doesn't work for some reason.</p>
<p>How i can do?</p>
<p>Thanks for reply.</p>
<p><strong>EDIT 1 :</strong></p>
<p>It was my form that was poorly build.</p> | 40,412,853 | 6 | 5 | null | 2016-11-03 21:09:33.743 UTC | null | 2021-08-25 06:53:16.917 UTC | 2020-08-25 08:28:31.143 UTC | null | 7,047,493 | null | 7,047,493 | null | 1 | 10 | php|laravel | 64,288 | <p>I believe your real problem is that you have two separate forms. Your checkbox is in one form, your submit button is in a second form. I believe they both need to be in the same form. Otherwise your checkbox state is never returned, regardless of it's state.</p>
<p>In your view, try replacing the form markup you provided with this:</p>
<pre><code><form data-toggle="validator" data-disable="false" role="form" action="/admin/role/add" method="post">
<div class="checkbox checkbox-success">
<input name="test" id="test" type="checkbox" value="test">
<label for="test" style="padding-left: 15px!important;">test</label>
</div>
{{ csrf_field() }}
<div class="form-group pull-right">
<button type="submit" class="btn btn-danger">Submit</button>
</div>
</form>
</code></pre> |
20,461,165 | How to convert index of a pandas dataframe into a column | <p>This seems rather obvious, but I can't seem to figure out how to convert an index of data frame to a column?</p>
<p>For example:</p>
<pre><code>df=
gi ptt_loc
0 384444683 593
1 384444684 594
2 384444686 596
</code></pre>
<p>To,</p>
<pre><code>df=
index1 gi ptt_loc
0 0 384444683 593
1 1 384444684 594
2 2 384444686 596
</code></pre> | 20,461,206 | 8 | 1 | null | 2013-12-09 00:34:16.403 UTC | 181 | 2022-09-24 18:16:41.613 UTC | 2021-04-23 21:43:53.693 UTC | null | 7,758,804 | null | 1,090,629 | null | 1 | 742 | python|pandas|dataframe|indexing|series | 1,050,432 | <p>either:</p>
<pre><code>df['index1'] = df.index
</code></pre>
<p>or, <a href="https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="noreferrer"><code>.reset_index</code></a>:</p>
<pre><code>df = df.reset_index(level=0)
</code></pre>
<hr />
<p>so, if you have a multi-index frame with 3 levels of index, like:</p>
<pre><code>>>> df
val
tick tag obs
2016-02-26 C 2 0.0139
2016-02-27 A 2 0.5577
2016-02-28 C 6 0.0303
</code></pre>
<p>and you want to convert the 1st (<code>tick</code>) and 3rd (<code>obs</code>) levels in the index into columns, you would do:</p>
<pre><code>>>> df.reset_index(level=['tick', 'obs'])
tick obs val
tag
C 2016-02-26 2 0.0139
A 2016-02-27 2 0.5577
C 2016-02-28 6 0.0303
</code></pre> |
20,853,066 | How to center form in bootstrap 3 | <p>How can I center my login form ? I'm using bootstrap column but it's not working.</p>
<p>Here is my code:</p>
<pre><code><div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-6">
<h2>Log in</h2>
<div>
<table>
<tr>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>3</td>
<td>3</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</code></pre> | 20,853,119 | 10 | 1 | null | 2013-12-31 06:42:57.17 UTC | 21 | 2021-11-27 01:51:11.853 UTC | 2015-11-11 07:50:54.65 UTC | null | 3,885,376 | null | 2,836,246 | null | 1 | 66 | html|css|twitter-bootstrap|twitter-bootstrap-3 | 309,886 | <p>A simple way is to add </p>
<pre><code>.center_div{
margin: 0 auto;
width:80% /* value of your choice which suits your alignment */
}
</code></pre>
<p>to you class <code>.container</code>.Add <code>width:xx %</code> to it and you get perfectly centered div!</p>
<p>eg :</p>
<pre><code><div class="container center_div">
</code></pre>
<p>but i feel that by default <code>container</code> is centered in BS!</p> |
32,413,025 | ES6 Destructuring in Class constructor | <p>This may sound ridiculous but bear with me. I wonder if there is support on the language level to destructure object into class properties in constructor, e.g.</p>
<pre><code>class Human {
// normally
constructor({ firstname, lastname }) {
this.firstname = firstname;
this.lastname = lastname;
this.fullname = `${this.firstname} ${this.lastname}`;
}
// is this possible?
// it doesn't have to be an assignment for `this`, just something
// to assign a lot of properties in one statement
constructor(human) {
this = { firstname, lastname };
this.fullname = `${this.firstname} ${this.lastname}`;
}
}
</code></pre> | 32,413,517 | 1 | 3 | null | 2015-09-05 12:25:52.963 UTC | 7 | 2015-09-05 13:18:38.47 UTC | null | null | null | null | 1,684,058 | null | 1 | 33 | javascript|ecmascript-6|destructuring | 20,512 | <p>You cannot assign to <code>this</code> anywhere in the language.</p>
<p>One option is to merge into <code>this</code> or other object:</p>
<pre><code>constructor(human) {
Object.assign(this, human);
}
</code></pre> |
25,420,470 | Limit the number of pages displayed in bootstrap 3 pagination | <p>I have various web pages on my website which are using bootstraps (bootstrap 3) pagination but I need to know how to limit the number of pages displayed in it (e.g. display pages 1 to 10 only).</p>
<p>If you then select page 2, page 11 would b displayed and so on.</p>
<p>How do you do this?</p>
<p>I know it will probably be JavaScript/jQuery but any help is appreciated. and if it can be done without having to use JavaScript/jQuery, then all the better.</p>
<p>Below is a screenshot of my pagination.</p>
<p><img src="https://i.stack.imgur.com/MsLrm.png" alt="Current pagination"></p>
<p>As you can see there are 12 pages displayed, I would like pages 11 & 12 to be hidden until page 2 or the next page is selected then pages 11 would be displayed and pages one would be hidden, so on and so on.</p> | 25,421,197 | 4 | 3 | null | 2014-08-21 07:20:29.91 UTC | 1 | 2018-08-24 17:19:40.45 UTC | 2018-04-17 04:17:24.57 UTC | null | 534,109 | null | 3,194,213 | null | 1 | 24 | javascript|jquery|css|twitter-bootstrap|pagination | 51,630 | <p>There is a jquery plugin to work with bootstrap, that solves this problem:
<a href="http://josecebe.github.io/twbs-pagination/" rel="noreferrer">http://josecebe.github.io/twbs-pagination/</a>
Have a look at the "visible pages option" section.</p>
<p>You can find more/other solutions with google and <code>bootstrap 3 pagination many pages</code>.</p> |
39,644,638 | How to take the nth digit of a number in python | <p>I want to take the nth digit from an N digit number in python. For example:</p>
<pre><code>number = 9876543210
i = 4
number[i] # should return 6
</code></pre>
<p>How can I do something like that in python? Should I change it to string first and then change it to int for the calculation?</p> | 39,644,706 | 7 | 2 | null | 2016-09-22 16:46:31.04 UTC | 7 | 2021-04-27 18:40:28.43 UTC | 2016-09-23 01:00:04.697 UTC | null | 3,254,859 | null | 6,865,397 | null | 1 | 57 | python|int | 183,964 | <p>First treat the number like a string</p>
<pre><code>number = 9876543210
number = str(number)
</code></pre>
<p>Then to get the first digit:</p>
<pre><code>number[0]
</code></pre>
<p>The fourth digit:</p>
<pre><code>number[3]
</code></pre>
<p>EDIT:</p>
<p>This will return the digit as a character, not as a number. To convert it back use:</p>
<pre><code>int(number[0])
</code></pre> |
39,717,516 | Why is System.Net.Http.HttpMethod a class, not an enum? | <p><code>HttpStatusCode</code> is implemented as an <code>enum</code>, with each possible value assigned to its corresponding HTTP status code (e.g. <code>(int)HttpStatusCode.Ok == 200</code>).</p>
<p>However, <code>HttpMethod</code> is <a href="https://msdn.microsoft.com/en-us/library/system.net.http.httpmethod(v=vs.118).aspx" rel="noreferrer">implemented as a <code>class</code></a>, with static properties to get instances for the various HTTP verbs (<code>HttpMethod.Get</code>, <code>HttpMethod.Put</code> etc). What is the rationale behind <em>not</em> implementing <code>HttpMethod</code> as an <code>enum</code>?</p> | 39,717,699 | 2 | 2 | null | 2016-09-27 06:29:58.743 UTC | null | 2021-08-18 13:05:02.493 UTC | 2021-01-19 19:20:42.64 UTC | null | 704,022 | null | 38,055 | null | 1 | 28 | c#|language-design | 16,576 | <p>From the <a href="https://msdn.microsoft.com/en-us/library/system.net.http.httpmethod(v=vs.110).aspx#Anchor_6">documentation</a> (emphasis mine):</p>
<blockquote>
<p><strong>Remarks</strong></p>
<p>The most common usage of HttpMethod is to use one of the static properties on this class. <em>However, if an app needs a different value for the HTTP method, the HttpMethod constructor initializes a new instance of the HttpMethod with an HTTP method that the app specifies.</em></p>
</blockquote>
<p>Which is of course not possible with an enum.</p>
<p>See its <a href="https://msdn.microsoft.com/en-us/library/system.net.http.httpmethod.httpmethod(v=vs.110).aspx">constructor</a> and <a href="https://msdn.microsoft.com/en-us/library/system.net.http.httpmethod.method(v=vs.110).aspx">method property</a>.</p> |
31,446,603 | How to make type cast for python custom class | <p>Consider a class;</p>
<pre><code>class temp:
def __init__(self):
pass
</code></pre>
<p>I make an object of it;</p>
<pre><code>obj = temp()
</code></pre>
<p>Convert it to string;</p>
<pre><code>strObj = str(obj)
</code></pre>
<p>Now, how can i convert strObj to an object of temp class??</p>
<pre><code>org = temp(strObj)
</code></pre> | 31,447,048 | 6 | 7 | null | 2015-07-16 06:19:43.203 UTC | 1 | 2021-09-07 02:02:00.89 UTC | null | null | null | null | 2,177,330 | null | 1 | 15 | python|class|python-2.7|casting | 38,051 | <p>As noted by Anand in comments, what you're looking for is object serialization and deserialization. One way to achieve this is through the pickle (or cPickle) module:</p>
<pre><code>>>> import pickle
>>> class Example():
... def __init__(self, x):
... self.x = x
...
>>> a = Example('foo')
>>> astr = pickle.dumps(a) # (i__main__\nExample\np0\n(dp1\nS'x'\np2\nS'foo'\np3\nsb.
>>> b = pickle.loads(astr)
>>> b
<__main__.Example instance at 0x101c89ea8>
>>> b.x
'foo'
</code></pre>
<p>Note, however, that one gotcha in using the pickle module is dealing with implementation versions. As suggested in the Python docs, if you want an unpickled instance to automatically handle implementation versioning, you may want to add a version instance attribute and add a custom __setstate__ implementation: <a href="https://docs.python.org/2/library/pickle.html#object.__setstate__" rel="nofollow">https://docs.python.org/2/library/pickle.html#object.<strong>setstate</strong></a>. Otherwise, the version of the object at serialization time will be exactly what you get at deserialization time, regardless of code changes made to the object itself.</p> |
31,431,341 | SQL Adding a column to a table, with case statement | <p><em>I have my case statement but would like to add the new column "Unit_Type" to the table...</em></p>
<pre><code>Unit_type =(case [INSP_UNIT_TYPE_ID]
when '9' then 'Semi Trailer'
when '7' then 'Pole Trailer'
when '6' then 'Other'
when '5' then 'Motor Carrier'
when '3' then 'Full Trailer'
when '2' then 'Dolly Converter'
when '14' then 'Intermodal Chassis'
when '12' then 'Van'
when '11' then 'Truck Tractor'
when '10' then 'Straight Truck'
else 'Invalid'
end) from [dbo].[Insp_Unit_Pub_01012015_05282015];
</code></pre> | 31,432,451 | 2 | 8 | null | 2015-07-15 13:10:19.187 UTC | 3 | 2015-07-15 14:27:13.147 UTC | 2015-07-15 13:10:42.603 UTC | null | 2,686,013 | null | 5,119,519 | null | 1 | 2 | sql | 42,081 | <p>don't do that and use a view.</p>
<p>the above suggestion is the result of a wild guess because you provide neither context nor database structure so it may be plain wrong or not suitable for your situation.</p>
<p>your untold requirement looks like some kind of visualization of the table with human readable data and that's what views are good for.</p>
<p>create a view adding the required joins or including the CASE statement you are trying to put in the table (check the syntax ^^):</p>
<pre><code>CREATE VIEW [name of the view here]
AS
SELECT field1,
field2,
field3,
Unit_type = CASE [INSP_UNIT_TYPE_ID]
WHEN '9' THEN 'Semi Trailer'
WHEN '7' THEN 'Pole Trailer'
WHEN '6' THEN 'Other'
WHEN '5' THEN 'Motor Carrier'
WHEN '3' THEN 'Full Trailer'
WHEN '2' THEN 'Dolly Converter'
WHEN '14' THEN 'Intermodal Chassis'
WHEN '12' THEN 'Van'
WHEN '11' THEN 'Truck Tractor'
WHEN '10' THEN 'Straight Truck'
ELSE 'Invalid'
END
FROM [dbo].[Insp_Unit_Pub_01012015_05282015];
</code></pre>
<p>as suggested by some comment you may put a <code>JOIN</code> in the query instead of the <code>CASE</code> statement if the human readable text comes from a lookup table.</p> |
6,800,467 | Quotes in XML. Single or double? | <p>I've heard that using single quotes to surround XML attribute values is a "bad style". Is this correct?</p>
<p>Should I always write: </p>
<pre><code><element attr="value">
</code></pre>
<p>Or is it acceptable to write: </p>
<pre><code><element attr='value'>
</code></pre>
<p>Or does it not matter which style I use?</p> | 6,800,482 | 2 | 2 | null | 2011-07-23 12:50:12.557 UTC | 4 | 2017-11-15 17:53:49.19 UTC | 2017-11-15 17:53:49.19 UTC | null | 3,357,935 | null | 377,133 | null | 1 | 80 | xml|formatting | 36,697 | <p>Both are legal. Choose one and stick with it. It doesn't matter.</p>
<p>From the <a href="http://www.w3.org/TR/xml/#NT-AttValue">spec</a>:</p>
<pre><code>AttValue ::= '"' ([^<&"] | Reference)* '"'
| "'" ([^<&'] | Reference)* "'"
</code></pre>
<p>Showing that both are valid, as is mixing the two styles within an element, per attribute (though I suggest being consistent within any single document/set of documents).</p> |
7,097,374 | PHP "pretty print" json_encode | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/6054033/pretty-printing-json-with-php">Pretty-Printing JSON with PHP</a> </p>
</blockquote>
<p>I'm working on a script that creates a JSON file. Right now I'm just using <code>json_encode</code> (PHP 5.2.x) to encode an array into JSON output. Then I print the returned value to a file and save it. Problem is that the client wants to be able to open these JSON files for readability, so I'd like to add line breaks in and "pretty print" the JSON output. Any ideas on how to do this? My only other alternative that I can see is to not use <code>json_encode</code> at all and just write the file contents manually and add in my own line breaks for each line.</p>
<p>Here's what I get:</p>
<pre><code>{"product_name":"prod1","val1":1,"val2":8}
</code></pre>
<p>Here's what I want:</p>
<pre><code>{
"product_name":"prod1",
"val1":1,
"val2":8
}
</code></pre>
<p>I suppose I could also just replace every comma with a command followed by a \n, and same for the brackets... Thoughts?</p> | 13,638,998 | 3 | 2 | null | 2011-08-17 18:06:21.567 UTC | 27 | 2019-01-26 03:51:21.903 UTC | 2017-05-23 11:54:40.827 UTC | null | -1 | null | 899,199 | null | 1 | 152 | php|json|encode | 189,893 | <p>PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).</p>
<p>This should do the job:</p>
<pre><code>$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);
</code></pre>
<p>See <a href="http://www.php.net/manual/en/function.json-encode.php" rel="noreferrer">http://www.php.net/manual/en/function.json-encode.php</a></p>
<p>Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)</p> |
7,099,191 | jquery .show('slow') direction? | <p>Is it possible to change direction of <code>$("selector").show('slow')</code> and <code>hide('slow')</code> effects in jQuery?</p>
<p>I can define directions for other effects such as slide and clip, but there's no option for show or <code>hide('slow')</code></p> | 7,099,260 | 4 | 0 | null | 2011-08-17 20:40:28.107 UTC | 2 | 2014-08-05 12:13:10.55 UTC | 2011-08-17 20:42:15.337 UTC | null | 871,050 | null | 100,240 | null | 1 | 26 | jquery|show|direction | 59,663 | <p><code>show()</code> is just an arbitrary function to display an element on a page. Without the argument it wouldn't even have an animation. If you want access to more elaborate animations and control the direction it fades in on you will need to use <a href="http://api.jquery.com/animate/"><code>.animate()</code></a></p>
<p>Or use an extra library that extends jQuery's native functions like <a href="http://jqueryui.com/">jQuery UI</a></p>
<p><code>show()</code> on itself doesn't have any extra effects though..</p> |
7,461,265 | how to use views in code first entity framework | <p>How can I use the database view in entity framework code first,</p> | 9,351,059 | 4 | 3 | null | 2011-09-18 11:48:58.043 UTC | 33 | 2022-01-18 12:10:31.913 UTC | 2015-06-22 18:54:10.75 UTC | null | 2,686,013 | null | 518,708 | null | 1 | 99 | .net|database|entity-framework|view|code-first | 111,972 | <p>If, like me, you are interested only in mapping entity coming from an other database (an erp in my case) to relate them to entities specific of your application, then you can use the views as you use a table (map the view in the same way!). Obviously, if you try to update that entities, you will get an exception if the view is not updatable.
The procedure is the same as in the case of normal (based on a table) entities:</p>
<ol>
<li><p>Create a POCO class for the view; for example FooView</p>
</li>
<li><p>Add the DbSet property in the DbContext class</p>
</li>
<li><p>Use a FooViewConfiguration file to set a different name for the view (using ToTable("Foo"); in the constructor) or to set particular properties</p>
<pre><code>public class FooViewConfiguration : EntityTypeConfiguration<FooView>
{
public FooViewConfiguration()
{
this.HasKey(t => t.Id);
this.ToTable("myView");
}
}
</code></pre>
</li>
<li><p>Add the FooViewConfiguration file to the modelBuilder, for example overriding the OnModelCreating method of the Context:</p>
<pre><code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new FooViewConfiguration ());
}
</code></pre>
</li>
</ol> |
21,803,830 | Why is the range object "not an iterator"? | <p>I wrote this and expected <code>0</code>:</p>
<pre><code>>>> x = range(20)
>>> next(x)
</code></pre>
<p>Instead I got:</p>
<blockquote>
<p>TypeError: 'range' object is not an iterator</p>
</blockquote>
<p>But I thought it was a generator?</p>
<p>The initial answer yielded the same thing I initially said to myself: it's an iterable, not an interator. But then, that wouldn't explain why this works, if both are simply generators:</p>
<pre><code>>>> x = (i for i in range(30))
>>> next(x)
0
</code></pre> | 21,803,943 | 4 | 2 | null | 2014-02-15 21:24:21.68 UTC | 8 | 2017-04-28 16:58:32.783 UTC | 2017-04-28 16:58:32.783 UTC | null | 236,247 | null | 1,029,146 | null | 1 | 30 | python|python-3.x|generator | 15,277 | <p><code>range</code> returns an iterable, not an iterator. It can make iterators when iteration is necessary. <strong>It is not a generator.</strong></p>
<p>A generator expression evaluates to an iterator (and hence an iterable as well).</p> |
2,162,061 | Specify constructor for the Unity IoC container to use | <p>I'm using the Unity IoC container for resolving my objects. However, I've run into an issue. When I have more than one constructor - how does Unity know which one to use? It seems to use the one with parameters when I have one with and one without. Can I explicitly tell it which constructor to use? </p>
<p>Specifically I had a case similar to the following Person class with two constructors. In this case I want the IoC container to use the default constructor - without parameters - but it chooses the one with parameters. </p>
<pre><code>public class SomeValueObject
{
public SomeValueObject(string name)
{
Name = name;
}
public string Name { get; set; }
}
public class Person
{
private string _name;
public Person()
{
_name = string.Empty;
}
public Person(SomeValueObject obj)
{
_name = obj.Name;
}
}
</code></pre>
<p>This obviously fails as it can't create the SomeValueObject - not knowing what to inject to its string parameter. The error it gives is: </p>
<blockquote>
<p>Resolution of the dependency failed, type = "MyApp.Person", name = "". Exception message is: The current build operation (build key Build Key[MyApp.Person, null]) failed: The parameter obj could not be resolved when attempting to call constructor MyApp.Person(MyApp.SomeValueObject obj). (Strategy type BuildPlanStrategy, index 3)</p>
</blockquote>
<p>The container registration: </p>
<pre><code>Container.RegisterType<Person, Person>(new Microsoft.Practices.Unity.ContainerControlledLifetimeManager());
</code></pre>
<p>And the resolving: </p>
<pre><code>var person = Container.Resolve<Person>();
</code></pre> | 2,162,119 | 4 | 3 | null | 2010-01-29 13:05:00.627 UTC | 6 | 2010-03-25 16:54:55.913 UTC | 2010-03-25 16:54:55.913 UTC | null | 25,300 | null | 100,894 | null | 1 | 44 | c#|.net|unity-container|ioc-container | 22,871 | <p>Register it like this instead:</p>
<pre><code>container.RegisterType<Person>(new InjectionConstructor());
</code></pre>
<p>You can add the LifetimeManager as well using an overload of the RegisterType method.</p>
<p>That said, when modeling for DI, your life will be much easier if you have unambiguous contructors (i.e. no overloaded constructors).</p> |
1,756,825 | How can I do a CPU cache flush in x86 Windows? | <p>I am interested in forcing a CPU cache flush in Windows (for benchmarking reasons, I want to emulate starting with no data in CPU cache), preferably a basic C implementation or Win32 call.</p>
<p>Is there a known way to do this with a system call or even something as sneaky as doing say a large <code>memcpy</code>?</p>
<p>Intel i686 platform (P4 and up is okay as well). </p> | 1,757,198 | 4 | 0 | null | 2009-11-18 15:34:11.88 UTC | 29 | 2021-11-21 20:07:37.86 UTC | 2015-11-08 10:31:34.033 UTC | null | 895,245 | null | 183,135 | null | 1 | 51 | c|windows|x86|cpu|cpu-cache | 37,565 | <p>Fortunately, there is more than one way to explicitly flush the caches.</p>
<p>The instruction "wbinvd" writes back modified cache content and marks the caches empty. It executes a bus cycle to make external caches flush their data. Unfortunately, it is a privileged instruction. But if it is possible to run the test program under something like DOS, this is the way to go. This has the advantage of keeping the cache footprint of the "OS" very small.</p>
<p>Additionally, there is the "invd" instruction, which invalidates caches <strong>without</strong> flushing them back to main memory. This violates the coherency of main memory and cache, so you have to take care of that by yourself. Not really recommended.</p>
<p>For benchmarking purposes, the simplest solution is probably copying a large memory block to a region marked with WC (write combining) instead of WB. The memory mapped region of the graphics card is a good candidate, or you can mark a region as WC by yourself via the MTRR registers.</p>
<p>You can find some resources about benchmarking short routines at <a href="http://www.agner.org/optimize/" rel="noreferrer">Test programs for measuring clock cycles and performance monitoring.</a></p> |
2,211,030 | failing to compile a project, missing io.h file | <p>I fail to compile a C++ project for mobile device with Windows Mobile (Windows CE-based) operating system and Visual C++ compiler from Visual Studio fails with:</p>
<pre><code>Error 1 fatal error C1083: Cannot open include file: 'io.h'
</code></pre>
<p><strong>EDIT</strong><br>
I am trying to compile the SQLite amalgamation, the shell.c file includes the call to this io.h but the io.h is missing from the files.</p>
<p>I googled and I couldn't locate how can I get this .h file. </p>
<p>Can someone point me in the right direction?</p> | 2,211,614 | 5 | 6 | null | 2010-02-05 22:55:12.327 UTC | 0 | 2014-04-28 14:39:05.187 UTC | 2010-02-06 01:35:54.28 UTC | null | 151,641 | null | 243,782 | null | 1 | 5 | c++|compiler-construction|compact-framework|include | 40,551 | <p>The <code>io.h</code> file is <strong>not</strong> available in SDKs for Windows CE-based systems like Windows Mobile.
In fact, <code>io.h</code> header has never been a part of ISO C nor C++ standards. It defines features that belongs <a href="http://en.wikipedia.org/wiki/Microsoft_POSIX_subsystem" rel="noreferrer">POSIX compatibility layer</a> on Windows NT, but not <a href="http://en.wikipedia.org/wiki/Microsoft_Windows_CE" rel="noreferrer">Windows CE</a>.</p>
<p>Due to lack of POSIX features on Windows CE, I developed a small utility library <a href="http://wcelibcex.sourceforge.net/" rel="noreferrer">WCELIBCEX</a>. <a href="http://wcelibcex.svn.sourceforge.net/viewvc/wcelibcex/trunk/src/wce_io.h?revision=62&view=markup" rel="noreferrer">It does include io.h</a> but a very minimal version and which is likely insufficient for SQLite. However, as <em>ctacke</em> mentioned, you should use <a href="http://sqlite-wince.sourceforge.net/" rel="noreferrer">SQLite port for Windows CE</a> because original version of SQLite is not compilable for this platform.</p>
<p>p.s. Note, Your question does not specify explicitly that you're building for Windows Mobile. If one doesn't spot the .NET Compact Framework mentioned in tags, then the whole question is ambiguous.</p> |
52,640,271 | Why is String.prototype.substr() deprecated? | <p>It is mentioned on the ECMAScript standard <a href="https://www.ecma-international.org/ecma-262/9.0/index.html#sec-additional-ecmascript-features-for-web-browsers" rel="noreferrer">here</a> that :</p>
<blockquote>
<p>... These features are not considered part of the core ECMAScript
language. Programmers should not use or assume the existence of these
features and behaviours when writing new ECMAScript code. ECMAScript
implementations are discouraged from implementing these features
unless the implementation is part of a web browser or is required to
run the same legacy ECMAScript code that web browsers encounter.</p>
</blockquote>
<p>There is also a red warning on MDN : <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr" rel="noreferrer">String.prototype.substr() MDN doc</a></p>
<p>Does anyone know why (ECMAScript standard say that) programmers should not use or assume the existence of <code>String.prototype.substr</code> ?</p> | 52,640,366 | 3 | 5 | null | 2018-10-04 06:21:52.44 UTC | 5 | 2022-03-29 08:52:11.043 UTC | 2022-03-29 08:52:11.043 UTC | null | 123,671 | null | 3,614,478 | null | 1 | 89 | javascript|standards|ecma | 52,184 | <p>Because it's never been part of the standardized language. It wasn't in the ECMAScript 1 or 2 specs at all, and only appears in ECMAScript 3 in Section B.2 ("Additional Properties") (and subsequent editions in similar annexes through to <a href="https://tc39.es/ecma262/#sec-string.prototype.substr" rel="noreferrer">today</a> [ES2022 draft as of this writing]), which said:¹</p>
<blockquote>
<p>Some implementations of ECMAScript have included additional properties for some of the standard native objects. This non-normative annex suggests uniform semantics for such properties without making the properties or their semantics part of this standard.</p>
</blockquote>
<p>Moreover, <code>substr</code> is largely redundant with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring" rel="noreferrer"><code>substring</code></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/slice" rel="noreferrer"><code>slice</code></a>, but the second argument has a different meaning,.</p>
<p>In pragmatic terms, I'd be surprised if you found a full mainstream JavaScript engine that didn't provide it; but I wouldn't be surprised if JavaScript engines targeted at embedded/constrained environments use <em>didn't</em> provide it.</p>
<hr />
<p>¹ That wording has changed more recently to:</p>
<blockquote>
<p>The ECMAScript language syntax and semantics defined in this annex are required when the ECMAScript host is a web browser. The content of this annex is normative but optional if the ECMAScript host is not a web browser.</p>
<hr />
<p>NOTE
This annex describes various legacy features and other characteristics of web browser ECMAScript hosts. All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification. However, the usage of these features by large numbers of existing web pages means that web browsers must continue to support them. The specifications in this annex define the requirements for interoperable implementations of these legacy features.</p>
<p>These features are not considered part of the core ECMAScript language. Programmers should not use or assume the existence of these features and behaviours when writing new ECMAScript code. ECMAScript implementations are discouraged from implementing these features unless the implementation is part of a web browser or is required to run the same legacy ECMAScript code that web browsers encounter.</p>
<hr />
</blockquote> |
28,689,524 | Show Real Time, Date, Day of the Week in javascript or jquery | <p>How to show real time, date, day in this format?</p>
<p><img src="https://i.stack.imgur.com/Cl6wx.jpg" alt="enter image description here"></p>
<p>The time should be actual (which runs the seconds count).</p>
<p>Thanks guys!</p> | 28,691,832 | 3 | 2 | null | 2015-02-24 06:32:50.397 UTC | 3 | 2015-02-24 09:12:28.95 UTC | null | null | null | null | 4,235,233 | null | 1 | 8 | javascript|jquery|date|time | 38,549 | <p>To update time panel every second we should use <code>setInterval()</code> function.</p>
<p>To format date the way you need the best approach is to use <code>moment.js</code> library. The code is shortened greatly:</p>
<pre><code>$(document).ready(function() {
var interval = setInterval(function() {
var momentNow = moment();
$('#date-part').html(momentNow.format('YYYY MMMM DD') + ' '
+ momentNow.format('dddd')
.substring(0,3).toUpperCase());
$('#time-part').html(momentNow.format('A hh:mm:ss'));
}, 100);
});
</code></pre>
<p><a href="http://jsfiddle.net/ivangrs/zf80q3nh/">Here is working fiddle</a></p> |
26,306,326 | Swift apply .uppercaseString to only the first letter of a string | <p>I am trying to make an autocorrect system, and when a user types a word with a capital letter, the autocorrect doesn't work. In order to fix this, I made a copy of the string typed, applied .lowercaseString, and then compared them. If the string is indeed mistyped, it should correct the word. However then the word that replaces the typed word is all lowercase. So I need to apply .uppercaseString to only the first letter. I originally thought I could use</p>
<pre><code>nameOfString[0]
</code></pre>
<p>but this apparently does not work. How can I get the first letter of the string to uppercase, and then be able to print the full string with the first letter capitalized? </p>
<p>Thanks for any help!</p> | 26,306,372 | 30 | 1 | null | 2014-10-10 19:03:39.52 UTC | 47 | 2021-09-15 11:32:58.227 UTC | 2019-02-19 02:45:55.167 UTC | null | 2,303,865 | null | 1,672,545 | null | 1 | 269 | ios|swift|string|ios8-extension | 176,389 | <p>Including mutating and non mutating versions that are consistent with API guidelines.</p>
<p><strong>Swift 3:</strong></p>
<pre><code>extension String {
func capitalizingFirstLetter() -> String {
let first = String(characters.prefix(1)).capitalized
let other = String(characters.dropFirst())
return first + other
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
</code></pre>
<p><strong>Swift 4:</strong></p>
<pre><code>extension String {
func capitalizingFirstLetter() -> String {
return prefix(1).uppercased() + self.lowercased().dropFirst()
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
</code></pre> |
7,223,530 | How can I properly center a JPanel ( FIXED SIZE ) inside a JFrame? | <p>Hi all!
I'm trying to solve an -apparently- simple problem, but I cannot fix it.
I'm working on a sample application with Java/Swing libraries;
I have a JFrame and a JPanel.
I just want to achieve the following objectives:</p>
<ol>
<li><p>JPanel <em>MUST</em> be centered inside the JFrame.</p></li>
<li><p>JPanel <em>MUST</em> have <em>ALWAYS</em> the size that is specified with<br>
setPreferredSize() method. It MUST NOT be resized under this size.</p></li>
</ol>
<p>I tried by using a GridBagLayout: it's the <em>ONLY</em> way I can do it.</p>
<p>See the sample below:</p>
<pre><code>/* file StackSample01.java */
import java.awt.*;
import javax.swing.*;
public class StackSample01 {
public static void main(String [] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.setBackground(Color.RED);
frame.setLayout(new GridBagLayout());
frame.add(panel, new GridBagConstraints());
frame.setSize(new Dimension(200, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
</code></pre>
<p><a href="http://i1141.photobucket.com/albums/n589/IT00/Screenshot01.png">Here</a> a screenshot: </p>
<p>I would not use a GridBagLayout to do a thing too simple.
I tried a simplest solution, by using a Box, but this does not work:</p>
<p>Sample code:</p>
<pre><code>/* file StackSample02.java */
import java.awt.*;
import javax.swing.*;
public class StackSample02 {
public static void main(String [] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(100, 100));
panel.setBackground(Color.RED); // for debug
panel.setAlignmentX(JComponent.CENTER_ALIGNMENT); // have no effect
Box box = new Box(BoxLayout.Y_AXIS);
box.add(Box.createVerticalGlue());
box.add(panel);
box.add(Box.createVerticalGlue()); // causes a deformation
frame.add(box);
frame.setSize(new Dimension(200, 200));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
</code></pre>
<p><a href="http://i1141.photobucket.com/albums/n589/IT00/Screenshot02.png">Here</a> a screenshot, </p>
<p>Any ideas? Thanks to all :-)</p> | 7,224,700 | 6 | 5 | null | 2011-08-28 20:00:29.05 UTC | 8 | 2014-09-05 06:28:14.163 UTC | 2011-08-28 20:36:46.817 UTC | null | 702,048 | null | 871,766 | null | 1 | 17 | java|swing|gridbaglayout | 66,423 | <p><a href="http://download.oracle.com/javase/tutorial/uiswing/layout/box.html" rel="noreferrer">BoxLayout</a> can pretty to hold your setXxxSize(), then just add <code>panel.setMaximumSize(new Dimension(100, 100));</code></p>
<p>and your output would be </p>
<p><strong>Removed by setMinimumSize</strong>(<em>notice if Container has greater size as ... )</em></p>
<p><img src="https://i.stack.imgur.com/Lry74.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/3F1kO.png" alt="enter image description here">
<img src="https://i.stack.imgur.com/cgdMn.png" alt="enter image description here"></p>
<pre><code>import java.awt.*;
import javax.swing.*;
public class CustomComponent12 extends JFrame {
private static final long serialVersionUID = 1L;
public CustomComponent12() {
Box box = new Box(BoxLayout.Y_AXIS);
box.setAlignmentX(JComponent.CENTER_ALIGNMENT);
box.add(Box.createVerticalGlue());
box.add(new CustomComponents12());
box.add(Box.createVerticalGlue());
add(box);
pack();
setTitle("Custom Component Test / BoxLayout");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setMaximumSize(getMinimumSize());
setMinimumSize(getMinimumSize());
setPreferredSize(getPreferredSize());
setLocation(150, 150);
setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
CustomComponent12 main = new CustomComponent12();
}
};
javax.swing.SwingUtilities.invokeLater(r);
}
}
class CustomComponents12 extends JPanel {
private static final long serialVersionUID = 1L;
@Override
public Dimension getMinimumSize() {
return new Dimension(100, 100);
}
@Override
public Dimension getMaximumSize() {
return new Dimension(100, 100);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
@Override
public void paintComponent(Graphics g) {
int margin = 10;
Dimension dim = getSize();
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(margin, margin, dim.width - margin * 2, dim.height - margin * 2);
}
}
</code></pre> |
7,504,546 | View-based NSTableView with rows that have dynamic heights | <p>I have an application with a view-based <code>NSTableView</code> in it. Inside this table view, I have rows that have cells that have content consisting of a multi-row <code>NSTextField</code> with word-wrap enabled. Depending on the textual content of the <code>NSTextField</code>, the size of the rows needed to display the cell will vary. </p>
<p>I know that I can implement the <code>NSTableViewDelegate</code> method -<code>tableView:heightOfRow:</code> to return the height, but the height will be determined based on the word wrapping used on the <code>NSTextField</code>. The word wrapping of the <code>NSTextField</code> is similarly based on how wide the <code>NSTextField</code> is… which is determined by the width of the <code>NSTableView</code>.</p>
<p>Soooo… I guess my question is… what is a good design pattern for this? It seems like everything I try winds up being a convoluted mess. Since the TableView requires knowledge of the height of the cells to lay them out... and the <code>NSTextField</code> needs knowledge of it's layout to determine the word wrap… and the cell needs knowledge of the word wrap to determine it's height… it's a circular mess… and it's driving me <em>insane</em>.</p>
<p>Suggestions?</p>
<p>If it matters, the end result will also have editable <code>NSTextFields</code> that will resize to adjust to the text within them. I already have this working on the view level, but the tableview does not yet adjust the heights of the cells. I figure once I get the height issue worked out, I'll use the -<code>noteHeightOfRowsWithIndexesChanged</code> method to inform the table view the height changed… but it's still then going to ask the delegate for the height… hence, my quandry.</p>
<p>Thanks in advance!</p> | 8,054,170 | 10 | 5 | null | 2011-09-21 18:10:12.633 UTC | 79 | 2017-11-01 23:27:09.14 UTC | 2016-05-15 12:36:13.043 UTC | null | 846,275 | null | 705,569 | null | 1 | 91 | objective-c|macos|cocoa|osx-lion | 39,162 | <p>This is a chicken and the egg problem. The table needs to know the row height because that determines where a given view will lie. But you want a view to already be around so you can use it to figure out the row height. So, which comes first?</p>
<p>The answer is to keep an extra <code>NSTableCellView</code> (or whatever view you are using as your "cell view") around just for measuring the height of the view. In the <code>tableView:heightOfRow:</code> delegate method, access your model for 'row' and set the <code>objectValue</code> on <code>NSTableCellView</code>. Then set the view's width to be your table's width, and (however you want to do it) figure out the required height for that view. Return that value. </p>
<p>Don't call <code>noteHeightOfRowsWithIndexesChanged:</code> from in the delegate method <code>tableView:heightOfRow:</code> or <code>viewForTableColumn:row:</code> ! That is bad, and will cause mega-trouble.</p>
<p>To dynamically update the height, then what you should do is respond to the text changing (via the target/action) and recalculate your computed height of that view. Now, don't dynamically change the <code>NSTableCellView</code>'s height (or whatever view you are using as your "cell view"). The table <em>must</em> control that view's frame, and you will be fighting the tableview if you try to set it. Instead, in your target/action for the text field where you computed the height, call <code>noteHeightOfRowsWithIndexesChanged:</code>, which will let the table resize that individual row. Assuming you have your autoresizing mask setup right on subviews (i.e.: subviews of the <code>NSTableCellView</code>), things should resize fine! If not, first work on the resizing mask of the subviews to get things right with variable row heights.</p>
<p>Don't forget that <code>noteHeightOfRowsWithIndexesChanged:</code> animates by default. To make it not animate:</p>
<pre><code>[NSAnimationContext beginGrouping];
[[NSAnimationContext currentContext] setDuration:0];
[tableView noteHeightOfRowsWithIndexesChanged:indexSet];
[NSAnimationContext endGrouping];
</code></pre>
<p>PS: I respond more to questions posted on the Apple Dev Forums than stack overflow. </p>
<p>PSS: I wrote the view based NSTableView</p> |
13,933,312 | Is there any private api to monitor network traffic on iPhone? | <p>I need to implement an app that monitors inbound/outbound connections by different apps on iPhone. my app is going to run in background using apple's background multitasking feature for voip and navigators.
I can use private api as my client doesn't need this app on appstore.</p>
<p>Thanks.</p> | 14,252,327 | 3 | 0 | null | 2012-12-18 12:43:44.977 UTC | 9 | 2013-03-20 06:12:59.397 UTC | 2012-12-18 12:48:35.09 UTC | null | 106,435 | null | 999,277 | null | 1 | 8 | objective-c|ios|cocoa-touch|iphone-privateapi | 4,903 | <p>I got through this.</p>
<p>I didn't need any private Api to get information of inbound/outbound active connections.
Its just you need to know basic C programming and some patience.</p>
<p>I wrote to apple dev forums regarding this,and got response as-</p>
<pre><code>From my perspective most of what I have to say about this issue is covered in the post referenced below.
<https://devforums.apple.com/message/748272#748272>>
The way to make progress on this is to:
o grab the relevant headers from the Mac OS X SDK
o look at the Darwin source for netstat to see how the pieces fit together
WARNING: There are serious compatibility risks associated with shipping an app that uses this technique; it's fine to use this for debugging and so on, but I recommend against shipping code like this to end users.
</code></pre>
<p>What I did step by step is -</p>
<p>1)downloaded <a href="http://opensource.apple.com/source/network_cmds/network_cmds-396.6/netstat.tproj/" rel="nofollow">code of netstat</a> from BSD opensource - </p>
<p>2)add this to your new iphone project.</p>
<p>3)see,some header files are not present in ios sdk so you need take it copied from opensource.apple.com and add those in your iphone sdk at <strong>relevant</strong> path under- </p>
<pre><code>/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.0.sdk/usr/include
</code></pre>
<p>My xcode version is 4.5.2. so this is path relevent to my xcode. you can have different path according to versions of xcodes.Anyway. and remember to add those headers in both iosSdk & iOSSimulatorSdk both so that code will work on device as well as on simulator.</p>
<p>4)you may find some minor errors in netstat code relating not finding definitions of some structures in header files.e.g " struct xunpcb64 " .dont wory. definitions are present there.you need to comment some "#if !TARGET_OS_EMBEDDED" #else in those header files so that ios sdk can reach in those if condition and access the definition.(need some try and error.be patient.)</p>
<p>5)finally you will be abe to compile your code.Cheers!!</p> |
14,043,886 | Python 2,3 Convert Integer to "bytes" Cleanly | <p>The shortest ways I have found are:</p>
<pre><code>n = 5
# Python 2.
s = str(n)
i = int(s)
# Python 3.
s = bytes(str(n), "ascii")
i = int(s)
</code></pre>
<p>I am particularly concerned with two factors: readability and portability. The second method, for Python 3, is ugly. However, I think it may be backwards compatible.</p>
<p>Is there a shorter, cleaner way that I have missed? I currently make a lambda expression to fix it with a new function, but maybe that's unnecessary.</p> | 14,044,431 | 7 | 10 | null | 2012-12-26 17:22:27.857 UTC | 6 | 2022-09-09 11:37:32.827 UTC | 2019-08-05 16:14:15.323 UTC | null | 4,304,503 | null | 688,624 | null | 1 | 40 | python | 136,979 | <p><strong>Answer 1:</strong></p>
<p>To convert a string to a sequence of bytes in either Python 2 or Python 3, you use the string's <code>encode</code> method. If you don't supply an encoding parameter <code>'ascii'</code> is used, which will always be good enough for numeric digits.</p>
<pre><code>s = str(n).encode()
</code></pre>
<ul>
<li>Python 2: <a href="http://ideone.com/Y05zVY" rel="noreferrer">http://ideone.com/Y05zVY</a></li>
<li>Python 3: <a href="http://ideone.com/XqFyOj" rel="noreferrer">http://ideone.com/XqFyOj</a></li>
</ul>
<p>In Python 2 <code>str(n)</code> already produces bytes; the <code>encode</code> will do a double conversion as this string is implicitly converted to Unicode and back again to bytes. It's unnecessary work, but it's harmless and is completely compatible with Python 3.
<hr>
<strong>Answer 2:</strong></p>
<p>Above is the answer to the question that was actually asked, which was to produce a string of ASCII bytes in human-readable form. But since people keep coming here trying to get the answer to a <em>different</em> question, I'll answer that question too. If you want to convert <code>10</code> to <code>b'10'</code> use the answer above, but if you want to convert <code>10</code> to <code>b'\x0a\x00\x00\x00'</code> then keep reading.</p>
<p>The <a href="https://docs.python.org/3/library/struct.html" rel="noreferrer"><code>struct</code> module</a> was specifically provided for converting between various types and their binary representation as a sequence of bytes. The conversion from a type to bytes is done with <a href="https://docs.python.org/3/library/struct.html#struct.pack" rel="noreferrer"><code>struct.pack</code></a>. There's a format parameter <code>fmt</code> that determines which conversion it should perform. For a 4-byte integer, that would be <code>i</code> for signed numbers or <code>I</code> for unsigned numbers. For more possibilities see the <a href="https://docs.python.org/3/library/struct.html#format-characters" rel="noreferrer">format character table</a>, and see the <a href="https://docs.python.org/3/library/struct.html#byte-order-size-and-alignment" rel="noreferrer">byte order, size, and alignment table</a> for options when the output is more than a single byte.</p>
<pre><code>import struct
s = struct.pack('<i', 5) # b'\x05\x00\x00\x00'
</code></pre> |
9,384,448 | How many bytes does a string take? A char? | <p>I'm doing a review of my first semester C++ class, and I think I missing something. How many bytes does a string take up? A char? </p>
<p>The examples we were given are, some being character literals and some being strings:</p>
<p><code>'n', "n", '\n', "\n", "\\n", ""</code></p>
<p>I'm particularly confused by the usage of newlines in there.</p> | 9,384,476 | 10 | 1 | null | 2012-02-21 20:11:42.9 UTC | 6 | 2022-07-18 14:21:50.233 UTC | 2012-02-21 20:23:28.917 UTC | null | 224,988 | null | 224,988 | null | 1 | 20 | c++|string|character | 92,046 | <pre><code>#include <iostream>
int main()
{
std::cout << sizeof 'n' << std::endl; // 1
std::cout << sizeof "n" << std::endl; // 2
std::cout << sizeof '\n' << std::endl; // 1
std::cout << sizeof "\n" << std::endl; // 2
std::cout << sizeof "\\n" << std::endl; // 3
std::cout << sizeof "" << std::endl; // 1
}
</code></pre>
<ul>
<li>Single quotes indicate characters.</li>
<li>Double quotes indicate C-style strings with an invisible <code>NUL</code>
terminator.</li>
</ul>
<p><code>\n</code> (line break) is only a single char and so is <code>\\</code> (backslash). <code>\\n</code> is just a backslash followed by <code>n</code>.</p> |
32,964,884 | Add child view controller to current view controller | <p>I am trying to add a child view controller in code, to the current view controller from storyboard by using the next code:</p>
<pre><code>UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
LogInTutorialViewController *lvc = [[LogInTutorialViewController alloc] init];
lvc = (LogInTutorialViewController *)[storyboard instantiateViewControllerWithIdentifier:@"LogInTutorialViewControllerID"];
[self displayContentController:lvc];
- (void) displayContentController: (LogInTutorialViewController*) content;
{
//add as childViewController
[self addChildViewController:content];
[content didMoveToParentViewController:self];
[content.view setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
[self.view addSubview:content.view];
}
</code></pre>
<p>The view seem to be displaying on the simulator at least but in console I get a lot or error:</p>
<pre><code> <Error>: CGContextSaveGState: invalid context 0x0. This is a serious error. This application, or a library it uses, is using an invalid context and is thereby contributing to an overall degradation of system stability and reliability. This notice is a courtesy: please fix this problem. It will become a fatal error in an upcoming update.
</code></pre>
<p>And also the same description but different error:</p>
<p>CGContextSetLineWidth, CGContextSetLineJoin, CGContextSetLineCap, CGContextSetMiterLimit, CGContextSetFlatness, CGContextAddPath, CGContextDrawPath, CGContextRestoreGState</p>
<p>all these error get logged twice. </p>
<p>Does anyone know what I am doing wrong?</p>
<p>also I read a few posts and in some it was suggested to alloc and init the view controller before passing the data, I also tried that without any luck.</p> | 32,965,097 | 5 | 2 | null | 2015-10-06 08:13:23.077 UTC | 7 | 2020-04-29 08:32:55.273 UTC | null | null | null | null | 2,812,726 | null | 1 | 21 | ios|objective-c|uinavigationcontroller | 55,026 | <p>didMoveToParentViewController must be the last.</p> |
19,353,255 | How to put Google Maps V2 on a Fragment using ViewPager | <p>I am trying to do a tab layout same in Play Store. I got to display the <a href="http://www.androidhive.info/2013/10/android-tab-layout-with-swipeable-views-1/" rel="noreferrer">tab layout using a fragments and viewpager from androidhive.</a> However, I can't implement <a href="http://wptrafficanalyzer.in/blog/driving-distance-and-travel-time-duration-between-two-locations-in-google-map-android-api-v2/" rel="noreferrer">google maps v2</a> on it. I searched the internet for hours already, but I can't find a tutorial on how to do it. Can some one please show me how?</p> | 19,354,359 | 13 | 2 | null | 2013-10-14 03:48:36.047 UTC | 96 | 2021-11-25 20:10:45.823 UTC | 2018-12-17 12:18:18.79 UTC | null | 3,924,118 | null | 2,718,577 | null | 1 | 142 | android|google-maps|android-fragments | 263,732 | <p>By using this code we can setup MapView anywhere, inside any ViewPager or Fragment or Activity.</p>
<p><em><strong>In the latest update of Google for Maps, only MapView is supported for fragments. MapFragment & SupportMapFragment didn't work for me.</strong></em></p>
<p>Setting up the layout for showing the map in the file <code>location_fragment.xml</code>:</p>
<pre><code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.google.android.gms.maps.MapView
android:id="@+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
</code></pre>
<p>Now, we setup the Java class for showing the map in the file <code>MapViewFragment.java</code>:</p>
<pre><code>public class MapViewFragment extends Fragment {
MapView mMapView;
private GoogleMap googleMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.location_fragment, container, false);
mMapView = (MapView) rootView.findViewById(R.id.mapView);
mMapView.onCreate(savedInstanceState);
mMapView.onResume(); // needed to get the map to display immediately
try {
MapsInitializer.initialize(getActivity().getApplicationContext());
} catch (Exception e) {
e.printStackTrace();
}
mMapView.getMapAsync(new OnMapReadyCallback() {
@Override
public void onMapReady(GoogleMap mMap) {
googleMap = mMap;
// For showing a move to my location button
googleMap.setMyLocationEnabled(true);
// For dropping a marker at a point on the Map
LatLng sydney = new LatLng(-34, 151);
googleMap.addMarker(new MarkerOptions().position(sydney).title("Marker Title").snippet("Marker Description"));
// For zooming automatically to the location of the marker
CameraPosition cameraPosition = new CameraPosition.Builder().target(sydney).zoom(12).build();
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
});
return rootView;
}
@Override
public void onResume() {
super.onResume();
mMapView.onResume();
}
@Override
public void onPause() {
super.onPause();
mMapView.onPause();
}
@Override
public void onDestroy() {
super.onDestroy();
mMapView.onDestroy();
}
@Override
public void onLowMemory() {
super.onLowMemory();
mMapView.onLowMemory();
}
}
</code></pre>
<p><em>Finally you need to get the API Key for your app by registering your app at <a href="https://cloud.google.com/console" rel="nofollow noreferrer">Google Cloud Console</a>. Register your app as Native Android App.</em></p> |
19,304,574 | Center/Set Zoom of Map to cover all visible Markers? | <p>I am setting multiple markers on my map and I can set statically the zoom levels and the center but what I want is, to cover all the markers and zoom as much as possible having all markets visible </p>
<p>Available methods are following </p>
<p><a href="https://developers.google.com/maps/documentation/javascript/reference#Map" rel="noreferrer"><code>setZoom(zoom:number)</code></a></p>
<p>and </p>
<p><a href="https://developers.google.com/maps/documentation/javascript/reference#Map" rel="noreferrer"><code>setCenter(latlng:LatLng)</code></a></p>
<p>Neither <code>setCenter</code> supports multiple location or Location array input nor <code>setZoom</code> does have this type of functionality</p>
<p><img src="https://i.stack.imgur.com/Bkqjl.jpg" alt="enter image description here"></p> | 19,304,625 | 4 | 2 | null | 2013-10-10 19:28:05.11 UTC | 88 | 2019-12-08 18:09:56.743 UTC | 2017-12-16 23:25:31.177 UTC | null | 2,314,737 | null | 1,215,724 | null | 1 | 393 | javascript|google-maps-api-3 | 207,928 | <p>You need to use the <code>fitBounds()</code> method.</p>
<pre><code>var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
bounds.extend(markers[i]);
}
map.fitBounds(bounds);
</code></pre>
<hr>
<p><strong>Documentation</strong> from <a href="https://developers.google.com/maps/documentation/javascript/reference/map#Map.fitBounds" rel="noreferrer">developers.google.com/maps/documentation/javascript</a>:</p>
<blockquote>
<h2><strong><code>fitBounds(bounds[, padding])</code></strong></h2>
<p><strong>Parameters:</strong> </p>
<pre><code>`bounds`: [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional): number|[`Padding`][1]
</code></pre>
<p><strong>Return Value:</strong> None </p>
<p>Sets the viewport to contain the given bounds.<br>
<strong>Note</strong>: When the map is set to <code>display: none</code>, the <code>fitBounds</code> function reads the map's size as <code>0x0</code>, and therefore does not do anything. To change the viewport while the map is hidden, set the map to <code>visibility: hidden</code>, thereby ensuring the map div has an actual size.</p>
</blockquote> |
34,286,407 | Gradle: What is the difference between classpath and compile dependencies? | <p>When adding dependencies to my project I am never sure what prefix I should give them, e.g. <code>"classpath"</code> or <code>"compile".</code> </p>
<p>For example, should my dependencies below be compile time or classpath? </p>
<p>Also, should this be in my <em>applications</em> build.gradle or in the <em>module</em> specific build.gradle?</p>
<p><strong>Current build.gradle (at application level):</strong></p>
<pre><code>apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile 'org.hibernate:hibernate-core:5.0.5.Final'
compile 'mysql:mysql-connector-java:5.1.38'
}
</code></pre> | 34,295,609 | 4 | 4 | null | 2015-12-15 10:14:15.037 UTC | 19 | 2021-10-19 13:26:13.723 UTC | 2015-12-15 17:20:47.897 UTC | null | 25,066 | null | 5,528,751 | null | 1 | 117 | java|gradle|dependencies | 94,906 | <p>I'm going to guess that you're referencing <code>compile</code> and <code>classpath</code> within the <code>dependencies {}</code> block. If that is so, those are dependency <a href="https://docs.gradle.org/current/userguide/artifact_dependencies_tutorial.html" rel="noreferrer">Configurations</a>.</p>
<blockquote>
<p>A configuration is simply a named set of dependencies.</p>
</blockquote>
<p>The <code>compile</code> configuration is created by the Java plugin. The <code>classpath</code> configuration is commonly seen in the <code>buildSrc {}</code> block where one needs to declare dependencies <em>for the build.gradle, itself</em> (for plugins, perhaps).</p> |
34,910,841 | Difference between Collections.sort(list) and list.sort(Comparator) | <p>Is there any reason why I should prefer <code>Collections.sort(list)</code> method over simply calling the <code>list.sort()</code>? Internally <code>Collections.sort</code> merely calls the <code>sort</code> method of the <code>List</code> class anyway.</p>
<p>It's just surprising that almost everyone is telling me to use <code>Collections.sort</code>. Why?</p> | 34,910,953 | 3 | 4 | null | 2016-01-20 21:23:58.263 UTC | 3 | 2021-02-12 14:58:22.527 UTC | 2021-02-12 14:58:22.527 UTC | null | 1,439,733 | null | 5,539,357 | null | 1 | 54 | java|list|sorting | 15,873 | <p>The method <a href="https://docs.oracle.com/javase/8/docs/api/java/util/List.html#sort-java.util.Comparator-" rel="noreferrer"><code>List.sort(comparator)</code></a> that you are refering to was introduced in Java 8, whereas the utility method <a href="https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-" rel="noreferrer"><code>Collections.sort</code></a> has been there since Java 1.2.</p>
<p>As such, you will find a lot of reference on the Internet mentioning that utility method but that's just because it has been in the JDK for a lot longer.</p>
<p>Note that the change in implementation for <code>Collections.sort</code> <a href="https://stackoverflow.com/a/34827492/1743880">was made in 8u20</a>.</p> |
262,618 | Java BufferedReader back to the top of a text file? | <p>I currently have 2 <code>BufferedReader</code>s initialized on the same text file. When I'm done reading the text file with the first <code>BufferedReader</code>, I use the second one to make another pass through the file from the top. Multiple passes through the same file are necessary.</p>
<p>I know about <code>reset()</code>, but it needs to be preceded with calling <code>mark()</code> and <code>mark()</code> needs to know the size of the file, something I don't think I should have to bother with.</p>
<p>Ideas? Packages? Libs? Code?</p>
<p>Thanks
TJ</p> | 262,631 | 5 | 0 | null | 2008-11-04 17:31:43.11 UTC | 4 | 2015-03-20 16:00:51.78 UTC | 2015-03-20 16:00:51.78 UTC | null | 1,501,234 | T to the J | null | null | 1 | 26 | java|file|file-io|text-files|bufferedinputstream | 74,923 | <p>What's the disadvantage of just creating a new <code>BufferedReader</code> to read from the top? I'd expect the operating system to cache the file if it's small enough.</p>
<p>If you're concerned about performance, have you proved it to be a bottleneck? I'd just do the simplest thing and not worry about it until you have a specific reason to. I mean, you could just read the whole thing into memory and then do the two passes on the result, but again that's going to be more complicated than just reading from the start again with a new reader.</p> |
557,574 | What is a native implementation in Java? | <p>If we look at the Java Object class then we can find some of the methods like:</p>
<pre><code>public native int hashCode()
protected native Object clone()
</code></pre>
<p>What are these natives and how do these methods work?</p> | 557,610 | 5 | 0 | null | 2009-02-17 16:13:40.223 UTC | 13 | 2017-10-21 21:53:02.423 UTC | 2017-10-21 21:53:02.423 UTC | starblue | 3,745,896 | Dinesh Simkhada | 13,240 | null | 1 | 35 | java|java-native-interface | 20,342 | <p>These methods are either <em>Intrinsic</em> or written outside Java in "native" code, that is, specific to the given machine. </p>
<p>The ones you mention are <em>Intrinsic</em> and part of the JDK but you can also write native methods yourself using the <a href="http://java.sun.com/docs/books/jni/" rel="noreferrer">Java Native Interface</a> (JNI). This would normally use C to write the methods, but a lot of other languages, such as python allow you to write methods this way fairly easily. Code is written this way either for performance, or because it needs to access platform specific infrastructure which cannot be done in plain java.</p>
<p>In the case of <code>hashcode()</code>, this is implemented by the JVM. This is because often the hashcode will be related to something only the JVM knows. On early JVMs this was related to the object's location in memory - on other JVMs the Object may move in memory, and so a more complicated (but still very fast) scheme may be used.</p> |
750,298 | Easy way to check that a variable is defined in python? | <p>Is there any way to check if a variable (class member or standalone) with specified name is defined? Example:</p>
<pre><code>if "myVar" in myObject.__dict__ : # not an easy way
print myObject.myVar
else
print "not defined"
</code></pre> | 750,318 | 5 | 5 | null | 2009-04-15 04:21:17.717 UTC | 17 | 2014-07-17 13:47:57.78 UTC | 2014-07-17 13:47:57.78 UTC | null | 1,751,037 | null | 69,882 | null | 1 | 48 | python | 77,219 | <p>A compact way:</p>
<pre><code>print myObject.myVar if hasattr(myObject, 'myVar') else 'not defined'
</code></pre>
<p>htw's way is more Pythonic, though.</p>
<p><code>hasattr()</code> is different from <code>x in y.__dict__</code>, though: <code>hasattr()</code> takes inherited class attributes into account, as well as dynamic ones returned from <code>__getattr__</code>, whereas <code>y.__dict__</code> only contains those objects that are attributes of the <code>y</code> instance.</p> |
197,190 | Why can't I use a type argument in a type parameter with multiple bounds? | <p>So, I understand <i>that</i> the following doesn't work, but <i>why</i> doesn't it work?</p>
<pre><code>interface Adapter<E> {}
class Adaptulator<I> {
<E, A extends I & Adapter<E>> void add(Class<E> extl, Class<A> intl) {
addAdapterFactory(new AdapterFactory<E, A>(extl, intl));
}
}
</code></pre>
<p>The <code>add()</code> method gives me a compile error, "Cannot specify any additional bound Adapter<E> when first bound is a type parameter" (in Eclipse), or "Type parameter cannot be followed by other bounds" (in IDEA), take your pick.</p>
<p>Clearly you're just Not Allowed to use the type parameter <code>I</code> there, before the <code>&</code>, and that's that. (And before you ask, it doesn't work if you switch 'em, because there's no guarantee that <code>I</code> isn't a concrete class.) But why not? I've looked through Angelika Langer's FAQ and can't find an answer.</p>
<p>Generally when some generics limitation seems arbitrary, it's because you've created a situation where the type system can't actually enforce correctness. But I don't see what case would break what I'm trying to do here. I'd say maybe it has something to do with method dispatch after type erasure, but there's only one <code>add()</code> method, so it's not like there's any ambiguity...</p>
<p>Can someone demonstrate the problem for me?</p> | 197,391 | 5 | 0 | null | 2008-10-13 10:21:58.29 UTC | 14 | 2020-12-09 14:39:22.567 UTC | 2014-09-29 09:47:43.277 UTC | mark | 474,189 | David Moles | 27,358 | null | 1 | 59 | java|generics|constraints | 15,971 | <p>I'm also not sure why the restriction is there. You could try sending a friendly e-mail to the designers of Java 5 Generics (chiefly Gilad Bracha and Neal Gafter).</p>
<p>My guess is that they wanted to support only an absolute minimum of <a href="https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.9" rel="noreferrer">intersection types</a> (which is what multiple bounds essentially are), to make the language no more complex than needed. An intersection cannot be used as a type annotation; a programmer can only express an intersection when it appears as the upper bound of a type variable.</p>
<p>And why was this case even supported? The answer is that multiple bounds allow you to control the erasure, which allows to maintain binary compatibility when generifying existing classes. As explained in section 17.4 of the <a href="http://java-generics-book.dev.java.net/" rel="noreferrer">book</a> by Naftalin and Wadler, a <code>max</code> method would logically have the following signature:</p>
<pre><code>public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll)
</code></pre>
<p>However, this erases to:</p>
<pre><code>public static Comparable max(Collection coll)
</code></pre>
<p>Which does not match the historical signature of <code>max</code>, and causes old clients to break.
With multiple bounds, only the left-most bound is considered for the erasure, so if <code>max</code> is given the following signature:</p>
<pre><code>public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll)
</code></pre>
<p>Then the erasure of its signature becomes:</p>
<pre><code>public static Object max(Collection coll)
</code></pre>
<p>Which is equal to the signature of <code>max</code> before Generics.</p>
<p>It seems plausible that the Java designers only cared about this simple case and restricted other (more advanced) uses of intersection types because they were just unsure of the complexity that it might bring. So the reason for this design decision does not need to be a possible safety problem (as the question suggests).</p>
<p>More discussion on intersection types and restrictions of generics in an <a href="http://www.cs.rice.edu/~javaplt/papers/oopsla2008.pdf" rel="noreferrer">upcoming OOPSLA paper</a>.</p> |
1,115,230 | casting Object array to Integer array error | <p>What's wrong with the following code?</p>
<pre><code>Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;
</code></pre>
<p>The code has the following error at the last line :</p>
<blockquote>
<p>Exception in thread "main" java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;</p>
</blockquote> | 8,220,245 | 5 | 0 | null | 2009-07-12 03:14:18.007 UTC | 29 | 2018-03-06 07:24:11.273 UTC | 2017-05-29 14:19:07.963 UTC | null | 833,070 | null | 65,167 | null | 1 | 77 | java|casting | 141,962 | <p>Ross, you can use Arrays.copyof() or Arrays.copyOfRange() too.</p>
<pre><code>Integer[] integerArray = Arrays.copyOf(a, a.length, Integer[].class);
Integer[] integerArray = Arrays.copyOfRange(a, 0, a.length, Integer[].class);
</code></pre>
<p>Here the reason to hitting an <code>ClassCastException</code> is you can't treat an array of <code>Integer</code> as an array of <code>Object</code>. <code>Integer[]</code> is a subtype of <code>Object[]</code> but <code>Object[]</code> is not a <code>Integer[]</code>.</p>
<p>And the following also will not give an <code>ClassCastException</code>.</p>
<pre><code>Object[] a = new Integer[1];
Integer b=1;
a[0]=b;
Integer[] c = (Integer[]) a;
</code></pre> |
1,166,444 | MKMapView Zoom and Region | <p>I'm familiar with using Google Maps Javascript API. Recently I started using MapKit framework for an iphone project, but I'm having a hard time to figure out zooming and setting a region on map.</p>
<p>In Google Maps API I used to use integer zoom levels like 8, 9, 10 along with straightforward function setZoom(). The only equivalent method I can see in the MapKit framework is setRegion:animated. As I understand, I need to set a region's span's latitude and longitude "delta" values to specify zoom level. But I really don't have an idea what these values represent(I read the documentation).</p>
<p>When I use a MKMapView delegate and trace the span values in regionDidChange delegate method results don't seem to correlate each other. It's ok when I zoom out and see the span delta values are increasing as specified in documentation. But suddenly I drag the map without zooming and delta values become 0.0. </p>
<p>Can somebody please explain what is the reference point to these span and delta? Or is there any algorithm to convert an integer zoom level(like 9) to these delta values? </p>
<p>As a bonus question is there any way to specify a minimum-maximum zoom level on a MKMapView :) </p>
<p>Thanks</p> | 1,167,696 | 5 | 0 | null | 2009-07-22 16:16:58.52 UTC | 59 | 2016-07-01 14:40:08.067 UTC | 2012-01-24 14:39:36.82 UTC | user353955 | null | null | 133,617 | null | 1 | 86 | iphone|cocoa-touch|mapkit|zooming | 80,649 | <p>First of all, <strong>MKMapView</strong> does not use/have a predefined set of zoom levels like Google Maps does.</p>
<p>Instead, the visible area of a MKMapView is described using <strong>MKCoordinateRegion</strong>, which consists of two values:</p>
<ol>
<li><strong>center</strong> (the center point of the region), and</li>
<li><strong>span</strong> (the size of the visible area around center).</li>
</ol>
<p>The center point should be obvious (it's the center point of the region.)</p>
<p>However, span (which is a <strong>MKCoordinateSpan</strong>) consists of:</p>
<ol>
<li><strong>latitudeDelta</strong> (the vertical distance represented by the region), and</li>
<li><strong>longitudeDelta</strong> (the horizontal distance represented by the region).</li>
</ol>
<p>A brief example. Here's a toy MKCoordinateRegion:</p>
<ol>
<li>center:
<ul>
<li>latitude: 0</li>
<li>longitude: 0</li>
</ul></li>
<li>span:
<ul>
<li>latitudeDelta: 8</li>
<li>longitudeDelta: 6</li>
</ul></li>
</ol>
<p>The region could be described using its min and max coordinates as follows:</p>
<ol>
<li>min coordinate (lower left-hand point):
<ul>
<li>latitude: -4</li>
<li>longitude: -3</li>
</ul></li>
<li>max coordinate (upper right-hand point):
<ul>
<li>latitude: 4</li>
<li>longitude: 3</li>
</ul></li>
</ol>
<p>So, you can specify zoom levels around a center point by using an appropriately sized MKCoordinateSpan. As an approximation of Google's numeric zoom levels, you could reverse engineer the span sizes that Google uses for a given zoom level and create a span, accordingly. (Google describes their view regions in the same way that MKMapView does, as a center + span, so you can pull these values out of Google Maps.)</p>
<p>As for restricting the region, you may play w/ this delegate method:</p>
<pre><code>mapView:regionWillChangeAnimated
</code></pre>
<p>e.g. by resizing the region back into your allowed zoom levels. (Kind of like how table views will let you scroll past the edge, but will then rubber band back into place.) However, your mileage may vary, since I haven't used it for this purpose.</p>
<p>btw, there are definite fixes/improvements in OS 3.1 to aspects of MapKit that were giving me trouble in 3.0.</p> |
1,221,322 | How does semaphore work? | <p>Can the semaphore be lower than 0? I mean, say I have a semaphore with N=3 and I call "down" 4 times, then N will remain 0 but one process will be blocked?</p>
<p>And same the other way, if in the beginning I call up, can N be higher than 3? Because as I see it, if N can be higher than 3 if in the beginning I call up couple of times, then later on I could call down more times than I can, thus putting more processes in the critical section then the semaphore allows me.</p>
<p>If someone would clarify it a bit for me I will much appreciate.</p>
<p>Greg</p> | 1,221,387 | 6 | 1 | null | 2009-08-03 09:02:19.673 UTC | 6 | 2019-01-30 15:13:55.183 UTC | 2012-10-09 09:10:54.047 UTC | null | 1,528,262 | Greg | null | null | 1 | 14 | java|multithreading|computer-science|semaphore | 39,627 | <p>Calling down when it's 0 should not work. Calling up when it's 3 does work. (I am thinking of Java).</p>
<p>Let me add some more. Many people think of locks like (binary) semaphores (ie - N = 1, so the value of the semaphore is either 0 (held) or 1 (not held)). But this is not quite right. A lock has a notion of "ownership" so it may be "reentrant". That means that a thread that holds a lock, is allowed to call lock() again (effectively moving the count from 0 to -1), because the thread already holds the lock and is allowed to "reenter" it. Locks can also be non reentrant. A lock holder is expected to call unlock() the same number of times as lock().</p>
<p>Semaphores have no notion of ownership, so they cannot be reentrant, although as many permits as are available may be acquired. That means a thread needs to block when it encounters a value of 0, until someone increments the semaphore.</p>
<p>Also, in what I have seen (which is Java), you can increment the semaphore greater than N, and that also sort of has to do with ownership: a Semaphore has no notion of ownership so anybody can give it more permits. Unlike a thread, where whenever a thread calls unlock() without holding a lock, that is an error. (In java it will throw an exception).</p>
<p>Hope this way of thinking about it helps.</p> |
659,463 | What's causing xcopy to tell me Access Denied? | <p>The postbuild task for one of our solutions uses xcopy to move files into a common directory for build artifacts. For some reason, on my computer (and on a VM I tested), the xcopy fails with "Access Denied". Here's what I've done to try and isolate the problems:</p>
<ul>
<li>I tried a normal copy; this works.</li>
<li>I double-checked that none of the files in question were read-only.</li>
<li>I checked the permissions on both the source and destination folder; I have full control of both.</li>
<li>I tried calling the xcopy from the command line in case the VS build process had locked the file.</li>
<li>I used Unlocker and Process Explorer to determine there were no locks on the source file.</li>
</ul>
<p>What have I missed, other than paranoid conspiracy theories involving computers out to get me? This happens on my dev machine and a clean VM, but <em>doesn't</em> happen for anyone else on the project. </p> | 659,837 | 6 | 2 | null | 2009-03-18 18:07:11.543 UTC | 3 | 2018-11-02 06:44:25.52 UTC | 2018-11-02 06:44:25.52 UTC | Adam Lassek | 3,826,372 | OwenP | 2,547 | null | 1 | 21 | windows|cmd|xcopy | 97,131 | <p>Problem solved; there's two pieces to the puzzle.</p>
<p>The /O switch requires elevation on Vista. Also, I noticed that xcopy is deprecated in Vista in favor of robocopy. Now I'm talking with our build engineers about this.</p> |
1,072,311 | Code Sign error: The identity 'iPhone Developer: x Xxxxx' doesn't match any identity in any profile | <p>I get this build error when I build my iPhone project to run on my device:</p>
<pre><code> **Code Sign error: The identity 'iPhone Developer: x Xxxxx' doesn't match any identity in any profile**
</code></pre>
<p>My development code signing certificate expired so I got a new one. On my first attempt I created a new CSR and got the message above. The second time I reused my original CSR and got the same result. Another strange thing is the new certificate has an extra string with brackets after my name in the "common name" when I look at it using Keychain Access like this:</p>
<pre><code>iPhone Developer: x Xxxxx **(3BDUAJYC9Q)**
</code></pre>
<p>`My original certificate didn't have that.</p>
<pre><code>I have Xcode Version 3.1.3
Component versions
Xcode IDE: 1191.0
Xcode Core: 1192.0
ToolSupport: 1186.0
</code></pre>
<p>Does anyone know how to solve this?</p> | 1,072,343 | 6 | 1 | null | 2009-07-02 03:25:45.393 UTC | 13 | 2013-05-10 13:49:36.727 UTC | 2011-12-28 12:21:30.077 UTC | null | 1,099,169 | null | 87,507 | null | 1 | 33 | iphone|iphone-sdk-3.0|certificate|code-signing | 81,377 | <p>I think you need to create new provisioning profiles based on your new certificate.</p>
<p>Log on to developer.apple.com and go to the iOS Provisioning Portal -> Provisioning -> Development. Most likely, the profile you once created has expired, so just renew and redownload it.</p> |
628,343 | Objective C Boolean Array | <p>I need to utilize an array of booleans in objective-c. I've got it mostly set up, but the compiler throws a warning at the following statement:</p>
<pre><code>[updated_users replaceObjectAtIndex:index withObject:YES];
</code></pre>
<p>This is, I'm sure, because YES is simply not an object; it's a primitive. Regardless, I need to do this, and would greatly appreciate advice on how to accomplish it.</p>
<p>Thanks.</p> | 628,359 | 6 | 1 | null | 2009-03-09 22:52:46.527 UTC | 7 | 2015-01-30 20:53:11.783 UTC | null | null | null | Allyn | 57,414 | null | 1 | 39 | c|objective-c|arrays|boolean|primitive | 41,935 | <p>Yep, that's exactly what it is: the NS* containers can only store objective-C objects, not primitive types.</p>
<p>You should be able to accomplish what you want by wrapping it up in an NSNumber:</p>
<p><code>[updated_users replaceObjectAtIndex:index withObject:[NSNumber numberWithBool:YES]]</code></p>
<p>or by using <code>@(YES)</code> which wraps a <code>BOOL</code> in an <code>NSNumber</code></p>
<p><code>[updated_users replaceObjectAtIndex:index withObject:@(YES)]]</code></p>
<p>You can then pull out the boolValue:</p>
<p><code>BOOL mine = [[updated_users objectAtIndex:index] boolValue];</code></p> |
1,232,953 | Speed up File.Exists for non existing network shares | <p>I have to check if a set of file paths represent an existing file.</p>
<p>It works fine except when the path contains a network share on a machine that's not on the current network. In this case it takes a pretty long time (30 or 60 seconds) to timeout.</p>
<p>Questions</p>
<ul>
<li><p>Is there a way to shorten the timeout for non existing network shares? (I'm certain that when they do exist they'll answer quickly, so a timeout of 1 sec would be fine)</p></li>
<li><p>Is there any other way to solve this issue without starting to cache and making the algorithm more complex? (ie, I already know these X network shares don't exist, skip the rest of the matching paths)</p></li>
</ul>
<p>UPDATE: Using Threads work, not particularly elegant, though</p>
<pre><code>public bool pathExists(string path)
{
bool exists = true;
Thread t = new Thread
(
new ThreadStart(delegate ()
{
exists = System.IO.File.Exists(path);
})
);
t.Start();
bool completed = t.Join(500); //half a sec of timeout
if (!completed) { exists = false; t.Abort(); }
return exists;
}
</code></pre>
<p>This solution avoids the need for a thread per attempt, first check which drives are reachable and store that somewhere.</p>
<hr>
<h2><a href="http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_22595703.html" rel="noreferrer"><strong>Experts exchange solution</strong></a>:</h2>
<blockquote>
<p>First of all, there is a "timeout" value that you can set in the IsDriveReady function. I have it set for 5 seconds, but set it for whatever works for you.</p>
<p>3 methods are used below:</p>
<ol>
<li>The first is the WNetGetConnection API function that gets the
UNC (\servername\share) of the drive</li>
<li>The second is our main method: The Button1_Click event</li>
<li>The third is the IsDriveReady function that pings the server.</li>
</ol>
<p>This worked great for me! Here you go:</p>
<pre><code>'This API Function will be used to get the UNC of the drive
Private Declare Function WNetGetConnection Lib "mpr.dll" Alias _
"WNetGetConnectionA" _
(ByVal lpszLocalName As String, _
ByVal lpszRemoteName As String, _
ByRef cbRemoteName As Int32) As Int32
'This is just a button click event - add code to your appropriate event
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim bIsReady As Boolean = False
For Each dri As IO.DriveInfo In IO.DriveInfo.GetDrives()
'If the drive is a Network drive only, then ping it to see if it's ready.
If dri.DriveType = IO.DriveType.Network Then
'Get the UNC (\\servername\share) for the
' drive letter returned by dri.Name
Dim UNC As String = Space(100)
WNetGetConnection(dri.Name.Substring(0, 2), UNC, 100)
'Presuming the drive is mapped \\servername\share
' Parse the servername out of the UNC
Dim server As String = _
UNC.Trim().Substring(2, UNC.Trim().IndexOf("\", 2) - 2)
'Ping the server to see if it is available
bIsReady = IsDriveReady(server)
Else
bIsReady = dri.IsReady
End If
'Only process drives that are ready
If bIsReady = True Then
'Process your drive...
MsgBox(dri.Name & " is ready: " & bIsReady)
End If
Next
MsgBox("All drives processed")
End Sub
Private Function IsDriveReady(ByVal serverName As String) As Boolean
Dim bReturnStatus As Boolean = False
'*** SET YOUR TIMEOUT HERE ***
Dim timeout As Integer = 5 '5 seconds
Dim pingSender As New System.Net.NetworkInformation.Ping()
Dim options As New System.Net.NetworkInformation.PingOptions()
options.DontFragment = True
'Enter a valid ip address
Dim ipAddressOrHostName As String = serverName
Dim data As String = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Dim buffer As Byte() = System.Text.Encoding.ASCII.GetBytes(data)
Dim reply As System.Net.NetworkInformation.PingReply = _
pingSender.Send(ipAddressOrHostName, timeout, buffer, options)
If reply.Status = Net.NetworkInformation.IPStatus.Success Then
bReturnStatus = True
End If
Return bReturnStatus
End Function
</code></pre>
</blockquote> | 1,233,089 | 6 | 6 | null | 2009-08-05 12:30:15.607 UTC | 8 | 2018-10-05 11:15:02.183 UTC | 2015-08-14 14:52:13.083 UTC | null | 1,364,007 | null | 5,190 | null | 1 | 39 | c#|networking|timeout|c#-2.0 | 23,033 | <p>Use Threads to do the checks. I think that threads can be timed out.</p> |
1,072,097 | Pointers to some good SVM Tutorial | <p>I have been trying to grasp the basics of Support Vector Machines, and downloaded and read many online articles. But still am not able to grasp it.</p>
<p>I would like to know, if there are some</p>
<ul>
<li>nice tutorial</li>
<li>sample code which can be used for understanding</li>
</ul>
<p>or something, that you can think of, and that will enable me to learn SVM Basics easily.</p>
<p>PS: I somehow managed to learn PCA (Principal Component Analysis).
BTW, you guys would have guessed that I am working on Machine Learning.</p> | 1,072,973 | 6 | 3 | null | 2009-07-02 02:10:37.307 UTC | 41 | 2018-01-08 01:33:40.387 UTC | 2009-11-18 06:55:47.007 UTC | null | 25,891 | null | 70,702 | null | 1 | 48 | algorithm|machine-learning|svm|libsvm | 20,259 | <p>The standard recommendation for a tutorial in SVMs is <a href="http://research.microsoft.com/pubs/67119/svmtutorial.pdf" rel="noreferrer">A Tutorial on Support Vector Machines for Pattern Recognition</a> by Christopher Burges. Another good place to learn about SVMs is the <a href="http://see.stanford.edu/see/courseInfo.aspx?coll=348ca38a-3a6d-4052-937d-cb017338d7b1" rel="noreferrer">Machine Learning Course</a> at Stanford (SVMs are covered in lectures 6-8). Both these are quite theoretical and heavy on the maths.</p>
<p>As for source code; <a href="http://svmlight.joachims.org/" rel="noreferrer">SVMLight</a>, <a href="http://www.csie.ntu.edu.tw/~cjlin/libsvm/" rel="noreferrer">libsvm</a> and <a href="http://chasen.org/~taku/software/TinySVM/" rel="noreferrer">TinySVM</a> are all open-source, but the code is not very easy to follow. I haven't looked at each of them very closely, but the source for TinySVM is probably the is easiest to understand. There is also a pseudo-code implementation of the SMO algorithm in <a href="http://research.microsoft.com/apps/pubs/?id=68391" rel="noreferrer">this paper</a>.</p> |
649,106 | MSTest copy file to test run folder | <p>I've got a test which requires an XML file to be read in and then parsed. How can I have this file copied into the test run folder each time?</p>
<p>The XML file is set to "Copy if newer" and a compile mode of "none" (since it's not really a compile-able thing)</p> | 649,449 | 6 | 0 | null | 2009-03-16 02:49:20.383 UTC | 19 | 2014-01-07 10:37:29.683 UTC | 2009-04-06 17:11:03.987 UTC | Slace | 685 | Slace | 11,388 | null | 1 | 112 | visual-studio|mstest | 39,243 | <p>use a <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.deploymentitemattribute(VS.80).aspx" rel="noreferrer"><code>DeploymentItem</code> attribute</a></p>
<pre><code>using System;
using System.IO;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using CarMaker;
namespace DeploymentTest
{
[TestClass]
public class UnitTest1
{
[TestMethod()]
[DeploymentItem("testFile1.xml")]
public void ConstructorTest()
{
string file = "testFile1.xml";
Assert.IsTrue(File.Exists(file), "deployment failed: " + file +
" did not get deployed");
}
}
}
</code></pre> |
37,634,483 | Default Docker entrypoint | <p>I am creating an image from another image that set a specific entrypoint. However I want my image to have default one. How do I reset the ENTRYPOINT?</p>
<p>I tried the following Dockerfile:</p>
<pre><code>FROM some-image
ENTRYPOINT ["/bin/sh", "-c"]
</code></pre>
<p>Unfortunately it doesn't work like the default entrypoint as it need the command to be quoted.</p>
<pre><code>docker run myimage ls -l / # "-l /" arguments are ignored
file1 file2 file3 # files in current working directory
docker run myimage "ls -l /" # works correctly
</code></pre>
<p>How do I use commands without quoting?</p> | 37,636,548 | 3 | 2 | null | 2016-06-04 20:00:14.75 UTC | 5 | 2021-11-10 00:22:35.857 UTC | null | null | null | null | 2,582,797 | null | 1 | 38 | docker|sh | 27,897 | <p>To disable an existing <code>ENTRYPOINT</code>, set an empty array in your docker file</p>
<pre><code>ENTRYPOINT []
</code></pre>
<p>Then your arguments to <code>docker run</code> will exec as a <a href="https://docs.docker.com/engine/reference/builder/#cmd" rel="noreferrer">shell form CMD</a> would normally.</p>
<p>The reason your <code>ENTRYPOINT ["/bin/sh", "-c"]</code> requires quoted strings is that without the quotes, the arguments to <code>ls</code> are being passed to <code>sh</code> instead.</p>
<p>Unquoted results in lots of arguments being sent to <code>sh</code></p>
<pre><code>"/bin/sh", "-c", "ls", "-l", "/"
</code></pre>
<p>Quoting allows the complete command (<code>sh -c</code>) to be passed on to <code>sh</code> as one argument.</p>
<pre><code>"/bin/sh", "-c", "ls -l /"
</code></pre> |
21,036,744 | Set asp.net textbox value using javascript | <p>I want to set the value of a asp.net textbox using javascript</p>
<p>My JS Code is:</p>
<pre><code>document.getElementById('<%=txtFlag.ClientID %>').value = "Track";
</code></pre>
<p>My textbox is:</p>
<pre><code><asp:TextBox ID="txtFlag" runat="server" Visible="False"></asp:TextBox>
</code></pre>
<p>But it gives me an error <code>document.getElementById(...)' is null or not an object</code></p>
<p>I dont understand what is wrong.</p>
<p>Please help.</p> | 21,036,965 | 5 | 4 | null | 2014-01-10 05:24:22.77 UTC | 2 | 2014-01-10 05:48:36.843 UTC | 2014-01-10 05:27:36.487 UTC | null | 2,231,046 | null | 2,124,167 | null | 1 | 6 | javascript|asp.net | 67,129 | <p>Solution 1:</p>
<p>Make that textbox as visible=true and try,</p>
<p>When you make a control as visible false, that control will not be loaded in client side and as you knew javascript will be executed on client side itself.</p>
<p>Solution 2:</p>
<p>Add this javascript at the end of the page.</p> |
21,002,616 | How to disable a <option> of select element when using AngularJS ng-options? | <p>Is there a way to disable an <code>option</code> in a <code>select</code> element when we populate <code>options</code> with ng-options in AngularJS?</p>
<p>Like this: <a href="http://www.w3schools.com/tags/att_option_disabled.asp" rel="noreferrer">http://www.w3schools.com/tags/att_option_disabled.asp</a></p>
<p>You can do it by adding <code>ng-disabled</code> to each <code><option></code> tag, but is there a way to do it if we are using the <code>ng-options</code> directive in the <code>select</code> tag?</p> | 21,003,743 | 5 | 6 | null | 2014-01-08 17:35:04.857 UTC | 1 | 2016-06-19 08:27:52.3 UTC | 2016-06-19 08:01:58.277 UTC | null | 4,015,856 | null | 3,099,273 | null | 1 | 10 | angularjs|angularjs-directive|ng-options | 63,240 | <p>One way to do this is, to forget using <code>ng-options</code> on the <code>select</code> element, and add the options in with <code>ng-repeat</code>, then you can add a <code>ng-disabled</code> check on each <code>option</code>.</p>
<p><a href="http://jsfiddle.net/97LP2/" rel="noreferrer">http://jsfiddle.net/97LP2/</a></p>
<pre><code><div ng-app="myapp">
<form ng-controller="ctrl">
<select id="t1" ng-model="curval">
<option ng-repeat="i in options" value="{{i}}" ng-disabled="disabled[i]">{{i}}</option>
</select>
<button ng-click="disabled[curval]=true">disable</button>
</form>
</div>
</code></pre>
<p>a minimal controller for testing:</p>
<pre><code>angular.module('myapp',[]).controller("ctrl", function($scope){
$scope.options=['test1','test2','test3','test4','test5'];
$scope.disabled={};
})
</code></pre> |
17,819,884 | XML (.xsd) feed validation against a schema | <p>I have a XML file and I have a XML schema. I want to validate the file against that schema and check if it adheres to that. I am using python but am open to any language for that matter if there is no such useful library in python. </p>
<p>What would be my best options here? I would worry about the how fast I can get this up and running. </p> | 17,819,981 | 3 | 0 | null | 2013-07-23 19:58:26.54 UTC | 11 | 2021-06-23 07:36:22.44 UTC | null | null | null | null | 2,487,334 | null | 1 | 18 | python|xml|python-2.7|xsd|xml-validation | 17,749 | <p>Definitely <a href="http://lxml.de/" rel="nofollow noreferrer"><code>lxml</code></a>. </p>
<p>Define an <a href="http://lxml.de/api/index.html" rel="nofollow noreferrer"><code>XMLParser</code></a> with a predefined schema, load the the file <code>fromstring()</code> and catch any XML Schema errors:</p>
<pre><code>from lxml import etree
def validate(xmlparser, xmlfilename):
try:
with open(xmlfilename, 'r') as f:
etree.fromstring(f.read(), xmlparser)
return True
except etree.XMLSchemaError:
return False
schema_file = 'schema.xsd'
with open(schema_file, 'r') as f:
schema_root = etree.XML(f.read())
schema = etree.XMLSchema(schema_root)
xmlparser = etree.XMLParser(schema=schema)
filenames = ['input1.xml', 'input2.xml', 'input3.xml']
for filename in filenames:
if validate(xmlparser, filename):
print("%s validates" % filename)
else:
print("%s doesn't validate" % filename)
</code></pre>
<h2>Note about encoding</h2>
<p>If the schema file contains an xml tag with an encoding (e.g. <code><?xml version="1.0" encoding="UTF-8"?></code>), the code above will generate the following error:</p>
<pre><code>Traceback (most recent call last):
File "<input>", line 2, in <module>
schema_root = etree.XML(f.read())
File "src/lxml/etree.pyx", line 3192, in lxml.etree.XML
File "src/lxml/parser.pxi", line 1872, in lxml.etree._parseMemoryDocument
ValueError: Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
</code></pre>
<p><a href="https://stackoverflow.com/questions/28534460/lxml-etree-xml-valueerror-for-unicode-string">A solution</a> is to open the files in byte mode: <code>open(..., 'rb')</code></p>
<pre><code>[...]
def validate(xmlparser, xmlfilename):
try:
with open(xmlfilename, 'rb') as f:
[...]
with open(schema_file, 'rb') as f:
[...]
</code></pre> |
18,139,910 | Internal Server Error when using Flask session | <p>I want to save an ID between requests, using Flask <code>session</code> cookie, but I'm getting an <code>Internal Server Error</code> as result, when I perform a request.</p>
<p>I prototyped a simple Flask app for demonstrating my problem:</p>
<pre><code>#!/usr/bin/env python
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def run():
session['tmp'] = 43
return '43'
if __name__ == '__main__':
app.run()
</code></pre>
<p>Why I can't store the <code>session</code> cookie with the following value when I perform the request?</p> | 18,139,945 | 3 | 2 | null | 2013-08-09 04:10:39.853 UTC | 7 | 2018-10-15 17:44:25.47 UTC | 2018-10-12 23:41:32.993 UTC | null | 5,780,109 | null | 2,236,401 | null | 1 | 33 | python|session|cookies|flask | 52,639 | <p>According to <a href="http://flask.pocoo.org/docs/quickstart/#sessions">Flask sessions documentation</a>:</p>
<blockquote>
<p>...
What this means is that the user could look at the contents of your
cookie but not modify it, unless they know the secret key used for
signing.</p>
<p>In order to use sessions you <strong>have to set a secret key</strong>.</p>
</blockquote>
<p>Set <em>secret key</em>. And you should return string, not int.</p>
<pre><code>#!/usr/bin/env python
from flask import Flask, session
app = Flask(__name__)
@app.route('/')
def run():
session['tmp'] = 43
return '43'
if __name__ == '__main__':
app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT'
app.run()
</code></pre> |
47,121,961 | Can atomics suffer spurious stores? | <p>In C++, can atomics suffer spurious stores?</p>
<p>For example, suppose that <code>m</code> and <code>n</code> are atomics and that <code>m = 5</code> initially. In thread 1,</p>
<pre><code> m += 2;
</code></pre>
<p>In thread 2,</p>
<pre><code> n = m;
</code></pre>
<p>Result: the final value of <code>n</code> should be either 5 or 7, right? But could it spuriously be 6? Could it spuriously be 4 or 8, or even something else?</p>
<p>In other words, does the C++ memory model forbid thread 1 from behaving as though it did this?</p>
<pre><code> ++m;
++m;
</code></pre>
<p>Or, more weirdly, as though it did this?</p>
<pre><code> tmp = m;
m = 4;
tmp += 2;
m = tmp;
</code></pre>
<p>Reference: <a href="http://www.hpl.hp.com/techreports/2008/HPL-2008-56.pdf" rel="noreferrer">H.-J. Boehm & S. V. Adve, 2008,</a> Figure 1. (If you follow the link, then, in the paper's section 1, see the first bulleted item: "The informal specifications provided by ...")</p>
<p><strong>THE QUESTION IN ALTERNATE FORM</strong></p>
<p>One answer (appreciated) shows that the question above can be misunderstood. If helpful, then here is the question in alternate form.</p>
<p>Suppose that the programmer tried to tell thread 1 <em>to skip</em> the operation:</p>
<pre><code> bool a = false;
if (a) m += 2;
</code></pre>
<p>Does the C++ memory model forbid thread 1 from behaving, at run time, as though it did this?</p>
<pre><code> m += 2; // speculatively alter m
m -= 2; // oops, should not have altered! reverse the alteration
</code></pre>
<p>I ask because Boehm and Adve, earlier linked, seem to explain that a multithreaded execution can</p>
<ul>
<li>speculatively alter a variable, but then</li>
<li>later change the variable back to its original value when the speculative alteration turns out to have been unnecessary.</li>
</ul>
<p><strong>COMPILABLE SAMPLE CODE</strong></p>
<p>Here is some code you can actually compile, if you wish.</p>
<pre><code>#include <iostream>
#include <atomic>
#include <thread>
// For the orignial question, do_alter = true.
// For the question in alternate form, do_alter = false.
constexpr bool do_alter = true;
void f1(std::atomic_int *const p, const bool do_alter_)
{
if (do_alter_) p->fetch_add(2, std::memory_order_relaxed);
}
void f2(const std::atomic_int *const p, std::atomic_int *const q)
{
q->store(
p->load(std::memory_order_relaxed),
std::memory_order_relaxed
);
}
int main()
{
std::atomic_int m(5);
std::atomic_int n(0);
std::thread t1(f1, &m, do_alter);
std::thread t2(f2, &m, &n);
t2.join();
t1.join();
std::cout << n << "\n";
return 0;
}
</code></pre>
<p>This code always prints <code>5</code> or <code>7</code> when I run it. (In fact, as far as I can tell, it always prints <code>7</code> when I run it.) However, I see nothing <em>in the semantics</em> that would prevent it from printing <code>6</code>, <code>4</code> or <code>8</code>.</p>
<p>The excellent Cppreference.com <a href="http://en.cppreference.com/w/cpp/atomic" rel="noreferrer">states,</a> "Atomic objects are free of data races," which is nice, but in such a context as this, what does it mean?</p>
<p>Undoubtedly, all this means that I do not understand the semantics very well. Any illumination you can shed on the question would be appreciated.</p>
<p><strong>ANSWERS</strong></p>
<p>@Christophe, @ZalmanStern and @BenVoigt each illuminate the question with skill. Their answers cooperate rather than compete. In my opinion, readers should heed all three answers: @Christophe first; @ZalmanStern second; and @BenVoigt last to sum up.</p> | 47,125,566 | 3 | 18 | null | 2017-11-05 13:11:55.203 UTC | 7 | 2017-11-05 22:48:53.63 UTC | 2017-11-05 22:34:59.96 UTC | null | 1,275,653 | null | 1,275,653 | null | 1 | 32 | c++|multithreading|atomic|memory-barriers | 2,173 | <p>The existing answers provide a lot of good explanation, but they fail to give a direct answer to your question. Here we go:</p>
<blockquote>
<p>can atomics suffer spurious stores?</p>
</blockquote>
<h1>Yes, but you cannot observe them from a C++ program which is free from data races.</h1>
<p><strong>Only <code>volatile</code> is actually prohibited from performing extra memory accesses.</strong></p>
<blockquote>
<p>does the C++ memory model forbid thread 1 from behaving as though it did this?</p>
<pre><code>++m;
++m;
</code></pre>
</blockquote>
<p>Yes, but this one is allowed:</p>
<blockquote>
<pre><code>lock (shared_std_atomic_secret_lock)
{
++m;
++m;
}
</code></pre>
</blockquote>
<p>It's allowed but stupid. A more realistic possibility is turning this:</p>
<pre><code>std::atomic<int64_t> m;
++m;
</code></pre>
<p>into</p>
<pre><code>memory_bus_lock
{
++m.low;
if (last_operation_did_carry)
++m.high;
}
</code></pre>
<p>where <code>memory_bus_lock</code> and <code>last_operation_did_carry</code> are features of the hardware platform that can't be expressed in portable C++.</p>
<p>Note that peripherals sitting on the memory bus <em>do</em> see the intermediate value, but can interpret this situation correctly by looking at the memory bus lock. Software debuggers won't be able to see the intermediate value.</p>
<p>In other cases, atomic operations can be implemented by software locks, in which case:</p>
<ol>
<li>Software debuggers can see intermediate values, and have to be aware of the software lock to avoid misinterpretation</li>
<li>Hardware peripherals will see changes to the software lock, and intermediate values of the atomic object. Some magic may be required for the peripheral to recognize the relationship between the two.</li>
<li>If the atomic object is in shared memory, other processes can see the intermediate values and may not have any way to inspect the software lock / may have a separate copy of said software lock</li>
<li>If other threads in the same C++ program break type safety in a way that causes a data race (For example, using <code>memcpy</code> to read the atomic object) they can observe intermediate values. Formally, that's undefined behavior.</li>
</ol>
<hr />
<p>One last important point. The "speculative write" is a very complex scenario. It's easier to see this if we rename the condition:</p>
<p>Thread #1</p>
<pre><code>if (my_mutex.is_held) o += 2; // o is an ordinary variable, not atomic or volatile
return o;
</code></pre>
<p>Thread #2</p>
<pre><code>{
scoped_lock l(my_mutex);
return o;
}
</code></pre>
<p>There's no data race here. If Thread #1 has the mutex locked, the write and read can't occur unordered. If it doesn't have the mutex locked, the threads run unordered but both are performing only reads.</p>
<p>Therefore the compiler cannot allow intermediate values to be seen. This C++ code is not a correct rewrite:</p>
<pre><code>o += 2;
if (!my_mutex.is_held) o -= 2;
</code></pre>
<p>because the compiler invented a data race. However, if the hardware platform provides a mechanism for race-free speculative writes (Itanium perhaps?), the compiler can use it. So hardware might see intermediate values, even though C++ code cannot.</p>
<p>If intermediate values shouldn't be seen by hardware, you need to use <code>volatile</code> (possibly in addition to atomics, because <code>volatile</code> read-modify-write is not guaranteed atomic). With <code>volatile</code>, asking for an operation which can't be performed as-written will result in compilation failure, not spurious memory access.</p> |
54,480,641 | flutter - how to create forms in popup | <p>I want to create a form inside a pop-up with flutter like the image below:
popup</p>
<p><img src="https://www.formget.com/wp-content/uploads/2014/05/jquery-popup-contact-form.png" alt="popup">.</p>
<p>how can I do that with flutter?</p> | 54,481,069 | 5 | 3 | null | 2019-02-01 13:35:58.223 UTC | 16 | 2022-01-14 00:52:49.423 UTC | 2020-10-24 12:28:46.883 UTC | user10563627 | null | null | 10,378,771 | null | 1 | 47 | flutter|dart|popup|flutter-layout|flutter-form-builder | 115,685 | <p>Here you go! showDialog takes a WidgetBuilder as a parameter so you can return any widget.</p>
<pre><code> import 'package:flutter/material.dart';
void main() {
runApp(new MaterialApp(home: new MyApp()));
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final _formKey = GlobalKey<FormState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter"),
),
body: Center(
child: RaisedButton(
onPressed: () {
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
content: Stack(
overflow: Overflow.visible,
children: <Widget>[
Positioned(
right: -40.0,
top: -40.0,
child: InkResponse(
onTap: () {
Navigator.of(context).pop();
},
child: CircleAvatar(
child: Icon(Icons.close),
backgroundColor: Colors.red,
),
),
),
Form(
key: _formKey,
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Padding(
padding: EdgeInsets.all(8.0),
child: TextFormField(),
),
Padding(
padding: EdgeInsets.all(8.0),
child: TextFormField(),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: RaisedButton(
child: Text("Submitß"),
onPressed: () {
if (_formKey.currentState.validate()) {
_formKey.currentState.save();
}
},
),
)
],
),
),
],
),
);
});
},
child: Text("Open Popup"),
),
),
);
}
}
</code></pre>
<p>Hop it helps!</p> |
33,124,930 | Android 6.0 permission.GET_ACCOUNTS | <p>I'm using this to get permission:</p>
<pre><code>if (ContextCompat.checkSelfPermission(context, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(context, Manifest.permission.GET_ACCOUNTS)) {
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(context, new String[]{Manifest.permission.GET_ACCOUNTS}, PERMISSIONS_REQUEST_GET_ACCOUNTS);
// MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
// app-defined int constant. The callback method gets the
// result of the request.
}
}
</code></pre>
<p>But the pop up dialog for permission asks user for access Contacts!?!?</p>
<p>In pre 6.0 in Play Store with </p>
<pre><code><uses-permission android:name="android.permission.GET_ACCOUNTS"/>
</code></pre>
<p>request is named Identity and explains I need it to get device account. </p> | 33,125,123 | 6 | 3 | null | 2015-10-14 12:10:27.597 UTC | 9 | 2019-02-08 11:57:32.357 UTC | 2017-09-12 14:35:02.32 UTC | null | 3,968,276 | null | 3,206,119 | null | 1 | 37 | android|permissions|android-6.0-marshmallow | 51,374 | <p>That is because of Permission Groups. Basically, permissions are placed under different groups and all permissions from that group would be granted if one of them is granted. </p>
<p>Eg. Under "Contacts" , there is write/read contacts and get accounts, so when you ask for any of those, the popup asks for Contacts permissions.</p>
<p>Read through: <a href="http://inthecheesefactory.com/blog/things-you-need-to-know-about-android-m-permission-developer-edition/en" rel="noreferrer">Everything every Android Developer must know about new Android's Runtime Permission</a></p>
<hr>
<p><em>EDIT 1</em></p>
<p>Just thought i'l add the related(not to get accounts but permissions and groups) Oreo update info:<br>
source: <a href="https://developer.android.com/about/versions/oreo/android-8.0-changes.html#rmp" rel="noreferrer">https://developer.android.com/about/versions/oreo/android-8.0-changes.html#rmp</a></p>
<blockquote>
<p>Prior to Android 8.0 (API level 26), if an app requested a permission
at runtime and the permission was granted, the system also incorrectly
granted the app the rest of the permissions that belonged to the same
permission group, and that were registered in the manifest.</p>
<p>For apps targeting Android 8.0, this behavior has been corrected. The
app is granted only the permissions it has explicitly requested.
However, once the user grants a permission to the app, all subsequent
requests for permissions in that permission group are automatically
granted.</p>
</blockquote>
<hr> |
1,822,122 | How do I add space between items in an ASP.NET RadioButtonList | <p>I've got an ASP.NET RadioButtonList that displays four items using <strong><em>RepeatDirection="Horizontal"</em></strong> to display them on a single line. I'm using <strong><em>RepeatLayout="Flow"</em></strong> to avoid the markup for a table. However, this causes the items in the list to be placed right next to each other, which does not look good.</p>
<p>So, I tried the table layout to take advantage of the <strong><em>CellSpacing</em></strong> and/or <strong><em>CellPadding</em></strong> properties. Unfortunately, these properties affect both the vertical and horizontal spacing/padding within the table, so while I get the horizontal spacing, I also get undesired vertical spacing.</p>
<p>At this point, I'm down to this:</p>
<pre><code><asp:RadioButtonList ID="rblMyRadioButtonList" runat="server"
RepeatDirection="Horizontal"
RepeatLayout="Flow" >
<asp:ListItem Selected="false" Text="Item One&nbsp;&nbsp;&nbsp;&nbsp;" Value="Item_1" />
<asp:ListItem Selected="false" Text="Item Two&nbsp;&nbsp;&nbsp;&nbsp;" Value="Item_2" />
<asp:ListItem Selected="false" Text="Item Three&nbsp;&nbsp;&nbsp;&nbsp;" Value="Item_3" />
<asp:ListItem Selected="false" Text="Item Four&nbsp;&nbsp;&nbsp;&nbsp;" Value="Item_4" />
</asp:RadioButtonList>
</code></pre>
<p>...which screams at me "You're not doing it right!"</p>
<p>What is the right way to accomplish this?</p> | 1,822,153 | 6 | 0 | null | 2009-11-30 20:12:28.193 UTC | 4 | 2020-12-24 17:02:15.59 UTC | null | null | null | null | 5,420 | null | 1 | 29 | asp.net|formatting|markup|radiobuttonlist | 124,498 | <p>Use css to add a right margin to those particular elements. Generally I would build the control, then run it to see what the resulting html structure is like, then make the css alter just those elements.</p>
<p>Preferably you do this by setting the class. Add the <code>CssClass="myrblclass"</code> attribute to your list declaration.</p>
<p>You can also add attributes to the items programmatically, which will come out the other side.</p>
<pre><code>rblMyRadioButtonList.Items[x].Attributes.CssStyle.Add("margin-right:5px;")
</code></pre>
<p>This may be better for you since you can add that attribute for all but the last one.</p> |
2,224,350 | PowerShell Start-Job Working Directory | <p>Is there a way to specify a working directory to the Start-Job command?</p>
<p>Use-case:</p>
<p>I'm in a directory, and I want to open a file using Emacs for editing. If I do this directly, it will block PowerShell until I close Emacs. But using Start-Job attempts to run Emacs from my home directory, thus having Emacs open a new file instead of the one I wanted.</p>
<p>I tried to specify the full path using $pwd, but variables in the script block are not resolved until they're executing in the Start-Job context. So some way to force resolving the variables in the shell context would also be an acceptable answer to this.</p>
<p>So, here's what I've tried, just for completeness:</p>
<pre><code>Start-Job { emacs RandomFile.txt }
Start-Job { emacs "$pwd/RandomFile.txt" }
</code></pre> | 2,246,542 | 6 | 0 | null | 2010-02-08 19:42:22.607 UTC | 9 | 2020-03-19 03:20:49.36 UTC | 2011-05-12 16:12:28.413 UTC | null | 64,046 | null | 12,275 | null | 1 | 33 | powershell|start-job | 19,491 | <p>A possible solution would be to create a "kicker-script":</p>
<pre><code>Start-Job -filepath .\emacs.ps1 -ArgumentList $workingdir, "RandomFile.txt"
</code></pre>
<p>Your script would look like this:</p>
<pre><code>Set-Location $args[0]
emacs $args[1]
</code></pre>
<p>Hope this helps.</p> |
2,008,101 | Recommendations for learning ASP.NET MVC from a desktop developer's perspective | <p>One of my New Year's Resolutions is to finally learn some web development. I've decided on ASP.NET MVC as I'm a believer in TDD and IoC. I'm looking for a list of topics and perhaps an order to learn them for what I'll need to know to be a solid ASP.NET MVC developer. Perhaps this is embarassing, but the only web experience I have was html pages I made using WYSIWYG editors 5+ years ago when I was in college.</p> | 2,008,289 | 7 | 0 | 2010-01-05 18:12:19.85 UTC | 2010-01-05 18:12:19.85 UTC | 10 | 2010-08-02 15:23:05.96 UTC | 2010-01-06 14:15:57.69 UTC | null | 135,148 | null | 135,148 | null | 1 | 9 | asp.net-mvc | 5,091 | <p>So first, congratulations on picking ASP.NET MVC. I dare say that ASP.NET MVC is easier to work with than WebForms. WebForms tends to take somewhat of a "black-box" approach to the web and treat it more like classic WinForms development. WebForms would probably be a slightly more <em>comfortable</em> technology for you (coming from WinForms development) but MVC will leave you with a greater understanding of <em>how the web works</em>, which is incredibly important.</p>
<p>Before you dive into ASP.NET MVC, you may want to brush up on the basics of HTTP, because it is important to understand when you starting writing action methods that respond differently based on request verbs. It's also nice to know exactly what HTTP headers are, and how they can be leveraged in your application. Anyway, here's my list for you:</p>
<h2>Important People and Their Blogs</h2>
<ul>
<li><a href="http://www.haacked.com/" rel="noreferrer">Phil Haack</a>: He is the lead developer on ASP.NET MVC, and his blog has tons of neat tricks and tips for using it.</li>
<li><a href="http://www.hanselman.com/" rel="noreferrer">Scott Hanselman</a>: He worked with the team on NerdDinner and from time to time his blog has some neat MVC stuff.</li>
<li><a href="http://blog.wekeroad.com/" rel="noreferrer">Rob Conery</a>: Rob's an avid promoter of ASP.NET MVC and an active open-source contributor. He has tons of code on github for you to browse for inspiration/guidance, and he also has <strong>tons</strong> of screencasts on his blog and on his business website, <a href="http://www.tekpub.com/" rel="noreferrer">TekPub</a>. I recommend purchasing his screencasts from TekPub because he's just an amazing presenter and makes understanding ASP.NET MVC so easy.</li>
<li><a href="http://weblogs.asp.net/scottgu/" rel="noreferrer">Scott Guthrie</a>: He wrote the first chapter with respects to NerdDinner in the <em>Professional ASP.NET MVC 1.0</em> book, and he always has some cool posts about new features coming in ASP.NET MVC.</li>
<li><a href="http://stephenwalther.com/blog/default.aspx" rel="noreferrer">Steven Walther</a>: It seems like every time I look at his blog he's got another cool trick or code snippet related to ASP.NET MVC. He's also written a book on ASP.NET MVC that has some pretty good reviews on Amazon.</li>
</ul>
<h2>Reading Material</h2>
<ul>
<li><a href="http://www.wdvl.com/Internet/Protocols/HTTP/" rel="noreferrer">WDVL: HyperText Transfer Protocol</a>: Again, this is your HTTP tutorial. I've read through part of it and it seems pretty decent. You don't need a rock solid understanding of HTTP, but a general overview of request verbs and headers specifically will help you.</li>
<li><a href="http://aspnetmvcbook.s3.amazonaws.com/aspnetmvc-nerdinner_v1.pdf" rel="noreferrer">NerdDinner.com Tutorial</a>: This is lengthy step-by-step guide written by ScottGu himself about how to create a basic ASP.NET MVC website from beginning to end.</li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0470384611" rel="noreferrer" rel="nofollow noreferrer">Profesional ASP.NET MVC 1.0</a>: This is a book by the team that wrote this ASP.NET MVC, and it really does a great job of explaining the framework.</li>
<li><a href="https://rads.stackoverflow.com/amzn/click/com/0672329980" rel="noreferrer" rel="nofollow noreferrer">ASP.NET MVC Framework Unleashed</a>: This is Steven Walther's book on the framework. It has some decent reviews on Amazon, though I've never read it myself, so I couldn't really give my opinion one way or the other.</li>
</ul>
<h2>Screencasts</h2>
<ul>
<li><a href="http://blog.wekeroad.com/category/mvc-storefront" rel="noreferrer">Rob Conery's MVC Storefront Series</a>: These screencasts are amazingly helpful. In the beginning they were working against pre-release copies of the MVC framework, so some stuff has changed, but they're still amazing material for learning ASP.NET MVC.</li>
<li><a href="http://weblogs.asp.net/scottgu/archive/2010/01/02/asp-net-4-asp-net-mvc-and-silverlight-4-videos-of-my-talks-in-europe.aspx" rel="noreferrer">Scott Guthrie's Presentations on ASP.NET MVC 2</a>: Look at the ASP.NET MVC section of this page. There are some really neat new features coming in ASP.NET MVC 2, and Scott actually builds a good foundation from the ground up with this presentation. He takes you through beginner stuff first and then shows the neat new tricks later.</li>
<li><a href="http://videos.visitmix.com/MIX09/T50F" rel="noreferrer">Phil Haack's MIX09 MVC Session</a>: Great content here straight from the man himself. Phil's actually a great presenter, and there's a lot of good content here.</li>
<li><a href="http://videos.visitmix.com/MIX09/T44F" rel="noreferrer">Phil Haack's MIX09 Advanced MVC Session</a>: Some more advanced stuff and neat tricks from Phil.</li>
<li><a href="http://videos.visitmix.com/MIX09/T49F" rel="noreferrer">Scott Hanselman's File -> New Company MIX09 Session</a>: I actually attended this session while I was at MIX09, and Scott's a great presenter. Well worth a gander :)</li>
<li><a href="http://www.tekpub.com/preview/aspmvc" rel="noreferrer">Rob Conery and Steven Sanderson TekPub Screencasts</a>: These aren't free, but they're worth every penny. Rob and Steven are amazing teachers, and I can't recommend TekPub screencasts enough. They are top-notch.</li>
</ul>
<h2>IoC and Dependency Injection</h2>
<p>Since you mentioned IoC specifically in your OP, there are a few libraries and blog posts that might help you with that:</p>
<ul>
<li><a href="http://codeclimber.net.nz/archive/2009/08/10/how-to-use-ninject-2-with-asp.net-mvc.aspx" rel="noreferrer">Simone Chiaretta: How to use Ninject 2 with ASP.NET MVC</a>: I actually use Ninject in my own personal projects, so this is a great resource if you're a fan of Ninject.</li>
<li><a href="http://github.com/robconery/Hana" rel="noreferrer">Rob Conery's "Hana" Source Code</a>: Sometimes I just love seeing some quality reference code. This is actually the source for Rob's blog. He was using StructureMap originally, but I think he changed recently to Ninject.Mvc.</li>
<li><a href="http://blog.wekeroad.com/mvc-storefront/mvcstore-part-13/" rel="noreferrer">MVC Storefront DI Screencast</a>: Rob talks about setting up dependency injection in the MVC Storefront. This one uses StructureMap I believe.</li>
<li><a href="http://www.tekpub.com/view/concepts/1" rel="noreferrer">TekPub Concepts video (free)</a>: Rob goes over the basics of IoC and DI in this video if you need a refresher. It's free too :)</li>
</ul>
<h2>Other Pertinent Web Technologies</h2>
<p>Because you're looking to move to the web, there are other languages and technologies that you need to know as well. Below is a list of some brief tutorials to get you started, although each of these subjects could easily warrant a post as big (or bigger) than this one!</p>
<ul>
<li><a href="http://www.w3schools.com/html/default.asp" rel="noreferrer">HTML</a>: Seems silly that I'm mentioning this here, but I only mention it because there's a lot of push these days to write <strong>valid</strong> HTML. A majority of accessibility and browser incompatibility issues can be averted by having clean markup. I personally use XHTML in my sites, but any doctype will do :)</li>
<li><a href="http://www.w3schools.com/js/default.asp" rel="noreferrer">JavaScript</a>: This is a neat language that can be used to make many web applications feel more like a desktop application (amongst other things). There are a lot of performance gains and design victories that can be had by properly leveraging JavaScript. Once you feel comfortable with JavaScript, you will probably want to make the move to a JavaScript library to make cross-browser compatibility very easy. My JavaScript library of choice is <a href="http://www.jquery.com" rel="noreferrer">jQuery</a>.</li>
<li><a href="http://www.w3schools.com/css/default.asp" rel="noreferrer">CSS</a>: This is how you should be applying <em>style</em> to your websites. One of the biggest mistakes a lot of developers make is to make their HTML in charge of presentation (using tables for layouts [holy war], etc. etc.). Arguments and holy wars aside, CSS is a valid skill to have, and it really isn't as hard as some might have you believe :)</li>
</ul>
<p>I know this seems like a lot, and I've probably inundated you with material to read, however I think it's important to build a solid foundation. Web development is a lot of fun when you are good at it, and it's definitely a great way to make a living! Good luck! ASP.NET MVC is a great framework, and you've made a great choice.</p>
<p>Oh yeah, and there are a few other things you might want to Google in your spare time. They tend to be pretty advanced, so I didn't include them here, but you will run into them when you get more involved in the web world:</p>
<ul>
<li><strong>AJAX</strong>: Makes your web applications perform more naturally and do things in the background.</li>
<li><strong>Web Services</strong>: A universal way to exchange data on the web. For example, there are web services that provide weather forecasts and stock quotes. You can consume them and even create some of your own!</li>
<li><strong>XML and JSON</strong>: These are used to describe data. When you serialize data on the web, XML and/or JSON are the conventional technologies most developers use. JSON is popular particularly because it can be consumed so nicely within JavaScript.</li>
</ul> |
1,682,920 | Determine If a User Is Idented On IRC | <p>In my IRC Bot, there are some commands that I want to only be usable by me, and I want to check to make sure that anyone using my name is identified with nickserv (idented). I couldn't, however, find an easy way to determine this, which is why I'm here.</p>
<p><a href="http://freenode.net/" rel="noreferrer">Freenode</a> and <a href="http://www.rizon.net/" rel="noreferrer">Rizon</a> are the primary target networks, if that matters.</p>
<p>Edit: I was actually aware of the various usermodes for idented users (although I didn't pay enough attention to realize that they differ!); sorry for not mentioning that before. The raw response that I get from a user, however, doesn't include their usermodes; it looks something like this:</p>
<pre><code>:[email protected] PRIVMSG #erasmus-testing :foo
</code></pre>
<p>I suppose, then, that I'm trying to find a way (with various ircds, grr) to get those flags. If, as someone mentioned, Rizon returns whether or not someone is idented in a WHOIS query, then that's the sort of thing I'm looking for.</p> | 1,733,975 | 7 | 0 | null | 2009-11-05 19:19:56.22 UTC | 9 | 2019-01-31 12:27:30.653 UTC | 2009-11-06 01:50:05.72 UTC | null | 120,999 | null | 120,999 | null | 1 | 11 | irc|bots | 9,814 | <p>On freenode, sending a private message to nickserv with the message <code>ACC <nickname></code> will return a number that indicates the user's ident status:</p>
<blockquote>
<p>The answer is in the form <code><nickname> ACC <digit></code>:</p>
<pre><code> 0 - account or user does not exist
1 - account exists but user is not logged in
2 - user is not logged in but recognized (see ACCESS)
3 - user is logged in
</code></pre>
</blockquote>
<p>The <code>STATUS <nickname></code> command gives similar results on Rizon:</p>
<blockquote>
<p>The response has this format:</p>
<p><code><nickname> <digit></code></p>
<pre><code> 0 - no such user online or nickname not registered
1 - user not recognized as nickname's owner
2 - user recognized as owner via access list only
3 - user recognized as owner via password identification
</code></pre>
</blockquote>
<p>The advantages that this method has over a WHOIS:</p>
<ol>
<li><strong>Information about ident status is always included.</strong> With WHOISes, you will just not get a line saying something along the lines of "identified with nickserv as such-and-such" if the user is not, in fact, idented.</li>
<li><strong>Consistent number of lines returned.</strong> Since I want to grab the message before passing on control to the rest of my program, I can easily read one line out of the buffer (I see synchronization issues in your future!), determine the status, and continue on like normal.</li>
</ol> |
2,191,632 | Begin, Rescue and Ensure in Ruby? | <p>I've recently started programming in Ruby, and I am looking at exception handling.</p>
<p>I was wondering if <code>ensure</code> was the Ruby equivalent of <code>finally</code> in C#? Should I have:</p>
<pre><code>file = File.open("myFile.txt", "w")
begin
file << "#{content} \n"
rescue
#handle the error here
ensure
file.close unless file.nil?
end
</code></pre>
<p>or should I do this?</p>
<pre><code>#store the file
file = File.open("myFile.txt", "w")
begin
file << "#{content} \n"
file.close
rescue
#handle the error here
ensure
file.close unless file.nil?
end
</code></pre>
<p>Does <code>ensure</code> get called no matter what, even if an exception isn't raised?</p> | 2,192,010 | 7 | 1 | null | 2010-02-03 11:54:15.12 UTC | 241 | 2020-03-25 08:40:02.617 UTC | 2014-01-23 12:57:02.177 UTC | null | 128,421 | null | 67,258 | null | 1 | 611 | ruby-on-rails|ruby|exception|exception-handling|error-handling | 471,151 | <p>Yes, <code>ensure</code> ensures that the code is always evaluated. That's why it's called <code>ensure</code>. So, it is equivalent to Java's and C#'s <code>finally</code>.</p>
<p>The general flow of <code>begin</code>/<code>rescue</code>/<code>else</code>/<code>ensure</code>/<code>end</code> looks like this:</p>
<pre><code>begin
# something which might raise an exception
rescue SomeExceptionClass => some_variable
# code that deals with some exception
rescue SomeOtherException => some_other_variable
# code that deals with some other exception
else
# code that runs only if *no* exception was raised
ensure
# ensure that this code always runs, no matter what
# does not change the final value of the block
end
</code></pre>
<p>You can leave out <code>rescue</code>, <code>ensure</code> or <code>else</code>. You can also leave out the variables in which case you won't be able to inspect the exception in your exception handling code. (Well, you can always use the global exception variable to access the last exception that was raised, but that's a little bit hacky.) And you can leave out the exception class, in which case all exceptions that inherit from <code>StandardError</code> will be caught. (Please note that this does not mean that <em>all</em> exceptions are caught, because there are exceptions which are instances of <code>Exception</code> but not <code>StandardError</code>. Mostly very severe exceptions that compromise the integrity of the program such as <code>SystemStackError</code>, <code>NoMemoryError</code>, <code>SecurityError</code>, <code>NotImplementedError</code>, <code>LoadError</code>, <code>SyntaxError</code>, <code>ScriptError</code>, <code>Interrupt</code>, <code>SignalException</code> or <code>SystemExit</code>.)</p>
<p>Some blocks form implicit exception blocks. For example, method definitions are implicitly also exception blocks, so instead of writing</p>
<pre><code>def foo
begin
# ...
rescue
# ...
end
end
</code></pre>
<p>you write just</p>
<pre><code>def foo
# ...
rescue
# ...
end
</code></pre>
<p>or</p>
<pre><code>def foo
# ...
ensure
# ...
end
</code></pre>
<p>The same applies to <code>class</code> definitions and <code>module</code> definitions.</p>
<p>However, in the specific case you are asking about, there is actually a much better idiom. In general, when you work with some resource which you need to clean up at the end, you do that by passing a block to a method which does all the cleanup for you. It's similar to a <code>using</code> block in C#, except that Ruby is actually powerful enough that you don't have to wait for the high priests of Microsoft to come down from the mountain and graciously change their compiler for you. In Ruby, you can just implement it yourself:</p>
<pre><code># This is what you want to do:
File.open('myFile.txt', 'w') do |file|
file.puts content
end
# And this is how you might implement it:
def File.open(filename, mode='r', perm=nil, opt=nil)
yield filehandle = new(filename, mode, perm, opt)
ensure
filehandle&.close
end
</code></pre>
<p>And what do you know: this is <em>already</em> available in the core library as <code>File.open</code>. But it is a general pattern that you can use in your own code as well, for implementing any kind of resource cleanup (à la <code>using</code> in C#) or transactions or whatever else you might think of.</p>
<p>The only case where this doesn't work, if acquiring and releasing the resource are distributed over different parts of the program. But if it is localized, as in your example, then you can easily use these resource blocks.</p>
<hr>
<p>BTW: in modern C#, <code>using</code> is actually superfluous, because you can implement Ruby-style resource blocks yourself:</p>
<pre><code>class File
{
static T open<T>(string filename, string mode, Func<File, T> block)
{
var handle = new File(filename, mode);
try
{
return block(handle);
}
finally
{
handle.Dispose();
}
}
}
// Usage:
File.open("myFile.txt", "w", (file) =>
{
file.WriteLine(contents);
});
</code></pre> |
1,831,353 | The speed of .NET in numerical computing | <p>In my experience, .NET is 2 to 3 times slower than native code. (I implemented L-BFGS for multivariate optimization).</p>
<p>I have traced the ads on stackoverflow to
<a href="http://www.centerspace.net/products/" rel="noreferrer">http://www.centerspace.net/products/</a></p>
<p>the speed is really amazing, the speed is close to native code. How can they do that?
They said that:</p>
<blockquote>
<p>Q. Is NMath "pure" .NET?</p>
<p>A. The answer depends somewhat on your definition of "pure .NET". NMath is written in C#, plus a small Managed C++ layer. For better performance of basic linear algebra operations, however, NMath does rely on the native Intel Math Kernel Library (included with NMath). But there are no COM components, no DLLs--just .NET assemblies. Also, all memory allocated in the Managed C++ layer and used by native code is allocated from the managed heap.</p>
</blockquote>
<p>Can someone explain more to me?</p> | 1,831,564 | 8 | 4 | null | 2009-12-02 08:09:30.147 UTC | 11 | 2016-03-15 19:04:09.413 UTC | 2020-06-20 09:12:55.06 UTC | null | -1 | null | 183,828 | null | 1 | 18 | c#|.net|managed-c++|managed-code|nmath | 6,965 | <p>The point about C++/CLI is correct. To complete the picture, just two additional interesting points:</p>
<ul>
<li><p>.NET memory management (garbage collector) obviously is not the problem here, as NMath still depends on it</p></li>
<li><p>The performance advantage is actually provided by Intel MKL, which offers implementations extremely optimized for many CPUs. From my point of view, this is the crucial point. Using straight-forward, naiv C/C++ code wont necessarily give you superior performance over C#/.NET, it's sometimes even worse. However C++/CLI allows you to exploit all the "dirty" optimization options.</p></li>
</ul> |
2,074,454 | Override a static method | <p>I am extending a new class by inheriting from RolesService. In RolesService I have a static methog that I would like to override in my newly derived class. When I make the call from my derived object it does not use the overridden static method it actually calls the base class method. Any ideas? </p>
<pre><code>public class RolesService : IRolesService
{
public static bool IsUserInRole(string username, string rolename)
{
return Roles.IsUserInRole(username, rolename);
}
}
public class MockRoleService : RolesService
{
public new static bool IsUserInRole(string username, string rolename)
{
return true;
}
}
</code></pre> | 2,075,226 | 10 | 1 | null | 2010-01-15 20:09:14.893 UTC | 7 | 2020-12-06 16:20:38.727 UTC | 2017-11-03 17:37:00.423 UTC | null | 4,684,797 | null | 106,403 | null | 1 | 40 | c#|asp.net|asp.net-mvc | 63,986 | <p>Doing the following the will allow you to work around the static call. Where you want to use the code take an IRolesService via dependency injection then when you need MockRolesService you can pass that in.</p>
<pre><code>public interface IRolesService
{
bool IsUserInRole(string username, string rolename);
}
public class RolesService : IRolesService
{
public bool IsUserInRole(string username, string rolename)
{
return Roles.IsUserInRole(username, rolename);
}
}
public class MockRoleService : IRolesService
{
public bool IsUserInRole(string username, string rolename)
{
return true;
}
}
</code></pre> |
1,387,612 | How can I introduce multiple conditions in LIKE operator? | <p>I want to write an SQL statement like below:</p>
<pre><code>select * from tbl where col like ('ABC%','XYZ%','PQR%');
</code></pre>
<p>I know it can be done using <code>OR</code>. But I want to know is there any better solution.</p> | 1,387,627 | 10 | 6 | null | 2009-09-07 05:03:38.097 UTC | 34 | 2021-10-07 16:44:20.347 UTC | 2020-12-14 14:16:51.92 UTC | null | 1,783,163 | null | 147,025 | null | 1 | 83 | sql|oracle | 436,954 | <p>Here is an alternative way:</p>
<pre><code>select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';
</code></pre>
<p>Here is the test code to verify:</p>
<pre><code>create table tbl (col varchar(255));
insert into tbl (col) values ('ABCDEFG'), ('HIJKLMNO'), ('PQRSTUVW'), ('XYZ');
select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';
+----------+
| col |
+----------+
| ABCDEFG |
| XYZ |
| PQRSTUVW |
+----------+
3 rows in set (0.00 sec)
</code></pre> |
8,903,601 | How to process a form (via get or post) using class-based views? | <p>Im trying to learn class-based views, for a detail or list view is not that complicated.</p>
<p>I have a search form and I just want to see if I send a query to show up the results.</p>
<p>Here is the function code (is not mine, is from a django book):</p>
<pre><code>def search_page(request):
form = SearchForm()
bookmarks = []
show_results = False
if 'query' in request.GET:
show_results = True
query = request.GET['query'].strip()
if query:
form = SearchForm({'query': query})
bookmarks = Bookmark.objects.filter(title__icontains=query)[:10]
show_tags = True
show_user = True
if request.is_ajax():
return render_to_response("bookmarks/bookmark_list.html", locals(), context_instance=RequestContext(request))
else:
return render_to_response("search/search.html", locals(), context_instance=RequestContext(request))
</code></pre>
<p>Ignoring the ajax fact (just to make the problem easier for now), how can I translate this to class-based views?</p>
<p>I quick tried something like this:</p>
<pre><code>class SearchPageView(FormView):
template_name = 'search/search.html'
def get(self, request, *args, **kwargs):
form = SearchForm()
self.bookmarks = []
self.show_results = False
if 'query' in self.request.GET:
self.show_results = True
query = self.request.GET['query'].strip()
if query:
form = SearchForm({'query': query})
self.bookmarks = Bookmark.objects.filter(title__icontains=query)[:10]
return super(SearchPageView, self).get(request, *args, **kwargs)
def get_context_data(self, **kwargs):
context = super(SearchPageView, self).get_context_data(**kwargs)
context.update({
'show_tags': True,
'show_user': True,
'show_results': self.show_results,
'bookmarks': self.bookmarks
})
return context
</code></pre>
<p>Doesn't work, I get a: "'NoneType' object is not callable"</p>
<p>Fair enough, I started today with this stuff.</p>
<p>So, what's the way to make a Class-based views that can manage a get (and a post too if needed) request?</p>
<p>I have another example:</p>
<pre><code>@render_to('registration/register.html')
def register_page(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return HttpResponseRedirect('/accounts/register/success/')
else:
form = RegistrationForm()
return locals()
</code></pre>
<p>Would this be "transformed" the same way that the first one? Or they extend differents Views?</p>
<p>Im confused a lot. I don't know if the first is ProcessFormView and the second FormView or what.</p>
<p>Thanks.</p>
<p><strong>EDIT:</strong> Solution I ended with:</p>
<pre><code>class SearchPageView(FormView):
template_name = 'search/search.html'
def get(self, request, *args, **kwargs):
self.bookmarks = []
self.show_results = False
form = SearchForm(self.request.GET or None)
if form.is_valid():
self.show_results = True
self.bookmarks = Bookmark.objects.filter(title__icontains=form.cleaned_data['query'])[:10]
return self.render_to_response(self.get_context_data(form=form))
def get_context_data(self, **kwargs):
context = super(SearchPageView, self).get_context_data(**kwargs)
context.update({
'show_tags': True,
'show_user': True,
'show_results': self.show_results,
'bookmarks': self.bookmarks
})
return context
</code></pre>
<p>I leave this here to someone with same question :)</p> | 8,903,801 | 2 | 2 | null | 2012-01-18 00:25:12.587 UTC | 25 | 2015-01-03 21:29:51.35 UTC | 2012-01-19 10:35:25.86 UTC | null | 123,204 | null | 123,204 | null | 1 | 37 | django|django-class-based-views | 58,239 | <p>The default behaviour of the <a href="https://docs.djangoproject.com/en/dev/ref/class-based-views/generic-editing/#formview" rel="noreferrer"><code>FormView</code></a> class is to display an unbound form for <code>GET</code> requests, and bind the form for <code>POST</code> (or <code>PUT</code>) requests. If the bound form is valid, then the <code>form_valid</code> method is called, which simply redirects to the success url (defined by the <code>success_url</code> attribute or the <code>get_success_url</code> method.</p>
<p>This matches the example quite well. You need to override the <code>form_valid</code> method to create the new <code>User</code>, before calling the superclass method to redirect to the success url.</p>
<pre><code>class CreateUser(FormView):
template_name = 'registration/register.html'
success_url = '/accounts/register/success/'
form_class = RegistrationForm
def form_valid(self, form):
user = User.objects.create_user(
username=form.cleaned_data['username'],
password=form.cleaned_data['password1'],
email=form.cleaned_data['email']
)
return super(CreateUser, self).form_valid(form)
</code></pre>
<p>Your first example does not match the flow of <code>FormView</code> so well, because you aren't processing a form with <code>POST</code> data, and you don't do anything when the form is valid. </p>
<p>I might try extending <code>TemplateView</code>, and putting all the logic in <code>get_context_data</code>.
Once you get that working, you could factor the code that parses the GET data and returns the bookmarks into its own method. You could look at extending <code>ListView</code>, but I don't think there's any real advantage unless you want to paginate results.</p> |
6,930,584 | Proper Android REST client | <p>I made my own REST client library for an Android application, but after watching the <a href="http://www.google.com/events/io/2010/sessions/developing-RESTful-android-apps.html" rel="nofollow">Google I/O presentation</a> on the subject I realized I had it all wrong (precisely what they show slide 9).</p>
<p>Now I am looking to do it again the right way, but I'm wondering if there isn't a library that could save me the trouble. We use Jersey on the server side.</p>
<p>I've looked at different solutions : <a href="http://crest.codegist.org/" rel="nofollow">CRest</a> and <a href="http://beders.github.com/Resty/Resty/Overview.html" rel="nofollow">Resty</a>, but what I'd like to find an Android solution so I don't have to implement the ContentProvider stuff myself, and <a href="http://code.google.com/p/android-jbridge/" rel="nofollow">android-jbridge</a>, but it doesn't look very active.</p>
<p>At this point I'm considering using <a href="http://static.springsource.org/spring-android/docs/1.0.x/reference/html/rest-template.html" rel="nofollow">RestTemplate</a> (from Spring Android) and writing the stuff around it myself, but that'll take some time.</p>
<p>Any better alternative?</p> | 8,694,157 | 3 | 4 | null | 2011-08-03 17:28:13.137 UTC | 9 | 2015-02-11 06:39:31.413 UTC | 2013-06-27 17:31:17.837 UTC | null | 318,557 | null | 318,557 | null | 1 | 12 | android|rest|jersey|rest-client | 9,133 | <p>"Developing Android REST client applications" by Virgil Dobjanschi led to much discussion, since no source code was presented during the session or was provided afterwards.</p>
<p>The only reference implementation I know (please comment if you know more) is available at <a href="http://datadroid.foxykeep.com" rel="noreferrer">Datadroid</a> (the Google IO session is mentioned under /presentation). It is a library which you can use in your own application.</p>
<p><strong>Update</strong><br>
There are other libraries available. I do not know how they confirm to Dobjanschis patterns, but I would like to list them for your reference (text is taken from the homepage of the library):</p>
<ul>
<li><p><a href="https://github.com/octo-online/robospice" rel="noreferrer">RoboSpice</a> is a modular android library that makes writing asynchronous long running tasks easy. It is specialized in network requests, supports caching and offers REST requests out-of-the box using extension modules.</p></li>
<li><p><a href="https://github.com/PCreations/RESTDroid" rel="noreferrer">RESTDroid</a> (currently alpha) provides a way to handle calls to REST web-services. It contains only the fundamental logic to handle these requests, extension is possible with modules (some are provided). </p></li>
</ul> |
6,551,777 | How to check if SP1 for SQL Server 2008 R2 is already installed? | <p>I have trouble figuring out if the SP1 is already installed. I don't think I could check it from the Management Studio as its a different application. But the SQl server it self has no UI to check under "about". :)</p>
<p>Any ideas?</p> | 6,551,847 | 3 | 0 | null | 2011-07-01 18:22:51.63 UTC | 3 | 2017-08-16 01:05:01.77 UTC | 2012-01-10 09:38:28.813 UTC | null | 626,273 | null | 92,153 | null | 1 | 16 | sql-server-express|sql-server-2008-r2 | 46,237 | <p>There is not SP1 for SQL Server 2008 R2 just yet.....</p>
<p>But to check, you can inspect the <code>productlevel</code> server property:</p>
<pre><code>SELECT
SERVERPROPERTY('productlevel')
</code></pre>
<p>This will contain <code>RTM</code> for the original RTM version (as it is in my case with SQL Server 2008 R2 now), or it will contain info about the service pack installed.</p>
<p>I typically use this SQL query:</p>
<pre><code>SELECT
SERVERPROPERTY('productversion') as 'Product Version',
SERVERPROPERTY('productlevel') as 'Patch Level',
SERVERPROPERTY('edition') as 'Product Edition',
SERVERPROPERTY('buildclrversion') as 'CLR Version',
SERVERPROPERTY('collation') as 'Default Collation',
SERVERPROPERTY('instancename') as 'Instance',
SERVERPROPERTY('lcid') as 'LCID',
SERVERPROPERTY('servername') as 'Server Name'
</code></pre>
<p>This lists your server version, edition, service pack (if applicable) etc. - something like this:</p>
<pre><code>Product Version Patch Level Product Edition CLR Version Default Collation Instance LCID Server Name
10.50.1617.0 RTM Developer Edition (64-bit) v2.0.50727 Latin1_General_CI_AS NULL 1033 *********
</code></pre>
<p><strong>Update:</strong> this answer was correct when it was posted - July 2011.</p>
<p>By now, November 2012, there's <a href="http://www.microsoft.com/en-us/download/details.aspx?id=30437" rel="noreferrer">SQL Server 2008 R2 Service Pack 2</a> available for download</p> |
6,777,419 | How to configure Spring to make JPA (Hibernate) and JDBC (JdbcTemplate or MyBatis) share the same transaction | <p>I have a single dataSource, I use Spring 3.0.3, Hibernate 3.5.1 as JPA provider and I use MyBatis 3.0.2 for some queries and my app runs on Tomcat 6. I have a HibernateDAO and a MyBatisDAO, when I call both from the same method which is annotated with @Transactional it looks like they don't share the same transaction, they get different connections.
<br>How can I make them to do?</p>
<p>I've tried getting a connection from DataSourceUtils.getConnection(dataSource) and I get the one which is used by MyBatis which is strange I thought the problem was in MyBatis config and it can't use JpaTransactionManager. Even calling multiple times DataSoruceUtils.getConnection gives the same connection always, which is ok.</p>
<p>After some googling I've tried spring-instrument-tomcat's classloader (although I don't know if tomcat really uses it :))</p>
<p>partial applicationContext</p>
<pre class="lang-xml prettyprint-override"><code><bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven mode="aspectj" transaction-manager="transactionManager"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="dataSource" ref="dataSource"/>
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:META-INF/mybatis/mybatis-config.xml" />
</bean>
</code></pre>
<p>partial mybatis config</p>
<pre class="lang-xml prettyprint-override"><code><settings>
<setting name="cacheEnabled" value="false" />
<setting name="useGeneratedKeys" value="false" />
<setting name="defaultExecutorType" value="REUSE" />
<setting name="lazyLoadingEnabled" value="false"/>
</settings>
</code></pre>
<p>partial persistence.xml</p>
<pre class="lang-xml prettyprint-override"><code><persistence-unit name="persistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
</code></pre> | 6,784,884 | 3 | 1 | null | 2011-07-21 14:11:23.357 UTC | 22 | 2012-02-09 09:17:58.137 UTC | null | null | null | null | 299,788 | null | 1 | 28 | hibernate|spring|jpa|transactions|mybatis | 31,926 | <p>I've found the solution here: <a href="https://stackoverflow.com/questions/2673678/what-transaction-manager-should-i-use-for-jbdc-template-when-using-jpa">What transaction manager should I use for JBDC template When using JPA ?</a></p>
<p>I'm using JpaTransactionManager and not DataSourceTransactionManager.
<br>JavaDoc <a href="http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/jpa/JpaTransactionManager.html" rel="noreferrer">http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/jpa/JpaTransactionManager.html</a></p>
<blockquote>
<p>This transaction manager <strong>also supports direct DataSource access within a transaction (i.e. plain JDBC code working with the same DataSource)</strong>. This allows for mixing services which access JPA and services which use plain JDBC (without being aware of JPA)! Application code needs to stick to the same simple Connection lookup pattern as with DataSourceTransactionManager (i.e. DataSourceUtils.getConnection(javax.sql.DataSource) or going through a TransactionAwareDataSourceProxy). <strong>Note that this requires a vendor-specific JpaDialect to be configured.</strong></p>
</blockquote>
<p>After I've added jpaVendorAdapter to my entityManagerFactory config everything works, both JdbcTemplate query and MyBatis runs in the same transaction as expected. Based on the JavaDoc I guess a jpaDialect should be enough but it's 4 a.m. here so I won't try that now :)</p>
<pre><code><bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit"/>
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" />
</bean>
</property>
</bean>
</code></pre> |
6,697,614 | How to draw a triangle programmatically | <p>I have a triangle solver, I want a way to use the values I get from the answer to draw a triangle to the screen that matches it. </p> | 6,697,796 | 3 | 2 | null | 2011-07-14 17:42:29.86 UTC | 13 | 2017-09-20 00:03:21.213 UTC | 2011-07-14 17:49:44.917 UTC | null | 19,679 | null | 804,306 | null | 1 | 31 | iphone|ios|cocoa-touch|quartz-graphics | 29,530 | <p>If you subclass a UIView you can implement something like this in drawRect to draw a triangle:</p>
<pre><code>-(void)drawRect:(CGRect)rect
{
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextBeginPath(ctx);
CGContextMoveToPoint (ctx, CGRectGetMinX(rect), CGRectGetMinY(rect)); // top left
CGContextAddLineToPoint(ctx, CGRectGetMaxX(rect), CGRectGetMidY(rect)); // mid right
CGContextAddLineToPoint(ctx, CGRectGetMinX(rect), CGRectGetMaxY(rect)); // bottom left
CGContextClosePath(ctx);
CGContextSetRGBFillColor(ctx, 1, 1, 0, 1);
CGContextFillPath(ctx);
}
</code></pre> |
6,552,980 | ASP.NET MVC: Html.EditorFor and multi-line text boxes | <p>This is my code:</p>
<pre><code> <div class="editor-label">
@Html.LabelFor(model => model.Comments[0].Comment)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Comments[0].Comment)
@Html.ValidationMessageFor(model => model.Comments[0].Comment)
</div>
</code></pre>
<p>This is what it generates:</p>
<pre><code> <div class="editor-label">
<label for="Comments_0__Comment">Comment</label>
</div>
<div class="editor-field">
<input class="text-box single-line" data-val="true" data-val-required="The Comment field is required." id="Comments_0__Comment" name="Comments[0].Comment" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Comments[0].Comment" data-valmsg-replace="true"></span>
</div>
</code></pre>
<p>How do I tell it that the field should be a text box with five lines instead of just a single-line text box?</p> | 6,553,039 | 3 | 1 | null | 2011-07-01 20:36:31.443 UTC | 6 | 2017-06-23 14:15:05.483 UTC | null | null | null | null | 5,274 | null | 1 | 54 | asp.net-mvc-3|razor | 114,389 | <p>Use data type 'MultilineText':</p>
<pre><code>[DataType(DataType.MultilineText)]
public string Text { get; set; }
</code></pre>
<p>See <a href="https://stackoverflow.com/questions/4927003/asp-net-mvc3-textarea-with-html-editorfor">ASP.NET MVC3 - textarea with @Html.EditorFor</a></p> |
6,469,683 | Format() function doesn't work? | <p>I am trying to execute following built-in function in sql but it gives me error that this function doesn't exist </p>
<p>my query:</p>
<pre><code>select EmpId, EmpName, format(EmpJoinDate, "YYYY-DD-MM") as date from Employee
</code></pre>
<p>Error i am getting:</p>
<pre><code>'format' is not a recognized built-in function name
</code></pre>
<p>What may be the problem, or what am i doing wrong? </p>
<p>Thanks!</p> | 6,469,714 | 4 | 0 | null | 2011-06-24 15:02:36.833 UTC | 1 | 2020-01-24 19:28:30.763 UTC | 2011-06-27 18:23:41.91 UTC | null | 787,016 | user728885 | null | null | 1 | 14 | sql|sql-server-2005|tsql|sql-server-2008|format | 53,802 | <p>Use <a href="http://msdn.microsoft.com/en-us/library/ms187928.aspx" rel="noreferrer"><code>Convert</code></a> function instead. Example:</p>
<pre><code>select convert(varchar(5), GETDATE(), 126) + convert(varchar(5), GETDATE(), 105)
</code></pre> |
23,551,729 | SQL Server 2012 installation Reporting Services Catalog error | <p>I'm installing SQL Server 2012 at the moment and when I was about to run the installation, this error pops up: </p>
<p><img src="https://i.stack.imgur.com/rgr1C.png" alt="The errors can be seen clearly in this picture"></p>
<p>On clicking the first failed test, which is "Reporting Services Catalog Database File Existence", this is what i get:</p>
<p><img src="https://i.stack.imgur.com/Ipmqu.png" alt="enter image description here"></p>
<p>On clicking the second failed test, which is "Reporting Services Catalog Temporary Database File Existence", this is what i get:</p>
<p><img src="https://i.stack.imgur.com/MV3XS.png" alt="enter image description here"></p>
<p>So basically, both of the message box says me that "Catalog Database File" & "Catalog Temporary database files exists". Because of this, i need to select Reporting Services file-only mode installation. </p>
<p>My questions are:</p>
<ol>
<li>How do i select file-only mode installation?</li>
<li>Do i've to close the setup and do something and afterwards run the setup again?</li>
</ol>
<p>Btw, I had SQL Server 2012 installed before. I uninstalled it completely due to some strange errors and decided to reinstall a fresh copy of SQL Server 2012 and now I'm stuck with these errors. Any help will be sincerely appreciated. :)</p> | 23,551,886 | 2 | 2 | null | 2014-05-08 20:19:19.957 UTC | 13 | 2017-09-11 10:47:16.197 UTC | null | null | null | null | 3,584,973 | null | 1 | 50 | sql|sql-server|visual-studio-2012|sql-server-2012 | 53,386 | <p>Since you already had one installation of SQL Server done before, there was a database already created. That <strong>did not</strong> get removed. So when you reinstall, its trying to create the database with the same name, hence, the error. You need to delete the old files to continue the new installation.</p>
<blockquote>
<p>From the direcotry</p>
<p><code>C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA</code> </p>
<p>Remove the following files</p>
<ul>
<li><code>ReportServer.mdf</code></li>
<li><code>ReportServer_log.LDF</code></li>
<li><code>ReportServerTempDB.mdf</code></li>
<li><code>ReportServerTempDB_log.LDF</code></li>
</ul>
</blockquote>
<p><a href="https://i.stack.imgur.com/6Yx6g.png" rel="noreferrer"><img src="https://i.stack.imgur.com/6Yx6g.png" alt="Screenshot"></a></p>
<p>Try the Following link for further help.</p>
<p><strong><a href="https://blog.sqlauthority.com/2017/07/05/sql-server-fix-rule-reporting-services-catalog-database-file-existence-failed/" rel="noreferrer">Reporting Services Catalog Error.</a></strong></p>
<hr>
<p>For <a href="/questions/tagged/sql-server-2012" class="post-tag" title="show questions tagged 'sql-server-2012'" rel="tag">sql-server-2012</a> the path is:</p>
<pre><code>C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQL2012\MSSQL\DATA
</code></pre>
<p>where <code>MSSQL2012</code> is the instance name and the respective file names are:</p>
<ul>
<li><code>ReportServer$MSSQL2012.mdf</code></li>
<li><code>ReportServer$MSSQL2012_log.mdf</code></li>
<li><code>ReportServer$MSSQL2012TempDB.mdf</code></li>
<li><code>ReportServer$MSSQL2012TempDB_log.mdf</code></li>
</ul> |
143,020 | mathematical optimization library for Java --- free or open source recommendations? | <p>Does anyone know of such a library that performs mathematical optimization (linear programming, convex optimization, or more general types of problems)? I'm looking for something like MATLAB, but with the ability to handle larger problems. Do I have to write my own implementations, or buy one of those commercial products (CPLEX and the like)?</p> | 146,415 | 7 | 0 | null | 2008-09-27 04:52:44.323 UTC | 10 | 2018-05-08 16:20:25.96 UTC | 2016-02-10 16:32:55.737 UTC | null | 14,167 | Zach Scrivena | 20,029 | null | 1 | 16 | mathematical-optimization|linear-programming|cplex|gurobi|convex-optimization | 18,540 | <p>A good answer is dependent on what you mean by "convex" and "more general" If you are trying to solve large or challenging linear or convex-quadratic optimization problems (especially with a discrete component to them), then it's hard to beat the main commercial solvers, <a href="http://www.gurobi.com" rel="nofollow noreferrer">gurobi</a>, <a href="http://www.ilog.com/products/cplex" rel="nofollow noreferrer">cplex</a> and <a href="http://www.dashoptimization.com/home/cgi-bin/example.pl#bcl_java" rel="nofollow noreferrer">Dash</a> unless money is a big issue for you. They all have clean JNI interfaces and are available on most major platforms.</p>
<p>The <a href="http://www.coin-or.org" rel="nofollow noreferrer">coin-or</a> project has several optimizers and have a project for JNI interface. It is totally free (<a href="http://www.eclipse.org/legal/eplfaq.php" rel="nofollow noreferrer">EPL</a> license), but will take more work to set-up and probably not give you the same performance.</p> |
1,048,805 | Compressing a directory of files with PHP | <p>I am creating a php backup script that will dump everything from a database and save it to a file. I have been successful in doing that but now I need to take hundreds of images in a directory and compress them into one simple .tar.gz file.</p>
<p>What is the best way to do this and how is it done? I have no idea where to start. </p>
<p>Thanks in advance</p> | 1,048,860 | 7 | 1 | null | 2009-06-26 12:12:34.663 UTC | 11 | 2021-06-08 05:04:57.617 UTC | 2009-06-26 12:47:00.303 UTC | null | 124,024 | null | 124,024 | null | 1 | 17 | php|compression|backup | 41,306 | <p>If you are using PHP 5.2 or later, you could use the <a href="http://us3.php.net/manual/en/book.zip.php" rel="nofollow noreferrer">Zip Library</a></p>
<p>and then do something along the lines of:</p>
<pre><code>$images_dir = '/path/to/images';
//this folder must be writeable by the server
$backup = '/path/to/backup';
$zip_file = $backup.'/backup.zip';
if ($handle = opendir($images_dir))
{
$zip = new ZipArchive();
if ($zip->open($zip_file, ZipArchive::CREATE)!==TRUE)
{
exit("cannot open <$zip_file>\n");
}
while (false !== ($file = readdir($handle)))
{
$zip->addFile($images_dir.'/'.$file);
echo "$file\n";
}
closedir($handle);
echo "numfiles: " . $zip->numFiles . "\n";
echo "status:" . $zip->status . "\n";
$zip->close();
echo 'Zip File:'.$zip_file . "\n";
}
</code></pre> |
325,667 | How can I check if a server has ssl enable or not | <p>Does anyone of you know, if and if so, how can I check, with my application code, if a server has ssl enabled or not?</p> | 325,833 | 8 | 3 | null | 2008-11-28 12:30:19.463 UTC | 5 | 2021-10-18 09:54:50.02 UTC | 2016-03-04 09:13:54.66 UTC | null | 1,740,715 | null | 40,077 | null | 1 | 16 | ssl | 47,957 | <p><a href="http://mail.python.org/pipermail/python-list/2003-May/203039.html" rel="nofollow noreferrer">"It's easier to ask forgiveness than permission"</a></p>
<p>For example, to read <code>stackoverflow.com</code> via SSL, don't ask whether <code>stackoverflow.com</code> supports it, just do it. In Python:</p>
<pre><code>>>> import urllib2
>>> urllib2.urlopen('https://stackoverflow.com')
Traceback (most recent call last):
...
urllib2.URLError: <urlopen error (10060, 'Operation timed out')>
>>> html = urllib2.urlopen('http://stackoverflow.com').read()
>>> len(html)
146271
>>>
</code></pre>
<p>It shows that <code>stackoverflow.com</code> doesn't support SSL (2008).</p>
<hr>
<p><strong>Update:</strong> <code>stackoverflow.com</code> supports https now.</p> |
185,235 | jQuery tabs - getting newly selected index | <p>I've previously used <a href="https://jqueryui.com/tabs/" rel="nofollow noreferrer"><code>jquery-ui tabs</code></a> extension to load page fragments via <code>ajax</code>, and to conceal or reveal hidden <code>div</code>s within a page. Both of these methods are well documented, and I've had no problems there.</p>
<p>Now, however, I want to do something different with tabs. When the user selects a tab, it should reload the page entirely - the reason for this is that the contents of each tabbed section are somewhat expensive to render, so I don't want to just send them all at once and use the normal method of toggling 'display:none' to reveal them.</p>
<p>My plan is to intercept the tabs' <code>select</code> event, and have that function reload the page with by manipulating document.location.</p>
<p>How, in the <code>select</code> handler, can I get the newly selected tab index and the html LI object it corresponds to?</p>
<pre><code>$('#edit_tabs').tabs( {
selected: 2, // which tab to start on when page loads
select: function(e, ui) {
var t = $(e.target);
// alert("data is " + t.data('load.tabs')); // undef
// alert("data is " + ui.data('load.tabs')); // undef
// This gives a numeric index...
alert( "selected is " + t.data('selected.tabs') )
// ... but it's the index of the PREVIOUSLY selected tab, not the
// one the user is now choosing.
return true;
// eventual goal is:
// ... document.location= extract-url-from(something); return false;
}
});
</code></pre>
<p>Is there an attribute of the event or ui object that I can read that will give the index, id, or object of the newly selected tab or the anchor tag within it? </p>
<p>Or is there a better way altogether to use tabs to reload the entire page?</p> | 185,257 | 8 | 0 | null | 2008-10-08 22:51:00.71 UTC | 7 | 2017-12-28 07:48:42.597 UTC | 2017-12-28 07:48:42.597 UTC | Adam Bellaire | 2,833,516 | Matt Hucke | 2,554,901 | null | 1 | 26 | javascript|jquery|jquery-ui|jquery-plugins|jquery-ui-tabs | 69,423 | <p>I would take a look at the <a href="http://docs.jquery.com/UI/Tabs#Events" rel="noreferrer">events</a> for Tabs. The following is taken from the jQuery docs:</p>
<pre><code> $('.ui-tabs-nav').bind('tabsselect', function(event, ui) {
ui.options // options used to intialize this widget
ui.tab // anchor element of the selected (clicked) tab
ui.panel // element, that contains the contents of the selected (clicked) tab
ui.index // zero-based index of the selected (clicked) tab
});
</code></pre>
<p>Looks like ui.tab is the way to go.</p> |
229,069 | Dead code detection in legacy C/C++ project | <p>How would you go about dead code detection in C/C++ code? I have a pretty large code base to work with and at least 10-15% is dead code. Is there any Unix based tool to identify this areas? Some pieces of code still use a lot of preprocessor, can automated process handle that?</p> | 229,121 | 8 | 1 | null | 2008-10-23 09:18:25.01 UTC | 31 | 2017-11-01 16:08:16.053 UTC | 2008-10-23 09:20:38.267 UTC | Dror Helper | 11,361 | Nazgob | 3,579 | null | 1 | 68 | c++|automation|static-analysis|legacy-code|dead-code | 37,604 | <p>You could use a code coverage analysis tool for this and look for unused spots in your code.</p>
<p>A popular tool for the gcc toolchain is gcov, together with the graphical frontend lcov (<a href="http://ltp.sourceforge.net/coverage/lcov.php" rel="noreferrer">http://ltp.sourceforge.net/coverage/lcov.php</a>).</p>
<p>If you use gcc, you can compile with gcov support, which is enabled by the '--coverage' flag. Next, run your application or run your test suite with this gcov enabled build.</p>
<p>Basically gcc will emit some extra files during compilation and the application will also emit some coverage data while running. You have to collect all of these (.gcdo and .gcda files). I'm not going in full detail here, but you probably need to set two environment variables to collect the coverage data in a sane way: GCOV_PREFIX and GCOV_PREFIX_STRIP... </p>
<p>After the run, you can put all the coverage data together and run it through the lcov toolsuite. Merging of all the coverage files from different test runs is also possible, albeit a bit involved.</p>
<p>Anyhow, you end up with a nice set of webpages showing some coverage information, pointing out the pieces of code that have no coverage and hence, were not used.</p>
<p>Off course, you need to double check if the portions of code are not used in any situation and a lot depends on how good your tests exercise the codebase. But at least, this will give an idea about possible dead-code candidates...</p> |
1,336,791 | Dictionary vs Object - which is more efficient and why? | <p>What is more efficient in Python in terms of memory usage and CPU consumption - Dictionary or Object?</p>
<p><strong>Background:</strong>
I have to load huge amount of data into Python. I created an object that is just a field container. Creating 4M instances and putting them into a dictionary took about 10 minutes and ~6GB of memory. After dictionary is ready, accessing it is a blink of an eye.</p>
<p><strong>Example:</strong>
To check the performance I wrote two simple programs that do the same - one is using objects, other dictionary:</p>
<p>Object (execution time ~18sec):</p>
<pre><code>class Obj(object):
def __init__(self, i):
self.i = i
self.l = []
all = {}
for i in range(1000000):
all[i] = Obj(i)
</code></pre>
<p>Dictionary (execution time ~12sec):</p>
<pre><code>all = {}
for i in range(1000000):
o = {}
o['i'] = i
o['l'] = []
all[i] = o
</code></pre>
<p><strong>Question:</strong>
Am I doing something wrong or dictionary is just faster than object? If indeed dictionary performs better, can somebody explain why?</p> | 1,336,890 | 8 | 2 | null | 2009-08-26 18:55:45.71 UTC | 52 | 2021-08-25 16:48:56.893 UTC | null | null | null | null | 42,201 | null | 1 | 145 | python|performance|dictionary|object | 71,263 | <p>Have you tried using <code>__slots__</code>?</p>
<p>From the <a href="https://docs.python.org/2/reference/datamodel.html#slots" rel="noreferrer">documentation</a>:</p>
<blockquote>
<p>By default, instances of both old and new-style classes have a dictionary for attribute storage. This wastes space for objects having very few instance variables. The space consumption can become acute when creating large numbers of instances.</p>
<p>The default can be overridden by defining <code>__slots__</code> in a new-style class definition. The <code>__slots__</code> declaration takes a sequence of instance variables and reserves just enough space in each instance to hold a value for each variable. Space is saved because <code>__dict__</code> is not created for each instance.</p>
</blockquote>
<p>So does this save time as well as memory?</p>
<p>Comparing the three approaches on my computer:</p>
<p>test_slots.py:</p>
<pre><code>class Obj(object):
__slots__ = ('i', 'l')
def __init__(self, i):
self.i = i
self.l = []
all = {}
for i in range(1000000):
all[i] = Obj(i)
</code></pre>
<p>test_obj.py:</p>
<pre><code>class Obj(object):
def __init__(self, i):
self.i = i
self.l = []
all = {}
for i in range(1000000):
all[i] = Obj(i)
</code></pre>
<p>test_dict.py:</p>
<pre><code>all = {}
for i in range(1000000):
o = {}
o['i'] = i
o['l'] = []
all[i] = o
</code></pre>
<p>test_namedtuple.py (supported in 2.6):</p>
<pre><code>import collections
Obj = collections.namedtuple('Obj', 'i l')
all = {}
for i in range(1000000):
all[i] = Obj(i, [])
</code></pre>
<p>Run benchmark (using CPython 2.5):</p>
<pre><code>$ lshw | grep product | head -n 1
product: Intel(R) Pentium(R) M processor 1.60GHz
$ python --version
Python 2.5
$ time python test_obj.py && time python test_dict.py && time python test_slots.py
real 0m27.398s (using 'normal' object)
real 0m16.747s (using __dict__)
real 0m11.777s (using __slots__)
</code></pre>
<p>Using CPython 2.6.2, including the named tuple test:</p>
<pre><code>$ python --version
Python 2.6.2
$ time python test_obj.py && time python test_dict.py && time python test_slots.py && time python test_namedtuple.py
real 0m27.197s (using 'normal' object)
real 0m17.657s (using __dict__)
real 0m12.249s (using __slots__)
real 0m12.262s (using namedtuple)
</code></pre>
<p>So yes (not really a surprise), using <code>__slots__</code> is a performance optimization. Using a named tuple has similar performance to <code>__slots__</code>.</p> |
1,277,278 | Is there a zip-like function that pads to longest length? | <p>Is there a built-in function that works like <a href="https://docs.python.org/3/library/functions.html#zip" rel="noreferrer"><code>zip()</code></a> but that will pad the results so that the length of the resultant list is the length of the <em>longest</em> input rather than the <em>shortest</em> input?</p>
<pre><code>>>> a = ['a1']
>>> b = ['b1', 'b2', 'b3']
>>> c = ['c1', 'c2']
>>> zip(a, b, c)
[('a1', 'b1', 'c1')]
>>> What command goes here?
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
</code></pre> | 1,277,311 | 8 | 0 | null | 2009-08-14 11:04:09.12 UTC | 38 | 2022-07-21 17:32:14.587 UTC | 2021-03-19 23:25:02.45 UTC | null | 355,230 | null | 116 | null | 1 | 242 | python|list|zip | 109,259 | <p>In Python 3 you can use <a href="https://docs.python.org/3/library/itertools.html#itertools.zip_longest" rel="noreferrer"><code>itertools.zip_longest</code></a></p>
<pre><code>>>> list(itertools.zip_longest(a, b, c))
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
</code></pre>
<p>You can pad with a different value than <code>None</code> by using the <code>fillvalue</code> parameter:</p>
<pre><code>>>> list(itertools.zip_longest(a, b, c, fillvalue='foo'))
[('a1', 'b1', 'c1'), ('foo', 'b2', 'c2'), ('foo', 'b3', 'foo')]
</code></pre>
<p>With Python 2 you can either use <a href="https://docs.python.org/2/library/itertools.html#itertools.izip_longest" rel="noreferrer"><code>itertools.izip_longest</code></a> (Python 2.6+), or you can use <code>map</code> with <code>None</code>. It is a little known <a href="https://docs.python.org/2/library/functions.html#map" rel="noreferrer">feature of <code>map</code></a> (but <code>map</code> changed in Python 3.x, so this only works in Python 2.x).</p>
<pre><code>>>> map(None, a, b, c)
[('a1', 'b1', 'c1'), (None, 'b2', 'c2'), (None, 'b3', None)]
</code></pre> |
903,572 | Consequences of doing "good enough" software | <p>Does doing "good enough" software take anything from you being a programmer?</p>
<p>Here are my thoughts on this:</p>
<p>Well Joel Spolsky from JoelOnSoftware says that programmers gets bored because they do "good enough" (software that satisfies the requirements even though they are not that optimized). I agree, because people like to do things that are right all the way. On one side of the spectra, I want to go as far as:</p>
<ol>
<li>Optimizing software in such a way as I can apply all my knowledge in Math and Computer Science I acquired in college as much as possible.</li>
<li>Do all of the possible software development process say: get specs from a repository, generate the code, build, test, deploy complete with manuals in a single automated build step.</li>
</ol>
<p>On the other hand, a trait to us human is that we like variety. In order to us to maintain attraction (love programming), we need to jump from one project or technology to the other in order for us to not get bored and have "fun".</p>
<p>I would like your opinion if there is any good or bad side effects in doing "good enough" software to you as a programmer or human being?</p> | 903,609 | 9 | 0 | null | 2009-05-24 11:22:51.55 UTC | 9 | 2012-03-20 14:23:28.2 UTC | 2012-03-20 14:23:28.2 UTC | null | 21,234 | null | 77,993 | null | 1 | 11 | language-agnostic | 1,292 | <p>I actually consider good-enough programmers to be better than the blue-sky-make-sure-everything-is-perfect variety.</p>
<p>That's because, although I'm a coder, I'm also a businessman and realize that programs are <em>not</em> for the satisfaction of programmers, they're to meet a specific business need.</p>
<p>I actually had an argument in another question regarding the best way to detect a won tic-tac-toe/noughts-and-crosses game (an interview question).</p>
<p>The best solution that I'd received was from a candidate that simply checked all 8 possibilities with <code>if</code> statements. There were some that gave a generalized solution which, while workable, were totally unnecessary since the specs were quite clear it was for a 3x3 board only.</p>
<p>Many people thought I was being too restrictive and the "winning" solution was rubbish but my opinion is that it's not the job of a programmer to write perfect beautifully-extendable software. It's their job to meet a business need.</p>
<p>If that business need allows them the freedom to do more than necessary, that's fine, but most software and fixes are delivered under time and cost constraints. Programmers (or any profession) don't work in a vacuum.</p> |
110,911 | What is the closest thing to Slime for Scheme? | <p>I do most of my development in Common Lisp, but there are some moments when I want to switch to Scheme (while reading <em>Lisp in Small Pieces</em>, when I want to play with continuations, or when I want to do some scripting in Gauche, for example). In such situations, my main source of discomfort is that I don't have Slime (yes, you may call me an addict).</p>
<p>What is Scheme's closest counterpart to Slime? Specifically, I am most interested in:</p>
<ul>
<li>Emacs integration (this point is obvious ;))</li>
<li>Decent tab completion (ideally, c-w-c-c TAB should expand to call-with-current-continuation). It may be even symbol-table based (ie. it doesn't have to notice a function I defined in a <code>let</code> at once).</li>
<li>Function argument hints in the minibuffer (if I have typed <code>(map |)</code> (cursor position is indicated by <code>|</code>)), I'd like to see <code>(map predicate . lists)</code> in the minibuffer</li>
<li>Sending forms to the interpreter</li>
<li>Integration with a debugger.</li>
</ul>
<p>I have ordered the features by descending importance.</p>
<p>My Scheme implementations of choice are:</p>
<ul>
<li>MzScheme</li>
<li>Ikarus</li>
<li>Gauche</li>
<li>Bigloo</li>
<li>Chicken</li>
</ul>
<p>It would be great if it worked at least with them.</p> | 129,009 | 9 | 1 | null | 2008-09-21 12:34:20.89 UTC | 18 | 2021-09-26 14:10:59.837 UTC | 2013-09-23 18:38:49.01 UTC | Ryszard Szopa | 1,281,433 | Ryszard Szopa | 19,922 | null | 1 | 45 | emacs|lisp|scheme|common-lisp|slime | 14,188 | <p>You also might consider Scheme Complete:</p>
<p><a href="http://www.emacswiki.org/cgi-bin/wiki/SchemeComplete" rel="noreferrer">http://www.emacswiki.org/cgi-bin/wiki/SchemeComplete</a></p>
<p>It basically provides tab-completion.</p> |
1,110,915 | Is a DIV inside a TD a bad idea? | <p>It seems like I heard/read somewhere that a <code><div></code> inside of a <code><td></code> was a no-no. Not that it won't work, just something about them not being really compatible based on their display type. Can't find any evidence to back up my hunch, so I may be totally wrong. </p> | 1,111,197 | 9 | 0 | null | 2009-07-10 17:33:40.25 UTC | 19 | 2017-12-13 07:00:32.61 UTC | 2016-01-25 23:58:39.403 UTC | null | 30,946 | null | 30,946 | null | 1 | 159 | html|html-table|semantic-markup|web-standards | 174,630 | <p>Using a <code>div</code> instide a <code>td</code> is not worse than any other way of using tables for layout. (Some people never use tables for layout though, and I happen to be one of them.)</p>
<p>If you use a <code>div</code> in a <code>td</code> you will however get in a situation where it might be hard to predict how the elements will be sized. The default for a div is to determine its width from its parent, and the default for a table cell is to determine its size depending on the size of its content.</p>
<p>The rules for how a <code>div</code> should be sized is well defined in the standards, but the rules for how a <code>td</code> should be sized is not as well defined, so different browsers use slightly different algorithms.</p> |
227,007 | Resetting the time part of a timestamp in Java | <p>In Java, given a timestamp, how to reset the time part alone to 00:00:00 so that the timestamp represents the midnight of that particular day ?</p>
<p>In T-SQL, this query will do to achieve the same, but I don't know how to do this in Java.</p>
<p><code>SELECT CAST( FLOOR( CAST(GETDATE() AS FLOAT ) ) AS DATETIME) AS 'DateTimeAtMidnight';</code></p> | 227,049 | 10 | 0 | null | 2008-10-22 18:28:18.63 UTC | 12 | 2019-08-20 13:03:07.11 UTC | null | null | null | Vijay Dev | 27,474 | null | 1 | 39 | java|sql|timestamp | 57,565 | <p>You can go Date->Calendar->set->Date:</p>
<pre><code>Date date = new Date(); // timestamp now
Calendar cal = Calendar.getInstance(); // get calendar instance
cal.setTime(date); // set cal to date
cal.set(Calendar.HOUR_OF_DAY, 0); // set hour to midnight
cal.set(Calendar.MINUTE, 0); // set minute in hour
cal.set(Calendar.SECOND, 0); // set second in minute
cal.set(Calendar.MILLISECOND, 0); // set millis in second
Date zeroedDate = cal.getTime(); // actually computes the new Date
</code></pre>
<p>I love Java dates.</p>
<p>Note that if you're using actual java.sql.Timestamps, they have an extra nanos field. Calendar of course, knows nothing of nanos so will blindly ignore it and effectively drop it when creating the zeroedDate at the end, which you could then use to create a new Timetamp object.</p>
<p>I should also note that Calendar is not thread-safe, so don't go thinking you can make that a static single cal instance called from multiple threads to avoid creating new Calendar instances.</p> |
1,148,309 | Inverting a 4x4 matrix | <p>I am looking for a sample code implementation on how to invert a 4x4 matrix. I know there is Gaussian eleminiation, LU decomposition, etc., but instead of looking at them in detail I am really just looking for the code to do this.</p>
<p>Language ideally C++, data is available in array of 16 floats in column-major order.</p> | 1,148,405 | 10 | 5 | null | 2009-07-18 19:04:34.033 UTC | 37 | 2021-05-18 16:09:42.353 UTC | 2020-02-24 11:51:56.143 UTC | null | 7,508,700 | null | 97,688 | null | 1 | 90 | c++|algorithm|math|matrix|matrix-inverse | 86,739 | <p>here:</p>
<pre><code>bool gluInvertMatrix(const double m[16], double invOut[16])
{
double inv[16], det;
int i;
inv[0] = m[5] * m[10] * m[15] -
m[5] * m[11] * m[14] -
m[9] * m[6] * m[15] +
m[9] * m[7] * m[14] +
m[13] * m[6] * m[11] -
m[13] * m[7] * m[10];
inv[4] = -m[4] * m[10] * m[15] +
m[4] * m[11] * m[14] +
m[8] * m[6] * m[15] -
m[8] * m[7] * m[14] -
m[12] * m[6] * m[11] +
m[12] * m[7] * m[10];
inv[8] = m[4] * m[9] * m[15] -
m[4] * m[11] * m[13] -
m[8] * m[5] * m[15] +
m[8] * m[7] * m[13] +
m[12] * m[5] * m[11] -
m[12] * m[7] * m[9];
inv[12] = -m[4] * m[9] * m[14] +
m[4] * m[10] * m[13] +
m[8] * m[5] * m[14] -
m[8] * m[6] * m[13] -
m[12] * m[5] * m[10] +
m[12] * m[6] * m[9];
inv[1] = -m[1] * m[10] * m[15] +
m[1] * m[11] * m[14] +
m[9] * m[2] * m[15] -
m[9] * m[3] * m[14] -
m[13] * m[2] * m[11] +
m[13] * m[3] * m[10];
inv[5] = m[0] * m[10] * m[15] -
m[0] * m[11] * m[14] -
m[8] * m[2] * m[15] +
m[8] * m[3] * m[14] +
m[12] * m[2] * m[11] -
m[12] * m[3] * m[10];
inv[9] = -m[0] * m[9] * m[15] +
m[0] * m[11] * m[13] +
m[8] * m[1] * m[15] -
m[8] * m[3] * m[13] -
m[12] * m[1] * m[11] +
m[12] * m[3] * m[9];
inv[13] = m[0] * m[9] * m[14] -
m[0] * m[10] * m[13] -
m[8] * m[1] * m[14] +
m[8] * m[2] * m[13] +
m[12] * m[1] * m[10] -
m[12] * m[2] * m[9];
inv[2] = m[1] * m[6] * m[15] -
m[1] * m[7] * m[14] -
m[5] * m[2] * m[15] +
m[5] * m[3] * m[14] +
m[13] * m[2] * m[7] -
m[13] * m[3] * m[6];
inv[6] = -m[0] * m[6] * m[15] +
m[0] * m[7] * m[14] +
m[4] * m[2] * m[15] -
m[4] * m[3] * m[14] -
m[12] * m[2] * m[7] +
m[12] * m[3] * m[6];
inv[10] = m[0] * m[5] * m[15] -
m[0] * m[7] * m[13] -
m[4] * m[1] * m[15] +
m[4] * m[3] * m[13] +
m[12] * m[1] * m[7] -
m[12] * m[3] * m[5];
inv[14] = -m[0] * m[5] * m[14] +
m[0] * m[6] * m[13] +
m[4] * m[1] * m[14] -
m[4] * m[2] * m[13] -
m[12] * m[1] * m[6] +
m[12] * m[2] * m[5];
inv[3] = -m[1] * m[6] * m[11] +
m[1] * m[7] * m[10] +
m[5] * m[2] * m[11] -
m[5] * m[3] * m[10] -
m[9] * m[2] * m[7] +
m[9] * m[3] * m[6];
inv[7] = m[0] * m[6] * m[11] -
m[0] * m[7] * m[10] -
m[4] * m[2] * m[11] +
m[4] * m[3] * m[10] +
m[8] * m[2] * m[7] -
m[8] * m[3] * m[6];
inv[11] = -m[0] * m[5] * m[11] +
m[0] * m[7] * m[9] +
m[4] * m[1] * m[11] -
m[4] * m[3] * m[9] -
m[8] * m[1] * m[7] +
m[8] * m[3] * m[5];
inv[15] = m[0] * m[5] * m[10] -
m[0] * m[6] * m[9] -
m[4] * m[1] * m[10] +
m[4] * m[2] * m[9] +
m[8] * m[1] * m[6] -
m[8] * m[2] * m[5];
det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
if (det == 0)
return false;
det = 1.0 / det;
for (i = 0; i < 16; i++)
invOut[i] = inv[i] * det;
return true;
}
</code></pre>
<p>This was lifted from <a href="http://www.mesa3d.org/" rel="noreferrer">MESA</a> implementation of the GLU library.</p> |
508,374 | What are vectors and how are they used in programming? | <p>I'm familiar with the mathematical/physics concept of a vector as a magnitude and a direction, but I also keep coming across references to vectors in the context of programming (for example C++ seems to have a stl::vector library which comes up fairly frequently on SO).</p>
<p>My intuition from the context has been that they're a fairly primitive construct most often used to represent something along the lines of a variable length array (storing its size as the magnitude, I presume), but it would be really helpful if somebody could provide me with a more complete explanation, preferably including how and why they're used in practice.</p> | 508,394 | 11 | 1 | null | 2009-02-03 18:44:06.223 UTC | 18 | 2018-07-13 12:42:17.947 UTC | null | null | null | Lawrence Johnston | 1,512 | null | 1 | 57 | computer-science|vector | 76,272 | <p>From <a href="http://www.cplusplus.com/reference/stl/vector/" rel="noreferrer">http://www.cplusplus.com/reference/stl/vector/</a></p>
<blockquote>
<p>Vector containers are implemented as
dynamic arrays; Just as regular
arrays, vector containers have their
elements stored in contiguous storage
locations, which means that their
elements can be accessed not only
using iterators but also using offsets
on regular pointers to elements.</p>
<p>But unlike regular arrays, storage in
vectors is handled automatically,
allowing it to be expanded and
contracted as needed.</p>
</blockquote>
<p>Furthermore, vectors can typically hold any object - so you can make a class to hold information about vehicles, and then store the fleet in a vector.</p>
<p>Nice things about vectors, aside from resizing, is that they still allow access in constant time to individual elements via index, just like an array.</p>
<p>The tradeoff for resizing, is that when you hit the current capacity it has to reallocate, and sometimes copy to, more memory. However most capacity increasing algorithms double the capacity each time you hit the barrier, so you never hit it more than log2(heap available) which turns out to be perhaps a dozen times in the worst case throughout program operation.</p>
<p>-Adam</p> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.