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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
439,573 | How to convert a single char into an int | <p>I have a string of digits, e.g. "123456789", and I need to extract each one of them to use them in a calculation. I can of course access each char by index, but how do I convert it into an int?</p>
<p>I've looked into atoi(), but it takes a string as argument. Hence I must convert each char into a string and then call atoi on it. Is there a better way?</p> | 439,589 | 11 | 3 | null | 2009-01-13 16:07:35.703 UTC | 39 | 2021-07-26 16:13:17.9 UTC | 2009-05-15 13:50:32.67 UTC | null | 71,394 | null | 37,268 | null | 1 | 69 | c++|char | 256,097 | <p>You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (<em>see comments below for more on this</em>).</p>
<p>Therefore the integer value for any digit is the digit minus '0' (or 48).</p>
<pre><code>char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'
</code></pre>
<p>is synonymous to</p>
<pre><code>char c = '1';
int i = c - 48; // i is now equal to 1, not '1'
</code></pre>
<p>However I find the first <code>c - '0'</code> far more readable.</p> |
177,437 | What does 'const static' mean in C and C++? | <pre><code>const static int foo = 42;
</code></pre>
<p>I saw this in some code here on StackOverflow and I couldn't figure out what it does. Then I saw some confused answers on other forums. My best guess is that it's used in C to hide the constant <code>foo</code> from other modules. Is this correct? If so, why would anyone use it in a C++ context where you can just make it <code>private</code>?</p> | 177,451 | 12 | 0 | null | 2008-10-07 06:59:39.837 UTC | 62 | 2019-08-08 10:30:07.01 UTC | 2015-06-14 21:27:21.62 UTC | MrValdez | 212,378 | null | 2,079 | null | 1 | 143 | c++|c | 234,386 | <p>It has uses in both C and C++.</p>
<p>As you guessed, the <code>static</code> part limits its scope to that <a href="https://stackoverflow.com/questions/1106149/what-is-a-translation-unit-in-c">compilation unit</a>. It also provides for static initialization. <code>const</code> just tells the compiler to not let anybody modify it. This variable is either put in the data or bss segment depending on the architecture, and might be in memory marked read-only.</p>
<p>All that is how C treats these variables (or how C++ treats namespace variables). In C++, a member marked <code>static</code> is shared by all instances of a given class. Whether it's private or not doesn't affect the fact that one variable is shared by multiple instances. Having <code>const</code> on there will warn you if any code would try to modify that.</p>
<p>If it was strictly private, then each instance of the class would get its own version (optimizer notwithstanding).</p> |
11,194 | How can I conditionally apply a Linq operator? | <p>We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?</p> | 11,203 | 13 | 0 | null | 2008-08-14 15:20:26.973 UTC | 27 | 2021-07-01 09:40:09.82 UTC | 2021-07-01 09:40:09.82 UTC | Keith | 542,251 | Sam | 1,204 | null | 1 | 99 | c#|linq|linq-to-sql | 104,473 | <p>if you want to only filter if certain criteria is passed, do something like this</p>
<pre><code>var logs = from log in context.Logs
select log;
if (filterBySeverity)
logs = logs.Where(p => p.Severity == severity);
if (filterByUser)
logs = logs.Where(p => p.User == user);
</code></pre>
<p>Doing so this way will allow your Expression tree to be exactly what you want. That way the SQL created will be exactly what you need and nothing less.</p> |
1,311,428 | Haml: Control whitespace around text | <p>In my Rails template, I'd like to accomplish final HTML to this effect using HAML:</p>
<pre><code>I will first <a href="http://example.com">link somewhere</a>, then render this half of the sentence if a condition is met
</code></pre>
<p>The template that comes close:</p>
<pre><code>I will first
= link_to 'link somewhere', 'http://example.com'
- if @condition
, then render this half of the sentence if a condition is met
</code></pre>
<p>You may, however, note that this produces a space between the link and the comma. Is there any practical way to avoid this whitespace? I know there's syntax to remove whitespace around tags, but can this same syntax be applied to just text? I really don't like the solution of extra markup to accomplish this.</p> | 6,283,768 | 13 | 0 | null | 2009-08-21 11:30:10.697 UTC | 59 | 2017-04-20 02:04:13.073 UTC | 2015-11-24 10:04:16.593 UTC | null | 2,202,702 | null | 107,415 | null | 1 | 100 | ruby-on-rails|haml | 39,680 | <p>A better way to do this has been introduced via Haml's helpers: </p>
<h3><a href="http://haml.info/docs/yardoc/file.REFERENCE.html#surround">surround</a></h3>
<pre><code>= surround '(', ')' do
%a{:href => "food"} chicken
</code></pre>
Produces:
<pre><code>(<a href='food'>chicken</a>)
</code></pre>
<h3><a href="http://haml.info/docs/yardoc/file.REFERENCE.html#succeed">succeed</a>:</h3>
<pre><code>click
= succeed '.' do
%a{:href=>"thing"} here
</code></pre>
Produces:
<pre><code>click
<a href='thing'>here</a>.
</code></pre>
<h3><a href="http://haml.info/docs/yardoc/file.REFERENCE.html#precede">precede</a>:</h3>
<pre><code>= precede '*' do
%span.small Not really
</code></pre>
Produces:
<pre><code>*<span class='small'>Not really</span>
</code></pre>
<h3>To answer the original question:</h3>
<pre><code>I will first
= succeed ',' do
= link_to 'link somewhere', 'http://example.com'
- if @condition
then render this half of the sentence if a condition is met
</code></pre>
Produces:
<pre><code>I will first
<a href="http://example.com">link somewhere</a>,
then render this half of the sentence if a condition is met
</code></pre> |
267,200 | Visual Studio Solutions Folder as real Folders | <p>I have a Visual Studio Solution. Currently, it is an empty solution (=no projects) and I have added a few solution folders.</p>
<p>Solution Folders only seem to be "virtual folders", because they are not really created in the Filesystem and files inside solution folders are just sitting in the same folder as the .sln file.</p>
<p>Is there a setting that i've overlooked that tells Visual Studio to treat Solution Folders as "real" folders, that is to create them in the file system and move files into it when I move them inside the solution into one of those folders?</p>
<p><strong>Edit:</strong> Thanks. Going to make a suggestion for VS2010 then :)</p> | 267,210 | 18 | 4 | null | 2008-11-05 23:54:44.023 UTC | 21 | 2021-09-22 15:45:41.753 UTC | 2008-11-06 00:06:06.09 UTC | Michael Stum | 91 | Michael Stum | 91 | null | 1 | 166 | visual-studio | 78,000 | <p>No special setting. I don't think it's supported.</p>
<p>You can create real folders in a "project" within the solution, but not in the solution itself.</p> |
6,904,883 | Android: automatically make variables for all IDs in xml | <p>I noticed one of the most tedious parts of Android development is the layout design, even with layout builder.</p>
<p>After setting up the graphics, then the layout, making variable associations with the layout elements is very tedious, such as <code>ImageButton myButton = (ImageButton)findViewById(R.id.myButton);</code></p>
<p>in larger layouts, these can get tedious to keep track of (recalling the names of the elements) and then the need to add more variables in any kind of order gets frustrating.</p>
<p>To slightly mitigate this, it would be very convenient if all of the IDs I declared in the XML were automatically associated with their proper variables, and all of those datatypes were already included in that class</p>
<p>Is there something that already does this?</p>
<p>for instance if I write</p>
<pre><code> <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/myButton" android:id="@+id/myButton"></ImageButton>
</code></pre>
<p>then I would like the classes which include this layout to already have</p>
<pre><code> import android.ImageButton;
ImageButton myButton;
myButton = (ImageButton)findViewById(R.id.myButton);
</code></pre>
<p>is this a setting or a feature to request? I am using the Eclipse IDE and it would be very convenient</p> | 6,917,675 | 5 | 2 | null | 2011-08-01 21:47:09.087 UTC | 9 | 2020-03-02 15:30:58.06 UTC | null | null | null | null | 727,429 | null | 1 | 21 | android|xml|layout|convenience-methods | 9,822 | <p>Try using <a href="http://code.google.com/p/androidannotations/" rel="noreferrer">Android Annotations</a>. It provides useful annotations to replace boilerplate code.</p>
<p>For instance, see <code>@ViewById</code> <a href="http://code.google.com/p/androidannotations/wiki/LayoutAndViews#@ViewById" rel="noreferrer">documentation</a>: just declare the fields annotated</p>
<pre><code>@ViewById
EditText myEditText;
@ViewById(R.id.myTextView)
TextView textView;
</code></pre>
<p>It replaces </p>
<pre><code>EditText myEditText;
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
[...]
myEditText = (EditText) findViewById(R.id.myEditText);
textView = (TextView) findViewById(R.id.myTextView);
}
</code></pre> |
6,501,043 | Limit number of lines in textarea and Display line count using jQuery | <p>Using jQuery I would like to:</p>
<ul>
<li>Limit the number of lines a user can enter in a textarea to a set number</li>
<li>Have a line counter appear that updates number of lines as lines are entered</li>
<li>Return key or \n would count as line</li>
</ul>
<pre><code>$(document).ready(function(){
$('#countMe').keydown(function(event) {
// If number of lines is > X (specified by me) return false
// Count number of lines/update as user enters them turn red if over limit.
});
});
<form class="lineCount">
<textarea id="countMe" cols="30" rows="5"></textarea><br>
<input type="submit" value="Test Me">
</form>
<div class="theCount">Lines used = X (updates as lines entered)<div>
</code></pre>
<p>For this example lets say limit the number of lines allowed to 10.</p> | 6,501,310 | 5 | 2 | null | 2011-06-28 02:50:17.623 UTC | 11 | 2021-08-16 05:38:14.6 UTC | 2021-08-16 05:38:14.6 UTC | null | 5,267,751 | null | 337,529 | null | 1 | 27 | javascript|jquery|html|validation|textarea | 66,132 | <p>html:</p>
<pre><code><textarea id="countMe" cols="30" rows="5"></textarea>
<div class="theCount">Lines used: <span id="linesUsed">0</span><div>
</code></pre>
<p>js:</p>
<pre><code>$(document).ready(function(){
var lines = 10;
var linesUsed = $('#linesUsed');
$('#countMe').keydown(function(e) {
newLines = $(this).val().split("\n").length;
linesUsed.text(newLines);
if(e.keyCode == 13 && newLines >= lines) {
linesUsed.css('color', 'red');
return false;
}
else {
linesUsed.css('color', '');
}
});
});
</code></pre>
<p>fiddle:
<a href="http://jsfiddle.net/XNCkH/17/">http://jsfiddle.net/XNCkH/17/</a></p> |
6,965,847 | Obtaining more than 20 results with Google Places API | <p>I want to develop a map application which will display the banks near a given place.</p>
<p>I use the Places library to search and everytime it just return 20 results. What should I do if I want more results?</p> | 6,969,897 | 7 | 0 | null | 2011-08-06 09:12:17.21 UTC | 12 | 2021-01-25 13:20:48.143 UTC | 2013-02-23 14:16:40.653 UTC | null | 1,565,279 | null | 782,574 | null | 1 | 41 | google-maps-api-3|google-places-api | 73,228 | <p><strong>UPDATE</strong>: Since I originally wrote this answer, the API was enhanced, making this answer out of date (or, at least, incomplete). See <a href="https://stackoverflow.com/questions/9614258/how-to-get-20-result-from-google-places-api">How to get 20+ result from Google Places API?</a> for more information.</p>
<p><strong>ORIGINAL ANSWER</strong>:</p>
<p>The <a href="http://code.google.com/apis/maps/documentation/places/#PlaceSearchResults" rel="noreferrer">documentation</a> says that the Places API returns up to 20 results. It does not indicate that there is any way to change that limit. So, the short answer seems to be: You can't.</p>
<p>Of course, you might be able to sort of fake it by doing queries for several locations, and then merging/de-duplicating the results. It's kind of a cheap hack, though, and might not work very well. And I'd check first to make sure it doesn't violate the terms of service.</p> |
6,782,660 | Incorrect lazy initialization | <p>Findbug told me that I use incorrect lazy initialization.</p>
<pre><code>public static Object getInstance() {
if (instance != null) {
return instance;
}
instance = new Object();
return instance;
}
</code></pre>
<p>I don't see anything wrong here. Is it wrong behaviour of findbug, or I missed something?</p> | 6,782,690 | 8 | 3 | null | 2011-07-21 20:54:31.293 UTC | 12 | 2017-08-25 15:06:44.773 UTC | null | null | null | null | 471,149 | null | 1 | 61 | java|findbugs | 38,759 | <p>Findbug is referencing a potential threading issue. In a multi thread environment, there would be potential for your singleton to be created more than once with your current code.</p>
<p>There is a lot of reading <a href="http://www.javaworld.com/jw-01-2001/jw-0112-singleton.html" rel="noreferrer">here</a>, but it will help explain.</p>
<p>The race condition here is on the <code>if check</code>. On the first call, a thread will get into the <code>if check</code>, and will create the instance and assign it to 'instance'. But there is potential for another thread to become active between the <code>if check</code> and the instance creation/assignment. This thread could also pass the <code>if check</code> because the assignment hasn't happened yet. Therefore, two (or more, if more threads got in) instances would be created, and your threads would have references to different objects.</p> |
6,416,065 | C# - Regex for file paths e.g. C:\test\test.exe | <p>I am currently looking for a regex that can help validate a file path e.g.:</p>
<pre><code>C:\test\test2\test.exe
</code></pre> | 6,416,209 | 10 | 5 | null | 2011-06-20 19:02:13.98 UTC | 8 | 2020-04-15 18:35:18.257 UTC | null | null | null | null | 807,051 | null | 1 | 27 | c#|.net|windows|regex | 70,534 | <p>I decided to post this answer which does use a regular expression.</p>
<pre><code>^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$
</code></pre>
<p>Works for these:</p>
<pre><code>\\test\test$\TEST.xls
\\server\share\folder\myfile.txt
\\server\share\myfile.txt
\\123.123.123.123\share\folder\myfile.txt
c:\folder\myfile.txt
c:\folder\myfileWithoutExtension
</code></pre>
<p>Edit: Added example usage:</p>
<pre><code>if (Regex.IsMatch (text, @"^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$"))
{
// Valid
}
</code></pre>
<p>*Edit: * This is an approximation of the paths you could see. If possible, it is probably better to use the Path class or FileInfo class to see if a file or folder exists.</p> |
6,389,600 | not-null property references a null or transient value | <p>Facing trouble in saving parent/child object with hibernate. Any idea would be highly appreciated.</p>
<pre><code>org.hibernate.PropertyValueException: not-null property references a null or transient value: example.forms.InvoiceItem.invoice
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:100)
.... (truncated)
</code></pre>
<p>hibernate mapping:</p>
<pre><code><hibernate-mapping package="example.forms">
<class name="Invoice" table="Invoices">
<id name="id" type="long">
<generator class="native" />
</id>
<property name="invDate" type="timestamp" />
<property name="customerId" type="int" />
<set cascade="all" inverse="true" lazy="true" name="items" order-by="id">
<key column="invoiceId" />
<one-to-many class="InvoiceItem" />
</set>
</class>
<class name="InvoiceItem" table="InvoiceItems">
<id column="id" name="itemId" type="long">
<generator class="native" />
</id>
<property name="productId" type="long" />
<property name="packname" type="string" />
<property name="quantity" type="int" />
<property name="price" type="double" />
<many-to-one class="example.forms.Invoice" column="invoiceId" name="invoice" not-null="true" />
</class>
</hibernate-mapping>
</code></pre>
<p>InvoiceManager.java</p>
<pre><code>class InvoiceManager {
public Long save(Invoice theInvoice) throws RemoteException {
Session session = HbmUtils.getSessionFactory().getCurrentSession();
Transaction tx = null;
Long id = null;
try {
tx = session.beginTransaction();
session.persist(theInvoice);
tx.commit();
id = theInvoice.getId();
} catch (RuntimeException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
throw new RemoteException("Invoice could not be saved");
} finally {
if (session.isOpen())
session.close();
}
return id;
}
}
</code></pre>
<p>Invoice.java</p>
<pre><code>public class Invoice implements java.io.Serializable {
private Long id;
private Date invDate;
private int customerId;
private Set<InvoiceItem> items;
public Long getId() {
return id;
}
public Date getInvDate() {
return invDate;
}
public int getCustomerId() {
return customerId;
}
public Set<InvoiceItem> getItems() {
return items;
}
void setId(Long id) {
this.id = id;
}
void setInvDate(Date invDate) {
this.invDate = invDate;
}
void setCustomerId(int customerId) {
this.customerId = customerId;
}
void setItems(Set<InvoiceItem> items) {
this.items = items;
}
}
</code></pre>
<p>InvoiceItem.java</p>
<pre><code>public class InvoiceItem implements java.io.Serializable {
private Long itemId;
private long productId;
private String packname;
private int quantity;
private double price;
private Invoice invoice;
public Long getItemId() {
return itemId;
}
public long getProductId() {
return productId;
}
public String getPackname() {
return packname;
}
public int getQuantity() {
return quantity;
}
public double getPrice() {
return price;
}
public Invoice getInvoice() {
return invoice;
}
void setItemId(Long itemId) {
this.itemId = itemId;
}
void setProductId(long productId) {
this.productId = productId;
}
void setPackname(String packname) {
this.packname = packname;
}
void setQuantity(int quantity) {
this.quantity = quantity;
}
void setPrice(double price) {
this.price = price;
}
void setInvoice(Invoice invoice) {
this.invoice = invoice;
}
}
</code></pre> | 6,389,676 | 12 | 0 | null | 2011-06-17 17:41:08.633 UTC | 24 | 2022-09-12 07:46:01.053 UTC | null | null | null | null | 248,258 | null | 1 | 110 | hibernate | 243,188 | <p>Every <code>InvoiceItem</code> must have an <code>Invoice</code> attached to it because of the <code>not-null="true"</code> in the <em>many-to-one</em> mapping. </p>
<p>So the basic idea is you need to set up that explicit relationship in code. There are many ways to do that. On your class I see a <code>setItems</code> method. I do NOT see an <code>addInvoiceItem</code> method. When you set items, you need to loop through the set and call <code>item.setInvoice(this)</code> on all of the items. If you implement an <code>addItem</code> method, you need to do the same thing. Or you need to otherwise set the Invoice of every <code>InvoiceItem</code> in the collection.</p> |
6,690,745 | Converting Integer to Long | <p>I need to get the value of a field using reflection. It so happens that I am not always sure what the datatype of the field is. For that, and to avoid some code duplication I have created the following method:</p>
<pre><code>@SuppressWarnings("unchecked")
private static <T> T getValueByReflection(VarInfo var, Class<?> classUnderTest, Object runtimeInstance) throws Throwable {
Field f = classUnderTest.getDeclaredField(processFieldName(var));
f.setAccessible(true);
T value = (T) f.get(runtimeInstance);
return value;
}
</code></pre>
<p>And use this method like: </p>
<pre><code>Long value1 = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
</code></pre>
<p>or</p>
<pre><code>Double[] value2 = getValueByReflection(inv.var2(), classUnderTest, runtimeInstance);
</code></pre>
<p>The problem is that I can't seem to cast <code>Integer</code> to <code>Long</code>:</p>
<pre><code>java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long
</code></pre>
<p>Is there a better way to achieve this?</p>
<p>I am using Java 1.6.</p> | 6,690,782 | 17 | 0 | null | 2011-07-14 08:57:05.077 UTC | 21 | 2022-08-02 11:28:43.123 UTC | null | null | null | null | 166,789 | null | 1 | 133 | java|reflection|casting | 452,930 | <p>No, you can't cast <code>Integer</code> to <code>Long</code>, even though you can convert from <code>int</code> to <code>long</code>. For an <em>individual</em> value which is known to be a number and you want to get the long value, you could use:</p>
<pre><code>Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp.longValue();
</code></pre>
<p>For arrays, it will be trickier...</p> |
38,476,486 | Understanding Spring Boot @Autowired | <p>I don't understand how spring boot's annotation <code>@Autowired</code> correctly works. Here is a simple example:</p>
<pre><code>@SpringBootApplication
public class App {
@Autowired
public Starter starter;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
public App() {
System.out.println("init App");
//starter.init();
}
}
</code></pre>
<p>--</p>
<pre><code>@Repository
public class Starter {
public Starter() {System.out.println("init Starter");}
public void init() { System.out.println("call init"); }
}
</code></pre>
<p>When I execute this code, I get the logs <code>init App</code> and <code>init Starter</code>, so spring creates this objects. But when I call the init method from <code>Starter</code> in <code>App</code>, I get a <code>NullPointerException</code>. Is there more I need to do other than using the annotation <code>@Autowired</code> to init my object?</p>
<pre><code>Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'app': Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [{package}.App$$EnhancerBySpringCGLIB$$87a7ccf]: Constructor threw exception; nested exception is java.lang.NullPointerException
</code></pre> | 38,476,580 | 1 | 1 | null | 2016-07-20 08:46:16.667 UTC | 4 | 2019-10-05 22:25:27.527 UTC | 2019-10-05 22:25:27.527 UTC | null | 1,246,547 | user4554100 | null | null | 1 | 13 | java|spring|spring-boot | 42,993 | <p>When you call the <code>init</code> method from the constructor of class <code>App</code>, Spring has not yet autowired the dependencies into the <code>App</code> object. If you want to call this method after Spring has finished creating and autowiring the <code>App</code> object, then add a method with a <code>@PostConstruct</code> annotation to do this, for example:</p>
<pre><code>@SpringBootApplication
public class App {
@Autowired
public Starter starter;
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
public App() {
System.out.println("constructor of App");
}
@PostConstruct
public void init() {
System.out.println("Calling starter.init");
starter.init();
}
}
</code></pre> |
15,760,856 | How to read a pandas Series from a CSV file | <p>I have a CSV file formatted as follows:</p>
<pre><code>somefeature,anotherfeature,f3,f4,f5,f6,f7,lastfeature
0,0,0,1,1,2,4,5
</code></pre>
<p>And I try to read it as a pandas Series (using pandas daily snapshot for Python 2.7).
I tried the following:</p>
<pre><code>import pandas as pd
types = pd.Series.from_csv('csvfile.txt', index_col=False, header=0)
</code></pre>
<p>and:</p>
<pre><code>types = pd.read_csv('csvfile.txt', index_col=False, header=0, squeeze=True)
</code></pre>
<p>But both just won't work: the first one gives a random result, and the second just imports a DataFrame without squeezing.</p>
<p>It seems like pandas can only recognize as a Series a CSV formatted as follows:</p>
<pre><code>f1, value
f2, value2
f3, value3
</code></pre>
<p>But when the features keys are in the first row instead of column, pandas does not want to squeeze it.</p>
<p>Is there something else I can try? Is this behaviour intended?</p> | 64,530,739 | 6 | 0 | null | 2013-04-02 09:41:11.077 UTC | 2 | 2021-12-16 12:51:46.383 UTC | null | null | null | null | 1,121,352 | null | 1 | 14 | csv|pandas|series | 69,712 | <p>This works. Squeeze still works, but it just won't work alone. The <code>index_col</code> needs to be set to zero as below</p>
<pre><code>series = pd.read_csv('csvfile.csv', header = None, index_col = 0, squeeze = True)
</code></pre> |
15,487,408 | Button's text vertical align | <p>I have got tricky problem here. I'd like to vertical align my text inside a button</p>
<pre><code><button id="rock" onClick="choose(1)">Rock</button>
</code></pre>
<p>And here is my CSS</p>
<pre><code>button {
font-size: 22px;
border: 2px solid #87231C;
border-radius: 100px;
width: 100px;
height: 100px;
color: #FF5A51;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
}
button:active {
font-size: 22px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}
</code></pre>
<p>You can check it out here <a href="http://jsfiddle.net/kA8pp/" rel="noreferrer">http://jsfiddle.net/kA8pp/</a> . I want to have the text on the bottom. <strong>Thank you very much!</strong></p>
<p><strong>EDIT:</strong> I can't explain it well so here is the picture of it :)</p>
<p><a href="https://i.stack.imgur.com/Ws6Ek.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Ws6Ek.png" alt="enter image description here"></a></p> | 15,487,515 | 5 | 1 | null | 2013-03-18 21:37:22.953 UTC | 1 | 2020-01-09 13:58:35.61 UTC | 2020-01-09 13:58:35.61 UTC | null | 4,684,797 | null | 2,177,932 | null | 1 | 23 | html|css | 103,587 | <p>Try <code>padding-top:65px;</code> in button class</p>
<pre><code>button {
font-size: 22px;
border: 2px solid #87231C;
border-radius: 100px;
width: 100px;
height: 100px;
color: #FF5A51;
text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
padding-top:65px;
}
</code></pre>
<p><a href="http://jsfiddle.net/kA8pp/4/" rel="noreferrer">JS Fiddle Demo</a></p> |
10,520,274 | Custom MKAnnotationView with frame,icon and image | <p>I've been searching for a similar solution on how to design a custom MKAnnotationView like this one.</p>
<p><img src="https://i.stack.imgur.com/MzJL4.jpg" alt="enter image description here"></p>
<p>I'v subclassed the MKAnnotation and i was able to add an image named F.png
the F.png is a frame image as showed in the picture.
what i want is to add an inner image. (colored Blue in the picture i draw)</p>
<pre><code>- (MKAnnotationView *)mapView:(MKMapView *)theMapView viewForAnnotation:(id <MKAnnotation>)annotation
{
if ([annotation isKindOfClass:[MKUserLocation class]])
return nil;
static NSString* AnnotationIdentifier = @"AnnotationIdentifier";
MKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationIdentifier];
if(annotationView)
return annotationView;
else
{
MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
annotationView.canShowCallout = YES;
annotationView.image = [UIImage imageNamed:[NSString stringWithFormat:@"F.png"]];
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self action:@selector(writeSomething:) forControlEvents:UIControlEventTouchUpInside];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
annotationView.rightCalloutAccessoryView = rightButton;
annotationView.canShowCallout = YES;
annotationView.draggable = NO;
return annotationView;
}
return nil;
}
</code></pre> | 10,526,298 | 2 | 3 | null | 2012-05-09 16:30:10.147 UTC | 10 | 2016-03-11 13:54:26.713 UTC | 2012-05-09 18:01:13.187 UTC | null | 857,865 | null | 857,865 | null | 1 | 13 | iphone|objective-c|ios|cocoa-touch|ios5 | 14,673 | <p>here in your code </p>
<pre><code>else
{
MKAnnotationView *annotationView = [[MKAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationIdentifier];
annotationView.canShowCallout = YES;
//change here
annotationView.image = [UIImage imageNamed:[NSString stringWithFormat:@"F.png"]];
UIImage *frame = [UIImage imageNamed:[NSString stringWithFormat:@"F.png"];
UIImage *image = theImageInFrameInner;
UIGraphicsBeginImageContext(CGSizeMake(pin.size.width, pin.size.height));
[frame drawInRect:CGRectMake(0, 0, frame.size.width, frame.size.height)];
[image drawInRect:CGRectMake(2, 2, 60, 60)]; // the frame your inner image
//maybe you should draw the left bottom icon here,
//then set back the new image, done
annotationView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
UIButton* rightButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
[rightButton addTarget:self action:@selector(writeSomething:) forControlEvents:UIControlEventTouchUpInside];
[rightButton setTitle:annotation.title forState:UIControlStateNormal];
annotationView.rightCalloutAccessoryView = rightButton;
annotationView.canShowCallout = YES;
annotationView.draggable = NO;
return annotationView;
}
</code></pre> |
13,406,790 | Filling a vector of pairs | <p>I want to fill a vector with 8 pairs. Each pair represents the moves in x and y coordinates a knight in a game of chess can make. At the moment I'm doing it like this</p>
<pre><code>vector<pair<int,int>> moves;
pair<int,int> aPair;
aPair.first = -2;
aPair.second = -1;
moves.push_back(aPair);
aPair.first = -2;
aPair.second = 1;
moves.push_back(aPair);
aPair.first = -1;
aPair.second = -2;
moves.push_back(aPair);
aPair.first = -1;
aPair.second = 2;
moves.push_back(aPair);
aPair.first = 1;
aPair.second = -2;
moves.push_back(aPair);
aPair.first = 1;
aPair.second = 2;
moves.push_back(aPair);
aPair.first = 2;
aPair.second = -1;
moves[6].push_back(aPair);
aPair.first = 2;
aPair.second = 1;
moves.push_back(aPair);
</code></pre>
<p>I'm doing this to learn about the Std library. This seems like a hopelessly inefficient way of solving this problem.</p>
<p>Anyone have a more elegant solution? </p> | 13,407,857 | 9 | 2 | null | 2012-11-15 21:46:12.98 UTC | 2 | 2020-08-13 21:23:51.507 UTC | 2018-05-03 12:15:52.817 UTC | null | 1,235,291 | null | 1,235,291 | null | 1 | 15 | c++|stl | 59,363 | <p>Loops to the rescue:</p>
<pre><code>for(int k = 0; k < 2; k++)
for(int i = -1; i < 2; i += 2)
for(int j = -1; j < 2; j+= 2)
result.push_back(make_pair(i * (k+1), j * (((k + 1) % 2) + 1)));
</code></pre>
<p>Output: <a href="http://ideone.com/2B0F9b" rel="noreferrer">http://ideone.com/2B0F9b</a></p> |
3,343,922 | Get column names | <p>I need to get all of the column names of a table using VBA or Access SQL and iterate through them for validation, does anyone have a solution to this, I have searched Google to no avail.</p> | 3,343,973 | 2 | 0 | null | 2010-07-27 13:09:53.247 UTC | 6 | 2017-06-19 17:35:38.507 UTC | 2015-09-24 23:25:41.84 UTC | null | 2,753,501 | null | 155,476 | null | 1 | 15 | sql|ms-access|vba | 51,466 | <p>This will work</p>
<pre><code>Set db = CurrentDb()
Set rs1 = db.OpenRecordset("Table1")
Dim fld As DAO.Field
For Each fld In rs1.Fields
MsgBox (fld.Name)
Next
Set fld = Nothing
</code></pre> |
3,924,654 | Datalog vs CLIPS vs Prolog | <p>As many programmers I studied Prolog in university, but only very little. I understand that Prolog and Datalog are closely related, but Datalog is simpler? Also, I believe that I read that Datalog does not depend on ordering of the logic clauses, but I am not sure why this is advantages. CLIPS is supposedly altogether different, but it is too subtle for me to understand. Can someone please to provide a general highlights of the languages over the other languages?</p> | 5,616,371 | 2 | 1 | null | 2010-10-13 14:18:02.073 UTC | 13 | 2011-04-11 02:58:16.043 UTC | null | null | null | null | 443,928 | null | 1 | 33 | prolog|logic-programming|clips|datalog | 15,128 | <p>datalog is a subset of prolog. the subset which datalog carries has two things in mind:</p>
<ol>
<li>adopt an API which would support rules and queries</li>
<li>make sure all queries terminate</li>
</ol>
<p>prolog is Turing complete. datalog is not.</p>
<p>getting datalog out of the way, let's see how prolog compares with clips.</p>
<p>prolog's expertise is "problem solving" while clips is an "expert system". if i understand correctly, "problem solving" involves expertise using code and data. "expert systems" mostly use data structures to express expertise. see <a href="http://en.wikipedia.org/wiki/Expert_system#Comparison_to_problem-solving_systems">http://en.wikipedia.org/wiki/Expert_system#Comparison_to_problem-solving_systems</a></p>
<p>another way to look at it is:</p>
<p>expert systems operate on the premise that most (if not all) outcomes are known. all of these outcomes are compiled into data and then is fed into an expert system. give the expert system a scenario, the expert system computes the outcome from the compiled data, aka knowledge base. it's always a "an even number plus an even number is always even" kind of thinking.</p>
<p>problem solving systems have an incomplete view of the problem. so one starts out with modeling data and behavior, which would comprise the knowledge base (this gives justice to the term "corner case") and ends up with "if we add two to six, we end up with eight. is eight divisible by two? then it is even"</p> |
9,364,563 | How to populate a ViewModel in ASP.NET MVC3 | <p>In my Controller I have a <code>ProductInfo</code> class from my <strong>Domain Model</strong> and I need some of its information to populate my <strong>View Model</strong> <code>ProductStatsVM</code>.</p>
<p>How do you populate the View Model? I heard three possible ways:</p>
<ol>
<li>Populate the View Model directly <strong>from the Controller</strong> (not good, I want to keep my Controller slim)</li>
<li>By using a <strong>View Model constructor</strong> and pass the domain model as parameter. (I have to create a constructor for each domain model class I want to use)</li>
<li>By using a <strong>Fill() method</strong>. (I saw it on the web, no idea how it works I guess this way the ViewModel should be aware of the Service Layer and creates coupling).</li>
</ol>
<p>I know there are tools like AutoMapper, which I am going to use indeed, but before I want to understand the logic on how to fill a View Model from the Controller without using any additional tool.</p> | 9,364,648 | 2 | 2 | null | 2012-02-20 16:26:04.88 UTC | 11 | 2012-02-20 16:37:33.877 UTC | null | null | null | null | 675,082 | null | 1 | 20 | c#|asp.net-mvc-3|viewmodel|fill | 6,675 | <p>The idea is that your controller action queries some repository to fetch a domain model. Then it passes this domain model to a mapping layer which is responsible to convert it to a view model and finally it passes the view model to the view:</p>
<pre><code>public ActionResult Index(int id)
{
ProductInfo product = repository.GetProductInfo(id);
ProductViewModel viewModel = Mapper.Map<ProductInfo, ProductViewModel>(product);
return View(viewModel);
}
</code></pre>
<p>and you could even make your controller slimmer by introducing a custom action filter that will automatically intercept the Model in the <code>OnActionExecuted</code> event and call into the mapping layer to substitute it with the corresponding view model so that your controller action now becomes:</p>
<pre><code>[AutoMapTo(typeof(ProductViewModel))]
public ActionResult Index(int id)
{
ProductInfo product = repository.GetProductInfo(id);
return View(product);
}
</code></pre>
<p>and of course now the view is strongly typed to ProductViewModel:</p>
<pre><code>@model ProductViewModel
...
</code></pre>
<p>Up to you to implement the <code>Mapper.Map<TSource, TDest></code> method. And if you don't want to implement it yourself you could download <a href="http://automapper.org/">AutoMapper</a> which already has this method for you.</p>
<p>The mapping layer is something that is part of the MVC application. It must be aware of both the domain models coming from your service layer and the view models defined in your MVC application in order to be able to perform the mapping.</p>
<p>Don't use constructors (other than the default parameterless one) in your view models. The default model binder will choke if the view model doesn't have a parameterless constructor in your POST actions and you will have to implement custom model binders.</p> |
9,326,438 | dnsmasq, serve different ip addresses based on interface used | <p>Basically my situation is that I'm running a VM for developing web sites.</p>
<p>The host machine has its dns pointing at the VM which, is running dnsmasq, which resolves the addresses of various dev sites; i.e. test.mysite.vm, etc.</p>
<p>The issue is, when I go from my work network to my home network, it all breaks because the IP of the VM changes. Is it possible to serve different IP addresses based on which interface the request came from? Or should I be trying to tackle this in a completely different way?</p>
<p>Thanks for your help!</p>
<hr>
<p><strong><em>Turns out there was a much easier approach to this after all...</em></strong></p>
<p>I now set up 2 interfaces on the VM, and don't need to use dnsmasq.</p>
<p>The first is just a bridged/shared interface which allows the VM to use whatever internet connection is available to the host, with a restart of the network each time I move office.</p>
<p>The 2nd is a private connection to my VM host, which has a static IP address. This is the interface I use to connect and bind any services such as nginx, mysql, etc.</p> | 13,296,605 | 4 | 2 | null | 2012-02-17 10:18:07.803 UTC | 13 | 2019-12-09 04:44:00.637 UTC | 2019-12-09 04:44:00.637 UTC | null | 2,066,657 | null | 962,355 | null | 1 | 28 | dns|virtual-machine|dnsmasq | 62,920 | <p>You can run two instances of <code>dnsmasq</code>, each with a different interface it listens on. You can use the <code>--interface=X</code> and <code>--bind-interfaces</code> options for that. By default, it also binds the loopback device <code>lo</code> and will fail if two processes try to bind it. Use <code>--except-interface=lo</code> to avoid that.</p>
<pre><code>dnsmasq --interface=eth0 --except-interface=lo --bind-interfaces --dhcp-range=192.168.0.2,192.168.0.10,12h
dnsmasq --interface=eth1 --except-interface=lo --bind-interfaces --dhcp-range=10.0.0.2,10.0.0.10,12h
</code></pre>
<p>Make sure your configuration file is empty when you test this as it always overrides the command line. You can also use <code>--conf-file=/dev/null</code>.</p>
<p>As I mentioned in the comment, I'm not too sure how this helps your situation, but it might help anyone else who tries to get two different address ranges on two different interfaces.</p> |
9,487,223 | What is the maximum number of characters that can be displayed in Android and iOS push notification? | <p>What is the maximum number of characters that can be displayed in push notification in Android without the text being truncated?</p>
<p>The documentation for iPhone states that the notification payload has to be under 256 bytes in total, but I was unable to find something similar for Android.</p> | 25,984,522 | 6 | 2 | null | 2012-02-28 17:58:39.533 UTC | 5 | 2018-05-12 21:52:35.817 UTC | 2017-05-09 16:47:27.763 UTC | null | 250,260 | null | 867,591 | null | 1 | 29 | android|ios|android-c2dm | 56,585 | <h3><strong>Android</strong></h3>
<p>The message size limit in <strong>Firebase Cloud Messaging (FCM)</strong> is 4 kbytes.
<a href="https://firebase.google.com/docs/cloud-messaging/concept-options#notification-messages-with-optional-data-payload" rel="noreferrer">https://firebase.google.com/docs/cloud-messaging/concept-options#notification-messages-with-optional-data-payload</a></p>
<p><strike><a href="https://firebase.google.com/docs/cloud-messaging/server#choose" rel="noreferrer">https://firebase.google.com/docs/cloud-messaging/server#choose</a></strike></p>
<p><strike>The message size limit in <strong>GCM</strong> is 4 kbytes. (DEPRECATED)
<a href="https://developer.android.com/google/gcm/server.html#params" rel="noreferrer">https://developer.android.com/google/gcm/server.html#params</a></strike></p>
<p><strike>The message size limit in <strong>C2DM</strong> is 1024 bytes. (DEPRECATED)
<a href="https://developers.google.com/android/c2dm/#limitations" rel="noreferrer">https://developers.google.com/android/c2dm/#limitations</a></strike></p>
<hr>
<h3><strong>iOS</strong></h3>
<p>For regular remote notifications, the <strong>maximum size is 4KB (4096 bytes)</strong></p>
<p><a href="https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html" rel="noreferrer">https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CreatingtheNotificationPayload.html</a></p>
<p><strike>Since the introduction of iOS 8 has changed to <strong>2 kbytes</strong>!</strike></p>
<p><a href="https://forums.aws.amazon.com/ann.jspa?annID=2626" rel="noreferrer">https://forums.aws.amazon.com/ann.jspa?annID=2626</a></p>
<blockquote>
<p>With <strong>iOS 8</strong>, Apple introduced new features that enable some rich new
use cases for mobile push notifications — interactive push
notifications, third party widgets, and larger (2 KB) payloads. Today,
we are pleased to announce support for the new mobile push
capabilities announced with iOS 8. We are publishing a new iOS 8
Sample App that demonstrates how these new features can be implemented
with SNS, and have also implemented support for larger 2KB payloads.</p>
</blockquote>
<p><strike>in iOS the size limit is 256 bytes</strike></p> |
9,324,772 | Cross compiling static C hello world for Android using arm-linux-gnueabi-gcc | <p>I want to build a static hello world from C using arm-linux-gnueabi-gcc as opposed to using the NDK standalone toolchain or Codesourcery for that matter.</p>
<p>In Ubuntu...</p>
<p>I have done the following:</p>
<pre><code>sudo apt-get install gcc-arm-linux-gnueabi
</code></pre>
<p>I created a hi.c like this:</p>
<pre><code>#include <stdio.h>
int main(int argc, char** argv) {
printf("hello world\n");
return 0;
}
</code></pre>
<p>I have compiled it like this:</p>
<pre><code>arm-linux-gnueabi-gcc -static hi.c -o hi
</code></pre>
<p>I ran it on an emulator like this:</p>
<pre><code>adb push hi /data/hi
adb shell /data/hi
</code></pre>
<p>But, I get this:</p>
<pre><code>[1] Illegal instruction /data/hi
</code></pre>
<p>What step have I forgot? Based on past experience this "should" have worked, but I obviously messed this up.</p> | 9,522,815 | 6 | 2 | null | 2012-02-17 08:02:30.19 UTC | 28 | 2019-11-22 15:24:32.503 UTC | null | null | null | null | 500,964 | null | 1 | 39 | android|c|android-ndk|arm|cross-compiling | 61,299 | <p>If I do this on a Debian machine (VM in my case), all seems well. I am not sure what when wrong with doing similar on ubuntu. It could be as Leo suggested, but I cannot confirm. This should work for you though.</p>
<p><a href="http://www.cnx-software.com/2012/01/16/installing-emdebian-arm-cross-toolchain-in-debian/" rel="nofollow">http://www.cnx-software.com/2012/01/16/installing-emdebian-arm-cross-toolchain-in-debian/</a></p>
<p>Someone added this link, but it is not using the toolchain I mentioned in the description. Leaving it in case anyone is interested.</p>
<p><a href="http://tariqzubairy.wordpress.com/2012/03/09/arm-binaries-static-library-for-android/" rel="nofollow">http://tariqzubairy.wordpress.com/2012/03/09/arm-binaries-static-library-for-android/</a></p> |
29,504,516 | Getting string input and displaying input with DOS interrupts MASM | <p>In MASM, I created a buffer variable to hold the user string input from keyboard. I am stuck on how to hold the string input into that buffer variable. I don't have any libraries linked like the irvine ones and want to do this with DOS interrupts. So far I have something along the lines of</p>
<pre><code> .model small
.stack 100h
.data
buff db 25 dup(0), 10, 13
lbuff EQU ($ - buff) ; bytes in a string
.code
main:
mov ax, @data
mov ds, ax
mov ah, 0Ah ; doesn't work
mov buff, ah ; doesn't seem right
int 21h
mov ax, 4000h ; display to screen
mov bx, 1
mov cx, lbuff
mov dx, OFFSET buff
int 21h
mov ah, 4ch
int 21h
end main
</code></pre>
<p>I assume using 0Ah is correct as it is for reading array of input of buffered characters.</p> | 29,517,960 | 4 | 4 | null | 2015-04-08 01:52:10.42 UTC | 2 | 2020-02-16 19:19:22.77 UTC | 2015-04-08 20:10:05.54 UTC | null | 4,160,439 | null | 4,160,439 | null | 1 | 4 | string|assembly|input|keyboard|masm | 55,109 | <p>I made some changes to your code. First, the "buff" variable needs the three level format (max number of characters allowed, another byte for the number of characteres entered, and the buffer itself) because that's what service 0AH requires. To use service 0AH I added "offset buff" (as Wolfgang said). Here it is:</p>
<pre><code> .model small
.stack 100h
.data
buff db 26 ;MAX NUMBER OF CHARACTERS ALLOWED (25).
db ? ;NUMBER OF CHARACTERS ENTERED BY USER.
db 26 dup(0) ;CHARACTERS ENTERED BY USER.
.code
main:
mov ax, @data
mov ds, ax
;CAPTURE STRING FROM KEYBOARD.
mov ah, 0Ah ;SERVICE TO CAPTURE STRING FROM KEYBOARD.
mov dx, offset buff
int 21h
;CHANGE CHR(13) BY '$'.
mov si, offset buff + 1 ;NUMBER OF CHARACTERS ENTERED.
mov cl, [ si ] ;MOVE LENGTH TO CL.
mov ch, 0 ;CLEAR CH TO USE CX.
inc cx ;TO REACH CHR(13).
add si, cx ;NOW SI POINTS TO CHR(13).
mov al, '$'
mov [ si ], al ;REPLACE CHR(13) BY '$'.
;DISPLAY STRING.
mov ah, 9 ;SERVICE TO DISPLAY STRING.
mov dx, offset buff + 2 ;MUST END WITH '$'.
int 21h
mov ah, 4ch
int 21h
end main
</code></pre>
<p>When 0AH captures the string from keyboard, it ends with ENTER (character 13), that's why, if you want to capture 25 characters, you must specify 26.</p>
<p>To know how many characters the user entered (length), access the second byte (offset buff + 1). The ENTER is not included, so, if user types 8 characters and ENTER, this second byte will contain the number 8, not 9.</p>
<p>The entered characters start at offset buff + 2, and they end when character 13 appears. We use this to add the length to buff+2 + 1 to replace chr(13) by '$'. Now we can display the string.</p> |
16,519,438 | Keeping zero count combinations when aggregating with data.table | <p>Suppose I've got the following <code>data.table</code> :</p>
<pre><code>dt <- data.table(id = c(rep(1, 5), rep(2, 4)),
sex = c(rep("H", 5), rep("F", 4)),
fruit = c("apple", "tomato", "apple", "apple", "orange", "apple", "apple", "tomato", "tomato"),
key = "id")
id sex fruit
1: 1 H apple
2: 1 H tomato
3: 1 H apple
4: 1 H apple
5: 1 H orange
6: 2 F apple
7: 2 F apple
8: 2 F tomato
9: 2 F tomato
</code></pre>
<p>Each row represents the fact that someone (identified by it's <code>id</code> and <code>sex</code>) ate a <code>fruit</code>. I want to count the number of times each <code>fruit</code> has been eaten by <code>sex</code>. I can do it with :</p>
<pre><code>dt[ , .N, by = c("fruit", "sex")]
</code></pre>
<p>Which gives:</p>
<pre><code> fruit sex N
1: apple H 3
2: tomato H 1
3: orange H 1
4: apple F 2
5: tomato F 2
</code></pre>
<p>The problem is, by doing it this way I'm losing the count of <code>orange</code> for <code>sex == "F"</code>, because this count is 0. Is there a way to do this aggregation without loosing combinations of zero counts?</p>
<p>To be perfectly clear, the desired result would be the following:</p>
<pre><code> fruit sex N
1: apple H 3
2: tomato H 1
3: orange H 1
4: apple F 2
5: tomato F 2
6: orange F 0
</code></pre>
<p>Thanks a lot !</p> | 16,547,425 | 2 | 0 | null | 2013-05-13 10:05:10.877 UTC | 10 | 2018-08-15 06:51:36.09 UTC | 2017-07-29 18:15:29.73 UTC | null | 1,851,712 | null | 249,691 | null | 1 | 17 | r|data.table | 3,094 | <p>Seems like the most straightforward approach is to explicitly supply all category combos in a data.table passed to <code>i=</code>, setting <code>by=.EACHI</code> to iterate over them: </p>
<pre><code>setkey(dt, sex, fruit)
dt[CJ(sex, fruit, unique = TRUE), .N, by = .EACHI]
# sex fruit N
# 1: F apple 2
# 2: F orange 0
# 3: F tomato 2
# 4: H apple 3
# 5: H orange 1
# 6: H tomato 1
</code></pre> |
16,572,286 | git pull gives error: 401 Authorization Required while accessing https://git.foo.com/bar.git | <p>My macbook pro is able to clone/push/pull from the company git server.
My cent 6.3 vm gets a 401 error </p>
<pre><code>git clone https://git.acme.com/git/torque-setup
"error: The requested URL returned error: 401 Authorization Required while accessing https://git.acme.com/git/torque-setup/info/refs
</code></pre>
<p>As a work around, I've tried creating a folder, with an empty repository, then setting the remote to the company server. I get the same error when trying a git pull</p>
<p>The remotes are identical between the machines</p>
<p><em><strong>MacBook Pro</em></strong> (working)</p>
<pre><code>git --version
git version 1.7.10.2 (Apple Git-33)
git remote -v
origin https://git.acme.com/git/torque-setup (fetch)
origin https://git.acme.com/git/torque-setup (push)
</code></pre>
<p><em><strong>Cent 6.3</em></strong> (not working)</p>
<pre><code>yum install -y git
git --version
git version 1.7.1
git remote -v
origin https://git.acme.com/git/torque-setup (fetch)
origin https://git.acme.com/git/torque-setup (push)
</code></pre>
<p><br>
The git server only allows https. Not git or ssh connections. </p>
<p>Why is the macbook pro able to do a git pull, while the cent os machine can't? </p>
<p><br>
<strong><em>Solution Update 2013-5-15</em></strong></p>
<p>As jku mentioned, the culprit is the old version of git installed on the cent box. Unfortunately, 1.7.1 is what you get when you run <code>yum install git</code></p>
<p>The work around is to manually install a newer version of git, or simply add the username to the repo</p>
<pre><code>git clone https://[email protected]/git/torque-setup
</code></pre> | 16,572,958 | 2 | 1 | null | 2013-05-15 18:19:36.53 UTC | 3 | 2016-06-27 11:48:51.07 UTC | 2013-06-25 16:19:08.793 UTC | null | 1,626,687 | null | 1,626,687 | null | 1 | 22 | git | 45,628 | <p>I would update the git version: 1.7.10 (or thereabouts) had authentication improvements. It's possible that these improvements were only related to proxies though -- I've forgotten the details already.</p>
<p>Speaking of proxies, you could double-check git config: You wouldn't have proxies or anything like that configured on the macbook but not on the cent machine?</p> |
17,410,399 | Finding k-largest elements of a very large file (while k is very LARGE) | <p>Let's assume that we have a very large file which contains billions of integers , and we want to find <code>k</code> largest elements of these values , </p>
<p>the tricky part is that <code>k</code> itself is very large too , which means we cannot keep <code>k</code> elements in the memory (for example we have a file with 100 billon elements and we want to find 10 billion largest elements)</p>
<p>How can we do this in <code>O(n)</code> ?</p>
<p>What I thought : </p>
<p>We start reading the file and we check it with another file which keeps the <code>k</code> largest elements (sorted in increasing order) , if the read element is larger than the first line of the second file we delete the first line and we insert it into the second file , the time complexity would be of <code>O(NlogK)</code> (if we have random access to that file , otherwise it would be 'O(Nk)'</p>
<p>Any idea to do this in <code>O(n)</code> , I guess if we have external version of <code>Selection algorithm</code> (the partitioning algorithm in quicksort) we would be able to do this in <code>O(n)</code> but I couldn't find it anywhere</p> | 17,411,709 | 6 | 4 | null | 2013-07-01 17:37:58.2 UTC | 13 | 2021-06-28 22:59:21.587 UTC | 2013-07-01 18:13:02.63 UTC | null | 2,020,229 | null | 1,664,315 | null | 1 | 12 | algorithm|large-files | 13,234 | <p>PS: My definition of K is different. It is a smallish number say 2 or 100 or 1000. Here m corresponds to OPS's definition of k. Sorry about this.</p>
<p>Depends on how many reads you can do of the original data and how much more space you have. This approach assumes you have extra space equivalent to the original data.</p>
<p>Step 1: Pick K random numbers across the whole data<br>
Step 2: Sort the K numbers (assume index are from 1 to K)<br>
Step 3: Create K+1 separate files and name them 0 to K<br>
Step 4: For every element in the data, if it is between ith and i+th element put it in ith file.<br>
Step 5: Based on the size of each file, choose the file that is going to have mth number.<br>
Step 6: Repeat everything with the new file and new m (new_m = m - sum_of_size_of_all_lower_files) </p>
<p>Regarding the last step, if K=2, m=1000 and size of file 0 is 800, 1 is 900 and 2 is 200, new_m = m-800 = 200 and work through file 1 iteratively.</p> |
11,513,312 | How to initialize an array of integers? | <p>I have:</p>
<pre><code>integer test[7:0];
</code></pre>
<p>but I cannot do:</p>
<pre><code>test[0] = 0;
</code></pre>
<p>or </p>
<pre><code>assign test[0] = 0;
</code></pre>
<p>or</p>
<pre><code>intial
begin
test[0]=0;
end
</code></pre>
<p>or</p>
<pre><code>integer test[7:0] = {0,0,0,0,0,0,0,0,0};
</code></pre>
<p>Any ideas? Just using 0 as an example, I need it to be 26, 40, 32, 18, 50, 0, 20, 12</p> | 11,513,945 | 1 | 0 | null | 2012-07-16 22:09:33.157 UTC | 1 | 2012-07-17 15:47:18.687 UTC | 2012-07-17 15:47:18.687 UTC | user597225 | null | null | 1,154,026 | null | 1 | 3 | verilog | 39,736 | <p>Are you sure <code>initial</code> doesn't work (you might have a typo in there...)?</p>
<pre><code>initial begin
for(int i=0; i<8; i++) begin
test[i] = i;
end
$display(test[4]);
end
</code></pre>
<p>In systemverilog, something like the following will work. These are known as "Assignment Patterns":</p>
<pre><code>integer test[7:0] = '{26, 40, 32, 18, 50, 0, 20, 12}; // note the '
</code></pre>
<p>I doubt either of the above are synthesisable, except maybe when targeting an FPGA.</p> |
37,430,217 | Has many through many-to-many | <p>I have the following table layout:</p>
<pre><code>deals:
- id
- price
products:
- id
- name
deal_product:
- id
- deal_id
- product_id
metrics:
- id
- name
metric_product:
- id
- metric_id
- product_id
- value
</code></pre>
<p><code>products</code> and <code>metrics</code> have a many-to-many relationship with a pivot column of value.</p>
<p><code>deals</code> and <code>products</code> also have a many-to-many relationship.</p>
<p>I can get metrics for a product with <code>$product->metrics</code>, but I want to be able to get all metrics for all products related to a deal, so I could do something like this: <code>$deal->metrics</code>.</p>
<p>I currently have the following in my <code>Deal</code> model:</p>
<pre><code>public function metrics()
{
$products = $this->products()->pluck('products.id')->all();
return Metric::whereHas('products', function (Builder $query) use ($products) {
$query->whereIn('products.id', $products);
});
}
</code></pre>
<p>But this doesn't return a relationship, so I cannot eager load it or get related models from it.</p>
<p>It needs to be in relationship format, because they need to be eager loaded for my use case.</p>
<p>Thanks for your help!</p> | 37,720,428 | 7 | 2 | null | 2016-05-25 07:14:31.537 UTC | 9 | 2019-12-13 16:59:51.933 UTC | 2016-05-25 09:17:21.323 UTC | null | 2,012,476 | null | 2,012,476 | null | 1 | 28 | laravel|laravel-5|laravel-5.2 | 20,715 | <p>If you want to have a custom relation, you can create your own extends to Relation abstract class. For example: <code>BelongsToManyThought</code>.</p>
<p>But if you don't want to implement a Relation, I think that it can fulfill your needs : </p>
<p>In App\Deal.php, you can combine the solution of @thomas-van-der-veen</p>
<pre class="lang-php prettyprint-override"><code>public function metrics()
{
return Metric
::join('metric_product', 'metric.id', '=', 'metric_product.metric_id')
->join('products', 'metric_product.product_id', '=', 'products.id')
->join('deal_product', 'products.id', '=', 'deal_product.product_id')
->join('deals', 'deal_product.deal_id', '=', 'deal.id')
->where('deal.id', $this->id);
}
// you can access to $deal->metrics and use eager loading
public function getMetricsAttribute()
{
if (!$this->relationLoaded('products') || !$this->products->first()->relationLoaded('metrics')) {
$this->load('products.metrics');
}
return collect($this->products->lists('metrics'))->collapse()->unique();
}
</code></pre>
<p>You can refer to this <a href="https://softonsofa.com/laravel-querying-any-level-far-relations-with-simple-trick/" rel="noreferrer">post</a> to see how you can simply use nested relations.</p>
<p>This solution can do the trick for querying relation with method and access to metrics attribute.</p> |
37,323,379 | Expression "IS NOT NULL" not working on HQL | <p>When I do a select statement for non-null values on a hive table, there are no correct results in the response. The result is as if "is not null" expression is not there!</p>
<p><strong>Example</strong>:</p>
<pre><code>select count(*)
from test_table
where test_col_id1='12345' and test_col_id2 is not null;
</code></pre>
<p>Note <code>test_col_id1</code> and <code>test_col_id2</code> are not partition keys.</p>
<p>Here's my hive version.</p>
<blockquote>
<p>Hive 0.14.0.2.2.0.0-2041</p>
</blockquote>
<p>Here's the table:</p>
<p>... | test_col_id1 | test_col_id2 | <br/>
... | 12345 | x | <br/>
... | 12345 | NULL | <br/></p>
<p>This query returns 2 records.</p> | 37,402,664 | 2 | 3 | null | 2016-05-19 12:34:18.103 UTC | 3 | 2017-08-25 16:01:27.807 UTC | 2016-05-23 09:37:41.263 UTC | null | 2,477,612 | null | 2,477,612 | null | 1 | 9 | null|hive|hql | 56,177 | <p>Try the following query, does it return rows?</p>
<pre><code>select count(*)
from test_table
where test_col_id1='12345' and test_col_id2 != 'NULL';
</code></pre>
<p>Then your <code>NULL</code> is not <code>NULL</code>, it's the string 'NULL'. Loads of people have problems with Hive treatment of <code>NULL</code> strings. By default, it's the blank string <code>''</code>. If we want anything else, we have to specify exactly the way NULL strings should be treated when we create the table. Here are 3 examples of how to change what is recognized as <code>NULL</code>. The first one sets 'NULL' strings as <code>NULL</code>:</p>
<pre><code>CREATE TABLE nulltest1 (id STRING, another_string STRING)
TBLPROPERTIES('serialization.null.format'='NULL') --sets the string 'NULL' as NULL;
CREATE TABLE nulltest2 (id STRING, another_string STRING)
TBLPROPERTIES('serialization.null.format'='') --sets empty string as NULL;
CREATE TABLE nulltest3 (id STRING, another_string STRING)
TBLPROPERTIES('serialization.null.format'='\N'); --sets \N as NULL;
</code></pre>
<p>Since you've already created your table, you can alter your table so that it will recognize your <code>'NULL'</code> as <code>NULL</code>:</p>
<pre><code>ALTER TABLE test_table SET TBLPROPERTIES ('serialization.null.format' = 'NULL');
</code></pre> |
21,854,426 | Get "Internal error in the expression evaluator" on "Add watch" function when trying to debug WCF service code (MSVS 2013) | <p>Few days ago I moved my solution to MSVS 2013. It works fine except one thing: when I trying to debug code of my WCF service it works, but when I want to watch state of any variable it says: "Internal error in the expression evaluator". Add watch function works normal on client side, but in service code it broken. I'm trying to debug my own WCF service running on the localhost. Could you help me, how to repair this?</p>
<p><img src="https://i.stack.imgur.com/WBdQg.png" alt="enter image description here"></p>
<p>Here MSVS info:
Microsoft Visual Studio Professional 2013
Version 12.0.30110.00 Update 1
Microsoft .NET Framework
Version 4.5.51641
OS: Windows 8.1</p> | 22,596,776 | 4 | 4 | null | 2014-02-18 12:51:11.23 UTC | 27 | 2020-02-24 01:53:34.963 UTC | 2014-07-09 22:53:13.323 UTC | null | 41,956 | null | 692,665 | null | 1 | 114 | c#|visual-studio-2013|visual-studio-debugging | 34,160 | <p>This might be a bug in the new (managed) debug engine that ships with Visual Studio 2013. Try turning on <strong>Managed Compatibility Mode</strong> (which effectively turns it into pre-2013 debug engine), located under <strong>Tools - Options - Debugging</strong>:</p>
<p><img src="https://i.stack.imgur.com/NSRnl.png" alt=""></p>
<p>If this solves the issue, then I'd suggest trying to reproduce it with a small project, and then reporting it on <a href="https://connect.microsoft.com/VisualStudio/" rel="nofollow noreferrer">Connect</a>, so it could be fixed.</p>
<p><strong>@bjhuffine</strong> comments below that there are other ways to enable compatibility mode, without globally disabling it (e.g. per-project). More information here: <a href="https://devblogs.microsoft.com/devops/switching-to-managed-compatibility-mode-in-visual-studio-2013/" rel="nofollow noreferrer">https://devblogs.microsoft.com/devops/switching-to-managed-compatibility-mode-in-visual-studio-2013/</a></p> |
19,356,278 | I'm getting "found character that cannot start any token while scanning for the next token" | <p>I have been running Ruby on Rails on my laptop for about a month now, but when I wanted to run the server in this instance (and it was working fine a few hours ago) I now receive this message. How can I get the server to run again please? </p>
<pre><code>C:\Sites\LaunchPage>rails s
C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/psych.rb:203:in `parse': (<unknown>):
found character that cannot start any token while scanning for the next token at line 17 column 17 (Psych::SyntaxError)
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/psych.rb:203:in `parse_stream'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/psych.rb:151:in `parse'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/1.9.1/psych.rb:127:in `load'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/figaro-0.6.3/lib/figaro.rb:21:in `raw'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/figaro-0.6.3/lib/figaro.rb:17:in `env'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/figaro-0.6.3/lib/figaro/railtie.rb:7:in `block in <class:Railtie>'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:34:in `call'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:34:in `execute_hook'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:43:in `block in run_load_hooks'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:42:in `each'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/activesupport-3.2.8/lib/active_support/lazy_load_hooks.rb:42:in `run_load_hooks'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/application.rb:67:in `inherited'
from C:/Sites/LaunchPage/config/application.rb:13:in `<module:LaunchPage>'
from C:/Sites/LaunchPage/config/application.rb:12:in `<top (required)>'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:53:in `require'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:53:in `block in <top (required)>'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:50:in `tap'
from C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/railties-3.2.8/lib/rails/commands.rb:50:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'
</code></pre> | 19,357,178 | 7 | 6 | null | 2013-10-14 08:33:29.837 UTC | 5 | 2018-10-23 10:53:36.983 UTC | 2017-07-10 18:15:59.857 UTC | null | 792,066 | null | 2,738,175 | null | 1 | 44 | ruby-on-rails|ruby|ruby-on-rails-3 | 72,108 | <p>This error is originating from the <a href="https://github.com/laserlemon/figaro" rel="noreferrer">Figaro gem</a>, which would indicate to me that you probably have a syntax error in <code>config/application.yml</code>. Double check this file for any incorrect YAML syntax.</p> |
19,650,917 | How to convert BigDecimal to Double in Java? | <p>How we convert <code>BigDecimal</code> into <code>Double</code> in java? I have a requirement where we have to use Double as argument but we are getting <code>BigDecimal</code> so i have to convert <code>BigDecimal</code> into <code>Double</code>.</p> | 19,650,938 | 3 | 7 | null | 2013-10-29 06:07:40.517 UTC | 23 | 2014-08-01 16:33:21.563 UTC | null | null | null | null | 476,828 | null | 1 | 155 | java | 291,883 | <p>You need to use the <a href="http://docs.oracle.com/javase/7/docs/api/java/math/BigDecimal.html#doubleValue%28%29"><code>doubleValue()</code></a> method to get the double value from a BigDecimal object.</p>
<pre><code>BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want
</code></pre> |
44,868,369 | How to immediately invoke a C++ lambda? | <p>A constructor from a class I'm inheriting requires a non-trivial object to be passed in. Similar to this:</p>
<pre><code>MyFoo::MyFoo() : SomeBase( complexstuff )
{
return;
}
</code></pre>
<p>The <code>complexstuff</code> has little to do with <code>MyFoo</code>, so I didn't want to have to pass it in.</p>
<p>Instead of writing some kind of 1-off temporary function that returns <code>complexstuff</code> I used a lambda. What took me a few minutes to figure out is I have to <em>invoke</em> the lambda. So my code now looks like this:</p>
<pre><code>MyFoo::MyFoo() : SomeBase(
[]()
{
/* blah blah do stuff with complexstuff */
return complexstuff;
} () )
{
return;
}
</code></pre>
<p>If you didn't catch it, it is subtle. But after the lambda body, I had to put <code>()</code> to tell the compiler to immediately "run" the lambda. Which made sense after I figured out what I had done wrong. Otherwise, without the <code>()</code> to invoke the lambda, gcc says something similar to this:</p>
<pre><code>error: no matching function for call to 'SomeBase(<lambda()>)'
</code></pre>
<p>But now that has me thinking -- did I do this correctly? Is there a better way in C++11 or C++14 to tell the compiler that I want it to immediately invoke a lambda I've written? Or is appending an empty <code>()</code> like I did the usual way to do this?</p> | 44,868,417 | 4 | 6 | null | 2017-07-02 07:19:49.713 UTC | 4 | 2021-04-08 19:05:32.79 UTC | 2017-07-02 07:29:51.777 UTC | null | 3,980,929 | null | 13,022 | null | 1 | 29 | c++|c++11|lambda|c++14 | 16,513 | <blockquote>
<p>But now that has me thinking -- did I do this correctly?</p>
</blockquote>
<p>Yes you did.</p>
<blockquote>
<p>Is there a better way in C++11 or C++14 to tell the compiler that I want it to immediately invoke a lambda I've written? </p>
</blockquote>
<p>Not that I know of. A lambda is also just a function object, so you <em>need</em> to have a <code>()</code> to call it, there is no way around it (except of course some function that invokes the lambda like <code>std::invoke</code>).</p>
<p>If you want you can drop the <code>()</code> after the capture list, because your lambda doesn't take any parameters. </p>
<blockquote>
<p>Or is appending an empty <code>()</code> like I did the usual way to do this?</p>
</blockquote>
<p>Yes, it is the shortest way. As said before, <code>std::invoke</code> would also work instead, but it requires more typing. I would say a direct call with <code>()</code> is the usual way it is done.</p> |
17,438,253 | Accessing struct fields inside a map value (without copying) | <p>Assuming the following</p>
<pre><code>type User struct {
name string
}
users := make(map[int]User)
users[5] = User{"Steve"}
</code></pre>
<p>Why isn't it possible to access the struct instance now stored in the map?</p>
<pre><code>users[5].name = "Mark"
</code></pre>
<p>Can anyone shed some light into how to access the map-stored struct, or the logic behind why it's not possible?</p>
<h2>Notes</h2>
<p>I know that you can achieve this by making a copy of the struct, changing the copy, and copying back into the map -- but that's a costly copy operation.</p>
<p>I also know this can be done by storing struct pointers in my map, but I don't want to do that either.</p> | 17,443,950 | 2 | 2 | null | 2013-07-03 01:12:52.38 UTC | 14 | 2020-08-24 14:31:12.187 UTC | 2020-02-26 08:16:29.523 UTC | null | 8,208,215 | null | 1,415,721 | null | 1 | 47 | go | 8,794 | <p>The fundamental problem is that you can't take the address of an item within a map. You might think the compiler would re-arrange <code>users[5].name = "Mark"</code> into this</p>
<pre><code>(&users[5]).name = "Mark"
</code></pre>
<p>But that doesn't compile, giving this error</p>
<pre><code>cannot take the address of users[5]
</code></pre>
<p>This gives the maps the freedom to re-order things at will to use memory efficiently.</p>
<p>The only way to change something explicitly in a map is to assign value to it, i.e.</p>
<pre><code>t := users[5]
t.name = "Mark"
users[5] = t
</code></pre>
<p>So I think you either have to live with the copy above or live with storing pointers in your map. Storing pointers have the disadvantage of using more memory and more memory allocations, which may outweigh the copying way above - only you and your application can tell that.</p>
<p>A third alternative is to use a slice - your original syntax works perfectly if you change <code>users := make(map[int]User)</code> to <code>users := make([]User, 10)</code></p> |
17,665,809 | Remove key from dictionary in Python returning new dictionary | <p>I have a dictionary</p>
<pre><code>d = {'a':1, 'b':2, 'c':3}
</code></pre>
<p>I need to remove a key, say <strong>c</strong> and return the dictionary without that key in one function call</p>
<pre><code>{'a':1, 'b':2}
</code></pre>
<p>d.pop('c') will return the key value - 3 - instead of the dictionary.</p>
<p><em>I am going to need one function solution if it exists, as this will go into comprehensions</em></p> | 17,665,928 | 6 | 4 | null | 2013-07-15 23:50:00.43 UTC | 7 | 2021-10-28 03:06:12.783 UTC | 2013-07-16 00:08:07.43 UTC | null | 599,202 | null | 599,202 | null | 1 | 69 | python|methods|dictionary | 51,655 | <p>How about this:</p>
<pre><code>{i:d[i] for i in d if i!='c'}
</code></pre>
<p>It's called <a href="https://www.python.org/dev/peps/pep-0274/" rel="noreferrer">Dictionary Comprehensions</a> and it's available since Python 2.7.</p>
<p>or if you are using Python older than 2.7:</p>
<pre><code>dict((i,d[i]) for i in d if i!='c')
</code></pre> |
30,750,271 | Disable ip v6 in docker container | <p>I have ipv6 enabled on docker host but there is one particular container where ipv6 is causing issues. Is there a way to launch a container without ipv6 support, either through command line argument or dockerfile directive?</p> | 30,773,513 | 7 | 3 | null | 2015-06-10 07:49:46.177 UTC | 3 | 2022-07-26 16:31:17.11 UTC | null | null | null | null | 4,636,126 | null | 1 | 18 | docker|ipv6 | 73,725 | <p>Unfortunately there isn't: <code>--ipv6</code> is a daemon-wide flag that cannot be overridden on a per-container basis.</p> |
18,759,095 | Is Hibernate using pessimistic or optimistic locking? | <p>All my classes have an </p>
<p>@Version</p>
<p>annotation, so I assumed they were using optimistic locking.</p>
<p>But I the following exception in my logs that seem to indicate Im using pessimistic locking. So which is it ? (I want to use optimistic locking) </p>
<pre><code>update Song set acoustidFingerprint=?, acoustidId=?, album=?, albumArtist=?, albumArtistSort=?, albumSort=?, amazonId=?, arranger=?, artist=?, artistSort=?, artists=?, barcode=?, bpm=?, catalogNo=?, comment=?, composer=?, composerSort=?, conductor=?, country=?, custom1=?, custom2=?, custom3=?, custom4=?, custom5=?, discNo=?, discSubtitle=?, discTotal=?, djmixer=?, duration=?, encoder=?, engineer=?, fbpm=?, filename=?, genre=?, grouping=?, isCompilation=?, isrc=?, keyOfSong=?, language=?, lastModified=?, lyricist=?, lyrics=?, media=?, mixer=?, mood=?, musicbrainzArtistId=?, musicbrainzDiscId=?, musicbrainzOriginalReleaseId=?, musicbrainzRecordingId=?, musicbrainzReleaseArtistId=?, musicbrainzReleaseCountry=?, musicbrainzReleaseGroupId=?, musicbrainzReleaseId=?, musicbrainzReleaseStatus=?, musicbrainzReleaseType=?, musicbrainzWorkId=?, musicipId=?, occasion=?, originalAlbum=?, originalArtist=?, originalLyricist=?, originalYear=?, producer=?, quality=?, rating=?, recordLabel=?, releaseYear=?, remixer=?, script=?, subtitle=?, tags=?, tempo=?, title=?, titleSort=?, track=?, trackTotal=?, urlDiscogsArtistSite=?, urlDiscogsReleaseSite=?, urlLyricsSite=?, urlOfficialArtistSite=?, urlOfficialReleaseSite=?, urlWikipediaArtistSite=?, urlWikipediaReleaseSite=?, version=? where recNo=? and version=? [50200-172]
**org.hibernate.PessimisticLockException: Timeout trying to lock table ; SQL statement:**
update Song set acoustidFingerprint=?, acoustidId=?, album=?, albumArtist=?, albumArtistSort=?, albumSort=?, amazonId=?, arranger=?, artist=?, artistSort=?, artists=?, barcode=?, bpm=?, catalogNo=?, comment=?, composer=?, composerSort=?, conductor=?, country=?, custom1=?, custom2=?, custom3=?, custom4=?, custom5=?, discNo=?, discSubtitle=?, discTotal=?, djmixer=?, duration=?, encoder=?, engineer=?, fbpm=?, filename=?, genre=?, grouping=?, isCompilation=?, isrc=?, keyOfSong=?, language=?, lastModified=?, lyricist=?, lyrics=?, media=?, mixer=?, mood=?, musicbrainzArtistId=?, musicbrainzDiscId=?, musicbrainzOriginalReleaseId=?, musicbrainzRecordingId=?, musicbrainzReleaseArtistId=?, musicbrainzReleaseCountry=?, musicbrainzReleaseGroupId=?, musicbrainzReleaseId=?, musicbrainzReleaseStatus=?, musicbrainzReleaseType=?, musicbrainzWorkId=?, musicipId=?, occasion=?, originalAlbum=?, originalArtist=?, originalLyricist=?, originalYear=?, producer=?, quality=?, rating=?, recordLabel=?, releaseYear=?, remixer=?, script=?, subtitle=?, tags=?, tempo=?, title=?, titleSort=?, track=?, trackTotal=?, urlDiscogsArtistSite=?, urlDiscogsReleaseSite=?, urlLyricsSite=?, urlOfficialArtistSite=?, urlOfficialReleaseSite=?, urlWikipediaArtistSite=?, urlWikipediaReleaseSite=?, version=? where recNo=? and version=? [50200-172]
at org.hibernate.dialect.H2Dialect$2.convert(H2Dialect.java:317)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy22.executeUpdate(Unknown Source)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3123)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3021)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3350)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:140)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:362)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:354)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:276)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
at org.hibernate.event.internal.DefaultAutoFlushEventListener.onAutoFlush(DefaultAutoFlushEventListener.java:62)
at org.hibernate.internal.SessionImpl.autoFlushIfRequired(SessionImpl.java:1182)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1611)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:374)
at com.jthink.songkong.db.SongCache.loadSongsFromDatabase(SongCache.java:58)
at com.jthink.songkong.analyse.analyser.SongGroup.getSongs(SongGroup.java:48)
at com.jthink.songkong.analyse.analyser.MergeMusicBrainzMatches.matchToMissingTracks(MergeMusicBrainzMatches.java:318)
at com.jthink.songkong.analyse.analyser.MergeMusicBrainzMatches.call(MergeMusicBrainzMatches.java:105)
at com.jthink.songkong.analyse.analyser.MergeMusicBrainzMatches.call(MergeMusicBrainzMatches.java:40)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:722)
Caused by: org.h2.jdbc.JdbcSQLException: Timeout trying to lock table ; SQL statement:
update Song set acoustidFingerprint=?, acoustidId=?, album=?, albumArtist=?, albumArtistSort=?, albumSort=?, amazonId=?, arranger=?, artist=?, artistSort=?, artists=?, barcode=?, bpm=?, catalogNo=?, comment=?, composer=?, composerSort=?, conductor=?, country=?, custom1=?, custom2=?, custom3=?, custom4=?, custom5=?, discNo=?, discSubtitle=?, discTotal=?, djmixer=?, duration=?, encoder=?, engineer=?, fbpm=?, filename=?, genre=?, grouping=?, isCompilation=?, isrc=?, keyOfSong=?, language=?, lastModified=?, lyricist=?, lyrics=?, media=?, mixer=?, mood=?, musicbrainzArtistId=?, musicbrainzDiscId=?, musicbrainzOriginalReleaseId=?, musicbrainzRecordingId=?, musicbrainzReleaseArtistId=?, musicbrainzReleaseCountry=?, musicbrainzReleaseGroupId=?, musicbrainzReleaseId=?, musicbrainzReleaseStatus=?, musicbrainzReleaseType=?, musicbrainzWorkId=?, musicipId=?, occasion=?, originalAlbum=?, originalArtist=?, originalLyricist=?, originalYear=?, producer=?, quality=?, rating=?, recordLabel=?, releaseYear=?, remixer=?, script=?, subtitle=?, tags=?, tempo=?, title=?, titleSort=?, track=?, trackTotal=?, urlDiscogsArtistSite=?, urlDiscogsReleaseSite=?, urlLyricsSite=?, urlOfficialArtistSite=?, urlOfficialReleaseSite=?, urlWikipediaArtistSite=?, urlWikipediaReleaseSite=?, version=? where recNo=? and version=? [50200-172]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:329)
at org.h2.message.DbException.get(DbException.java:158)
at org.h2.command.Command.filterConcurrentUpdate(Command.java:281)
at org.h2.command.Command.executeUpdate(Command.java:237)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdateInternal(JdbcPreparedStatement.java:154)
at org.h2.jdbc.JdbcPreparedStatement.executeUpdate(JdbcPreparedStatement.java:140)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:105)
at sun.reflect.GeneratedMethodAccessor55.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 24 more
</code></pre> | 38,205,983 | 3 | 0 | null | 2013-09-12 08:22:42.18 UTC | 8 | 2021-06-27 07:24:25.323 UTC | 2017-11-29 07:57:52.677 UTC | null | 1,025,118 | null | 1,480,018 | null | 1 | 13 | java|database|hibernate|transactions|locking | 38,902 | <p>You are using optimistic locking, as your <code>UPDATE</code> statement already indicates:</p>
<pre><code>where recNo=? and version=?
</code></pre>
<p>The presence of the <code>version</code> column is what optimistic locking is all about.</p>
<p>You were misled by the <code>PessimisticLockException</code> which might be caused by an explicit or an implicit row-level lock.</p> |
18,669,756 | BASH - How to extract data from a column in CSV file and put it in an array? | <p>I am learning to script in Bash.</p>
<p>I have a CSV file with 5 columns and 22 rows. I am interested in taking the data from the second column and put it into an array. </p>
<p>What I want is that the first name be in <code>array[0]</code>, the second in <code>array[1]</code> and so on.</p>
<p>Bash script:</p>
<pre><code>#!/bin/sh
IFS=","
eCollection=( $(cut -d ',' -f2 MyAssignment.csv ) )
printf "%s\n" "${eCollection[0]}"
</code></pre>
<p>The CSV looks like this. There is no line with headers.</p>
<p>The column with the <code>Vl18xx</code> numbers is what I want to split into an array. </p>
<pre><code>John,Vl1805,VRFname,10.9.48.64/28,10.9.48.78
John,Vl1806,VRFname,10.9.48.80/28,10.9.48.94
John,Vl1807,VRFname,10.9.48.96/28,10.9.48.110
John,Vl1808,VRFname,10.9.48.112/28,10.9.48.126
John,Vl1809,VRFname,167.107.152.32/28,167.107.152.46
</code></pre>
<p>The bash script is not placing the 2nd column into the array, what am I doing wrong?</p> | 18,669,878 | 4 | 1 | null | 2013-09-07 04:38:09.277 UTC | 7 | 2021-02-09 03:13:40.403 UTC | 2013-09-14 03:55:49.37 UTC | null | 445,131 | null | 2,756,247 | null | 1 | 8 | arrays|bash|csv | 57,690 | <p>Remove the <code>IFS=","</code> assignment thereby letting the default IFS value of space, tab, newline apply</p>
<pre><code>#!/bin/bash
eCollection=( $(cut -d ',' -f2 MyAssignment.csv ) )
printf "%s\n" "${eCollection[0]}"
</code></pre>
<p>Explained: The <code>eCollection</code> variable is an array due to the outer parenthesis. It is initialized with each element from the IFS-separated (think function or command line arguments) words which come from the <code>$(cut -d ',' -f2 MyAssignment.csv)</code> subshell, which is the <code>cut</code> command used with the <code>','</code> delimiter and printing the second field <code>-f2</code> from the <code>MyAssignment.csv</code> file.</p>
<p>The <code>printf</code> statement just shows how to print any item by index, you could also try <code>echo "${eCollection[@}]}"</code> to see all of the elements.</p> |
5,313,495 | How can I get a reference to an HttpResponse in ASP.NET MVC? | <p>I'm calling a third-party library that takes a <code>System.Web.HttpResponse</code>. I see I have a <code>HttpResponseBase</code>, but not <code>HttpResponse</code> like in web forms.</p>
<p>Is there a way to get the <code>HttpResponse</code>? Using <code>MVC 3</code>.</p>
<p><strong>[Edit]</strong> :
I'm trying to do this in a controller method. Also corrected casing.</p> | 5,315,335 | 3 | 2 | null | 2011-03-15 14:49:43.59 UTC | 6 | 2016-01-06 08:27:42.33 UTC | 2015-05-02 06:43:41.123 UTC | null | 2,024,469 | null | 128,208 | null | 1 | 28 | asp.net|asp.net-mvc|asp.net-mvc-3|asp.net-mvc-2|asp.net-mvc-4 | 31,892 | <p>If you need to interact with systems which take the non-mockable types, you can get access to the current HttpContext via the static property <strong>System.Web.HttpContext.Current</strong>. The HttpResponse is just hanging off of there via the Response property.</p> |
5,062,916 | Replace Div with another Div | <p>I have this thing I m trying to do. I have a main picture of a map and within that map there are regions. These regions have hot spots on them so you can click them and it will replace the whole map with only the region. (just a simple <code>div</code> swap). </p>
<p>I need it as a <code>div</code> because in this <code>div</code> i have the hot spots listed. </p>
<p>There are a total of 4 <code>div</code>s that I am going to need to do this with. </p>
<p>If anyone could help me that would be awesome!</p>
<p>So links that are listed in a table need to replace the image in a separate <code>div</code>. </p>
<pre><code><tr class="thumb"></tr>
<td>All Regions (shows main map) (link)</td>
</tr>
<tr class="thumb"></tr>
<td>Northern Region (link)</td>
</tr>
<tr class="thumb"></tr>
<td>Southern Region (link)</td>
</tr>
<tr class="thumb"></tr>
<td>Eastern Region (link)</td>
</tr>
</table>
<div>All Regions image</div>
<div>northern image</div>
<div>southern image</div>
<div>Eastern image</div>
</code></pre>
<p>I am not allowed to post images because I don't have enough points so I know the image links wont work.</p> | 5,062,952 | 3 | 7 | null | 2011-02-21 06:15:42.957 UTC | 6 | 2017-04-06 12:54:57.35 UTC | 2011-02-21 06:52:44.217 UTC | null | 447,023 | null | 625,985 | null | 1 | 40 | jquery|html|swap | 134,151 | <p>You can use <a href="http://api.jquery.com/replaceWith/" rel="noreferrer"><strong><code>.replaceWith()</code></strong></a></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() {
$(".region").click(function(e) {
e.preventDefault();
var content = $(this).html();
$('#map').replaceWith('<div class="region">' + content + '</div>');
});
});</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="map">
<div class="region"><a href="link1">region1</a></div>
<div class="region"><a href="link2">region2</a></div>
<div class="region"><a href="link3">region3</a></div>
</div></code></pre>
</div>
</div>
</p> |
4,917,030 | Move cursor x lines from current position in vi/vim | <p>Is there a way to move the cursor a relative amount of lines in vi/vim? Say you have the cursor 10 lines under a block of code you want to remove. If you have the line numbers shown in relative order, it would be nice to have a "jump 10 lines up command" that would take you there.</p>
<p>Or perhaps it's better to have the absolute line numbers shown and go xgg where x is the line number?</p> | 4,917,042 | 3 | 1 | null | 2011-02-06 23:49:32.18 UTC | 11 | 2018-06-20 09:49:53.647 UTC | 2015-01-06 16:45:43.077 UTC | null | 445,131 | Flawe | null | null | 1 | 93 | vim|vi | 56,796 | <p>Yep, of course there's a way. <code>j</code> and <code>k</code> move down and up one line, so <code>10j</code> and <code>10k</code> move down and up ten lines. You can repeat any motion by putting a number before it.</p>
<p>You might also want to <code>set relativenumber</code> if this is something you do a lot of - it'll help save you counting by printing line numbers relative to the current line, instead of absolute numbers.</p> |
25,759,885 | UIActionSheet from Popover with iOS8 GM | <p>Anyone is getting this message while trying to show UIActionSheet from popover?</p>
<p><strong>Your application has presented a UIAlertController () of style UIAlertControllerStyleActionSheet. The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. You must provide location information for this popover through the alert controller's popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem. If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.</strong></p>
<p>Previously to the GM I used some workaround for converting the UIActionSheet to UIAlertController and this is working fine.
However it seems that Apple tried to solve the UIActionSheet issues and I didn't want to use my workaround - but it seems that I have no choice...</p> | 27,440,957 | 6 | 2 | null | 2014-09-10 07:42:26.053 UTC | 4 | 2019-01-04 10:33:39.977 UTC | null | null | null | null | 1,619,554 | null | 1 | 47 | ios|ios8|uipopovercontroller|uiactionsheet|uialertcontroller | 23,431 | <p>To support iPad, include this code:</p>
<pre><code>alertView.popoverPresentationController?.sourceView = self.view
alertView.popoverPresentationController?.sourceRect = self.view.bounds
// this is the center of the screen currently but it can be any point in the view
self.presentViewController(alertView, animated: true, completion: nil)
</code></pre> |
18,647,214 | How can I increment a variable without exceeding a maximum value? | <p>I am working on a simple video game program for school and I have created a method where the player gets 15 health points if that method is called. I have to keep the health at a max of 100 and with my limited programming ability at this point I am doing something like this.</p>
<pre><code>public void getHealed(){
if(health <= 85)
health += 15;
else if(health == 86)
health += 14;
else if(health == 87)
health += 13;
}// this would continue so that I would never go over 100
</code></pre>
<p>I understand my syntax about isn't perfect but my question is, what may be a better way to do it, because I also have to do a similar thing with the damage points and not go below 0.</p>
<p>This is called <a href="https://en.wikipedia.org/wiki/Saturation_arithmetic" rel="nofollow noreferrer">saturation arithmetic</a>.</p> | 18,647,232 | 14 | 1 | null | 2013-09-05 22:53:09.937 UTC | 15 | 2019-06-10 14:16:29.953 UTC | 2019-06-10 14:16:29.953 UTC | null | 995,714 | user2053184 | null | null | 1 | 89 | java|if-statement|switch-statement|saturation-arithmetic | 21,208 | <p>I would just do this. It basically takes the minimum between 100 (the max health) and what the health would be with 15 extra points. It ensures that the user's health does not exceed 100.</p>
<pre><code>public void getHealed() {
health = Math.min(health + 15, 100);
}
</code></pre>
<p>To ensure that hitpoints do not drop below zero, you can use a similar function: <code>Math.max</code>.</p>
<pre><code>public void takeDamage(int damage) {
if(damage > 0) {
health = Math.max(health - damage, 0);
}
}
</code></pre> |
19,914,915 | How to make protractor press the enter key? | <p>I've tried this:</p>
<pre><code>browser.actions().keyDown(protractor.Key.ENTER).keyUp(protractor.Key.Enter).perform();
</code></pre>
<p>which gives the error:</p>
<pre><code>Error: Not a modifier key
</code></pre> | 19,919,105 | 6 | 3 | null | 2013-11-11 20:06:02.943 UTC | 4 | 2020-04-23 03:53:33.42 UTC | 2017-09-20 06:04:45.407 UTC | null | 1,927,695 | null | 592,844 | null | 1 | 59 | javascript|angularjs|protractor | 80,158 | <p>Keyup/Keydown is limited to modifier keys in WebDriver (shift, ctrl, etc). I think you want</p>
<p><code>browser.actions().sendKeys(protractor.Key.ENTER).perform();</code></p> |
15,194,718 | how to Merge two xml files with XSLT | <p>I have two xml files which need to be merged into one by using XSLT. </p>
<p>First XML is (the original one): </p>
<pre><code><feed>
<author>
<firstName>f</firstName>
<lastName>l</lastName>
</author>
<date>2011-01-02 </date>
<entry>
<id>1</id>
<Name>aaa</Name>
<Content>XXX</Content>
</entry>
<entry>
<id>2</id>
<Name>bbb</Name>
<Content>YYY</Content>
</entry>
</feed>
</code></pre>
<p>Second XML(updated data) is like this:</p>
<pre><code> <feed>
<author>
<firstName>f</firstName>
<lastName>l</lastName>
</author>
<date>2012-05-02 </date>
<entry>
<id>2</id>
<Name>newName</Name>
<Content>newContent</Content>
</entry>
<entry>
<id>3</id>
<Name>ccc</Name>
<Content>ZZZ</Content>
</entry>
</feed>
</code></pre>
<p>The desired merged result - using the second XML to update the first one :</p>
<pre><code> <feed>
<author>
<firstName>f</firstName>
<lastName>l</lastName>
</author>
<date>2012-05-02 </date>
<entry>
<id>1</id>
<Name>aaa</Name>
<Content>XXX</Content>
</entry>
<entry>
<id>2</id>
<Name>newName</Name>
<Content>newContent</Content>
</entry>
<entry>
<id>3</id>
<Name>ccc</Name>
<Content>ZZZ</Content>
</entry>
</feed>
</code></pre>
<p>I have searched stackoverflow but still could not find the answer. Thanks for help.</p> | 15,196,470 | 1 | 5 | null | 2013-03-04 04:46:36.797 UTC | 9 | 2013-03-04 10:01:26.003 UTC | 2013-03-04 09:42:58.733 UTC | null | 1,562,238 | null | 1,562,238 | null | 1 | 9 | xml|xslt | 44,767 | <p>Pretty much the same answer as I provided to your last question, modified to match your new XML format:</p>
<pre><code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:param name="fileName" select="'updates.xml'" />
<xsl:param name="updates" select="document($fileName)" />
<xsl:variable name="updateItems" select="$updates/feed/entry" />
<xsl:template match="@* | node()">
<xsl:copy>
<xsl:apply-templates select="@* | node()"/>
</xsl:copy>
</xsl:template>
<xsl:template match="feed">
<xsl:copy>
<xsl:apply-templates select="@* | node()[not(self::entry)] |
entry[not(id = $updateItems/id)]" />
<xsl:apply-templates select="$updateItems" />
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
</code></pre>
<p>When run on the first sample XML, with the second one saved as "updates.xml", this produces:</p>
<pre><code><feed>
<author>
<firstName>f</firstName>
<lastName>l</lastName>
</author>
<date>2011-01-02 </date>
<entry>
<id>1</id>
<Name>aaa</Name>
<Content>XXX</Content>
</entry>
<entry>
<id>2</id>
<Name>newName</Name>
<Content>newContent</Content>
</entry>
<entry>
<id>3</id>
<Name>ccc</Name>
<Content>ZZZ</Content>
</entry>
</feed>
</code></pre> |
15,219,873 | force download using ZF2 | <p>I am trying to do force download using ZF2. Here is the snippet to my code </p>
<pre><code> use Zend\Http\Request;
.....
public function downloadAction() {
$response = new Request();
$response->setHeaders(Request::fromString("Content-Type: application/octet-stream\r\nContent-Length: 9\r\nContent-Disposition: attachment; filename=\"ultimate_remedy_readme.txt\""));
}
</code></pre>
<p>now i am getting this error </p>
<pre><code>/var/www/whowantsmymoney/vendor/zendframework/zendframework/library/Zend/Http/Request.php:88
</code></pre>
<p>Message:</p>
<pre><code>A valid request line was not found in the provided string
</code></pre>
<p>Stack trace:</p>
<pre><code>#0 /var/www/whowantsmymoney/module/Admin/src/Admin/Controller/LanguageController.php(93): Zend\Http\Request::fromString('Content-Type: a...')
</code></pre> | 15,229,031 | 2 | 2 | null | 2013-03-05 09:14:42.073 UTC | 10 | 2015-05-23 07:05:12.387 UTC | null | null | null | null | 1,045,808 | null | 1 | 17 | zend-framework2|force-download | 12,455 | <p>This code should help you for a simple file download.</p>
<pre class="lang-php prettyprint-override"><code>public function downloadAction() {
$fileName = 'somefile';
if(!is_file($fileName)) {
//do something
}
$fileContents = file_get_contents($fileName);
$response = $this->getResponse();
$response->setContent($fileContents);
$headers = $response->getHeaders();
$headers->clearHeaders()
->addHeaderLine('Content-Type', 'whatever your content type is')
->addHeaderLine('Content-Disposition', 'attachment; filename="' . $fileName . '"')
->addHeaderLine('Content-Length', strlen($fileContents));
return $this->response;
}
</code></pre>
<p>I imagine this code leaves a lot to be desired, but should work in simple cases, as was mine. I'm not sure how you might handle reading the file in chunks. Maybe somebody else could shed some light?</p>
<p><strong>Edit - Sending streams</strong></p>
<p>I've added this here for informational purposes. It is probably the better way to force downloads as it will use much less memory.</p>
<pre class="lang-php prettyprint-override"><code>public function downloadAction() {
$fileName = 'somefile';
$response = new \Zend\Http\Response\Stream();
$response->setStream(fopen($fileName, 'r'));
$response->setStatusCode(200);
$headers = new \Zend\Http\Headers();
$headers->addHeaderLine('Content-Type', 'whatever your content type is')
->addHeaderLine('Content-Disposition', 'attachment; filename="' . $fileName . '"')
->addHeaderLine('Content-Length', filesize($fileName));
$response->setHeaders($headers);
return $response;
</code></pre> |
15,365,471 | Initializing Half-edge data structure from vertices | <p>I'm working on implementing various subdivision algorithms (such as catmull-clark); to do this efficiently requires a good way to store information about a grid of tesselated polygons. I implemented the half-edge data structure as <a href="http://www.flipcode.com/archives/The_Half-Edge_Data_Structure.shtml" rel="noreferrer">outlined by flipcode</a>, but now I'm not sure how to populate the data structure from vertices!</p>
<p>My initial attempt was to</p>
<ul>
<li>create vertices</li>
<li>group vertices into faces</li>
<li>sort vertices within faces (using their angle relative to the centroid)</li>
<li>for each face, grab the first vertex and then walk through the sorted vertex list to create a half-edge list.</li>
</ul>
<p>However, this creates a list of faces (with half-edges) that don't have any information about adjacent faces! This also feels a bit wrong, because it seems as if the faces are really the first-class object and the edges provide auxiliary information; I really feel like I should be creating edges from the vertices and then sorting out the faces from there. But again, I'm not really sure how to go about it that way -- I can't think of a way to create a list of half-edges without creating the faces first.</p>
<p>Any suggestions for what the best way to go turning data about vertices (and faces) into half-edges?</p> | 15,366,479 | 1 | 0 | null | 2013-03-12 15:35:12.557 UTC | 10 | 2021-02-20 22:06:46.617 UTC | 2021-02-20 22:06:46.617 UTC | null | 2,838,606 | null | 1,226,676 | null | 1 | 26 | algorithm|c++11|data-structures|polygon|computational-geometry | 20,449 | <p>First, I'd like to point you to an excellent C++ implementation of the half-edge data structure: <a href="http://www.openmesh.org/" rel="noreferrer">OpenMesh</a>. If you want to use it, make sure you work you way through the tutorial. If (and only if) you do that, working with OpenMesh is quite straightforward. It also contains some nice methods on top of which you can implement subdivision or reduction algorithms.</p>
<p>Now to your question:</p>
<blockquote>
<p>However, this creates a list of faces (with half-edges) that don't have any information about adjacent faces! This also feels a bit wrong, because it seems as if the faces are really the first-class object and the edges provide auxiliary information</p>
</blockquote>
<p>I think this somewhat misses the point of the half-edge data structure. In a half-edge structure, it is the half-edges that carry the most information!</p>
<p>Quoting shamelessly from the <a href="http://openmesh.org/Documentation/OpenMesh-Doc-Latest/mesh_hds.html" rel="noreferrer">OpenMesh documentation</a> (see also the figure there):</p>
<ul>
<li>Each vertex references one outgoing halfedge, i.e. a halfedge that starts at this vertex.</li>
<li>Each face references one of the halfedges bounding it.</li>
<li>Each halfedge provides a handle to
<ul>
<li>the vertex it points to ,</li>
<li>the face it belongs to </li>
<li>the next halfedge inside the face (ordered counter-clockwise) ,</li>
<li>the opposite halfedge ,</li>
<li>(optionally: the previous halfedge in the face ).</li>
</ul></li>
</ul>
<p>As you see, <strong>most information is stored in the half-edges</strong> - these are the primary objects. Iterating over meshes in this data-structure is all about cleverly following pointers.</p>
<blockquote>
<p>However, this creates a list of faces (with half-edges) that don't have any information about adjacent faces!</p>
</blockquote>
<p>This is perfectly ok! As you see above, a face references <strong>only</strong> one bounding half edge. Assuming a triangle mesh, the chain of pointers you follow to get the 3 adjacent triangles to a given face <code>F</code> is the following:</p>
<p><code>F -> halfEdge -> oppositeHalfEdge -> face</code></p>
<p><code>F -> halfEdge -> nextHalfEdge -> oppositeHalfEdge -> face</code></p>
<p><code>F -> halfEdge -> previousHalfEdge -> oppositeHalfEdge -> face</code></p>
<p>Optionally, you can use <code>nextHalfEdge -> nextHalfEdge</code> if you don't use the 'previous' pointers. This, of course, generalizes easily to quads or higher order polygons.</p>
<p>If you set the pointers listed above correctly when building your mesh, then you can iterate over all kinds of adjacencies in your mesh like this. If you use OpenMesh, you can use a bunch of special iterators that to the pointer chasing for you.</p>
<p>Setting the "opposite half edge" pointers is of course the tricky part when building a half-edge structure from a "triangle soup". I suggest to use a map data-structure of some kind to keep track of half-edges already created.</p>
<p>To be more specific, here is some <strong>very conceptual pseudo-code</strong> for creating a half-edge mesh from faces. I omitted the vertex part, which is simpler, and can be implemented in the same spirit. I assume that iteration over a face edges is ordered (e.g. clock-wise).</p>
<p>I assume half edges are implemented as structs of type <code>HalfEdge</code>, which contain the pointers listed above as members. </p>
<pre><code> struct HalfEdge
{
HalfEdge * oppositeHalfEdge;
HalfEdge * nextHalfEdge;
Vertex * vertex;
Face * face;
}
</code></pre>
<p>Let <code>Edges</code> be a map from pairs of vertex identifiers to pointers to the actual half-edge instances, e.g.</p>
<pre><code>map< pair<unsigned int, unsigned int>, HalfEdge* > Edges;
</code></pre>
<p>in C++. Here is the construction pseudo-code (without the vertex and face part):</p>
<pre><code>map< pair<unsigned int, unsigned int>, HalfEdge* > Edges;
for each face F
{
for each edge (u,v) of F
{
Edges[ pair(u,v) ] = new HalfEdge();
Edges[ pair(u,v) ]->face = F;
}
for each edge (u,v) of F
{
set Edges[ pair(u,v) ]->nextHalfEdge to next half-edge in F
if ( Edges.find( pair(v,u) ) != Edges.end() )
{
Edges[ pair(u,v) ]->oppositeHalfEdge = Edges[ pair(v,u) ];
Edges[ pair(v,u) ]->oppositeHalfEdge = Edges[ pair(u,v) ];
}
}
}
</code></pre>
<p><strong>EDIT:</strong> Made the code a bit less pseudo, to be more clear about the <code>Edges</code> map and the pointers.</p> |
15,003,095 | Getting value of selected item in list box as string | <p>I am trying to get the value of the selected item in the listbox using the code below, but it is always returning null string.</p>
<pre><code>DataSet ds = searchforPrice(Convert.ToString(listBox1.SelectedItem));
</code></pre>
<p>Here I am trying to pass the value of selected item as string to method searchforPrice to retrive dataset from the database.</p>
<p>How can i retrive the value of selected item as string?</p>
<p>I am adding items to listbox from combo box which in turn loads the items from the database.</p>
<pre><code> listBox1.Items.Add(comboBox2.Text);
</code></pre>
<p><img src="https://i.stack.imgur.com/bPNrK.png" alt="enter image description here"></p>
<p>Anybody has answer for this..</p> | 15,003,160 | 11 | 1 | null | 2013-02-21 13:10:40.027 UTC | 7 | 2022-06-07 09:48:57.743 UTC | 2013-02-22 05:18:11.09 UTC | null | 1,722,381 | null | 1,722,381 | null | 1 | 32 | c#|winforms|listbox | 289,251 | <p>If you want to retrieve the display text of the item, use the <a href="http://msdn.microsoft.com/fr-fr/library/system.windows.forms.listcontrol.getitemtext.aspx"><code>GetItemText</code></a> method:</p>
<pre><code>string text = listBox1.GetItemText(listBox1.SelectedItem);
</code></pre> |
15,422,203 | How to disable/override the enter key for autocomplete? | <p>In Sublime Text 3, I want to disable the <kbd>enter</kbd> key to select an item from the autocomplete drop down, and only allow the <kbd>tab</kbd> key to do so.</p>
<p>I found this section in the inbuilt <code>Default (OSX).sublime-keymap</code> file:</p>
<pre><code>{ "keys": ["enter"], "command": "commit_completion", "context":
[
{ "key": "auto_complete_visible" },
{ "key": "setting.auto_complete_commit_on_tab", "operand": false }
]
},
</code></pre>
<p>It seems that if I remove this from the config that <kbd>enter</kbd> will not select an item in the drop down. Unfortunately it is not recommended to change this file, and only to override it in my <code>User</code> files. I don't think I actually can edit it without modifying the <code>.app</code> contents.</p>
<p>I tried to override it by removing different sections, and also remove everything except <code>"keys": ["enter"]</code>, but nothing seems to work.</p>
<p>How would I go about achieving this without modifying the inbuilt <code>Default (OSX).sublime-keymap</code> and only the <code>User/Default (OSX).sublime-keymap</code> file?</p> | 15,923,958 | 2 | 0 | null | 2013-03-14 23:37:13.07 UTC | 8 | 2021-10-15 00:41:10.003 UTC | 2017-09-08 18:29:17.617 UTC | null | 7,954,504 | null | 11,125 | null | 1 | 48 | autocomplete|sublimetext3|keyboard-shortcuts|sublimetext | 17,289 | <p><strong>I have never used Sublime Text 3,</strong> but I don't think the following has changed since Sublime Text 2.</p>
<p>What you want to achieve is actually a standard feature in Sublime Text. You just have to turn it on.</p>
<p>This line from your the code you quoted …</p>
<pre><code>{ "key": "setting.auto_complete_commit_on_tab", "operand": false }
</code></pre>
<p>… means "only execute the command if the setting called 'auto_complete_commit_on_tab' is set to false". So simply turn on that setting.</p>
<p>In Default/Preferences.sublime-settings:</p>
<pre><code>// By default, auto complete will commit the current completion on enter.
// This setting can be used to make it complete on tab instead.
// Completing on tab is generally a superior option, as it removes
// ambiguity between committing the completion and inserting a newline.
"auto_complete_commit_on_tab": false,
</code></pre>
<p>Put <code>"auto_complete_commit_on_tab": true</code> in User/Preferences.sublime-settings. Both mentioned files can be accessed via the Preferences menu.</p> |
15,125,628 | Putting mathematical symbols and subscripts mixed with regular letters | <p>I want to plot a label that looks like this in <code>ggplot2</code>:</p>
<p><code>Value is $\sigma$, R^{2} = 0.6</code> where <code>Value is</code> is ordinary font, <code>$\sigma$</code> is a Greek lowercase sigma letter and <code>R^{2} = 0.6</code> appears as an <code>R</code> with a superscript <code>2</code> followed by equal sign (<code>=</code>) followed by <code>0.6</code>. How can this be used in ggplot <code>factor</code>s and in arguments to things like <code>xlab,ylab</code> of R?</p> | 15,125,755 | 2 | 0 | null | 2013-02-28 01:04:52.157 UTC | 26 | 2020-11-04 17:50:11.407 UTC | 2019-02-04 21:34:28.32 UTC | null | 680,068 | user248237 | null | null | 1 | 64 | r|ggplot2|mathematical-typesetting | 89,020 | <p>Something like this :</p>
<pre><code>g <- ggplot(data=data.frame(x=0,y=0))+geom_point(aes(x=x,y=y))
g+ xlab( expression(paste("Value is ", sigma,",", R^{2},'=0.6')))
</code></pre>
<p><strong>EDIT</strong></p>
<p>Another option is to use <code>annotate</code> with <code>parse=T</code>:</p>
<pre><code>g+ annotate('text', x = 0, y = 0,
label = "Value~is~sigma~R^{2}==0.6 ",parse = TRUE,size=20)
</code></pre>
<p><img src="https://i.stack.imgur.com/HPbJo.png" alt="enter image description here"></p>
<p><strong>EDIT</strong></p>
<p>The <code>paste</code> solution may be useful if the constant 0.6 is computed during plotting. </p>
<pre><code>r2.value <- 0.90
g+ xlab( expression(paste("Value is ", sigma,",", R^{2},'=',r2.value)))
</code></pre> |
15,301,999 | Default arguments with *args and **kwargs | <p>In <strong>Python 2.x</strong> (I use 2.7), which is the proper way to use default arguments with <code>*args</code> and <code>**kwargs</code>?<br>
I've found a question on SO related to this topic, but that is for <strong>Python 3</strong>:<br>
<a href="https://stackoverflow.com/questions/9872824/calling-a-python-function-with-args-kwargs-and-optional-default-arguments">Calling a Python function with *args,**kwargs and optional / default arguments</a></p>
<p>There, they say this method works:</p>
<pre><code>def func(arg1, arg2, *args, opt_arg='def_val', **kwargs):
#...
</code></pre>
<p>In 2.7, it results in a <code>SyntaxError</code>. Is there any recommended way to define such a function?<br>
I got it working this way, but I'd guess there is a nicer solution.</p>
<pre><code>def func(arg1, arg2, *args, **kwargs):
opt_arg ='def_val'
if kwargs.__contains__('opt_arg'):
opt_arg = kwargs['opt_arg']
#...
</code></pre> | 15,302,042 | 7 | 2 | null | 2013-03-08 19:43:12.83 UTC | 31 | 2022-08-10 19:22:35.587 UTC | 2018-05-01 23:07:12.793 UTC | null | 6,862,601 | user1563285 | null | null | 1 | 97 | python|python-2.7 | 80,701 | <p>Just put the default arguments before the <code>*args</code>:</p>
<pre><code>def foo(a, b=3, *args, **kwargs):
</code></pre>
<p>Now, <code>b</code> will be explicitly set if you pass it as a keyword argument or the second positional argument.</p>
<p>Examples:</p>
<pre><code>foo(x) # a=x, b=3, args=(), kwargs={}
foo(x, y) # a=x, b=y, args=(), kwargs={}
foo(x, b=y) # a=x, b=y, args=(), kwargs={}
foo(x, y, z, k) # a=x, b=y, args=(z, k), kwargs={}
foo(x, c=y, d=k) # a=x, b=3, args=(), kwargs={'c': y, 'd': k}
foo(x, c=y, b=z, d=k) # a=x, b=z, args=(), kwargs={'c': y, 'd': k}
</code></pre>
<p>Note that, in particular, <code>foo(x, y, b=z)</code> doesn't work because <code>b</code> is assigned by position in that case.</p>
<hr />
<p>This code works in Python 3 too. Putting the default arg <em>after</em> <code>*args</code> in Python 3 makes it a "keyword-only" argument that can <em>only</em> be specified by name, not by position. If you want a keyword-only argument in Python 2, you can use @mgilson's <a href="https://stackoverflow.com/a/15302038/355230">solution</a>.</p> |
45,113,527 | Why does mulss take only 3 cycles on Haswell, different from Agner's instruction tables? (Unrolling FP loops with multiple accumulators) | <p>I'm a newbie at instruction optimization.</p>
<p>I did a simple analysis on a simple function dotp which is used to get the dot product of two float arrays.</p>
<p>The C code is as follows:</p>
<pre><code>float dotp(
const float x[],
const float y[],
const short n
)
{
short i;
float suma;
suma = 0.0f;
for(i=0; i<n; i++)
{
suma += x[i] * y[i];
}
return suma;
}
</code></pre>
<p>I use the test frame provided by Agner Fog on the web <a href="http://agner.org/optimize/#testp" rel="noreferrer">testp</a>.</p>
<p>The arrays which are used in this case are aligned:</p>
<pre><code>int n = 2048;
float* z2 = (float*)_mm_malloc(sizeof(float)*n, 64);
char *mem = (char*)_mm_malloc(1<<18,4096);
char *a = mem;
char *b = a+n*sizeof(float);
char *c = b+n*sizeof(float);
float *x = (float*)a;
float *y = (float*)b;
float *z = (float*)c;
</code></pre>
<p>Then I call the function dotp, n=2048, repeat=100000:</p>
<pre><code> for (i = 0; i < repeat; i++)
{
sum = dotp(x,y,n);
}
</code></pre>
<p>I compile it with gcc 4.8.3, with the compile option -O3.</p>
<p>I compile this application on a computer which does not support FMA instructions, so you can see there are only SSE instructions.</p>
<p>The assembly code:</p>
<pre><code>.L13:
movss xmm1, DWORD PTR [rdi+rax*4]
mulss xmm1, DWORD PTR [rsi+rax*4]
add rax, 1
cmp cx, ax
addss xmm0, xmm1
jg .L13
</code></pre>
<p>I do some analysis:</p>
<pre><code> μops-fused la 0 1 2 3 4 5 6 7
movss 1 3 0.5 0.5
mulss 1 5 0.5 0.5 0.5 0.5
add 1 1 0.25 0.25 0.25 0.25
cmp 1 1 0.25 0.25 0.25 0.25
addss 1 3 1
jg 1 1 1 -----------------------------------------------------------------------------
total 6 5 1 2 1 1 0.5 1.5
</code></pre>
<p>After running, we get the result:</p>
<pre><code> Clock | Core cyc | Instruct | BrTaken | uop p0 | uop p1
--------------------------------------------------------------------
542177906 |609942404 |1230100389 |205000027 |261069369 |205511063
--------------------------------------------------------------------
2.64 | 2.97 | 6.00 | 1 | 1.27 | 1.00
uop p2 | uop p3 | uop p4 | uop p5 | uop p6 | uop p7
-----------------------------------------------------------------------
205185258 | 205188997 | 100833 | 245370353 | 313581694 | 844
-----------------------------------------------------------------------
1.00 | 1.00 | 0.00 | 1.19 | 1.52 | 0.00
</code></pre>
<p>The second line is the value read from the Intel registers; the third line is divided by the branch number, "BrTaken".</p>
<p>So we can see, in the loop there are 6 instructions, 7 uops, in agreement with the analysis.</p>
<p>The numbers of uops run in port0 port1 port 5 port6 are similar to what the analysis says. I think maybe the uops scheduler does this, it may try to balance loads on the ports, am I right?</p>
<p>I absolutely do not understand know why there are only about 3 cycles per loop. According to Agner's <a href="http://agner.org/optimize/" rel="noreferrer">instruction table</a>, the latency of instruction <code>mulss</code> is 5, and there are dependencies between the loops, so as far as I see it should take at least 5 cycles per loop.</p>
<p>Could anyone shed some insight?</p>
<p>==================================================================</p>
<p>I tried to write an optimized version of this function in nasm, unrolling the loop by a factor of 8 and using the <code>vfmadd231ps</code> instruction:</p>
<pre><code>.L2:
vmovaps ymm1, [rdi+rax]
vfmadd231ps ymm0, ymm1, [rsi+rax]
vmovaps ymm2, [rdi+rax+32]
vfmadd231ps ymm3, ymm2, [rsi+rax+32]
vmovaps ymm4, [rdi+rax+64]
vfmadd231ps ymm5, ymm4, [rsi+rax+64]
vmovaps ymm6, [rdi+rax+96]
vfmadd231ps ymm7, ymm6, [rsi+rax+96]
vmovaps ymm8, [rdi+rax+128]
vfmadd231ps ymm9, ymm8, [rsi+rax+128]
vmovaps ymm10, [rdi+rax+160]
vfmadd231ps ymm11, ymm10, [rsi+rax+160]
vmovaps ymm12, [rdi+rax+192]
vfmadd231ps ymm13, ymm12, [rsi+rax+192]
vmovaps ymm14, [rdi+rax+224]
vfmadd231ps ymm15, ymm14, [rsi+rax+224]
add rax, 256
jne .L2
</code></pre>
<p>The result:</p>
<pre><code> Clock | Core cyc | Instruct | BrTaken | uop p0 | uop p1
------------------------------------------------------------------------
24371315 | 27477805| 59400061 | 3200001 | 14679543 | 11011601
------------------------------------------------------------------------
7.62 | 8.59 | 18.56 | 1 | 4.59 | 3.44
uop p2 | uop p3 | uop p4 | uop p5 | uop p6 | uop p7
-------------------------------------------------------------------------
25960380 |26000252 | 47 | 537 | 3301043 | 10
------------------------------------------------------------------------------
8.11 |8.13 | 0.00 | 0.00 | 1.03 | 0.00
</code></pre>
<p>So we can see the L1 data cache reach 2*256bit/8.59, it is very near to the peak 2*256/8, the usage is about 93%, the FMA unit only used 8/8.59, the peak is 2*8/8, the usage is 47%. </p>
<p>So I think I've reached the L1D bottleneck as Peter Cordes expects.</p>
<p>==================================================================</p>
<p>Special thanks to Boann, fix so many grammatical errors in my question.</p>
<p>=================================================================</p>
<p>From Peter's reply, I get it that only "read and written" register would be the dependence, "writer-only" registers would not be the dependence.</p>
<p>So I try to reduce the registers used in loop, and I try to unrolling by 5, if everything is ok, I should meet the same bottleneck, L1D.</p>
<pre><code>.L2:
vmovaps ymm0, [rdi+rax]
vfmadd231ps ymm1, ymm0, [rsi+rax]
vmovaps ymm0, [rdi+rax+32]
vfmadd231ps ymm2, ymm0, [rsi+rax+32]
vmovaps ymm0, [rdi+rax+64]
vfmadd231ps ymm3, ymm0, [rsi+rax+64]
vmovaps ymm0, [rdi+rax+96]
vfmadd231ps ymm4, ymm0, [rsi+rax+96]
vmovaps ymm0, [rdi+rax+128]
vfmadd231ps ymm5, ymm0, [rsi+rax+128]
add rax, 160 ;n = n+32
jne .L2
</code></pre>
<p>The result:</p>
<pre><code> Clock | Core cyc | Instruct | BrTaken | uop p0 | uop p1
------------------------------------------------------------------------
25332590 | 28547345 | 63700051 | 5100001 | 14951738 | 10549694
------------------------------------------------------------------------
4.97 | 5.60 | 12.49 | 1 | 2.93 | 2.07
uop p2 |uop p3 | uop p4 | uop p5 |uop p6 | uop p7
------------------------------------------------------------------------------
25900132 |25900132 | 50 | 683 | 5400909 | 9
-------------------------------------------------------------------------------
5.08 |5.08 | 0.00 | 0.00 |1.06 | 0.00
</code></pre>
<p>We can see 5/5.60 = 89.45%, it is a little smaller than urolling by 8, is there something wrong?</p>
<p>=================================================================</p>
<p>I try to unroll loop by 6, 7 and 15, to see the result.
I also unroll by 5 and 8 again, to double confirm the result.</p>
<p>The result is as follow, we can see this time the result is much better than before.</p>
<p>Although the result is not stable, the unrolling factor is bigger and the result is better.</p>
<pre><code> | L1D bandwidth | CodeMiss | L1D Miss | L2 Miss
----------------------------------------------------------------------------
unroll5 | 91.86% ~ 91.94% | 3~33 | 272~888 | 17~223
--------------------------------------------------------------------------
unroll6 | 92.93% ~ 93.00% | 4~30 | 481~1432 | 26~213
--------------------------------------------------------------------------
unroll7 | 92.29% ~ 92.65% | 5~28 | 336~1736 | 14~257
--------------------------------------------------------------------------
unroll8 | 95.10% ~ 97.68% | 4~23 | 363~780 | 42~132
--------------------------------------------------------------------------
unroll15 | 97.95% ~ 98.16% | 5~28 | 651~1295 | 29~68
</code></pre>
<p>=====================================================================</p>
<p>I try to compile the function with gcc 7.1 in the web "<a href="https://gcc.godbolt.org" rel="noreferrer">https://gcc.godbolt.org</a>"</p>
<p>The compile option is "-O3 -march=haswell -mtune=intel", that is similar to gcc 4.8.3.</p>
<pre><code>.L3:
vmovss xmm1, DWORD PTR [rdi+rax]
vfmadd231ss xmm0, xmm1, DWORD PTR [rsi+rax]
add rax, 4
cmp rdx, rax
jne .L3
ret
</code></pre> | 45,114,487 | 1 | 9 | null | 2017-07-15 01:14:57.503 UTC | 11 | 2022-05-21 19:11:44.46 UTC | 2021-09-30 17:23:05.187 UTC | null | 2,754,173 | null | 8,306,489 | null | 1 | 46 | c|assembly|x86|sse|micro-optimization | 4,291 | <p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/59494745/avx2-computing-dot-product-of-512-float-arrays">AVX2: Computing dot product of 512 float arrays</a> has a good manually-vectorized dot-product loop using multiple accumulators with FMA intrinsics. The rest of the answer explains why that's a good thing, with cpu-architecture / asm details.</li>
<li><a href="https://stackoverflow.com/questions/47405717/dot-product-of-vectors-with-simd">Dot Product of Vectors with SIMD</a> shows that with the right compiler options, some compilers will auto-vectorize that way.</li>
<li><a href="https://stackoverflow.com/questions/21090873/loop-unrolling-to-achieve-maximum-throughput-with-ivy-bridge-and-haswell">Loop unrolling to achieve maximum throughput with Ivy Bridge and Haswell</a> another version of this Q&A with more focus on unrolling to hide latency (and bottleneck on throughput), less background on what that even means. And with examples using C intrinsics.</li>
<li><a href="https://stackoverflow.com/questions/63095394/latency-bounds-and-throughput-bounds-for-processors-for-operations-that-must-occ">Latency bounds and throughput bounds for processors for operations that must occur in sequence</a> - a textbook exercise on dependency chains, with two interlocking chains, one reading from earlier in the other.</li>
</ul>
<hr />
<p>Look at your loop again: <strong><code>movss xmm1, src</code> has no dependency on the old value of <code>xmm1</code>, because its destination is write-only</strong>. Each iteration's <code>mulss</code> is independent. Out-of-order execution can and does exploit that instruction-level parallelism, so you definitely don't bottleneck on <code>mulss</code> latency.</p>
<p>Optional reading: In computer architecture terms: register renaming avoids the <a href="https://en.wikipedia.org/wiki/Register_renaming#Data_hazards" rel="nofollow noreferrer">WAR anti-dependency data hazard</a> of reusing the same architectural register. (Some pipelining + dependency-tracking schemes before register renaming didn't solve all the problems, so the field of computer architecture makes a big deal out of different kinds of data hazards.</p>
<p>Register renaming with <a href="https://en.wikipedia.org/wiki/Tomasulo_algorithm" rel="nofollow noreferrer">Tomasulo's algorithm</a> makes everything go away except the actual true dependencies (read after write), so any instruction where the destination is not also a source register has no interaction with the dependency chain involving the old value of that register. (Except for false dependencies, like <a href="https://stackoverflow.com/questions/25078285/replacing-a-32-bit-loop-count-variable-with-64-bit-introduces-crazy-performance"><code>popcnt</code> on Intel CPUs</a>, and writing only part of a register without clearing the rest (like <code>mov al, 5</code> or <code>sqrtss xmm2, xmm1</code>). Related: <a href="https://stackoverflow.com/questions/11177137/why-do-most-x64-instructions-zero-the-upper-part-of-a-32-bit-register">Why do x86-64 instructions on 32-bit registers zero the upper part of the full 64-bit register?</a>).</p>
<hr />
<p>Back to your code:</p>
<pre><code>.L13:
movss xmm1, DWORD PTR [rdi+rax*4]
mulss xmm1, DWORD PTR [rsi+rax*4]
add rax, 1
cmp cx, ax
addss xmm0, xmm1
jg .L13
</code></pre>
<p>The loop-carried dependencies (from one iteration to the next) are each:</p>
<ul>
<li><code>xmm0</code>, read and written by <strong><code>addss xmm0, xmm1</code></strong>, which has 3 cycle latency on Haswell.</li>
<li><code>rax</code>, read and written by <code>add rax, 1</code>. 1c latency, so it's not the critical-path.</li>
</ul>
<p>It looks like you measured the execution time / cycle-count correctly, because <strong>the loop bottlenecks on the 3c <code>addss</code> latency</strong>.</p>
<p>This is expected: the serial dependency in a dot product is the addition into a single sum (aka the reduction), not the multiplies between vector elements. (Unrolling with multiple <code>sum</code> accumulator variables / registers can hide that latency.)</p>
<p>That is by far the dominant bottleneck for this loop, despite various minor inefficiencies:</p>
<hr />
<p><code>short i</code> produced the silly <code>cmp cx, ax</code>, which takes an extra operand-size prefix. Luckily, gcc managed to avoid actually doing <code>add ax, 1</code>, because signed-overflow is Undefined Behaviour in C. <a href="http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html" rel="nofollow noreferrer">So the optimizer can assume it doesn't happen</a>. (update: <a href="https://stackoverflow.com/questions/45113527/why-does-mulss-take-only-3-cycles-on-haswell-different-from-agners-instruction/45114487?noredirect=1#comment77208279_45114487">integer promotion rules make it different for <code>short</code></a>, so UB doesn't come into it, but gcc can still legally optimize. Pretty wacky stuff.)</p>
<p>If you'd compiled with <code>-mtune=intel</code>, or better, <code>-march=haswell</code>, gcc would have put the <code>cmp</code> and <code>jg</code> next to each other where they could macro-fuse.</p>
<p>I'm not sure why you have a <code>*</code> in your table on the <code>cmp</code> and <code>add</code> instructions. (update: I was purely guessing that you were using a notation like <a href="https://stackoverflow.com/questions/26021337/what-is-iaca-and-how-do-i-use-it">IACA</a> does, but apparently you weren't). Neither of them fuse. The only fusion happening is micro-fusion of <code>mulss xmm1, [rsi+rax*4]</code>.</p>
<p>And since it's a 2-operand ALU instruction with a read-modify-write destination register, it stays macro-fused even in the ROB on Haswell. (Sandybridge would un-laminate it at issue time.) <a href="https://stackoverflow.com/questions/26046634/micro-fusion-and-addressing-modes#comment76198723_31027695">Note that <code>vmulss xmm1, xmm1, [rsi+rax*4]</code> would un-laminate on Haswell, too</a>.</p>
<p>None of this really matters, since you just totally bottleneck on FP-add latency, much slower than any uop-throughput limits. Without <code>-ffast-math</code>, there's nothing compilers can do. With <code>-ffast-math</code>, clang will usually unroll with multiple accumulators, and it will auto-vectorize so they will be vector accumulators. So you can probably saturate Haswell's throughput limit of 1 vector or scalar FP add per clock, if you hit in L1D cache.</p>
<p>With FMA being 5c latency and 0.5c throughput on Haswell, you would need 10 accumulators to keep 10 FMAs in flight and max out FMA throughput by keeping p0/p1 saturated with FMAs. (Skylake reduced FMA latency to 4 cycles, and runs multiply, add, and FMA on the FMA units. So it actually has higher add latency than Haswell.)</p>
<p>(You're bottlenecked on loads, because you need two loads for every FMA. In other cases, you can actually gain add throughput by replacing some a <code>vaddps</code> instruction with an FMA with a multiplier of 1.0. This means more latency to hide, so it's best in a more complex algorithm where you have an add that's not on the critical path in the first place.)</p>
<hr />
<p><strong>Re: uops per port</strong>:</p>
<blockquote>
<p>there are 1.19 uops per loop in the port 5, it is much more than expect 0.5, is it the matter about the uops dispatcher trying to make uops on every port same</p>
</blockquote>
<p>Yes, something like that.</p>
<p>The uops are not assigned randomly, or somehow evenly distributed across every port they <em>could</em> run on. You assumed that the <code>add</code> and <code>cmp</code> uops would distribute evenly across p0156, but that's not the case.</p>
<p>The issue stage assigns uops to ports based on how many uops are already waiting for that port. Since <code>addss</code> can only run on p1 (and it's the loop bottleneck), there are usually a lot of p1 uops issued but not executed. So few other uops will ever be scheduled to port1. (This includes <code>mulss</code>: most of the <code>mulss</code> uops will end up scheduled to port 0.)</p>
<p>Taken-branches can only run on port 6. Port 5 doesn't have any uops in this loop that can <em>only</em> run there, so it ends up attracting a lot of the many-port uops.</p>
<p>The scheduler (which picks unfused-domain uops out of the Reservation Station) isn't smart enough to run critical-path-first, so this is assignment algorithm reduces resource-conflict latency (other uops stealing port1 on cycles when an <code>addss</code> could have run). It's also useful in cases where you bottleneck on the throughput of a given port.</p>
<p>Scheduling of already-assigned uops is normally oldest-ready first, as I understand it. This simple algorithm is hardly surprising, since it has to pick a uop with its inputs ready for each port from <a href="http://www.realworldtech.com/haswell-cpu/3/" rel="nofollow noreferrer">a 60-entry RS</a> every clock cycle, without melting your CPU. The out-of-order machinery that finds and exploits <a href="https://en.wikipedia.org/wiki/Instruction-level_parallelism" rel="nofollow noreferrer">the ILP</a> is one of the significant power costs in a modern CPU, comparable to the execution units that do the actual work.</p>
<p>Related / more details: <a href="https://stackoverflow.com/questions/40681331/how-are-x86-uops-scheduled-exactly">How are x86 uops scheduled, exactly?</a></p>
<hr />
<h2>More performance analysis stuff:</h2>
<p>Other than cache misses / branch mispredicts, the three main possible bottlenecks for CPU-bound loops are:</p>
<ul>
<li>dependency chains (like in this case)</li>
<li>front-end throughput (max of 4 fused-domain uops issued per clock on Haswell)</li>
<li>execution port bottlenecks, like if lots of uops need p0/p1, or p2/p3, like in your unrolled loop. Count unfused-domain uops for specific ports. Generally you can assuming best-case distribution, with uops that can run on other ports not stealing the busy ports very often, but it does happen some.</li>
</ul>
<p>A loop body or short block of code can be approximately characterized by 3 things: fused-domain uop count, unfused-domain count of which execution units it can run on, and total critical-path latency assuming best-case scheduling for its critical path. (Or latencies from each of input A/B/C to the output...)</p>
<p>For example of doing all three to compare a few short sequences, see my answer on <a href="https://stackoverflow.com/questions/34407437/what-is-the-efficient-way-to-count-set-bits-at-a-position-or-lower/34410357#34410357">What is the efficient way to count set bits at a position or lower?</a></p>
<p>For short loops, modern CPUs have enough out-of-order execution resources (physical register file size so renaming doesn't run out of registers, ROB size) to have enough iterations of a loop in-flight to find all the parallelism. But as dependency chains within loops get longer, eventually they run out. See <a href="http://blog.stuffedcow.net/2013/05/measuring-rob-capacity/" rel="nofollow noreferrer">Measuring Reorder Buffer Capacity</a> for some details on what happens when a CPU runs out of registers to rename onto.</p>
<p>See also lots of performance and reference links in the <a href="/questions/tagged/x86" class="post-tag" title="show questions tagged 'x86'" rel="tag">x86</a> tag wiki.</p>
<hr />
<h2>Tuning your FMA loop:</h2>
<p>Yes, dot-product on Haswell will bottleneck on L1D throughput at only half the throughput of the FMA units, since it takes two loads per multiply+add.</p>
<p>If you were doing <code>B[i] = x * A[i] + y;</code> or <code>sum(A[i]^2)</code>, you could saturate FMA throughput.</p>
<p><strong>It looks like you're still trying to avoid register reuse even in write-only cases like the destination of a <code>vmovaps</code> load, so you ran out of registers after unrolling by 8</strong>. That's fine, but could matter for other cases.</p>
<p>Also, using <code>ymm8-15</code> can slightly increase code-size if it means a 3-byte VEX prefix is needed instead of 2-byte. Fun fact: <code>vpxor ymm7,ymm7,ymm8</code> needs a 3-byte VEX while <code>vpxor ymm8,ymm8,ymm7</code> only needs a 2-byte VEX prefix. For commutative ops, sort source regs from high to low.</p>
<p>Our load bottleneck means the best-case FMA throughput is half the max, so we need at least 5 vector accumulators to hide their latency. 8 is good, so there's plenty of slack in the dependency chains to let them catch up after any delays from unexpected latency or competition for p0/p1. 7 or maybe even 6 would be fine, too: your unroll factor doesn't have to be a power of 2.</p>
<p><strong>Unrolling by exactly 5 would mean that you're also right at the bottleneck for dependency chains</strong>. Any time an FMA doesn't run in the exact cycle its input is ready means a lost cycle in that dependency chain. This can happen if a load is slow (e.g. it misses in L1 cache and has to wait for L2), or if loads complete out of order and an FMA from another dependency chain steals the port this FMA was scheduled for. (Remember that scheduling happens at issue time, so the uops sitting in the scheduler are either port0 FMA or port1 FMA, not an FMA that can take whichever port is idle).</p>
<p>If you leave some slack in the dependency chains, out-of-order execution can "catch up" on the FMAs, because they won't be bottlenecked on throughput or latency, just waiting for load results. @Forward found (in an update to the question) that unrolling by 5 reduced performance from 93% of L1D throughput to 89.5% for this loop.</p>
<p>My guess is that unroll by 6 (one more than the minimum to hide the latency) would be ok here, and get about the same performance as unroll by 8. If we were closer to maxing out FMA throughput (rather than just bottlenecked on load throughput), one more than the minimum might not be enough.</p>
<p><strong>update: @Forward's experimental test shows my guess was wrong</strong>. There isn't a big difference between unroll5 and unroll6. Also, unroll15 is twice as close as unroll8 to the theoretical max throughput of 2x 256b loads per clock. Measuring with just independent loads in the loop, or with independent loads and register-only FMA, would tell us how much of that is due to interaction with the FMA dependency chain. Even the best case won't get perfect 100% throughput, if only because of measurement errors and disruption due to timer interrupts. (Linux <code>perf</code> measures only user-space cycles unless you run it as root, but time still includes time spent in interrupt handlers. This is why your CPU frequency might be reported as 3.87GHz when run as non-root, but 3.900GHz when run as root and measuring <code>cycles</code> instead of <code>cycles:u</code>.)</p>
<hr />
<p>We aren't bottlenecked on front-end throughput, but we can reduce the fused-domain uop count by avoiding indexed addressing modes for non-<code>mov</code> instructions. Fewer is better and makes this more <strong>hyperthreading-friendly</strong> when sharing a core with something other than this.</p>
<p>The simple way is just to do two pointer-increments inside the loop. The complicated way is a neat trick of indexing one array relative to the other:</p>
<pre><code>;; input pointers for x[] and y[] in rdi and rsi
;; size_t n in rdx
;;; zero ymm1..8, or load+vmulps into them
add rdx, rsi ; end_y
; lea rdx, [rdx+rsi-252] to break out of the unrolled loop before going off the end, with odd n
sub rdi, rsi ; index x[] relative to y[], saving one pointer increment
.unroll8:
vmovaps ymm0, [rdi+rsi] ; *px, actually py[xy_offset]
vfmadd231ps ymm1, ymm0, [rsi] ; *py
vmovaps ymm0, [rdi+rsi+32] ; write-only reuse of ymm0
vfmadd231ps ymm2, ymm0, [rsi+32]
vmovaps ymm0, [rdi+rsi+64]
vfmadd231ps ymm3, ymm0, [rsi+64]
vmovaps ymm0, [rdi+rsi+96]
vfmadd231ps ymm4, ymm0, [rsi+96]
add rsi, 256 ; pointer-increment here
; so the following instructions can still use disp8 in their addressing modes: [-128 .. +127] instead of disp32
; smaller code-size helps in the big picture, but not for a micro-benchmark
vmovaps ymm0, [rdi+rsi+128-256] ; be pedantic in the source about compensating for the pointer-increment
vfmadd231ps ymm5, ymm0, [rsi+128-256]
vmovaps ymm0, [rdi+rsi+160-256]
vfmadd231ps ymm6, ymm0, [rsi+160-256]
vmovaps ymm0, [rdi+rsi-64] ; or not
vfmadd231ps ymm7, ymm0, [rsi-64]
vmovaps ymm0, [rdi+rsi-32]
vfmadd231ps ymm8, ymm0, [rsi-32]
cmp rsi, rdx
jb .unroll8 ; } while(py < endy);
</code></pre>
<p>Using a non-indexed addressing mode as the memory operand for <code>vfmaddps</code> lets it stay micro-fused in the out-of-order core, instead of being un-laminated at issue. <a href="https://stackoverflow.com/questions/26046634/micro-fusion-and-addressing-modes">Micro fusion and addressing modes</a></p>
<p>So my loop is 18 fused-domain uops for 8 vectors. Yours takes 3 fused-domain uops for each vmovaps + vfmaddps pair, instead of 2, because of un-lamination of indexed addressing modes. Both of them still of course have 2 unfused-domain load uops (port2/3) per pair, so that's still the bottleneck.</p>
<p>Fewer fused-domain uops lets out-of-order execution see more iterations ahead, potentially helping it absorb cache misses better. It's a minor thing when we're bottlenecked on an execution unit (load uops in this case) even with no cache misses, though. But with hyperthreading, you only get every other cycle of front-end issue bandwidth unless the other thread is stalled. If it's not competing too much for load and p0/1, fewer fused-domain uops will let this loop run faster while sharing a core. (e.g. maybe the other hyper-thread is running a lot of port5 / port6 and store uops?)</p>
<p>Since un-lamination happens after the uop-cache, your version doesn't take extra space in the uop cache. A disp32 with each uop is ok, and doesn't take extra space. But bulkier code-size means the uop-cache is less likely to pack as efficiently, since you'll hit 32B boundaries before uop cache lines are full more often. (Actually, smaller code doesn't guarantee better either. Smaller instructions could lead to filling a uop cache line and needing one entry in another line before crossing a 32B boundary.) This small loop can run from the loopback buffer (LSD), so fortunately the uop-cache isn't a factor.</p>
<hr />
<p>Then after the loop: Efficient cleanup is the hard part of efficient vectorization for small arrays that might not be a multiple of the unroll factor or especially the vector width</p>
<pre><code> ...
jb
;; If `n` might not be a multiple of 4x 8 floats, put cleanup code here
;; to do the last few ymm or xmm vectors, then scalar or an unaligned last vector + mask.
; reduce down to a single vector, with a tree of dependencies
vaddps ymm1, ymm2, ymm1
vaddps ymm3, ymm4, ymm3
vaddps ymm5, ymm6, ymm5
vaddps ymm7, ymm8, ymm7
vaddps ymm0, ymm3, ymm1
vaddps ymm1, ymm7, ymm5
vaddps ymm0, ymm1, ymm0
; horizontal within that vector, low_half += high_half until we're down to 1
vextractf128 xmm1, ymm0, 1
vaddps xmm0, xmm0, xmm1
vmovhlps xmm1, xmm0, xmm0
vaddps xmm0, xmm0, xmm1
vmovshdup xmm1, xmm0
vaddss xmm0, xmm1
; this is faster than 2x vhaddps
vzeroupper ; important if returning to non-AVX-aware code after using ymm regs.
ret ; with the scalar result in xmm0
</code></pre>
<p>For more about the horizontal sum at the end, see <a href="https://stackoverflow.com/questions/6996764/fastest-way-to-do-horizontal-float-vector-sum-on-x86">Fastest way to do horizontal SSE vector sum (or other reduction)</a>. The two 128b shuffles I used don't even need an immediate control byte, so it saves 2 bytes of code size vs. the more obvious <code>shufps</code>. (And 4 bytes of code-size vs. <code>vpermilps</code>, because that opcode always needs a 3-byte VEX prefix as well as an immediate). AVX 3-operand stuff is <em>very</em> nice compared the SSE, especially when writing in C with intrinsics so you can't as easily pick a cold register to <code>movhlps</code> into.</p> |
23,895,563 | Is it safe to call Type.GetType with an untrusted type name? | <p>I came across the following in a code review:</p>
<pre><code>Type type = Type.GetType(typeName);
if (type == typeof(SomeKnownType))
DoSomething(...); // does not use type or typeName
</code></pre>
<p><code>typeName</code> originates from an AJAX request and is not validated. <strong>Does this pose any potential security issues?</strong> For example, is it possible for unexpected code to be executed, or for the entire
application to crash (denial of service), as the result of loading arbitrary types from arbitrary assemblies?</p>
<p>(I suppose some joker could attempt to exhaust available memory by loading every type from every assembly in the GAC. Anything worse?)</p>
<p>Notes:</p>
<ul>
<li>This is an ASP.NET application running under Full Trust.</li>
<li>The resulting <code>type</code> is <em>only</em> used as shown above. No attempt is made to instantiate the type.</li>
</ul> | 23,896,200 | 3 | 6 | null | 2014-05-27 17:32:25.603 UTC | 1 | 2014-05-28 14:58:26.277 UTC | null | null | null | null | 1,127,114 | null | 1 | 28 | c#|asp.net|.net|security | 1,138 | <p>No, this is not safe at all. <a href="http://msdn.microsoft.com/en-us/library/vstudio/w3f99sx1" rel="nofollow">Type.GetType</a> will load an assembly if it has not been loaded before:</p>
<blockquote>
<p>GetType causes loading of the assembly specified in typeName.</p>
</blockquote>
<p>So what's wrong with loading an assembly? Aside from it using additional memory as Daniel points out, .NET assemblies <em>can</em> execute code when they load, even though this functionality is not exposed to normal compilers like C# and VB.NET. These are called <a href="http://blogs.msdn.com/b/junfeng/archive/2005/11/19/494914.aspx" rel="nofollow">module initializers</a>.</p>
<blockquote>
<p>The module’s initializer method is executed at, or sometime before, first access to any types, methods, or data defined in the module</p>
</blockquote>
<p>Just the fact that you are loading an assembly and examining its types is enough to get the module initializer to run.</p>
<p>Someone with a cleverly written assembly (say by using ilasm and writing raw MSIL) can execute code just by getting the assembly loaded and you examining the types. That's why we have <a href="http://msdn.microsoft.com/en-us/library/0et80c7k%28v=vs.110%29.aspx" rel="nofollow">Assembly.ReflectionOnlyLoad</a>, so we can safely load the assembly in a non-executable environment.</p>
<hr>
<p>I did a little more thinking about this and thought of a few more cases.</p>
<p>Consider that your Application Pool is set to run 64-bit. Now imagine that your attacker uses the AJAX service to attempt to load an assembly that is strictly for x86 architecture only. For example, there is one in my GAC called Microsoft.SqlServer.Replication that is x86 only, there is no AMD64 counter-part. If I ask your service to load that assembly, you'd get a <code>BadImageFormatException</code>. Depending on what guard clauses you have in place around loading the assembly, unhandled exceptions could completely <a href="http://msdn.microsoft.com/en-us/magazine/cc793966.aspx" rel="nofollow">bring down your AppPool</a>.</p> |
8,919,095 | Lifetime of ASP.NET Static Variable | <p>I am holding some information in static variables defined in page class (not in Global.asax). I only declare variable in code like:</p>
<pre><code>protected static int SomeGlobalUnsecureID;
protected static string SomeGlobalUnsecureString;
</code></pre>
<p>and define the variable in PageLoad event. For example, I check ID from the database, if it's different from SomeGlobalUnsecureID, I update SomeGlobalUnsecureID and String from somewhere else, otherwise leave them as is. This is perfectly safe in my app. logic (i.e. those data are not secure, everybody can access them, no problem); only thing I want to accomplish is </p>
<ol>
<li><p>Hold the same amount of memory regardless of users connected</p></li>
<li><p>Change if and only if persistent info is different from the one in
'memory' (because actually reading the string is time consuming for
me.</p></li>
</ol>
<p>Now, since I make the check in PageLoad, I have no problems in reloaded pages. However my page is full of WebMethods, and sometimes I see that the static variables are zeroed. And the strange part is; the session is still active even when the static variables are zeroed (so-> no server or app. pool restart etc.)</p>
<p>This is really strange for me. I assume that static variable will hold its value until the application (somehow) ends. But even the Session did not expire, the static variable is zeroed. What do you suggest? Is using application variables a better choice? All documents I've read on web suggest static variables instead of application variables, do I need to declare them somehow different?</p> | 8,919,336 | 3 | 4 | null | 2012-01-18 23:31:24.517 UTC | 19 | 2018-05-24 17:45:25.367 UTC | 2016-10-17 21:37:25.937 UTC | null | 159,270 | null | 192,936 | null | 1 | 85 | c#|asp.net|static | 101,093 | <p>Static variables persist for the life of the app domain. So the two things that will cause your static variables to 'reset' is an app domain restart or the use of a new class. In your case with static variables stored in an aspx Page class, you may be losing the static variables when ASP.NET decides to recompile the aspx Page into a new class, replacing the old page class with the new one.</p>
<p>For those reasons if the system decide to restart or replace the class (<a href="http://blogs.msdn.com/b/jasonz/archive/2004/05/31/145105.aspx" rel="noreferrer">.NET doesn't kill or unload classes/assemblies in a running app domain</a>) then your static variables will reset because you are getting a new class with the restart or replacement. This applies to both aspx Pages and <a href="http://msdn.microsoft.com/en-us/library/t990ks23%28v=vs.80%29.aspx" rel="noreferrer">classes in the App_Code folder</a></p>
<p>ASP.NET will replace a class if for any reason thinks that need to recompile it (<a href="http://msdn.microsoft.com/en-us/library/ms366723%28v=vs.100%29.aspx" rel="noreferrer">see ASP.NET dynamic compilation</a>).</p>
<p>You can't prevent the loss of static variables from an app domain restart, but you can try to avoid it from class replacement. You could put your static variables in a class that is not an aspx page and is not in the App_Code directory. You might want to place them on a <code>static class</code> somewhere in your program.</p>
<pre><code>public static class GlobalVariables
{
public static int SomeGlobalUnsecureID;
public static string SomeGlobalUnsecureString;
}
</code></pre>
<p>The static variables are per pool, that is means that if you have 2 pools that runs your asp.net site, you have 2 different static variables. (<a href="http://msdn.microsoft.com/en-us/library/aa479328.aspx" rel="noreferrer">Web garden mode</a>)</p>
<p>The static variables are lost if the system restarts your asp.net application with one of this way.</p>
<ol>
<li>the pool decide that need to make a recompile. </li>
<li>You open the app_offline.htm file </li>
<li>You make manual restart of the pool </li>
<li>The pool is reach some limits that you have define and make restart. </li>
<li>For any reason you restart the iis, or the pool.</li>
</ol>
<p>This static variables are not thread safe, and you need to use the <strong>lock</strong> keyword especial if you access them from different threads.</p>
<p>Since an app restart will reset your statics no matter what, if you really want to persist your data, you should store the data in a database using custom classes. You can store information per-user in <a href="http://msdn.microsoft.com/en-us/library/ms178581%28v=vs.100%29.aspx" rel="noreferrer">Session State</a> with a <a href="http://msdn.microsoft.com/en-us/library/ms178586%28v=vs.100%29.aspx" rel="noreferrer">database session state mode</a>. ASP.NET Application State/Variables will not help you because <a href="http://msdn.microsoft.com/en-us/library/ms178594%28v=vs.100%29.aspx" rel="noreferrer">they are stored in memory, not the database</a>, so they are lost on app domain restart too.</p> |
8,946,906 | Why is javascript the only client side scripting language implemented in browsers? | <p>Why don't browsers add support for, say, Python scripting as an alternative to Javascript? Or more general purpose scripting languages? Is there a reason that Javascript is the only one implemented across browsers? After all, the script tag does have support to specify the scripting language used.</p>
<p>(I know there is VBScript support in IE, but it seems obsolete for all intents and purposes.)</p> | 8,947,021 | 3 | 5 | null | 2012-01-20 19:35:46.37 UTC | 11 | 2012-01-20 20:17:10.157 UTC | 2012-01-20 20:17:10.157 UTC | null | 12,649 | null | 12,649 | null | 1 | 75 | javascript|browser|web|standards | 28,878 | <p>Well, Google is trying to buck that trend with <a href="http://en.wikipedia.org/wiki/Dart_(programming_language)" rel="noreferrer">Dart</a>. The community hasn't been entirely receptive to the idea; either.</p>
<p>Google <a href="https://lists.webkit.org/pipermail/webkit-dev/2011-December/018775.html" rel="noreferrer">proposed adding multiple VM support for Webkit</a> which didn't go down very well.</p>
<p>One particular comment summed it up nicely as to why there has been some resistance to that:</p>
<blockquote>
<p>In this case the feature is exposing additional programming languages to the web, something without any real benefit to anyone other than fans of the current "most awesome" language (not too long ago that might have been Go, a year or so ago this would have been ruby, before than python, i recall i brief surge in haskell popularity not that long ago as well, Lua has been on the verges for a long time, in this case it's Dart -- who's to say there won't be a completely different language in vogue in 6 months?), but as a cost it fragments the web and adds a substantial additional maintenance burden -- just maintaining the v8 and jsc bindings isn't trivial and they're for the same language.</p>
<p>The issue here isn't "can we make multiple vms live in webkit" it's "can we expose multiple languages to the web", to the former i say obviously as we already do, to the latter I say that we don't want to.</p>
<p>Unless we want to turn webkit into the engine that everyone hates because of all its unique "features" that break the open web, a la certain browsers in the late 90s.</p>
</blockquote>
<p>CoffeeScript is another example of an emerging client-side scripting language. However, rather than support another virtual machine in a browser (as Google is trying to do with Dart), it compiles to JavaScript. There are several other "compile X to JavaScript" that do that as well. <a href="https://github.com/kripken/emscripten" rel="noreferrer">emscripten</a> is a good example of compiling <em>LLVM</em> to JavaScript.</p>
<p>So there are plenty of other client languages; they just all use JavaScript as an intermediate. I'd argue that should be what Dart does as well, though <a href="http://lostechies.com/jimmybogard/2011/10/12/the-dart-hello-world/" rel="noreferrer">they have some room to improve</a>.</p> |
8,525,396 | How to put a new line into a wpf TextBlock control? | <p>I'm fetching text from an XML file, and I'd like to insert some new lines that are interpreted by the textblock render as new lines.</p>
<p>I've tried:</p>
<pre><code><data>Foo bar baz \n baz bar</data>
</code></pre>
<p>But the data is still displayed without the new line. I set the contents of <code><data></code> via the <code>.Text</code> property via C#.</p>
<p>What do I need to put in the XML in order for it to render the new line in the GUI?</p>
<p>I've tried something like this manually setting the text in the XAML:</p>
<pre><code><TextBlock Margin="0 15 0 0" Width="600">
There &#10;
is a new line.
</TextBlock>
</code></pre>
<p>And while the encoded character doesn't appear in the GUI it also doesn't give me a new line.</p> | 8,525,453 | 13 | 5 | null | 2011-12-15 19:16:47.82 UTC | 20 | 2022-06-22 06:43:10.397 UTC | 2011-12-15 19:27:19.607 UTC | null | 699,978 | null | 699,978 | null | 1 | 126 | c#|wpf|newline|textblock | 165,330 | <p>You can try putting a new line in the data:</p>
<pre><code><data>Foo bar baz
baz bar</data>
</code></pre>
<p>If that does not work you might need to parse the string manually.</p>
<p>If you need direct XAML that's easy by the way:</p>
<pre class="lang-xml prettyprint-override"><code><TextBlock>
Lorem <LineBreak/>
Ipsum
</TextBlock>
</code></pre> |
5,551,301 | Clone MySQL database | <p>I have database on a server with 120 tables.</p>
<p>I want to clone the whole database with a new db name and the copied data.</p>
<p>Is there an efficient way to do this?</p> | 5,551,359 | 7 | 1 | null | 2011-04-05 11:47:49.343 UTC | 28 | 2020-04-16 22:10:49.577 UTC | 2015-07-28 07:09:54.66 UTC | null | 596,532 | null | 435,964 | null | 1 | 55 | mysql|database|mysqldump | 75,237 | <pre><code>$ mysqldump yourFirstDatabase -u user -ppassword > yourDatabase.sql
$ mysql yourSecondDatabase -u user -ppassword < yourDatabase.sql
</code></pre> |
5,487,876 | How can I get the utc offset in Rails? | <p>I need the utc offset from the timezone specified.</p> | 5,488,161 | 8 | 0 | null | 2011-03-30 14:43:23.157 UTC | 6 | 2019-10-28 02:01:37.797 UTC | null | null | null | null | 210,512 | null | 1 | 27 | ruby-on-rails|ruby|datetime|timezone | 43,431 | <pre><code>require 'time'
p Time.zone_offset('EST') #=> -18000 #(-5*60*60)
</code></pre> |
5,484,922 | Secondary axis with twinx(): how to add to legend? | <p>I have a plot with two y-axes, using <code>twinx()</code>. I also give labels to the lines, and want to show them with <code>legend()</code>, but I only succeed to get the labels of one axis in the legend:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')
ax.legend(loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
</code></pre>
<p>So I only get the labels of the first axis in the legend, and not the label 'temp' of the second axis. How could I add this third label to the legend?</p>
<p><img src="https://i.stack.imgur.com/MdCYW.png" alt="enter image description here"></p> | 5,487,005 | 10 | 4 | null | 2011-03-30 10:10:56.473 UTC | 164 | 2022-05-12 19:30:43.283 UTC | 2011-03-30 10:26:26.83 UTC | null | 653,364 | null | 653,364 | null | 1 | 417 | python|matplotlib|axis|legend | 356,381 | <p>You can easily add a second legend by adding the line:</p>
<pre><code>ax2.legend(loc=0)
</code></pre>
<p>You'll get this:</p>
<p><img src="https://i.stack.imgur.com/DLZkF.png" alt="enter image description here"></p>
<p>But if you want all labels on one legend then you should do something like this:</p>
<pre><code>import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(10)
temp = np.random.random(10)*30
Swdown = np.random.random(10)*100-10
Rn = np.random.random(10)*100-10
fig = plt.figure()
ax = fig.add_subplot(111)
lns1 = ax.plot(time, Swdown, '-', label = 'Swdown')
lns2 = ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
lns3 = ax2.plot(time, temp, '-r', label = 'temp')
# added these three lines
lns = lns1+lns2+lns3
labs = [l.get_label() for l in lns]
ax.legend(lns, labs, loc=0)
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
</code></pre>
<p>Which will give you this:</p>
<p><img src="https://i.stack.imgur.com/Z8pg4.png" alt="enter image description here"></p> |
5,427,656 | iOS UIImagePickerController result image orientation after upload | <p>I am testing my iPhone application on an iOS 3.1.3 iPhone. I am selecting/capturing an image using a <code>UIImagePickerController</code>:</p>
<pre><code>UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
[imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
[imagePicker setDelegate:self];
[self.navigationController presentModalViewController:imagePicker animated:YES];
[imagePicker release];
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
self.image = [info objectForKey:UIImagePickerControllerOriginalImage];
imageView.image = self.image;
[self.navigationController dismissModalViewControllerAnimated:YES];
submitButton.enabled = YES;
}
</code></pre>
<p>I then at some point send it to my web server using the ASI classes:</p>
<pre><code>ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://example.com/myscript.php"]];
[request setDelegate:self];
[request setStringEncoding:NSUTF8StringEncoding];
[request setShouldContinueWhenAppEntersBackground:YES];
//other post keys/values
[request setFile:UIImageJPEGRepresentation(self.image, 100.0f) withFileName:[NSString stringWithFormat:@"%d.jpg", [[NSDate date] timeIntervalSinceNow]] andContentType:@"image/jpg" forKey:@"imageFile"];
[request startAsynchronous];
</code></pre>
<p>the problem:
when i take a picture with the iphone while holding it landscape, the image gets uploaded to the server and it viewed like you would expect. when taking a picture holding the phone in portrait, the image is uploaded and viewed as it had been rotated 90 degrees.</p>
<p>my application is set to only work in portrait modes(upsidedown and regular).</p>
<p>How can i make the image always show the correct orientation after uploading?</p>
<p>the image appears to be correct as displayed in an UIImageView(directly after taking the picture), but viewing on the server says otherwise.</p> | 5,427,890 | 20 | 0 | null | 2011-03-25 01:41:18.263 UTC | 230 | 2020-10-06 11:04:06.433 UTC | 2015-08-16 10:12:11.39 UTC | null | 3,024,579 | null | 416,412 | null | 1 | 346 | ios|iphone|cocoa-touch|uiimage|uiimagepickercontroller | 143,203 | <p>A <code>UIImage</code> has a property <code>imageOrientation</code>, which instructs the <code>UIImageView</code> and other <code>UIImage</code> consumers to rotate the raw image data. There's a good chance that this flag is being saved to the exif data in the uploaded jpeg image, but the program you use to view it is not honoring that flag.</p>
<p>To rotate the <code>UIImage</code> to display properly when uploaded, you can use a category like this:</p>
<p><strong>UIImage+fixOrientation.h</strong></p>
<pre><code>@interface UIImage (fixOrientation)
- (UIImage *)fixOrientation;
@end
</code></pre>
<p><strong>UIImage+fixOrientation.m</strong></p>
<pre><code>@implementation UIImage (fixOrientation)
- (UIImage *)fixOrientation {
// No-op if the orientation is already correct
if (self.imageOrientation == UIImageOrientationUp) return self;
// We need to calculate the proper transformation to make the image upright.
// We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
CGAffineTransform transform = CGAffineTransformIdentity;
switch (self.imageOrientation) {
case UIImageOrientationDown:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, self.size.height);
transform = CGAffineTransformRotate(transform, M_PI);
break;
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0);
transform = CGAffineTransformRotate(transform, M_PI_2);
break;
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, 0, self.size.height);
transform = CGAffineTransformRotate(transform, -M_PI_2);
break;
case UIImageOrientationUp:
case UIImageOrientationUpMirrored:
break;
}
switch (self.imageOrientation) {
case UIImageOrientationUpMirrored:
case UIImageOrientationDownMirrored:
transform = CGAffineTransformTranslate(transform, self.size.width, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationLeftMirrored:
case UIImageOrientationRightMirrored:
transform = CGAffineTransformTranslate(transform, self.size.height, 0);
transform = CGAffineTransformScale(transform, -1, 1);
break;
case UIImageOrientationUp:
case UIImageOrientationDown:
case UIImageOrientationLeft:
case UIImageOrientationRight:
break;
}
// Now we draw the underlying CGImage into a new context, applying the transform
// calculated above.
CGContextRef ctx = CGBitmapContextCreate(NULL, self.size.width, self.size.height,
CGImageGetBitsPerComponent(self.CGImage), 0,
CGImageGetColorSpace(self.CGImage),
CGImageGetBitmapInfo(self.CGImage));
CGContextConcatCTM(ctx, transform);
switch (self.imageOrientation) {
case UIImageOrientationLeft:
case UIImageOrientationLeftMirrored:
case UIImageOrientationRight:
case UIImageOrientationRightMirrored:
// Grr...
CGContextDrawImage(ctx, CGRectMake(0,0,self.size.height,self.size.width), self.CGImage);
break;
default:
CGContextDrawImage(ctx, CGRectMake(0,0,self.size.width,self.size.height), self.CGImage);
break;
}
// And now we just create a new UIImage from the drawing context
CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
UIImage *img = [UIImage imageWithCGImage:cgimg];
CGContextRelease(ctx);
CGImageRelease(cgimg);
return img;
}
@end
</code></pre> |
12,597,678 | Tag editor component for Delphi/C++Builder | <p>I need a VCL tag editor component for Delphi or C++Builder, similar to what's available for JavaScript: e.g. <a href="http://aehlke.github.com/tag-it/examples.html" rel="nofollow noreferrer">this one</a>, or <a href="http://xoxco.com/projects/code/tagsinput/" rel="nofollow noreferrer">this one</a> or StackOverflow's own tags editor.</p>
<p>Is there something like this available or do I need to make it from scratch?</p>
<p>Some specific things that I need are:</p>
<ul>
<li>Editor should allow either scrolling or become multi-line if more tags are present than the editor's width allows. If multi-line, there should be an option to define some maximum height however, preventing it from becoming too tall</li>
<li>Option to select whether tags are created when pressing space or comma key</li>
<li>Prompt text in the editor, when it is not focused (for example "Add new tag")</li>
<li>Ideally, you should be able to move between tags (highlighting them) using the keyboard arrows, so you can delete any tag using the keyboard only</li>
</ul> | 12,600,297 | 1 | 1 | null | 2012-09-26 08:34:24.987 UTC | 13 | 2019-07-30 10:42:36.337 UTC | 2016-05-24 09:24:15.05 UTC | null | 937,125 | null | 297,464 | null | 1 | 14 | delphi|components|c++builder|vcl | 3,221 | <p>Of course you want to do this yourself! Writing GUI controls is fun and rewarding!</p>
<p>You could do something like</p>
<pre><code>unit TagEditor;
interface
uses
Windows, Messages, SysUtils, Classes, Controls, StdCtrls, Forms, Graphics,
Types, Menus;
type
TClickInfo = cardinal;
GetTagIndex = word;
const TAG_LOW = 0;
const TAG_HIGH = MAXWORD - 2;
const EDITOR = MAXWORD - 1;
const NOWHERE = MAXWORD;
const PART_BODY = $00000000;
const PART_REMOVE_BUTTON = $00010000;
function GetTagPart(ClickInfo: TClickInfo): cardinal;
type
TTagClickEvent = procedure(Sender: TObject; TagIndex: integer;
const TagCaption: string) of object;
TRemoveConfirmEvent = procedure(Sender: TObject; TagIndex: integer;
const TagCaption: string; var CanRemove: boolean) of object;
TTagEditor = class(TCustomControl)
private
{ Private declarations }
FTags: TStringList;
FEdit: TEdit;
FBgColor: TColor;
FBorderColor: TColor;
FTagBgColor: TColor;
FTagBorderColor: TColor;
FSpacing: integer;
FTextColor: TColor;
FLefts, FRights, FWidths,
FTops, FBottoms: array of integer;
FCloseBtnLefts, FCloseBtnTops: array of integer;
FCloseBtnWidth: integer;
FSpaceAccepts: boolean;
FCommaAccepts: boolean;
FSemicolonAccepts: boolean;
FTrimInput: boolean;
FNoLeadingSpaceInput: boolean;
FTagClickEvent: TTagClickEvent;
FAllowDuplicates: boolean;
FPopupMenu: TPopupMenu;
FMultiLine: boolean;
FTagHeight: integer;
FEditPos: TPoint;
FActualTagHeight: integer;
FShrunk: boolean;
FEditorColor: TColor;
FTagAdded: TNotifyEvent;
FTagRemoved: TNotifyEvent;
FOnChange: TNotifyEvent;
FOnRemoveConfirm: TRemoveConfirmEvent;
FMouseDownClickInfo: TClickInfo;
FCaretVisible: boolean;
FDragging: boolean;
FAutoHeight: boolean;
FNumRows: integer;
procedure SetBorderColor(const Value: TColor);
procedure SetTagBgColor(const Value: TColor);
procedure SetTagBorderColor(const Value: TColor);
procedure SetSpacing(const Value: integer);
procedure TagChange(Sender: TObject);
procedure SetTags(const Value: TStringList);
procedure SetTextColor(const Value: TColor);
procedure ShowEditor;
procedure HideEditor;
procedure EditKeyPress(Sender: TObject; var Key: Char);
procedure mnuDeleteItemClick(Sender: TObject);
procedure SetMultiLine(const Value: boolean);
procedure SetTagHeight(const Value: integer);
procedure EditExit(Sender: TObject);
function Accept: boolean;
procedure SetBgColor(const Value: TColor);
function GetClickInfoAt(X, Y: integer): TClickInfo;
function GetSeparatorIndexAt(X, Y: integer): integer;
procedure CreateCaret;
procedure DestroyCaret;
function IsFirstOnRow(TagIndex: integer): boolean; inline;
function IsLastOnRow(TagIndex: integer): boolean;
procedure SetAutoHeight(const Value: boolean);
protected
{ Protected declarations }
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X: Integer;
Y: Integer); override;
procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); override;
procedure KeyPress(var Key: Char); override;
procedure WndProc(var Message: TMessage); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X: Integer;
Y: Integer); override;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
{ Published declarations }
property TabOrder;
property TabStop;
property Color;
property Anchors;
property Align;
property Tag;
property Cursor;
property BgColor: TColor read FBgColor write SetBgColor;
property BorderColor: TColor read FBorderColor write SetBorderColor;
property TagBgColor: TColor read FTagBgColor write SetTagBgColor;
property TagBorderColor: TColor read FTagBorderColor
write SetTagBorderColor;
property Spacing: integer read FSpacing write SetSpacing;
property Tags: TStringList read FTags write SetTags;
property TextColor: TColor read FTextColor write SetTextColor;
property SpaceAccepts: boolean read FSpaceAccepts write FSpaceAccepts
default true;
property CommaAccepts: boolean read FCommaAccepts write FCommaAccepts
default true;
property SemicolonAccepts: boolean read FSemicolonAccepts
write FSemicolonAccepts default true;
property TrimInput: boolean read FTrimInput write FTrimInput default true;
property NoLeadingSpaceInput: boolean read FNoLeadingSpaceInput
write FNoLeadingSpaceInput default true;
property AllowDuplicates: boolean read FAllowDuplicates write FAllowDuplicates
default false;
property MultiLine: boolean read FMultiLine write SetMultiLine default false;
property TagHeight: integer read FTagHeight write SetTagHeight default 32;
property EditorColor: TColor read FEditorColor write FEditorColor
default clWindow;
property AutoHeight: boolean read FAutoHeight write SetAutoHeight;
property OnTagClick: TTagClickEvent read FTagClickEvent write FTagClickEvent;
property OnTagAdded: TNotifyEvent read FTagAdded write FTagAdded;
property OnTagRemoved: TNotifyEvent read FTagRemoved write FTagRemoved;
property OnChange: TNotifyEvent read FOnChange write FOnChange;
property OnRemoveConfirm: TRemoveConfirmEvent read FOnRemoveConfirm
write FOnRemoveConfirm;
end;
procedure Register;
implementation
uses Math, Clipbrd;
procedure Register;
begin
RegisterComponents('Rejbrand 2009', [TTagEditor]);
end;
function IsKeyDown(const VK: integer): boolean;
begin
IsKeyDown := GetKeyState(VK) and $8000 <> 0;
end;
function GetTagPart(ClickInfo: TClickInfo): cardinal;
begin
result := ClickInfo and $FFFF0000;
end;
{ TTagEditor }
constructor TTagEditor.Create(AOwner: TComponent);
var
mnuItem: TMenuItem;
begin
inherited;
FEdit := TEdit.Create(Self);
FEdit.Parent := Self;
FEdit.BorderStyle := bsNone;
FEdit.Visible := false;
FEdit.OnKeyPress := EditKeyPress;
FEdit.OnExit := EditExit;
FTags := TStringList.Create;
FTags.OnChange := TagChange;
FBgColor := clWindow;
FBorderColor := clWindowFrame;
FTagBgColor := clSkyBlue;
FTagBorderColor := clNavy;
FSpacing := 8;
FTextColor := clWhite;
FSpaceAccepts := true;
FCommaAccepts := true;
FSemicolonAccepts := true;
FTrimInput := true;
FNoLeadingSpaceInput := true;
FAllowDuplicates := false;
FMultiLine := false;
FTagHeight := 32;
FShrunk := false;
FEditorColor := clWindow;
FCaretVisible := false;
FDragging := false;
FPopupMenu := TPopupMenu.Create(Self);
mnuItem := TMenuItem.Create(PopupMenu);
mnuItem.Caption := 'Delete';
mnuItem.OnClick := mnuDeleteItemClick;
mnuItem.Hint := 'Deletes the selected tag.';
FPopupMenu.Items.Add(mnuItem);
TabStop := true;
end;
procedure TTagEditor.EditExit(Sender: TObject);
begin
if FEdit.Text <> '' then
Accept
else
HideEditor;
end;
procedure TTagEditor.mnuDeleteItemClick(Sender: TObject);
begin
if Sender is TMenuItem then
begin
FTags.Delete(TMenuItem(Sender).Tag);
if Assigned(FTagRemoved) then
FTagRemoved(Self);
end;
end;
procedure TTagEditor.TagChange(Sender: TObject);
begin
Invalidate;
if Assigned(FOnChange) then
FOnChange(Self);
end;
procedure TTagEditor.WndProc(var Message: TMessage);
begin
inherited;
case Message.Msg of
WM_SETFOCUS:
Invalidate;
WM_KILLFOCUS:
begin
if FCaretVisible then DestroyCaret;
FDragging := false;
Invalidate;
end;
WM_COPY:
Clipboard.AsText := FTags.DelimitedText;
WM_CLEAR:
FTags.Clear;
WM_CUT:
begin
Clipboard.AsText := FTags.DelimitedText;
FTags.Clear;
end;
WM_PASTE:
begin
if Clipboard.HasFormat(CF_TEXT) then
if FTags.Count = 0 then
FTags.DelimitedText := Clipboard.AsText
else
FTags.DelimitedText := FTags.DelimitedText + ',' + Clipboard.AsText;
end;
end;
end;
function TTagEditor.Accept: boolean;
begin
Assert(FEdit.Visible);
result := false;
if FTrimInput then
FEdit.Text := Trim(FEdit.Text);
if (FEdit.Text = '') or
((not AllowDuplicates) and (FTags.IndexOf(FEdit.Text) <> -1)) then
begin
beep;
Exit;
end;
FTags.Add(FEdit.Text);
result := true;
HideEditor;
if Assigned(FTagAdded) then
FTagAdded(Self);
Invalidate;
end;
procedure TTagEditor.EditKeyPress(Sender: TObject; var Key: Char);
begin
if (Key = chr(VK_SPACE)) and (FEdit.Text = '') and FNoLeadingSpaceInput then
begin
Key := #0;
Exit;
end;
if ((Key = chr(VK_SPACE)) and FSpaceAccepts) or
((Key = ',') and FCommaAccepts) or
((Key = ';') and FSemicolonAccepts) then
Key := chr(VK_RETURN);
case ord(Key) of
VK_RETURN:
begin
Accept;
ShowEditor;
Key := #0;
end;
VK_BACK:
begin
if (FEdit.Text = '') and (FTags.Count > 0) then
begin
FTags.Delete(FTags.Count - 1);
if Assigned(FTagRemoved) then
FTagRemoved(Sender);
end;
end;
VK_ESCAPE:
begin
HideEditor;
Self.SetFocus;
Key := #0;
end;
end;
end;
destructor TTagEditor.Destroy;
begin
FPopupMenu.Free;
FTags.Free;
FEdit.Free;
inherited;
end;
procedure TTagEditor.HideEditor;
begin
FEdit.Text := '';
FEdit.Hide;
// SetFocus;
end;
procedure TTagEditor.KeyDown(var Key: Word; Shift: TShiftState);
begin
inherited;
case Key of
VK_END:
ShowEditor;
VK_DELETE:
Perform(WM_CLEAR, 0, 0);
VK_INSERT:
Perform(WM_PASTE, 0, 0);
end;
end;
procedure TTagEditor.KeyPress(var Key: Char);
begin
inherited;
case Key of
^C:
begin
Perform(WM_COPY, 0, 0);
Key := #0;
Exit;
end;
^X:
begin
Perform(WM_CUT, 0, 0);
Key := #0;
Exit;
end;
^V:
begin
Perform(WM_PASTE, 0, 0);
Key := #0;
Exit;
end;
end;
ShowEditor;
FEdit.Perform(WM_CHAR, ord(Key), 0);
end;
function TTagEditor.GetClickInfoAt(X, Y: integer): TClickInfo;
var
i: integer;
begin
result := NOWHERE;
if (X >= FEditPos.X) and (Y >= FEditPos.Y) then
Exit(EDITOR);
for i := 0 to FTags.Count - 1 do
if InRange(X, FLefts[i], FRights[i]) and InRange(Y, FTops[i], FBottoms[i]) then
begin
result := i;
if InRange(X, FCloseBtnLefts[i], FCloseBtnLefts[i] + FCloseBtnWidth) and
InRange(Y, FCloseBtnTops[i], FCloseBtnTops[i] + FActualTagHeight) and
not FShrunk then
result := result or PART_REMOVE_BUTTON;
break;
end;
end;
function TTagEditor.IsFirstOnRow(TagIndex: integer): boolean;
begin
result := (TagIndex = 0) or (FTops[TagIndex] > FTops[TagIndex-1]);
end;
function TTagEditor.IsLastOnRow(TagIndex: integer): boolean;
begin
result := (TagIndex = FTags.Count - 1) or (FTops[TagIndex] < FTops[TagIndex+1]);
end;
function TTagEditor.GetSeparatorIndexAt(X, Y: integer): integer;
var
i: Integer;
begin
result := FTags.Count;
Y := Max(Y, FSpacing + 1);
for i := FTags.Count - 1 downto 0 do
begin
if Y < FTops[i] then Continue;
if (IsLastOnRow(i) and (X >= FRights[i])) or
((X < FRights[i]) and (IsFirstOnRow(i) or (FRights[i-1] < X))) then
begin
result := i;
if (IsLastOnRow(i) and (X >= FRights[i])) then inc(result);
Exit;
end;
end;
end;
procedure TTagEditor.MouseDown(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
begin
FMouseDownClickInfo := GetClickInfoAt(X, Y);
if GetTagIndex(FMouseDownClickInfo) <> EDITOR then
SetFocus;
end;
procedure TTagEditor.CreateCaret;
begin
if not FCaretVisible then
FCaretVisible := Windows.CreateCaret(Handle, 0, 0, FActualTagHeight);
end;
procedure TTagEditor.DestroyCaret;
begin
if not FCaretVisible then Exit;
Windows.DestroyCaret;
FCaretVisible := false;
end;
procedure TTagEditor.MouseMove(Shift: TShiftState; X, Y: Integer);
var
SepIndex: integer;
begin
inherited;
if IsKeyDown(VK_LBUTTON) and
InRange(GetTagIndex(FMouseDownClickInfo), TAG_LOW, TAG_HIGH) then
begin
FDragging := true;
Screen.Cursor := crDrag;
SepIndex := GetSeparatorIndexAt(X, Y);
TForm(Parent).Caption := IntToStr(SepIndex);
CreateCaret;
if SepIndex = FTags.Count then
SetCaretPos(FLefts[SepIndex - 1] + FWidths[SepIndex - 1] + FSpacing div 2,
FTops[SepIndex - 1])
else
SetCaretPos(FLefts[SepIndex] - FSpacing div 2, FTops[SepIndex]);
ShowCaret(Handle);
Exit;
end;
case GetTagIndex(GetClickInfoAt(X,Y)) of
NOWHERE: Cursor := crArrow;
EDITOR: Cursor := crIBeam;
TAG_LOW..TAG_HIGH: Cursor := crHandPoint;
end;
end;
procedure TTagEditor.MouseUp(Button: TMouseButton; Shift: TShiftState; X,
Y: Integer);
var
pnt: TPoint;
CanRemove: boolean;
ClickInfo: TClickInfo;
i: word;
p: cardinal;
SepIndex: integer;
begin
inherited;
if FDragging then
begin
DestroyCaret;
FDragging := false;
Screen.Cursor := crDefault;
SepIndex := GetSeparatorIndexAt(X, Y);
if not InRange(SepIndex, GetTagIndex(FMouseDownClickInfo),
GetTagIndex(FMouseDownClickInfo) + 1) then
FTags.Move(GetTagIndex(FMouseDownClickInfo), SepIndex -
IfThen(SepIndex > GetTagIndex(FMouseDownClickInfo), 1, 0));
Exit;
end;
ClickInfo := GetClickInfoAt(X, Y);
if ClickInfo <> FMouseDownClickInfo then Exit;
i := GetTagIndex(ClickInfo);
p := GetTagPart(ClickInfo);
case i of
EDITOR:
ShowEditor;
NOWHERE: ;
else
case Button of
mbLeft:
begin
case p of
PART_BODY:
if Assigned(FTagClickEvent) then
FTagClickEvent(Self, i, FTags[i]);
PART_REMOVE_BUTTON:
begin
if Assigned(FOnRemoveConfirm) then
begin
CanRemove := false;
FOnRemoveConfirm(Self, i, FTags[i], CanRemove);
if not CanRemove then Exit;
end;
FTags.Delete(i);
if Assigned(FTagRemoved) then
FTagRemoved(Self);
end;
end;
end;
mbRight:
begin
FPopupMenu.Items[0].Tag := i;
pnt := ClientToScreen(Point(X,Y));
FPopupMenu.Items[0].Caption := 'Delete tag "' + FTags[i] + '"';
FPopupMenu.Popup(pnt.X, pnt.Y);
end;
end;
end;
end;
procedure TTagEditor.Paint;
var
i: integer;
w: integer;
x, y: integer;
R: TRect;
MeanWidth: integer;
S: string;
DesiredHeight: integer;
begin
inherited;
Canvas.Brush.Color := FBgColor;
Canvas.Pen.Color := FBorderColor;
Canvas.Rectangle(ClientRect);
Canvas.Font.Assign(Self.Font);
SetLength(FLefts, FTags.Count);
SetLength(FRights, FTags.Count);
SetLength(FTops, FTags.Count);
SetLength(FBottoms, FTags.Count);
SetLength(FWidths, FTags.Count);
SetLength(FCloseBtnLefts, FTags.Count);
SetLength(FCloseBtnTops, FTags.Count);
FCloseBtnWidth := Canvas.TextWidth('×');
FShrunk := false;
// Do metrics
FNumRows := 1;
if FMultiLine then
begin
FActualTagHeight := FTagHeight;
x := FSpacing;
y := FSpacing;
for i := 0 to FTags.Count - 1 do
begin
FWidths[i] := Canvas.TextWidth(FTags[i] + ' ×') + 2*FSpacing;
FLefts[i] := x;
FRights[i] := x + FWidths[i];
FTops[i] := y;
FBottoms[i] := y + FTagHeight;
if x + FWidths[i] + FSpacing > ClientWidth then
{ no need to make room for the editor, since it can reside on the next row! }
begin
x := FSpacing;
inc(y, FTagHeight + FSpacing);
inc(FNumRows);
FLefts[i] := x;
FRights[i] := x + FWidths[i];
FTops[i] := y;
FBottoms[i] := y + FTagHeight;
end;
FCloseBtnLefts[i] := x + FWidths[i] - FCloseBtnWidth - FSpacing;
FCloseBtnTops[i] := y;
inc(x, FWidths[i] + FSpacing);
end;
end
else // i.e., not FMultiLine
begin
FActualTagHeight := ClientHeight - 2*FSpacing;
x := FSpacing;
y := FSpacing;
for i := 0 to FTags.Count - 1 do
begin
FWidths[i] := Canvas.TextWidth(FTags[i] + ' ×') + 2*FSpacing;
FLefts[i] := x;
FRights[i] := x + FWidths[i];
FTops[i] := y;
FBottoms[i] := y + FActualTagHeight;
inc(x, FWidths[i] + FSpacing);
FCloseBtnLefts[i] := FRights[i] - FCloseBtnWidth - FSpacing;
FCloseBtnTops[i] := y;
end;
FShrunk := x + 64 {FEdit} > ClientWidth;
if FShrunk then
begin
// Enough to remove close buttons?
x := FSpacing;
y := FSpacing;
for i := 0 to FTags.Count - 1 do
begin
FWidths[i] := Canvas.TextWidth(FTags[i]) + 2*FSpacing;
FLefts[i] := x;
FRights[i] := x + FWidths[i];
FTops[i] := y;
FBottoms[i] := y + FActualTagHeight;
inc(x, FWidths[i] + FSpacing);
FCloseBtnLefts[i] := FRights[i] - FCloseBtnWidth - FSpacing;
FCloseBtnTops[i] := y;
end;
if x + 64 {FEdit} > ClientWidth then // apparently no
begin
MeanWidth := (ClientWidth - 2*FSpacing - 64 {FEdit}) div FTags.Count - FSpacing;
x := FSpacing;
for i := 0 to FTags.Count - 1 do
begin
FWidths[i] := Min(FWidths[i], MeanWidth);
FLefts[i] := x;
FRights[i] := x + FWidths[i];
inc(x, FWidths[i] + FSpacing);
end;
end;
end;
end;
FEditPos := Point(FSpacing, FSpacing + (FActualTagHeight - FEdit.Height) div 2);
if FTags.Count > 0 then
FEditPos := Point(FRights[FTags.Count - 1] + FSpacing,
FTops[FTags.Count - 1] + (FActualTagHeight - FEdit.Height) div 2);
if FMultiLine and (FEditPos.X + 64 > ClientWidth) and (FTags.Count > 0) then
begin
FEditPos := Point(FSpacing,
FTops[FTags.Count - 1] + FTagHeight + FSpacing +
(FActualTagHeight - FEdit.Height) div 2);
inc(FNumRows);
end;
DesiredHeight := FSpacing + FNumRows*(FTagHeight+FSpacing);
if FMultiLine and FAutoHeight and (ClientHeight <> DesiredHeight) then
begin
ClientHeight := DesiredHeight;
Invalidate;
Exit;
end;
// Draw
for i := 0 to FTags.Count - 1 do
begin
x := FLefts[i];
y := FTops[i];
w := FWidths[i];
R := Rect(x, y, x + w, y + FActualTagHeight);
Canvas.Brush.Color := FTagBgColor;
Canvas.Pen.Color := FTagBorderColor;
Canvas.Rectangle(R);
Canvas.Font.Color := FTextColor;
Canvas.Brush.Style := bsClear;
R.Left := R.Left + FSpacing;
S := FTags[i];
if not FShrunk then
S := S + ' ×';
DrawText(Canvas.Handle, PChar(S), -1, R, DT_SINGLELINE or DT_VCENTER or
DT_LEFT or DT_END_ELLIPSIS or DT_NOPREFIX);
Canvas.Brush.Style := bsSolid;
end;
if FEdit.Visible then
begin
FEdit.Left := FEditPos.X;
FEdit.Top := FEditPos.Y;
FEdit.Width := ClientWidth - FEdit.Left - FSpacing;
end;
if Focused then
begin
R := Rect(2, 2, ClientWidth - 2, ClientHeight - 2);
SetBkColor(Canvas.Handle, clWhite);
SetTextColor(clBlack);
Canvas.DrawFocusRect(R);
end;
end;
procedure TTagEditor.SetAutoHeight(const Value: boolean);
begin
if FAutoHeight <> Value then
begin
FAutoHeight := Value;
Invalidate;
end;
end;
procedure TTagEditor.SetBgColor(const Value: TColor);
begin
if FBgColor <> Value then
begin
FBgColor := Value;
Invalidate;
end;
end;
procedure TTagEditor.SetBorderColor(const Value: TColor);
begin
if FBorderColor <> Value then
begin
FBorderColor := Value;
Invalidate;
end;
end;
procedure TTagEditor.SetMultiLine(const Value: boolean);
begin
if FMultiLine <> Value then
begin
FMultiLine := Value;
Invalidate;
end;
end;
procedure TTagEditor.SetTagBgColor(const Value: TColor);
begin
if FTagBgColor <> Value then
begin
FTagBgColor := Value;
Invalidate;
end;
end;
procedure TTagEditor.SetTagBorderColor(const Value: TColor);
begin
if FTagBorderColor <> Value then
begin
FTagBorderColor := Value;
Invalidate;
end;
end;
procedure TTagEditor.SetTagHeight(const Value: integer);
begin
if FTagHeight <> Value then
begin
FTagHeight := Value;
Invalidate;
end;
end;
procedure TTagEditor.SetTags(const Value: TStringList);
begin
FTags.Assign(Value);
Invalidate;
end;
procedure TTagEditor.SetTextColor(const Value: TColor);
begin
if FTextColor <> Value then
begin
FTextColor := Value;
Invalidate;
end;
end;
procedure TTagEditor.ShowEditor;
begin
FEdit.Left := FEditPos.X;
FEdit.Top := FEditPos.Y;
FEdit.Width := ClientWidth - FEdit.Left - FSpacing;
FEdit.Color := FEditorColor;
FEdit.Text := '';
FEdit.Show;
FEdit.SetFocus;
end;
procedure TTagEditor.SetSpacing(const Value: integer);
begin
if FSpacing <> Value then
begin
FSpacing := Value;
Invalidate;
end;
end;
initialization
Screen.Cursors[crHandPoint] := LoadCursor(0, IDC_HAND); // Get the normal hand cursor
end.
</code></pre>
<p>which yields</p>
<p><img src="https://privat.rejbrand.se/tageditor.png" alt="Screenshot" /></p>
<p><a href="https://privat.rejbrand.se/tageditor.mp4" rel="noreferrer">Sample video</a></p>
<p><a href="https://privat.rejbrand.se/tagEditorTest.exe" rel="noreferrer">Demo (Compiled EXE)</a></p>
<p>If I get more time later on today I will do some more work on this control, e.g., button highlighting on mouse hover, tag click event, button max width etc.</p>
<p><strong>Update:</strong> Added a lot of features.</p>
<p><strong>Update:</strong> Added multi-line feature.</p>
<p><strong>Update:</strong> More features.</p>
<p><strong>Update:</strong> Added clipboard interface, fixed some issues, etc.</p>
<p><strong>Update:</strong> Added drag-and-drop reordering and fixed some minor issues. By the way, this is the last version I'll post here. Later versions (if there will be any) will be posted at <a href="http://specials.rejbrand.se/dev/controls/" rel="noreferrer">http://specials.rejbrand.se/dev/controls/</a>.</p>
<p><strong>Update:</strong> Added <code>AutoHeight</code> property, made edit box vertically centred, and changed the drag cursor. (Yeah, I couldn't resist making yet another update.)</p> |
12,087,670 | jQuery offset top doesn't work correctly | <p>I'm trying to create an script draw something in an element by mouse and I'm using <code>Raphaeljs</code> to do that.</p>
<p>For correct drawing I need to find <code>top</code> and <code>left</code> of <code>input</code> element. I'm using <code>var offset = $("#input").offset();</code> to get <code>left</code> and <code>top</code>.</p>
<p>But the <code>top</code> value isn't correct. It's <code>10px</code> lower than the real <code>top</code> distance. I think the <code>10px</code> maybe change in different resolutions then I can't add <code>10px</code> to it normally then <strong>I want to know how can I fix the problem!</strong></p>
<p>I uploaded my test <a href="http://matonia.net/t/" rel="noreferrer">here</a>.</p> | 12,097,770 | 3 | 2 | null | 2012-08-23 08:30:16.147 UTC | 5 | 2018-01-29 15:51:11.74 UTC | null | null | null | null | 1,003,464 | null | 1 | 17 | javascript|jquery|raphael|offset | 57,566 | <p>The jQuery <code>.offset()</code> function has <a href="http://api.jquery.com/offset/" rel="noreferrer">this limitation</a>:</p>
<blockquote>
<p>Note: jQuery does not support getting the offset coordinates of hidden elements or accounting for borders, margins, or padding set on the body element.</p>
</blockquote>
<p>The body in this case has a 10px top border, which is why your drawing is off by 10 pixels.</p>
<p>Recommended solution:</p>
<pre><code>var offset = $("#input").offset();
x = x - offset.left - $(document.body).css( "border-left" );
y = y - offset.top + $(document.body).css( "border-top" );
</code></pre> |
12,310,782 | Sorting dropdown alphabetically in AngularJS | <p>I'm populating a dropdown through the use of ng-options which is hooked to a controller that in turn is calling a service. Unfortunately the data coming in is a mess and I need to be able to sort it alphabetically.</p>
<p>You figure that something like <code>$.sortBy</code> would do it but unfortunately it didn't do jack. I know I can sort it via javascript with a helper method <code>function asc(a,b)</code> or something like that but I refuse to believe that there is not cleaner way of doing this plus I don't want to bloat the controller with helper methods. It is something so basic in principle so I don't understand why AngularJS doesn't have this.</p>
<p>Is there a way of doing something like <code>$orderBy('asc')</code>?</p>
<p>Example:</p>
<pre class="lang-html prettyprint-override"><code><select ng-option="items in item.$orderBy('asc')"></select>
</code></pre>
<p>It would be extremely useful to have options in <code>orderBy</code> so you can do whatever you want, whenever you usually try to sort data. </p> | 12,311,163 | 4 | 0 | null | 2012-09-07 02:01:39.767 UTC | 19 | 2018-03-07 05:10:16.253 UTC | 2013-07-07 22:02:01.433 UTC | null | 547,020 | null | 1,607,197 | null | 1 | 161 | angularjs | 154,775 | <p>Angular has an <a href="http://docs.angularjs.org/api/ng.filter:orderBy">orderBy</a> filter that can be used like this:</p>
<pre><code><select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name'"></select>
</code></pre>
<p>See <a href="http://jsfiddle.net/aBccw/">this fiddle</a> for an example.</p>
<p>It's worth noting that if <code>track by</code> is being used it needs to appear after the <code>orderBy</code> filter, like this:</p>
<pre><code><select ng-model="selected" ng-options="f.name for f in friends | orderBy:'name' track by f.id"></select>
</code></pre> |
43,991,246 | Google Cloud Platform: how to monitor memory usage of VM instances | <p>I have recently performed a migration to Google Cloud Platform, and I really like it.</p>
<p>However I can't find a way to monitor the memory usage of the Dataproc VM intances. As you can see on the attachment, the console provides utilization info about CPU, disk and network, but not about memory.</p>
<p>Without knowing how much memory is being used, how is it possible to understand if there is a need of extra memory?</p>
<p><a href="https://i.stack.imgur.com/n3iCd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/n3iCd.png" alt="enter image description here" /></a></p> | 45,721,295 | 7 | 3 | null | 2017-05-16 01:40:53.463 UTC | 6 | 2022-05-09 12:34:47.12 UTC | 2021-02-04 17:17:12.11 UTC | null | 4,128,149 | null | 913,867 | null | 1 | 54 | memory|google-cloud-platform|memory-management|google-compute-engine|google-cloud-dataproc | 45,571 | <p>By installing the <a href="https://cloud.google.com/monitoring/agent/install-agent" rel="nofollow noreferrer">Stackdriver agent</a> in GCE VMs additional <a href="https://cloud.google.com/monitoring/api/metrics#agent" rel="nofollow noreferrer">metrics</a> like memory can be monitored. Stackdriver also offers you <a href="https://cloud.google.com/monitoring/alerts/" rel="nofollow noreferrer">alerting and notification</a> features. Nevertheless agent metrics are only available for <a href="https://cloud.google.com/stackdriver/pricing" rel="nofollow noreferrer">premium tier accounts</a>.</p>
<p>See this <a href="https://stackoverflow.com/questions/68403172/dataproc-vm-memory-and-local-disk-usage-metrics">answer</a> for Dataproc VMs.</p> |
18,783,427 | Nested Try and Catch blocks | <p>I have nested <code>try-catch</code> blocks in a custom C# code for SharePoint. I want to execute the code in only one <code>catch</code> block (the inner one) when the code inside the inner <code>try</code> block throws an exception.</p>
<pre><code>try
{
//do something
try
{
//do something if exception is thrown, don't go to parent catch
}
catch(Exception ex) {...}
}
catch(Exception ex)
{ .... }
</code></pre>
<p>I know I can use different types of exceptions but that's not what I am looking for.</p>
<p><strong>Summary</strong></p>
<p>If exception occurs, I don't want it to reach the parent <code>catch</code> in addition to the inner <code>catch</code>.</p> | 18,783,484 | 2 | 3 | null | 2013-09-13 09:57:46.76 UTC | 9 | 2018-07-27 20:10:35.247 UTC | 2016-10-19 09:58:48.487 UTC | user6269864 | null | null | 1,668,069 | null | 1 | 28 | c#|web-services|exception | 54,465 | <p>If you don't want to execute the outer exception in that case you should not throw the exception from the inner catch block.</p>
<pre><code>try
{
//do something
try
{
//do something IF EXCEPTION HAPPENs don't Go to parent catch
}
catch(Exception ex)
{
// logging and don't use "throw" here.
}
}
catch(Exception ex)
{
// outer logging
}
</code></pre> |
3,613,682 | How do you restore a corrupted object in a git repository (for newbies)? | <p>I tried to open my repository today and it came up with no commit history. Everything I tried (git status, git log, git checkout...) threw an error about a corrupt object.</p>
<p>I researched this problem online and found the <a href="http://www.kernel.org/pub/software/scm/git/docs/howto/recover-corrupted-blob-object.txt" rel="noreferrer">article</a> by Linus Torvalds, but got lost at the point where he found the broken link ID: none of my file IDs, tree or blob, match the culprit ID thrown by the error message.</p>
<p>I then returned to the article on recovering <a href="https://stackoverflow.com/questions/801577/how-to-recover-git-objects-damaged-by-hard-disk-failure">"git objects damaged by hard disk failure"</a> and (after moving the culprit object out of the way) worked my way through until </p>
<pre><code>$ cat packed-refs
</code></pre>
<p>at which point my computer said: <code>cat: packed-refs: No such file or directory</code>
I skipped that step and did the</p>
<pre><code>$ git fsck --full
</code></pre>
<p>and got the appropriate output, but then I was supposed to copy the culprit (or what I was referring to as the culprit, the sha1 ID thrown by the error) from a backup repository back into the main repository, then copy the missing objects from the backup repository into the main repository, as far as I can tell; and I don't want to do anything <em>too</em> drastic or I might force something I can't unforce later.</p>
<p>So my question(s) is (are), was I supposed to have made a backup (<em>ooh, newbie alert</em>), or was that what happened when I unpacked the .pack file? And is the "culprit" I'm copying back actually a clean file, i.e. not corrupted?</p>
<p>(I think it only fair to tell you that I was initially confused by a simple dash in Torvalds' file between the "git" and "fsck." So I'm <em>REALLY</em> new at this.)</p>
<h2>BUG-LIST</h2>
<h3>Original bug:</h3>
<pre><code>$ git status
fatal: object 016660b7605cfc2da85f631bbe809f7cb7962608 is corrupted
</code></pre>
<h3>Bug after moving corrupt object:</h3>
<pre><code>$ git status
fatal: bad object HEAD
$ git fsck --full
error: HEAD: invalid sha1 pointer 016660b7605cfc2da85f631bbe809f7cb7962608
error: refs/heads/RPG does not point to a valid object!
dangling tree 2c1033501b82e301d47dbf53ba0a199003af25a8
dangling blob 531aca5783033131441ac7e132789cfcad82d06d
dangling blob 74a47ff40a8c5149a8701c2f4b29bba408fa36f5
dangling blob b8df4d9751c0518c3560e650b21a182ea6d7bd5e
dangling blob fc2d15aead4bd0c197604a9f9822d265bb986d8b
$ git ls-tree 2c1033501b82e301d47dbf53ba0a199003af25a8
040000 tree 4a8b0b3747450085b1cd920c22ec82c18d9311bd folder1
040000 tree 33298295f646e8b378299191ce20b4594f5eb625 folder2
040000 tree dec82bad6283fc7fcc869c20fdea9f8588a2f1b2 folder3
040000 tree 4544967c6b04190f4c95b516ba8a86cab266a872 folder4
$ git ls-tree dec82bad6283fc7fcc869c20fdea9f8588a2f1b2
100644 blob 67bda6df733f6cd76fc0fc4c8a6132d8015591d8 fileA
100644 blob 4cb7272c9e268bfbd83a04e568d7edd87f78589c fileB
100644 blob ce9e0f2cc4d3b656fa30340afbdfed47fe35f3ef fileC
$ git ls-tree 4544967c6b04190f4c95b516ba8a86cab266a872
100644 blob d64fe3add8328d81b1f31c9dbd528956ab391fb6 fileD
100644 blob d1ebd7df7082abc5190d87caa821bf3edb7b68e8 fileE
100644 blob bb6cd264e47a3e5bc7beadf35ea13bac86024b02 ...
100644 blob 995d622b9012f4ef69921091d1e1a73f32aa94e6
100644 blob 9141dbd2b1c7931a6461195934b6599f5dfb485a
100644 blob ab128da1d82907cd0568448dc089a7996d5f79d3
100644 blob 57b11a7eb408a79739d2bb60a0dc35c591340d18
100644 blob 118105291c1c6ca4a01744889ffafbb018bc7ed3
100644 blob 86b1dfda56d0603f16910228327751f869d16bdc
100644 blob 077fe0cddde0d0be9d0974f928f66815caca7b76
100644 blob c0b32fd0450f21994bdc53ea83d3cf0bccd74004
100644 blob 37b87a4d11453468c4ae04572db5d322cd2d1d80
100644 blob 79d39f8d4e57fa3a71664598a63b6dfd88149638
100644 blob ee07bbe3e8cb5d6bb79fb0cd52cfbc9bd830498d files
$ git ls-tree 33298295f646e8b378299191ce20b4594f5eb625
100644 blob f9d6f45cd028aec97f761f00c5f4f2f6b50fb925 MoreFiles
100644 blob 0cb9eed1d0dd9214d54a03af1bda21f37b8c0d02
100644 blob 198e4f97ece735cce47b7e99b54f1b5fa99fabf5
100644 blob fc004212fa8e483e5a8ab35b508027c7a9a1cbfa
100644 blob 0c7d74c7a9a8337b4a9f20802b63d71d42287f89
$ git ls-tree 4a8b0b3747450085b1cd920c22ec82c18d9311bd
100644 blob 0320f5b23dd7cce677fac60b9ad03f418cff5c88 oneLASTfile
</code></pre>
<h3>After moving the corrupted object back:</h3>
<pre><code>$ git log --raw --all
fatal: object 016660b7605cfc2da85f631bbe809f7cb7962608 is corrupted
$ cat packed-refs
cat: packed-refs: No such file or directory
$ git fsck --full
fatal: object 016660b7605cfc2da85f631bbe809f7cb7962608 is corrupted
</code></pre>
<h3>After moving the file back out:</h3>
<pre><code>$ git fsck --full`
error: HEAD: invalid sha1 pointer 016660b7605cfc2da85f631bbe809f7cb7962608
error: refs/heads/RPG does not point to a valid object!
dangling tree 2c1033501b82e301d47dbf53ba0a199003af25a8
dangling blob 531aca5783033131441ac7e132789cfcad82d06d
dangling blob 74a47ff40a8c5149a8701c2f4b29bba408fa36f5
dangling blob b8df4d9751c0518c3560e650b21a182ea6d7bd5e
dangling blob fc2d15aead4bd0c197604a9f9822d265bb986d8b
</code></pre>
<h3>After unpacking the .pack file:</h3>
<pre><code>$ git log
fatal: bad object HEAD
$ cat packed-refs
cat: packed-refs: No such file or directory
$ git fsck --full
error: HEAD: invalid sha1 pointer 016660b7605cfc2da85f631bbe809f7cb7962608
error: refs/heads/RPG does not point to a valid object!
dangling tree 2c1033501b82e301d47dbf53ba0a199003af25a8
dangling blob 531aca5783033131441ac7e132789cfcad82d06d
dangling blob 74a47ff40a8c5149a8701c2f4b29bba408fa36f5
dangling blob b8df4d9751c0518c3560e650b21a182ea6d7bd5e
dangling blob fc2d15aead4bd0c197604a9f9822d265bb986d8b
</code></pre> | 3,619,208 | 3 | 5 | null | 2010-08-31 22:29:18.083 UTC | 9 | 2016-12-21 02:14:15.83 UTC | 2017-05-23 12:25:33.503 UTC | null | -1 | null | 436,424 | null | 1 | 31 | git|recovery | 65,055 | <p>Okay, so. We can see from the second error message that the corrupt object which you moved was a commit. (HEAD was pointing to it!) Unfortunately, this means that it's hard to manually repair it. (By "hard" I mean likely impossible unless you can remember exactly what the commit message was and what time you made the commit.) Fortunately, this does mean that it's easy to resurrect a new commit with the same file contents - you'll just have to write a new message for it.</p>
<p>Before you start, have a look at the contents of <code>.git/HEAD</code> - if it's a branch name, remember that for later.</p>
<p>First, we need to figure out what the parent of this commit should've been. You can use <code>git reflog</code> to look at the reflog of HEAD, and find the SHA1 of where HEAD was just before you made commit 016660b. It should look something like this:</p>
<pre><code>016660b HEAD@{n}: commit: <subject of commit>
1234abc HEAD@{n-1}: ...
</code></pre>
<p>You can copy the SHA1 of the previous position of HEAD, and check out that commit:</p>
<pre><code>git checkout 1234abc
</code></pre>
<p>Then you can read in the tree that your corrupted commit had:</p>
<pre><code>git read-tree 2c1033501b82e301d47dbf53ba0a199003af25a8
</code></pre>
<p>And then commit!</p>
<pre><code>git commit
</code></pre>
<p>Now, there's some question here about what should've happened to your branches. If HEAD was pointing to a branch (say master) which in turn pointed to the corrupted commit, we definitely want to fix that up:</p>
<pre><code>git branch -d master # remove the original master branch
git checkout -b master # recreate it here
</code></pre>
<p>If there are other branches which contained the corrupted commit, you'll have to do some restoration on them too - let me know if you need help with that.</p> |
26,197,347 | "Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC | <p>While attempting to compile my C program, running the following command: </p>
<pre><code>gcc pthread.c -o pthread
</code></pre>
<p>Returns:</p>
<blockquote>
<p>Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.</p>
</blockquote>
<p>and my code does not compile.</p>
<p>Why is this happening and how can I fix this problem?</p> | 26,197,363 | 11 | 8 | null | 2014-10-04 21:25:32.237 UTC | 61 | 2019-12-26 06:25:55.51 UTC | 2016-09-26 18:39:29.42 UTC | null | 128,421 | null | 2,566,879 | null | 1 | 492 | ios|xcode|gcc | 209,277 | <p>Open up Xcode, and accept the new user agreement. This was happening because a new version of Xcode was downloaded and the new agreement was not accepted.</p> |
11,017,332 | show/hide div with slide left\right animation | <p>I tried this here: <a href="http://jsfiddle.net/92HXT/1/" rel="noreferrer">http://jsfiddle.net/92HXT/1/</a> but it does not work.
It only works if I use <code>show("slow")</code>/<code>hide("slow")</code>.</p>
<p>Thanks.</p> | 11,017,572 | 2 | 1 | null | 2012-06-13 14:41:11.353 UTC | 5 | 2018-08-13 11:17:52.087 UTC | 2012-06-13 18:03:47.247 UTC | null | 865,552 | null | 1,453,918 | null | 1 | 7 | jquery|jquery-ui | 82,426 | <p>While not the sharpest animation, I have enabled it to behave the way I think you're wanting by finding the parent and hiding all the siblings. I'm not sure yet why this slides the elements out to the left whereas a direct call to <code>.siblings()</code> doesn't seem to.</p>
<p><a href="http://jsfiddle.net/92HXT/10/" rel="noreferrer">Seen here</a>.</p>
<p>As others have mentioned, using classes to identify a group of items is the correct approach instead of by ID.</p>
<p><strong>Update</strong>:</p>
<p>While I'm still not sure why siblings() doesn't find the siblings to the div you've found by ID, I'm suspecting it has to do something with the process of showing / hiding or possibly even using the sliding animation. Here is my suggested jQuery/jQueryUI:</p>
<pre><code>$('a.view-list-item').click(function () {
var divname= this.name;
$("#"+divname).show("slide", { direction: "left" }, 1000);
$("#"+divname).parent().siblings(":visible").hide("slide", { direction: "left" }, 1000);
});
</code></pre>
<p>Here is the <a href="http://jsfiddle.net/92HXT/13/" rel="noreferrer">updated version</a>.</p>
<p><strong>Update</strong>:</p>
<p>An <a href="http://jsfiddle.net/92HXT/15/" rel="noreferrer">excellent update</a> to the solution by @jesus.tesh</p>
<p><strong>Update</strong>:</p>
<p>A <a href="http://jsfiddle.net/erwinjulius/CgM3x/" rel="noreferrer">behavior update</a> to the solution by @erwinjulius.
I changed DIVs positioning so it behaves better, allowing user to click on links quickly without breaking the animation.
Added white background and left-padding just for better effect presentation.</p> |
11,314,545 | Casting enum definition to unsigned int | <p>According to this SO post:<br>
<a href="https://stackoverflow.com/questions/366017/what-is-the-size-of-an-enum-in-c">What is the size of an enum in C?</a><br>
enum types have <code>signed int</code> type. </p>
<p>I would like to convert an enum definition from <code>signed int</code> to <code>unsigned int</code>. </p>
<p>For example, on my platform an <code>unsigned int</code> is 32-bits wide.
I want to create an enum:</p>
<pre><code>typedef enum hardware_register_e
{
REGISTER_STATUS_BIT = (1U << 31U)
} My_Register_Bits_t;
</code></pre>
<p>My compiler is complaining that the above definition is out of range (which it is for a <code>signed int</code>). </p>
<p>How do I declare <code>unsigned int</code> <code>enum</code> values? </p>
<h2>Edit 1:</h2>
<ol>
<li>The preference is not to expand to 64 bits (because the code resides
in an embedded system).</li>
<li>Due to skill limitations, C++ is not allowed for this project. :-( </li>
</ol>
<h2>Edit 2:</h2>
<ul>
<li>Compiler is IAR Embedded Workbench for ARM7.</li>
</ul> | 11,314,760 | 4 | 9 | null | 2012-07-03 15:44:27.14 UTC | 3 | 2012-07-05 17:11:49.1 UTC | 2017-05-23 12:02:02.617 UTC | null | -1 | null | 225,074 | null | 1 | 9 | c|casting|enums|unsigned-integer|iar | 46,645 | <p>Unfortunately ISO C standard (c99 6.4.4.3) states that the enumeration constants are of type <code>int</code>. If you compile the above with e.g. <code>gcc -W -std=c89 -pedantic</code>, it will issue a warning <code>ISO C restricts enumerator values to range of ‘int’ [-pedantic]</code>. Some embedded compilers may not accept the code at all.</p>
<p>If your compiler is of the pickier variety, you can workaround the issue by using</p>
<pre><code>typedef enum hardware_register_e
{
REGISTER_STATUS_BIT = -2147483648 /* 1<<31, for 32-bit two's complement integers */
} hardware_register_t;
</code></pre>
<p>but it works correctly only if <code>int</code> is 32-bit two's complement type on your architecture. It is on all 32-bit and 64-bit architectures I have ever used or heard of.</p>
<p>Edited to add: ARM7 uses 32-bit two's complement <code>int</code> type, so the above should work fine. I only recommend you keep the comment explaining that the actual value is <code>1<<31</code>. You never know if somebody ports the code, or uses another compiler. If the new compiler issues a warning, the comment on the same line should make it trivial to fix. Personally, I'd wrap the code in a conditional, perhaps</p>
<pre><code>typedef enum hardware_register_e
{
#ifdef __ICCARM__
REGISTER_STATUS_BIT = -2147483648 /* 1<<31, for 32-bit two's complement integers */
#else
REGISTER_STATUS_BIT = 1 << 31
#endif
} hardware_register_t;
</code></pre> |
11,088,612 | JavaFX select item in ListView | <p>Hi I am trying to set focus on an item in a listview. After a user opens a file the item is added to the listview, but the issue I am having is that the listview is not setting focus on the new item that was added. I have to click the item in the listview to set focus to it. Is there a way to have the listview to highlight the newly added item right away in JavaFX 2.1 . </p> | 11,097,321 | 1 | 0 | null | 2012-06-18 18:13:10.043 UTC | 4 | 2012-06-19 08:34:35.947 UTC | 2012-06-18 18:26:23.617 UTC | null | 829,571 | null | 1,426,949 | null | 1 | 22 | java|javafx-2 | 43,730 | <p>Assuming that the newly added item has an index of <code>N</code>,<br>
Selecting it:</p>
<pre><code>listView.getSelectionModel().select(N);
</code></pre>
<p>Focusing on it:</p>
<pre><code>listView.getFocusModel().focus(N);
</code></pre>
<p>Scrolling to it:</p>
<pre><code>listView.scrollTo(N);
</code></pre>
<p>You can use combinations of these and preferably in <code>Platform.runLater()</code>.<br>
Scroll then select:</p>
<pre><code>Platform.runLater(new Runnable() {
@Override
public void run() {
listView.scrollTo(N);
listView.getSelectionModel().select(N);
}
});
</code></pre> |
11,302,271 | How to properly abort a node.js promise chain using Q? | <p>I'm using <a href="https://github.com/kriskowal/q/">the Q module</a> for Node.js in attempts to avoid the "pyramid of doom" in scenarios where I have many steps. For example:</p>
<pre><code>function doTask(task, callback)
{
Q.ncall(task.step1, task)
.then(function(result1){
return Q.ncall(task.step2, task);
})
.then(function(result2){
return Q.ncall(task.step3, task);
})
.fail(callback).end();
}
</code></pre>
<p>Essentially this seems to work; if an error is thrown by any of the task steps, it is passed to the callback (though I would be welcome to improvements, as I am new to node.js promises). However, I have a problem when I need to abort the task-chain early. For example, if result1 is successfully returned I might want to call the callback early and abort the rest, but my attempts to do so are failing...</p>
<pre><code>function doTask(task, callback)
{
Q.ncall(task.step1, task)
.then(function(result1){
if(result1)
{// the rest of the task chain is unnecessary
console.log('aborting!');
callback(null, result1);
return null;
}
return Q.ncall(task.step2, task);
})
.then(function(result2){
console.log('doing step 3...');
return Q.ncall(task.step3, task);
})
.fail(callback).end();
}
</code></pre>
<p>In this example, I see both "aborting!" and "doing step 3..." printed.</p>
<p>I'm sure I'm merely misunderstanding some basic principles here, so would appreciate any help. Thanks!</p> | 18,602,945 | 3 | 1 | null | 2012-07-02 22:57:10.18 UTC | 10 | 2016-04-11 18:08:17.26 UTC | 2015-01-30 13:24:35.53 UTC | null | 1,048,572 | null | 559,301 | null | 1 | 36 | node.js|promise|q | 29,177 | <p>Any errors that are thrown within the promise chain will cause the entire stack to be aborted early and control is given to the error-back path. (in this case, the fail() handler) When you detect a certain state which causes you to want to abort the promise chain, then just throw a very specific error, which you trap in the error-back and ignore (if you so choose)</p>
<pre><code>function doTask(task, callback)
{
Q.ncall(task.step1, task)
.then(function(result1){
if(result1 == 'some failure state I want to cause abortion')
{// the rest of the task chain is unnecessary
console.log('aborting!');
throw new Error('abort promise chain');
return null;
}
return Q.ncall(task.step2, task);
})
.then(function(result2){
console.log('doing step 3...');
return Q.ncall(task.step3, task);
})
.fail(function(err) {
if (err.message === 'abort promise chain') {
// just swallow error because chain was intentionally aborted
}
else {
// else let the error bubble up because it's coming from somewhere else
throw err;
}
})
.end();
}
</code></pre> |
11,382,473 | Resize external website content to fit iFrame width | <p>I have a webpage with 2 iFrames in it. Both of them are with fixed width and height. I am loading external websites inside them. How can I resize those external websites width to fit with the iFrame (like mobile browsers does by changing viewport)?</p> | 11,382,661 | 2 | 1 | null | 2012-07-08 10:38:44.367 UTC | 23 | 2018-03-07 00:28:25.023 UTC | null | null | null | null | 606,075 | null | 1 | 48 | javascript|html|css|iframe|web | 181,411 | <p>What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.</p>
<p>E.g.</p>
<pre><code><iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>
</code></pre> |
11,054,213 | Advantage of 2's complement over 1's complement? | <p>What is the advantage of 2's complement over 1's complement in negative number representation in binary number system? How does it affect the range of values stored in a certain bit representation of number in binary system?</p> | 11,054,367 | 6 | 2 | null | 2012-06-15 15:55:22.353 UTC | 28 | 2018-12-05 16:46:18.473 UTC | 2018-12-05 16:46:18.473 UTC | null | 161,052 | null | 1,066,797 | null | 1 | 67 | binary|negative-number | 115,462 | <p>The primary advantage of two's complement over one's complement is that two's complement only has one value for zero. One's complement has a "positive" zero and a "negative" zero.</p>
<p>Next, to add numbers using one's complement you have to first do binary addition, then add in an end-around carry value.</p>
<p>Two's complement has only one value for zero, and doesn't require carry values.</p>
<p>You also asked how the range of values stored are affected. Consider an eight-bit integer value, the following are your minimum and maximum values:</p>
<pre><code>Notation Min Max
========== ==== ====
Unsigned: 0 255
One's Comp: -127 +127
Two's Comp: -128 +127
</code></pre>
<p>References:</p>
<ul>
<li><a href="http://en.wikipedia.org/wiki/Signed_number_representations" rel="noreferrer">http://en.wikipedia.org/wiki/Signed_number_representations</a></li>
<li><a href="http://en.wikipedia.org/wiki/Ones%27_complement" rel="noreferrer">http://en.wikipedia.org/wiki/Ones%27_complement</a></li>
<li><a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="noreferrer">http://en.wikipedia.org/wiki/Two%27s_complement</a></li>
</ul> |
11,308,328 | SetupSequence in Moq | <p>I want a mock that returns <code>0</code> the first time, then returns <code>1</code> anytime the method is called thereafter. The problem is that if the method is called 4 times, I have to write:</p>
<pre><code>mock.SetupSequence(x => x.GetNumber())
.Returns(0)
.Returns(1)
.Returns(1)
.Returns(1);
</code></pre>
<p>Otherwise, the method returns null.</p>
<p>Is there any way to write that, after the initial call, the method returns <code>1</code>?</p> | 11,308,543 | 6 | 0 | null | 2012-07-03 09:46:23.993 UTC | 12 | 2022-04-26 20:55:18.89 UTC | 2021-08-09 22:48:06.3 UTC | null | 6,789,816 | null | 375,460 | null | 1 | 90 | c#|unit-testing|mocking|moq | 54,074 | <p>That's not particulary fancy, but I think it would work:</p>
<pre><code> var firstTime = true;
mock.Setup(x => x.GetNumber())
.Returns(()=>
{
if(!firstTime)
return 1;
firstTime = false;
return 0;
});
</code></pre> |
11,441,666 | Java error: Comparison method violates its general contract | <p>I saw many questions about this, and tried to solve the problem, but after one hour of googling and a lots of trial & error, I still can't fix it. I hope some of you catch the problem.</p>
<p>This is what I get:</p>
<pre class="lang-none prettyprint-override"><code>java.lang.IllegalArgumentException: Comparison method violates its general contract!
at java.util.ComparableTimSort.mergeHi(ComparableTimSort.java:835)
at java.util.ComparableTimSort.mergeAt(ComparableTimSort.java:453)
at java.util.ComparableTimSort.mergeForceCollapse(ComparableTimSort.java:392)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:191)
at java.util.ComparableTimSort.sort(ComparableTimSort.java:146)
at java.util.Arrays.sort(Arrays.java:472)
at java.util.Collections.sort(Collections.java:155)
...
</code></pre>
<p>And this is my comparator:</p>
<pre><code>@Override
public int compareTo(Object o) {
if(this == o){
return 0;
}
CollectionItem item = (CollectionItem) o;
Card card1 = CardCache.getInstance().getCard(cardId);
Card card2 = CardCache.getInstance().getCard(item.getCardId());
if (card1.getSet() < card2.getSet()) {
return -1;
} else {
if (card1.getSet() == card2.getSet()) {
if (card1.getRarity() < card2.getRarity()) {
return 1;
} else {
if (card1.getId() == card2.getId()) {
if (cardType > item.getCardType()) {
return 1;
} else {
if (cardType == item.getCardType()) {
return 0;
}
return -1;
}
}
return -1;
}
}
return 1;
}
}
</code></pre>
<p>Any idea?</p> | 11,441,813 | 12 | 7 | null | 2012-07-11 21:20:15.19 UTC | 27 | 2022-08-09 09:28:32.727 UTC | 2017-03-06 16:12:47.06 UTC | null | 1,420,715 | null | 1,420,715 | null | 1 | 109 | java|compare|migration|java-7|comparator | 174,658 | <p>The exception message is actually pretty descriptive. The contract it mentions is <em>transitivity</em>: if <code>A > B</code> and <code>B > C</code> then for any <code>A</code>, <code>B</code> and <code>C</code>: <code>A > C</code>. I checked it with paper and pencil and your code seems to have few holes:</p>
<pre><code>if (card1.getRarity() < card2.getRarity()) {
return 1;
</code></pre>
<p>you do not return <code>-1</code> if <code>card1.getRarity() > card2.getRarity()</code>.</p>
<hr>
<pre><code>if (card1.getId() == card2.getId()) {
//...
}
return -1;
</code></pre>
<p>You return <code>-1</code> if ids aren't equal. You should return <code>-1</code> or <code>1</code> depending on which id was bigger.</p>
<hr>
<p>Take a look at this. Apart from being much more readable, I think it should actually work:</p>
<pre><code>if (card1.getSet() > card2.getSet()) {
return 1;
}
if (card1.getSet() < card2.getSet()) {
return -1;
};
if (card1.getRarity() < card2.getRarity()) {
return 1;
}
if (card1.getRarity() > card2.getRarity()) {
return -1;
}
if (card1.getId() > card2.getId()) {
return 1;
}
if (card1.getId() < card2.getId()) {
return -1;
}
return cardType - item.getCardType(); //watch out for overflow!
</code></pre> |
13,159,089 | Marshalling nested classes with JAXB | <p>I am trying to marshal some classes I designed, with standard JAXB, the classes all have void constructors, this is my first attempt at using JAXB or marshalling/unmarhslling in any language for that matter but as I understand it JAXB should be able to marshall them without a XSD.</p>
<p>The classes are as follow:</p>
<pre><code>@XmlRootElement(name="place")
class Place {
@XmlAttribute
//various fields and get set methods
public Place() {
}
}
@XmlRootElement(name="Arc")
class Arc {
// various fields and get set methods
@XmlAttribute
Place p;
public setPlace(Place p) {
// ...
}
public Arc() {
}
}
@XmlRootElement(name="Transition")
class Transition {
Arc[] a;
public Transition() {
}
}
</code></pre>
<p>I can marshall the <code>Place</code> class but not the <code>Arc</code> class, the <code>Transition</code> I didn't even try, the classes have the <code>@XMLPropriety</code> tags but when it reaches the nested <code>Place</code> class JAXB doesn't seem to understand which XML object to map it too.</p>
<p>If there is another tag I should be using for the nested class or there's another error I'm overlooking? </p> | 13,161,255 | 2 | 2 | null | 2012-10-31 13:27:54.393 UTC | 3 | 2018-05-09 08:46:09 UTC | 2012-11-01 20:29:12.573 UTC | null | 1,019,515 | null | 1,019,515 | null | 1 | 8 | java|xml|jaxb | 38,644 | <p>There is nothing special you need to do to handle nested classes with any <a href="http://jcp.org/en/jsr/detail?id=222" rel="noreferrer"><strong>JAXB (JSR-222)</strong></a> implementation. Below is a complete example where only one <code>@XmlRootElement</code> annotation is used:</p>
<p><strong>Transition</strong></p>
<pre><code>package forum13159089;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
class Transition {
Arc[] a;
public Arc[] getA() {
return a;
}
public void setA(Arc[] a) {
this.a = a;
}
}
</code></pre>
<p><strong>Arc</strong></p>
<pre><code>package forum13159089;
class Arc {
Place p;
public Place getPlace() {
return p;
}
public void setPlace(Place p) {
this.p = p;
}
}
</code></pre>
<p><strong>Place</strong></p>
<pre><code>package forum13159089;
class Place {
}
</code></pre>
<p><strong>Demo</strong></p>
<pre><code>package forum13159089;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Transition.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum13159089/input.xml");
Transition transition = (Transition) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(transition, System.out);
}
}
</code></pre>
<p><strong>input.xml/Output</strong></p>
<pre><code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<transition>
<a>
<place/>
</a>
<a>
<place/>
</a>
</transition>
</code></pre>
<p><strong>For More Information</strong></p>
<ul>
<li><a href="http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html" rel="noreferrer">http://blog.bdoughan.com/2012/07/jaxb-no-annotations-required.html</a></li>
<li><a href="http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html" rel="noreferrer">http://blog.bdoughan.com/2010/09/jaxb-collection-properties.html</a></li>
<li><a href="http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted" rel="noreferrer">http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted</a></li>
</ul>
<hr />
<p><strong>Note:</strong> <code>@XMLProperty</code> is not a JAXB annotation.</p> |
13,179,620 | Force overflow menu in ActionBarSherlock | <p>I want the 4.0+ overflow menu to be used on pre ICS devices (2.3 - 2.1). I'm using HoloEverywhere with ActionBarSherlock.</p>
<p>I tried the following solution:</p>
<p><a href="https://stackoverflow.com/questions/10509510/actionbarsherlock-holoeverywhere-forcing-overflow">ActionBarSherlock & HoloEverywhere - Forcing Overflow?</a></p>
<p>but it does not work because <code>absForceOverflow</code> does not exist. Was it removed in the newest version or something? I've checked the <code>R</code> files of both ABS and HE library projects and the field is simply not there.</p>
<p>My app's theme is set to <code>@style/Holo.Theme.Sherlock.Light</code> and that is the theme that i was trying to inherit from and add the <code>absForceOverflow</code> parameter set to <code>true</code>.</p> | 13,180,285 | 4 | 0 | null | 2012-11-01 14:51:22.077 UTC | 16 | 2016-01-19 16:02:57.173 UTC | 2017-05-23 12:24:23.877 UTC | null | -1 | null | 567,200 | null | 1 | 26 | android|android-actionbar|actionbarsherlock|android-holo-everywhere | 16,320 | <p>If you are using Version 4.2.0, then <code>.ForceOverflow</code> themes have in fact been removed.</p>
<p><strong>Source:</strong> <a href="https://github.com/JakeWharton/ActionBarSherlock/blob/master/CHANGELOG.md#readme" rel="nofollow noreferrer">Version 4.2.0 Changelog</a></p>
<p>Extract of the Change Log:</p>
<pre><code>Add SearchView widget for standard search interaction (API 8+ only)
Fix: ShareActionProvider in the split action bar no longer fills the entire screen.
Fix: ShareActionProvider now does file I/O on a background thread.
Fix: Automatically correct ColorDrawable not respecting bounds when used as a stacked background.
Fix: Ensure fragments collection is present before dispatching events.
Fix: XML-defined onClick searches the correct context for the declared method.
Fix: Ensure action mode start/finish callbacks are invoked on the activity for the native action bar.
Fix: Allow tab callbacks to have a fragment transaction instance for any FragmentActivity.
Fix: Ensure CollapsibleActionView callbacks are dispatched in both native and compatbility action bars.
Fix: Remove .ForceOverflow themes. These never should have been included.
</code></pre>
<p>If you absolutely need to force Overflow, you will need to download an earlier version of ABS. You can get a list of download as per their release history here: <a href="http://actionbarsherlock.com/download.html" rel="nofollow noreferrer">http://actionbarsherlock.com/download.html</a></p>
<p>I personally still use the ABS version 4.1.0 since I do not currently want to make ancillary changes in my app. I also use this in my <code>theme.xml</code>:</p>
<pre><code><style name="MyTheme" parent="@style/Theme.Sherlock.ForceOverflow">
<item name="android:windowBackground">@color/background</item>
<item name="actionBarStyle">@style/Widget.Styled.ActionBar</item>
<item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item>
</style>
<style name="MyTheme.ForceOverflow">
<item name="absForceOverflow">true</item>
</style>
</code></pre>
<p>And while applying a theme for an <code>Activity</code> in the <code>manifest.xml</code>, I use this as the attribute: <code>"@style/Theme.SociallyYOU"</code></p>
<p>Again, if you must absolutely force overflow, you might also want to read CommonsWare's thought on the same in another question here: <a href="https://stackoverflow.com/a/12872537/450534">https://stackoverflow.com/a/12872537/450534</a>.</p>
<p><strong>NOTE:</strong> That being said, it is always better to use the latest version if the trade offs aren't to critical. By posting how I force the overflow menu, I am neither suggesting that you use an older version nor do I recommend that. It is merely informing you of the possibilities.</p> |
12,806,584 | What is better "int 0x80" or "syscall" in 32-bit code on Linux? | <p>I study the Linux kernel and found out that for x86_64 architecture the interrupt <code>int 0x80</code> doesn't work for calling system calls<sup>1</sup>.</p>
<p><strong>For the i386 architecture (32-bit x86 user-space), what is more preferable: <code>syscall</code> or <code>int 0x80</code> and why?</strong></p>
<p>I use Linux kernel version 3.4.</p>
<hr>
<p>Footnote 1: <code>int 0x80</code> does work in some cases in 64-bit code, but is never recommended. <a href="https://stackoverflow.com/questions/46087730/what-happens-if-you-use-the-32-bit-int-0x80-linux-abi-in-64-bit-code">What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code?</a></p> | 12,806,910 | 3 | 6 | null | 2012-10-09 18:56:52.323 UTC | 34 | 2020-06-10 07:32:45.913 UTC | 2020-02-06 09:39:32.427 UTC | null | 224,132 | null | 1,132,871 | null | 1 | 74 | linux|assembly|x86|system-calls|32-bit | 43,878 | <ul>
<li><code>syscall</code> is the default way of entering kernel mode on <code>x86-64</code>. This instruction is not available in 32 bit modes of operation <em>on Intel processors</em>.</li>
<li><code>sysenter</code> is an instruction most frequently used to invoke system calls in 32 bit modes of operation. It is similar to <code>syscall</code>, a bit more difficult to use though, but that is the kernel's concern.</li>
<li><code>int 0x80</code> is a legacy way to invoke a system call and should be avoided.</li>
</ul>
<p>The preferred way to invoke a system call is to use <a href="https://en.wikipedia.org/wiki/VDSO" rel="noreferrer">vDSO</a>, a part of memory mapped in each process address space that allows to use system calls more efficiently (for example, by not entering kernel mode in some cases at all). vDSO also takes care of more difficult, in comparison to the legacy <code>int 0x80</code> way, handling of <code>syscall</code> or <code>sysenter</code> instructions.</p>
<p>Also, see <a href="https://articles.manugarg.com/systemcallinlinux2_6.html" rel="noreferrer">this</a> and <a href="https://www.win.tue.nl/~aeb/linux/lk/lk-4.html" rel="noreferrer">this</a>.</p> |
13,152,946 | What is OncePerRequestFilter? | <p>Documentation says <code>org.springframework.web.filter.OncePerRequestFilter</code> "<em>guarantees to be just executed once per request</em>". Under what circumstances a Filter may possibly be executed more than once per request?</p> | 13,153,022 | 5 | 0 | null | 2012-10-31 07:11:20.637 UTC | 23 | 2021-08-26 05:53:19.127 UTC | 2018-08-22 16:50:42.777 UTC | null | 157,882 | null | 389,489 | null | 1 | 92 | spring | 63,573 | <blockquote>
<p>Under what circumstances a Filter may possibly be executed more than once per request?</p>
</blockquote>
<p>You could have the filter on the filter chain more than once.</p>
<p>The request could be dispatched to a different (or the same) servlet using the request dispatcher.</p>
<hr>
<p>A common use-case is in Spring Security, where authentication and access control functionality is typically implemented as filters that sit in front of the main application servlets. When a request is dispatched using a request dispatcher, it has to go through the filter chain again (or possibly a different one) before it gets to the servlet that is going to deal with it. The problem is that some of the security filter actions should only be performed once for a request. Hence the need for <em>this</em> filter.</p> |
30,537,359 | Can't resolve Log Forging Fortify issue | <p>I am having trouble fixing a Log Forging issue in Fortify. The issue, "writes unvalidated user input to the log", is being raised from both of the logging calls in the getLongFromTimestamp() method.</p>
<pre><code>public long getLongFromTimestamp(final String value) {
LOGGER.info("getLongFromTimestamp(" + cleanLogString(value) + ")");
long longVal = 0;
Date tempDate = null;
try {
tempDate = new SimpleDateFormat(FORMAT_YYYYMMDDHHMMSS, Locale.US).parse(value);
} catch (ParseException e) {
LOGGER.warn("Failed to convert to Date: " + cleanLogString(value) + " Exception: " + cleanLogString(e.getMessage()));
throw new Exception(e);
}
if (tempDate != null) {
longVal = tempDate.getTime();
}
return longVal;
}
private cleanLogString(String logString) {
String clean = logString.replaceAll("[^A-Za-z0-9]", "");
if(!logString.equals(clean)) {
clean += " (CLEANED)";
}
return clean;
}
</code></pre>
<p>The cleanLogString() method has fixed other Log Forging Fortify issues in my project, however it has no effect on the 2 above.</p>
<p>Any help would be appreciated!</p> | 39,492,740 | 4 | 6 | null | 2015-05-29 19:12:46.843 UTC | 2 | 2019-04-09 11:49:31.08 UTC | 2016-11-01 07:37:59.927 UTC | null | 2,588,800 | null | 2,437,610 | null | 1 | 8 | java|fortify|log-forging | 38,847 | <p>Originally when this question was written our team was using log4j v1.2.8, however we noticed that all the log forging issues disappeared after upgrading to log4j v2.6.2.</p>
<p>Once the log4j version is upgraded the Fortify log forging issues should go away. The cleanLogString() method form the question above is also unnecessary. For example:</p>
<pre><code>LOGGER.info("getLongFromTimestamp(" + value + ")");
</code></pre> |
16,991,335 | Highcharts tooltip formatter | <p>For <code>this.x</code>, I am getting the index location when I push the data in via code. If I populate the data separately, like the following code, then <code>this.x</code> returns the right item. How can I fix this issue?</p>
<p><strong>Works</strong></p>
<pre class="lang-js prettyprint-override"><code>xAxis: {
categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
},
series: [{
data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
}]
</code></pre>
<p><strong>Index location is getting pushed out for <code>this.x</code> here</strong></p>
<pre class="lang-js prettyprint-override"><code>var points = [{
Name: 'good',
Y: '15000'
}, {
Name: 'baad',
Y: '3000'
}, {
Name: 'wow',
Y: '2000'
}];
var chartData = {
GetChartSeries: function (points, name) {
var seriesData = [];
if (points != null && points != 'undefined') {
for (i=0; i<points.length; i++) {
seriesData.push({
name: ""+points[i].Name,
y: parseFloat(points[i].Y)
//,color: ''
});
}
}
return seriesData;
}
};
$(function () {
$('#container').highcharts({
chart: {
type: 'column',
margin: [ 50, 50, 100, 80],
borderColor: '#A4A4A4',
borderRadius: 5,
borderWidth: 2
},
legend: {
enabled: false
},
title: {
text: 'Graduation Year Breakdown'
},
colors: ['#790000'],
legend: {
enabled: false
},
plotOptions: {
series: {
/*
dataLabels: {
enabled: true,
color: 'red'
},
*/
borderRadius: 3,
colorByPoint: true
}
},
tooltip: {
formatter: function() {
return '<b>'+ Highcharts.numberFormat(this.y, 0) +'</b><br/>'+
'in year: '+ this.x;
}
},
xAxis: {
categories: [],
labels: {
rotation: -45,
align: 'right',
style: {
fontSize: '13px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Number of Students'
}
},
series: [{
//name: 'Population',
data: chartData.GetChartSeries(points, ""),//[4000, 3400, 2000, 34000, 120000],
dataLabels: {
enabled: true,
//rotation: -90,
color: '#4F4F4F',
align: 'center',//'right',
//x: 4,
//y: 10,
style: {
fontSize: '12px',
//fontWeight: 'bold',
fontFamily: 'Verdana, sans-serif'
}
}
}]
});
});
</code></pre> | 17,011,630 | 1 | 2 | null | 2013-06-07 19:12:23.433 UTC | 5 | 2018-12-17 01:11:23.453 UTC | 2018-12-17 01:11:23.453 UTC | null | 4,335,488 | null | 179,531 | null | 1 | 16 | highcharts|tooltip | 87,447 | <p>While I am uncertain as to why your solution doesn't work, I can propose an alternative solution.</p>
<p>The <a href="http://api.highcharts.com/highcharts#tooltip.formatter" rel="noreferrer">tooltip formatter</a> function has access to a number of different parameters. Instead of <code>this.x</code>, you could use <code>this.point.name</code>.</p>
<p>For example:</p>
<pre><code>formatter: function() {
// If you want to see what is available in the formatter, you can
// examine the `this` variable.
// console.log(this);
return '<b>'+ Highcharts.numberFormat(this.y, 0) +'</b><br/>'+
'in year: '+ this.point.name;
}
</code></pre> |
16,700,415 | cmake generate Xcode project from existing sources | <p>This is what I have, when I started generation:</p>
<pre><code>iMac:IXCSoftswitch alex$ /usr/bin/cmake -G Xcode .
-- CMAKE_SOURCE_DIR = /Users/alex/Desktop/ixc-v/IXCSoftswitch, CMAKE_BINARY_DIR = /Users/alex/Desktop/ixc-v/IXCSoftswitch
CMake Error at CMakeLists.txt:25 (MESSAGE):
Binary and source directory cannot be the same
-- Configuring incomplete, errors occurred!
</code></pre>
<p>How can I fix it? I'm new to CMake, samples appreciated.</p> | 16,701,018 | 2 | 0 | null | 2013-05-22 19:49:34.647 UTC | 10 | 2021-01-25 16:47:26.61 UTC | 2021-01-25 16:47:26.61 UTC | null | 2,494,271 | null | 979,895 | null | 1 | 24 | macos|cocoa|cmake | 69,642 | <p>CMake is used to produce <a href="https://gitlab.kitware.com/cmake/community/wikis/FAQ#what-is-an-out-of-source-build" rel="noreferrer">out-of-source</a> builds.</p>
<p>The idea here is that you don't mix the files created during compilation with the original source files. In practice, you usually run CMake from a new, empty build directory and give the path to the source directory as an argument.</p>
<pre><code>cd IXCSoftswitch
mkdir build
cd build
cmake -G Xcode ..
</code></pre>
<p>All of the files generated by CMake (which could be a <em>lot</em>) will now go into the <code>build</code> subdirectory, while your source directory stays clean of build artifacts.</p>
<p>The concept of out-of-source builds may seem strange at first, but it is actually a very convenient way of working once you get used to it.</p> |
26,777,832 | Replicating rows in a pandas data frame by a column value | <p>I want to replicate rows in a Pandas Dataframe. Each row should be repeated n times, where n is a field of each row. </p>
<pre><code>import pandas as pd
what_i_have = pd.DataFrame(data={
'id': ['A', 'B', 'C'],
'n' : [ 1, 2, 3],
'v' : [ 10, 13, 8]
})
what_i_want = pd.DataFrame(data={
'id': ['A', 'B', 'B', 'C', 'C', 'C'],
'v' : [ 10, 13, 13, 8, 8, 8]
})
</code></pre>
<p>Is this possible?</p> | 26,778,637 | 4 | 5 | null | 2014-11-06 11:01:59.267 UTC | 9 | 2021-11-20 04:03:53.82 UTC | null | null | null | null | 4,222,508 | null | 1 | 43 | python|pandas | 16,604 | <p>You can use <a href="https://pandas.pydata.org/docs/reference/api/pandas.Index.repeat.html" rel="noreferrer"><code>Index.repeat</code></a> to get repeated index values based on the column then select from the DataFrame:</p>
<pre><code>df2 = df.loc[df.index.repeat(df.n)]
id n v
0 A 1 10
1 B 2 13
1 B 2 13
2 C 3 8
2 C 3 8
2 C 3 8
</code></pre>
<p>Or you could use <a href="https://numpy.org/doc/stable/reference/generated/numpy.repeat.html" rel="noreferrer"><code>np.repeat</code></a> to get the repeated indices and then use that to index into the frame:</p>
<pre><code>df2 = df.loc[np.repeat(df.index.values, df.n)]
id n v
0 A 1 10
1 B 2 13
1 B 2 13
2 C 3 8
2 C 3 8
2 C 3 8
</code></pre>
<p>After which there's only a bit of cleaning up to do:</p>
<pre><code>df2 = df2.drop("n", axis=1).reset_index(drop=True)
id v
0 A 10
1 B 13
2 B 13
3 C 8
4 C 8
5 C 8
</code></pre>
<p>Note that if you might have duplicate indices to worry about, you could use <a href="https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.iloc.html" rel="noreferrer"><code>.iloc</code></a> instead:</p>
<pre><code>df.iloc[np.repeat(np.arange(len(df)), df["n"])].drop("n", axis=1).reset_index(drop=True)
id v
0 A 10
1 B 13
2 B 13
3 C 8
4 C 8
5 C 8
</code></pre>
<p>which uses the positions, and not the index labels.</p> |
26,649,406 | Nested Recycler view height doesn't wrap its content | <p>I have an application that manage collections of books (like playlists).</p>
<p>I want to display a list of collection with a vertical RecyclerView and inside each row, a list of book in an horizontal RecyclerView.</p>
<p>When i set the layout_height of the inner horizontal RecyclerView to 300dp, it is displayed correctly but <strong>when i set it to wrap_content, it doesn't display anything.</strong>
I need to use wrap_content because I want to be able to change the layout manager programmatically to switch between vertical and horizontal display. </p>
<p><img src="https://i.stack.imgur.com/zGbAL.png" alt="enter image description here"></p>
<p>Do you know what i'm doing wrong ?</p>
<p>My Fragment layout : </p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white">
<com.twibit.ui.view.CustomSwipeToRefreshLayout
android:id="@+id/swipe_container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/shelf_collection_listview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="10dp"/>
</LinearLayout>
</com.twibit.ui.view.CustomSwipeToRefreshLayout>
</LinearLayout>
</code></pre>
<p>Collection element layout : </p>
<pre><code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#FFF">
<!-- Simple Header -->
</RelativeLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/empty_collection"
android:id="@+id/empty_collection_tv"
android:visibility="gone"
android:gravity="center"/>
<android.support.v7.widget.RecyclerView
android:id="@+id/collection_book_listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"/> <!-- android:layout_height="300dp" -->
</FrameLayout>
</LinearLayout>
</code></pre>
<p>Book list item :</p>
<pre><code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="180dp"
android:layout_height="220dp"
android:layout_gravity="center">
<ImageView
android:id="@+id/shelf_item_cover"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:maxWidth="150dp"
android:maxHeight="200dp"
android:src="@drawable/placeholder"
android:contentDescription="@string/cover"
android:adjustViewBounds="true"
android:background="@android:drawable/dialog_holo_light_frame"/>
</FrameLayout>
</code></pre>
<p>Here is my Collection Adapter : </p>
<pre><code>private class CollectionsListAdapter extends RecyclerView.Adapter<CollectionsListAdapter.ViewHolder> {
private final String TAG = CollectionsListAdapter.class.getSimpleName();
private Context mContext;
// Create the ViewHolder class to keep references to your views
class ViewHolder extends RecyclerView.ViewHolder {
private final TextView mHeaderTitleTextView;
private final TextView mHeaderCountTextView;
private final RecyclerView mHorizontalListView;
private final TextView mEmptyTextView;
public ViewHolder(View view) {
super(view);
mHeaderTitleTextView = (TextView) view.findViewById(R.id.collection_header_tv);
mHeaderCountTextView = (TextView) view.findViewById(R.id.collection_header_count_tv);
mHorizontalListView = (RecyclerView) view.findViewById(R.id.collection_book_listview);
mEmptyTextView = (TextView) view.findViewById(R.id.empty_collection_tv);
}
}
public CollectionsListAdapter(Context context) {
mContext = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
Log.d(TAG, "CollectionsListAdapter.onCreateViewHolder(" + parent.getId() + ", " + i + ")");
// Create a new view by inflating the row item xml.
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.shelf_collection, parent, false);
// Set the view to the ViewHolder
ViewHolder holder = new ViewHolder(v);
holder.mHorizontalListView.setHasFixedSize(false);
holder.mHorizontalListView.setHorizontalScrollBarEnabled(true);
// use a linear layout manager
LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
mLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
holder.mHorizontalListView.setLayoutManager(mLayoutManager);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int i) {
Log.d(TAG, "CollectionsListAdapter.onBindViewHolder(" + holder.getPosition() + ", " + i + ")");
Collection collection = mCollectionList.get(i);
Log.d(TAG, "Collection : " + collection.getLabel());
holder.mHeaderTitleTextView.setText(collection.getLabel());
holder.mHeaderCountTextView.setText("" + collection.getBooks().size());
// Create an adapter if none exists
if (!mBookListAdapterMap.containsKey(collection.getCollectionId())) {
mBookListAdapterMap.put(collection.getCollectionId(), new BookListAdapter(getActivity(), collection));
}
holder.mHorizontalListView.setAdapter(mBookListAdapterMap.get(collection.getCollectionId()));
}
@Override
public int getItemCount() {
return mCollectionList.size();
}
}
</code></pre>
<p>And finally, the Book adapter :</p>
<pre><code>private class BookListAdapter extends RecyclerView.Adapter<BookListAdapter.ViewHolder> implements View.OnClickListener {
private final String TAG = BookListAdapter.class.getSimpleName();
// Create the ViewHolder class to keep references to your views
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView mCoverImageView;
public ViewHolder(View view) {
super(view);
mCoverImageView = (ImageView) view.findViewById(R.id.shelf_item_cover);
}
}
@Override
public void onClick(View v) {
BookListAdapter.ViewHolder holder = (BookListAdapter.ViewHolder) v.getTag();
int position = holder.getPosition();
final Book book = mCollection.getBooks().get(position);
// Click on cover image
if (v.getId() == holder.mCoverImageView.getId()) {
downloadOrOpenBook(book);
return;
}
}
private void downloadOrOpenBook(final Book book) {
// do stuff
}
private Context mContext;
private Collection mCollection;
public BookListAdapter(Context context, Collection collection) {
Log.d(TAG, "BookListAdapter(" + context + ", " + collection + ")");
mCollection = collection;
mContext = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int i) {
Log.d(TAG, "onCreateViewHolder(" + parent.getId() + ", " + i + ")");
// Create a new view by inflating the row item xml.
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.shelf_grid_item, parent, false);
// Set the view to the ViewHolder
ViewHolder holder = new ViewHolder(v);
holder.mCoverImageView.setOnClickListener(BookListAdapter.this); // Download or Open
holder.mCoverImageView.setTag(holder);
return holder;
}
@Override
public void onBindViewHolder(ViewHolder holder, int i) {
Log.d(TAG, "onBindViewHolder(" + holder.getPosition() + ", " + i + ")");
Book book = mCollection.getBooks().get(i);
ImageView imageView = holder.mCoverImageView;
ImageLoader.getInstance().displayImage(book.getCoverUrl(), imageView);
}
@Override
public int getItemCount() {
return mCollection.getBooks().size();
}
}
</code></pre> | 35,617,359 | 15 | 11 | null | 2014-10-30 09:34:29.87 UTC | 99 | 2022-01-11 11:43:20.16 UTC | 2017-06-16 11:49:32.763 UTC | null | 2,826,147 | null | 2,819,876 | null | 1 | 183 | android|android-layout|android-studio|android-recyclerview|android-support-library | 109,374 | <p><strong>Update</strong></p>
<p>Many issues relating to this feature in version 23.2.0 have been fixed in 23.2.1, update to that instead.</p>
<p>With the release of Support Library version 23.2, <code>RecyclerView</code> now supports that!</p>
<p>Update <code>build.gradle</code> to:</p>
<pre><code>compile 'com.android.support:recyclerview-v7:23.2.1'
</code></pre>
<p>or any version beyond that.</p>
<blockquote>
<p>This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.</p>
</blockquote>
<p>This can be disabled via <code>setAutoMeasurementEnabled()</code> if need be. Check in detail <a href="http://android-developers.blogspot.com/2016/02/android-support-library-232.html">here</a>.</p> |
10,247,132 | How can I get the height of the baseline of a certain font? | <p>I'm hoping to be able to find the height of the <a href="http://en.wikipedia.org/wiki/Baseline_%28typography%29" rel="noreferrer">baseline</a> of a piece of text in a div using javascript. </p>
<p>I can't use a predefined font, because many of my users will be using a larger font setting in their browser.</p>
<p>How can I do this in javascript?</p> | 11,615,439 | 3 | 0 | null | 2012-04-20 13:23:16.36 UTC | 11 | 2019-05-25 13:29:29.43 UTC | 2018-05-17 19:51:28.97 UTC | null | 3,359,687 | null | 658,540 | null | 1 | 9 | javascript|fonts | 4,366 | <p>I made a tiny jQuery plugin for that. The principle is simple:</p>
<p>In a container, insert 2 inline elements with the same content but one styled very small <code>.</code> and the other very big <code>A</code>.
Then, since there are <code>vertical-align:baseline</code> by default, the baseline is given as follow:</p>
<pre><code> ^ +----+ ^
| | +-+| | top
height | |.|A|| v
| | +-+|
v +----+
=======================
baseline = top / height
=======================
</code></pre>
<p>Here is the plugin in coffeescript (<a href="http://coffeescript.org/#try:$%20=%20@jQuery%20?%20require%20%27jQuery%27%0A%0AdetectBaseline%20=%20%28el%20=%20%27body%27%29%20-%3E%0A%20%20$container%20=%20$%28%27%3Cdiv%20style=%22visibility:hidden;%22/%3E%27%29%0A%20%20$smallA%20%20%20%20=%20$%28%27%3Cspan%20style=%22font-size:0;%22%3EA%3C/span%3E%27%29%0A%20%20$bigA%20%20%20%20%20%20=%20$%28%27%3Cspan%20style=%22font-size:999px;%22%3EA%3C/span%3E%27%29%0A%0A%20%20$container%0A%20%20%20%20.append%28$smallA%29.append%28$bigA%29%0A%20%20%20%20.appendTo%28el%29;%0A%20%20setTimeout%20%28-%3E%20$container.remove%28%29%29,%2010%0A%0A%20%20$smallA.position%28%29.top%20/%20$bigA.height%28%29%0A%0A$.fn.baseline%20=%20-%3E%0A%20%20detectBaseline%28@get%280%29%29" rel="noreferrer">JS here</a>):</p>
<pre><code>$ = @jQuery ? require 'jQuery'
detectBaseline = (el = 'body') ->
$container = $('<div style="visibility:hidden;"/>')
$smallA = $('<span style="font-size:0;">A</span>')
$bigA = $('<span style="font-size:999px;">A</span>')
$container
.append($smallA).append($bigA)
.appendTo(el);
setTimeout (-> $container.remove()), 10
$smallA.position().top / $bigA.height()
$.fn.baseline = ->
detectBaseline(@get(0))
</code></pre>
<p>then, smoke it with:</p>
<pre><code>$('body').baseline()
// or whatever selector:
$('#foo').baseline()
</code></pre>
<p>--</p>
<p>Give it a try at: <a href="http://bl.ocks.org/3157389" rel="noreferrer">http://bl.ocks.org/3157389</a></p> |
9,961,742 | Time complexity of find() in std::map? | <p>How efficient is the find() function on the std::map class? Does it iterate through all the elements looking for the key such that it's O(n), or is it in a balanced tree, or does it use a hash function or what?</p> | 9,961,759 | 3 | 2 | null | 2012-04-01 03:50:00.453 UTC | 7 | 2013-08-28 21:32:10.983 UTC | 2013-01-30 20:04:03.71 UTC | null | 569,097 | null | 569,097 | null | 1 | 23 | c++|map|complexity-theory|std | 62,341 | <p><a href="http://en.cppreference.com/w/cpp/container/map/find">Log(n)</a> It is based on a red black tree.</p>
<p>Edit: n is of course the number of members in the map.</p> |
9,872,670 | PHP Implode wrap in tags | <p>Been trying to google an answer but cant seem to find anything, I have the following...</p>
<pre><code><?php
$values = array_map('trim', get_post_custom_values($key));
$value = implode($values,', ');
echo "<div class='top-meta-vals'>".apply_filters(" $value\n", $value)."</div>";
?>
</code></pre>
<p>I want to wrap each and every <code>$value</code> in a span tag but im unsure how... </p>
<p>I tried,</p>
<pre><code><?php
$value = "<span>".implode($values,', ')."</span>";
?>
</code></pre>
<p>with no luck, can anybody give me an idea of where im going wrong? </p> | 9,872,698 | 3 | 2 | null | 2012-03-26 13:05:18.21 UTC | 5 | 2012-03-26 17:57:30.857 UTC | 2012-03-26 17:57:30.857 UTC | null | 904,874 | null | 766,532 | null | 1 | 32 | php|html|implode | 22,471 | <p>In this way you are wrapping the entire set in one span, you have to add the closing/opening tag to the implode:</p>
<pre><code>$value = "<span>".implode('</span>,<span>', $values)."</span>";
</code></pre> |
9,975,836 | How can I simulate Haskell's "Either a b" in Java | <p>How can I write a typesafe Java method that returns either something of class a or something of class b? For example:</p>
<pre><code>public ... either(boolean b) {
if (b) {
return new Integer(1);
} else {
return new String("hi");
}
}
</code></pre>
<p>What is the cleanest way?</p>
<p>( The only thing that comes to my mind is using exceptions which is obviously bad, as it is abusing a error-handling mechanism for a general language feature ...</p>
<pre><code>public String either(boolean b) throws IntException {
if (b) {
return new String("test");
} else {
throw new IntException(new Integer(1));
}
}
</code></pre>
<p>)</p> | 9,998,272 | 14 | 3 | null | 2012-04-02 11:47:51.497 UTC | 14 | 2017-07-12 11:26:06.933 UTC | 2016-02-11 08:21:02.307 UTC | null | 27,385 | null | 914,053 | null | 1 | 35 | java|haskell | 11,215 | <p>My general formula for simulating algebraic data types is: </p>
<ul>
<li>The type is an abstract base class, and the constructors are subclasses of that</li>
<li>The data for each constructor are defined in each subclass. (This allows constructors with different numbers of data to work correctly. It also removes the need to maintain invariants like only one variable is non-null or stuff like that).</li>
<li>The constructors of the subclasses serve to construct the value for each constructor. </li>
<li>To deconstruct it, one uses <code>instanceof</code> to check the constructor, and downcast to the appropriate type to get the data.</li>
</ul>
<p>So for <code>Either a b</code>, it would be something like this:</p>
<pre><code>abstract class Either<A, B> { }
class Left<A, B> extends Either<A, B> {
public A left_value;
public Left(A a) { left_value = a; }
}
class Right<A, B> extends Either<A, B> {
public B right_value;
public Right(B b) { right_value = b; }
}
// to construct it
Either<A, B> foo = new Left<A, B>(some_A_value);
Either<A, B> bar = new Right<A, B>(some_B_value);
// to deconstruct it
if (foo instanceof Left) {
Left<A, B> foo_left = (Left<A, B>)foo;
// do stuff with foo_left.a
} else if (foo instanceof Right) {
Right<A, B> foo_right = (Right<A, B>)foo;
// do stuff with foo_right.b
}
</code></pre> |
10,147,969 | Saving jQuery UI Sortable's order to Backbone.js Collection | <p>I have a Backbone.js collection that I would like to be able to sort using jQuery UI's Sortable. Nothing fancy, I just have a list that I would like to be able to sort. </p>
<p>The problem is that I'm not sure how to get the current order of items after being sorted and communicate that to the collection. Sortable can serialize itself, but that won't give me the model data I need to give to the collection.</p>
<p>Ideally, I'd like to be able to just get an array of the current order of the models in the collection and use the reset method for the collection, but I'm not sure how to get the current order. Please share any ideas or examples for getting an array with the current model order.</p> | 10,149,738 | 3 | 0 | null | 2012-04-13 20:36:48.453 UTC | 43 | 2015-09-10 20:48:21.567 UTC | null | null | null | null | 13,281 | null | 1 | 46 | javascript|jquery-ui|backbone.js|backbone.js-collections | 18,694 | <p>I've done this by using jQuery UI Sortable to trigger an event on the item view when an item is dropped. I can then trigger another event on the item view that includes the model as data which the collection view is bound to. The collection view can then be responsible for updating the sort order. </p>
<h1>Working example</h1>
<p><a href="http://jsfiddle.net/7X4PX/260/" rel="noreferrer">http://jsfiddle.net/7X4PX/260/</a></p>
<h1>jQuery UI Sortable</h1>
<pre><code>$(document).ready(function() {
$('#collection-view').sortable({
// consider using update instead of stop
stop: function(event, ui) {
ui.item.trigger('drop', ui.item.index());
}
});
});
</code></pre>
<p>The <a href="http://api.jqueryui.com/sortable/#event-stop" rel="noreferrer">stop</a> event is bound to a function that triggers <code>drop</code> on the DOM node for the item with the item's index (provided by jQuery UI) as data.</p>
<h1>Item view</h1>
<pre><code>Application.View.Item = Backbone.View.extend({
tagName: 'li',
className: 'item-view',
events: {
'drop' : 'drop'
},
drop: function(event, index) {
this.$el.trigger('update-sort', [this.model, index]);
},
render: function() {
$(this.el).html(this.model.get('name') + ' (' + this.model.get('id') + ')');
return this;
}
});
</code></pre>
<p>The drop event is bound to the <code>drop</code> function which triggers an <code>update-sort</code> event on the item view's DOM node with the data <code>[this.model, index]</code>. That means we are passing the current model and it's index (from jQuery UI sortable) to whomever is bound to the <code>update-sort</code> event.</p>
<h1>Items (collection) view</h1>
<pre><code>Application.View.Items = Backbone.View.extend({
events: {
'update-sort': 'updateSort'
},
render: function() {
this.$el.children().remove();
this.collection.each(this.appendModelView, this);
return this;
},
appendModelView: function(model) {
var el = new Application.View.Item({model: model}).render().el;
this.$el.append(el);
},
updateSort: function(event, model, position) {
this.collection.remove(model);
this.collection.each(function (model, index) {
var ordinal = index;
if (index >= position) {
ordinal += 1;
}
model.set('ordinal', ordinal);
});
model.set('ordinal', position);
this.collection.add(model, {at: position});
// to update ordinals on server:
var ids = this.collection.pluck('id');
$('#post-data').html('post ids to server: ' + ids.join(', '));
this.render();
}
});
</code></pre>
<p>The <code>Items</code> view is bound to the <code>update-sort</code> event and the function uses the data passed by the event (model and index). The model is removed from the collection, the <code>ordinal</code> attribute is updated on each remaining item and the order of items by id is sent to the server to store state.</p>
<h1>Collection</h1>
<pre><code>Application.Collection.Items = Backbone.Collection.extend({
model: Application.Model.Item,
comparator: function(model) {
return model.get('ordinal');
},
});
</code></pre>
<p>The collection has a <a href="http://backbonejs.org/#Collection-comparator" rel="noreferrer">comparator</a> function defined which orders the collection by <code>ordinal</code>. This keeps the rendered order of items in sync as the "default order" of the collection is now by the value of the <code>ordinal</code> attribute.</p>
<p>Note there is some duplication of effort: the model doesn't need to be removed and added back to the collection if a collection has a comparator function as the jsfiddle does. Also the view may not need to re-render itself.</p>
<p><strong>Note</strong>: compared to the other answer, my feeling was that it was more correct to notify the model instance of the item that it needed to be updated instead of the collection directly. Both approaches are valid. The other answer here goes directly to the collection instead of taking the model-first approach. Pick whichever makes more sense to you.</p> |
10,170,163 | Reset local repo to be exactly the same as remote repo | <p>How do I reset my local git repo to be exactly the same as the remote repo?</p>
<p>I've tried:</p>
<pre><code>git reset --hard HEAD^
</code></pre>
<p>But now <code>git status</code> says I have diverging commits. I basically want to just wipe anything I've got locally and get the exact remote repo on my local machine.</p> | 10,170,195 | 2 | 2 | null | 2012-04-16 07:28:46.083 UTC | 16 | 2012-04-16 07:42:42.427 UTC | null | null | null | null | 21,677 | null | 1 | 59 | git | 59,354 | <p><code>git reset --hard HEAD^</code> will only reset your working copy to the previous (parent) commit. Instead, you want to run</p>
<pre><code>git reset --hard origin/master
</code></pre>
<p>Assuming remote is <code>origin</code> and the branch you want to reset to is <code>master</code></p> |
11,511,826 | Joining multiple tables within an update statement | <p>I am trying to join three tables within an update statement, but I have been unsuccessful so far. I know this query works for joining two tables: </p>
<pre><code>update table 1
set x = X * Y
from table 1 as t1 join table 2 as t2 on t1.column1 = t2.column1
</code></pre>
<p>However, in my case, I need to join three tables so: </p>
<pre><code>update table 1
set x = X * Y
from table 1 as t1 join table 2 as t2 join table3 as t3
on t1.column1 = t2.column1 and t2.cloumn2 = t3.column1
</code></pre>
<p>Will not work. I also tried the following query: </p>
<pre><code>update table 1
set x = X * Y
from table 1, table 2, table 3
where column1 = column2 and column2= column3
</code></pre>
<p>Does anyone know of a method to accomplish this? </p> | 11,511,859 | 1 | 0 | null | 2012-07-16 20:12:48.19 UTC | 1 | 2020-05-13 02:04:56.637 UTC | 2012-07-16 20:17:37.17 UTC | null | 61,305 | null | 1,229,204 | null | 1 | 7 | sql-server | 41,120 | <p>You definitely don't want to use <code>table, table, table</code> syntax; <a href="https://sqlblog.org/2009/10/08/bad-habits-to-kick-using-old-style-joins" rel="nofollow noreferrer">here's why</a>. As for your middle code sample, join syntax follows roughly the same rules for <code>SELECT</code> as it does for <code>UPDATE</code>. <code>JOIN t2 JOIN t3 ON ...</code> is not valid, but <code>JOIN t2 ON ... JOIN t3 ON</code> is valid.</p>
<p>So here is my proposal, though it should be updated to fully qualify where <code>y</code> comes from:</p>
<pre><code>UPDATE t1
SET x = x * y -- should either be t2.y or t3.y, not just y
FROM dbo.table1 AS t1
INNER JOIN table2 AS t2
ON t1.column1 = t2.column1
INNER JOIN table3 AS t3
ON t2.column2 = t3.column1;
</code></pre> |
11,477,854 | Show truncated text normally, but show full text on hover | <p>I have a div with a paragraph or so of text inside it. I'd like it to show the first few words normally, but expand to show the full text on hover. Ideally, I'd like to do it with only CSS and without data duplication.</p>
<p>This is what I've tried: <a href="http://jsfiddle.net/SEgun/" rel="noreferrer">http://jsfiddle.net/SEgun/</a></p>
<p>I don't want the divs to move when the text expands, only for div 2 to expand to show the full text covering div 3. Is this possible? P.S. I don't care about retarded browsers.</p> | 11,477,928 | 2 | 0 | null | 2012-07-13 20:23:35.183 UTC | 3 | 2012-07-13 20:56:03.31 UTC | 2012-07-13 20:34:39.873 UTC | null | 205,233 | null | 289,068 | null | 1 | 14 | css | 47,641 | <p>The CSS below will cause the div to "cover" everything below it so it doesn't push any content down.</p>
<pre><code>position: absolute;
background-color:#FFF;
</code></pre>
<p>The background color is important so you can't see the stuff below.</p>
<p>To make sure everything stays in the same place, you can give the next element a top margin of the same value as the line height. The <code>+</code> sign is the <a href="http://www.w3.org/TR/CSS2/selector.html#adjacent-selectors" rel="noreferrer">adjacent sibling</a> selector.</p>
<pre><code>div {
line-height: 20px;
}
#data:hover+div {
margin-top:20px;
}
</code></pre>
<p><a href="http://jsfiddle.net/KGqnj/1/" rel="noreferrer"><strong>DEMO</strong></a></p> |
12,002,315 | Extract vmlinux from vmlinuz or bzImage | <p>I want to generate System.map from vmlinuz,cause most of machines don't have the file System.map.In fact,vmlinuz are compressed to vmlinuz or bzImage.</p>
<p>It's any tool or script can do this?</p>
<p>I tried:</p>
<pre><code>dd if=/boot/vmlinuz skip=`grep -a -b -o -m 1 -e $'\x1f\x8b\x08\x00' /boot/vmlinuz | cut -d: -f 1` bs=1 | zcat > /tmp/vmlinux
</code></pre>
<p>It was failed:</p>
<pre><code>zcat: stdin: not in gzip format
32769+0 records in
32768+0 records out
</code></pre> | 12,002,789 | 4 | 2 | null | 2012-08-17 08:26:01.917 UTC | 11 | 2022-03-17 23:42:34.817 UTC | null | null | null | null | 1,072,579 | null | 1 | 16 | bash|linux-kernel|kernel | 37,165 | <p>To extract the uncompressed kernel from the kernel image, you can use the <code>extract-vmlinux</code> script from the <code>scripts</code> directory in the kernel tree (available at least in kernel version 3.5) (if you get an error like</p>
<blockquote>
<p>mktemp: Cannot create temp file /tmp/vmlinux-XXX: Invalid argument</p>
</blockquote>
<p>you need to replace <code>$(mktemp /tmp/vmlinux-XXX)</code> by <code>$(mktemp /tmp/vmlinux-XXXXXX)</code> in the script). The command is <code>/path/to/kernel/tree/scripts/extract-vmlinux <kernel image> >vmlinux</code>.</p>
<p>If the extracted kernel binary contains symbol information, you should¹ be able to create the <code>System.map</code> file using the <code>mksysmap</code> script from the same subdirectory. The command here is <code>NM=nm /path/to/kernel/tree/scripts/mksysmap vmlinux System.map</code>.</p>
<p>¹ The kernel images shipped with my distribution seem to be stripped, so the script was not able to get the symbols.</p> |
11,855,517 | git rm file name with space | <p>I tried merging with the command line for a project in Xcode and I think a file needs to be removed. It is a file that exists in the branch I was merging from, but not the branch I was merging into. The problem is it has a space in the name:</p>
<pre><code>TestService/TestService copy-Info.plist
</code></pre>
<p>How do I remove that file? thanks!</p> | 11,855,549 | 4 | 1 | null | 2012-08-07 23:26:25.047 UTC | 6 | 2013-04-12 15:19:28.85 UTC | null | null | null | null | 980,962 | null | 1 | 30 | git | 31,269 | <p>The same way you'd use <code>rm</code> to remove such a file: quote the name:</p>
<pre><code>git rm "TestService/TestService copy-Info.plist"
</code></pre>
<p>or</p>
<pre><code>git rm 'TestService/TestService copy-Info.plist'
</code></pre>
<p>or</p>
<pre><code>git rm TestService/TestService\ copy-Info.plist
</code></pre>
<p>Depending on your shell and the names of other files, tab completion may help with this. Typing</p>
<p><code>$ git rm Te</code><kbd>Tab</kbd></p>
<p>will likely complete the directory name:</p>
<p><code>$ git rm TestingService/</code></p>
<p>Then typing part of the file name and another tab:</p>
<p><code>$ git rm TestService/Te</code><kbd>Tab</kbd></p>
<p>will complete the filename, including an inserted <code>\</code> to escape the space character:</p>
<p><code>$ git rm TestService/TestService\ copy-Info.plist</code> </p>
<p>But tab completion usually only expands a unique prefix based on all the files available, so this may or may not work.</p> |
12,019,947 | Null termination of char array | <p>Consider following case:</p>
<pre><code>#include<stdio.h>
int main()
{
char A[5];
scanf("%s",A);
printf("%s",A);
}
</code></pre>
<p>My question is if char <code>A[5]</code> contains only two characters. Say "ab", then <code>A[0]='a'</code>, <code>A[1]='b'</code> and <code>A[2]='\0'</code>.
But if the input is say, "abcde" then where is <code>'\0'</code> in that case. Will <code>A[5]</code> contain <code>'\0'</code>?
If yes, why?
<code>sizeof(A)</code> will always return 5 as answer. Then when the array is full, is there an extra byte reserved for <code>'\0'</code> which <code>sizeof()</code> doesn't count?</p> | 12,019,987 | 8 | 0 | null | 2012-08-18 15:49:44.75 UTC | 17 | 2017-08-01 05:35:01.927 UTC | 2014-02-07 17:10:38.303 UTC | null | 369,450 | null | 976,766 | null | 1 | 41 | c|null|char | 106,206 | <p>If you type more than four characters then the extra characters and the null terminator will be written outside the end of the array, overwriting memory not belonging to the array. This is a buffer overflow. </p>
<p>C does not prevent you from clobbering memory you don't own. This results in <strong><a href="http://en.wikipedia.org/wiki/Undefined_behavior">undefined behavior</a></strong>. Your program could do anything—it could crash, it could silently trash other variables and cause confusing behavior, it could be harmless, or anything else. Notice that there's no guarantee that your program will either work reliably or crash reliably. You can't even depend on it crashing immediately.</p>
<p>This is a great example of why <code>scanf("%s")</code> is dangerous and should never be used. It doesn't know about the size of your array which means there is no way to use it safely. Instead, avoid scanf and use something safer, like <a href="http://linux.die.net/man/3/fgets">fgets()</a>:</p>
<blockquote>
<p>fgets() reads in at most <strong>one less than size</strong> characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.</p>
</blockquote>
<p>Example:</p>
<pre><code>if (fgets(A, sizeof A, stdin) == NULL) {
/* error reading input */
}
</code></pre>
<p>Annoyingly, fgets() will leave a trailing newline character ('\n') at the end of the array. So you may also want code to remove it.</p>
<pre><code>size_t length = strlen(A);
if (A[length - 1] == '\n') {
A[length - 1] = '\0';
}
</code></pre>
<p>Ugh. A simple (but broken) <code>scanf("%s")</code> has turned into a 7 line monstrosity. And that's the second lesson of the day: C is not good at I/O and string handling. It can be done, and it can be done safely, but C will kick and scream the whole time.</p> |
11,829,393 | Why is the span's line-height useless? | <p>First, let's see a piece of code:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div { width:200px; height:200px; border:1px solid black; line-height:200px; }
span { line-height:1.7; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div><span>123<br>456<br>789<br>000</span></div></code></pre>
</div>
</div>
</p>
<p>Why is the <code>span</code>'s <code>line-height</code> unused?</p>
<p>The <code>line-height</code> is still <code>200px</code>, but when we set <code>span</code>'s <code>display</code> property to <code>inline-block</code>, the <code>line-height</code> of the <code>span</code> is used?</p>
<p>See below:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>div { width:200px; height:200px; border:1px solid black; line-height:200px; }
span { display:inline-block; line-height:1.7; }</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><div><span>123<br>456<br>789<br>000</span></code></pre>
</div>
</div>
</p> | 11,841,648 | 2 | 0 | null | 2012-08-06 13:36:42.12 UTC | 34 | 2020-09-06 19:16:29.47 UTC | 2020-08-07 20:00:57.14 UTC | null | 8,620,333 | null | 1,318,581 | null | 1 | 75 | html|css | 63,783 | <p>Block layouts, like <code>div</code> elements are by default, are made up of a vertical stack of <em>line boxes</em>, which never have space between them and never overlap. Each line box starts with a <em>strut</em> which is an imaginary inline box the height of the line-height specified for the block. The line box then continues with the inline boxes of the markup, according to their line heights.</p>
<p>The diagram below shows the layout for your first example. Note that because 1.7 times the font-height is much less than the height of the strut, the line height is determined by the height of the strut, since the line box must wholly contain its inline boxes. If you had set the line height on the <code>span</code> to be greater than 200px, the line boxes would be taller, and you would see the text move further apart.</p>
<p><img src="https://i.stack.imgur.com/wWFNd.gif" alt="Layout with span as inline" /></p>
<p>When you make the <code>span</code> inline-block, the relationship between the <code>div</code> and the <code>span</code> doesn't change, but the span gains it's own block layout structure with its own stack of line boxes. So the the text and the line breaks are laid out within this inner stack. The strut of the inner block is 1.7 times the font-height, i.e., the same as the text, and the layout now looks as below, so the text lines are positioned closer together, reflecting the line-height setting of the <code>span</code>.</p>
<p>(Note that the two diagrams are on different scales.)</p>
<p><img src="https://i.stack.imgur.com/VxE6a.gif" alt="Layout with span as inline-block" /></p> |
20,203,982 | OwinStartup not firing | <p>I had the OwinStartup configuration code working perfectly and then it stopped working. Unfortunately I'm not sure exactly what I did to get it to stop working and am having a really hard time figuring it out. </p>
<p>To make sure I have the basics covered, I doubled checked to make sure the I have the </p>
<pre><code>[assembly:OwinStartup(typeof(WebApplication.Startup))]
</code></pre>
<p>attribute assigned properly and made sure that I don't have an appSetting for owin:AutomaticAppStartup that is set to false so I made one set to true to be safe as there was nothing there before.</p>
<pre><code><add key="owin:AutomaticAppStartup" value="true" />
</code></pre>
<p>I also tried specifically calling out the appSetting:</p>
<pre><code><add key="owin:appStartup" value="WebApplication.Startup" />
</code></pre>
<p>Before it stopped working I upgraded the Microsoft.Owin.Security NuGet packages to 2.0.2, so I tried reverting them to 2.0.1 (that was a pain) but it didn't change anything. I have WebActivator installed on the project and am using that to bootstrap other things but I've tested that on a fresh WebApplication template and it works there so I don't think that is the culprit.</p>
<p>I also tried removing my Startup class and using Visual Studio to add a new one using the OWIN Startup Class type in Add New Item and that isn't getting called either. Next I tried adding a second Startup class since I know it will throw an exception if there is more than one OwinStartup attributes defined, but it isn't throwing any exception there.</p>
<p>Not sure what else to try. Any thoughts?</p>
<p><strong>Update</strong></p>
<p>Turns out that Resharper removed the reference to Microsoft.Owin.Host.SystemWeb when I used it to remove unused references.</p> | 20,204,884 | 22 | 6 | null | 2013-11-25 21:45:17.107 UTC | 53 | 2021-02-24 11:24:34.787 UTC | 2013-11-25 22:36:03.243 UTC | null | 321,815 | null | 321,815 | null | 1 | 390 | asp.net-mvc|asp.net-mvc-5|owin | 118,825 | <p>Make sure you have installed <code>Microsoft.Owin.Host.SystemWeb</code> package in the project. This package is needed for startup detection in IIS hosted applications. For more information you can refer to <a href="https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline" rel="noreferrer">this article</a>. </p> |
3,454,201 | macOS document icon template? | <p>The original question below has been overtaken by time: these days you do not have to supply icons or icon sets for your documents any more, as macOS will generate a standard icon out of your application icon and the system document icon template. See <a href="https://developer.apple.com/news/?id=5i6jlf4d" rel="nofollow noreferrer">https://developer.apple.com/news/?id=5i6jlf4d</a> This seems a recent development, the document in the link is dated January 2021.</p>
<p>You still have to supply CFBundleDocumentTypes in your plist, to bind the document extension to your application, but leave out CFBundleTypeIconFile that you can use to attach your own iconset to your documents.</p>
<p><strong>Original question:</strong>
Is there a template available for the Mac OS X document icon? It looks like a white piece of paper with the top right corner curled down. Lots of applications seem to use this icon as a base for their own custom document types. Does everyone use a template for the basic shape, or does every developer have to draw their own from scratch?</p>
<p>I know you can get the plain document icon here:</p>
<pre><code>/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/GenericDocument.icns
</code></pre>
<p>But that is in <a href="http://en.wikipedia.org/wiki/Apple_Icon_Image_format" rel="nofollow noreferrer">.icns</a> format rather than a format I can easily edit. Also, it doesn't make it easy if you want the document background to be anything but white.</p>
<p>It would be great if there is a Photoshop (.psd) template available for each icon size (512, 256, 128, 32, 16).</p> | 7,753,727 | 4 | 4 | null | 2010-08-10 23:09:27.877 UTC | 16 | 2021-01-29 10:55:23.517 UTC | 2021-01-29 10:55:23.517 UTC | null | 863,133 | null | 111,418 | null | 1 | 28 | macos|icons | 10,284 | <p>There are several tools, that converts your image (drawn in Photoshop) into an icon-format:</p>
<ul>
<li><a href="http://www.squidoo.com/iconeer" rel="nofollow">Iconeer</a></li>
<li><a href="http://www.img2icnsapp.com/" rel="nofollow">Img2icns</a></li>
<li><a href="http://iconfactory.com/software/iconbuilder/" rel="nofollow">IconBuilder</a></li>
<li><a href="http://mac.softpedia.com/progDownload/PicIcon-Download-5734.html" rel="nofollow">Pic2Icon</a> <em>(seems to be not supported any longer)</em></li>
<li><a href="http://projects.digitalwaters.net/index.php?q=fasticns" rel="nofollow">FastIcns</a></li>
</ul>
<p>To convert an icon-format into another graphic-format (so you can easily modify) I can recommend:</p>
<ul>
<li><a href="http://www.lemkesoft.com/" rel="nofollow">GraphicConverter</a></li>
<li><a href="http://www.pl32.com/" rel="nofollow">PhotoLine</a></li>
</ul>
<p>Greate sources for free icons are:</p>
<ul>
<li><a href="http://www.freeiconsweb.com/" rel="nofollow">freeiconsweb</a></li>
<li><a href="http://www.freeiconsdownload.com/" rel="nofollow">freeiconsdownload</a></li>
<li><a href="http://speckyboy.com/2010/09/30/60-psd-icon-and-button-templates/" rel="nofollow">60 Icon Photoshop Templates</a></li>
</ul>
<p>Please read the licence of the sets you download! You can download a lot of free icons there and reuse them or even modify them. Then you can convert them back into the icon-format with the tools mentioned above.</p> |
3,722,831 | Does PHP's filter_var FILTER_VALIDATE_EMAIL actually work? | <p>After reading various posts I decided not to use REGEX to check if an email is valid and simply use PHP's inbuilt filter_var function. It seemed to work ok, until it started telling me an email was invalid because I had a number in it.</p>
<p>ie [email protected] works, while [email protected] doesn't.</p>
<p>Am I missing something or is the <code>filter_var($email, FILTER_VALIDATE_EMAIL)</code> really quite ineffective?</p> | 3,722,924 | 4 | 2 | null | 2010-09-16 00:20:04.26 UTC | 12 | 2014-05-21 22:08:44.547 UTC | 2013-05-11 14:23:38.64 UTC | null | 1,640,606 | null | 84,433 | null | 1 | 32 | php|email-validation | 28,125 | <p>The regular expression used in the PHP 5.3.3 filter code is based on Michael Rushton's blog about <a href="http://squiloople.com/2009/12/20/email-address-validation/" rel="noreferrer">Email Address Validation</a>. It does seem to work for the case you mention.</p>
<p>You could also check out some of the options in <a href="http://fightingforalostcause.net/misc/2006/compare-email-regex.php" rel="noreferrer">Comparing E-mail Address Validating Regular Expressions</a> (the regexp currently used in PHP is one of those tested).</p>
<p>Then you could choose a regexp you like better, and use it in a call to <code>preg_match()</code>.</p>
<p>Or else you could take the regexp and replace the one in file PHP/ext/filter/logical_filter.c, function <code>php_filter_validate_email()</code>, and rebuild PHP.</p> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.